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
@@ -1,9 +1,9 @@
1
1
  import { render } from "./vendor/lit-html.js";
2
2
  import { admitImages, chipName, chipsTemplate, imageFiles } from "./images.js";
3
3
  import { promptHeight } from "./composer_size.js";
4
- import { GRIP_KEY, createComposerGrip } from "./composer_grip.js";
4
+ import { createComposerGrip } from "./composer_grip.js";
5
5
  import { createPromptHistory } from "./prompt_history.js";
6
- import { readStored } from "./storage.js";
6
+ import { COMPOSER_FLOOR, read as readPref } from "./session_prefs.js";
7
7
 
8
8
  // The composer, mounted on a page's markup (composer.css): the message box,
9
9
  // its height (it grows with the text; the grip sets a floor), its image
@@ -26,7 +26,7 @@ import { readStored } from "./storage.js";
26
26
  // +fold+: createComposerGrip's page hooks (session, waiting, allViewOpen,
27
27
  // lightboxOpen, infoBarEl, typeAnywhere).
28
28
  // @return {el, button, chips(), setChips(list), addImageFiles(files), fit(),
29
- // hasDraft(), refreshHistory(), and the grip's isComposerFolded,
29
+ // hasDraft(), refreshHistory(), applyPrefs(), and the grip's isComposerFolded,
30
30
  // openForVisit, focusPrompt, drawFoldControls, newVisit, decideVisit}
