samagotchi 0.161.0 → 0.163.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 (39) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +41 -1
  3. data/docs/architecture.md +2 -2
  4. data/docs/cli.md +1 -1
  5. data/docs/configuration.md +1 -1
  6. data/docs/internals/block-renderers.md +3 -2
  7. data/docs/internals/bridge.md +85 -22
  8. data/docs/internals/inline-widgets.md +6 -3
  9. data/docs/internals/web-frontend.md +1 -1
  10. data/docs/memory.md +8 -2
  11. data/docs/sessions.md +1 -1
  12. data/docs/testing.md +13 -1
  13. data/lib/samagotchi/bridge/card_store.rb +23 -13
  14. data/lib/samagotchi/bridge/turn_accumulator.rb +7 -1
  15. data/lib/samagotchi/bridge/turn_drawings/synth.rb +559 -0
  16. data/lib/samagotchi/bridge/turn_drawings.rb +118 -7
  17. data/lib/samagotchi/bridge/turn_ranges.rb +175 -0
  18. data/lib/samagotchi/bridge.rb +35 -12
  19. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  20. data/lib/samagotchi/plugin/sessions.rb +8 -1
  21. data/lib/samagotchi/project_command.rb +74 -6
  22. data/lib/samagotchi/project_id_clash.rb +1 -1
  23. data/lib/samagotchi/project_subfolders.rb +188 -0
  24. data/lib/samagotchi/terminal_ui/join_replay.rb +36 -130
  25. data/lib/samagotchi/terminal_ui.rb +12 -1
  26. data/lib/samagotchi/version.rb +1 -1
  27. data/lib/samagotchi/web/message_display.rb +58 -37
  28. data/lib/samagotchi/web/public/app.js +8 -7
  29. data/lib/samagotchi/web/public/block_frame.js +5 -1
  30. data/lib/samagotchi/web/public/data.js +4 -6
  31. data/lib/samagotchi/web/public/reload_check.js +7 -4
  32. data/lib/samagotchi/web/public/time_gaps.js +1 -2
  33. data/lib/samagotchi/web/public/timing.js +52 -216
  34. data/lib/samagotchi/web/public/turn_block.js +46 -124
  35. data/lib/samagotchi/web/public/turn_html.js +3 -2
  36. data/lib/samagotchi/web/public/widget_walk.js +4 -2
  37. data/lib/samagotchi/web/reload_check_route.rb +6 -3
  38. data/lib/samagotchi/web/session_show.rb +23 -28
  39. metadata +4 -1
