samagotchi 0.175.0 → 0.177.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 (71) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +50 -1
  3. data/bin/chi +1 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/cli.md +11 -4
  6. data/docs/configuration.md +1 -0
  7. data/docs/internals/bridge.md +2 -2
  8. data/docs/internals/engine.md +2 -2
  9. data/docs/internals/participants.md +13 -6
  10. data/docs/internals/prompt-caching.md +3 -0
  11. data/docs/internals/web-frontend.md +38 -11
  12. data/docs/internals/working-set.md +77 -6
  13. data/docs/sessions.md +3 -2
  14. data/lib/samagotchi/bridge.rb +11 -4
  15. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  16. data/lib/samagotchi/config.rb +3 -0
  17. data/lib/samagotchi/engine/models.rb +11 -0
  18. data/lib/samagotchi/engine/session.rb +9 -0
  19. data/lib/samagotchi/engine.rb +1 -0
  20. data/lib/samagotchi/engine_snapshots.rb +3 -0
  21. data/lib/samagotchi/participant_uploads.rb +14 -1
  22. data/lib/samagotchi/prompt_part.rb +66 -0
  23. data/lib/samagotchi/session.rb +10 -1
  24. data/lib/samagotchi/system_prompt.rb +191 -12
  25. data/lib/samagotchi/version.rb +1 -1
  26. data/lib/samagotchi/web/app.rb +15 -2
  27. data/lib/samagotchi/web/participant_images.rb +16 -12
  28. data/lib/samagotchi/web/participant_show.rb +1 -1
  29. data/lib/samagotchi/web/participant_view.rb +27 -1
  30. data/lib/samagotchi/web/public/app.js +7 -2
  31. data/lib/samagotchi/web/public/composer_fold.js +3 -1
  32. data/lib/samagotchi/web/public/composer_grip.js +18 -10
  33. data/lib/samagotchi/web/public/composer_mount.js +17 -6
  34. data/lib/samagotchi/web/public/ctx_tokens.js +33 -0
  35. data/lib/samagotchi/web/public/index.html +43 -9
  36. data/lib/samagotchi/web/public/restore.js +3 -1
  37. data/lib/samagotchi/web/public/session_fields.js +10 -4
  38. data/lib/samagotchi/web/public/session_prefs.js +92 -0
  39. data/lib/samagotchi/web/public/session_state.js +14 -1
  40. data/lib/samagotchi/web/public/session_store.js +1 -1
  41. data/lib/samagotchi/web/public/session_sync.js +3 -0
  42. data/lib/samagotchi/web/public/session_view.js +33 -3
  43. data/lib/samagotchi/web/public/stage_asking.js +20 -11
  44. data/lib/samagotchi/web/public/stage_cloud.js +3 -2
  45. data/lib/samagotchi/web/public/stage_missing.js +3 -5
  46. data/lib/samagotchi/web/public/stage_model.js +2 -1
  47. data/lib/samagotchi/web/public/stage_view.js +6 -1
  48. data/lib/samagotchi/web/public/stage_view_memory.js +76 -0
  49. data/lib/samagotchi/web/public/stream_handlers.js +10 -5
  50. data/lib/samagotchi/web/public/tokens.css +2 -2
  51. data/lib/samagotchi/web/public/turn_events.js +1 -1
  52. data/lib/samagotchi/web/public/working_set.js +51 -7
  53. data/lib/samagotchi/web/public/working_set_rail.js +22 -7
  54. data/lib/samagotchi/web/public/working_set_view.js +188 -58
  55. data/lib/samagotchi/web/public/ws_reader.js +2 -0
  56. data/lib/samagotchi/web/public/ws_sections.js +251 -0
  57. data/lib/samagotchi/web/server.rb +6 -2
  58. data/lib/samagotchi/web/session_show.rb +13 -2
  59. data/lib/samagotchi/worker/child_side.rb +123 -0
  60. data/lib/samagotchi/worker/command_queue.rb +350 -0
  61. data/lib/samagotchi/worker/leave.rb +286 -0
  62. data/lib/samagotchi/worker/scratch.rb +99 -0
  63. data/lib/samagotchi/worker/signal_grace.rb +96 -0
  64. data/lib/samagotchi/worker/startup.rb +92 -0
  65. data/lib/samagotchi/worker/wake_turns.rb +190 -0
  66. data/lib/samagotchi/worker.rb +25 -1065
  67. data/lib/samagotchi/worker_exit_claim.rb +12 -0
  68. data/lib/samagotchi/working_set.rb +32 -4
  69. data/lib/samagotchi/working_set_command.rb +3 -2
  70. data/lib/samagotchi/working_set_steer.rb +21 -3
  71. metadata +13 -1
@@ -38,14 +38,19 @@
38
38
  // on its tool rows, live (stampRows) and reloaded (stampHistory); a jump
39
39
  // finds the row by them, never by a row key.
40
40
  import { html, nothing, render, svg } from "./vendor/lit-html.js";
