samagotchi 0.162.0 → 0.164.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 (56) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +42 -1
  3. data/docs/architecture.md +2 -2
  4. data/docs/bundles.md +4 -2
  5. data/docs/cli.md +7 -2
  6. data/docs/configuration.md +1 -1
  7. data/docs/internals/block-renderers.md +3 -1
  8. data/docs/internals/bridge.md +37 -24
  9. data/docs/internals/inline-widgets.md +5 -2
  10. data/docs/internals/remote-sessions.md +7 -2
  11. data/docs/internals/web-frontend.md +1 -1
  12. data/docs/memory.md +8 -2
  13. data/docs/sessions.md +3 -2
  14. data/docs/sub-agent.md +11 -0
  15. data/docs/testing.md +8 -2
  16. data/lib/samagotchi/block_renderers.rb +14 -4
  17. data/lib/samagotchi/bridge/turn_drawings/synth.rb +7 -3
  18. data/lib/samagotchi/bridge/turn_drawings.rb +45 -30
  19. data/lib/samagotchi/bundles/inline-widgets/manifest.yml +2 -2
  20. data/lib/samagotchi/bundles/inline-widgets/plugin.rb +8 -4
  21. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  22. data/lib/samagotchi/cli/parent_wait.rb +5 -1
  23. data/lib/samagotchi/continue_intent.rb +48 -0
  24. data/lib/samagotchi/message_parts.rb +13 -0
  25. data/lib/samagotchi/note_command.rb +3 -6
  26. data/lib/samagotchi/parent_report.rb +3 -2
  27. data/lib/samagotchi/project_command.rb +74 -6
  28. data/lib/samagotchi/project_subfolders.rb +188 -0
  29. data/lib/samagotchi/send_command/parent_gate.rb +8 -5
  30. data/lib/samagotchi/send_command.rb +139 -34
  31. data/lib/samagotchi/session_access/local.rb +6 -0
  32. data/lib/samagotchi/session_access/remote.rb +25 -0
  33. data/lib/samagotchi/session_continue.rb +5 -3
  34. data/lib/samagotchi/session_inbox_delivery.rb +54 -7
  35. data/lib/samagotchi/session_manager/delivery.rb +3 -1
  36. data/lib/samagotchi/terminal_ui/join_replay.rb +2 -2
  37. data/lib/samagotchi/version.rb +1 -1
  38. data/lib/samagotchi/web/message_display.rb +45 -36
  39. data/lib/samagotchi/web/public/app.js +8 -7
  40. data/lib/samagotchi/web/public/apple-touch-icon.png +0 -0
  41. data/lib/samagotchi/web/public/data.js +4 -6
  42. data/lib/samagotchi/web/public/favicon.svg +1 -1
  43. data/lib/samagotchi/web/public/icons/chi-180.png +0 -0
  44. data/lib/samagotchi/web/public/icons/chi-192.png +0 -0
  45. data/lib/samagotchi/web/public/icons/chi-512.png +0 -0
  46. data/lib/samagotchi/web/public/inline_widgets.js +4 -1
  47. data/lib/samagotchi/web/public/reload_check.js +7 -4
  48. data/lib/samagotchi/web/public/time_gaps.js +1 -2
  49. data/lib/samagotchi/web/public/timing.js +49 -224
  50. data/lib/samagotchi/web/public/turn_block.js +40 -122
  51. data/lib/samagotchi/web/public/turn_html.js +3 -2
  52. data/lib/samagotchi/web/public/widget_walk.js +14 -4
  53. data/lib/samagotchi/web/reload_check_route.rb +6 -3
  54. data/lib/samagotchi/web/session_access_routes.rb +8 -1
  55. data/lib/samagotchi/web/session_show.rb +8 -24
  56. metadata +3 -1
@@ -145,132 +145,77 @@ function replaceById(records, record) {
145
145
  return true;
146
146
  }
147
147
 
148
- // The record at a prompt's place among the turns that left one: a failure
149
- // that kept nothing (its prompt went back) has no place (Bridge::TurnRanges.records).
150
- function placedRecord(timing, index) {
151
- const records = Array.isArray(timing?.turnRecords) ? timing.turnRecords : [];
152
- const placed = records.filter((r) => !(r?.status === "failed" && r.failure && typeof r.failure === "object" && !r.failure.kept_steps));
153
- return placed[index] || null;
154
- }
155
-
156
- export function turnRecordAt(timing, index) {
157
- const records = timing?.turnRecords;
158
- return Array.isArray(records) ? records[index] || null : null;
159
- }
160
-
161
148
  // A history item that starts a turn: a prompt, or the note a context wake
162
149
  // turn starts with (turn_start). A `!cmd`'s record (shell_command.js) is a
163
150
  // user message but no prompt: no turn, no record, no timing.
164
151
  const startsTurn = (item) =>
165
152
  (item?.role === "user" && !isShellCommandItem(item)) || (item?.role === "note" && item.turn_start === true);
166
153
 
