samagotchi 0.179.0 → 0.181.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 (95) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +76 -1
  3. data/bin/chi +10 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/bundles.md +39 -3
  6. data/docs/cli.md +16 -9
  7. data/docs/configuration.md +25 -5
  8. data/docs/context.md +7 -0
  9. data/docs/internals/anthropic.md +4 -3
  10. data/docs/internals/background-tasks.md +4 -1
  11. data/docs/internals/block-renderers.md +11 -7
  12. data/docs/internals/bundles.md +12 -10
  13. data/docs/internals/objectives.md +9 -4
  14. data/docs/internals/web-frontend.md +127 -6
  15. data/docs/internals/working-set.md +24 -5
  16. data/docs/memory.md +3 -0
  17. data/docs/plugins.md +17 -6
  18. data/docs/sessions.md +1 -1
  19. data/docs/testing.md +5 -1
  20. data/lib/samagotchi/block_renderers.rb +22 -3
  21. data/lib/samagotchi/bundle_command.rb +9 -2
  22. data/lib/samagotchi/bundle_needs.rb +1 -1
  23. data/lib/samagotchi/bundle_settings_check.rb +5 -2
  24. data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
  25. data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
  26. data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
  27. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  28. data/lib/samagotchi/client.rb +8 -1
  29. data/lib/samagotchi/config.rb +6 -1
  30. data/lib/samagotchi/context_providers.rb +6 -8
  31. data/lib/samagotchi/core_notice.rb +44 -0
  32. data/lib/samagotchi/host_address.rb +7 -0
  33. data/lib/samagotchi/host_config.rb +8 -5
  34. data/lib/samagotchi/host_registry.rb +26 -8
  35. data/lib/samagotchi/installed_bundles/dir.rb +17 -55
  36. data/lib/samagotchi/installed_bundles/standing.rb +23 -3
  37. data/lib/samagotchi/installed_bundles.rb +26 -11
  38. data/lib/samagotchi/kernel_loop.rb +3 -2
  39. data/lib/samagotchi/llm/adapter_common.rb +3 -2
  40. data/lib/samagotchi/llm/adapters.rb +2 -1
  41. data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
  42. data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
  43. data/lib/samagotchi/llm/chat_loop.rb +6 -5
  44. data/lib/samagotchi/llm/errors.rb +41 -3
  45. data/lib/samagotchi/llm/http.rb +85 -22
  46. data/lib/samagotchi/llm/openai_chat.rb +20 -3
  47. data/lib/samagotchi/memory_bundle/status.rb +10 -6
  48. data/lib/samagotchi/objectives.rb +7 -2
  49. data/lib/samagotchi/owner_lock.rb +2 -0
  50. data/lib/samagotchi/plugin/api.rb +4 -1
  51. data/lib/samagotchi/plugin/context.rb +9 -0
  52. data/lib/samagotchi/plugin/peer.rb +32 -15
  53. data/lib/samagotchi/plugin/tool_spec.rb +13 -2
  54. data/lib/samagotchi/row_refs.rb +14 -3
  55. data/lib/samagotchi/session_chain/delete.rb +6 -6
  56. data/lib/samagotchi/session_config.rb +15 -9
  57. data/lib/samagotchi/session_manager/removal.rb +2 -2
  58. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  59. data/lib/samagotchi/terminal_ui/formatting.rb +13 -3
  60. data/lib/samagotchi/terminal_ui/join_replay.rb +1 -1
  61. data/lib/samagotchi/tool_ids.rb +19 -0
  62. data/lib/samagotchi/tool_runner.rb +8 -4
  63. data/lib/samagotchi/tools/registry.rb +3 -2
  64. data/lib/samagotchi/tools/task_runtime.rb +46 -3
  65. data/lib/samagotchi/turn_stages/objectives.rb +10 -5
  66. data/lib/samagotchi/version.rb +1 -1
  67. data/lib/samagotchi/web/public/app.js +22 -14
  68. data/lib/samagotchi/web/public/block_host.js +20 -20
  69. data/lib/samagotchi/web/public/block_renderers.css +5 -5
  70. data/lib/samagotchi/web/public/context_chips.js +183 -49
  71. data/lib/samagotchi/web/public/history_shape.js +5 -3
  72. data/lib/samagotchi/web/public/images.js +1 -1
  73. data/lib/samagotchi/web/public/index.html +90 -5
  74. data/lib/samagotchi/web/public/objectives_strip.js +16 -6
  75. data/lib/samagotchi/web/public/pan_zoom.js +121 -0
  76. data/lib/samagotchi/web/public/peer_chip.js +171 -0
  77. data/lib/samagotchi/web/public/peer_data.js +131 -0
  78. data/lib/samagotchi/web/public/peer_exchange.js +83 -0
  79. data/lib/samagotchi/web/public/peer_links.js +161 -0
  80. data/lib/samagotchi/web/public/peer_note.js +49 -0
  81. data/lib/samagotchi/web/public/picture_viewer.js +304 -0
  82. data/lib/samagotchi/web/public/popover_modal.js +3 -2
  83. data/lib/samagotchi/web/public/session_view.js +10 -1
  84. data/lib/samagotchi/web/public/stream_handlers.js +17 -4
  85. data/lib/samagotchi/web/public/turn_html.js +11 -2
  86. data/lib/samagotchi/web/public/working_set.js +9 -3
  87. data/lib/samagotchi/web/public/working_set_view.js +28 -11
  88. data/lib/samagotchi/web/public/ws_cards.js +36 -10
  89. data/lib/samagotchi/web/public/ws_markdown.js +129 -0
  90. data/lib/samagotchi/web/public/ws_order.js +48 -0
  91. data/lib/samagotchi/web/public/ws_peek.js +22 -5
  92. data/lib/samagotchi/web/public/ws_preview.css +41 -1
  93. data/lib/samagotchi/web/public/ws_reader.js +35 -6
  94. data/lib/samagotchi/web/public/ws_sections.js +24 -15
  95. metadata +11 -1
