samagotchi 0.199.0 → 0.200.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 (53) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +31 -1
  3. data/docs/bundles.md +3 -2
  4. data/docs/cli.md +18 -3
  5. data/docs/configuration.md +12 -7
  6. data/docs/internals/bridge.md +9 -4
  7. data/docs/internals/knowledge.md +8 -5
  8. data/docs/internals/participants.md +2 -1
  9. data/docs/internals/prompt-caching.md +9 -4
  10. data/docs/internals/web-frontend.md +27 -2
  11. data/docs/plugins.md +4 -2
  12. data/docs/sessions.md +8 -1
  13. data/docs/testing.md +1 -1
  14. data/lib/samagotchi/bridge/card_store.rb +19 -10
  15. data/lib/samagotchi/bridge.rb +1 -1
  16. data/lib/samagotchi/bundles/knowledge/github.rb +28 -10
  17. data/lib/samagotchi/bundles/knowledge/manifest.yml +4 -4
  18. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  19. data/lib/samagotchi/cache_confirm.rb +54 -18
  20. data/lib/samagotchi/engine/models.rb +10 -0
  21. data/lib/samagotchi/guardrail_wiring.rb +1 -1
  22. data/lib/samagotchi/inline_widgets.rb +14 -2
  23. data/lib/samagotchi/level_setting_command.rb +2 -3
  24. data/lib/samagotchi/llm_context_command.rb +2 -2
  25. data/lib/samagotchi/model_switch_mark.rb +49 -0
  26. data/lib/samagotchi/paths.rb +8 -1
  27. data/lib/samagotchi/plugin/secrets.rb +1 -1
  28. data/lib/samagotchi/plugin_session_state.rb +1 -1
  29. data/lib/samagotchi/session_commands.rb +11 -4
  30. data/lib/samagotchi/session_stats.rb +11 -6
  31. data/lib/samagotchi/toolkit_command.rb +1 -1
  32. data/lib/samagotchi/version.rb +1 -1
  33. data/lib/samagotchi/web/public/app.js +3 -1
  34. data/lib/samagotchi/web/public/bar_fold.js +1 -1
  35. data/lib/samagotchi/web/public/bubbles.js +7 -2
  36. data/lib/samagotchi/web/public/cache_cost_text.js +15 -0
  37. data/lib/samagotchi/web/public/commands.js +11 -2
  38. data/lib/samagotchi/web/public/confirm_block.js +59 -0
  39. data/lib/samagotchi/web/public/index.html +26 -1
  40. data/lib/samagotchi/web/public/info_bar.js +12 -1
  41. data/lib/samagotchi/web/public/info_bar_model.js +11 -1
  42. data/lib/samagotchi/web/public/model_mark.js +18 -0
  43. data/lib/samagotchi/web/public/model_picker.js +23 -6
  44. data/lib/samagotchi/web/public/model_switch.js +101 -0
  45. data/lib/samagotchi/web/public/more_sheet.js +11 -4
  46. data/lib/samagotchi/web/public/quiet_notes.js +1 -1
  47. data/lib/samagotchi/web/public/reasoning_history_chip.js +2 -1
  48. data/lib/samagotchi/web/public/settings_chip.js +2 -1
  49. data/lib/samagotchi/web/public/start_page.js +41 -8
  50. data/lib/samagotchi/web/public/stream_handlers.js +13 -2
  51. data/lib/samagotchi/web/public/thinking_chip.js +2 -1
  52. data/lib/samagotchi/web/public/tokens.css +2 -2
  53. metadata +6 -1
@@ -0,0 +1,59 @@
1
+ // A change that restarts the prompt cache asks first (CacheConfirm): this
2
+ // tab's own command bubble then is a warning block, its title ("Switch to
3
+ // qwen-3.5?"), its body (when the cost lands and how much; "Nothing has
4
+ // changed yet.") and one solid button that sends the --yes line. It stays a
5
+ // `.bubble.command` (the kept bubbles, the resync and the anchors find it by
6
+ // that class and its .command-line): commands.js drawCommandBubble draws it.
7
+ // An older worker's confirm has no title: today's bubble and Apply.
8
+ //
9
+ // A new module: the page's modules are cached at unversioned URLs, and a new
10
+ // export of an old one leaves a cached copy without it
11
+ // (docs/internals/web-frontend.md). Plain DOM, no lit: commands.js loads
12
+ // without a DOM.
13
+
14
+ const SVG = "http://www.w3.org/2000/svg";
15
+
16
+ // The block's words from a command_ran's confirm, or null for an older
17
+ // worker's (no title or body).
18
+ export function confirmBlockOf(confirm) {
19
+ if (!confirm || typeof confirm.title !== "string" || typeof confirm.body !== "string") return null;
20
+ return { title: confirm.title, body: confirm.body, button: typeof confirm.button === "string" && confirm.button ? confirm.button : "Apply" };
21
+ }
22
+
23
+ // The warning triangle before the title (decor: the title says it).
24
+ function warnIcon(doc) {
25
+ const svg = doc.createElementNS(SVG, "svg");
26
+ svg.setAttribute("class", "cc-icon");
27
+ svg.setAttribute("viewBox", "0 0 14 14");
28
+ svg.setAttribute("aria-hidden", "true");
29
+ for (const d of ["M7 1.5l6 11H1z", "M7 5.5v3.2M7 10.4v.1"]) {
30
+ const path = doc.createElementNS(SVG, "path");
31
+ path.setAttribute("d", d);
32
+ svg.appendChild(path);
33
+ }
34
+ return svg;
35
+ }
36
+
37
+ // Draws +block+ into +div+ (a command bubble, its .command-line already in
38
+ // it): the title, the body and the button that sends +confirm+ (the --yes
39
+ // line; app.js's delegated click on [data-confirm-line]).
40
+ export function drawConfirmBlock(div, { block, confirm }) {
41
+ const doc = div.ownerDocument;
42
+ div.classList.add("cache-confirm");
43
+ div.setAttribute("role", "group");
44
+ const title = doc.createElement("div");
45
+ title.className = "cc-title";
46
+ title.append(warnIcon(doc), doc.createTextNode(block.title));
47
+ const body = doc.createElement("div");
48
+ body.className = "cc-body";
49
+ body.textContent = block.body;
50
+ const apply = doc.createElement("button");
51
+ apply.type = "button";
52
+ apply.className = "command-confirm cc-apply";
53
+ apply.dataset.confirmLine = confirm;
54
+ apply.title = confirm;
55
+ apply.textContent = block.button;
56
+ div.setAttribute("aria-label", block.title);
57
+ div.prepend(title, body);
58
+ div.appendChild(apply);
59
+ }
@@ -614,6 +614,15 @@ button.peer-state{cursor:pointer}
614
614
  .bubble.command .command-confirm{margin-top:8px;padding:3px 10px;border-radius:6px;font:inherit;font-size:12px;cursor:pointer;background:var(--accent-bg);color:var(--accent);border:1px solid var(--accent-border)}
