samagotchi 0.165.0 → 0.167.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 (100) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +99 -1
  3. data/docs/architecture.md +1 -0
  4. data/docs/cli.md +16 -7
  5. data/docs/configuration.md +4 -1
  6. data/docs/guardrails.md +8 -3
  7. data/docs/hooks.md +4 -6
  8. data/docs/internals/bridge.md +6 -0
  9. data/docs/internals/bundles.md +2 -4
  10. data/docs/internals/engine.md +4 -5
  11. data/docs/internals/objectives.md +141 -9
  12. data/docs/internals/remote-sessions.md +6 -7
  13. data/docs/internals/web-frontend.md +62 -24
  14. data/docs/memory.md +1 -2
  15. data/docs/releasing.md +12 -3
  16. data/docs/sessions.md +24 -6
  17. data/docs/testing.md +14 -4
  18. data/lib/samagotchi/bridge.rb +1 -1
  19. data/lib/samagotchi/bundle_command/installed_check.rb +2 -14
  20. data/lib/samagotchi/bundle_command.rb +19 -11
  21. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  22. data/lib/samagotchi/cli/command.rb +10 -0
  23. data/lib/samagotchi/compat.rb +4 -14
  24. data/lib/samagotchi/config.rb +3 -0
  25. data/lib/samagotchi/context_command.rb +2 -1
  26. data/lib/samagotchi/engine/objectives.rb +20 -1
  27. data/lib/samagotchi/engine/side_requests.rb +3 -2
  28. data/lib/samagotchi/engine/turn_end.rb +4 -1
  29. data/lib/samagotchi/engine.rb +3 -0
  30. data/lib/samagotchi/extension_load.rb +2 -26
  31. data/lib/samagotchi/guardrails/approvals.rb +59 -9
  32. data/lib/samagotchi/jsonl_store.rb +61 -0
  33. data/lib/samagotchi/memory_bundle/status.rb +3 -15
  34. data/lib/samagotchi/memory_bundle/system_bundle.rb +16 -10
  35. data/lib/samagotchi/memory_command.rb +4 -2
  36. data/lib/samagotchi/objectives.rb +43 -14
  37. data/lib/samagotchi/objectives_backing.rb +124 -0
  38. data/lib/samagotchi/objectives_check.rb +19 -126
  39. data/lib/samagotchi/objectives_command.rb +14 -7
  40. data/lib/samagotchi/objectives_record.rb +104 -0
  41. data/lib/samagotchi/objectives_track.rb +353 -0
  42. data/lib/samagotchi/plugin/sessions.rb +4 -1
  43. data/lib/samagotchi/push_command.rb +2 -1
  44. data/lib/samagotchi/remote_command.rb +2 -1
  45. data/lib/samagotchi/reply_wait/poll.rb +10 -21
  46. data/lib/samagotchi/reply_wait.rb +4 -47
  47. data/lib/samagotchi/run_options.rb +1 -1
  48. data/lib/samagotchi/schedule_command.rb +6 -0
  49. data/lib/samagotchi/schedules.rb +1 -1
  50. data/lib/samagotchi/session_access/remote.rb +7 -24
  51. data/lib/samagotchi/session_commands.rb +1 -1
  52. data/lib/samagotchi/session_inbox.rb +1 -1
  53. data/lib/samagotchi/sessions_command.rb +12 -6
  54. data/lib/samagotchi/share_command.rb +2 -1
  55. data/lib/samagotchi/tool_activity.rb +11 -1
  56. data/lib/samagotchi/tool_declarations.rb +5 -1
  57. data/lib/samagotchi/tools/delegate.rb +2 -4
  58. data/lib/samagotchi/tools/objectives_tool.rb +19 -2
  59. data/lib/samagotchi/turn_stages/objectives.rb +46 -3
  60. data/lib/samagotchi/version.rb +1 -1
  61. data/lib/samagotchi/web/participant_access.rb +1 -1
  62. data/lib/samagotchi/web/public/app.js +55 -420
  63. data/lib/samagotchi/web/public/auth_lost.js +3 -1
  64. data/lib/samagotchi/web/public/bar_fold.js +1 -1
  65. data/lib/samagotchi/web/public/chip_popover.js +5 -1
  66. data/lib/samagotchi/web/public/copy.js +2 -1
  67. data/lib/samagotchi/web/public/delivery_line.js +19 -4
  68. data/lib/samagotchi/web/public/index.html +156 -49
  69. data/lib/samagotchi/web/public/info_bar.js +1 -1
  70. data/lib/samagotchi/web/public/info_bar_model.js +8 -1
  71. data/lib/samagotchi/web/public/live_timing.js +3 -0
  72. data/lib/samagotchi/web/public/no_contact_fill.js +29 -0
  73. data/lib/samagotchi/web/public/objectives.css +14 -0
  74. data/lib/samagotchi/web/public/objectives_moves.js +82 -9
  75. data/lib/samagotchi/web/public/objectives_state.js +42 -0
  76. data/lib/samagotchi/web/public/objectives_strip.js +33 -9
  77. data/lib/samagotchi/web/public/objectives_track.js +52 -0
  78. data/lib/samagotchi/web/public/objectives_wiring.js +16 -1
  79. data/lib/samagotchi/web/public/participant.html +1 -1
  80. data/lib/samagotchi/web/public/participants_panel.js +14 -7
  81. data/lib/samagotchi/web/public/question_cards.js +7 -12
  82. data/lib/samagotchi/web/public/resync_reach.js +63 -0
  83. data/lib/samagotchi/web/public/scope.js +3 -3
  84. data/lib/samagotchi/web/public/session_fields.js +1 -0
  85. data/lib/samagotchi/web/public/session_rename.js +6 -2
  86. data/lib/samagotchi/web/public/session_state.js +6 -1
  87. data/lib/samagotchi/web/public/session_sync.js +249 -0
  88. data/lib/samagotchi/web/public/session_view.js +279 -0
  89. data/lib/samagotchi/web/public/stage_frame.js +4 -2
  90. data/lib/samagotchi/web/public/stage_stall.js +134 -0
  91. data/lib/samagotchi/web/public/stage_view.js +75 -6
  92. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  93. data/lib/samagotchi/web/public/tokens.css +2 -2
  94. data/lib/samagotchi/web/public/turn_block.js +8 -0
  95. data/lib/samagotchi/web/public/turn_html.js +1 -1
  96. data/lib/samagotchi/web/public/widget_picks.js +3 -0
  97. data/lib/samagotchi/web/public/working_set_view.js +1 -1
  98. data/lib/samagotchi/web/session_access_routes.rb +4 -15
  99. data/lib/samagotchi/web/token.rb +2 -2
  100. metadata +12 -1