@@ -22,6 +22,8 @@
22
22
  // (contextChips null for a viewer without them, viewer.js)
23
23
  // workingSet the stage view's working set (web.working_set),
24
24
  // null when off
25
+ // peers the open session's peers (peer_data.js createPeers),
26
+ // read again on a peer's note, send or command; null: none
25
27
  // participantsControl the owner's participants panel (participants_panel.js),
26
28
  // null for none
27
29
  // sentIds, earlyRestores restore.js's bookkeeping
@@ -62,12 +64,13 @@ import { keepEarlyRestore, restoreAction } from "./restore.js";
62
64
  import { setBadgeMode } from "./participant_names.js";
63
65
  import { isParticipantAuthor } from "./participant_model.js";
64
66
  import { stillOn } from "./latest.js";
67
+ import { peerRef } from "./peer_exchange.js";
65
68
 
66
69
  export function createStreamHandlers(deps) {
67
70
  const {
68
71
  selected, store, clientId, capabilities, historyEl,
69
72
  liveTurn, turnDom, shownTexts, questionCards, contextChips,
70
- workingSet = null, participantsControl = null, sentIds, earlyRestores, stream, composer, getSession,
73
+ workingSet = null, participantsControl = null, peers = null, sentIds, earlyRestores, stream, composer, getSession,
71
74
  resync, applyPromptOps, showSteers, markRecapStale, setTurnRunning, setLiveStatus, endTurnView,
72
75
  appendChunk, readTurnEnd, applyFinalMarkdown, refreshTimingFromSession, makeUserBubble, addEndBubble,
73
76
  commandBubble, addCommandBubble, addNoteBubble, findInTurnRoots, setUsedMemories, showRecap,
@@ -191,6 +194,8 @@ export function createStreamHandlers(deps) {
191
194
  // A participant's turn: their spend and turns in the panel moved.
192
195
  if (data.origin?.author) participantsControl?.reload();
193
196
  endTurnView("completed", null, { emptyAnswer: data.turn_summary?.empty_answer || null });
197
+ // Its peer sends' state as an ended turn's (no fetch).
198
+ peers?.touch?.();
194
199
  const out = turnOutput(data);
195
200
  if (out) appendChunk(out);
196
201
  if (data.verdict) deps.placeVerdict?.(data.verdict);
@@ -297,6 +302,8 @@ export function createStreamHandlers(deps) {
297
302
  const id = selected();
298
303
  // A queued /working-set line is no longer pending (the list's pill).
299
304
  workingSet?.commandRan(data);
305
+ // A /claude validate … may have sent to a peer.
306
+ peers?.refresh();
300
307
  const view = commandView(data, clientId);
301
308
  // What the command changed, in one patch: the bar and the chips'
302
309
  // popovers redraw once (the store; the working set's list follows
@@ -364,9 +371,11 @@ export function createStreamHandlers(deps) {
364
371
  context_added: (data) => {
365
372
  const at = data.at || data.created_at || null;
366
373
  gapBefore(at);
367
- addNoteBubble({ label: data.label, content: data.text || "", at, objectives: data.objectives });
368
- // An attached context source's note: its chip changed.
374
+ addNoteBubble({ label: data.label, content: data.text || "", at, objectives: data.objectives, peer: data.peer,
375
+ context_source: data.context_source });
376
+ // An attached context source's note: its chip changed; a peer's answer: its exchange.
369
377
  if (data.context_source) contextChips?.refresh();
378
+ if (data.peer) peers?.refresh();
370
379
  },
371
380
  // The session's list changed (objectives_strip.js): an edit waiting, a
372
381
  // list note in, a turn's moves.
@@ -379,7 +388,11 @@ export function createStreamHandlers(deps) {
379
388
  continue_offered: (data) => questionCards.renderContinue(data),
380
389
  continue_resolved: (data) => questionCards.resolveContinue(data),
381
390
  tool_call_started: (data) => turnDom.toolStarted(data),
382
- tool_call_completed: (data) => turnDom.toolCompleted(data),
391
+ tool_call_completed: (data) => {
392
+ turnDom.toolCompleted(data);
393
+ // A peer send: its exchange went out (or didn't).
394
+ if (peerRef(data)) peers?.refresh();
395
+ },
383
396
  // The engine's list, after every memory read and at a turn's end.
384
397
  used_memories_updated: (data) => {
385
398
  if (Array.isArray(data.used_memory_names)) setUsedMemories(data.used_memory_names);
@@ -19,6 +19,8 @@ import { STOPPED_LINE_CLASS, cancelLineText, formatDuration } from "./timing.js"
19
19
  import { emptyAnswerLine } from "./turn_events.js";
20
20
  import { authorBadge, authorBadgeText, authorBadgeTitle } from "./participant_names.js";
21
21
  import { ownerLabel, viewerSelf } from "./viewer_self.js";
22
+ import { peerRef } from "./peer_exchange.js";
23
+ import { peerNoteTemplate } from "./peer_note.js";
22
24
 
23
25
  // A row's status (live, or a saved tool record's on reload): running,
24
26
  // error, stopped (a task_wait the user's Stop ended), blocked (a guardrail
@@ -181,11 +183,16 @@ export function toolRowInnerTemplate(row, { thumbs = () => nothing, stop = nothi
181
183
  : nothing;
182
184
  const duration = formatDuration(row.duration_ms);
183
185
  const full = row.status === "running" ? "" : String(row.output || "").replace(/^\[[^\]]*\]\s*/, "");
184
- const output = full
186
+ // A peer send (its peer ref): an empty slot peer_links.js draws the
187
+ // exchange's state into, the output (chi's advice to the model) its hover
188
+ // instead of a line, unless the send failed.
189
+ const peer = peerRef(row);
190
+ const peerSlot = peer ? html`<span class="peer-slot" data-peer-ref=${peer.target.id} title=${full || nothing}></span>` : nothing;
191
+ const output = full && !(peer && row.status === "ok" && !/^Error:/.test(full))
185
192
  ? html`<div class=${tailMode(row.tool, full) ? "activity-output tail" : "activity-output"} title=${full}>${inlineOutput(row.tool, full)}</div>`
186
193
  : nothing;
187
194
  const status = statusParts(row.status, { noMatch: !!row.no_match });
188
- return html`${statusMarkTemplate(status)}<span class="activity-tool">${toolName(row)}</span>${params}${stop}${alias}${statusWordTemplate(status)}${row.status === "ok" ? wayInTemplate(row) : nothing}${auto}${wrong}${duration ? html`<span class="activity-duration">${duration}</span>` : nothing}${commandBlockTemplate(row.view, row.title)}${llmEditTemplate(row)}${output}${full ? readLinesTemplate(row) : nothing}${row.images?.length ? thumbs(row.images) : nothing}${row.diff ? activityDiffTemplate(row.diff) : nothing}`;
195
+ return html`${statusMarkTemplate(status)}<span class="activity-tool">${toolName(row)}</span>${params}${peerSlot}${stop}${alias}${statusWordTemplate(status)}${row.status === "ok" ? wayInTemplate(row) : nothing}${auto}${wrong}${duration ? html`<span class="activity-duration">${duration}</span>` : nothing}${commandBlockTemplate(row.view, row.title)}${llmEditTemplate(row)}${output}${full ? readLinesTemplate(row) : nothing}${row.images?.length ? thumbs(row.images) : nothing}${row.diff ? activityDiffTemplate(row.diff) : nothing}`;
189
196
  }
190
197
 
191
198
  // A prompt bubble's states and their badges: queued (waiting for its
@@ -286,6 +293,8 @@ export function answerBubbleTemplate(message, { cls = "", at = null, turnId = nu
286
293
  // text.
287
294
  export function noteBubbleTemplate(note) {
288
295
  if (note?.objectives) return objectivesEntryTemplate(note, timeTitle(note.at));
296
+ // A peer's answer: a bubble from the peer (peer_note.js).
297
+ if (note?.peer && typeof note.peer === "object") return peerNoteTemplate(note);
289
298
  const from = note?.label ? `note from ${note.label}` : "note";
290
299
  // A wake turn's note opens that turn (TURN_PROMPT, bubbles.js); a class, not
291
300
  // data-turn-id, which marks a claim's anchor (claim_link.js). Its turn's id
@@ -10,9 +10,11 @@
10
10
  // write: a write of a file is an edit), at the first row that brought it in
11
11
  // as ordinals ({turn, step, row}: the turn's place in the page's turns, the
12
12
  // generation's in the turn, the row's in the generation; never a row key,
13
- // which differs live and reloaded), count the rows that touched it, runs
13
+ // which differs live and reloaded), last the newest row that touched it
14
+ // (the same ordinals: the list's order and its session step tag,
15
+ // ws_order.js), count the rows that touched it, runs
14
16
  // each row's tool id with its at ([{id, at}], rows with an id only). A later
15
- // touch unions its ops and bumps its count, never its at: within a turn
17
+ // touch unions its ops, bumps its count and moves its last, never its at: within a turn
16
18
  // the set is append-only, which keeps the fold stable. state is "live" from
17
19
  // the rows; the server's projection (GET working_set, :working_set_updated:
18
20
  // WorkingSet) overlays its state (live, stale, forgotten, dropped) and
@@ -147,6 +149,8 @@ export function itemsOfTurn(turn, turnOrdinal) {
147
149
  byKey.set(id, item);
148
150
  items.push(item);
149
151
  }
152
+ // Its newest touch so far (the turn's last, once the walk ends).
153
+ item.last = at;
150
154
  // The row's tool id and place: the timeline's step tags and "go to
151
155
  // the call" (ws_timeline.js placeOf); a legacy row has none.
152
156
  if (row.tool_id) item.runs = [...(item.runs || []), { id: row.tool_id, at }];
@@ -157,7 +161,7 @@ export function itemsOfTurn(turn, turnOrdinal) {
157
161
  }
158
162
 
159
163
  // The session's set: every turn's items merged (the first entry's at kept,
160
- // ops unioned, counts summed), the preloaded memories first (tag
164
+ // the latest list's last, ops unioned, counts summed), the preloaded memories first (tag
161
165
  // "prompt"), the used memories no row explains (a turn without its saved
162
166
  // rows) after them; the muted memories listed apart, never counted.
163
167
  // @param turns the finished turns' item lists, in order
@@ -184,6 +188,8 @@ export function sessionItems({ turns = [], live = [], preloaded = [], notes = []
184
188
  found.count += it.count;
185
189
  if (it.runs) found.runs = [...(found.runs || []), ...it.runs];
186
190
  if (!found.at) found.at = it.at;
191
+ // Lists come in turn order, the live turn's last: the latest wins.
192
+ if (it.last) found.last = it.last;
187
193
  }
188
194
  }
189
195
  }
@@ -53,6 +53,7 @@ import {
53
53
  steerId, steerLine, stepRange, stepTag, tokensText, turnLens, undroppable,
54
54
  } from "./working_set.js";
55
55
  import { serverSig } from "./ws_item_sig.js";
56
+ import { heldOrder, recencyOrder } from "./ws_order.js";
56
57
 
57
58
  // The popover's files fold to this many lines (groups open in place, one at
58
59
  // a time), its memories past this many to one group.
@@ -177,6 +178,10 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
177
178
  // lit on the session's list), the group open in it.
178
179
  let lens = null;
179
180
  let openGroup = null;
181
+ // The list's order taken at the open (ws_order.js): the item keys, last
182
+ // touched first. Held while it is open (rows that come go on top, the
183
+ // others stay); every open takes it again (null: closed).
184
+ let openKeys = null;
180
185
  // What the drawn list shows of the context's tokens (tokenText): a chunk's
181
186
  // new count redraws it only when that text changes.
182
187
  let shownTokens = null;
@@ -224,11 +229,14 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
224
229
  session,
225
230
  // Opened: the server's set asked again (a file changed while the
226
231
  // session sat idle shows stale).
232
+ // The order is taken again at each open (a footprint or the rail while
233
+ // it is open too: they open it again).
227
234
  show: (_data, opening) => {
235
+ if (opening) openKeys = recencyOrder(sessionSet().items).map(itemKey);
228
236
  draw();
229
237
  if (opening) fetchServer();
230
238
  },
231
- onClose: () => { openGroup = null; peek?.close(); onChange(); },
239
+ onClose: () => { openGroup = null; openKeys = null; peek?.close(); onChange(); },
232
240
  // The foot's + add (the popover's submit): one KEY as typed (quoted
233
241
  // when it has spaces).
234
242
  onSubmit: (form) => {
@@ -298,11 +306,14 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
298
306
  // the words, the edited mark) and nothing else.
299
307
  const item = touched ? lensItem(row0, touched) : row0;
300
308
  const lensClass = touched && !row0.added ? (touched.has(itemKey(row0)) ? " lit" : " dim") : "";
301
- // A dimmed row's entry is the session's (its first, "t1·s1"); a lit row's the turn's.
309
+ // A dimmed row's tag is the session's last touch ("t3·s4"; an older
310
+ // page's item: its first entry); a lit row's the turn's entry ("s3").
311
+ // By the lens class: a lit row carries the session's `last` too.
302
312
  const whole = inSession || lensClass === " dim";
313
+ const place = whole ? row0.last || row0.at : item.at;
303
314
  const fresh = isFresh(seenAt(row0), now);
304
315
  // A lit preloaded memory the turn read shows the turn's step, not "prompt".
305
- const tag = stepTag(lensClass === " lit" && item.at ? { ...item, preloaded: false } : item, { session: whole });
316
+ const tag = stepTag(lensClass === " lit" && item.at ? { ...item, preloaded: false } : { ...item, at: place }, { session: whole });
306
317
  const note = start && touched ? heldTwiceNote(row0, touched.get(itemKey(row0))) : "";
307
318
  // An added row's words: what it is (a phone's tap on them opens its strip).
308
319
  const what = start ? [memoryPartWords(row0), row0.state && row0.state !== "live" ? row0.state : ""].filter(Boolean).join(" · ") : opsText(item);
@@ -323,9 +334,9 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
323
334
  if (start && inSession && heldTwice(row0)) tagEl = html`<span class="ws-twice" title="already in the prompt and read again: held twice">held twice</span>`;
324
335
  else if (tag === "prompt") tagEl = start ? nothing : html`<span class="ws-step p" title="in the system prompt">prompt</span>`;
325
336
  else if (tag) {
326
- const prompt = whole ? promptOf(item.at.turn) : "";
327
- const where = whole ? `turn ${item.at.turn + 1}${prompt ? ` (${prompt})` : ""}, step ${item.at.step + 1}` : `step ${item.at.step + 1}`;
328
- tagEl = html`<button type="button" class=${`ws-step${item.kind === "memory" ? " p" : ""}${note ? " twice" : ""}`} data-ws="jump" data-at=${atAttr(item.at)} title=${`entered at ${where}: go to the call`}>${tag}</button>`;
337
+ const prompt = whole ? promptOf(place.turn) : "";
338
+ const where = whole ? `turn ${place.turn + 1}${prompt ? ` (${prompt})` : ""}, step ${place.step + 1}` : `step ${place.step + 1}`;
339
+ tagEl = html`<button type="button" class=${`ws-step${item.kind === "memory" ? " p" : ""}${note ? " twice" : ""}`} data-ws="jump" data-at=${atAttr(place)} title=${`${whole ? "last touched" : "entered"} at ${where}: go to the call`}>${tag}</button>`;
329
340
  }
330
341
  const edited = item.kind === "file" && item.ops.includes("edit");
331
342
  const state = row0.state && row0.state !== "live" ? ` ${row0.state}` : "";
@@ -367,8 +378,9 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
367
378
  const startRow = (row, opts) => (row.kind === "memory" ? rowTemplate(row, { ...opts, start: true }) : partRowTemplate(row, opts));
368
379
  const isLit = (item, opts) => !!opts.touched && opts.touched.has(itemKey(item));
369
380
 
370
- // The head view's sections (ws_sections.js headSections): each header
371
- // folds (per session, session_prefs.js WS_SECTION_FOLD); folded, a section
381
+ // The head view's sections (ws_sections.js headSections), read · talk ·
382
+ // start: each header folds (per session, session_prefs.js WS_SECTION_FOLD;
383
+ // none stored: start folded); folded, a section
372
384
  // shows only the rows the lens lights. Conversation is one row, no header,
373
385
  // no fold (a stored fold naming it is ignored).
374
386
  function headTemplate(sections, opts, folded) {
@@ -376,7 +388,7 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
376
388
  if (section.key === "talk") return html`<div class="ws-sec talk">${talkTemplate(section, opts)}</div>`;
377
389
  const open = !folded.has(section.key);
378
390
  const tokens = tokensText(section.tokens);
379
- const head = html`<button type="button" class="ws-sec-head" data-ws="section" data-id=${section.key} aria-expanded=${String(open)}><span class="k">${open ? "▾" : "▸"}</span><span class="t">${section.title}</span>${section.meta ? html`<span class="n">${section.meta}</span>` : nothing}${tokens ? html`<span class="tk">${tokens}</span>` : nothing}</button>`;
391
+ const head = html`<button type="button" class="ws-sec-head" data-ws="section" data-id=${section.key} aria-expanded=${String(open)}><span class="k">${open ? "▾" : "▸"}</span><span class="t">${section.title}</span>${section.meta ? html`<span class="n">${section.meta}</span>` : nothing}${section.twice ? html`<span class="w" title="in the prompt and read again: held twice">· ${section.twice} held twice</span>` : nothing}${tokens ? html`<span class="tk">${tokens}</span>` : nothing}</button>`;
380
392
  let body;
381
393
  if (section.inner) {
382
394
  body = open
@@ -409,7 +421,8 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
409
421
  }
410
422
 
411
423
  // The session's folded sections, and a toggle of one.
412
- const foldedNow = () => foldedSections(readPref(WS_SECTION_FOLD, session(), "[]"));
424
+ // Nothing stored (null, told from a stored []) is the default fold.
425
+ const foldedNow = () => foldedSections(readPref(WS_SECTION_FOLD, session(), null));
413
426
  function toggleSection(key) {
414
427
  const folded = foldedNow();
415
428
  if (folded.has(key)) folded.delete(key);
@@ -442,10 +455,14 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
442
455
  // session and is kept: the turn coming back lights it again.
443
456
  const at = curLens();
444
457
  const inSession = at === null;
445
- const set = sessionSet();
458
+ const full = sessionSet();
446
459
  const pend = pending();
447
460
  const forget = forgetOn(st.llmContext);
448
461
  const last = lastTurn();
462
+ // The list's order: last touched first, held while it is open
463
+ // (ws_order.js). Only the list's: rowItem, steer and the rail read the
464
+ // set as it is.
465
+ const set = { ...full, items: heldOrder(full.items, openKeys) };
449
466
  // The head view (no parts: today's list); a turn's read of `system/x`
450
467
  // lights the start row of `x`, and a prompt memory is never new.
451
468
  const head = headSections(set, POP_BUDGET, { parts: st.promptParts, ctxTokens: st.ctxTokens, turns: last + 1, inTurn: !inSession });
@@ -3,10 +3,14 @@
3
3
  // read's lines draw as a read row's do (.read-line, numbered); an edit's
4
4
  // diff with diff_view.js, the same renderer as the tool row's and the
5
5
  // approval card's. A card chi no longer has is greyed, its text folded.
6
+ // A memory's text and a whole read of an .md file render as markdown once
7
+ // their HTML is there (ws_markdown.js; the +md+ option), with a
8
+ // "rendered | source" switch in the card's header.
6
9
 
7
10
  import { html, nothing } from "./vendor/lit-html.js";
8
11
  import { diffCounts, diffTemplate } from "./diff_view.js";
9
12
  import { eventTag, goneText, linesText, placeOf, SLICE_FOLD_LINES, tagsText } from "./ws_timeline.js";
13
+ import { markdownTemplate, renderable, sourceText } from "./ws_markdown.js";
10
14
 
11
15
  const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
12
16
 
@@ -34,23 +38,40 @@ export function callTemplate(event, item, label = "go to the call") {
34
38
  return html`<button type="button" class="wsr-call" data-ws="jump" data-at=${`${at.turn}.${at.step}.${at.row}`}>${label}</button>`;
35
39
  }
36
40
 
37
- function goneBody(card, rows, undrop) {
41
+ // The card's "rendered | source" switch (+view+ the one pressed).
42
+ function viewTemplate(view) {
43
+ const button = (name) => html`<button type="button" class=${view === name ? "on" : ""} aria-pressed=${String(view === name)} data-wsr="view" data-view=${name}>${name}</button>`;
44
+ return html`<span class="wsr-view" role="group" aria-label="Show as">${button("rendered")}${button("source")}</span>`;
45
+ }
46
+
47
+ // A text, rendered when +shown+ holds its markdown (else as sent).
48
+ const textOr = (text, shown) => shown ?? textTemplate(text);
49
+
50
+ function goneBody(card, rows, undrop, shown = null) {
38
51
  const words = goneText(card.state);
39
52
  const what = card.type === "slice" ? plural(rows.length, "line") : "its text";
40
53
  const offer = card.state === "dropped" && undrop !== nothing ? html` · ${undrop}` : nothing;
41
- return html`<div class="wsr-gone">${what} · ${words}${offer}</div><details class="wsr-had"><summary>what it was</summary>${card.type === "slice" ? linesTemplate(rows) : textTemplate(card.event.text)}</details>`;
54
+ const had = shown ?? (card.type === "slice" ? linesTemplate(rows) : textTemplate(card.event.text));
55
+ return html`<div class="wsr-gone">${what} · ${words}${offer}</div><details class="wsr-had"><summary>what it was</summary>${had}</details>`;
42
56
  }
43
57
 
44
- // A memory read's overlay part (ws_timeline: event.memory.overlay).
45
- function overlayTemplate(memory) {
58
+ // A memory read's overlay part (ws_timeline: event.memory.overlay),
59
+ // rendered with its card (+md+, +on+: the card shows rendered).
60
+ function overlayTemplate(memory, md = null, on = false) {
46
61
  if (!memory?.overlay) return nothing;
47
62
  const name = String(memory.overlay_path || "").split("/").pop();
48
- return html`<div class="wsr-overlay"><div class="wsr-overlay-h">+ overlay for this model${name ? ` · ${name}` : ""}</div>${textTemplate(memory.overlay)}</div>`;
63
+ // Asked with its card's text, so both come together.
64
+ const rendered = md ? markdownTemplate(memory.overlay, md) : null;
65
+ const shown = on ? rendered : null;
66
+ return html`<div class="wsr-overlay"><div class="wsr-overlay-h">+ overlay for this model${name ? ` · ${name}` : ""}</div>${textOr(memory.overlay, shown)}</div>`;
49
67
  }
50
68
 
51
69
  // One card. +item+: the open item (its runs: the step tags); +undrop+: the
52
- // greyed card's undrop button (a template), or nothing.
53
- export function cardTemplate(card, { item, undrop = nothing } = {}) {
70
+ // greyed card's undrop button (a template), or nothing; +md+ ({view,
71
+ // html(text)}: the reader's): a renderable card whose HTML is there gets
72
+ // the switch and, with +view+ "rendered", its markdown. Without it (an old
73
+ // reader), today's source.
74
+ export function cardTemplate(card, { item, undrop = nothing, md = null } = {}) {
54
75
  const gone = card.state && card.state !== "sent";
55
76
  const pill = gone ? html`<span class="wsr-pill gone">chi no longer has this</span>`
56
77
  : card.latest ? html`<span class="wsr-pill latest">latest</span>` : nothing;
@@ -58,10 +79,13 @@ export function cardTemplate(card, { item, undrop = nothing } = {}) {
58
79
  let meta = "";
59
80
  let body;
60
81
  let call;
82
+ const rendered = md && renderable(card, item) ? markdownTemplate(sourceText(card), md) : null;
83
+ const on = rendered !== null && md.view !== "source";
84
+ const shown = on ? rendered : null;
61
85
  if (card.type === "slice") {
62
86
  title = linesText(card);
63
87
  meta = `${plural(card.reads.length, "read")} · ${tagsText(card.reads, item)}`;
64
- body = gone ? goneBody(card, card.rows, undrop) : linesTemplate(card.rows);
88
+ body = gone ? goneBody(card, card.rows, undrop, shown) : shown ?? linesTemplate(card.rows);
65
89
  call = callTemplate(card.reads[0], item);
66
90
  } else {
67
91
  const { event } = card;
@@ -81,9 +105,11 @@ export function cardTemplate(card, { item, undrop = nothing } = {}) {
81
105
  title = `${words} · ${tag}`;
82
106
  const shared = event.shared_with?.length ? `read with ${event.shared_with.join(", ")}` : "";
83
107
  meta = shared;
84
- body = gone ? goneBody(card, [], undrop) : html`${textTemplate(event.text)}${card.type === "memory" ? overlayTemplate(event.memory) : nothing}`;
108
+ body = gone ? goneBody(card, [], undrop, shown) : html`${textOr(event.text, shown)}${card.type === "memory" ? overlayTemplate(event.memory, md, on) : nothing}`;
85
109
  }
86
110
  }
87
111
  const classes = `wsr-card ${card.type}${gone ? ` gone ${card.state}` : ""}${card.latest ? " latest" : ""}`;
88
- return html`<article class=${classes} data-newest=${card.newest}><header class="wsr-card-h"><span class="wsr-card-t">${title}</span>${meta ? html`<span class="wsr-card-m">${meta}</span>` : nothing}${pill}${call}</header>${body}</article>`;
112
+ const view = rendered !== null ? viewTemplate(on ? "rendered" : "source") : nothing;
113
+ const first = card.type === "slice" ? card.first : nothing;
114
+ return html`<article class=${classes} data-newest=${card.newest} data-first=${first}><header class="wsr-card-h"><span class="wsr-card-t">${title}</span>${meta ? html`<span class="wsr-card-m">${meta}</span>` : nothing}${pill}<span class="wsr-card-actions">${view}${call}</span></header>${body}</article>`;
89
115
  }
@@ -0,0 +1,129 @@
1
+ // Markdown in the working set's reader and peek (ws_cards.js, ws_reader.js,
2
+ // ws_peek.js): which texts render, the text to send, a leading front
3
+ // matter taken off, the HTML of each text kept for the page, and its
4
+ // template (lit: its spec loads dom_shim.js). The HTML comes from markdown_place.js
5
+ // renderMarkdown (POST /api/render, sanitised there); null is markdown off,
6
+ // a viewer that may not render, or a failed read: the source stays.
7
+ //
8
+ // What renders (docs/internals/web-frontend.md, The working set's reader):
9
+ // a memory's text (read, written, its overlay, the greyed "what it was") and
10
+ // a whole read of an .md file. A slice stays numbered source (it can start
11
+ // inside a fence or a list, and its line numbers are the strip's jumps); an
12
+ // edit or a write stays its diff; a fetch's text is not rendered.
13
+
14
+ import { html, nothing } from "./vendor/lit-html.js";
15
+ import { unsafeHTML } from "./vendor/directives/unsafe-html.js";
16
+
17
+ // The route's cap on its JSON body (web/message_display.rb MAX_RENDER_BYTES;
18
+ // block_host.js MAX_SOURCE_BYTES mirrors it too).
19
+ export const RENDER_MAX_BYTES = 64 * 1024;
20
+ // About how many texts the page keeps the HTML of.
21
+ const CACHE_MAX = 50;
22
+
23
+ const MD_FILE = /\.(md|markdown)$/i;
24
+ const MEMORY_CARDS = new Set(["memory", "written"]);
25
+ const MEMORY_OPS = new Set(["memory_read", "memory_write"]);
26
+
27
+ const markdownFile = (item) => item?.kind === "file" && MD_FILE.test(String(item.key || ""));
28
+
29
+ // A card (ws_timeline.js timelineCards) of +item+ that renders: a memory's,
30
+ // or a slice of an .md file that is the whole file (from line 1, one of its
31
+ // reads a whole one).
32
+ export function renderable(card, item) {
33
+ if (!card) return false;
34
+ if (MEMORY_CARDS.has(card.type)) return true;
35
+ if (card.type !== "slice" || card.first !== 1 || !markdownFile(item)) return false;
36
+ return (card.reads || []).some((read) => read?.lines?.whole);
37
+ }
38
+
39
+ // The same rule for the peek's event (ws_timeline.js peekOf): a memory read
40
+ // or write; a whole read of an .md file, not a preview of it.
41
+ export function renderableEvent(event, item) {
42
+ if (!event) return false;
43
+ if (MEMORY_OPS.has(event.op)) return true;
44
+ return event.op === "read" && !!event.lines?.whole && !event.lines?.partial && markdownFile(item);
45
+ }
46
+
47
+ // The text a card renders: a slice's lines, else its event's text.
48
+ export function sourceText(card) {
49
+ if (card?.type === "slice") return (card.rows || []).map((r) => r.text).join("\n");
50
+ return String(card?.event?.text ?? "");
51
+ }
52
+
53
+ const FRONT = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/;
54
+
55
+ // A leading YAML front matter block (a --- line closed by a --- line):
56
+ // {front, body}, +front+ without its last newline; "" when there is none.
57
+ export function splitFrontMatter(text) {
58
+ const all = String(text ?? "");
59
+ const found = all.match(FRONT);
60
+ if (!found) return { front: "", body: all };
61
+ return { front: found[0].replace(/\r?\n$/, ""), body: all.slice(found[0].length) };
62
+ }
63
+
64
+ // The peek's source and rendered body omit a leading front matter block.
65
+ // The reader uses splitFrontMatter separately so it keeps that block above
66
+ // the rendered body.
67
+ export function peekText(text) {
68
+ return splitFrontMatter(text).body;
69
+ }
70
+
71
+ const tooBig = (text) => new TextEncoder().encode(JSON.stringify({ text })).length > RENDER_MAX_BYTES;
72
+
73
+ // The page's HTML of each text: +html(text)+ answers the HTML, null (too big
74
+ // for the route: no request) or undefined while its one request is on its
75
+ // way (+onReady()+ runs when HTML comes). A null answer (markdown off, a
76
+ // failed read) is not kept, so the next draw asks again; at most one
77
+ // request per text at a time. Bounded (+max+), the least recently used
78
+ // text going first.
79
+ export function createRenderCache(renderMarkdown, onReady = () => {}, { max = CACHE_MAX } = {}) {
80
+ const kept = new Map();
81
+ const asking = new Set();
82
+
83
+ function html(text) {
84
+ const key = String(text ?? "");
85
+ if (kept.has(key)) {
86
+ const found = kept.get(key);
87
+ kept.delete(key);
88
+ kept.set(key, found);
89
+ return found;
90
+ }
91
+ if (tooBig(key)) return null;
92
+ if (asking.has(key)) return undefined;
93
+ asking.add(key);
94
+ let asked;
95
+ try {
96
+ asked = Promise.resolve(renderMarkdown(key));
97
+ } catch {
98
+ asked = Promise.resolve(null);
99
+ }
100
+ asked
101
+ .catch(() => null)
102
+ .then((answer) => {
103
+ asking.delete(key);
104
+ if (typeof answer !== "string" || !answer) return;
105
+ kept.set(key, answer);
106
+ while (kept.size > max) kept.delete(kept.keys().next().value);
107
+ onReady();
108
+ });
109
+ return undefined;
110
+ }
111
+
112
+ return { html };
113
+ }
114
+
115
+ // +text+ as markdown: its front matter as source, then the HTML (sanitised
116
+ // on the server, POST /api/render); null while its HTML isn't there
117
+ // (+md.html+: undefined on its way, null off or failed).
118
+ export function markdownTemplate(text, md) {
119
+ if (!md?.html) return null;
120
+ const { front, body } = splitFrontMatter(text);
121
+ const found = md.html(body);
122
+ if (typeof found !== "string") return null;
123
+ return html`${front ? html`<pre class="wsr-front">${front}</pre>` : nothing}<div class="wsr-md">${unsafeHTML(found)}</div>`;
124
+ }
125
+
126
+ // The peek renders only the front matter's body, without source above it.
127
+ export function peekMarkdownTemplate(text, md) {
128
+ return markdownTemplate(peekText(text), md);
129
+ }
@@ -0,0 +1,48 @@
1
+ // The working-set list's order (docs/internals/working-set.md, The list's
2
+ // order): last touched first, and held still while the list is open.
3
+ // recencyOrder newest `last` (else `at`) first: turn, then step, then
4
+ // row; the items with neither (a preloaded memory never
5
+ // read, a used memory no row explains) after the rest, in
6
+ // the order they came.
7
+ // heldOrder the order taken at the open (+openKeys+, the item keys
8
+ // drawn then): the items not in it on top, newest first,
9
+ // the others where they stood.
10
+ // Only the popover's list is ordered this way; the rail, the footprints and
11
+ // the reader's side list keep the set's entry order.
12
+ //
13
+ // No DOM: `node --test` covers the rules; working_set_view.js uses them.
14
+ // A module of its own: static JS is cached at unversioned URLs, and a new
15
+ // export on an old module would blank the page.
16
+ import { itemKey } from "./working_set.js";
17
+
18
+ // An item's newest place: its last touch, else its first entry (an older
19
+ // page's item has no `last`), else null.
20
+ const placeOf = (item) => item?.last || item?.at || null;
21
+
22
+ // Which of two places is newer: > 0 when +a+ is.
23
+ function newer(a, b) {
24
+ return (a.turn - b.turn) || (a.step - b.step) || (a.row - b.row);
25
+ }
26
+
27
+ // +items+ newest first (a copy; stable on ties).
28
+ export function recencyOrder(items) {
29
+ return (items || [])
30
+ .map((item, i) => ({ item, i, at: placeOf(item) }))
31
+ .sort((x, y) => {
32
+ if (x.at && y.at) return newer(y.at, x.at) || x.i - y.i;
33
+ if (x.at || y.at) return x.at ? -1 : 1;
34
+ return x.i - y.i;
35
+ })
36
+ .map((x) => x.item);
37
+ }
38
+
39
+ // +items+ in the order of +openKeys+ (the keys drawn at the open), the ones
40
+ // it doesn't hold before them, newest first; an item that left the set is
41
+ // simply not there. Without +openKeys+: recencyOrder.
42
+ export function heldOrder(items, openKeys) {
43
+ if (!Array.isArray(openKeys)) return recencyOrder(items);
44
+ const place = new Map(openKeys.map((key, i) => [key, i]));
45
+ const fresh = recencyOrder((items || []).filter((item) => !place.has(itemKey(item))));
46
+ const kept = (items || []).filter((item) => place.has(itemKey(item))).sort((a, b) => place.get(itemKey(a)) - place.get(itemKey(b)));
47
+ return [...fresh, ...kept];
48
+ }
@@ -14,6 +14,11 @@
14
14
  // asks again (refresh) only when the item's server signature changed
15
15
  // (+sigOf+: working_set.js serverSig): mid-turn the route answers the
16
16
  // running turn's view as of its last step.
17
+ //
18
+ // A memory's text and a whole read of an .md file show rendered, the whole
19
+ // text in the peek's scroll box, once their HTML is in the reader's cache
20
+ // (+md+: ws_markdown.js createRenderCache); else, and without +md+, the
21
+ // first lines as source.
17
22
 
18
23
  import { html, nothing } from "./vendor/lit-html.js";
19
24
  import { createLatest } from "./latest.js";
@@ -21,6 +26,11 @@ import { diffCounts, diffTemplate } from "./diff_view.js";
21
26
  import { callTemplate, linesTemplate, textTemplate } from "./ws_cards.js";
22
27
  import { countsText, eventTag, eventWords, peekOf } from "./ws_timeline.js";
23
28
  import { olderAnswer } from "./ws_item_sig.js";
29
+ import { peekMarkdownTemplate, peekText, renderableEvent } from "./ws_markdown.js";
30
+
31
+ // No events while a turn runs (the answer's +running+): the read is in the
32
+ // step whose tool batch hasn't ended.
33
+ const STEP_RUNNING = "chi read this in the step still running. It shows here when that step's tools finish.";
24
34
 
25
35
  // The popover's width while a row is peeked (it is 420 otherwise).
26
36
  export const PEEK_WIDTH = 520;
@@ -28,8 +38,9 @@ export const PEEK_WIDTH = 520;
28
38
  // +session()+: the open session's id; +getItem(id, kind, key, opts)+: the item
29
39
  // route's answer; +sigOf(item)+: its server signature (undefined: always ask
30
40
  // again); +onChange()+: the peek's content changed (the popover redraws and
31
- // places itself again).
32
- export function createPeek({ session, getItem, sigOf = () => undefined, onChange = () => {} }) {
41
+ // places itself again); +md+: the reader's markdown cache ({html(text)}),
42
+ // null: none.
43
+ export function createPeek({ session, getItem, sigOf = () => undefined, onChange = () => {}, md = null }) {
33
44
  let openId = null;
34
45
  let item = null;
35
46
  let data = null;
@@ -98,16 +109,22 @@ export function createPeek({ session, getItem, sigOf = () => undefined, onChange
98
109
  if (!data) return html`<div class="ws-peek" role="region" aria-label="What chi has"><div class="ws-peek-note">Loading…</div></div>`;
99
110
  const events = data.events || [];
100
111
  const peek = peekOf(events);
101
- if (!peek) return html`<div class="ws-peek" role="region" aria-label="What chi has"><div class="ws-peek-note">Nothing of it in the conversation yet.</div></div>`;
112
+ if (!peek) return html`<div class="ws-peek" role="region" aria-label="What chi has"><div class="ws-peek-note">${data.running ? STEP_RUNNING : "Nothing of it in the conversation yet."}</div></div>`;
102
113
  const { event } = peek;
103
114
  const counts = peek.kind === "diff" && event.diff?.text && !event.diff.error && !event.diff.skipped ? diffCounts(event.diff) : "";
104
115
  const after = peek.after ? html`<span class="ws-peek-after">then ${eventWords(peek.after)} at ${eventTag(peek.after, row)}</span>` : nothing;
105
116
  const gone = event.sent === false ? html`<span class="wsr-pill gone">chi no longer has this</span>` : nothing;
106
117
  const head = html`<div class="ws-peek-h"><span class="ws-peek-t">latest · ${eventWords(event)} at ${eventTag(event, row)}</span>${counts ? html`<span class="ws-peek-c">${counts}</span>` : nothing}${gone}${after}</div>`;
107
118
  let body;
108
- if (peek.kind === "diff") body = diffTemplate(event.diff, { fold: 12 });
119
+ const markdown = peek.kind !== "diff" && renderableEvent(event, row);
120
+ const rendered = md && markdown ? peekMarkdownTemplate(event.text, md) : null;
121
+ if (rendered) body = rendered;
122
+ else if (peek.kind === "diff") body = diffTemplate(event.diff, { fold: 12 });
109
123
  else if (peek.kind === "lines") body = linesTemplate(peek.rows, { fold: Infinity });
110
- else body = textTemplate(peek.rows.map((r) => r.text).join("\n"), { fold: Infinity });
124
+ else {
125
+ const text = peek.rows.map((r) => r.text).join("\n");
126
+ body = textTemplate(markdown ? peekText(text) : text, { fold: Infinity });
127
+ }
111
128
  const words = countsText(events, data.counts);
112
129
  const foot = html`<div class="ws-peek-f"><button type="button" class="ws-peek-open" data-ws="timeline" data-ws-id=${openId}>Open the timeline${words ? html`<span class="ws-peek-n"> · ${words}</span>` : nothing}</button>${callTemplate(event, row)}</div>`;
113
130
  return html`<div class="ws-peek" role="region" aria-label="What chi has">${head}<div class="ws-peek-b">${body}</div>${foot}</div>`;