samagotchi 0.166.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.
Files changed (94) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +89 -1
  3. data/docs/architecture.md +1 -0
  4. data/docs/cli.md +24 -15
  5. data/docs/configuration.md +1 -0
  6. data/docs/guardrails.md +5 -5
  7. data/docs/hooks.md +4 -6
  8. data/docs/internals/bundles.md +2 -4
  9. data/docs/internals/engine.md +4 -5
  10. data/docs/internals/objectives.md +141 -9
  11. data/docs/internals/remote-sessions.md +5 -6
  12. data/docs/internals/web-frontend.md +85 -40
  13. data/docs/memory.md +1 -2
  14. data/docs/sessions.md +20 -2
  15. data/docs/testing.md +3 -3
  16. data/lib/samagotchi/bridge.rb +1 -1
  17. data/lib/samagotchi/bundle_command/installed_check.rb +2 -14
  18. data/lib/samagotchi/bundle_command.rb +35 -12
  19. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  20. data/lib/samagotchi/cli/command.rb +10 -0
  21. data/lib/samagotchi/compat.rb +1 -13
  22. data/lib/samagotchi/config.rb +3 -0
  23. data/lib/samagotchi/context_command.rb +2 -1
  24. data/lib/samagotchi/engine/objectives.rb +20 -1
  25. data/lib/samagotchi/engine/side_requests.rb +3 -2
  26. data/lib/samagotchi/engine/turn_end.rb +4 -1
  27. data/lib/samagotchi/engine.rb +3 -0
  28. data/lib/samagotchi/extension_load.rb +2 -26
  29. data/lib/samagotchi/guardrails/approvals.rb +15 -16
  30. data/lib/samagotchi/jsonl_store.rb +61 -0
  31. data/lib/samagotchi/memory_bundle/status.rb +3 -15
  32. data/lib/samagotchi/memory_bundle/system_bundle.rb +16 -10
  33. data/lib/samagotchi/memory_command.rb +4 -2
  34. data/lib/samagotchi/objectives.rb +43 -14
  35. data/lib/samagotchi/objectives_backing.rb +124 -0
  36. data/lib/samagotchi/objectives_check.rb +19 -126
  37. data/lib/samagotchi/objectives_command.rb +14 -7
  38. data/lib/samagotchi/objectives_record.rb +104 -0
  39. data/lib/samagotchi/objectives_track.rb +353 -0
  40. data/lib/samagotchi/push_command.rb +2 -1
  41. data/lib/samagotchi/remote_command.rb +2 -1
  42. data/lib/samagotchi/reply_wait/poll.rb +6 -6
  43. data/lib/samagotchi/reply_wait.rb +4 -24
  44. data/lib/samagotchi/schedule_command.rb +6 -0
  45. data/lib/samagotchi/schedules.rb +1 -1
  46. data/lib/samagotchi/session_access/remote.rb +3 -5
  47. data/lib/samagotchi/session_commands.rb +1 -1
  48. data/lib/samagotchi/sessions_command.rb +12 -6
  49. data/lib/samagotchi/share_command.rb +2 -1
  50. data/lib/samagotchi/tool_activity.rb +11 -1
  51. data/lib/samagotchi/tool_declarations.rb +5 -1
  52. data/lib/samagotchi/tools/objectives_tool.rb +19 -2
  53. data/lib/samagotchi/turn_stages/objectives.rb +46 -3
  54. data/lib/samagotchi/version.rb +1 -1
  55. data/lib/samagotchi/web/participant_access.rb +1 -1
  56. data/lib/samagotchi/web/public/app.js +52 -424
  57. data/lib/samagotchi/web/public/copy.js +2 -1
  58. data/lib/samagotchi/web/public/dock_reserve.js +12 -2
  59. data/lib/samagotchi/web/public/history_end.js +16 -0
  60. data/lib/samagotchi/web/public/index.html +74 -22
  61. data/lib/samagotchi/web/public/info_bar_model.js +3 -1
  62. data/lib/samagotchi/web/public/no_contact_fill.js +29 -0
  63. data/lib/samagotchi/web/public/objectives.css +14 -0
  64. data/lib/samagotchi/web/public/objectives_moves.js +82 -9
  65. data/lib/samagotchi/web/public/objectives_state.js +42 -0
  66. data/lib/samagotchi/web/public/objectives_strip.js +33 -9
  67. data/lib/samagotchi/web/public/objectives_track.js +52 -0
  68. data/lib/samagotchi/web/public/objectives_wiring.js +16 -1
  69. data/lib/samagotchi/web/public/participant.html +1 -1
  70. data/lib/samagotchi/web/public/participants_panel.js +14 -7
  71. data/lib/samagotchi/web/public/question_cards.js +8 -13
  72. data/lib/samagotchi/web/public/refs.js +4 -1
  73. data/lib/samagotchi/web/public/reload_check.js +5 -4
  74. data/lib/samagotchi/web/public/resync_reach.js +10 -6
  75. data/lib/samagotchi/web/public/scope.js +3 -3
  76. data/lib/samagotchi/web/public/session_rename.js +6 -2
  77. data/lib/samagotchi/web/public/session_state.js +1 -1
  78. data/lib/samagotchi/web/public/session_sync.js +249 -0
  79. data/lib/samagotchi/web/public/session_view.js +279 -0
  80. data/lib/samagotchi/web/public/stage_cards.js +20 -0
  81. data/lib/samagotchi/web/public/stage_frame.js +14 -16
  82. data/lib/samagotchi/web/public/stage_model.js +11 -4
  83. data/lib/samagotchi/web/public/stage_opened.js +229 -0
  84. data/lib/samagotchi/web/public/stage_slots.js +2 -3
  85. data/lib/samagotchi/web/public/stage_view.js +219 -147
  86. data/lib/samagotchi/web/public/stage_watch.js +8 -4
  87. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  88. data/lib/samagotchi/web/public/tokens.css +2 -2
  89. data/lib/samagotchi/web/public/turn_block.js +22 -2
  90. data/lib/samagotchi/web/public/turn_html.js +1 -1
  91. data/lib/samagotchi/web/public/widget_picks.js +3 -0
  92. data/lib/samagotchi/web/public/working_set_view.js +1 -1
  93. data/lib/samagotchi/web/session_access_routes.rb +4 -15
  94. metadata +13 -1