@@ -156,7 +156,11 @@ export function createBlockFrame({ files, fetchFile, doc = document, win = windo
156
156
  doc.body.append(iframe);
157
157
 
158
158
  async function load() {
159
- const texts = await Promise.all(files.map((file) => fetchFile(file)));
159
+ // Bounded too: browser fetch has no timeout, and a drop() meanwhile ends it.
160
+ const fetching = answer("fetch", true);
161
+ const texts = await Promise.race([Promise.all(files.map((file) => fetchFile(file))), fetching]);
162
+ settle((w) => w.resolve());
163
+ if (dead) throw new FrameError("the frame is gone", { dropped: true });
160
164
  const handshake = answer("load", true);
161
165
  loaded.then(() => {
162
166
  // Stop waiting on the handshake's own timer and start the code's.
@@ -129,12 +129,10 @@ export function uploadImage(id, file, name, opts = {}) {
129
129
  // opts.recent its timing holds the newest turn's records and turn_count
130
130
  // (mergeTiming), and opts.turnId asks for that turn's answer.
131
131
  // opts.timing: the whole timing alone (when the merge came up short).
132
- // opts.parts: each saved message with what it did (thinking, tool calls
133
- // and their output), for the turn block's reload; with it, drawings=1: a
134
- // finished turn with a drawing comes as its turn_drawings, its items
135
- // stamped (drawn) without their parts (turn_drawing.js).
136
- export function getSession(id, { tail, recent, turnId, timing, parts, cards, ...opts } = {}) {
137
- let query = cards ? "?cards=1" : tail ? "?tail=1" : timing ? "?timing=1" : parts ? "?parts=1&drawings=1" : "";
132
+ // The full read (none of those): every finished turn as its
133
+ // turn_drawings, its items stamped (drawn: turn_drawing.js).
134
+ export function getSession(id, { tail, recent, turnId, timing, cards, ...opts } = {}) {
135
+ let query = cards ? "?cards=1" : tail ? "?tail=1" : timing ? "?timing=1" : "";
138
136
  if (tail && recent) query += "&recent=1";
139
137
  if (tail && turnId) query += `&turn_id=${encodeURIComponent(turnId)}`;
140
138
  return api(`/api/sessions/${id}${query}`, opts);
@@ -7,8 +7,10 @@
7
7
  // entries that would explain the differences (`explained`: all of them
8
8
  // have one), so chi web's log counts each class apart (the bugs turn
9
9
  // drawings close, the deliberate ones). It posts the counts, never
10
- // content: {turn_id, same, kinds, excused, explained, drawn}; chi web logs
11
- // them (reload_checked, reload_mismatch). Fire-and-forget: no toast, no
10
+ // content: {turn_id, same, kinds, excused, explained, drawn, undrawn}; chi
11
+ // web logs them (reload_checked, reload_mismatch). `undrawn`: how many rows
12
+ // of the reload came without their turn's drawing (turn_block.js's plain
13
+ // fallback, data-undrawn): 0 unless chi web missed one. Fire-and-forget: no toast, no
12
14
  // store write, a failure is dropped.
13
15
  //
14
16
  // Cards are left out on both sides: a reload places them after the render
@@ -34,7 +36,7 @@ function withoutCards(shape) {
34
36
  // @param sessionId () => the open session's id
35
37
  // @param running () => whether a turn runs now (liveTurn.running: a queued
36
38
  // turn started streaming)
37
- // @param read (id) => the session as a reload reads it (GET ?parts=1)
39
+ // @param read (id) => the session as a reload reads it (the full GET)
38
40
  // @param render (data) => that read drawn as a reload draws it (a fragment)
39
41
  // @param post (id, body) => the counts to chi web
40
42
  export function createReloadCheck({ enabled, sessionId, running, read, render, post }) {
@@ -62,7 +64,8 @@ export function createReloadCheck({ enabled, sessionId, running, read, render, p
62
64
  : { same: false, kinds: ["prompt"], excused: [], explained: false };
63
65
  // Whether the read had a drawing for the turn (turn drawings, P2).
64
66
  const drawn = !!data?.turn_drawings?.[turnId];
65
- await post(id, { turn_id: turnId, same, kinds, excused, explained, drawn });
67
+ const undrawn = holder.querySelectorAll("[data-undrawn]").length;
68
+ await post(id, { turn_id: turnId, same, kinds, excused, explained, drawn, undrawn });
66
69
  } catch (_) {
67
70
  // Fire-and-forget: a failed read or post is no finding.
68
71
  }
@@ -28,8 +28,7 @@ export function timeGapEl(text) {
28
28
 
29
29
  // The history items a group (timing.js turnGroups) holds, by index.
30
30
  function groupIndexes(group) {
31
- if (group.kind === "note" || group.kind === "steer" || group.kind === "command") return [group.i];
32
- if (group.kind === "answer") return [group.answer];
31
+ if (group.kind === "note" || group.kind === "plain" || group.kind === "command") return [group.i];
33
32
  const steps = group.steps || [];
34
33
  return [
35
34
  group.user, ...steps.map((step) => step.i), ...steps.flatMap((step) => step.steers || []),
@@ -145,124 +145,80 @@ function replaceById(records, record) {
145
145
  return true;
146
146
  }
147
147
 
148
- export function turnRecordAt(timing, index) {
149
- const records = timing?.turnRecords;
150
- return Array.isArray(records) ? records[index] || null : null;
151
- }
152
-
153
148
  // A history item that starts a turn: a prompt, or the note a context wake
154
149
  // turn starts with (turn_start). A `!cmd`'s record (shell_command.js) is a
155
150
  // user message but no prompt: no turn, no record, no timing.
156
151
  const startsTurn = (item) =>
157
152
  (item?.role === "user" && !isShellCommandItem(item)) || (item?.role === "note" && item.turn_start === true);
158
153
 
159
- // For each history item, the turn index its timing shows under, or null. A
160
- // turn with tool calls holds several assistant messages; only the last one
161
- // before the next user message carries the turn's timing. A turn with none
162
- // (canceled before an answer, or still running: no record yet) has it on
163
- // its user message.
164
- export function timedTurnIndexes(items) {
165
- const result = items.map(() => null);
166
- let turnIndex = -1;
167
- let carrier = null;
168
- items.forEach((item, i) => {
169
- if (startsTurn(item)) {
170
- if (carrier !== null) result[carrier] = turnIndex;
171
- turnIndex += 1;
172
- carrier = i;
173
- } else if (item?.role === "assistant") {
174
- carrier = i;
175
- }
176
- });
177
- if (carrier !== null) result[carrier] = turnIndex;
178
- return result;
179
- }
180
-
181
- // The history as turns, for the turn block's reload: notes on their own, and
182
- // per prompt a turn with its record, its steps (one per iteration: the
183
- // turn's tool records grouped by iteration, and the assistant messages but
184
- // the last, in order; a text-less iteration leaves no message, so a text
185
- // can sit one step early: inspection, not truth) and its answer (the last
186
- // assistant message). Assistant messages before any prompt are answers on
187
- // their own. A turn that ended with no answer (the server's empty_answer
188
- // item) has no answer: its texts are steps, and `emptyAnswer` is that
189
- // item's index. A `!cmd`'s record is a group of its own (`command`, its
190
- // index): no steps, no record, no turn index. The turn index counts
191
- // prompts, as timedTurnIndexes does. The
192
- // user's lines merged into the running turn (`merged`, the server's
193
- // Steer::INPUT_KIND) stay in it: the turn's `merged` list.
194
- // +drawings+ (chi web's turn_drawings, {turn_id: {events, end}}): the items
195
- // stamped with a drawn turn's id (`drawn`) are that turn's group (`drawn`,
196
- // its `drawing`), whether or not they start with an opening (a reminder
197
- // turn has none; a wake's note, outside the range, opens it by its id); its
198
- // steps are the drawing's (turn_drawing.js), and an unstamped item after it
199
- // starts no part of it.
200
- 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 } = {}) {
201
168
  const groups = [];
202
169
  let turnIndex = -1;
203
170
  let turn = null;
171
+ let running = false;
204
172
  items.forEach((item, i) => {
205
173
  const drawn = drawings && typeof item?.drawn === "string" && drawings[item.drawn] ? item.drawn : null;
206
- const looseNote = item?.role === "note" && !startsTurn(item);
207
- if (turn?.drawn && !drawn && !looseNote) turn = null;
208
- // An opening just before the range with the drawn turn's id (a wake's
209
- // note, added before the turn began): the drawn turn's own.
210
- if (drawn && turn && !turn.drawn && turn.turnId === drawn && turn.texts.length === 0) turn.drawn = drawn;
211
- 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;
212
190
  turnIndex += 1;
213
- turn = { kind: "turn", turnIndex, turnId: drawn, drawn, user: startsTurn(item) ? i : null, texts: [], steers: [], merged: [] };
214
- groups.push(turn);
215
- if (startsTurn(item)) return;
216
- } 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") {
217
197
  // A second opening line of the drawn turn (a wake turn's report after
218
198
  // its note): one of its lines, as live drew it.
219
199
  turn.merged.push(i);
220
- return;
221
- }
222
- if (looseNote) {
223
- groups.push({ kind: "note", i });
224
- } else if (isShellCommandItem(item)) {
225
- // A `!cmd`'s record: its bubble alone, between the turns.
226
- groups.push({ kind: "command", i });
227
- turn = null;
228
- } else if (item?.role === "steer") {
229
- if (turn) turn.steers.push(i);
230
- else groups.push({ kind: "steer", i });
231
- } 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) {
232
203
  turn.merged.push(i);
233
- } else if (startsTurn(item)) {
234
- turnIndex += 1;
235
- turn = { kind: "turn", turnIndex, turnId: item.turn_id, user: i, texts: [], steers: [], merged: [] };
236
- groups.push(turn);
237
- } else if (item?.role === "assistant") {
238
- if (turn) turn.texts.push(i);
239
- else groups.push({ kind: "answer", answer: i });
240
- } 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") {
241
207
  turn.emptyAnswer = i;
242
208
  }
243
209
  });
244
- return groups.map((g) => {
245
- if (g.kind !== "turn") return g;
246
- if (g.drawn) return drawnGroup(g, items, timing, drawings[g.drawn]);
247
- const group = withSteers(turnGroup(g, items, timing), g.steers, items);
248
- // A turn that ended with no answer: its notice (the item's index) in
249
- // the answer's place.
250
- const ended = g.emptyAnswer == null ? group : { ...group, emptyAnswer: g.emptyAnswer };
251
- // Its opening's turn id (a prompt's, or a wake turn's note's): its
252
- // answer's key (data-answer-turn). A turn saved before turn ids keeps
253
- // its shape.
254
- const keyed = typeof g.turnId === "string" && g.turnId ? { ...ended, turnId: g.turnId } : ended;
255
- // A turn with no merged lines keeps its shape.
256
- return g.merged.length ? { ...keyed, merged: g.merged } : keyed;
257
- });
210
+ return groups.map((g) => (g.kind === "turn" ? drawnGroup(g, items, timing, drawings[g.drawn]) : g));
258
211
  }
259
212
 
260
- // A drawn turn's group: its record by id, its steps the drawing's gens
261
- // (the rows the working set and the footprint read, as live), its answer
262
- // the last text of a completed turn that had one, and its items (the
263
- // opening, merged lines, the empty answer) by index.
213
+ // A drawn turn's group: its record by the id its end names (`record_id`: a
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.
264
219
  function drawnGroup(g, items, timing, drawing) {
265
- const record = (timing?.turnRecords || []).find((r) => r.id === g.drawn) || null;
220
+ const recordId = drawing?.end?.record_id ?? g.drawn;
221
+ const record = (timing?.turnRecords || []).find((r) => r.id === recordId) || null;
266
222
  const steps = drawingTurn(drawing).gens.map((gen, k) => ({ i: null, iteration: k + 1, thinking: gen.thinking, tools: gen.tools }));
267
223
  const last = g.texts[g.texts.length - 1];
268
224
  const answered = drawnKind(drawing.end) === "completed" && g.emptyAnswer == null && last != null && String(items[last]?.content ?? "") !== "";
@@ -273,126 +229,6 @@ function drawnGroup(g, items, timing, drawing) {
273
229
  return group;
274
230
  }
275
231
 
276
- // A turn's steers (a plugin's nudges) into its steps: each goes to the step
277
- // that answered it (`step`: the server counts the model messages since the
278
- // prompt, plus one). One whose step isn't there (the answer, which leaves
279
- // the block) stays on the group (`steers`): a bubble before the answer, as
280
- // live. A turn without steers keeps its shape.
281
- function withSteers(group, steerIndexes, items) {
282
- if (!steerIndexes.length) return group;
283
- const steps = group.steps.map((step) => ({ ...step, steers: [] }));
284
- const left = [];
285
- for (const i of steerIndexes) {
286
- const n = Number(items[i].step) || 1;
287
- const step = steps.find((s) => s.iteration === n);
288
- if (step) step.steers.push(i);
289
- else left.push(i);
290
- }
291
- return { ...group, steps, steers: left };
292
- }
293
-
294
- // A prompt's turn record: the one with its turn id (the engine saves it
295
- // on the prompt), so a turn whose prompt left the conversation (a failed
296
- // one's went back to the user, !rollback) shifts no other; a prompt saved
297
- // before turn ids pairs by its place among the prompts.
298
- function promptRecord(timing, g) {
299
- if (typeof g.turnId !== "string" || !g.turnId) return turnRecordAt(timing, g.turnIndex);
300
- return (timing?.turnRecords || []).find((r) => r.id === g.turnId) || null;
301
- }
302
-
303
- function turnGroup(g, items, timing) {
304
- const record = promptRecord(timing, g);
305
- const tools = record ? (timing?.toolRecords || []).filter((r) => r.turn_id === record.id) : [];
306
- // A turn with no answer has none of its texts as one: they are steps.
307
- const stepsOnly = canceledSteps(g, record, tools) || g.emptyAnswer != null;
308
- if (g.texts.some((i) => items[i].parts)) return partsTurn(g, items, record, tools, stepsOnly);
309
- const maxIteration = tools.reduce((m, r) => Math.max(m, Number(r.iteration) || 0), 0);
310
- const stepTexts = stepsOnly ? g.texts : g.texts.slice(0, -1);
311
- const steps = [];
312
- for (let k = 0; k < Math.max(stepTexts.length, maxIteration); k += 1) {
313
- const iteration = k + 1;
314
- steps.push({ i: stepTexts[k] ?? null, iteration, tools: recordRows(tools, iteration) });
315
- }
316
- const answer = g.texts.length && !stepsOnly ? g.texts[g.texts.length - 1] : null;
317
- return { kind: "turn", turnIndex: g.turnIndex, user: g.user, answer, record, steps };
318
- }
319
-
320
- // A canceled turn that ran more than one step or any call has no answer:
321
- // its partial text stays in the block, as it does live (turn_block.js
322
- // turnEnded promotes only a completed turn or a lone step with no tools). A
323
- // failed turn never answered: its texts are steps.
324
- function canceledSteps(g, record, tools) {
325
- if (record?.status === "failed") return true;
326
- return record?.status === "canceled" && (g.texts.length > 1 || tools.length > 0);
327
- }
328
-
329
- // A call's row from its tool record alone (no saved parts): the record's
330
- // called_as and via too, so "(called as bash)" and "(via call_tool)" show
331
- // after a reload, as live, and
332
- // its no_match ("no match" on a grep that found nothing) and System 1's
333
- // auto-allow (guardrail: {rule, p}).
334
- function recordRows(tools, iteration) {
335
- return tools.filter((r) => Number(r.iteration) === iteration).map((r) => ({
336
- key: `${iteration}:${r.call_index ?? 0}`, tool: r.tool, status: r.status, duration_ms: r.duration_ms,
337
- ...(r.called_as ? { called_as: r.called_as } : {}),
338
- ...(r.via ? { via: r.via } : {}),
339
- ...recordFlags(r),
340
- }));
341
- }
342
-
343
- function recordFlags(record) {
344
- return {
345
- ...(record?.no_match ? { no_match: true } : {}),
346
- ...(record?.guardrail ? { guardrail: record.guardrail } : {}),
347
- };
348
- }
349
-
350
- // A turn whose saved messages carry their parts (the server's ?parts=1):
351
- // every assistant message is one step. Its calls take the turn's records by
352
- // tool, in call order (each the next record of its tool, consumed with the
353
- // ones it skipped), not by iteration: an empty retry spends an iteration
354
- // that left no message (as the TUI's join, attached_loop.rb join_record).
355
- // The last message is the answer when it has text and made no call (and the
356
- // turn is no canceled multi-step one); its thinking stays behind as a step,
357
- // as it does live.
358
- function partsTurn(g, items, record, tools, stepsOnly = false) {
359
- const last = g.texts[g.texts.length - 1];
360
- const lastItem = items[last];
361
- const answer = !stepsOnly && String(lastItem.content ?? "") !== "" && !lastItem.parts?.tools?.length ? last : null;
362
- const pool = [...tools].sort((a, b) =>
363
- (Number(a.iteration) || 0) - (Number(b.iteration) || 0) || (Number(a.call_index) || 0) - (Number(b.call_index) || 0));
364
- const steps = g.texts.map((i, k) => {
365
- const iteration = k + 1;
366
- const parts = items[i].parts || {};
367
- const rows = Array.isArray(parts.tools)
368
- ? parts.tools.map((call, j) => {
369
- const r = takeRecord(pool, call.tool);
370
- return { key: `${iteration}:${j + 1}`, status: r?.status || "ok", duration_ms: r?.duration_ms, ...recordFlags(r), ...call };
371
- })
372
- : [];
373
- const thinking = String(parts.thinking || "");
374
- if (i === answer) return thinking ? { i: null, iteration, thinking, tools: [] } : null;
375
- return { i, iteration, thinking, tools: rows };
376
- }).filter(Boolean);
377
- // Records no saved message took (a generation that saved nothing): a
378
- // step per iteration of theirs, after the messages'.
379
- let iteration = g.texts.length;
380
- for (const n of [...new Set(pool.map((r) => Number(r.iteration) || 0))]) {
381
- iteration += 1;
382
- const rows = recordRows(pool, n).map((row) => ({ ...row, key: `${iteration}:${row.key.split(":")[1]}` }));
383
- steps.push({ i: null, iteration, thinking: "", tools: rows });
384
- }
385
- return { kind: "turn", turnIndex: g.turnIndex, user: g.user, answer, record, steps };
386
- }
387
-
388
- // The next record of +tool+ in +pool+ (call order), removed with the ones
389
- // before it; undefined when there is none (the pool stays as it was).
390
- function takeRecord(pool, tool) {
391
- const at = pool.findIndex((r) => String(r.tool) === String(tool));
392
- if (at < 0) return undefined;
393
- return pool.splice(0, at + 1)[at];
394
- }
395
-
396
232
  // Append +el+ to the history, above +timingEl+ while it is a running turn's
397
233
  // live timing line, so that line stays under the turn's activity, thinking
398
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
@@ -910,7 +891,10 @@ function drawnTurnNodes(group, items, { thumbs, capabilities = {}, cards = null
910
891
  }
911
892
  const empty = kind === "completed" && (group.emptyAnswer != null || end.turn_summary?.empty_answer);
912
893
  const endNote = empty ? elementOf(emptyAnswerTemplate(group.emptyAnswer != null ? items[group.emptyAnswer] : end.turn_summary.empty_answer)) : null;
913
- const kept = view.turnEnded({ kind, endNote, turnId: end.turn_id || group.drawn }) || [];
894
+ // The answer's key (data-answer-turn: Revise, the fold) is the turn's own
895
+ // id, which a live line's end always names; a drawing made from the
896
+ // messages names none for an id it made up (m…, …~N).
897
+ const kept = view.turnEnded({ kind, endNote, turnId: end.turn_id || null }) || [];
914
898
  if (endNote && !answer.includes(endNote)) answer.push(endNote);
915
899
  // The stage's turn end: the warn cards beside the block leave with the
916
900
  // block's, after the end line.
@@ -934,7 +918,8 @@ function savedAnswer(el, group, items, kind) {
934
918
  const text = el.textContent.trim();
935
919
  const at = [group.answer, ...[...(group.texts || [])].reverse()].find((i) => i != null && String(items[i]?.content ?? "").trim() === text);
936
920
  if (at == null) return el;
937
- return nodesOf(answerBubbleTemplate(items[at], { at, turnId: kind === "completed" ? group.turnId : null })).firstElementChild;
921
+ const turnId = kind === "completed" ? group.drawing?.end?.turn_id || null : null;
922
+ return nodesOf(answerBubbleTemplate(items[at], { at, turnId })).firstElementChild;
938
923
  }
939
924
 
940
925
  // The steps' texts paired with the turn's saved texts in order: each its
@@ -958,22 +943,24 @@ function pairStepTexts(els, group, items) {
958
943
  }
959
944
  }
960
945
 
961
- // A reloaded history as turn blocks (renderHistory's object path), as
962
- // nodes: per turn the prompt, a collapsed block of its steps when it had
963
- // any (stepTemplate, the live page's: texts, and with the server's parts
964
- // the thinking, params and output, from the saved messages; status and
965
- // duration from the timing's tool records), then the answer and the turn's
966
- // 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.
967
955
  // +thumbs(images)+ draws a prompt's or a tool row's image thumbs (a
968
956
  // template, images.js thumbsTemplate). +workingSet+ (the stage's
969
957
  // web.working_set): each block stamped with its
970
958
  // turn's ordinal and its rows with theirs (working_set_view.js), and the
971
959
  // turn's footprint on its summary line.
972
- // +drawings+ (chi web's turn_drawings): a turn stamped with a drawn id is
973
- // drawn from its drawing (drawnTurnNodes), its pieces marked data-drawn;
974
960
  // +cards+ the snapshot's cards (a drawn card's body), +capabilities+ the
975
961
  // page's (a notice shown elsewhere).
976
- 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 }) {
977
964
  const timingTemplate = (group) => {
978
965
  const record = group.record;
979
966
  // Numbered by its place in the turn records, as live (a failed turn
@@ -988,9 +975,6 @@ export function turnHistoryNodes(items, timing, { thumbs, workingSet = false, no
988
975
  // turn's (data-answer-turn: a turn's answer only, not a report reply);
989
976
  // +replyKey+, a report reply's (data-reply-key).
990
977
  const answerBubble = (at, cls = "", turnId = null, replyKey = null) => answerBubbleTemplate(items[at], { cls, at, turnId, replyKey });
991
- // The timing line after the bubble, not in it: where the live view
992
- // leaves it at the turn's end.
993
- const answerTemplate = (at, timing, turnId = null) => html`${answerBubble(at, "", turnId)}${timing}`;
994
978
  // A user's line, labelled when chi brought it in (a delegate report). A
995
979
  // `!cmd`'s saved message (the worker's "!(<command>)\n<output>") renders
996
980
  // as its command bubble, as live does — not as a user bubble.
@@ -1019,8 +1003,6 @@ export function turnHistoryNodes(items, timing, { thumbs, workingSet = false, no
1019
1003
  const drawn = drawnTurnNodes(group, items, { thumbs, capabilities, cards });
1020
1004
  if (drawn.block) {
1021
1005
  if (workingSet) drawn.block.querySelector(":scope > summary > .tw-sum")?.prepend(nodesOf(footprintTemplate(groupItems(group, ordinal), ordinal)));
1022
- outlines.push(null);
1023
- blockEnds.push(null);
1024
1006
  blockTurns.push(ordinal);
1025
1007
  }
1026
1008
  const lineKey = (i) => (items[i]?.source === "delegate_report" ? `${group.turnId}:input:${i - (group.user ?? i)}` : null);
@@ -1044,107 +1026,47 @@ export function turnHistoryNodes(items, timing, { thumbs, workingSet = false, no
1044
1026
  });
1045
1027
  };
1046
1028
  const parts = [];
1047
- // Each block's steps, in order: its outline once the nodes exist; how its
1048
- // turn ended (whether it stays open); and its turn's place among the turns
1049
- // (the working set's stamp).
1050
- const outlines = [];
1051
- const blockEnds = [];
1029
+ // Each drawn block's turn's place among the turns (the working set's stamp).
1052
1030
  const blockTurns = [];
1053
1031
  let turnOrdinal = -1;
1054
- 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 });
1055
1046
  // A quiet stretch before a group: its divider first (time_gaps.js).
1056
1047
  const gaps = groupGaps(groups, items, now);
1057
1048
  for (const [k, group] of groups.entries()) {
1058
1049
  if (gaps[k]) parts.push(timeGapTemplate(gaps[k]));
1059
1050
  if (group.kind === "note") { parts.push(noteBubbleTemplate(items[group.i])); continue; }
1060
- if (group.kind === "steer") { parts.push(steerTemplate(group.i, true)); continue; }
1061
- if (group.kind === "answer") { parts.push(answerTemplate(group.answer, nothing)); continue; }
1062
1051
  // A `!cmd`'s record: its command bubble, no steps, no timing.
1063
1052
  if (group.kind === "command") { parts.push(userTemplate(items[group.i])); continue; }
1064
- turnOrdinal += 1;
1065
- if (group.drawn) {
1066
- 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);
1067
1061
  continue;
1068
1062
  }
1069
- const prompt = items[group.user];
1070
- // A context wake turn starts with its note.
1071
- const promptPiece = prompt.role === "note" ? noteBubbleTemplate(prompt) : userTemplate(prompt);
1072
- const [only] = group.steps;
1073
- const ended = group.answer !== null || group.emptyAnswer != null;
1074
- const textless = only && (only.i === null || !String(items[only.i].content ?? ""));
1075
- // A lone thinking step before an answer (or the notice of a turn with
1076
- // none): no block, the plain answer's collapsed thinking block.
1077
- const plainThinking = group.steps.length === 1 && ended && textless && !only.tools.length && only.thinking;
1078
- const noBlock = !group.steps.length || plainThinking;
1079
- let block = null;
1080
- if (plainThinking) {
1081
- block = thinkingTemplate({ body: only.thinking, cls: "bubble thinking" });
1082
- } else if (group.steps.length) {
1083
- // A step's text with its message's rendered markdown (html: web.markdown on).
1084
- const gens = group.steps.map((step) => ({
1085
- text: step.i === null ? "" : String(items[step.i].content ?? ""),
1086
- html: step.i === null ? null : items[step.i].html ?? null,
1087
- thinking: step.thinking || "", tools: step.tools,
1088
- }));
1089
- const steps = gens.map((gen, k) => stepTemplate(gen, {
1090
- // The steers the step answered first, where the live rows went.
1091
- steers: (group.steps[k].steers || []).map((i) => steerTemplate(i, false)),
1092
- items: gen.tools.length ? [rowNodes(gen.tools, thumbs)] : [],
1093
- // Its text knows its message's refs (a question's), as an answer does.
1094
- at: group.steps[k].i,
1095
- }));
1096
- // Its summary line: the working set's footprint, when the turn touched
1097
- // something, then the steps (the live block's, stage_view.js handOff).
1098
- const foot = workingSet ? footprintTemplate(groupItems(group, turnOrdinal), turnOrdinal) : nothing;
1099
- 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>`;
1100
- outlines.push(gens);
1101
- // No record: a turn saved before them, or running at the reload.
1102
- blockEnds.push(group.record?.status ?? "completed");
1103
- blockTurns.push(turnOrdinal);
1104
- }
1105
- // Steers with no step to sit in, or in a turn that shows no block: on
1106
- // their own after the prompt.
1107
- const loose = noBlock ? [...group.steps.flatMap((step) => step.steers || []), ...(group.steers || [])] : group.steers || [];
1108
- // The user's lines merged into the turn: the live "steered" bubbles,
1109
- // after its steps and before its answer. A delegate report's is
1110
- // followed by the text that answered it when that isn't the answer: a
1111
- // small model tells its user about a report before its next tool call,
1112
- // and that step's text would stay folded in the block.
1113
- // A report's fold key (answer_fold.js), as its reply's: the turn's id
1114
- // and its place after the opening; none in a turn saved before turn ids.
1115
- const lineKey = (i) => (group.turnId && items[i]?.source === "delegate_report" ? `${group.turnId}:input:${i - group.user}` : null);
1116
- const merged = (group.merged || []).map((i) =>
1117
- html`${userTemplate(items[i], { state: "steered", step: items[i].step, lineKey: lineKey(i) })}${reportReplyTemplate(i, group)}`);
1118
- // A participant's review turn with a reply: Apply under it (the owner's
1119
- // page only: the participant page has its own view). Not under a pair
1120
- // turn: it acted itself.
1121
- const reviewer = group.answer !== null && prompt.turn_id && prompt.participant_mode !== PAIR
1122
- ? authorBadge(prompt.author, prompt.author_name) : null;
1123
- // The live hand-off's order (turn_pieces.js): a turn that ended with no
1124
- // answer has chi's muted notice where the answer would be, before the
1125
- // timing; a turn with no answer (canceled, or running: no record yet)
1126
- // its timing after its prompt and steps. A canceled turn ends with its
1127
- // cancel line, a failed one whose steps stayed with its failure line, as
1128
- // the live view left them.
1129
- parts.push(turnPieces({
1130
- prompt: promptPiece,
1131
- block,
1132
- steers: loose.map((i) => steerTemplate(i, true)),
1133
- merged,
1134
- answer: group.emptyAnswer == null && group.answer !== null ? [answerBubble(group.answer, "", group.turnId)] : [],
1135
- emptyNote: group.emptyAnswer != null ? emptyAnswerTemplate(items[group.emptyAnswer]) : null,
1136
- timing: timingTemplate(group),
1137
- apply: reviewer ? applyRowTemplate(prompt.turn_id, reviewer) : null,
1138
- end: html`${cancelLineTemplate(group.record)}${failedLineTemplate(group.record)}`,
1139
- }));
1063
+ turnOrdinal += 1;
1064
+ parts.push(drawnGroupPieces(group, turnOrdinal));
1140
1065
  }
1141
1066
  const out = nodesOf(parts);
1142
- // A finished turn's block as the live end leaves it: its outline, closed
1143
- // unless the turn was cut short.
1144
- 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`);
1145
1068
  // A drawn block is outlined and opened as its live end left it.
1146
- blocks.forEach((block, i) => { if (outlines[i] !== null) block.open = openAfterEnd(blockEnds[i], outlineBlock(block, outlines[i] || [])); });
1147
- if (workingSet) stampHistory(blocks, blockTurns);
1069
+ if (workingSet) stampHistory([...out.children].filter((el) => el.matches(".turn-work")), blockTurns);
1148
1070
  // Each answer bubble and step text knows its message's refs
1149
1071
  // (answer_refs.js; the page pairs them after the render), the index
1150
1072
  // stays out of the DOM.