615
615
  @media(hover:hover){.bubble.command .command-confirm:hover:not(:disabled){border-color:var(--accent)}}
616
616
  .bubble.command .command-confirm:disabled{opacity:.55;cursor:default}
617
+ /* A cache confirm (confirm_block.js): a warning block, the title with its icon, the body, then the one solid button and the line it sends. Still a .bubble.command (kept across a resync). */
618
+ .bubble.command.cache-confirm{display:grid;grid-template-columns:auto minmax(0,1fr);align-items:center;gap:10px 10px;background:var(--warn-bg);border:1px solid var(--warn-border);border-radius:10px;padding:12px}
619
+ .cache-confirm .cc-title{grid-column:1/-1;display:flex;align-items:center;gap:8px;font-weight:600;color:var(--warn-bright)}
620
+ .cache-confirm .cc-icon{width:14px;height:14px;flex:none;fill:none;stroke:currentColor;stroke-width:1.4;stroke-linecap:round;stroke-linejoin:round}
621
+ .cache-confirm .cc-body{grid-column:1/-1;color:var(--warn-text);line-height:1.5;white-space:pre-wrap}
622
+ .bubble.command.cache-confirm .command-line{grid-row:3;grid-column:2;font-size:11px;color:var(--text-muted);overflow-wrap:anywhere}
623
+ .bubble.command.cache-confirm .cc-apply{grid-row:3;grid-column:1;margin:0;padding:7px 14px;border-radius:8px;font-weight:600;font-size:13px;background:var(--warn-solid);color:var(--on-warn-solid);border:1px solid var(--warn-solid-edge)}
624
+ @media(hover:hover){.bubble.command.cache-confirm .cc-apply:hover:not(:disabled){border-color:var(--warn-bright);filter:brightness(1.06)}}
625
+ @media(max-width:600px){.bubble.command.cache-confirm{grid-template-columns:minmax(0,1fr)}.bubble.command.cache-confirm .cc-apply{grid-column:1;min-height:44px;font-size:15px}.bubble.command.cache-confirm .command-line{display:none}}
617
626
  .bubble.continue{border-left:3px solid var(--accent);background:var(--bg-panel);padding:10px 12px}
618
627
  .bubble.continue.resolved{border-left-color:var(--text-muted);opacity:.8}
619
628
  .continue-text{font-size:14px;color:var(--text);margin-bottom:6px}
@@ -713,6 +722,10 @@ button.peer-state{cursor:pointer}
713
722
  .bubble.guardrail-warning{border-left:3px solid var(--danger);background:color-mix(in srgb,var(--danger) 8%,var(--bg-panel));color:var(--danger-text);font-size:13px;padding:8px 12px;white-space:pre-wrap}
714
723
  .bubble.hook-notice{border-left:3px solid var(--text-faint);background:var(--bg-panel);color:var(--text-3);font-size:13px;padding:8px 12px;white-space:pre-wrap}
715
724
  .bubble.hook-notice.warn{border-left-color:var(--warn);color:var(--warn-text)}
725
+ /* A /model switch's mark (model_mark.js): a quiet centred divider; on a phone the line wraps centred between short rules. */
726
+ .bubble.hook-notice.model-mark{display:flex;align-items:center;gap:10px;background:none;border:0;padding:2px 0;color:var(--text-muted);font-size:12px;white-space:normal;text-align:center;line-height:1.5}
727
+ .bubble.hook-notice.model-mark::before,.bubble.hook-notice.model-mark::after{content:"";flex:1 1 18px;min-width:18px;height:1px;background:var(--border)}
728
+ .model-mark .mm-text{flex:0 1 auto;min-width:0;overflow-wrap:anywhere}
716
729
  .gen .hook-notice{font-size:13px;color:var(--text-3);padding:5px 2px 5px 8px;border-top:1px solid var(--border);border-left:2px solid var(--text-faint);white-space:pre-wrap;word-break:break-word}
717
730
  .gen .activity-body>.hook-notice:first-child{border-top:none}
718
731
  .gen .hook-notice.warn{border-left-color:var(--warn);color:var(--warn-text)}
@@ -941,7 +954,7 @@ body.has-session.fresh-link #composer .actions-col .model-pick:not([hidden]){dis
941
954
  #modelPanel{position:absolute;left:10px;width:min(560px,calc(100% - 20px));bottom:calc(100% + 8px);max-height:360px;border-radius:12px;z-index:21;display:flex;flex-direction:column;overflow:hidden;background:var(--bg-panel);border:1px solid var(--glass-border);box-shadow:inset 0 1px 0 var(--glass-highlight),var(--glass-shadow)}
942
955
  #modelPanel.down{bottom:auto;top:calc(100% + 8px)}
943
956
  #modelPanel.over{bottom:0}
944
- #modelPanel[hidden],body.has-session:not(.fresh-link) #modelPanel{display:none}
957
+ #modelPanel[hidden],body.has-session:not(.fresh-link):not(.model-switch) #modelPanel{display:none}
945
958
  #modelPanel .model-search{flex:none;display:flex;align-items:center;gap:8px;padding:0 12px;border-bottom:1px solid var(--border)}