@@ -0,0 +1,279 @@
1
+ // The open session's view (split out of app.js): forgetSession() starts the
2
+ // page over for another session, renderSessionView() draws a read of it (the
3
+ // history, the replayed turn in progress, the cards, a pending question),
4
+ // readTurnEnd() re-reads a turn's end, endTurnView() closes a turn's
5
+ // rendering. Kept in app.js's order: their DOM placements depend on it.
6
+ //
7
+ // Everything that changes while the page runs is read through deps at the
8
+ // call, never captured at creation (as stream_handlers.js): the open session
9
+ // (store.selected), its fields (store.current), the page's capabilities
10
+ // (capabilities()), the views made after this one (the getters in +later+).
11
+ //
12
+ // deps:
13
+ // store the page's session store (session_store.js)
14
+ // historyEl the history element
15
+ // getSession(id, opts) data.js
16
+ // liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip
17
+ // the page's views
18
+ // workingSet the stage view's working set (web.working_set), null when off
19
+ // gapClock the page's last activity (time_gaps.js createGapClock)
20
+ // bubbles, cards bubbles.js, cards_place.js
21
+ // markdown markdown_place.js (linkTextRefs, applyFinalMarkdown)
22
+ // capabilities() the page's capabilities (card.js shownElsewhere, the history's cards)
23
+ // page: {setReviseAnchor(anchor), renderInitRow(), setMarkdownWarning(warning),
24
+ // setCapabilities(capabilities, editorUrl), findInTurnRoots(selector), appendToHistory(el),
25
+ // setTurnRunning(running), mergeTurnTiming(id, timing), applySessionPayload(data, opts),
26
+ // turnEndStatus(data), replaceSelectedCard(change)} the page's hooks
27
+ // later: {handlers(), composer(), ownerVerify(), commandList(), initTasks(), resetTurnView()}
28
+ // the views made after this one, and session_sync.js's resetTurnView
29
+ //
30
+ // @return {forgetSession, renderSessionView, historyOpts, readTurnEnd, endTurnView}
31
+ // Its own module: new exports go in new modules (web-frontend.md).
32
+
33
+ import { emptySessionState, sessionStateFrom } from "./session_state.js";
34
+ import { seedInitTasks } from "./init_row.js";
35
+ import { restoreCommandBubbles } from "./commands.js";
36
+ import { failedTurnText, normalize } from "./format.js";
37
+ import { splitSnapshotCards } from "./card.js";
38
+ import { turnGroups } from "./timing.js";
39
+ import { groupItems } from "./working_set_view.js";
40
+ import { thumbsTemplate } from "./images.js";
41
+ import { hintEl, outputBubbleTemplate } from "./bubbles.js";
42
+ import { turnHistoryNodes } from "./turn_block.js";
43
+ import { lastActivity } from "./time_gaps.js";
44
+ import { elementOf, emptyAnswerTemplate } from "./turn_html.js";
45
+ import { stillOn } from "./latest.js";
46
+
47
+ export function createSessionView(deps) {
48
+ const {
49
+ store, historyEl, getSession,
50
+ liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet = null, gapClock,
51
+ bubbles, cards, markdown, capabilities, page, later,
52
+ } = deps;
53
+ const { makeUserBubble, addEndBubble, showGuardrailWarning, showRecap } = bubbles;
54
+ const { placeSnapshotCards, upsertCard } = cards;
55
+ const { linkTextRefs, applyFinalMarkdown } = markdown;
56
+ const {
57
+ setReviseAnchor, renderInitRow, setMarkdownWarning, setCapabilities, findInTurnRoots, appendToHistory,
58
+ setTurnRunning, mergeTurnTiming, applySessionPayload, turnEndStatus, replaceSelectedCard,
59
+ } = page;
60
+ // The open session's id, for the stale-answer guards (latest.js stillOn).
61
+ const openId = () => store.selected;
62
+
63
+ // Forget everything the page knew about the open session: its fields (the
64
+ // info bar, composer, command list), the turn on view, its stream and
65
+ // question cards, its init row, the payload's markdown warning and tip and
66
+ // capabilities, and the composer's Verify claim and Revise (+keepVerify+:
67
+ // the same session opened again keeps them). The one reset list select() and
68
+ // clearSelection() share, so a field the previous session set (its
69
+ // "delegated by" parent, its commands, its card actions) never shows for
70
+ // the next one, also when the next one's read fails.
71
+ function forgetSession({ keepVerify = false } = {}) {
72
+ if (!keepVerify) later.ownerVerify().clear();
73
+ if (!keepVerify) setReviseAnchor(null);
74
+ store.batch(() => {
75
+ store.replaceCurrent(emptySessionState());
76
+ featureGates.prime(store.current);
77
+ });
78
+ later.commandList().close();
79
+ later.resetTurnView();
80
+ objectives.reset();
81
+ seedInitTasks(later.initTasks(), []);
82
+ renderInitRow();
83
+ setMarkdownWarning(null);
84
+ markdownTip.show(null);
85
+ setCapabilities(null, null);
86
+ later.composer().newVisit();
87
+ }
88
+
89
+ // A session view: its messages, then the turn in progress and the queued
90
+ // prompts (a live worker's snapshot) replayed through the stream handlers,
91
+ // then a pending question.
92
+ function renderSessionView(data, { kept = [] } = {}) {
93
+ setMarkdownWarning(data.markdown_warning);
94
+ markdownTip.show(data.markdown_tip);
95
+ setCapabilities(data.capabilities, data.editor_url);
96
+ // The saved fill (when there is one) goes in here too, so a reloaded or
97
+ // stopped session shows it before its next turn (a running turn's replay
98
+ // below streams over it).
99
+ const { status, ...fields } = sessionStateFrom(data);
100
+ // The fields in one batch (their chips' popovers, the bar); the replay's
101
+ // own redraws below stay where they run.
102
+ store.batch(() => {
103
+ store.update({ current: fields });
104
+ store.setStatus(status, "payload");
105
+ featureGates.prime(store.current);
106
+ });
107
+ liveTurn.timing.ended = store.current.timing.turnRecords.length;
108
+ const activeTurnId = store.current.timing.activeTurn?.id || null;
109
+ if (data.messages && data.messages.length) renderHistory(data.messages, data);
110
+ else renderHistory(data.history || []);
111
+ seedWorkingSet(data);
112
+ objectives.seed(data.objectives);
113
+ restoreCommandBubbles(historyEl, kept);
114
+ // A failed turn's prompt went back to the user: shown after the
115
+ // conversation, marked failed, as it was live (prompt_restored).
116
+ const failedPrompt = data.failed_turn ? makeUserBubble(data.failed_turn.prompt, { state: "failed" }) : null;
117
+ if (failedPrompt) {
118
+ failedPrompt.dataset.failedTurn = "1";
119
+ addEndBubble(failedTurnText(data.failed_turn));
120
+ }
121
+ seedSeenFromDom();
122
+ seedInitTasks(later.initTasks(), data.init_tasks);
123
+ renderInitRow();
124
+ // A guardrail file that failed to load, announced before this page
125
+ // joined: where it came (the snapshot's cards), else at the end.
126
+ const loadWarned = (label) => (data.cards || []).some((c) => c?.type === "guardrail_warning" && (c.label || "guardrails") === label);
127
+ if (!loadWarned("guardrails")) showGuardrailWarning(data.guardrail_warning);
128
+ if (!loadWarned("plugins")) showGuardrailWarning(data.plugin_warning, "plugins");
129
+ // A live worker's last cards and between-turns notices, where they
130
+ // arrived; the running turn's go into its step once it is drawn.
131
+ const snapshotCards = splitSnapshotCards(data.cards, capabilities());
132
+ // Above a failed turn's prompt: it came after them, and it is no turn.
133
+ placeSnapshotCards(snapshotCards.placed, { before: failedPrompt });
134
+ // The recap saved with the session (also a stopped one's), else a live
135
+ // worker's from before saved_recap existed. After the cards: the last
136
+ // turn's check-in notice goes to the end, and the recap closes the page.
137
+ const saved = data.saved_recap;
138
+ if (saved) showRecap(saved.text, saved.turns_since, saved.created_at || null, saved.opening_id || null);
139
+ else showRecap(data.recap);
140
+ // chi web's unfold of the join (TurnAccumulator.join_events): the turn in
141
+ // progress and the queue behind it as the live events that draw them.
142
+ const replay = data.replay ?? [];
143
+ // Marked replayed: a call's duration isn't timed from the replay's clock.
144
+ replay.forEach((event) => later.handlers()[event.type]?.({ ...event, replayed: true }));
145
+ // A join mid-generation: the worker's word on it clocks the delivery line.
146
+ const gen = data.current_turn?.generation;
147
+ liveTurn.serverGen = gen ? { ...gen, at: Date.now() } : null;
148
+ if (!data.current_turn) {
149
+ setTurnRunning(store.current.status === "running");
150
+ // Running with no turn to draw: the stage's status row still holds Stop turn.
151
+ turnDom.runningWithoutTurn?.(liveTurn.running);
152
+ if (liveTurn.running && store.current.timing.activeTurn?.started_at) liveTurn.timing.start(store.current.timing.activeTurn.started_at, activeTurnId);
153
+ } else if (liveTurn.running) {
154
+ // The live line's turn: the running turn's record's (the replayed
155
+ // turn_started carries the same id, on both unfolds).
156
+ liveTurn.timing.turnId = activeTurnId;
157
+ }
158
+ turnDom.flush();
159
+ snapshotCards.current.forEach((card) => upsertCard(card));
160
+ snapshotCards.during.forEach((card) => upsertCard(card));
161
+ // A question the worker is blocked on (also after a reload).
162
+ if (data.pending_question && data.pending_question.id && data.pending_question.status === "pending") {
163
+ // Its refs on the asking step, as question_requested puts them.
164
+ if (data.pending_question.refs) turnDom.questionRefs(data.pending_question.refs);
165
+ questionCards.renderQuestion(data.pending_question);
166
+ // The turn's replay drew it as asked; the snapshot knows whether it is
167
+ // relayed to the parent now.
168
+ questionCards.markRelayed(data.pending_question.id, data.pending_question.relayed_to || null);
169
+ }
170
+ // A turn ran out of iterations and waits for a yes or no.
171
+ if (data.continue_offer) questionCards.renderContinue(data.continue_offer);
172
+ // A whole view drawn: the composer and the bar once more (the working
173
+ // set's seed may change the bar's chip).
174
+ store.batch(() => {
175
+ store.touch("composer");
176
+ store.touch("infoBar");
177
+ });
178
+ }
179
+
180
+ // The working set's turns from a session's messages, as turnHistoryNodes
181
+ // numbers them: the drawn ones (the running turn, which the replay draws
182
+ // in the stage, has no drawing yet).
183
+ function seedWorkingSet(data) {
184
+ if (!workingSet) return;
185
+ const items = data.messages || [];
186
+ const groups = typeof items[0] === "object" && items[0]?.role ? turnGroups(items, store.current.timing, { drawings: data.turn_drawings }).filter((g) => g.kind === "turn") : [];
187
+ workingSet.seed(groups.map((g, i) => {
188
+ const text = String(items[g.user]?.content ?? "").replace(/\s+/g, " ").trim();
189
+ return { items: groupItems(g, i), prompt: text.length > 60 ? `${text.slice(0, 59)}\u2026` : text };
190
+ }));
191
+ }
192
+
193
+ // turnHistoryNodes' options for a read's +data+: its turns' drawings
194
+ // (turn_drawing.js), cards (a drawn card's body) and the running turn's id
195
+ // (its prompt has no drawing yet: a plain row, no miss).
196
+ const historyOpts = (data = {}) => ({ thumbs: (images) => thumbsTemplate(store.selected, images), workingSet: !!workingSet,
197
+ drawings: data.turn_drawings || null, cards: data.cards || null, capabilities: capabilities(),
198
+ runningTurnId: data.current_turn?.turn_id || null });
199
+
200
+ function renderHistory(items, data = {}) {
201
+ gapClock.seed(null);
202
+ if (!items.length) {
203
+ historyEl.replaceChildren(hintEl("No output yet. Send a message."));
204
+ return;
205
+ }
206
+ if (typeof items[0] === "object" && items[0].role) {
207
+ historyEl.replaceChildren(turnHistoryNodes(items, store.current.timing, historyOpts(data)));
208
+ later.ownerVerify().renderSaved();
209
+ // The live dividers count from the history's last activity.
210
+ gapClock.seed(lastActivity(turnGroups(items, store.current.timing, { drawings: data.turn_drawings }), items));
211
+ linkTextRefs();
212
+ } else {
213
+ historyEl.replaceChildren(...items.map((c) => elementOf(outputBubbleTemplate(c))));
214
+ }
215
+ historyEl.scrollTop = historyEl.scrollHeight;
216
+ }
217
+
218
+ async function readTurnEnd() {
219
+ if (!store.selected) return;
220
+ const id = store.selected;
221
+ // The line and the turn this read is for, before the await: a turn
222
+ // queued behind this one may start (a new live line) before it lands.
223
+ const line = liveTurn.timing.capture();
224
+ const still = stillOn(openId);
225
+ try {
226
+ const d = await getSession(id, { tail: true, recent: true, turnId: line.turnId });
227
+ if (!still()) return;
228
+ if (d.session) {
229
+ if (!(await mergeTurnTiming(id, d.timing))) return;
230
+ liveTurn.timing.finishLine(line);
231
+ // The rest in one batch: the bar and the lists redraw once, after the
232
+ // answer's markdown.
233
+ store.batch(() => {
234
+ // The notes chip: the first turn's build (or a /model) records them.
235
+ applySessionPayload(d, { fields: ["usedMemories", "promptNotes"] });
236
+ turnEndStatus(d);
237
+ setMarkdownWarning(d.markdown_warning);
238
+ markdownTip.show(d.markdown_tip);
239
+ setCapabilities(d.capabilities, d.editor_url);
240
+ if (Array.isArray(d.messages)) applyFinalMarkdown(d.messages);
241
+ // Its card, replaced (replaceSelectedCard).
242
+ replaceSelectedCard((sess) => ({ ...sess, used_memory_names: store.current.usedMemories.slice(), status: store.current.status }));
243
+ });
244
+ }
245
+ } catch (_) {
246
+ // A failed read (the server or worker gone a moment) leaves the answer
247
+ // as the stream drew it, plain text: the session's next load renders it.
248
+ }
249
+ }
250
+
251
+ function seedSeenFromDom() {
252
+ shownTexts.seed(findInTurnRoots(".bubble").map((b) => normalize(b.textContent)));
253
+ }
254
+
255
+ // Everything a turn's end (completed, canceled, failed) closes: then its
256
+ // end line (+endText+, the cancel or failed line), then the step cards that
257
+ // left the collapsed block (card.js leavesBlock), where a reload puts them.
258
+ function endTurnView(kind, endText = null, { emptyAnswer = null, stopped = false } = {}) {
259
+ setTurnRunning(false);
260
+ // Every ended turn has a record (completed, canceled, failed); a worker
261
+ // gone mid-turn is re-rendered (resync), which counts again.
262
+ if (kind !== "gone") liveTurn.timing.ended += 1;
263
+ // A completed turn with no answer: its notice where the answer goes
264
+ // (the turn block places it), else after the turn; before the timing.
265
+ const endNote = emptyAnswer ? elementOf(emptyAnswerTemplate(emptyAnswer)) : null;
266
+ const kept = turnDom.turnEnded({ kind, endNote, emptyAnswer: !!emptyAnswer, turnId: liveTurn.timing.turnId }) || [];
267
+ if (endNote && !endNote.isConnected) appendToHistory(endNote);
268
+ liveTurn.timing.finish({ canceled: kind === "canceled" });
269
+ if (endText) addEndBubble(endText, { stopped });
270
+ if (kept.length) {
271
+ kept.forEach((el) => appendToHistory(el));
272
+ if (!turnDom.holds()) historyEl.scrollTop = historyEl.scrollHeight;
273
+ }
274
+ // The question dies with its turn (the worker stopped waiting).
275
+ if (questionCards.pendingQuestion()) questionCards.resolveQuestion(questionCards.pendingQuestion().id, { cancelled: true, reason: "turn ended" });
276
+ }
277
+
278
+ return { forgetSession, renderSessionView, historyOpts, readTurnEnd, endTurnView };
279
+ }
@@ -0,0 +1,20 @@
1
+ // The cards that wait in the stage (stage_view.js, stage_model.js
2
+ // placeKind): what blocks the turn or asks the user stays in the stage
3
+ // whatever the turn's form, also when the turn is opened in the history
4
+ // (stage_opened.js).
5
+
6
+ // A card that waits for the user: a question or approval not answered, a
7
+ // continue offer not resolved.
8
+ export const PENDING = ".bubble.question:not(.answered):not(.cancelled), .bubble.continue:not(.resolved)";
9
+ // A running turn's card with actions (check-in's Nudge / Keep going / Stop)
10
+ // asks the user too, but the turn goes on: it waits only while the turn runs
11
+ // and never holds the hand-off (a turn cut short can leave it open).
12
+ export const ASKS = ".plugin-card[data-in-turn] .card-action";
13
+ // A plugin's warning stays in sight in the stage until the turn's end.
14
+ export const WARN_CARD = ".plugin-card.warn";
15
+
16
+ // +el+ waits in the stage: a pending card, an asking card's actions, a
17
+ // plugin's warning.
18
+ export function waitsInStage(el) {
19
+ return !!(el?.matches?.(PENDING) || el?.querySelector?.(ASKS) || el?.matches?.(WARN_CARD));
20
+ }
@@ -1,10 +1,11 @@
1
1
  // The stage view's cap and frame (stage_view.js): the one place that