41
+ import { repeat } from "./vendor/directives/repeat.js";
41
42
  import { createChipPopover, SHEET_SHARE, SHEET_TALL } from "./chip_popover.js";
42
43
  import { stillOn } from "./latest.js";
43
44
  import { showRow } from "./refs.js";
44
45
  import { PEEK_WIDTH } from "./ws_peek.js";
46
+ import { read as readPref, write as writePref } from "./session_prefs.js";
45
47
  import {
46
- addedItems, addLine, BUDGETS, dropRefusal, fold, footprint, footprintText, forgetOn, GLYPHS, INVERSE, isFresh, itemsOfTurn, labelText,
47
- labelTitle, newerSnapshot, opsText, overlay, parseSteerLine, pendingSteers, pinnable, refreshable, serverAddIds, sessionItems, STEER_OPS,
48
- steerId, steerLine, stepRange, stepTag, tokensText, undroppable,
48
+ foldedSections, headItems, headLine, headSections, heldTwice, heldTwiceNote, lensTouched, memoryPartWords, promptKeys, startTokensText, WS_SECTION_FOLD,
49
+ } from "./ws_sections.js";
50
+ import {
51
+ addedItems, addLine, bodySections, BUDGETS, dropRefusal, footprint, footprintText, forgetOn, GLYPHS, INVERSE, isFresh, itemKey, itemsOfTurn, labelText,
52
+ labelTitle, lensItem, newerSnapshot, opsText, overlay, parseSteerLine, pendingSteers, pinnable, refreshable, serverAddIds, sessionItems, STEER_OPS,
53
+ steerId, steerLine, stepRange, stepTag, tokensText, turnLens, undroppable,
49
54
  } from "./working_set.js";
50
55
 
51
56
  // The popover's files fold to this many lines (groups open in place, one at