@@ -78,8 +78,13 @@ export function emptySessionState() {
78
78
  // has to start; set by the page's resync, not by the payload.
79
79
  streamSeq: null,
80
80
  // The stream was opened from 0 (a wake with no cursor to go on) and no
81
- // new turn has started on it yet (app.js followWokenWorker).
81
+ // new turn has started on it yet (session_sync.js followWokenWorker).
82
82
  streamFromGuess: false,
83
+ // A re-read that couldn't reach chi web kept the drawn history
84
+ // (resync_reach.js): "reconnecting" while it retries, "offline" once
85
+ // the tries ran out; null otherwise. Never from a payload: the next
86
+ // re-read that draws the session clears it.
87
+ reach: null,
83
88
  };
84
89
  }
85
90
 
@@ -0,0 +1,249 @@
1
+ // The open session's sync with the server (split out of app.js): select()
2
+ // opens a session, resync() (re)renders it from GET /api/sessions/:id and
3
+ // streams on from the cursor that render covers, and the stream's life
4
+ // (startStream, workerGone, closeStream, restart). The stream handle and the
5
+ // re-read bookkeeping (resyncsInFlight, resyncAgain, resyncAttempts, the
6
+ // resync_reach.js instance) live here and nowhere else: the page reads them
7
+ // through hasStream() and streamLive().
8
+ //
9
+ // Everything that changes while the page runs is read through deps at the
10
+ // call, never captured at creation (as stream_handlers.js): the open session
11
+ // (store.selected), its fields (store.current), the views made after this
12
+ // one (the getters in +later+), the session view's hooks (+view+).
13
+ //
14
+ // deps:
15
+ // store the page's session store (session_store.js)
16
+ // historyEl, emptyEl the history and the start page's empty box
17
+ // getSession(id, opts), openStream(id, fromSeq, handlers, opts) data.js
18
+ // liveTurn, turnDom, questionCards, contextChips, participantsControl the page's views
19
+ // view: {forgetSession(opts), renderSessionView(data, opts), endTurnView(kind, endText, opts)}
20
+ // the session view (session_view.js)
21
+ // page: {clearNotice(), setSessionHash(id), setTurnRunning(running), setLiveStatus(status),
22
+ // replaceCard(id, change), addEndBubble(text)} the page's hooks
23
+ // later: {handlers(), composer(), focusPrompt(opts), sessionActions(), ownerClaim()}
24
+ // the views made after this one: the stream handlers,
25
+ // the composer, session_actions.js, owner_claim.js
26
+ //
27
+ // @return {select, resync, followSelectedSession, followWokenWorker, workerGone, resetTurnView, closeStream,
28
+ // restart, closeLive, hasStream, streamLive, startStream, retryResync}
29
+ // hasStream(): a stream object exists (the info bar's streaming, also while it connects);
30
+ // streamLive(): it delivers (its .live); restart(): close it and resync;
31
+ // closeLive(): close it, keeping the handle (workerGone clears it, through onStreamClosed).
32
+ // Its own module: new exports go in new modules (web-frontend.md).
33
+
34
+ import { fieldsFromCard } from "./session_fields.js";
35
+ import { hintEl } from "./bubbles.js";
36
+ import { withoutWorker } from "./format.js";
37
+ import { resyncRetry, streamDropEnd } from "./turn_events.js";
38
+ import { createResyncReach } from "./resync_reach.js";
39
+ import { keptCommandBubbles } from "./commands.js";
40
+
41
+ // +opened+ false: the stream never delivered a frame (the proxy answered
42
+ // 503, or the bridge refused it), so a retry waits a moment rather than
43
+ // spinning through resync → stream → error.
44
+ export const STREAM_RETRY_MS = 3000;
45
+ // A re-read that failed (the phone still offline, chi web a moment): try it
46
+ // again, backing off, and stop when the tries run out. The running turn's DOM
47
+ // is left alone meanwhile: a worker that still owns the turn keeps showing it running,
48
+ // and the hub's next event for the session is the fallback once the tries end.
49
+ export const RESYNC_RETRIES = 3;
50
+
51
+ export function createSessionSync(deps) {
52
+ const {
53
+ store, historyEl, emptyEl, getSession, openStream,
54
+ liveTurn, turnDom, questionCards, contextChips, participantsControl,
55
+ page, later,
56
+ } = deps;
57
+ let streamControl = null;
58
+ // resync() calls in flight, and whether a worker came up for the selected
59
+ // session while one ran (its bridge_up event): the tail runs once more.
60
+ let resyncsInFlight = 0;
61
+ let resyncAgain = false;
62
+ // A failed re-read keeps the drawn history and says so in the bar (resync_reach.js).
63
+ const resyncReach = createResyncReach({ store, historyEl, errorHint: (message) => hintEl(`Error: ${message}`) });
64
+ let resyncAttempts = 0;
65
+
66
+ // The selected session's card changed: its owner and, without a live
67
+ // stream, its status show in the info bar; a worker whose bridge is up
68
+ // (a turn another client sent woke one, or a replacement after a kill)
69
+ // gets the stream attached through one resync.
70
+ function followSelectedSession(sess) {
71
+ const streaming = !!(streamControl && streamControl.live);
72
+ // A Verify gate that flips (a restart brought the feature) redraws the
73
+ // cards' Verify fresh part: featureGates.
74
+ store.batch(() => {
75
+ store.update({ current: fieldsFromCard(sess) });
76
+ store.setStatus(sess.status, "hub", { streaming });
77
+ });
78
+ if (streaming || !(sess.bridge_up || resyncReach.needsReread())) return;
79
+ if (resyncsInFlight > 0) resyncAgain = true;
80
+ else resync();
81
+ }
82
+
83
+ async function select(id) {
84
+ page.clearNotice();
85
+ const same = store.selected === id;
86
+ // Its synchronous part in one batch: the active card, the composer and
87
+ // the bar redraw once, at its end (never across the await).
88
+ store.batch(() => {
89
+ store.update({ selected: id });
90
+ page.setSessionHash(id);
91
+ historyEl.replaceChildren(hintEl("Loading…"));
92
+ resyncReach.loading();
93
+ emptyEl.classList.add("hidden");
94
+ resyncAttempts = 0; // this session has its own re-read budget
95
+ deps.view.forgetSession({ keepVerify: same });
96
+ contextChips.load(id);
97
+ participantsControl.load(id);
98
+ });
99
+ await resync();
100
+ // A folded composer stays folded: typing on the page opens it.
101
+ later.focusPrompt({ open: false });
102
+ }
103
+
104
+ // Clear everything that belongs to one turn's rendering.
105
+ function resetTurnView() {
106
+ closeStream();
107
+ // workerGone and a re-render come through here: the answer_display wait
108
+ // goes too.
109
+ liveTurn.forget();
110
+ questionCards.removeQuestion();
111
+ questionCards.forgetContinue();
112
+ page.setTurnRunning(false);
113
+ }
114
+
115
+ // @return whether another try is scheduled
116
+ function retryResync(id, { endText = null } = {}) {
117
+ if (id !== store.selected) return false;
118
+ const { attempt, delayMs } = resyncRetry({ attempts: resyncAttempts, max: RESYNC_RETRIES, baseMs: STREAM_RETRY_MS });
119
+ if (delayMs === null) return false;
120
+ resyncAttempts = attempt;
121
+ setTimeout(() => {
122
+ if (id !== store.selected || (streamControl && streamControl.live)) return;
123
+ resync({ endText });
124
+ }, delayMs);
125
+ return true;
126
+ }
127
+
128
+ // (Re)render the selected session from the server and stream on from the
129
+ // event_seq that render covers. Used on select, when the stream resets
130
+ // (its cursor could not be replayed) and when it dropped (workerGone).
131
+ // Without a live bridge there is nothing to stream: the session's next
132
+ // event with bridge_up (a worker another client woke) resyncs again
133
+ // (followSelectedSession); a bridge_up that arrived while this ran is
134
+ // taken by the tail. +endText+: what workerGone said about the turn the
135
+ // worker left unfinished; shown again after the re-render when no worker
136
+ // took over.
137
+ async function resync({ endText = null } = {}) {
138
+ const id = store.selected;
139
+ if (!id) return;
140
+ resyncsInFlight += 1;
141
+ let data;
142
+ try {
143
+ try {
144
+ data = await getSession(id);
145
+ } catch (e) {
146
+ if (e.status === 404) return later.sessionActions().leaveGoneSession(id, "not_found");
147
+ if (id === store.selected) resyncReach.failed(id, e.message, { retrying: retryResync(id, { endText }) });
148
+ return;
149
+ }
150
+ resyncAttempts = 0;
151
+ if (id !== store.selected) return;
152
+ // An archived session opens folded: decided once per visit, from its
153
+ // first answer (the list may not hold it yet, or ever under ?dir).
154
+ later.composer().decideVisit(data.session?.archived);
155
+ const kept = keptCommandBubbles(historyEl, id);
156
+ resetTurnView();
157
+ deps.view.renderSessionView(data, { kept });
158
+ resyncReach.drawn(id);
159
+ later.ownerClaim().showPending();
160
+ // Preview is read-only: a worker is woken only by POST /turn, so attach
161
+ // only when a live bridge exists.
162
+ store.update({ current: { streamSeq: typeof data.last_event_seq === "number" ? (data.last_event_id || data.last_event_seq) : null } });
163
+ if (store.current.streamSeq !== null) startStream(id, store.current.streamSeq);
164
+ else if (endText) page.addEndBubble(endText);
165
+ } finally {
166
+ resyncsInFlight -= 1;
167
+ if (resyncsInFlight === 0 && resyncAgain) {
168
+ resyncAgain = false;
169
+ if (id === store.selected && !(streamControl && streamControl.live)) resync();
170
+ }
171
+ }
172
+ }
173
+
174
+ // A turn or command just woke the session's worker: follow its stream if
175
+ // none is open, from the render's cursor. A render with none (no worker
176
+ // then) streams from 0, the start of a new worker's events; should that
177
+ // worker have been up already, turn_started says so (replaysDrawnTurn).
178
+ function followWokenWorker() {
179
+ if (streamControl?.live) return;
180
+ startStream(store.selected, store.current.streamSeq ?? 0);
181
+ store.update({ current: { streamFromGuess: store.current.streamSeq === null } });
182
+ }
183
+
184
+ function startStream(id, fromSeq) {
185
+ store.update({ current: { streamFromGuess: false } });
186
+ if (streamControl) {
187
+ streamControl.close();
188
+ streamControl = null;
189
+ }
190
+ streamControl = openStream(id, fromSeq, later.handlers(), {
191
+ // The stream dropped or never opened: the worker left (idle exit, stop,
192
+ // crash) or is starting. Its cursor means nothing to the next worker
193
+ // (event_seq starts over), so re-read the session once one is live.
194
+ onStreamClosed: () => workerGone(id),
195
+ onStreamError: () => workerGone(id, { opened: false }),
196
+ });
197
+ store.touch("infoBar"); // streaming
198
+ }
199
+
200
+ function workerGone(id, { opened = true } = {}) {
201
+ streamControl = null;
202
+ if (id !== store.selected) return;
203
+ // A turn that was running is over only when the worker really left: a
204
+ // stream that merely dropped (no stop, it was open) waits for the re-read.
205
+ const stopped = later.sessionActions().stoppingId() === id;
206
+ const { endNow, endText } = streamDropEnd({ turnRunning: liveTurn.running, stopped, opened });
207
+ if (endNow) deps.view.endTurnView("gone", endText, { stopped });
208
+ store.batch(() => {
209
+ if (endNow && !stopped) page.setLiveStatus("idle");
210
+ store.update({ current: { ...(store.current.owner === "worker" ? { owner: null } : {}), bridgeUp: false } });
211
+ // Its card says "live" (the list's owner, or setLiveStatus's) until the
212
+ // hub's event says otherwise: the worker is gone now, as far as this
213
+ // tab can tell.
214
+ if (store.sessions.find((s) => s.id === id)?.owner === "worker") page.replaceCard(id, withoutWorker);
215
+ store.touch("infoBar"); // streaming
216
+ });
217
+ // Once: a worker still alive with a bridge (the stream dropped, not the
218
+ // worker: chi web restarted) reconnects right here. Otherwise the next
219
+ // worker's bridge_up event brings the stream back (followSelectedSession).
220
+ if (opened) resync({ endText });
221
+ else setTimeout(() => { if (id === store.selected && !(streamControl && streamControl.live)) resync({ endText }); }, STREAM_RETRY_MS);
222
+ }
223
+
224
+ function closeStream() {
225
+ turnDom.reset();
226
+ if (streamControl) {
227
+ streamControl.close();
228
+ streamControl = null;
229
+ }
230
+ }
231
+
232
+ // The stream handlers' restart (a reset the cursor can't replay): close
233
+ // the stream and resync.
234
+ function restart() {
235
+ streamControl?.close();
236
+ streamControl = null;
237
+ resync();
238
+ }
239
+
240
+ return {
241
+ select, resync, followSelectedSession, followWokenWorker, workerGone, resetTurnView, closeStream, restart,
242
+ // session_actions.js closeLiveStream: close only, the handle stays (workerGone clears it).
243
+ closeLive: () => streamControl?.close(),
244
+ hasStream: () => !!streamControl,
245
+ streamLive: () => !!streamControl?.live,
246
+ // For the spec.
247
+ startStream, retryResync,
248
+ };
249
+ }
@@ -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
+ }
@@ -125,9 +125,11 @@ export function createStageFrame({ stage, scroller, status, cloud, queuedSlot, h
125
125
  function fitCap() {
126
126
  if (stage.hidden) return;
127
127
  // The composer card and the gap above it (the stage floats over them,
128
- // out of the dock's flow).
128
+ // out of the dock's flow), the card's offset from the panel's bottom
129
+ // (index.html --dock-bottom: 16 px, a phone's home indicator's line)
130
+ // and 16 px over the stage.
129
131
  const rest = dockEl.offsetHeight + STAGE_GAP;
130
- const room = centerEl.clientHeight - rest - 32;
132
+ const room = centerEl.clientHeight - rest - 16 - (parseFloat(getComputedStyle(dockEl).bottom) || 16);
131
133
  const share = window.innerHeight * (isRoomCap() ? ROOM_SHARE : isCloudOpen() ? CLOUD_SHARE : SHARE);
132
134
  const cap = Math.max(96, Math.round(Math.min(share, room)));
133
135
  const was = capPx();