2
2
  // writes the stage's height, and the stage's own scrolls. The cap: at most
3
- // ~60% of the page (~80% with the cloud open, 85% from a card that needs the
4
- // room until the next step: a long reply's question, a tall approval), and
5
- // never above the session panel. The frame: held and grow-only while the
6
- // stage holds a turn (stage_model.js frameTarget), its growth eased; the next
7
- // step after an answered card lets it go once (forgetContent). The stage's state comes
3
+ // ~60% of the page (~80% with the cloud open, 85% from a tall approval
4
+ // until the next step), and never above the session panel. The frame: held
5
+ // and grow-only while the stage holds a turn (stage_model.js frameTarget),
6
+ // its growth eased; it lets go in two places only (forgetContent): the
7
+ // asking form (a turn opened in the history: the card alone, stage_view.js
8
+ // place) and the next step after an answered card (releaseHeldWait). The stage's state comes
8
9
  // in as getters (+isHolding+, +isCollapsed+, +isCloudOpen+, +isRoomCap+);
9
10
  // what the stage changes of the frame's goes through resetHeld and
10
11
  // forgetContent. +waitingCard+: the card blocking the turn, or null.
@@ -18,7 +19,7 @@ const GROW_EASE = "cubic-bezier(.2,.7,.3,1)";
18
19
  // The room between the stage and the composer card (index.html's margin-bottom).