@@ -148,7 +153,8 @@ function memberName(item, group) {
148
153
 
149
154
  // +historyEl+: where finished turns are; +stageRoot()+: the stage (the live
150
155
  // turn's block); +state()+: the open session's fields (session_state.js:
151
- // ctxPct and the preloaded, muted and used memories); +session()+: its id;
156
+ // ctxPct, ctxTokens, ctxWindow, the prompt's parts and the preloaded,
157
+ // prompt-note, muted and used memories); +session()+: its id;
152
158
  // +infoEl+: the session bar's line (the chip's popover is delegated there);
153
159
  // +onChange()+: the chip's count or dot changed (app.js updateInfoBar).
154
160
  // +getWorkingSet(id)+: the server's projection (data.js; null: none asked).
@@ -166,10 +172,13 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
166
172
  let live = null;
167
173
  let seenAt = () => undefined;
168
174
  let openedCount = 0;
169
- // The open view: its scope ("turn" / "session"), its turn, the group open
170
- // in it.
171
- let view = { scope: "session", turn: null };
175
+ // The open view: its lens (null: the session; a turn's index: that turn
176
+ // lit on the session's list), the group open in it.
177
+ let lens = null;
172
178
  let openGroup = null;
179
+ // What the drawn list shows of the context's tokens (tokenText): a chunk's
180
+ // new count redraws it only when that text changes.
181
+ let shownTokens = null;
173
182
  // The server's snapshot ({items, at}) and the session it is of; what
174
183
  // redraws the rail when it changes. +events+ counts the events taken, so
175
184
  // a GET knows whether one came while it was on its way.
@@ -187,26 +196,29 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
187
196
  const sessionSet = () => {
188
197
  const st = state();
189
198
  const set = sessionItems({
190
- turns: turns.map((t) => t.items), live: live?.items || [], preloaded: st.preloadedMemories, muted: st.mutedMemories,
199
+ turns: turns.map((t) => t.items), live: live?.items || [], preloaded: st.preloadedMemories, notes: st.promptNotes, muted: st.mutedMemories,
191
200
  used: st.usedMemories,
192
201
  });
193
202
  return { items: lit(set.items), muted: set.muted };
194
203
  };
204
+ // The turns the lens steps through: the finished ones and the running one.
205
+ const lastTurn = () => turns.length + (live ? 1 : 0) - 1;
206
+ const curLens = () => (lens !== null && lens > lastTurn() ? null : lens);
195
207
  const turnItems = (t) => lit(live && t === live.ordinal ? live.items : turns[t]?.items || []);
196
208
  const promptOf = (t) => (live && t === live.ordinal ? live.prompt : turns[t]?.prompt || "");
197
209
 
198
210
  const popover = createChipPopover({
199
211
  id: "workingSetPopover", className: "ctx-popover ws-popover", width: () => (peek?.any() ? PEEK_WIDTH : 420), el: infoEl, anchor: ".ws-chip",
200
212
  openers: ".ws-chip, .ts-ws, .ws-foot", sheet: true, label: "Working set", sheetShare: () => (peek?.any() ? SHEET_TALL : SHEET_SHARE),
201
- // The chip opens the session's scope; the rail and a footprint set
202
- // theirs before they open it.
213
+ // The chip opens the session lens; the rail and a footprint set theirs
214
+ // before they open it.
203
215
  summary: (anchor) => {
204
216
  if (anchor?.matches?.(".ws-chip")) {
205
- view = { scope: "session", turn: live ? live.ordinal : turns.length - 1 };
217
+ lens = null;
206
218
  // Opened: the chip's dot goes (chip()).
207
219
  queueMicrotask(onChange);
208
220
  }
209
- return { view };
221
+ return { lens };
210
222
  },
211
223
  session,
212
224
  // Opened: the server's set asked again (a file changed while the
@@ -273,13 +285,29 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
273
285
  return { pill: nothing, buttons: buttons.length ? buttons : nothing };
274
286
  }
275
287
 
276
- function rowTemplate(item, { session: inSession, group = null, now, pend = new Map(), forget = false }) {
277
- const fresh = isFresh(seenAt(item), now);
278
- const tag = stepTag(item, { session: inSession });
288
+ // +touched+ (a turn lens): the turn's items by key. A row it holds is lit
289
+ // and draws the turn's `at` and ops (its step tag, its words) on the
290
+ // session item's state, tokens and actions; the others dim.
291
+ // +start+: a "From the start" memory row (ws_sections.js): its part's
292
+ // words and tokens, no "prompt" tag (the section says it), "held twice"
293
+ // when it was read again, and the note in a turn lens that read it.
294
+ function rowTemplate(row0, { session: inSession, group = null, now, pend = new Map(), forget = false, touched = null, start = false }) {
295
+ // +row0+ is the session's item: its state, tokens, actions, peek. +item+ is
296
+ // what the lens shows of it: the turn's `at`, ops and count (the step tag,
297
+ // the words, the edited mark) and nothing else.
298
+ const item = touched ? lensItem(row0, touched) : row0;
299
+ const lensClass = touched && !row0.added ? (touched.has(itemKey(row0)) ? " lit" : " dim") : "";
300
+ // A dimmed row's entry is the session's (its first, "t1·s1"); a lit row's the turn's.
301
+ const whole = inSession || lensClass === " dim";
302
+ const fresh = isFresh(seenAt(row0), now);
303
+ // A lit preloaded memory the turn read shows the turn's step, not "prompt".
304
+ const tag = stepTag(lensClass === " lit" && item.at ? { ...item, preloaded: false } : item, { session: whole });
305
+ const note = start && touched ? heldTwiceNote(row0, touched.get(itemKey(row0))) : "";
279
306
  // An added row's words: what it is (a phone's tap on them opens its strip).
280
- const words = item.added ? "added" : `${opsText(item)}${fresh ? " · just now" : ""}`;
307
+ const what = start ? [memoryPartWords(row0), row0.state && row0.state !== "live" ? row0.state : ""].filter(Boolean).join(" · ") : opsText(item);
308
+ const words = item.added ? "added" : `${what}${fresh ? " · just now" : ""}`;
281
309
  const glyph = item.added ? "+" : item.muted ? GLYPHS.muted : fresh ? "●" : GLYPHS[item.kind] || "";
282
- const name = memberName(item, group);
310
+ const name = memberName(row0, group);
283
311
  const full = item.kind === "file" ? item.path || item.key : item.kind === "url" ? item.url || item.key : item.key;
284
312
  let nameEl;
285
313
  if (item.kind === "file") {
@@ -291,29 +319,101 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
291
319
  nameEl = html`<span class="t" title=${full}>${name}</span>`;
292
320
  }
293
321
  let tagEl = nothing;
294
- if (tag === "prompt") tagEl = html`<span class="ws-step p" title="preloaded into the system prompt">prompt</span>`;
322
+ if (start && inSession && heldTwice(row0)) tagEl = html`<span class="ws-twice" title="already in the prompt and read again: held twice">held twice</span>`;
323
+ else if (tag === "prompt") tagEl = start ? nothing : html`<span class="ws-step p" title="in the system prompt">prompt</span>`;
295
324
  else if (tag) {
296
- const prompt = inSession ? promptOf(item.at.turn) : "";
297
- const where = inSession ? `turn ${item.at.turn + 1}${prompt ? ` (${prompt})` : ""}, step ${item.at.step + 1}` : `step ${item.at.step + 1}`;
298
- tagEl = html`<button type="button" class=${`ws-step${item.kind === "memory" ? " p" : ""}`} data-ws="jump" data-at=${atAttr(item.at)} title=${`entered at ${where}: go to the call`}>${tag}</button>`;
325
+ const prompt = whole ? promptOf(item.at.turn) : "";
326
+ const where = whole ? `turn ${item.at.turn + 1}${prompt ? ` (${prompt})` : ""}, step ${item.at.step + 1}` : `step ${item.at.step + 1}`;
327
+ 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>`;
299
328
  }
300
329
  const edited = item.kind === "file" && item.ops.includes("edit");
301
- const state = item.state && item.state !== "live" ? ` ${item.state}` : "";
302
- const tokens = tokensText(item.tokens);
303
- const id = steerId(item);
304
- const { pill, buttons } = rowActions(item, pend, forget);
305
- const pin = item.pinned ? html`<span class="ws-pin" title="pinned: the model's forget_outputs refuses it">📌</span>` : nothing;
330
+ const state = row0.state && row0.state !== "live" ? ` ${row0.state}` : "";
331
+ const tokens = start ? startTokensText(row0) : tokensText(row0.tokens);
332
+ const id = steerId(row0);
333
+ const { pill, buttons } = rowActions(row0, pend, forget);
334
+ const pin = row0.pinned ? html`<span class="ws-pin" title="pinned: the model's forget_outputs refuses it">📌</span>` : nothing;
306
335
  const isPending = pill !== nothing;
307
336
  const strip = stripOpen === id && buttons !== nothing;
308
337
  const open = item.kind === "file" ? html`<button type="button" class="ws-act-b open ref" data-ref-kind="file" data-ref-path=${item.ref?.path || full}>open</button>` : nothing;
309
338
  // The ▸ that peeks at what chi has of it (the owner's: +peek+).
310
- const canPeek = peek && peekable(item);
339
+ const canPeek = peek && peekable(row0);
311
340
  const peeked = canPeek && peek.isOpen(id);
312
341
  const toggle = canPeek ? html`<button type="button" class="ws-peek-toggle" data-ws="peek" data-ws-id=${id} aria-expanded=${String(peeked)} aria-label=${`What chi has of ${name}`} title="What chi has of it">${peeked ? "▾" : "▸"}</button>` : nothing;
313
- const row = html`<div class=${`ws-row ${item.kind}${item.added ? " added" : ""}${fresh ? " fresh" : ""}${item.muted ? " muted" : ""}${group ? " member" : ""}${state}${isPending ? " pending" : ""}${strip ? " strip-open" : ""}${peeked ? " peeked" : ""}${canPeek ? " peekable" : ""}`} data-ws-id=${id}>${toggle}<span class="k">${glyph}</span>${nameEl}${pin}${edited ? html`<span class="e">✎</span>` : nothing}<span class="st">${words}</span>${pill}${tokens ? html`<span class="tk" title=${`about ${item.tokens} tokens of it are sent`}>${tokens}</span>` : nothing}${tagEl}${buttons !== nothing ? html`<span class="ws-act">${buttons}</span>` : nothing}</div>`;
342
+ const row = html`<div class=${`ws-row ${item.kind}${row0.added ? " added" : ""}${fresh ? " fresh" : ""}${row0.muted ? " muted" : ""}${group ? " member" : ""}${state}${isPending ? " pending" : ""}${strip ? " strip-open" : ""}${peeked ? " peeked" : ""}${canPeek ? " peekable" : ""}${note ? " twice" : ""}${lensClass}`} data-ws-id=${id}>${toggle}<span class="k">${glyph}</span>${nameEl}${pin}${edited ? html`<span class="e">✎</span>` : nothing}<span class="st">${words}</span>${pill}${tokens ? html`<span class="tk" title=${start ? "about its tokens in the prompt, + its reads'" : `about ${row0.tokens} tokens of it are sent`}>${tokens}</span>` : nothing}${tagEl}${buttons !== nothing ? html`<span class="ws-act">${buttons}</span>` : nothing}</div>`;
314
343
  // One template either way, so the tapped row stays the same node (a
315
344
  // click outside the popover closes it).
316
- return html`${row}${strip ? html`<div class="ws-strip">${buttons}${open}</div>` : nothing}${peeked ? peek.template(item) : nothing}`;
345
+ const noteEl = note ? html`<div class="ws-note twice" role="note">${note}</div>` : nothing;
346
+ return html`${row}${noteEl}${strip ? html`<div class="ws-strip">${buttons}${open}</div>` : nothing}${peeked ? peek.template(row0) : nothing}`;
347
+ }
348
+
349
+ // A prompt part's row: its label, its sub, its tokens; read-only, no
350
+ // peek. Never touched by a turn: dim in a turn lens.
351
+ function partRowTemplate(row, { touched = null }) {
352
+ const lensClass = touched ? " dim" : "";
353
+ const tokens = tokensText(row.partTokens);
354
+ return html`<div class=${`ws-row ${row.kind}${lensClass}`} data-ws-part=${row.key}><span class="k"></span><span class="t" title=${row.sub ? `${row.label}: ${row.sub}` : row.label}>${row.label}</span>${row.sub ? html`<span class="st">${row.sub}</span>` : nothing}${tokens ? html`<span class="tk" title="about its tokens in every request">${tokens}</span>` : nothing}</div>`;
355
+ }
356
+
357
+ // The Conversation section as one row at section level ("Conversation ·
358
+ // N turns ~X"): nothing to fold, read-only, never touched by a turn (dim
359
+ // in a turn lens).
360
+ function talkTemplate(section, { touched = null }) {
361
+ const row = section.rows[0];
362
+ return html`<div class=${`ws-row talk ws-sec-row${touched ? " dim" : ""}`} data-ws-part=${row.key}><span class="k"></span><span class="t">${section.title}</span>${row.sub ? html`<span class="n">· ${row.sub}</span>` : nothing}<span class="tk" title="about the conversation's tokens: the context's less the prompt's parts and the held reads">${tokensText(section.tokens)}</span></div>`;
363
+ }
364
+
365
+ // A head section's row: a part or a memory part.
366
+ const startRow = (row, opts) => (row.kind === "memory" ? rowTemplate(row, { ...opts, start: true }) : partRowTemplate(row, opts));
367
+ const isLit = (item, opts) => !!opts.touched && opts.touched.has(itemKey(item));
368
+
369
+ // The head view's sections (ws_sections.js headSections): each header
370
+ // folds (per session, session_prefs.js WS_SECTION_FOLD); folded, a section
371
+ // shows only the rows the lens lights. Conversation is one row, no header,
372
+ // no fold (a stored fold naming it is ignored).
373
+ function headTemplate(sections, opts, folded) {
374
+ return repeat(sections, (section) => section.key, (section) => {
375
+ if (section.key === "talk") return html`<div class="ws-sec talk">${talkTemplate(section, opts)}</div>`;
376
+ const open = !folded.has(section.key);
377
+ const tokens = tokensText(section.tokens);
378
+ 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>`;
379
+ let body;
380
+ if (section.inner) {
381
+ body = open
382
+ ? html`${section.inner.length ? nothing : html`<div class="ctx-pop-meta">Nothing read yet: the files, memories and URLs this session's turns read show here.</div>`}${section.inner.map((sub) => html`<div class="ctx-pop-meta ws-sub">${sub.title}${sub.meta ? ` · ${sub.meta}` : ""}</div>${labelsTemplate(sub.labels, opts)}${sub.muted.map((m) => rowTemplate(m, opts))}`)}`
383
+ : section.inner.flatMap((sub) => sub.labels.flatMap((l) => l.members)).filter((m) => isLit(m, opts)).map((m) => rowTemplate(m, opts));
384
+ } else {
385
+ body = (open ? section.rows : section.rows.filter((r) => r.kind === "memory" && isLit(r, opts))).map((r) => startRow(r, opts));
386
+ }
387
+ return html`<div class=${`ws-sec ${section.key}${open ? "" : " folded"}`}>${head}${body}</div>`;
388
+ });
389
+ }
390
+
391
+ // The line under the header, by lens: a turn lens has its touched line
392
+ // (draw's); the session lens the head line ("in chi's head now · ~X of
393
+ // Y") with parts and the context's tokens, else the size line ("N items ·
394
+ // ctx N %"), so the list never lacks a size. The header itself has none.
395
+ function lensLines(st, set, head, inSession) {
396
+ if (!inSession) return { line: "", size: "" };
397
+ const line = head ? headLine(st.ctxTokens, st.ctxWindow) : "";
398
+ if (line) return { line, size: "" };
399
+ const pct = Number.isFinite(st.ctxPct) ? ` · ctx ${Math.round(st.ctxPct)} %` : "";
400
+ return { line: "", size: `${set.items.length} item${set.items.length === 1 ? "" : "s"}${pct}` };
401
+ }
402
+
403
+ // The text the list shows of the context's tokens: the line under the
404
+ // header (the head line or the size line) and the conversation row's tokens.
405
+ function tokenText({ line, size }, head) {
406
+ const talk = head?.find((s) => s.key === "talk");
407
+ return `${line}|${size}|${talk ? tokensText(talk.tokens) : ""}`;
408
+ }
409
+
410
+ // The session's folded sections, and a toggle of one.
411
+ const foldedNow = () => foldedSections(readPref(WS_SECTION_FOLD, session(), "[]"));
412
+ function toggleSection(key) {
413
+ const folded = foldedNow();
414
+ if (folded.has(key)) folded.delete(key);
415
+ else folded.add(key);
416
+ writePref(WS_SECTION_FOLD, session(), JSON.stringify([...folded]));
317
417
  }
318
418
 
319
419
  // A section's labels: leaves as rows, groups as an opener row and, open,
@@ -322,40 +422,48 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
322
422
  return labels.map((label) => {
323
423
  if (label.type === "leaf") return rowTemplate(label.members[0], opts);
324
424
  const open = openGroup === label.id;
425
+ // A folded group still shows the members the lens lights.
426
+ const lit = opts.touched ? label.members.filter((m) => opts.touched.has(itemKey(m))) : [];
427
+ const lensClass = opts.touched ? (lit.length ? " lit" : " dim") : "";
325
428
  const state = label.state && label.state !== "live" ? ` ${label.state}` : "";
326
- const head = html`<button type="button" class=${`ws-row ws-group-head ${label.kind}${state}`} data-ws="group" data-id=${label.id} aria-expanded=${String(open)} title=${labelTitle(label)}><span class="k">${open ? "▾" : "▸"}</span><span class="t">${label.glyph ? `${label.glyph} ` : ""}${label.text}</span>${label.count ? html`<span class="n">· ${label.count}</span>` : nothing}${label.edited ? html`<span class="e">✎${label.edited}</span>` : nothing}${label.cut ? html`<span class="c" title=${`${label.cut} cut (forgotten or dropped)`}>✂${label.cut}</span>` : nothing}<span class="chev">${open ? "close" : "open"}</span></button>`;
429
+ const head = html`<button type="button" class=${`ws-row ws-group-head ${label.kind}${state}${lensClass}`} data-ws="group" data-id=${label.id} aria-expanded=${String(open)} title=${labelTitle(label)}><span class="k">${open ? "▾" : "▸"}</span><span class="t">${label.glyph ? `${label.glyph} ` : ""}${label.text}</span>${label.count ? html`<span class="n">· ${label.count}</span>` : nothing}${label.edited ? html`<span class="e">✎${label.edited}</span>` : nothing}${label.cut ? html`<span class="c" title=${`${label.cut} cut (forgotten or dropped)`}>✂${label.cut}</span>` : nothing}<span class="chev">${open ? "close" : "open"}</span></button>`;
327
430
  // A group drops its members that can be, not pending already.
328
431
  const droppable = sendLine ? label.members.filter((m) => dropRefusal(m) === "" && !opts.pend.has(steerId(m))) : [];
329
432
  const act = droppable.length ? html`<span class="ws-act">${actButton("drop", droppable, { label: `drop ${droppable.length}`, title: "send stubs instead of their reads from the next turn's start" })}</span>` : nothing;
330
- return html`<div class="ws-ghead">${head}${act}</div>${open ? label.members.map((m) => rowTemplate(m, { ...opts, group: label })) : nothing}`;
433
+ return html`<div class="ws-ghead">${head}${act}</div>${(open ? label.members : lit).map((m) => rowTemplate(m, { ...opts, group: label }))}`;
331
434
  });
332
435
  }
333
436
 
334
437
  function draw() {
335
438
  const now = Date.now();
336
439
  const st = state();
337
- const inSession = view.scope === "session";
338
- const set = inSession ? sessionSet() : { items: turnItems(view.turn), muted: [] };
339
- const files = set.items.filter((i) => i.kind === "file");
340
- const memories = set.items.filter((i) => i.kind === "memory");
341
- const urls = set.items.filter((i) => i.kind === "url");
440
+ // A lens past the last turn (a seed between a live turn's events) shows the
441
+ // session and is kept: the turn coming back lights it again.
442
+ const at = curLens();
443
+ const inSession = at === null;
444
+ const set = sessionSet();
342
445
  const pend = pending();
343
446
  const forget = forgetOn(st.llmContext);
344
- const opts = { session: inSession, now, pend, forget };
345
- const fileLabels = fold(files, POP_BUDGET).labels;
346
- // Memories are rows of their own; past the budget one group that opens.
347
- const memoryLabels = fold(memories, memories.length > POP_BUDGET ? 1 : Infinity).labels;
348
- const preloaded = memories.filter((m) => m.preloaded).length;
349
- const memMeta = [`${memories.length - preloaded} used`, preloaded ? `${preloaded} preloaded` : "", set.muted.length ? `${set.muted.length} muted` : ""].filter(Boolean).join(" · ");
350
- const turnLabel = view.turn !== null && view.turn >= 0 ? `turn ${view.turn + 1}` : "this turn";
351
- const pct = Number.isFinite(st.ctxPct) ? ` · ctx ${Math.round(st.ctxPct)} %` : "";
447
+ const last = lastTurn();
448
+ // The head view (no parts: today's list); a turn's read of `system/x`
449
+ // lights the start row of `x`, and a prompt memory is never new.
450
+ const head = headSections(set, POP_BUDGET, { parts: st.promptParts, ctxTokens: st.ctxTokens, turns: last + 1, inTurn: !inSession });
451
+ const inPrompt = promptKeys(head);
452
+ const picked = inSession ? null : turnLens(headItems(set, st.promptParts).filter((item) => !inPrompt.has(itemKey(item))), turnItems(at), at);
453
+ const opts = { session: inSession, now, pend, forget, touched: lensTouched(head, picked?.touched || null) };
454
+ const lines = lensLines(st, set, head, inSession);
455
+ const { line, size } = lines;
456
+ const sections = head ? [] : bodySections(set, POP_BUDGET);
457
+ shownTokens = tokenText(lines, head);
458
+ const turnLabel = last < 0 ? "turn" : `turn ${(at ?? last) + 1}`;
352
459
  const added = sendLine ? adding(pend) : [];
353
460
  const empty = !set.items.length && !set.muted.length && !added.length;
354
- const tpl = html`<div class="ctx-pop-head"><strong>working set</strong><span class="ws-scope" role="group" aria-label="Scope"><button type="button" class=${!inSession ? "on" : ""} aria-pressed=${String(!inSession)} data-ws="scope" data-scope="turn" ?disabled=${view.turn === null || view.turn < 0}>${turnLabel}</button><button type="button" class=${inSession ? "on" : ""} aria-pressed=${String(inSession)} data-ws="scope" data-scope="session">session</button></span><span class="ctx-pop-kind">${set.items.length} item${set.items.length === 1 ? "" : "s"}${pct}</span>${ringTemplate(st.ctxPct)}<button type="button" class="ctx-pop-close" data-act="close" aria-label="Close">×</button></div>
355
- ${empty ? html`<div class="ctx-pop-meta">Nothing yet: the files, memories and URLs ${inSession ? "this session's turns read" : "this turn reads"} show here.</div>` : nothing}
356
- ${files.length ? html`<div class="ctx-pop-meta">files · ${files.length}</div>${labelsTemplate(fileLabels, opts)}` : nothing}
357
- ${memories.length || set.muted.length ? html`<div class="ctx-pop-meta">memories${memMeta ? ` · ${memMeta}` : ""}</div>${labelsTemplate(memoryLabels, opts)}${set.muted.map((m) => rowTemplate(m, opts))}` : nothing}
358
- ${urls.length ? html`<div class="ctx-pop-meta">urls · ${urls.length}</div>${labelsTemplate(fold(urls, POP_BUDGET).labels, opts)}` : nothing}
461
+ const tpl = html`<div class="ctx-pop-head"><strong>working set</strong><span class="ws-lens" role="group" aria-label="Lens"><button type="button" class=${inSession ? "on" : ""} aria-pressed=${String(inSession)} data-ws="lens" data-lens="session">session</button><button type="button" class="arrow" data-ws="lens" data-lens="prev" aria-label="Previous turn" ?disabled=${last < 0 || at === 0}>‹</button><button type="button" class=${!inSession ? "on" : ""} aria-pressed=${String(!inSession)} data-ws="lens" data-lens="turn" ?disabled=${last < 0}>${turnLabel}</button><button type="button" class="arrow" data-ws="lens" data-lens="next" aria-label="Next turn" ?disabled=${inSession || at >= last}>›</button></span>${ringTemplate(st.ctxPct)}<button type="button" class="ctx-pop-close" data-act="close" aria-label="Close">×</button></div>
462
+ ${picked ? html`<div class="ctx-pop-meta ws-lens-line">turn ${at + 1} touched ${picked.count} · ${picked.fresh} new</div>` : nothing}
463
+ ${line ? html`<div class="ctx-pop-meta ws-head-line">${line}</div>` : nothing}
464
+ ${size ? html`<div class="ctx-pop-meta ws-size-line">${size}</div>` : nothing}
465
+ ${empty && !head ? html`<div class="ctx-pop-meta">Nothing yet: the files, memories and URLs this session's turns read show here.</div>` : nothing}
466
+ ${head ? headTemplate(head, opts, foldedNow()) : repeat(sections, (section) => section.key, (section) => html`<div class="ctx-pop-meta">${section.title}${section.meta ? ` · ${section.meta}` : ""}</div>${labelsTemplate(section.labels, opts)}${section.muted.map((m) => rowTemplate(m, opts))}`)}
359
467
  ${added.length ? html`<div class="ctx-pop-meta">adding · ${added.length}</div>${added.map((it) => rowTemplate(it, opts))}` : nothing}
360
468
  ${pend.size ? html`<div class="ws-pending" role="status"><span class="ws-pending-t">${pend.size} change${pend.size === 1 ? "" : "s"} pending<span class="ws-pending-when"> · apply at the next turn's start</span></span><button type="button" class="ws-act-b" data-ws="undo-all">undo all</button></div>` : nothing}
361
469
  ${sendLine ? html`<form class="ws-add" data-ws="add-form"><input class="ws-add-in" type="text" name="key" placeholder="+ path, memory:ENTRY or URL" aria-label="Add to the working set: a path, memory:ENTRY or a URL" autocomplete="off" autocapitalize="off" spellcheck="false" enterkeyhint="go"><button type="submit" class="ws-act-b">add</button></form>` : nothing}
@@ -391,13 +499,13 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
391
499
  // The item of the list's row +id+ (its steerId): the session's set, the
392
500
  // shown turn's.
393
501
  function rowItem(id) {
394
- return [...sessionSet().items, ...turnItems(view.turn)].find((it) => steerId(it) === id) || null;
502
+ return sessionSet().items.find((it) => steerId(it) === id) || null;
395
503
  }
396
504
 
397
505
  // Posts +op+ for the ids (the items' steer words, from the set).
398
506
  function steer(op, ids) {
399
507
  if (!sendLine || !ids.length) return;
400
- const all = [...sessionSet().items, ...turnItems(view.turn), ...adding()];
508
+ const all = [...sessionSet().items, ...adding()];
401
509
  const byId = new Map(all.map((it) => [steerId(it), it]));
402
510
  const items = ids.map((id) => byId.get(id)).filter(Boolean);
403
511
  if (items.length) Promise.resolve(sendLine(steerLine(op, items, state().dir))).catch(() => {});
@@ -434,9 +542,17 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
434
542
  } else if (act.dataset.ws === "jump") {
435
543
  const at = parseAt(act.dataset.at);
436
544
  if (at) jump(at);
437
- } else if (act.dataset.ws === "scope") {
438
- view = { ...view, scope: act.dataset.scope };
439
- openGroup = null;
545
+ } else if (act.dataset.ws === "lens") {
546
+ const last = lastTurn();
547
+ const to = act.dataset.lens;
548
+ const here = curLens();
549
+ const next = to === "session" ? null : to === "turn" ? here ?? last : to === "prev" ? (here === null ? last : here - 1) : here === null ? null : here + 1;
550
+ if (next !== null && (next < 0 || next > last)) return;
551
+ lens = next;
552
+ draw();
553
+ popover.replace();
554
+ } else if (act.dataset.ws === "section") {
555
+ toggleSection(act.dataset.id);
440
556
  draw();
441
557
  popover.replace();
442
558
  } else if (act.dataset.ws === "group") {
@@ -459,7 +575,7 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
459
575
  return;
460
576
  }
461
577
  if (popover.isOpen() && popover.opener() === foot) return popover.close();
462
- view = { scope: "turn", turn: Number(foot.dataset.wsTurn) };
578
+ lens = Number(foot.dataset.wsTurn);
463
579
  popover.open(foot);
464
580
  }
465
581
  doc.addEventListener("click", footClick);
@@ -546,7 +662,6 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
546
662
  server = null;
547
663
  serverOf = session();
548
664
  } else if (popover.isOpen()) {
549
- if (view.turn !== null && view.turn >= turns.length) view = { scope: "session", turn: turns.length - 1 };
550
665
  popover.refresh();
551
666
  }