946
959
  #modelPanel .model-search svg{flex:none;width:14px;height:14px;color:var(--text-faint)}
947
960
  #modelSearch{flex:1;min-width:0;height:38px;background:transparent;border:0;color:var(--text);font-size:13px}
@@ -1440,6 +1453,14 @@ button.ws-row:hover:not(:disabled){filter:none}@media(hover:hover){button.ws-row
1440
1453
  /* A chip is capped, cut with "…", its full text in the title: the model (and ⚙'s values) at 40ch, the folder at 48ch
1441
1454
  (its own rule above). The caps hold while the fold measures, so a chip's measured width is its drawn one. */
1442
1455
  #infoBar .meta .model{max-width:40ch;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
1456
+ /* The model's name as a button (model_switch.js): the chip's own box and width (no border: an inset ring; the small
1457
+ chevron takes the right padding's place: 4 + text + 1 + 6 + 1 = the span's 6 + text + 6), so the row folds as before;
1458
+ its text cut inside; hover, focus and the open list give it the accent. */
1459
+ #infoBar .meta button.model-name{font:inherit;font-size:11px;line-height:inherit;margin:0;border:0;padding:2px 1px 2px 4px;cursor:pointer;display:inline-flex;align-items:center;gap:0}
1460
+ #infoBar .meta button.model-name .mn-text{min-width:0;margin-right:1px;overflow:hidden;text-overflow:ellipsis}
1461
+ #infoBar .meta button.model-name .mn-chev{flex:none;width:6px;height:6px;fill:none;stroke:var(--accent);stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}
1462
+ @media(hover:hover){#infoBar .meta button.model-name:hover{background:var(--accent-bg);color:var(--text-bright);box-shadow:inset 0 0 0 1px var(--accent-border)}}
1463
+ #infoBar .meta button.model-name:focus-visible,#infoBar .meta button.model-name[aria-expanded="true"]{background:var(--accent-bg);color:var(--text-bright);box-shadow:inset 0 0 0 1px var(--accent);outline:none}
1443
1464
  /* The fold (bar_fold.js) as attributes on #infoBar: a folded item is display:none (still in the DOM: ⋯'s rows click
1444
1465
  it), ⚙ compact is its icon with the dot when the session set its own, an empty group goes with its hairline. One
1445
1466
  selector per BAR_ITEMS key (info_bar_model.js; info_bar_fold_css.test.js checks every foldable key has one). */
@@ -1847,6 +1868,10 @@ div.more-row{cursor:default}
1847
1868
  .more-text{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1848
1869
  .more-row.warn .more-text{color:var(--warn-text);font-weight:600}
1849
1870
  a.more-row .more-text{color:var(--accent)}
1871
+ /* The Model row as the action (more_sheet.js modelRow): a chevron after the name, the model's title on a line under it. */
1872
+ .more-chev{flex:none;color:var(--accent);font-size:1.1em;line-height:1}
1873
+ .more-row:has(> .more-sub){flex-wrap:wrap;row-gap:2px}
1874
+ .more-sub{flex:1 0 100%;font-size:12px;color:var(--text-muted);overflow-wrap:anywhere}
1850
1875
  .more-dot{flex:none;width:6px;height:6px;border-radius:50%;background:var(--accent)}
1851
1876
  .more-dot.warn{background:var(--warn-bright)}
1852
1877
  .more-sheet .chip-icon{flex:none;width:12px;height:12px;font-size:0;background:currentColor;-webkit-mask:var(--icon) center/contain no-repeat;mask:var(--icon) center/contain no-repeat}
@@ -108,7 +108,7 @@ export function infoBarHtml(bar) {
108
108
  const memories = bar.memories || [];
109
109
  const sep = (group) => html`<span class=${`bar-sep sep-${group}`} aria-hidden="true"></span>`;
110
110
  const identity = html`<button type="button" class="id" title=${`Session id ${bar.id}: click to copy it`}>${String(bar.id).slice(0, 8)}</button><span class=${bar.status ? `status ${bar.status}` : "status"} title=${bar.statusTip || nothing}><span>${bar.statusText || bar.status || ""}</span></span><span class="model ctx" title=${bar.ctx.tip}>${bar.ctx.text}</span>${bar.speed ? html`<span class=${`model speed${bar.speed.empty ? " empty" : ""}`} title=${bar.speed.tip}>${bar.speed.text}</span>` : nothing}<span class=${`model session-time${bar.clock ? "" : " empty"}`} title=${bar.clock ? "This session's time: its turns, and the running one" : "This session's time: no turn yet"}>${bar.clock || CLOCK_NONE}</span>`;
111
- const setup = html`${settingsChip(bar.settings)}<span class=${`model model-name${bar.model.mismatch ? " served-mismatch" : ""}`} title=${bar.model.title}>${bar.model.text}</span>${toolkitChip(bar.toolkit)}${bar.notes ? html`<span class="model notes-chip" title=${bar.notes.title}>${bar.notes.text}</span>` : nothing}${bar.workingSet ? workingSetChipTemplate(bar.workingSet.chip) : memories.length ? html`<span class="model mem-chip" title=${memChipTitle(memories)}>${memChipText(memories)}</span>` : nothing}`;
111
+ const setup = html`${settingsChip(bar.settings)}${modelTemplate(bar.model)}${toolkitChip(bar.toolkit)}${bar.notes ? html`<span class="model notes-chip" title=${bar.notes.title}>${bar.notes.text}</span>` : nothing}${bar.workingSet ? workingSetChipTemplate(bar.workingSet.chip) : memories.length ? html`<span class="model mem-chip" title=${memChipTitle(memories)}>${memChipText(memories)}</span>` : nothing}`;
112
112
  const pruned = !!bar.chain?.pruned && !bar.chain?.prev;
113
113
  const related = !!(bar.chain?.prev || bar.chain?.next || pruned || bar.parent || bar.kids || bar.participants);
114
114
  // A chain whose earlier link was deleted (by hand, or a schedule's prune:
@@ -121,6 +121,17 @@ export function infoBarHtml(bar) {
121
121
  return html`<div class="meta"><span class="bar-group identity">${identity}</span>${sep("setup")}<span class="bar-group setup">${setup}</span>${relations}${sep("trail")}<span class="bar-group trail">${trail}</span></div>`;
122
122
  }
123
123
 
124
+ // The model's name: a button that opens the session's model list when the
125
+ // session may switch (+switchable+: model_switch.js modelSwitchable, with its
126
+ // words in +switchTitle+ / +switchLabel+), else plain text (while a turn runs
127
+ // its tooltip says so: +runningTitle+, the bar's only, so ⋯'s row stays plain).
128
+ function modelTemplate(model) {
129
+ const cls = `model model-name${model.mismatch ? " served-mismatch" : ""}`;
130
+ if (!model.switchable) return html`<span class=${cls} title=${model.runningTitle || model.title}>${model.text}</span>`;
131
+ return html`<button type="button" class=${`${cls} switch`} data-model-switch title=${model.switchTitle || model.title}
132
+ aria-label=${model.switchLabel || nothing} aria-haspopup="listbox" aria-expanded="false"><span class="mn-text">${model.text}</span><svg class="mn-chev" viewBox="0 0 8 8" aria-hidden="true"><path d="M1.5 3l2.5 2.5L6.5 3"></path></svg></button>`;
133
+ }
134
+
124
135
  // Draws +bar+ into +el+ (#infoText), with the memories in its tooltip
125
136
  // (with the working set on, its list says them instead).
126
137
  export function renderInfoBar(el, bar) {
@@ -3,6 +3,7 @@
3
3
  // delete, archive, stop), from the page's session state (session_state.js),
4
4
  // its list and its in-flight actions. Pure: app.js's updateInfoBar applies
5
5
  // it, every second while a turn runs (the session clock).
6
+ import { modelSwitchable, RUNNING_TITLE, switchWords } from "./model_switch.js";
6
7
  import { canStopSession, childrenSummary, delegatedBy, modelLabel, promptNotesChip } from "./format.js";
7
8
  import { chainClock, chainDate, chainNeighbours } from "./chains.js";
8
9
  import { ctxBarText, ctxBarTip, lastSpeedText, speedText } from "./ctx.js";
@@ -201,12 +202,21 @@ export function infoBarModel({ id, state, sessions, chain, cardTitle, badge, res
201
202
  // The whole bar for the open session +id+ (null: the start page, no line).
202
203
  // @param sessions the page's list; +continuing+, +restarting+: Sets of ids
203
204
  // @return {buttons, bar}
204
- export function sessionBar({ id, state, sessions, versions, cardTitle, continuing, restarting, streaming, running, waiting = false, workingSet = undefined, participants = null }) {
205
+ // +modelSwitch+: the page can open the model list from the bar (the list is
206
+ // in, the viewer may run commands); the model is then a button where
207
+ // model_switch.js modelSwitchable allows it.
208
+ export function sessionBar({ id, state, sessions, versions, cardTitle, continuing, restarting, streaming, running, waiting = false, workingSet = undefined, participants = null, modelSwitch = false }) {
205
209
  const chain = id ? chainNeighbours(sessions, id, { continues: state.continues }) : { prev: null, next: null };
206
210
  const archived = !!sessions.find((s) => s.id === id)?.archived;
207
211
  const buttons = infoButtons({ id, state, chain, archived, continuing: continuing.has(id), streaming });
208
212
  if (!id) return { buttons, bar: null };
209
213
  const badge = workerBadgeFor(id, state, versions);
210
214
  const bar = infoBarModel({ id, state, sessions, chain, cardTitle, badge, restarting: restarting.has(id), running, waiting, workingSet, participants });
215
+ if (modelSwitch) {
216
+ const switchable = modelSwitchable(state, { running, hasNext: !!chain.next, archived });
217
+ const words = switchable ? switchWords(bar.model.title) : null;
218
+ bar.model = switchable ? { ...bar.model, switchable, switchTitle: words.title, switchLabel: words.label }
219
+ : running ? { ...bar.model, runningTitle: `${bar.model.title} (${RUNNING_TITLE})` } : bar.model;
220
+ }
211
221
  return { buttons, bar };
212
222
  }
@@ -0,0 +1,18 @@
1
+ // A /model switch's mark (lib/samagotchi/model_switch_mark.rb): a hook
2
+ // notice of hook "model" outside any turn, "model: gemma-4 → qwen-3.5 ·
3
+ // Dec 3, 09:31". The page draws it as a quiet centred divider where the
4
+ // switch happened (bubbles.js hookNoticeTemplate), live and after a reload
5
+ // alike, and never folds it into a notes row (quiet_notes.js QUIET): it is
6
+ // where the conversation changed model. A served follow's "model:" row is a
7
+ // turn's own (in_turn) and stays a row.
8
+ //
9
+ // A new module: the page's modules are cached at unversioned URLs
10
+ // (docs/internals/web-frontend.md).
11
+
12
+ export const MODEL_MARK_CLASS = "model-mark";
13
+
14
+ // +data+: a live hook_notice event (between_turns) or a reload's CardStore
15
+ // entry (in_turn false).
16
+ export function isModelMark(data) {
17
+ return !!data && data.hook === "model" && (data.between_turns === true || data.in_turn === false);
18
+ }
@@ -51,14 +51,22 @@ function readRecent() {
51
51
  // +onPick+ runs after a pick (the panel is closed by then). +remember+:
52
52
  // whether a pick is this browser's choice for a new session (stored, and in
53
53
  // Recent); false on a fresh chain link, where a pick is that link's only.
54
+ // open({from, onClose}) opens it from another control than +button+ (the
55
+ // info bar's model name): +from+ is that control's selector, read at each
56
+ // use (lit may draw it anew), for its aria-expanded, the outside click and
57
+ // Esc's refocus; +onClose+ runs once it closes.
54
58
  export function createModelPicker({ button, panel, input, list, composer, center, onPick, remember = () => true }) {
55
59
  let rows = [];
56
60
  let defaultName = "";
57
61
  let chosen = "";
58
62
  let shown = []; // the option rows in list order
59
63
  let active = 0;
64
+ // The control that opened it (a selector; null: +button+), and its close hook.
65
+ let opener = null;
66
+ let onClosed = null;
60
67
 
61
68
  const isOpen = () => !panel.hidden;
69
+ const openerEl = () => (opener ? document.querySelector(opener) : button);
62
70
 
63
71
  // Greyed while the chosen row's host is down (the button's tooltip,
64
72
  // app.js', carries the host's warning).
@@ -134,12 +142,14 @@ export function createModelPicker({ button, panel, input, list, composer, center
134
142
  panel.style.maxHeight = `${Math.max(0, Math.min(cap, room))}px`;
135
143
  }
136
144
 
137
- function open() {
138
- if (isOpen() || button.hidden) return;
145
+ function open({ from = null, onClose = null } = {}) {
146
+ if (isOpen() || (!from && button.hidden)) return;
147
+ opener = from;
148
+ onClosed = onClose;
139
149
  input.value = "";
140
150
  active = 0;
141
151
  panel.hidden = false;
142
- button.setAttribute("aria-expanded", "true");
152
+ openerEl()?.setAttribute("aria-expanded", "true");
143
153
  input.setAttribute("aria-expanded", "true");
144
154
  place();
145
155
  render();
@@ -155,10 +165,16 @@ export function createModelPicker({ button, panel, input, list, composer, center
155
165
  panel.hidden = true;
156
166
  draw(nothing, list);
157
167
  shown = [];
158
- button.setAttribute("aria-expanded", "false");
168
+ const el = openerEl();
169
+ el?.setAttribute("aria-expanded", "false");
159
170
  input.setAttribute("aria-expanded", "false");
160
171
  input.removeAttribute("aria-activedescendant");
161
- if (refocus) button.focus();
172
+ // An opener with no box (folded into ⋯ on a phone) takes no focus.
173
+ if (refocus && el && (el === button || el.getClientRects().length)) el.focus();
174
+ const hook = onClosed;
175
+ opener = null;
176
+ onClosed = null;
177
+ hook?.();
162
178
  }
163
179
 
164
180
  function pick(index) {
@@ -215,7 +231,7 @@ export function createModelPicker({ button, panel, input, list, composer, center
215
231
  if (option) pick(Number(option.dataset.index));
216
232
  });
217
233
  document.addEventListener("pointerdown", (e) => {
218
- if (isOpen() && !panel.contains(e.target) && !button.contains(e.target)) close();
234
+ if (isOpen() && !panel.contains(e.target) && !button.contains(e.target) && !openerEl()?.contains(e.target)) close();
219
235
  });
220
236
  window.addEventListener("resize", () => { if (isOpen()) place(); });
221
237
 
@@ -246,6 +262,7 @@ export function createModelPicker({ button, panel, input, list, composer, center
246
262
  chosen: () => chosen,
247
263
  // The picked model's row (its llm_context too); null before the list.
248
264
  chosenRow: () => rows.find((r) => r.name === chosen) || null,
265
+ open,
249
266
  close,
250
267
  isOpen,
251
268
  };
@@ -0,0 +1,101 @@
1
+ // The session's model from a control: one rule for "may /model run here
2
+ // from a click" (the info bar's model name, a fresh chain link's picker),
3
+ // read by start_page.js and info_bar_model.js.
4
+ //
5
+ // A new module: the page's modules are cached at unversioned URLs, and a new
6
+ // export of an old one leaves a cached copy without it
7
+ // (docs/internals/web-frontend.md).
8
+
9
+ import { freshLink } from "./chains.js";
10
+
11
+ // Whether a control may switch the open session's model (+state+: its
12
+ // session_state.js fields): never while a turn runs (a typed /model still
13
+ // queues for its end), in a session a terminal owns (the web can't send
14
+ // there), in an archived session or a link that was continued (a /model
15
+ // would wake a link whose next one runs: change the model on the newest
16
+ // link), nor without the page's models list (+available+: the list is in
17
+ // and the picker can open from the bar).
18
+ export function modelSwitchable(state, { running = false, hasNext = false, archived = false, available = true } = {}) {
19
+ if (!state || !available || running || hasNext || archived) return false;
20
+ return state.owner !== "tui";
21
+ }
22
+
23
+ // A fresh chain link's picker (the composer's #modelPick in a session): a
24
+ // link that may switch and has no turn yet (chains.js freshLink).
25
+ export function freshLinkPick(state, { running = false, hasNext = false } = {}) {
26
+ return modelSwitchable(state, { running, hasNext }) && freshLink(state, { running });
27
+ }
28
+
29
+ // The bar's model name as a button (info_bar.js): its tooltip (+title+, the
30
+ // name's own: the full name, what a server serves instead) and label.
31
+ export function switchWords(title) {
32
+ return { title: `Model: ${title} — click to change`, label: `Model: ${title}. Click to change` };
33
+ }
34
+ // While a turn runs the name is plain text that says why.
35
+ export const RUNNING_TITLE = "a turn is running";
36
+
37
+ // The bar's model name, clicked (on the row, or by ⋯'s Model row): opens
38
+ // the session's picker under it (+open+: start_page.js openForSession, given
39
+ // the name's selector). Delegated on #infoText (+el+), which lit redraws.
40
+ export const MODEL_SWITCH_SELECTOR = "#infoText [data-model-switch]";
41
+ export function wireModelSwitch({ el, open }) {
42
+ el?.addEventListener("click", (e) => {
43
+ if (!e.target.closest?.("[data-model-switch]")) return;
44
+ e.preventDefault();
45
+ open?.(MODEL_SWITCH_SELECTOR);
46
+ });
47
+ }
48
+
49
+ // ── A picked switch shows only its mark (D9 B) ─────────────────────────────
50
+ // A pick (the bar's list, a fresh link's) sends /model X as if typed, and
51
+ // registers that line for the session first (a command_ran can arrive before
52
+ // the POST resolves). Its question's --yes line is registered when the
53
+ // question comes back. This tab's command_ran of a registered line then:
54
+ // - the question (a confirm): drawn as the warning block, as typed;
55
+ // - its --yes, done: no bubble, and the block goes (the mark is the trace);
56
+ // - an error or busy: its line, as typed (the block stays);
57
+ // - a switch at once (no reply yet, so no mark): its line, as typed.
58
+ // Only with a worker that draws the mark (+marks+: the model_mark feature);
59
+ // an older one keeps today's lines. A typed /model is never registered.
60
+ const MARK_FEATURE = "model_mark";
61
+ const YES = " --yes";
62
+ const picked = new Map(); // session id → Set of command lines
63
+
64
+ export function registerPick(session, line) {
65
+ if (!session || !line) return;
66
+ // One session's at a time: the page shows one.
67
+ for (const key of picked.keys()) if (key !== session) picked.delete(key);
68
+ if (!picked.has(session)) picked.set(session, new Set());
69
+ picked.get(session).add(line);
70
+ }
71
+
72
+ // +workerFeatures+, +bridgeUp+: the open session's (session_state.js); a
73
+ // worker that isn't up is woken as a new one, which has the feature.
74
+ export function workerMarks(workerFeatures, bridgeUp) {
75
+ return !(bridgeUp === true && Array.isArray(workerFeatures) && !workerFeatures.includes(MARK_FEATURE));
76
+ }
77
+
78
+ // "skip": draw no bubble for this command_ran, or (+queued+) this
79
+ // command_queued (+view+: commands.js commandView's); null: as typed. A
80
+ // queued event never uses up a line: its command_ran decides.
81
+ export function pickReply(session, view, { marks = true, queued = false } = {}) {
82
+ const lines = picked.get(session);
83
+ if (!lines || !view?.own || !lines.has(view.line)) return null;
84
+ const yes = view.line.endsWith(YES);
85
+ // Queued for after a turn (waiting): drawn by its ran, if at all.
86
+ if (queued) return view.waiting && marks && yes ? "skip" : null;
87
+ lines.delete(view.line);
88
+ if (!marks) return null;
89
+ if (view.confirm) {
90
+ lines.add(view.confirm);
91
+ return null;
92
+ }
93
+ return yes && !view.failed && !view.busy ? "skip" : null;
94
+ }
95
+
96
+ // The warning block whose button sent +line+, gone once it applied.
97
+ export function dropAnsweredBlock(bubbles, line) {
98
+ for (const el of bubbles) {
99
+ if (el.querySelector(":scope > [data-confirm-line]")?.dataset.confirmLine === line) el.remove();
100
+ }
101
+ }
@@ -39,6 +39,7 @@ import { html, nothing, render } from "./vendor/lit-html.js";
39
39
  // The real element each `go:` act clicks.
40
40
  const TARGETS = {
41
41
  id: "#infoText .id",
42
+ model: "#infoText [data-model-switch]",
42
43
  settings: "#infoText .settings-chip",
43
44
  workingSet: "#infoText .ws-chip",
44
45
  participants: "#infoText .participants-chip",
@@ -86,9 +87,13 @@ function delegatesRow(kids) {
86
87
  }
87
88
 
88
89
  // The model's title unfolds only when it says more than the row already does
89
- // (a name cut at 40, what the server serves instead).
90
- function modelRow({ text, title }) {
91
- return { key: "model", label: "Model", value: text, info: title === text ? null : title };
90
+ // (a name cut at 40, what the server serves instead). A session that may
91
+ // switch (+switchable+) makes the row the action that opens the model list
92
+ // (the bar's name, model_switch.js), its title then a line under the name.
93
+ function modelRow({ text, title, switchable = false }) {
94
+ const info = title === text ? null : title;
95
+ return switchable ? { key: "model", label: "Model", value: text, go: "model", chevron: true, sub: info }
96
+ : { key: "model", label: "Model", value: text, info };
92
97
  }
93
98
 
94
99
  function workerRow({ badge, busy }) {
@@ -152,7 +157,9 @@ export function moreActions(buttons, folded = null) {
152
157
  function rowBody(row) {
153
158
  const dot = row.attention ? html`<span class=${`more-dot ${row.attention}`} aria-hidden="true"></span>` : nothing;
154
159
  const icon = row.icon ? html`<span class=${`chip-icon ${row.icon}`} aria-hidden="true"></span>` : nothing;
155
- return html`<span class="more-label">${row.label}</span><span class="more-value">${dot}${icon}<span class="more-text">${row.value}</span></span>`;
160
+ const chevron = row.chevron ? html`<span class="more-chev" aria-hidden="true">›</span>` : nothing;
161
+ const sub = row.sub ? html`<span class="more-sub">${row.sub}</span>` : nothing;
162
+ return html`<span class="more-label">${row.label}</span><span class="more-value">${dot}${icon}<span class="more-text">${row.value}</span>${chevron}</span>${sub}`;
156
163
  }
157
164
 
158
165
  function rowTemplate(row, { shownInfo, hash }) {
@@ -26,7 +26,7 @@
26
26
  import { html, nothing } from "./vendor/lit-html.js";
27
27
 
28
28
  // What folds: a direct child of #history that is one of these.
29
- export const QUIET = ".bubble.hook-notice:not(.empty-answer), .bubble.note:not(.turn-start):not(.peer-answer), .bubble.steer-row";
29
+ export const QUIET = ".bubble.hook-notice:not(.empty-answer):not(.model-mark), .bubble.note:not(.turn-start):not(.peer-answer), .bubble.steer-row";
30
30
  // What a stretch passes over (it stays visible).
31
31
  export const PASS = ".turn-timing";
32
32
  export const ROW_CLASS = "quiet-notes";
@@ -4,6 +4,7 @@
4
4
  // is null on a native host, which ignores it, or from an older worker: no
5
5
  // row then) and runs /reasoning-history in the session's worker.
6
6
 
7
+ import { CACHE_COST } from "./cache_cost_text.js";
7
8
  import * as level from "./level_chip.js";
8
9
 
9
10
  export const LEVELS = ["drop", "turn", "all"];
@@ -13,7 +14,7 @@ export const CONFIG = Object.freeze({
13
14
  prefix: "reasoning",
14
15
  command: "/reasoning-history",
15
16
  levels: LEVELS,
16
- cost: "A reasoning history change to or from all makes the server read the conversation again.",
17
+ cost: CACHE_COST.reasoningHistory,
17
18
  });
18
19
 
19
20
  // The /reasoning-history line for a level, with --yes; null when it is the
@@ -15,6 +15,7 @@
15
15
  // A new module: the page's modules are cached at unversioned URLs, and a
16
16
  // new export of an old module would leave a cached copy without it.
17
17
 
18
+ import { CACHE_COST } from "./cache_cost_text.js";
18
19
  import { createChipPopover, SHEET_TALL } from "./chip_popover.js";
19
20
  import { DEFAULT, commandLine as levelLine, segments } from "./level_chip.js";
20
21
  import { BUDGET_ERROR, commandLine as contextLine, ownValues, parseBudget } from "./llm_context_chip.js";
@@ -26,7 +27,7 @@ import { html, nothing, render } from "./vendor/lit-html.js";
26
27
  export const PANEL_LABEL = "Session settings";
27
28
  export const NOTE = "From the next turn's start.";
28
29
  export const RUNNING_NOTE = "A turn is running: it applies after this turn.";
29
- const CONTEXT_COST = "Turning forget on or off re-reads the whole prompt once.";
30
+ const CONTEXT_COST = CACHE_COST.llmContext;
30
31
 
31
32
  // A level's own value ("low"), null when it follows the model.
32
33
  const levelOwn = (summary) => summary?.own || null;
@@ -1,7 +1,8 @@
1
1
  import { choiceWords } from "./llm_context_chip.js";
2
2
  import { MODEL_KEY, modelsFailedText } from "./model_pick.js";
3
3
  import { createModelPicker } from "./model_picker.js";
4
- import { chainNeighbours, freshLink } from "./chains.js";
4
+ import { chainNeighbours } from "./chains.js";
5
+ import { freshLinkPick, modelSwitchable, registerPick } from "./model_switch.js";
5
6
  import { readStored } from "./storage.js";
6
7
  import { createStartSettings, overrides, settingsLabel } from "./start_settings.js";
7
8
  import { createStartToolkit, toolkitLabel, toolkitOverride } from "./start_toolkit.js";
@@ -10,7 +11,7 @@ import { createStartToolkit, toolkitLabel, toolkitOverride } from "./start_toolk
10
11
  // The hosts' models from GET /api/models, the choice this browser made last
11
12
  // preselected while it is still offered (else the server's default). Hidden
12
13
  // until the list is in, and in a session (its model is in the info bar),
13
- // but a fresh chain link's (chains.js freshLink): there it shows the link's
14
+ // but a fresh chain link's (model_switch.js freshLinkPick): there it shows the link's
14
15
  // model and a pick runs /model in the link, remembered neither as this
15
16
  // browser's choice nor in Recent. A host that failed is the picker's
16
17
  // tooltip; a route that fails leaves the picker hidden and the server's
@@ -26,6 +27,8 @@ import { createStartToolkit, toolkitLabel, toolkitOverride } from "./start_toolk
26
27
  // kind of choice (Auto, nothing sent, by default), with its own override
27
28
  // chip and dot; hidden without GET /api/models' toolkits.
28
29
  export const START_PICK_TITLE = "The model the new session starts on";
30
+ // On <body> while the list is open from the bar's name (index.html shows the panel then).
31
+ const SWITCH_CLASS = "model-switch";
29
32
 
30
33
  // Used by app.js. Elements: +pickEl+ (the picker's button), +panelEl+,
31
34
  // +searchEl+, +listEl+, +composerEl+, +centerEl+ (model_picker.js'),
@@ -140,7 +143,9 @@ export function createStartPage({
140
143
  center: centerEl,
141
144
  remember: () => !selected(),
142
145
  onPick: (name) => {
143
- if (selected()) pickForLink(name);
146
+ // The session's own model again: nothing to switch.
147
+ if (selected() && name === state().model) return focusPrompt();
148
+ if (selected()) pickForSession(name);
144
149
  else {
145
150
  renderOverrides();
146
151
  syncStartPickLabel();
@@ -148,11 +153,13 @@ export function createStartPage({
148
153
  focusPrompt();
149
154
  },
150
155
  });
151
- // A pick on a fresh link: /model in its worker (its command bubble and the
152
- // info bar follow from command_ran); refused, the button goes back to the
153
- // link's model, if the page is still on that link.
154
- function pickForLink(name) {
156
+ // A pick in a session (a fresh link's): /model in its worker (its command
157
+ // bubble and the info bar follow from command_ran); refused, the button
158
+ // goes back to the session's model, if the page is still on it.
159
+ function pickForSession(name) {
155
160
  const id = selected();
161
+ // Before it goes: its command_ran may come before the POST's answer (D9 B).
162
+ registerPick(id, `/model ${name}`);
156
163
  const ran = run(`/model ${name}`).then((ok) => {
157
164
  const ranEarly = pendingPick === ran && pickRanEarly;
158
165
  if (pendingPick === ran) {
@@ -182,13 +189,16 @@ export function createStartPage({
182
189
  const current = state();
183
190
  // The list walk only for a link that is fresh otherwise (the info bar
184
191
  // calls this every second while a turn runs).
185
- const fresh = !!open && freshLink(current, { running: running() })
192
+ const fresh = !!open && freshLinkPick(current, { running: running() })
186
193
  && !chainNeighbours(sessions(), open, { continues: current.continues }).next;
187
194
  doc.body.classList.toggle("fresh-link", fresh);
188
195
  const linkId = fresh ? open : null;
189
196
  // Another session (or the start page), or the link stopped being fresh:
190
197
  // a panel left open would come back open where it no longer belongs.
191
198
  if (open !== pickSelected || linkId !== pickLinkId) modelPicker.close();
199
+ // Opened from the bar's name: closed once the session can't switch (a
200
+ // turn started, a terminal took it, it was continued).
201
+ else if (doc.body.classList.contains(SWITCH_CLASS) && !sessionSwitchable(open, current)) modelPicker.close();
192
202
  pickSelected = open;
193
203
  pickLinkId = linkId;
194
204
  if (fresh) {
@@ -206,6 +216,25 @@ export function createStartPage({
206
216
  }
207
217
  }
208
218
  }
219
+ // The open session may switch from a control (model_switch.js), as the
220
+ // bar's rule reads it.
221
+ function sessionSwitchable(open, current) {
222
+ const archived = !!sessions().find((s) => s.id === open)?.archived;
223
+ const hasNext = !!chainNeighbours(sessions(), open, { continues: current.continues }).next;
224
+ return modelSwitchable(current, { running: running(), hasNext, archived });
225
+ }
226
+ // The bar's model name opens the list for the open session (+from+: the
227
+ // name's selector, the picker's opener): its model chosen, a pick runs
228
+ // /model there (pickForSession); a click while open closes it.
229
+ // body.model-switch shows the panel in a session that isn't a fresh link.
230
+ function openForSession(from) {
231
+ if (modelPicker.isOpen()) return modelPicker.close();
232
+ const open = selected();
233
+ if (!open || pickEl.hidden || !sessionSwitchable(open, state())) return undefined;
234
+ modelPicker.show(state().model);
235
+ doc.body.classList.add(SWITCH_CLASS);
236
+ return modelPicker.open({ from, onClose: () => doc.body.classList.remove(SWITCH_CLASS) });
237
+ }
209
238
  // A command_ran with a model (stream_handlers.js): while a pick is in
210
239
  // flight its ack syncs again.
211
240
  function commandRan() {
@@ -269,6 +298,10 @@ export function createStartPage({
269
298
 
270
299
  return {
271
300
  syncModelPick, commandRan, restoreStartPick, loadModels, chosenModel, newChoices, clearChoices, dropChoices,
301
+ openForSession,
302
+ // The models list is in: the bar's name may open it (info_bar_model.js sessionBar's modelSwitch).
303
+ // (An older cached model_picker.js has no open: the name stays plain text.)
304
+ modelsLoaded: () => !pickEl.hidden && typeof modelPicker.open === "function",
272
305
  // A fresh link's /model still in flight (a send waits for it), or null.
273
306
  pendingPick: () => pendingPick,
274
307
  // Start refused the picked kit (400 toolkit_refused): said in the 🧰
@@ -62,6 +62,8 @@ import {
62
62
  retryStatusLine, steerCutLine, turnOutput,
63
63
  } from "./turn_events.js";
64
64
  import { commandView, drawCommandBubble, historyHasCommandBubble } from "./commands.js";
65
+ import { isModelMark } from "./model_mark.js";
66
+ import { dropAnsweredBlock, pickReply, workerMarks } from "./model_switch.js";
65
67
  import { keepEarlyRestore, restoreAction } from "./restore.js";
66
68
  import { setBadgeMode } from "./participant_names.js";
67
69
  import { isParticipantAuthor } from "./participant_model.js";
@@ -349,6 +351,11 @@ export function createStreamHandlers(deps) {
349
351
  // Another session was opened during the re-read: the bubble isn't its.
350
352
  if (selected() !== id) return;
351
353
  }
354
+ // A picked switch's --yes, applied: its mark is the trace (model_switch.js, D9 B).
355
+ if (pickReply(id, view, { marks: workerMarks(store.current.workerFeatures, store.current.bridgeUp) }) === "skip") {
356
+ dropAnsweredBlock(findInTurnRoots(".bubble.command"), view.line);
357
+ return;
358
+ }
352
359
  // A card's action that isn't anytime (the step-limit question's
353
360
  // /continue) has no bubble: nothing to remove. An anytime or queued
354
361
  // one's bubble was drawn at its command_queued: filled in here. One
@@ -378,7 +385,10 @@ export function createStreamHandlers(deps) {
378
385
  // A /working-set line queued for after the turn: pending in the list.
379
386
  workingSet?.commandQueued(data);
380
387
  // A card's action waits for its command_ran: shown only if it answers.
381
- if ((data.anytime || data.waits) && !data.card && !commandBubble(data.command_id)) addCommandBubble(commandView(data, clientId));
388
+ // So does a picked switch's --yes (model_switch.js).
389
+ const view = commandView(data, clientId);
390
+ if (pickReply(selected(), view, { marks: workerMarks(store.current.workerFeatures, store.current.bridgeUp), queued: true }) === "skip") return;
391
+ if ((data.anytime || data.waits) && !data.card && !commandBubble(data.command_id)) addCommandBubble(view);
382
392
  },
383
393
  // Due reminders went into the turn (a reminder turn has no prompt bubble).
384
394
  reminder_injected: (data) => {
@@ -491,7 +501,8 @@ export function createStreamHandlers(deps) {
491
501
  store.update({ current: { toolkit: data.toolkit || null } });
492
502
  }
493
503
  if (shownElsewhere(data, capabilities())) return;
494
- if (!turnDom.notice(data)) showHookNotice(data);
504
+ // A /model switch's mark is the history's own line, never a turn's row.
505
+ if (isModelMark(data) || !turnDom.notice(data)) showHookNotice(data);
495
506
  },
496
507
  // The loop asks again after an empty answer: a row of the empty step
497
508
  // (a reload puts it back from the snapshot's cards).
@@ -3,6 +3,7 @@
3
3
  // the session bar's, settings_chip.js) and the /thinking line a session's
4
4
  // pick runs in its worker.
5
5
 
6
+ import { CACHE_COST } from "./cache_cost_text.js";
6
7
  import * as level from "./level_chip.js";
7
8
 
8
9
  export const LEVELS = ["off", "low", "medium", "high"];
@@ -12,7 +13,7 @@ export const CONFIG = Object.freeze({
12
13
  prefix: "think",
13
14
  command: "/thinking",
14
15
  levels: LEVELS,
15
- cost: "A thinking change: on Gemma the whole prompt is read again; a hosted API reads the whole conversation again.",
16
+ cost: CACHE_COST.thinking,
16
17
  });
17
18
 
18
19
  // The /thinking line for a level, with --yes (level_chip.js commandLine);