19
20
  export const STAGE_GAP = 10;
20
21
  // The cap's share of the page: the stage's own, with the cloud open, and
21
- // with the question room (a long reply that asks, stage_view.js).
22
+ // with a raised cap (a tall approval, stage_view.js raiseForApproval).
22
23
  const SHARE = 0.6;
23
24
  const CLOUD_SHARE = 0.8;
24
25
  const ROOM_SHARE = 0.85;
@@ -59,23 +60,21 @@ export function createStageFrame({ stage, scroller, status, cloud, queuedSlot, h
59
60
  }
60
61
 
61
62
  // ── the cap: at most ~60% of the page (~80% with the cloud open, 85%
62
- // while a card has the room), and never above the session
63
+ // with a raised cap), and never above the session
63
64
  // panel (the dock is absolute: a tall composer or a phone's keyboard
64
65
  // would push the stage's top out) ──────────────────────────────────────
65
66
 
66
67
  // Where the stage's scroll goes so +slot+ (the scroller's child) shows:
67
68
  // its end in sight, and the asking text's top too when it and the slot
68
69
  // (a waiting card) fit together (the reply reads from its start, the card
69
- // still in sight). +fromStart+ (the question room's arrival): the asking
70
- // text's top even when they don't (the card is reached by the stage's
71
- // jump pill, stage_view.js). A waiting card in +slot+ taller than the
70
+ // still in sight). A waiting card in +slot+ taller than the
72
71
  // view reads from its top, never from its options: the question and what
73
72
  // it approves are what the answer is about; the options are a scroll away.
74
73
  // null: nothing to show.
75
- function revealTop(slot, { fromStart = false } = {}) {
74
+ function revealTop(slot) {
76
75
  if (stage.hidden || slot.hidden) return null;
77
76
  let top = Math.max(scroller.scrollTop, slot.offsetTop + slot.offsetHeight - scroller.clientHeight);
78
- if (!asking.hidden && asking.offsetTop < top && (fromStart || slot.offsetTop + slot.offsetHeight - asking.offsetTop <= scroller.clientHeight)) top = asking.offsetTop;
77
+ if (!asking.hidden && asking.offsetTop < top && slot.offsetTop + slot.offsetHeight - asking.offsetTop <= scroller.clientHeight) top = asking.offsetTop;
79
78
  const card = waitingCard();
80
79
  if (card && slot.contains(card)) top = Math.min(top, Math.max(0, card.offsetTop - CARD_TOP_GAP));
81
80
  return top;
@@ -83,10 +82,9 @@ export function createStageFrame({ stage, scroller, status, cloud, queuedSlot, h
83
82
 
84
83
  // Scrolls the stage to show +slot+: eased, or at once (+now+: the cap
85
84
  // dropped under it; a running ease stops, or its next frame would take
86
- // the scroll back toward its target for the taller stage). +fromStart+:
87
- // revealTop's.
88
- function reveal(slot, { now = false, fromStart = false } = {}) {
89
- const top = revealTop(slot, { fromStart });
85
+ // the scroll back toward its target for the taller stage).
86
+ function reveal(slot, { now = false } = {}) {
87
+ const top = revealTop(slot);
90
88
  if (top === null) return;
91
89
  if (now) easeScrollTo(scroller, top, { reduce: true });
92
90
  else easeStage(top);
@@ -9,6 +9,7 @@ import { hookNoticeLabel } from "./turn_events.js";
9
9
  import { askingRefs, askingText } from "./turn_model.js";
10
10
  import { plainLine } from "./plain_line.js";
11
11
  import { turnPieces } from "./turn_pieces.js";
12
+ import { waitsInStage } from "./stage_cards.js";
12
13
 
13
14
  const READ_LIKE = new Set(["read", "memory_read", "web_fetch", "task_get", "task_list", "list_sessions"]);
14
15
  const EDITS = new Set(["edit", "write", "memory_write"]);
@@ -244,10 +245,12 @@ export const QUEUED_ROWS = '.bubble.user.queued[data-delivery="queue"], .bubble.
244
245
  // QUEUED_ROWS among +parent+'s own children (querySelectorAll on it).
245
246
  export const QUEUED_CHILDREN = QUEUED_ROWS.split(", ").map((sel) => `:scope > ${sel}`).join(", ");
246
247
 
247
- // The kind placeFor reads off an element app.js places.
248
+ // The kind placeFor reads off an element app.js places: "waits" for a card
249
+ // that waits in the stage (stage_cards.js waitsInStage).
248
250
  export function placeKind(el) {
249
251
  if (el.matches?.(".bubble.recap")) return "recap";
250
252
  if (el.matches?.(QUEUED_ROWS)) return "queued";
253
+ if (waitsInStage(el)) return "waits";
251
254
  return "row";
252
255
  }
253
256
 
@@ -284,9 +287,13 @@ export function flashOf(what, data = {}) {
284
287
 
285
288
  // A queued row ("queued", placeKind) goes after the running turn, not
286
289
  // into it: the stage's queued slot below the turn's card while one is
287
- // live, else the history's end (after the turn there too).
288
- export function placeFor({ live, handingOff, kind }) {
290
+ // live, else the history's end (after the turn there too). +opened+: the
291
+ // live turn is opened in the history (stage_view.js): a row ("row") goes
292
+ // to the history's end as the turn's ("opened": the stage moves it there
293
+ // and follows); a card that waits ("waits") stays in the stage.
294
+ export function placeFor({ live, handingOff, kind, opened = false }) {
289
295
  if (kind === "recap") return "history";
290
296
  if (!live || handingOff) return "history";
291
- return kind === "queued" ? "queued" : "stage";
297
+ if (kind === "queued") return "queued";
298
+ return opened && kind === "row" ? "opened" : "stage";
292
299
  }
@@ -0,0 +1,229 @@
1
+ // A running turn opened in the history (stage_view.js). When the model's
2
+ // own question blocks the turn after a reply, the reply that asked it (the
3
+ // reason) becomes a conversation bubble at the history's end, and from then
4
+ // to the turn's end the turn's prompt, its steps block and the rows that
5
+ // arrive are the history's; only what waits for the user (the card), the
6
+ // live slots and the answer stay in the stage. This module draws the reason
7
+ // bubble and moves things into the history (history_end.js), following a
8
+ // reader who was at the history's end (a reader scrolled up is never
9
+ // moved). At the hand-off the reasons go (end): each answered card's own
10
+ // two-line clamp says it then, as a finished turn and its reload have it.
11
+ //
12
+ // The reason bubble (.bubble.said, live only): a label line ("chi · step
13
+ // N", "asking you" while its card waits: .pending), the text raw at once,
14
+ // then its markdown when the page's render answers, refs linked on both
15
+ // draws. It carries data-question-id and data-said-turn (never
16
+ // data-turn-id: that marks a turn's opening, turn_range.js).
17
+ import { moveToHistoryEnd } from "./history_end.js";
18
+ import { revealInHistory } from "./history_reveal.js";
19
+ import { easeScrollTo } from "./scroll.js";
20
+
21
+ // What the history scrolls to sits this far under its top edge.
22
+ const READ_GAP = 8;
23
+
24
+ // +historyEl+: the history; +atHistoryEnd()+: the reader is at its end;
25
+ // +renderMarkdown(text)+: a promise of the text's HTML (null: keep it raw);
26
+ // +linkRefs(el, refs)+: the page's ref pass; +reduce()+: reduced motion;
27
+ // +afterSettle(fn)+: +fn+ once the stage has settled for a change made now
28
+ // (stage_frame.js afterGrowth: the asking form's shrink moves the history's
29
+ // bottom reserve, whose own follow of the end must not win over the
30
+ // reason's first line).
31
+ export function createOpenedTurn({
32
+ historyEl, atHistoryEnd, renderMarkdown = () => null, linkRefs = () => {}, reduce = () => false,
33
+ afterSettle = (fn) => requestAnimationFrame(() => requestAnimationFrame(fn)),
34
+ }) {
35
+ // card → its reason bubble, for the turn in the stage.
36
+ const reasons = new Map();
37
+ // The asking steps whose text a reason shows (data-said: their text is
38
+ // hidden in the block meanwhile, index.html), to clear at the end.
39
+ const saidSteps = new Set();
40
+
41
+ // The asking step: the last step of the history's last steps block (in
42
+ // order from the opening on, turn_block.js inOrder).
43
+ function askingStep() {
44
+ const block = [...historyEl.querySelectorAll(":scope > .turn-work")].at(-1);
45
+ return block?.querySelector(":scope > details.gen:last-of-type") || null;
46
+ }
47
+
48
+ // The reasons go: their steps show their own text again.
49
+ function clearSaid() {
50
+ for (const step of saidSteps) delete step.dataset.said;
51
+ saidSteps.clear();
52
+ }
53
+
54
+ // +el+'s top in the history's scroll.
55
+ function topIn(el) {
56
+ return historyEl.scrollTop + el.getBoundingClientRect().top - historyEl.getBoundingClientRect().top;
57
+ }
58
+
59
+ // The history to +el+'s top (none: its end). An +el+ gone meanwhile (a
60
+ // session switch drew another history) moves nothing: the scroll stays.
61
+ function scrollTo(el = null) {
62
+ return easeScrollTo(historyEl, () => {
63
+ if (el && !el.isConnected) return historyEl.scrollTop;
64
+ const end = historyEl.scrollHeight - historyEl.clientHeight;
65
+ return el ? Math.max(0, Math.min(end, topIn(el) - READ_GAP)) : end;
66
+ }, { reduce: reduce() });
67
+ }
68
+
69
+ // +pieces+ to the history's end in order; a reader at the end follows
70
+ // (+follow+: false when a reason's read follows instead).
71
+ function add(pieces, { follow = atHistoryEnd() } = {}) {
72
+ moveToHistoryEnd(historyEl, pieces);
73
+ if (follow) scrollTo();
74
+ }
75
+
76
+ function reasonBubble({ text, refs, step, turnId, questionId }) {
77
+ const bubble = document.createElement("div");
78
+ bubble.className = "bubble said pending";
79
+ if (questionId != null) bubble.dataset.questionId = String(questionId);
80
+ if (turnId) bubble.dataset.saidTurn = turnId;
81
+ const label = document.createElement("div");
82
+ label.className = "said-label";
83
+ const who = document.createElement("span");
84
+ who.textContent = step ? `chi · step ${step}` : "chi";
85
+ const asking = document.createElement("span");
86
+ asking.className = "said-asking";
87
+ asking.textContent = "asking you";
88
+ label.append(who, asking);
89
+ const body = document.createElement("div");
90
+ body.className = "said-text";
91
+ body.textContent = text;
92
+ bubble.append(label, body);
93
+ linkRefs(body, refs);
94
+ // Its markdown, under the reader's first lines (the bubble's one
95
+ // height change).
96
+ Promise.resolve()
97
+ .then(() => renderMarkdown(text))
98
+ .catch(() => null)
99
+ .then((html) => {
100
+ if (!html || !bubble.isConnected) return;
101
+ // Sanitised on the server (POST /api/render).
102
+ body.innerHTML = html;
103
+ body.classList.add("markdown", "md-compact");
104
+ linkRefs(body, refs);
105
+ });
106
+ return bubble;
107
+ }
108
+
109
+ // The card's way back to its reason, at its title line's right.
110
+ function reasonLink(card, bubble) {
111
+ const summary = card.querySelector(":scope > summary");
112
+ if (!summary) return;
113
+ const link = document.createElement("button");
114
+ link.type = "button";
115
+ link.className = "question-reason-link";
116
+ link.textContent = "↑ its reason";
117
+ link.title = "Show the reply that asked this";
118
+ link.addEventListener("click", (e) => {
119
+ // Inside the summary: no toggle.
120
+ e.preventDefault();
121
+ e.stopPropagation();
122
+ if (bubble.isConnected) scrollTo(bubble);
123
+ });
124
+ summary.appendChild(link);
125
+ }
126
+
127
+ // The first of the history's rows after one of +going+ (they move when
128
+ // it goes) whose bottom is below the view's top; null: none (what shows
129
+ // is above them all, and stays).
130
+ function firstInView(going) {
131
+ const top = historyEl.getBoundingClientRect().top;
132
+ let after = false;
133
+ for (const el of historyEl.children) {
134
+ if (going.includes(el)) {
135
+ after = true;
136
+ continue;
137
+ }
138
+ if (after && el.getBoundingClientRect().bottom > top) return el;
139
+ }
140
+ return null;
141
+ }
142
+
143
+ return {
144
+ // The turn's pieces so far (handOffOrder's order) into the history; the
145
+ // reason's read (ask) does the follow.
146
+ open: (pieces) => add(pieces, { follow: false }),
147
+ // A row of the opened turn: to the history's end.
148
+ add: (el) => add([el]),
149
+ // +card+ blocks the turn: its reason's bubble at the history's end, in
150
+ // the card's task; a reader at the end reads it from its first line.
151
+ // +follow+: the reader was at the end before the turn opened.
152
+ ask({ card, text, refs = null, step = 0, turnId = null, questionId = null, follow = atHistoryEnd() }) {
153
+ const bubble = reasonBubble({ text, refs, step, turnId, questionId });
154
+ moveToHistoryEnd(historyEl, [bubble]);
155
+ reasons.set(card, bubble);
156
+ // The step's own text is the reason: not twice (and raw while the
157
+ // step runs). data-said, not a class: lit owns the step's class.
158
+ const stepEl = askingStep();
159
+ if (stepEl) {
160
+ stepEl.dataset.said = "1";
161
+ saidSteps.add(stepEl);
162
+ }
163
+ reasonLink(card, bubble);
164
+ // The reader at the end reads it from its first line: meanwhile the
165
+ // history is marked data-reading, so the bottom reserve's follow
166
+ // (dock_reserve.js) doesn't take the end back.
167
+ if (follow) {
168
+ historyEl.dataset.reading = "";
169
+ afterSettle(() => {
170
+ const done = () => { delete historyEl.dataset.reading; };
171
+ if (bubble.isConnected) scrollTo(bubble).then(done, done);
172
+ else done();
173
+ });
174
+ }
175
+ return bubble;
176
+ },
177
+ has: (card) => reasons.has(card),
178
+ // +card+ no longer waits (answered, cancelled): it goes right under its
179
+ // reason, which stops saying "asking you"; another card of the turn to
180
+ // the history's end. A reader at the end follows.
181
+ settle(card) {
182
+ const bubble = reasons.get(card);
183
+ if (!bubble?.isConnected) return add([card]);
184
+ const follow = atHistoryEnd();
185
+ bubble.classList.remove("pending");
186
+ bubble.after(card);
187
+ if (follow) scrollTo();
188
+ },
189
+ // The turn's steps block (or one of its steps, +el+) in the history:
190
+ // unfolded and brought into view.
191
+ reveal(el) {
192
+ if (!el) return;
193
+ revealInHistory(el);
194
+ if (el.matches?.("details") && !el.open) el.open = true;
195
+ scrollTo(el);
196
+ },
197
+ // The reasons drawn (the hand-off waits while one is in use).
198
+ watched: () => [...reasons.values()].filter((el) => el.isConnected),
199
+ // The hand-off: the reasons go; each card's own clamp says it now. The
200
+ // reader keeps what they see: the first row in view that stays (the
201
+ // card under a reason they read) stays where it is (the history's own
202
+ // scroll anchoring has none to keep when the row it anchored on goes);
203
+ // a reader at the end then follows the turn's arrival (stage_view.js
204
+ // finishFold).
205
+ end() {
206
+ const gone = [...reasons.values()].filter((el) => el.isConnected);
207
+ reasons.clear();
208
+ clearSaid();
209
+ if (!gone.length) return;
210
+ const anchor = firstInView(gone);
211
+ const before = anchor?.getBoundingClientRect().top;
212
+ for (const bubble of gone) bubble.remove();
213
+ if (anchor) historyEl.scrollTop += anchor.getBoundingClientRect().top - before;
214
+ },
215
+ // The turn left the stage without a hand-off (a reset): forgotten, the
216
+ // history is drawn anew.
217
+ reset() {
218
+ reasons.clear();
219
+ saidSteps.clear();
220
+ },
221
+ // The turn was released without its end (a lost turn_completed, the
222
+ // next turn started): its reasons go, nothing else moves.
223
+ drop() {
224
+ for (const bubble of reasons.values()) bubble.remove();
225
+ reasons.clear();
226
+ clearSaid();
227
+ },
228
+ };
229
+ }
@@ -91,8 +91,7 @@ export function createStageSlots({
91
91
  // A null isn't kept: the next draw of this text asks again.
92
92
  if (!html && rendering === pending) rendering = { text: null, html: null };
93
93
  if (shown.asking !== text || askingFinal) return;
94
- // The raw text is final (markdown off, a failed read): the stage
95
- // measures it now.
94
+ // The raw text is final (markdown off, a failed read).
96
95
  if (!html) {
97
96
  askingFinal = true;
98
97
  onChange?.();
@@ -106,7 +105,7 @@ export function createStageSlots({
106
105
  asking.scrollTop = 0;
107
106
  linkRefs(asking, askingRefs);
108
107
  askingFinal = true;
109
- // Its height changed: the stage measures it now (the question room).
108
+ // Its height changed: the stage refits.
110
109
  onChange?.();
111
110
  });
112
111
  }