552
667
  openedCount = sessionSet().items.length;
@@ -558,6 +673,20 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
558
673
  strategyChanged() {
559
674
  if (popover.isOpen()) popover.refresh();
560
675
  },
676
+ // Prompt memories changed; the open session list reads them from state.
677
+ sessionChanged() {
678
+ if (popover.isOpen()) popover.refresh();
679
+ },
680
+ // The context's tokens or window changed (a chunk, a context_status):
681
+ // the open list redraws only when what it shows of them changes.
682
+ tokensChanged() {
683
+ if (!popover.isOpen()) return;
684
+ const st = state();
685
+ const inSession = curLens() === null;
686
+ const set = sessionSet();
687
+ const head = headSections(set, POP_BUDGET, { parts: st.promptParts, ctxTokens: st.ctxTokens, turns: lastTurn() + 1, inTurn: !inSession });
688
+ if (tokenText(lensLines(st, set, head, inSession), head) !== shownTokens) popover.refresh();
689
+ },
561
690
  // A :working_set_updated event's set ({items, at}).
562
691
  update(snapshot) {
563
692
  events += 1;
@@ -609,12 +738,13 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
609
738
  release() {
610
739
  if (!live) return;
611
740
  live = null;
741
+ if (lens !== null && lens > lastTurn()) lens = null;
612
742
  changed();
613
743
  },
614
744
  // The rail opens the running turn's view.
615
745
  openTurn(anchor) {
616
746
  if (popover.isOpen() && popover.opener() === anchor) return popover.close();
617
- view = { scope: "turn", turn: live ? live.ordinal : turns.length - 1 };
747
+ lens = lastTurn() < 0 ? null : lastTurn();
618
748
  popover.open(anchor);
619
749
  openedCount = sessionSet().items.length;
620
750
  onChange();
@@ -639,7 +769,7 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
639
769
  openList() {
640
770
  const chip = infoEl.querySelector(".ws-chip");
641
771
  if (!chip) return;
642
- view = { scope: "session", turn: live ? live.ordinal : turns.length - 1 };
772
+ lens = null;
643
773
  popover.open(chip);
644
774
  },
645
775
  ctxPct: () => state().ctxPct,
@@ -306,6 +306,8 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
306
306
  open: openItem,
307
307
  close,
308
308
  isOpen: () => !el.hidden,
309
+ // The open item ({kind, key}), null: none (stage_view_memory.js).
310
+ openItem: () => (!el.hidden && open ? { ...open } : null),
309
311
  // The ref ▾ menu's "What chi has" (refs.js): a file ref whose path is
310
312
  // an item of the set.
311
313
  whatChiHas: {