31
31
  export function mountComposer({
32
32
  els, minPx, toast, onWrite = () => {}, loadHistory = null, send, keyFirst = () => false, escape = () => false,
@@ -86,10 +86,12 @@ export function mountComposer({
86
86
  });
87
87
 
88
88
  // ── Height: grows with the text; the top-edge grip sets a floor ───────────
89
- // The floor is saved as it was set; fit holds it to half the window it is
90
- // drawn in (composer_size.js), so a floor saved in a bigger window fits this one
89
+ // The floor is saved as it was set, per session (session_prefs.js; the
90
+ // start page's in memory); fit holds it to half the window it is drawn in
91
+ // (composer_size.js), so a floor saved in a bigger window fits this one
91
92
  // and comes back when the window is big again.
92
- let floor = Number(readStored(GRIP_KEY)) || null;
93
+ const savedFloor = () => Number(readPref(COMPOSER_FLOOR, fold?.session?.() || null)) || null;
94
+ let floor = savedFloor();
93
95
 
94
96
  function fit() {
95
97
  const borders = promptEl.offsetHeight - promptEl.clientHeight;
@@ -177,6 +179,14 @@ export function mountComposer({
177
179
  });
178
180
  button.addEventListener("click", () => send({ queue: false }));
179
181
 
182
+ // The open session's own height and fold, read again as its view is drawn
183
+ // (session_view.js applyPrefs).
184
+ function applyPrefs() {
185
+ floor = savedFloor();
186
+ fit();
187
+ composerGrip.applyFolded?.();
188
+ }
189
+
180
190
  return {
181
191
  el: promptEl,
182
192
  button,
@@ -186,6 +196,7 @@ export function mountComposer({
186
196
  fit,
187
197
  hasDraft,
188
198
  refreshHistory,
199
+ applyPrefs,
189
200
  isComposerFolded: composerGrip.isComposerFolded,
190
201
  openForVisit: composerGrip.openForVisit,
191
202
  focusPrompt,
@@ -0,0 +1,33 @@
1
+ // The context's token count, next to its % (ctx.js): what the working set's
2
+ // head view says is in chi's head ("~X of Y") and what its Conversation row is
3
+ // the rest of. The same data ctx.js extractCtxPct reads: a :context_status's
4
+ // usage.estimated_used_tokens, a :generation_chunk's counts.total_tokens; on
5
+ // load the live worker's newest % back into tokens, else the saved
6
+ // timing.context.used_tokens.
7
+ //
8
+ // A module of its own: static JS is cached at unversioned URLs, and a new
9
+ // export on an old module would blank the page.
10
+
11
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
12
+
13
+ // The tokens in context a stream event says (+data+: a :context_status or a
14
+ // :generation_chunk), null when it says none.
15
+ export function ctxTokensOf(data) {
16
+ if (!data || typeof data !== "object") return null;
17
+ const used = num(data.usage?.estimated_used_tokens);
18
+ if (used !== null) return used;
19
+ return num(data.counts?.total_tokens);
20
+ }
21
+
22
+ // On load: the live worker's newest % (+pct+, counted against the window or
23
+ // the smaller budget) as tokens when the window is known, else the saved
24
+ // count (+context+: the session's timing.context). null when neither is.
25
+ export function loadedCtxTokens({ pct = null, context = null, budgetTokens = null } = {}) {
26
+ const window = num(context?.window_tokens);
27
+ if (num(pct) !== null && window && window > 0) {
28
+ const budget = num(budgetTokens);
29
+ const against = budget && budget > 0 ? Math.min(budget, window) : window;
30
+ return Math.round((pct / 100) * against);
31
+ }
32
+ return num(context?.used_tokens);
33
+ }
@@ -1123,12 +1123,41 @@ button.ws-step:hover:not(:disabled){filter:none}@media(hover:hover){button.ws-st
1123
1123
  /* The expanded view (a chip popover; a bottom sheet on a phone). */
1124
1124
  .ws-popover{gap:0}
1125
1125
  .ws-popover .ctx-pop-head{align-items:center;flex-wrap:wrap;margin-bottom:4px}
1126
- .ws-scope{display:inline-flex;gap:2px}
1127
- .ws-scope button{padding:1px 8px;border:1px solid transparent;border-radius:999px;background:transparent;color:var(--text-muted);font-size:11px;line-height:16px}
1128
- .ws-scope button.on{color:var(--text-2);border-color:var(--border-strong);background:var(--bg-raised)}
1129
- .ws-scope button:hover:not(:disabled){filter:none}@media(hover:hover){.ws-scope button:hover:not(:disabled){color:var(--text)}}
1126
+ /* The ring sits by ×, at the header's end (no size text between them now). */
1127
+ .ws-popover .ctx-pop-head>.ws-ring{margin-left:auto}
1128
+ .ws-popover .ctx-pop-head>.ws-ring~.ctx-pop-close{margin-left:0}
1129
+ .ws-lens{display:inline-flex;gap:2px;align-items:center}
1130
+ .ws-lens button{padding:1px 8px;border:1px solid transparent;border-radius:999px;background:transparent;color:var(--text-muted);font-size:11px;line-height:16px}
1131
+ .ws-lens button.arrow{padding:1px 5px}
1132
+ .ws-lens button.on{color:var(--text-2);border-color:var(--border-strong);background:var(--bg-raised)}
1133
+ .ws-lens button:disabled{opacity:.4}
1134
+ .ws-lens button:hover:not(:disabled){filter:none}@media(hover:hover){.ws-lens button:hover:not(:disabled){color:var(--text)}}
1135
+ /* A turn lens (--ws-lens-dim): the rows the turn touched lit, the rest dimmed; the line under the header says how many. */
1136
+ .ws-row.dim{opacity:var(--ws-lens-dim)}
1137
+ .ws-row.lit{background:var(--accent-tint)}
1130
1138
  .ws-popover .ctx-pop-meta{margin-top:6px;color:var(--ws-muted)}
1139
+ .ws-popover .ws-lens-line{color:var(--accent)}
1131
1140
  .ws-popover .ws-hint{margin-top:10px;color:var(--ws-faint)}
1141
+ /* The head view (ws_sections.js): From the start · Read in this session · Conversation, each header folding (per session); prompt parts read-only rows; a prompt memory read again "held twice" in the warn tokens. */
1142
+ .ws-sec-head{display:flex;align-items:center;gap:8px;width:100%;min-height:30px;box-sizing:border-box;margin-top:6px;padding:0 6px;border:0;border-top:1px solid var(--border);border-radius:0;background:transparent;font-family:ui-sans-serif,system-ui,sans-serif;font-size:12px;color:var(--ws-muted);text-align:left;cursor:pointer}
1143
+ .ws-sec-head:hover:not(:disabled){filter:none}@media(hover:hover){.ws-sec-head:hover{background:var(--bg-hover)}}
1144
+ .ws-sec-head .k{flex:none;width:12px;text-align:center;color:var(--ws-faint)}
1145
+ .ws-sec-head .t{font-weight:600;color:var(--text-2)}
1146
+ .ws-sec-head .n{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ws-faint)}
1147
+ .ws-sec-head .tk{flex:none;margin-left:auto;font-size:11px;color:var(--ws-faint);font-variant-numeric:tabular-nums}
1148
+ .ws-sec .ws-sub{margin-top:2px;padding-left:6px}
1149
+ .ws-row.part .t{margin-right:auto;font-family:ui-sans-serif,system-ui,sans-serif}
1150
+ /* Conversation: one row at section level (a section header's look, nothing to fold). */
1151
+ .ws-row.ws-sec-row{height:30px;margin-top:6px;border-top:1px solid var(--border);border-radius:0;font-family:ui-sans-serif,system-ui,sans-serif;font-size:12px}
1152
+ .ws-row.ws-sec-row .t{flex:none;font-weight:600;color:var(--text-2)}
1153
+ .ws-row.ws-sec-row .n{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ws-faint)}
1154
+ .ws-row.ws-sec-row .tk{margin-left:auto}
1155
+ .ws-popover.sheet .ws-row.ws-sec-row{font-size:13px}
1156
+ .ws-twice{flex:none;padding:0 6px;border:1px solid var(--warn-border);border-radius:999px;background:var(--warn-bg);color:var(--warn-text);font-family:ui-sans-serif,system-ui,sans-serif;font-size:10.5px;line-height:15px;white-space:nowrap}
1157
+ .ws-step.twice{color:var(--warn-text);background:var(--warn-bg)}
1158
+ .ws-row.twice.lit{background:var(--warn-bg)}
1159
+ .ws-note{padding:0 6px 4px 26px;font-size:11px;line-height:15px}
1160
+ .ws-note.twice{color:var(--warn-text);background:var(--warn-bg);border-radius:0 0 6px 6px}
1132
1161
  .ws-row{display:flex;align-items:center;gap:8px;width:100%;min-width:0;height:28px;box-sizing:border-box;padding:0 6px;border:0;border-radius:6px;background:transparent;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12.5px;line-height:28px;color:var(--text-2);text-align:left}
1133
1162
  @media(hover:hover){.ws-row:hover{background:var(--bg-hover)}}
1134
1163
  button.ws-row:hover:not(:disabled){filter:none}@media(hover:hover){button.ws-row:hover:not(:disabled){background:var(--bg-hover)}}
@@ -1172,11 +1201,16 @@ button.ws-row:hover:not(:disabled){filter:none}@media(hover:hover){button.ws-row
1172
1201
  .ws-strip{display:flex;gap:8px;padding:2px 6px 6px 26px}
1173
1202
  .ws-strip .ws-act-b{padding:0 14px;font-size:12.5px;line-height:28px;border-radius:6px}
1174
1203
  .ws-popover.sheet{border-radius:14px}
1175
- /* A phone's sheet: the name, the scope and × on the first line, the count and the ring under them. */
1176
- .ws-popover.sheet .ctx-pop-close{order:2}
1177
- .ws-popover.sheet .ctx-pop-head>.ctx-pop-kind{order:3;flex:1 0 calc(100% - 30px)}
1178
- .ws-popover.sheet .ctx-pop-head>.ws-ring{order:4}
1179
- .ws-popover.sheet .ws-row{height:30px;line-height:30px}
1204
+ /* A phone's sheet: one line, the name, the lens, the ring and ×; the size is the line under it. */
1205
+ .ws-popover.sheet .ctx-pop-head{flex-wrap:nowrap;gap:4px}
1206
+ .ws-popover.sheet .ws-lens{flex:none;white-space:nowrap}
1207
+ /* A long turn number (turn 100) shortens the name, never wraps the line. */
1208
+ .ws-popover.sheet .ctx-pop-head strong{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1209
+ /* A phone's sheet: rows and lens buttons 44 px targets; a part row drops its sub text. */
1210
+ .ws-popover.sheet .ws-row{height:44px;line-height:44px}
1211
+ .ws-popover.sheet .ws-sec-head{min-height:44px;font-size:13px}
1212
+ .ws-popover.sheet .ws-lens button{min-height:44px;min-width:44px;padding:1px 4px;font-size:12.5px;white-space:nowrap}
1213
+ .ws-popover.sheet .ws-row.part .st{display:none}
1180
1214
  /* + add: the list's foot (a sheet's last row), one KEY typed; an added item the set doesn't hold yet is a pending row of its own. */
1181
1215
  .ws-add{display:flex;align-items:center;gap:6px;margin-top:8px}
1182
1216
  .ws-add-in{flex:1;min-width:0;height:26px;box-sizing:border-box;padding:0 8px;border:1px dashed var(--border-strong);border-radius:6px;background:transparent;color:var(--text);font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px}
@@ -2,7 +2,7 @@
2
2
  // what goes back into this tab's composer, and when (a restore that comes
3
3
  // before its /turn ack waits for it). Split out of turn_events.js.
4
4
 
5
- import { clientLabel, isOwn, withImages } from "./turn_events.js";
5
+ import { authorOf, clientLabel, isOwn, withImages } from "./turn_events.js";
6
6
 
7
7
  // What a prompt_restored (the worker rolled a failed turn back and handed its
8
8
  // prompt back) does in this tab: `refill` is the text for an empty composer,
@@ -20,6 +20,8 @@ export function restoreAction(event, { myId, sentIds, composerEmpty }) {
20
20
  refill: back ? event.prompt : null,
21
21
  own,
22
22
  label: own ? null : clientLabel(origin.client_id),
23
+ // A participant's failed bubble wears their badge, as their other bubbles do.
24
+ ...authorOf(origin.author),
23
25
  ...(back && event.verify ? { verify: event.verify } : {}),
24
26
  // A Revise turn's draft ({turn_id}): its composer chip comes back.
25
27
  ...(back && event.revises?.turn_id ? { revises: { turn_id: event.revises.turn_id } } : {}),
@@ -34,12 +34,15 @@ export const FIELDS = {
34
34
  firstPreview: { redraws: ["infoBar"], writers: "send_turn.js (the first prompt)" },
35
35
  usedMemories: {
36
36
  source: (d) => list(d.session?.used_memory_names),
37
- redraws: ["infoBar"],
37
+ redraws: ["workingSet", "infoBar"],
38
38
  writers: "setUsedMemories (stream), readTurnEnd; both replace the card too",
39
39
  },
40
- preloadedMemories: { source: (d) => list(d.session?.preloaded_memory_names), redraws: ["infoBar"], writers: "the payload" },
40
+ preloadedMemories: { source: (d) => list(d.session?.preloaded_memory_names), redraws: ["workingSet", "infoBar"], writers: "the payload" },
41
41
  mutedMemories: { source: (d) => list(d.session?.muted_memory_names), redraws: ["infoBar"], writers: "the payload" },
42
- promptNotes: { source: (d) => list(d.session?.prompt_notes), redraws: ["infoBar"], writers: "readTurnEnd" },
42
+ promptNotes: { source: (d) => list(d.session?.prompt_notes), redraws: ["workingSet", "infoBar"], writers: "readTurnEnd" },
43
+ // A tail without the key (an older live worker) keeps the parts the page
44
+ // has: unknown is not none; only a list replaces them.
45
+ promptParts: { source: (d) => list(d.session?.prompt_parts), redraws: ["workingSet"], writers: "readTurnEnd" },
43
46
  parentId: { redraws: ["infoBar"], writers: "the payload" },
44
47
  continues: { redraws: ["infoBar"], writers: "the payload" },
45
48
  verdicts: {
@@ -54,7 +57,10 @@ export const FIELDS = {
54
57
  },
55
58
  createdAt: { redraws: ["infoBar"], writers: "the payload" },
56
59
  ctxPct: { redraws: ["infoBar"], writers: "session_state.js sessionStateFrom (the payload's context_status, else the saved fill), stream_handlers.js (generation_chunk, context_status)" },
57
- ctxWindow: { redraws: ["infoBar"], writers: "stream_handlers.js (generation_started, context_status)" },
60
+ // Changes with almost every chunk: its redraw draws the open list only
61
+ // when the text it shows changes (working_set_view.js tokensChanged).
62
+ ctxTokens: { redraws: ["workingSetTokens"], writers: "session_state.js sessionStateFrom (ctx_tokens.js loadedCtxTokens), stream_handlers.js (generation_chunk, context_status; cleared with ctxPct)" },
63
+ ctxWindow: { redraws: ["workingSetTokens", "infoBar"], writers: "stream_handlers.js (generation_started, context_status)" },
58
64
  ctxWindowSource: { redraws: ["infoBar"], writers: "stream_handlers.js (generation_started, context_status)" },
59
65
  ctxUnknownAfterSwitch: { redraws: ["infoBar"], writers: "stream_handlers.js (generation_started, context_status)" },
60
66
  status: {
@@ -0,0 +1,92 @@
1
+ // A session's own view settings (per browser, localStorage through
2
+ // storage.js): the stage's fold, the composer's dragged height and its fold,
3
+ // the working-set rail's fold, the working-set list's folded sections
4
+ // (ws_sections.js WS_SECTION_FOLD, defined there: a new export here would
5
+ // blank a page holding this module cached). Each is kept under `<key>:<session>`, so what
6
+ // you do to one session's window never shows in another, and a session never
7
+ // set by hand follows the default: the page's own (the stage fold's comes
8
+ // from config, web.stage_collapsed, as <body data-stage-collapsed="1">), else
9
+ // the module's built-in one (+fallback+).
10
+ //
11
+ // With no session (the start page) nothing is written: the value lives in
12
+ // this page's memory only, until a reload.
13
+ //
14
+ // The old global keys (chi_stage_collapsed, chi_composer_floor,
15
+ // chi_composer_collapsed, chi_working_set_collapsed) are neither read nor
16
+ // written, and left in storage as they are.
17
+ //
18
+ // One sweep for all of its keys (sweepSessionPrefs), with an unscoped session
19
+ // list only: these keys record no project root, so a project's list, which
20
+ // knows its own sessions only, sweeps nothing.
21
+ //
22
+ // A module of its own: static JS is cached at unversioned URLs, and a new
23
+ // export on an old module would blank the page.
24
+ import { readStored, removeStored, storedKeys, writeStored } from "./storage.js";
25
+ import { WS_SECTION_FOLD } from "./ws_sections.js";
26
+
27
+ export const STAGE_FOLD = "chi_stage_collapsed";
28
+ export const COMPOSER_FLOOR = "chi_composer_floor";
29
+ export const COMPOSER_FOLD = "chi_composer_collapsed";
30
+ export const WS_RAIL_FOLD = "chi_working_set_collapsed";
31
+ export const PREF_KEYS = [STAGE_FOLD, COMPOSER_FLOOR, COMPOSER_FOLD, WS_RAIL_FOLD, WS_SECTION_FOLD];
32
+
33
+ // The page's defaults: <body>'s data attribute that turns a key on ("1").
34
+ const PAGE_DEFAULTS = { [STAGE_FOLD]: "stageCollapsed" };
35
+
36
+ // The start page's values (no session), in memory only.
37
+ const unsaved = new Map();
38
+
39
+ // The stored key for +key+ in +session+, null without one.
40
+ export function prefKey(key, session) {
41
+ return session ? `${key}:${session}` : null;
42
+ }
43
+
44
+ // The page's default for +key+ ("1" when its body attribute is on), else null.
45
+ function pageDefault(key) {
46
+ const attr = PAGE_DEFAULTS[key];
47
+ if (!attr) return null;
48
+ try {
49
+ return globalThis.document?.body?.dataset?.[attr] === "1" ? "1" : null;
50
+ } catch (_) {
51
+ return null;
52
+ }
53
+ }
54
+
55
+ // +session+'s value for +key+ (a string), else the page's default, else +fallback+.
56
+ export function read(key, session, fallback = null) {
57
+ const own = session ? readStored(prefKey(key, session)) : (unsaved.has(key) ? unsaved.get(key) : null);
58
+ if (own !== null) return own;
59
+ return pageDefault(key) ?? fallback;
60
+ }
61
+
62
+ // +value+ (a string) for +key+ in +session+ only; no session: in memory.
63
+ export function write(key, session, value) {
64
+ if (!session) {
65
+ unsaved.set(key, String(value));
66
+ return;
67
+ }
68
+ writeStored(prefKey(key, session), String(value));
69
+ }
70
+
71
+ // +session+'s own value for +key+ forgotten (it follows the default again);
72
+ // no session: the memory's.
73
+ export function forget(key, session) {
74
+ if (!session) {
75
+ unsaved.delete(key);
76
+ return;
77
+ }
78
+ removeStored(prefKey(key, session));
79
+ }
80
+
81
+ // The session list loaded (+sessions+, each {id}): the keys of sessions not
82
+ // in it go. +scoped+ (a project's list): nothing goes.
83
+ export function sweepSessionPrefs(sessions, { scoped = false } = {}) {
84
+ if (scoped) return;
85
+ const ids = new Set((Array.isArray(sessions) ? sessions : []).map((s) => s?.id).filter(Boolean));
86
+ for (const key of PREF_KEYS) {
87
+ const prefix = `${key}:`;
88
+ for (const stored of storedKeys(prefix)) {
89
+ if (!ids.has(stored.slice(prefix.length))) removeStored(stored);
90
+ }
91
+ }
92
+ }
@@ -5,6 +5,7 @@
5
5
  // shows for the next one).
6
6
 
7
7
  import { savedCtxPct } from "./ctx.js";
8
+ import { loadedCtxTokens } from "./ctx_tokens.js";
8
9
  import { firstPreview, previewForCard } from "./format.js";
9
10
  import { normalizeTiming } from "./timing.js";
10
11
 
@@ -19,6 +20,10 @@ export function emptySessionState() {
19
20
  // The model notes the session's prompt carried (its prompt_notes: name,
20
21
  // scope, chars, digest; the info bar's notes chip).
21
22
  promptNotes: [],
23
+ // The parts of its system prompt as sizes (its prompt_parts: kind, label,
24
+ // chars, tokens, ref; the working set's "From the start"). [] from an
25
+ // older worker or file: no head-view sections.
26
+ promptParts: [],
22
27
  // A delegated session's parent (the info bar's "delegated by" chip).
23
28
  parentId: null,
24
29
  // The previous link of its chain (its `continues`), or null.
@@ -30,6 +35,9 @@ export function emptySessionState() {
30
35
  // times on its day), or null.
31
36
  createdAt: null,
32
37
  ctxPct: null,
38
+ // The tokens in context now (ctx_tokens.js: the count ctxPct is of; the
39
+ // working set's "in chi's head now"), or null.
40
+ ctxTokens: null,
33
41
  // Window the kernel resolved for the running generation (:generation_started).
34
42
  ctxWindow: null,
35
43
  // Where it came from ("server", "config", … "default": chi's guess).
@@ -111,7 +119,8 @@ export function sessionStateFrom(data) {
111
119
  // JSON as context_status, kept per request by the Engine) beats the saved
112
120
  // fill, which is only the last counted turn's; without it, the saved fill.
113
121
  const livePct = s.context_status?.est_pct;
114
- if (typeof livePct === "number" && Number.isFinite(livePct)) {
122
+ const live = typeof livePct === "number" && Number.isFinite(livePct);
123
+ if (live) {
115
124
  state.ctxPct = livePct;
116
125
  } else {
117
126
  // The saved fill, so a reloaded or stopped session shows it before its
@@ -119,6 +128,9 @@ export function sessionStateFrom(data) {
119
128
  const savedPct = savedCtxPct(data.timing?.context, s.llm_context?.budget_tokens);
120
129
  if (savedPct !== null) state.ctxPct = savedPct;
121
130
  }
131
+ // Its tokens, from the same source; left out (kept) when neither says.
132
+ const tokens = loadedCtxTokens({ pct: live ? livePct : null, context: data.timing?.context, budgetTokens: s.llm_context?.budget_tokens });
133
+ if (tokens !== null) state.ctxTokens = tokens;
122
134
  if (data.timing?.context?.window_tokens) {
123
135
  state.ctxWindow = data.timing.context.window_tokens;
124
136
  state.ctxWindowSource = data.timing.context.window_source || null;
@@ -128,6 +140,7 @@ export function sessionStateFrom(data) {
128
140
  state.preloadedMemories = s.preloaded_memory_names || [];
129
141
  state.mutedMemories = s.muted_memory_names || [];
130
142
  state.promptNotes = Array.isArray(s.prompt_notes) ? s.prompt_notes : [];
143
+ state.promptParts = Array.isArray(s.prompt_parts) ? s.prompt_parts : [];
131
144
  state.llmContext = s.llm_context || null;
132
145
  state.thinking = s.thinking || null;
133
146
  // null on a native host (it ignores the level) and from an older worker.
@@ -17,7 +17,7 @@ import { FIELDS, statusWrite } from "./session_fields.js";
17
17
  export const ORDER = [
18
18
  "lists",
19
19
  "paintActive",
20
- "settingsPanel", "workingSetStrategy",
20
+ "settingsPanel", "workingSetStrategy", "workingSet", "workingSetTokens",
21
21
  "featureGates",
22
22
  "composer",
23
23
  "infoBar",
@@ -92,6 +92,9 @@ export function createSessionSync(deps) {
92
92
  // first select): no key, and a removeItem(null) would delete "null".
93
93
  const leftFold = same ? null : foldKey(store.selected);
94
94
  if (leftFold) removeSession(leftFold);
95
+ // What the user opened of its running turn, kept for this tab before the
96
+ // reset below (session_view.js leaveSession; an older one has none).
97
+ deps.view.leaveSession?.();
95
98
  // Its synchronous part in one batch: the active card, the composer and
96
99
  // the bar redraw once, at its end (never across the await).
97
100
  store.batch(() => {
@@ -32,7 +32,9 @@
32
32
  // later: {handlers(), composer(), ownerVerify(), commandList(), initTasks(), resetTurnView()}
33
33
  // the views made after this one, and session_sync.js's resetTurnView
34
34
  //
35
- // @return {forgetSession, renderSessionView, historyOpts, readTurnEnd, endTurnView}
35
+ // @return {forgetSession, renderSessionView, historyOpts, readTurnEnd, endTurnView, leaveSession}
36
+ // leaveSession(): what the user opened of the open session's running turn,
37
+ // kept for this tab (stage_view_memory.js) before select() leaves it
36
38
  // Its own module: new exports go in new modules (web-frontend.md).
37
39
 
38
40
  import { emptySessionState, sessionStateFrom } from "./session_state.js";
@@ -48,6 +50,7 @@ import { turnHistoryNodes } from "./turn_block.js";
48
50
  import { lastActivity } from "./time_gaps.js";
49
51
  import { elementOf, emptyAnswerTemplate } from "./turn_html.js";
50
52
  import { stillOn } from "./latest.js";
53
+ import { applyView, captureView, createStageViewMemory } from "./stage_view_memory.js";
51
54
 
52
55
  export function createSessionView(deps) {
53
56
  const {
@@ -64,6 +67,14 @@ export function createSessionView(deps) {
64
67
  } = page;
65
68
  // The open session's id, for the stale-answer guards (latest.js stillOn).
66
69
  const openId = () => store.selected;
70
+ // What was opened of each session's running turn, in memory (stage_view_memory.js).
71
+ const viewMemory = createStageViewMemory();
72
+ // The session whose read the page drew last (renderSessionView), until forgetSession.
73
+ let drawnId = null;
74
+ function leaveSession(id = store.selected) {
75
+ const turnId = liveTurn.running ? liveTurn.timing.turnId : null;
76
+ viewMemory.leave(id, captureView({ stage: turnDom, turnId, reader: wsPreview }));
77
+ }
67
78
 
68
79
  // Forget everything the page knew about the open session: its fields (the
69
80
  // info bar, composer, command list), the turn on view, its stream and
@@ -74,6 +85,10 @@ export function createSessionView(deps) {
74
85
  // "delegated by" parent, its commands, its card actions) never shows for
75
86
  // the next one, also when the next one's read fails.
76
87
  function forgetSession({ keepVerify = false } = {}) {
88
+ // The drawn session's opened view, kept before the reset: every way off
89
+ // it (select, the start page's clearSelection, a gone session) gets here.
90
+ if (drawnId) leaveSession(drawnId);
91
+ drawnId = null;
77
92
  if (!keepVerify) later.ownerVerify().clear();
78
93
  if (!keepVerify) setReviseAnchor(null);
79
94
  store.batch(() => {
@@ -93,12 +108,24 @@ export function createSessionView(deps) {
93
108
  // The reader and the peek are the session's: another one (or none, the
94
109
  // start page) never finds them over #center, the composer inert under it.
95
110
  if (!keepVerify) wsPreview?.reset();
111
+ applyPrefs();
112
+ }
113
+
114
+ // The open session's own view settings (session_prefs.js), read again:
115
+ // the stage's fold, the rail's, the composer's height and fold. On a
116
+ // select (forgetSession, the session just set) and on each render. A
117
+ // module from an older cache without the hook is left as it is.
118
+ function applyPrefs() {
119
+ turnDom.applyPrefs?.();
120
+ later.composer().applyPrefs?.();
96
121
  }
97
122
 
98
123
  // A session view: its messages, then the turn in progress and the queued
99
124
  // prompts (a live worker's snapshot) replayed through the stream handlers,
100
125
  // then a pending question.
101
126
  function renderSessionView(data, { kept = [] } = {}) {
127
+ applyPrefs();
128
+ drawnId = store.selected;
102
129
  setMarkdownWarning(data.markdown_warning);
103
130
  markdownTip.show(data.markdown_tip);
104
131
  setCapabilities(data.capabilities, data.editor_url, data.viewer);
@@ -186,6 +213,8 @@ export function createSessionView(deps) {
186
213
  stageMissing.note(data);
187
214
  stageMissing.check();
188
215
  }
216
+ // The same running turn as when the page left it: what was opened, back.
217
+ applyView(viewMemory.take(store.selected, data.current_turn?.turn_id || null), { stage: turnDom, reader: wsPreview });
189
218
  // A whole view drawn: the composer and the bar once more (the working
190
219
  // set's seed may change the bar's chip).
191
220
  store.batch(() => {
@@ -254,7 +283,7 @@ export function createSessionView(deps) {
254
283
  // answer's markdown.
255
284
  store.batch(() => {
256
285
  // The notes chip: the first turn's build (or a /model) records them.
257
- applySessionPayload(d, { fields: ["usedMemories", "promptNotes"] });
286
+ applySessionPayload(d, { fields: ["usedMemories", "promptNotes", "promptParts"] });
258
287
  turnEndStatus(d);
259
288
  setMarkdownWarning(d.markdown_warning);
260
289
  markdownTip.show(d.markdown_tip);
@@ -279,6 +308,7 @@ export function createSessionView(deps) {
279
308
  // left the collapsed block (card.js leavesBlock), where a reload puts them.
280
309
  function endTurnView(kind, endText = null, { emptyAnswer = null, stopped = false } = {}) {
281
310
  setTurnRunning(false);
311
+ viewMemory.drop(store.selected);
282
312
  // Every ended turn has a record (completed, canceled, failed); a worker
283
313
  // gone mid-turn is re-rendered (resync), which counts again.
284
314
  if (kind !== "gone") liveTurn.timing.ended += 1;
@@ -297,5 +327,5 @@ export function createSessionView(deps) {
297
327
  if (questionCards.pendingQuestion()) questionCards.resolveQuestion(questionCards.pendingQuestion().id, { cancelled: true, reason: "turn ended" });
298
328
  }
299
329
 
300
- return { forgetSession, renderSessionView, historyOpts, reloadRender, readTurnEnd, endTurnView };
330
+ return { forgetSession, renderSessionView, historyOpts, reloadRender, readTurnEnd, endTurnView, leaveSession };
301
331
  }
@@ -6,12 +6,11 @@
6
6
  // stage's fold is the one); and the fold itself: the user's choice, a ref's
7
7
  // reveal, and the docked card's own fold.
8
8
  import { handOffOrder, stageCollapsed } from "./stage_model.js";
9
- import { readStored, writeStored } from "./storage.js";
9
+ import { STAGE_FOLD, read as readPref, write as writePref } from "./session_prefs.js";
10
10
  import { ASKS, PENDING, waitsInStage } from "./stage_cards.js";
11
11
  import { cardIn, waitingKey } from "./stage_waiting.js";
12
12
  import { warnDiffers } from "./card_kinds.js";
13
13
 
14
- const COLLAPSE_KEY = "chi_stage_collapsed";
15
14
  // The cards that get a lead-in bubble when their step wrote text: chi's own
16
15
  // question and its own approval (question_cards.js data-kind; not a
17
16
  // delegate's relayed one, a hook's question or the step limit).
@@ -20,8 +19,10 @@ const LEAD_IN_CARD = '.bubble.question[data-kind="question"]:not([data-relay]),
20
19
  // it never docks.
21
20
  const STEP_LIMIT = '.bubble.continue, .bubble.question.step-limit, .bubble.question[data-kind="continue"]';
22
21
 
23
- function readCollapsed() {
24
- return readStored(COLLAPSE_KEY) === "1";
22
+ // +session+'s fold by hand (session_prefs.js: chi_stage_collapsed:<session>),
23
+ // else the page's default (web.stage_collapsed), else open.
24
+ function readCollapsed(session) {
25
+ return readPref(STAGE_FOLD, session, "0") === "1";
25
26
  }
26
27
 
27
28
  // +stage+, +extras+, +tail+, +scroller+ and +fold+: the stage's root, its
@@ -32,15 +33,17 @@ function readCollapsed() {
32
33
  // the turn has ended; +promptEl()+: the turn's prompt bubble; +setCloud(open)+:
33
34
  // the cloud; +scheduleRefresh()+; +pendingCard()+: a card waits in the card
34
35
  // slots; +waiting+: the stage's waiting cards as data (stage_waiting.js),
35
- // which say the asking form's card and hold its fold.
36
+ // which say the asking form's card and hold its fold. +sessionId()+: the open
37
+ // session's id (null: the start page), whose fold by hand is kept.
36
38
  export function createStageAsking({
37
39
  stage, extras, tail, scroller, fold, view, opener, frame, isOpened, setOpened, isEnded, promptEl, setCloud,
38
- scheduleRefresh, pendingCard, waiting,
40
+ scheduleRefresh, pendingCard, waiting, sessionId = () => null,
39
41
  }) {
40
- // The user's own fold (chi_stage_collapsed), in memory: written on a
41
- // hand toggle, never read back from storage to decide (another tab's
42
- // write doesn't apply live).
43
- let choice = readCollapsed();
42
+ // The user's own fold for the open session (chi_stage_collapsed:<session>),
43
+ // in memory: written on a hand toggle, read again only when a session's
44
+ // stage is drawn (reloadChoice: a select, a render), never to decide
45
+ // meanwhile (another tab's write doesn't apply live).
46
+ let choice = readCollapsed(sessionId());
44
47
  // A ref's "show in turn" opened a collapsed stage (not kept).
45
48
  let revealed = false;
46
49
  // The docked card's fold is +waiting+'s (fold, trackFold): the waiting
@@ -258,7 +261,7 @@ export function createStageAsking({
258
261
  } else {
259
262
  choice = value;
260
263
  revealed = false;
261
- writeStored(COLLAPSE_KEY, value ? "1" : "0");
264
+ writePref(STAGE_FOLD, sessionId(), value ? "1" : "0");
262
265
  }
263
266
  applyCollapsed();
264
267
  // Opened on a waiting card: it shows as it does on arrival.
@@ -274,6 +277,12 @@ export function createStageAsking({
274
277
  revealed = true;
275
278
  applyCollapsed();
276
279
  },
280
+ // A session's stage is drawn (another session opens, or this one renders
281
+ // again): its own fold, read again; drawn only when it changed.
282
+ reloadChoice() {
283
+ choice = readCollapsed(sessionId());
284
+ drawCollapsed();
285
+ },
277
286
  // The stage cleared: a reveal ends with it.
278
287
  unreveal() {
279
288
  if (!revealed) return;
@@ -64,8 +64,9 @@ export function createStageCloud({
64
64
  headline.addEventListener("click", peek);
65
65
  // A ref's "show in turn" (refs.js) names a row in the cloud: open the
66
66
  // stage and the cloud to it, as a hand toggle would.
67
- // A collapsed stage opens for this turn only: the kept choice
68
- // (chi_stage_collapsed) is left alone and comes back at the release.
67
+ // A collapsed stage opens for this turn only: the kept choice (the
68
+ // session's own, chi_stage_collapsed:<session>) is left alone and comes
69
+ // back at the release.
69
70
  // The row's scroll into view (refs.js) waits for the stage's growth.
70
71
  // A row of a turn sliding away is no longer the stage's: it goes into the
71
72
  // history first (finishFold), and refs.js finds it there.
@@ -20,9 +20,7 @@
20
20
  // The numbers come from getBoundingClientRect at the call; the pure functions
21
21
  // take them as arguments, so a spec can pass its own. Its own module: new
22
22
  // exports go in new modules (web-frontend.md).
23
- import { readStored } from "./storage.js";
24
- import { COMPOSER_FOLD_KEY } from "./composer_fold.js";
25
- import { GRIP_KEY } from "./composer_grip.js";
23
+ import { COMPOSER_FLOOR, COMPOSER_FOLD, read as readPref } from "./session_prefs.js";
26
24
 
27
25
  // The replay events that end a turn.
28
26
  const ENDS = ["turn_completed", "turn_canceled", "turn_failed"];
@@ -126,8 +124,8 @@ export function createStageMissing({ store, turnDom, composerEl, win = globalThi
126
124
  stage: where,
127
125
  composer: {
128
126
  top: stage.composerTop,
129
- floor: readStored(GRIP_KEY),
130
- fold: readStored(COMPOSER_FOLD_KEY),
127
+ floor: readPref(COMPOSER_FLOOR, session),
128
+ fold: readPref(COMPOSER_FOLD, session),
131
129
  },
132
130
  }));
133
131
  }
@@ -125,7 +125,8 @@ export function stepSlotText({ step, ended, chipHidden }) {
125
125
  // none) only when the user folded that card (+askingFold+: the folded key,
126
126
  // null: none), so a
127
127
  // question always arrives open and a new one never matches an old fold;
128
- // else the user's +choice+ (chi_stage_collapsed, as set by hand), unless a
128
+ // else the user's +choice+ (the session's fold by hand, else the page's
129
+ // default: session_prefs.js chi_stage_collapsed:<session>), unless a
129
130
  // ref's "show in turn" opened it for this turn (+revealed+).
130
131
  export function stageCollapsed({ choice, revealed, asking = null, askingFold = null }) {
131
132
  if (asking) return askingFold === asking;
@@ -105,7 +105,7 @@ export function createStageView({
105
105
  // The working set's rail: out of the live slots' flow on their right (a
106
106
  // row under the trail in a narrow stage), so it never sets their height.
107
107
  const rail = workingSet
108
- ? createWorkingSetRail({ live, stage, onOpen: (el) => workingSet.openTurn(el), onChange: () => scheduleRefresh() })
108
+ ? createWorkingSetRail({ live, stage, onOpen: (el) => workingSet.openTurn(el), onChange: () => scheduleRefresh(), sessionId })
109
109
  : null;
110
110
  if (rail) {
111
111
  workingSet.setSeen(rail.seenAt);
@@ -209,6 +209,7 @@ export function createStageView({
209
209
  const ask = createStageAsking({
210
210
  stage, extras, tail, scroller, fold, view, opener, frame: () => frame, isOpened: () => opened, setOpened,
211
211
  isEnded: () => !!endKind, promptEl: () => promptEl, setCloud: (open) => cloudView.setCloud(open), scheduleRefresh, pendingCard, waiting,
212
+ sessionId,
212
213
  });
213
214
  const {
214
215
  askedText, settleCards, askingCard, cardOf, foldedText, markOwnToggles,
@@ -689,6 +690,8 @@ export function createStageView({
689
690
  // The turn model and its live phase as the status row reads it (the
690
691
  // composer's delivery line).
691
692
  current: () => view.current(),
693
+ // The cloud and a step's nodes (stage_view_memory.js: what was opened, put back).
694
+ cloud: cloudView, step: (i) => view.step(i),
692
695
  // Only a card that blocks says "goes in once the card above is
693
696
  // answered": check-in leaves the composer free.
694
697
  phase: () => liveSlots(view.current().turn, { pending: pendingCard() }).phase,
@@ -699,6 +702,8 @@ export function createStageView({
699
702
  handoff.reset();
700
703
  release();
701
704
  },
705
+ // The open session's own view settings (session_prefs.js), read again as its view is drawn (session_view.js).
706
+ applyPrefs: () => { ask.reloadChoice(); rail?.applyPrefs?.(); },
702
707
  // The stage's extras while it holds a turn, its queued slot, an opened
703
708
  // turn's history end; false: the history takes it (stage_place.js).
704
709
  place: (el) => placer.place(el),