167
- // For each history item, the turn index its timing shows under, or null. A
168
- // turn with tool calls holds several assistant messages; only the last one
169
- // before the next user message carries the turn's timing. A turn with none
170
- // (canceled before an answer, or still running: no record yet) has it on
171
- // its user message.
172
- export function timedTurnIndexes(items) {
173
- const result = items.map(() => null);
174
- let turnIndex = -1;
175
- let carrier = null;
176
- items.forEach((item, i) => {
177
- if (startsTurn(item)) {
178
- if (carrier !== null) result[carrier] = turnIndex;
179
- turnIndex += 1;
180
- carrier = i;
181
- } else if (item?.role === "assistant") {
182
- carrier = i;
183
- }
184
- });
185
- if (carrier !== null) result[carrier] = turnIndex;
186
- return result;
187
- }
188
-
189
- // The history as turns, for the turn block's reload: notes on their own, and
190
- // per prompt a turn with its record, its steps (one per iteration: the
191
- // turn's tool records grouped by iteration, and the assistant messages but
192
- // the last, in order; a text-less iteration leaves no message, so a text
193
- // can sit one step early: inspection, not truth) and its answer (the last
194
- // assistant message). Assistant messages before any prompt are answers on
195
- // their own. A turn that ended with no answer (the server's empty_answer
196
- // item) has no answer: its texts are steps, and `emptyAnswer` is that
197
- // item's index. A `!cmd`'s record is a group of its own (`command`, its
198
- // index): no steps, no record, no turn index. The turn index counts
199
- // prompts, as timedTurnIndexes does. The
200
- // user's lines merged into the running turn (`merged`, the server's
201
- // Steer::INPUT_KIND) stay in it: the turn's `merged` list.
202
- // +drawings+ (chi web's turn_drawings, {turn_id: {events, end}}): the items
203
- // stamped with a drawn turn's id (`drawn`) are that turn's group (`drawn`,
204
- // its `drawing`), whether or not they start with an opening (a reminder
205
- // turn has none; a wake's note, outside the range, opens it by its id); its
206
- // steps are the drawing's (turn_drawing.js), and an unstamped item after it
207
- // starts no part of it.
208
- export function turnGroups(items, timing, { drawings = null } = {}) {
154
+ // The history as turns, for a reload: chi web draws every finished turn
155
+ // (turn_drawings, {turn_id: {events, end}}), and the items stamped with a
156
+ // drawn turn's id (`drawn`) are that turn's group (`drawn`, its `drawing`),
157
+ // whether or not they start with an opening (a reminder turn has none; a
158
+ // wake's note, outside the range, opens it by its id); its steps are the
159
+ // drawing's (turn_drawing.js), and an unstamped item after it starts no
160
+ // part of it. A loose context note is a group of its own (`note`), a
161
+ // `!cmd`'s record too (`command`: no steps, no record, no turn index).
162
+ // Any other unstamped item is a `plain` group (its index): a row of its
163
+ // text, no steps. The running turn's (its opening's turn id
164
+ // +runningTurnId+, and what follows it: no line until its end) are
165
+ // `running`; any other is a miss (turn_block.js draws and logs it).
166
+ // The turn index counts the drawn turns.
167
+ export function turnGroups(items, timing, { drawings = null, runningTurnId = null } = {}) {
209
168
  const groups = [];
210
169
  let turnIndex = -1;
211
170
  let turn = null;
171
+ let running = false;
212
172
  items.forEach((item, i) => {
213
173
  const drawn = drawings && typeof item?.drawn === "string" && drawings[item.drawn] ? item.drawn : null;
214
- const looseNote = item?.role === "note" && !startsTurn(item);
215
- if (turn?.drawn && !drawn && !looseNote) turn = null;
216
- // An opening just before the range with the drawn turn's id (a wake's
217
- // note, added before the turn began): the drawn turn's own.
218
- if (drawn && turn && !turn.drawn && turn.turnId === drawn && turn.texts.length === 0) turn.drawn = drawn;
219
- if (drawn && turn?.drawn !== drawn && !looseNote) {
174
+ if (item?.role === "note" && !startsTurn(item)) { groups.push({ kind: "note", i }); return; }
175
+ if (!drawn) {
176
+ turn = null;
177
+ if (isShellCommandItem(item)) { groups.push({ kind: "command", i }); return; }
178
+ if (startsTurn(item) && !item.merged) running = runningTurnId != null && item.turn_id === runningTurnId;
179
+ groups.push(running ? { kind: "plain", i, running: true } : { kind: "plain", i });
180
+ return;
181
+ }
182
+ running = false;
183
+ if (turn?.drawn !== drawn) {
184
+ // An opening just before the range with the drawn turn's id (a wake's
185
+ // note, added before the turn began, loose notes after it): the drawn
186
+ // turn's own.
187
+ const back = groups.findLastIndex((g) => g.kind !== "note");
188
+ const wake = back >= 0 && groups[back].kind === "plain" && items[groups[back].i]?.role === "note"
189
+ && items[groups[back].i].turn_id === drawn ? groups[back].i : null;
220
190
  turnIndex += 1;
221
- turn = { kind: "turn", turnIndex, turnId: drawn, drawn, user: startsTurn(item) ? i : null, texts: [], steers: [], merged: [] };
222
- groups.push(turn);
223
- if (startsTurn(item)) return;
224
- } else if (drawn && turn?.drawn === drawn && startsTurn(item) && !item.merged && item.role === "user") {
191
+ turn = { kind: "turn", turnIndex, turnId: drawn, drawn, user: wake ?? (startsTurn(item) ? i : null), texts: [], steers: [], merged: [] };
192
+ if (wake != null) groups.splice(back, 1, turn);
193
+ else groups.push(turn);
194
+ if (wake == null && startsTurn(item)) return;
195
+ }
196
+ if (startsTurn(item) && !item.merged && item.role === "user") {
225
197
  // A second opening line of the drawn turn (a wake turn's report after
226
198
  // its note): one of its lines, as live drew it.
227
199
  turn.merged.push(i);
228
- return;
229
- }
230
- if (looseNote) {
231
- groups.push({ kind: "note", i });
232
- } else if (isShellCommandItem(item)) {
233
- // A `!cmd`'s record: its bubble alone, between the turns.
234
- groups.push({ kind: "command", i });
235
- turn = null;
236
- } else if (item?.role === "steer") {
237
- if (turn) turn.steers.push(i);
238
- else groups.push({ kind: "steer", i });
239
- } else if (item?.role === "user" && item.merged && turn) {
200
+ } else if (item.role === "steer") {
201
+ turn.steers.push(i);
202
+ } else if (item.role === "user" && item.merged) {
240
203
  turn.merged.push(i);
241
- } else if (startsTurn(item)) {
242
- turnIndex += 1;
243
- turn = { kind: "turn", turnIndex, turnId: item.turn_id, user: i, texts: [], steers: [], merged: [] };
244
- groups.push(turn);
245
- } else if (item?.role === "assistant") {
246
- if (turn) turn.texts.push(i);
247
- else groups.push({ kind: "answer", answer: i });
248
- } else if (item?.role === "empty_answer" && turn) {
204
+ } else if (item.role === "assistant") {
205
+ turn.texts.push(i);
206
+ } else if (item.role === "empty_answer") {
249
207
  turn.emptyAnswer = i;
250
208
  }
251
209
  });
252
- return groups.map((g) => {
253
- if (g.kind !== "turn") return g;
254
- if (g.drawn) return drawnGroup(g, items, timing, drawings[g.drawn]);
255
- const group = withSteers(turnGroup(g, items, timing), g.steers, items);
256
- // A turn that ended with no answer: its notice (the item's index) in
257
- // the answer's place.
258
- const ended = g.emptyAnswer == null ? group : { ...group, emptyAnswer: g.emptyAnswer };
259
- // Its opening's turn id (a prompt's, or a wake turn's note's): its
260
- // answer's key (data-answer-turn). A turn saved before turn ids keeps
261
- // its shape.
262
- const keyed = typeof g.turnId === "string" && g.turnId ? { ...ended, turnId: g.turnId } : ended;
263
- // A turn with no merged lines keeps its shape.
264
- return g.merged.length ? { ...keyed, merged: g.merged } : keyed;
265
- });
210
+ return groups.map((g) => (g.kind === "turn" ? drawnGroup(g, items, timing, drawings[g.drawn]) : g));
266
211
  }
267
212
 
268
213
  // A drawn turn's group: its record by the id its end names (`record_id`: a
269
- // drawing chi web made from the messages pairs one as promptRecord does, by
270
- // place for a turn saved before turn ids), else by its own id, its steps the
271
- // drawing's gens (the rows the working set and the footprint read, as live),
272
- // its answer the last text of a completed turn that had one, and its items
273
- // (the opening, merged lines, the empty answer) by index.
214
+ // drawing chi web made from the messages pairs one as Bridge::TurnRanges.records
215
+ // does, by place for a turn saved before turn ids), else by its own id, its
216
+ // steps the drawing's gens (the rows the working set and the footprint
217
+ // read, as live), its answer the last text of a completed turn that had
218
+ // one, and its items (the opening, merged lines, the empty answer) by index.
274
219
  function drawnGroup(g, items, timing, drawing) {
275
220
  const recordId = drawing?.end?.record_id ?? g.drawn;
276
221
  const record = (timing?.turnRecords || []).find((r) => r.id === recordId) || null;
@@ -284,126 +229,6 @@ function drawnGroup(g, items, timing, drawing) {
284
229
  return group;
285
230
  }
286
231
 
287
- // A turn's steers (a plugin's nudges) into its steps: each goes to the step
288
- // that answered it (`step`: the server counts the model messages since the
289
- // prompt, plus one). One whose step isn't there (the answer, which leaves
290
- // the block) stays on the group (`steers`): a bubble before the answer, as
291
- // live. A turn without steers keeps its shape.
292
- function withSteers(group, steerIndexes, items) {
293
- if (!steerIndexes.length) return group;
294
- const steps = group.steps.map((step) => ({ ...step, steers: [] }));
295
- const left = [];
296
- for (const i of steerIndexes) {
297
- const n = Number(items[i].step) || 1;
298
- const step = steps.find((s) => s.iteration === n);
299
- if (step) step.steers.push(i);
300
- else left.push(i);
301
- }
302
- return { ...group, steps, steers: left };
303
- }
304
-
305
- // A prompt's turn record: the one with its turn id (the engine saves it
306
- // on the prompt), so a turn whose prompt left the conversation (a failed
307
- // one's went back to the user, !rollback) shifts no other; a prompt saved
308
- // before turn ids pairs by its place among the prompts.
309
- function promptRecord(timing, g) {
310
- if (typeof g.turnId !== "string" || !g.turnId) return placedRecord(timing, g.turnIndex);
311
- return (timing?.turnRecords || []).find((r) => r.id === g.turnId) || null;
312
- }
313
-
314
- function turnGroup(g, items, timing) {
315
- const record = promptRecord(timing, g);
316
- const tools = record ? (timing?.toolRecords || []).filter((r) => r.turn_id === record.id) : [];
317
- // A turn with no answer has none of its texts as one: they are steps.
318
- const stepsOnly = canceledSteps(g, record, tools) || g.emptyAnswer != null;
319
- if (g.texts.some((i) => items[i].parts)) return partsTurn(g, items, record, tools, stepsOnly);
320
- const maxIteration = tools.reduce((m, r) => Math.max(m, Number(r.iteration) || 0), 0);
321
- const stepTexts = stepsOnly ? g.texts : g.texts.slice(0, -1);
322
- const steps = [];
323
- for (let k = 0; k < Math.max(stepTexts.length, maxIteration); k += 1) {
324
- const iteration = k + 1;
325
- steps.push({ i: stepTexts[k] ?? null, iteration, tools: recordRows(tools, iteration) });
326
- }
327
- const answer = g.texts.length && !stepsOnly ? g.texts[g.texts.length - 1] : null;
328
- return { kind: "turn", turnIndex: g.turnIndex, user: g.user, answer, record, steps };
329
- }
330
-
331
- // A canceled turn that ran more than one step or any call has no answer:
332
- // its partial text stays in the block, as it does live (turn_block.js
333
- // turnEnded promotes only a completed turn or a lone step with no tools). A
334
- // failed turn never answered: its texts are steps.
335
- function canceledSteps(g, record, tools) {
336
- if (record?.status === "failed") return true;
337
- return record?.status === "canceled" && (g.texts.length > 1 || tools.length > 0);
338
- }
339
-
340
- // A call's row from its tool record alone (no saved parts): the record's
341
- // called_as and via too, so "(called as bash)" and "(via call_tool)" show
342
- // after a reload, as live, and
343
- // its no_match ("no match" on a grep that found nothing) and System 1's
344
- // auto-allow (guardrail: {rule, p}).
345
- function recordRows(tools, iteration) {
346
- return tools.filter((r) => Number(r.iteration) === iteration).map((r) => ({
347
- key: `${iteration}:${r.call_index ?? 0}`, tool: r.tool, status: r.status, duration_ms: r.duration_ms,
348
- ...(r.called_as ? { called_as: r.called_as } : {}),
349
- ...(r.via ? { via: r.via } : {}),
350
- ...recordFlags(r),
351
- }));
352
- }
353
-
354
- function recordFlags(record) {
355
- return {
356
- ...(record?.no_match ? { no_match: true } : {}),
357
- ...(record?.guardrail ? { guardrail: record.guardrail } : {}),
358
- };
359
- }
360
-
361
- // A turn whose saved messages carry their parts (the server's ?parts=1):
362
- // every assistant message is one step. Its calls take the turn's records by
363
- // tool, in call order (each the next record of its tool, consumed with the
364
- // ones it skipped), not by iteration: an empty retry spends an iteration
365
- // that left no message (as the TUI's join, attached_loop.rb join_record).
366
- // The last message is the answer when it has text and made no call (and the
367
- // turn is no canceled multi-step one); its thinking stays behind as a step,
368
- // as it does live.
369
- function partsTurn(g, items, record, tools, stepsOnly = false) {
370
- const last = g.texts[g.texts.length - 1];
371
- const lastItem = items[last];
372
- const answer = !stepsOnly && String(lastItem.content ?? "") !== "" && !lastItem.parts?.tools?.length ? last : null;
373
- const pool = [...tools].sort((a, b) =>
374
- (Number(a.iteration) || 0) - (Number(b.iteration) || 0) || (Number(a.call_index) || 0) - (Number(b.call_index) || 0));
375
- const steps = g.texts.map((i, k) => {
376
- const iteration = k + 1;
377
- const parts = items[i].parts || {};
378
- const rows = Array.isArray(parts.tools)
379
- ? parts.tools.map((call, j) => {
380
- const r = takeRecord(pool, call.tool);
381
- return { key: `${iteration}:${j + 1}`, status: r?.status || "ok", duration_ms: r?.duration_ms, ...recordFlags(r), ...call };
382
- })
383
- : [];
384
- const thinking = String(parts.thinking || "");
385
- if (i === answer) return thinking ? { i: null, iteration, thinking, tools: [] } : null;
386
- return { i, iteration, thinking, tools: rows };
387
- }).filter(Boolean);
388
- // Records no saved message took (a generation that saved nothing): a
389
- // step per iteration of theirs, after the messages'.
390
- let iteration = g.texts.length;
391
- for (const n of [...new Set(pool.map((r) => Number(r.iteration) || 0))]) {
392
- iteration += 1;
393
- const rows = recordRows(pool, n).map((row) => ({ ...row, key: `${iteration}:${row.key.split(":")[1]}` }));
394
- steps.push({ i: null, iteration, thinking: "", tools: rows });
395
- }
396
- return { kind: "turn", turnIndex: g.turnIndex, user: g.user, answer, record, steps };
397
- }
398
-
399
- // The next record of +tool+ in +pool+ (call order), removed with the ones
400
- // before it; undefined when there is none (the pool stays as it was).
401
- function takeRecord(pool, tool) {
402
- const at = pool.findIndex((r) => String(r.tool) === String(tool));
403
- if (at < 0) return undefined;
404
- return pool.splice(0, at + 1)[at];
405
- }
406
-
407
232
  // Append +el+ to the history, above +timingEl+ while it is a running turn's
408
233
  // live timing line, so that line stays under the turn's activity, thinking
409
234
  // and answer.
@@ -38,8 +38,8 @@ import { thumbsTemplate } from "./images.js";
38
38
  import { shouldFollowScroll } from "./scroll.js";
39
39
  import { emptyRetryLine, hookNoticeLabel, llmContextNotice, reminderText, steerCutLine } from "./turn_events.js";
40
40
  import {
41
- answerBubbleTemplate, cancelLineTemplate, commandBubbleTemplate, elementOf, emptyAnswerTemplate, noteBubbleTemplate, shellCommandMessage,
42
- steerRowTemplate, toolRowInnerTemplate, toolRowTemplate, userBubbleTemplate,
41
+ answerBubbleTemplate, commandBubbleTemplate, elementOf, emptyAnswerTemplate, noteBubbleTemplate, shellCommandMessage,
42
+ steerRowTemplate, toolRowInnerTemplate, userBubbleTemplate,
43
43
  } from "./turn_html.js";
44
44
  import { cancelLineText, formatDuration, turnGroups, turnTimingText } from "./timing.js";
45
45
  import { createSentenceFeed } from "./sentences.js";
@@ -189,14 +189,6 @@ export function outlineBlock(blockEl, gens) {
189
189
  return true;
190
190
  }
191
191
 
192
- // Reloaded tool rows (turn_html.js toolRowTemplate) as nodes, each row's
193
- // plugin refs bound to its title (refs.js bindRowRefs).
194
- function rowNodes(rows, thumbs) {
195
- const nodes = nodesOf(rows.map((r) => toolRowTemplate(r, { thumbs })));
196
- [...nodes.children].forEach((el, i) => bindRowRefs(el, rows[i]));
197
- return nodes;
198
- }
199
-
200
192
  // ---- The live block ----
201
193
 
202
194
  // The container seams (the stage composes the block, stage_view.js):
@@ -813,17 +805,6 @@ export function stepText(block, iteration) {
813
805
  return text?.getAttribute("data-copy-source") ?? text?.textContent ?? "";
814
806
  }
815
807
 
816
- // A re-rendered failed turn's line (a .bubble.cancel, as live's
817
- // addEndBubble), in turn_failed's words (failedTurnText) from what the turn
818
- // record kept of it (SessionMetrics' failure: summary, message,
819
- // error_class, kept_steps); nothing for any other record, or a failed one
820
- // saved before records kept that.
821
- function failedLineTemplate(record) {
822
- const failure = record?.status === "failed" ? record.failure : null;
823
- if (!failure || typeof failure !== "object") return nothing;
824
- return html`<div class="bubble cancel">${failedTurnText(failure)}</div>`;
825
- }
826
-
827
808
  // ---- A drawn turn ----
828
809
 
829
810
  // A drawn turn's card: the snapshot's card of its id when the page has it
@@ -962,22 +943,24 @@ function pairStepTexts(els, group, items) {
962
943
  }
963
944
  }
964
945
 
965
- // A reloaded history as turn blocks (renderHistory's object path), as
966
- // nodes: per turn the prompt, a collapsed block of its steps when it had
967
- // any (stepTemplate, the live page's: texts, and with the server's parts
968
- // the thinking, params and output, from the saved messages; status and
969
- // duration from the timing's tool records), then the answer and the turn's
970
- // timing line under it.
946
+ // A reloaded history as nodes: each finished turn drawn from its drawing
947
+ // (+drawings+, chi web's turn_drawings: a turn stamped with a drawn id,
948
+ // drawnTurnNodes), its pieces marked data-drawn, then its timing line;
949
+ // notes and `!cmd` records between them. chi web draws every finished
950
+ // turn, so an unstamped turn item is the running turn's (+runningTurnId+:
951
+ // its prompt, before its line is written) or a miss (a bug, a cover that
952
+ // failed): a plain row of its text (its prompt or answer bubble, no
953
+ // steps), marked data-undrawn (the reload check counts them) and logged
954
+ // once per render (console.warn), never a throw.
971
955
  // +thumbs(images)+ draws a prompt's or a tool row's image thumbs (a
972
956
  // template, images.js thumbsTemplate). +workingSet+ (the stage's
973
957
  // web.working_set): each block stamped with its
974
958
  // turn's ordinal and its rows with theirs (working_set_view.js), and the
975
959
  // turn's footprint on its summary line.
976
- // +drawings+ (chi web's turn_drawings): a turn stamped with a drawn id is
977
- // drawn from its drawing (drawnTurnNodes), its pieces marked data-drawn;
978
960
  // +cards+ the snapshot's cards (a drawn card's body), +capabilities+ the
979
961
  // page's (a notice shown elsewhere).
980
- export function turnHistoryNodes(items, timing, { thumbs, workingSet = false, now = Date.now(), drawings = null, cards = null, capabilities = {} }) {
962
+ export function turnHistoryNodes(items, timing, { thumbs, workingSet = false, now = Date.now(), drawings = null, cards = null, capabilities = {},
963
+ runningTurnId = null }) {
981
964
  const timingTemplate = (group) => {
982
965
  const record = group.record;
983
966
  // Numbered by its place in the turn records, as live (a failed turn
@@ -992,9 +975,6 @@ export function turnHistoryNodes(items, timing, { thumbs, workingSet = false, no
992
975
  // turn's (data-answer-turn: a turn's answer only, not a report reply);
993
976
  // +replyKey+, a report reply's (data-reply-key).
994
977
  const answerBubble = (at, cls = "", turnId = null, replyKey = null) => answerBubbleTemplate(items[at], { cls, at, turnId, replyKey });
995
- // The timing line after the bubble, not in it: where the live view
996
- // leaves it at the turn's end.
997
- const answerTemplate = (at, timing, turnId = null) => html`${answerBubble(at, "", turnId)}${timing}`;
998
978
  // A user's line, labelled when chi brought it in (a delegate report). A
999
979
  // `!cmd`'s saved message (the worker's "!(<command>)\n<output>") renders
1000
980
  // as its command bubble, as live does — not as a user bubble.
@@ -1023,8 +1003,6 @@ export function turnHistoryNodes(items, timing, { thumbs, workingSet = false, no
1023
1003
  const drawn = drawnTurnNodes(group, items, { thumbs, capabilities, cards });
1024
1004
  if (drawn.block) {
1025
1005
  if (workingSet) drawn.block.querySelector(":scope > summary > .tw-sum")?.prepend(nodesOf(footprintTemplate(groupItems(group, ordinal), ordinal)));
1026
- outlines.push(null);
1027
- blockEnds.push(null);
1028
1006
  blockTurns.push(ordinal);
1029
1007
  }
1030
1008
  const lineKey = (i) => (items[i]?.source === "delegate_report" ? `${group.turnId}:input:${i - (group.user ?? i)}` : null);
@@ -1048,107 +1026,47 @@ export function turnHistoryNodes(items, timing, { thumbs, workingSet = false, no
1048
1026
  });
1049
1027
  };
1050
1028
  const parts = [];
1051
- // Each block's steps, in order: its outline once the nodes exist; how its
1052
- // turn ended (whether it stays open); and its turn's place among the turns
1053
- // (the working set's stamp).
1054
- const outlines = [];
1055
- const blockEnds = [];
1029
+ // Each drawn block's turn's place among the turns (the working set's stamp).
1056
1030
  const blockTurns = [];
1057
1031
  let turnOrdinal = -1;
1058
- const groups = turnGroups(items, timing, { drawings });
1032
+ // An unstamped item's row: its prompt (or a wake's note), its answer,
1033
+ // a steer's bubble, an empty answer's notice; nothing for a text-less
1034
+ // step.
1035
+ const plainTemplate = (i) => {
1036
+ const item = items[i];
1037
+ if (item?.role === "note") return noteBubbleTemplate(item);
1038
+ if (item?.role === "user") return userTemplate(item, item.merged ? { state: "steered", step: item.step } : {});
1039
+ if (item?.role === "steer") return steerTemplate(i, true);
1040
+ if (item?.role === "empty_answer") return emptyAnswerTemplate(item);
1041
+ if (item?.role === "assistant" && String(item.content ?? "").trim()) return answerBubble(i);
1042
+ return nothing;
1043
+ };
1044
+ let misses = 0;
1045
+ const groups = turnGroups(items, timing, { drawings, runningTurnId });
1059
1046
  // A quiet stretch before a group: its divider first (time_gaps.js).
1060
1047
  const gaps = groupGaps(groups, items, now);
1061
1048
  for (const [k, group] of groups.entries()) {
1062
1049
  if (gaps[k]) parts.push(timeGapTemplate(gaps[k]));
1063
1050
  if (group.kind === "note") { parts.push(noteBubbleTemplate(items[group.i])); continue; }
1064
- if (group.kind === "steer") { parts.push(steerTemplate(group.i, true)); continue; }
1065
- if (group.kind === "answer") { parts.push(answerTemplate(group.answer, nothing)); continue; }
1066
1051
  // A `!cmd`'s record: its command bubble, no steps, no timing.
1067
1052
  if (group.kind === "command") { parts.push(userTemplate(items[group.i])); continue; }
1068
- turnOrdinal += 1;
1069
- if (group.drawn) {
1070
- parts.push(drawnGroupPieces(group, turnOrdinal));
1053
+ if (group.kind === "plain") {
1054
+ const piece = plainTemplate(group.i);
1055
+ if (piece === nothing) continue;
1056
+ if (group.running) { parts.push(piece); continue; }
1057
+ misses += 1;
1058
+ const els = [...nodesOf(piece).children];
1059
+ els.forEach((el) => { el.dataset.undrawn = "1"; });
1060
+ parts.push(els);
1071
1061
  continue;
1072
1062
  }
1073
- const prompt = items[group.user];
1074
- // A context wake turn starts with its note.
1075
- const promptPiece = prompt.role === "note" ? noteBubbleTemplate(prompt) : userTemplate(prompt);
1076
- const [only] = group.steps;
1077
- const ended = group.answer !== null || group.emptyAnswer != null;
1078
- const textless = only && (only.i === null || !String(items[only.i].content ?? ""));
1079
- // A lone thinking step before an answer (or the notice of a turn with
1080
- // none): no block, the plain answer's collapsed thinking block.
1081
- const plainThinking = group.steps.length === 1 && ended && textless && !only.tools.length && only.thinking;
1082
- const noBlock = !group.steps.length || plainThinking;
1083
- let block = null;
1084
- if (plainThinking) {
1085
- block = thinkingTemplate({ body: only.thinking, cls: "bubble thinking" });
1086
- } else if (group.steps.length) {
1087
- // A step's text with its message's rendered markdown (html: web.markdown on).
1088
- const gens = group.steps.map((step) => ({
1089
- text: step.i === null ? "" : String(items[step.i].content ?? ""),
1090
- html: step.i === null ? null : items[step.i].html ?? null,
1091
- thinking: step.thinking || "", tools: step.tools,
1092
- }));
1093
- const steps = gens.map((gen, k) => stepTemplate(gen, {
1094
- // The steers the step answered first, where the live rows went.
1095
- steers: (group.steps[k].steers || []).map((i) => steerTemplate(i, false)),
1096
- items: gen.tools.length ? [rowNodes(gen.tools, thumbs)] : [],
1097
- // Its text knows its message's refs (a question's), as an answer does.
1098
- at: group.steps[k].i,
1099
- }));
1100
- // Its summary line: the working set's footprint, when the turn touched
1101
- // something, then the steps (the live block's, stage_view.js handOff).
1102
- const foot = workingSet ? footprintTemplate(groupItems(group, turnOrdinal), turnOrdinal) : nothing;
1103
- block = html`<details class="turn-work done"><summary><span class="tw-sum">${foot}<span class="turn-steps">${model.blockSummary({ gens, ended: true })}</span></span></summary>${steps}</details>`;
1104
- outlines.push(gens);
1105
- // No record: a turn saved before them, or running at the reload.
1106
- blockEnds.push(group.record?.status ?? "completed");
1107
- blockTurns.push(turnOrdinal);
1108
- }
1109
- // Steers with no step to sit in, or in a turn that shows no block: on
1110
- // their own after the prompt.
1111
- const loose = noBlock ? [...group.steps.flatMap((step) => step.steers || []), ...(group.steers || [])] : group.steers || [];
1112
- // The user's lines merged into the turn: the live "steered" bubbles,
1113
- // after its steps and before its answer. A delegate report's is
1114
- // followed by the text that answered it when that isn't the answer: a
1115
- // small model tells its user about a report before its next tool call,
1116
- // and that step's text would stay folded in the block.
1117
- // A report's fold key (answer_fold.js), as its reply's: the turn's id
1118
- // and its place after the opening; none in a turn saved before turn ids.
1119
- const lineKey = (i) => (group.turnId && items[i]?.source === "delegate_report" ? `${group.turnId}:input:${i - group.user}` : null);
1120
- const merged = (group.merged || []).map((i) =>
1121
- html`${userTemplate(items[i], { state: "steered", step: items[i].step, lineKey: lineKey(i) })}${reportReplyTemplate(i, group)}`);
1122
- // A participant's review turn with a reply: Apply under it (the owner's
1123
- // page only: the participant page has its own view). Not under a pair
1124
- // turn: it acted itself.
1125
- const reviewer = group.answer !== null && prompt.turn_id && prompt.participant_mode !== PAIR
1126
- ? authorBadge(prompt.author, prompt.author_name) : null;
1127
- // The live hand-off's order (turn_pieces.js): a turn that ended with no
1128
- // answer has chi's muted notice where the answer would be, before the
1129
- // timing; a turn with no answer (canceled, or running: no record yet)
1130
- // its timing after its prompt and steps. A canceled turn ends with its
1131
- // cancel line, a failed one whose steps stayed with its failure line, as
1132
- // the live view left them.
1133
- parts.push(turnPieces({
1134
- prompt: promptPiece,
1135
- block,
1136
- steers: loose.map((i) => steerTemplate(i, true)),
1137
- merged,
1138
- answer: group.emptyAnswer == null && group.answer !== null ? [answerBubble(group.answer, "", group.turnId)] : [],
1139
- emptyNote: group.emptyAnswer != null ? emptyAnswerTemplate(items[group.emptyAnswer]) : null,
1140
- timing: timingTemplate(group),
1141
- apply: reviewer ? applyRowTemplate(prompt.turn_id, reviewer) : null,
1142
- end: html`${cancelLineTemplate(group.record)}${failedLineTemplate(group.record)}`,
1143
- }));
1063
+ turnOrdinal += 1;
1064
+ parts.push(drawnGroupPieces(group, turnOrdinal));
1144
1065
  }
1145
1066
  const out = nodesOf(parts);
1146
- // A finished turn's block as the live end leaves it: its outline, closed
1147
- // unless the turn was cut short.
1148
- const blocks = [...out.children].filter((el) => el.matches(".turn-work"));
1067
+ if (misses) console.warn(`chi: ${misses} history item(s) came without their turn's drawing; drawn as plain rows`);
1149
1068
  // A drawn block is outlined and opened as its live end left it.
1150
- blocks.forEach((block, i) => { if (outlines[i] !== null) block.open = openAfterEnd(blockEnds[i], outlineBlock(block, outlines[i] || [])); });
1151
- if (workingSet) stampHistory(blocks, blockTurns);
1069
+ if (workingSet) stampHistory([...out.children].filter((el) => el.matches(".turn-work")), blockTurns);
1152
1070
  // Each answer bubble and step text knows its message's refs
1153
1071
  // (answer_refs.js; the page pairs them after the render), the index
1154
1072
  // stays out of the DOM.
@@ -141,8 +141,9 @@ function tailClip(text) {
141
141
  // an execute/task_wait's last ones (inlineOutput), the rest on hover; a read
142
142
  // of the file as-is also its numbered lines, closed: read_view.js), its images (+thumbs+(images) draws them) and an
143
143
  // edit's collapsed diff, and a reloaded row's ✂ mark above its output. A
144
- // part with nothing to say is left out. A reload renders toolRowTemplate;
145
- // the live view renders toolRowInnerTemplate into its own row element
144
+ // part with nothing to say is left out. toolRowTemplate is the row in its
145
+ // element (the specs' harness); the live view, a drawn turn's too, renders
146
+ // toolRowInnerTemplate into its own row element
146
147
  // (turn_block.js), again on each event: lit writes only what changed, so a
147
148
  // part the user toggled (the raw command, the diff, the read lines) stays.
148
149
  // +stop+: the live row's stop-task button (a node), after the title.
@@ -2,7 +2,8 @@
2
2
  // one step at a time. On top a swimlane, one column per actor and one row per
3
3
  // step (the current, the seen and a case's target marked; a click jumps); under
4
4
  // it the step's card (the actor, what it does, "You see", the dashed "Behind
5
- // it"); a fork asks "Which case?" instead of Next; Back, Next and the path
5
+ // it"); a fork asks "Which case?" instead of Next (beside it when every case
6
+ // loops back); Back, Next and the path
6
7
  // taken, and the arrow keys while the widget has the focus. Ported from eval
7
8
  // 0013's viewer.
8
9
  //
@@ -30,6 +31,10 @@ const isAlways = (when) => ALWAYS.test(String(when ?? "").trim());
30
31
  // step), or null when k is no fork. A case that is no condition reads as
31
32
  // the usual path, and a step that names a next as well offers it first when
32
33
  // no case goes there (round 1's next + branches).
34
+ // - hasNext(k): whether Next shows at k: no fork, or a fork none of whose
35
+ // cases moves on (each loops back, a retry from an earlier step or its own,
36
+ // or names no step). Its unwritten usual path is then nextOf(k): the step
37
+ // below, or Start over at the end; without it the walk would be stuck there.
33
38
  export function walkRoutes(walk) {
34
39
  const steps = walk?.steps || [];
35
40
  const byId = new Map(steps.map((s, k) => [String(s.id), k]));
@@ -55,7 +60,12 @@ export function walkRoutes(walk) {
55
60
  return cases;
56
61
  }
57
62
 
58
- return { steps, nextOf, casesOf };
63
+ function hasNext(k) {
64
+ const cases = casesOf(k);
65
+ return !cases || !cases.some((c) => c.to != null && c.to > k);
66
+ }
67
+
68
+ return { steps, nextOf, casesOf, hasNext };
59
69
  }
60
70
 
61
71
  // The swimlane's cells: one per step, in its actor's column (1-based, after
@@ -121,7 +131,7 @@ function button(doc, className, text) {
121
131
  // The walk as an element, for a widget host's shadow root.
122
132
  export function drawWalk(walk, doc = document) {
123
133
  const routes = walkRoutes(walk);
124
- const { steps, nextOf, casesOf } = routes;
134
+ const { steps, nextOf, casesOf, hasNext } = routes;
125
135
  const actors = (walk.actors || []).map(String);
126
136
  const walker = createWalker(routes);
127
137
 
@@ -221,7 +231,7 @@ export function drawWalk(walk, doc = document) {
221
231
  });
222
232
  count.textContent = `step ${k + 1} of ${steps.length}`;
223
233
  prev.disabled = walker.path.length < 2;
224
- next.hidden = !!cases;
234
+ next.hidden = !hasNext(k);
225
235
  next.textContent = nextOf(k) == null ? "Start over" : "Next →";
226
236
  trail.textContent = trailText(walker.path);
227
237
  if (hadFocus && (!focused.isConnected || focused.hidden || focused.disabled)) box.focus({ preventScroll: true });
@@ -51,8 +51,8 @@ module Samagotchi
51
51
 
52
52
  private
53
53
 
54
- # {turn_id, same, kinds, excused, explained, drawn} from the page: 204,
55
- # whatever it said
54
+ # {turn_id, same, kinds, excused, explained, drawn, undrawn} from the
55
+ # page: 204, whatever it said
56
56
  # (fire-and-forget); 400 for a body that isn't a JSON object.
57
57
  # worker_version is chi web's own view of the session's worker (its
58
58
  # sidecar), never the body's.
@@ -66,7 +66,10 @@ module Samagotchi
66
66
 
67
67
  same = body["same"] == true
68
68
  drawn = body["drawn"] == true
69
- fields = { sid: id, turn_id: turn_id, same: same, drawn: drawn, worker_version: checked_worker_version(id) }
69
+ # The reload's rows with no drawing (the page's plain fallback): a
70
+ # count chi web should keep at 0.
71
+ undrawn = body["undrawn"].is_a?(Integer) ? body["undrawn"].clamp(0, 10_000) : 0
72
+ fields = { sid: id, turn_id: turn_id, same: same, drawn: drawn, undrawn: undrawn, worker_version: checked_worker_version(id) }
70
73
  Log.info(:web, "reload_checked", **fields)
71
74
  unless same
72
75
  Log.info(:web, "reload_mismatch", **fields.except(:same), kinds: checked_tokens(body["kinds"], KINDS),