samagotchi 0.174.0 → 0.176.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 (63) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +38 -1
  3. data/bin/chi +1 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/cli.md +3 -0
  6. data/docs/configuration.md +1 -0
  7. data/docs/internals/bridge.md +10 -3
  8. data/docs/internals/engine.md +2 -2
  9. data/docs/internals/participants.md +11 -5
  10. data/docs/internals/web-frontend.md +44 -11
  11. data/docs/sessions.md +2 -2
  12. data/docs/testing.md +25 -3
  13. data/lib/samagotchi/answer_text.rb +4 -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/llm/stray_tool_call.rb +7 -4
  18. data/lib/samagotchi/llm_context_stale.rb +2 -1
  19. data/lib/samagotchi/message_parts.rb +5 -2
  20. data/lib/samagotchi/model_markup.rb +22 -0
  21. data/lib/samagotchi/model_profile.rb +8 -7
  22. data/lib/samagotchi/participant_uploads.rb +14 -1
  23. data/lib/samagotchi/prompt_literal_guard.rb +7 -6
  24. data/lib/samagotchi/task_transcript.rb +10 -5
  25. data/lib/samagotchi/tool_call_parser.rb +6 -5
  26. data/lib/samagotchi/turn_note.rb +2 -1
  27. data/lib/samagotchi/version.rb +1 -1
  28. data/lib/samagotchi/web/app.rb +15 -2
  29. data/lib/samagotchi/web/participant_images.rb +16 -12
  30. data/lib/samagotchi/web/participant_show.rb +1 -0
  31. data/lib/samagotchi/web/participant_view.rb +31 -3
  32. data/lib/samagotchi/web/public/app.js +18 -4
  33. data/lib/samagotchi/web/public/composer_fold.js +3 -1
  34. data/lib/samagotchi/web/public/composer_grip.js +18 -10
  35. data/lib/samagotchi/web/public/composer_mount.js +17 -6
  36. data/lib/samagotchi/web/public/reload_check.js +0 -3
  37. data/lib/samagotchi/web/public/restore.js +3 -1
  38. data/lib/samagotchi/web/public/session_prefs.js +89 -0
  39. data/lib/samagotchi/web/public/session_sync.js +3 -0
  40. data/lib/samagotchi/web/public/session_view.js +41 -3
  41. data/lib/samagotchi/web/public/stage_asking.js +21 -18
  42. data/lib/samagotchi/web/public/stage_cloud.js +3 -2
  43. data/lib/samagotchi/web/public/stage_missing.js +148 -0
  44. data/lib/samagotchi/web/public/stage_model.js +2 -1
  45. data/lib/samagotchi/web/public/stage_view.js +14 -4
  46. data/lib/samagotchi/web/public/stage_view_memory.js +76 -0
  47. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  48. data/lib/samagotchi/web/public/turn_events.js +1 -1
  49. data/lib/samagotchi/web/public/working_set_rail.js +22 -7
  50. data/lib/samagotchi/web/public/ws_reader.js +2 -0
  51. data/lib/samagotchi/web/server.rb +6 -2
  52. data/lib/samagotchi/web/session_show.rb +42 -4
  53. data/lib/samagotchi/worker/child_side.rb +123 -0
  54. data/lib/samagotchi/worker/command_queue.rb +346 -0
  55. data/lib/samagotchi/worker/leave.rb +286 -0
  56. data/lib/samagotchi/worker/scratch.rb +99 -0
  57. data/lib/samagotchi/worker/signal_grace.rb +96 -0
  58. data/lib/samagotchi/worker/startup.rb +92 -0
  59. data/lib/samagotchi/worker/wake_turns.rb +190 -0
  60. data/lib/samagotchi/worker.rb +24 -1065
  61. data/lib/samagotchi/worker_exit_claim.rb +12 -0
  62. metadata +12 -2
  63. data/lib/samagotchi/web/public/cards_offscreen.js +0 -69
@@ -1,11 +1,13 @@
1
1
  import { GRIP_CLICK_FOLD_MS, GRIP_OPEN_PX, gripFloor, gripFolds, gripGesture } from "./composer_size.js";
2
- import { COMPOSER_FOLD_KEY, composerFolded, foldHandle, opensOnKey } from "./composer_fold.js";
3
- import { readStored, removeStored, writeStored } from "./storage.js";
2
+ import { composerFolded, foldHandle, opensOnKey } from "./composer_fold.js";
3
+ import { COMPOSER_FLOOR, COMPOSER_FOLD, forget as forgetPref, read as readPref, write as writePref } from "./session_prefs.js";
4
4
 
5
5
  // The composer's grip and fold (made by composer_mount.js): the grip's drag, click
6
6
  // and keys, the fold's state per visit and its page-wide listeners. The mount keeps
7
7
  // the box's height (fitPrompt) and the grip's floor (+floor+ / +setFloor+), which
8
- // fitPrompt reads; the floor is saved under GRIP_KEY.
8
+ // fitPrompt reads; the floor is saved per session (session_prefs.js
9
+ // COMPOSER_FLOOR, chi_composer_floor:<session>; the start page's in memory).
10
+ // GRIP_KEY: its name, kept for an older importer.
9
11
  export const GRIP_KEY = "chi_composer_floor";
10
12
  // A card's text field with the focus folds the composer on these screens.
11
13
  const CARD_FIELD_SCREEN = "(max-width: 600px), (hover: none) and (pointer: coarse)";
@@ -56,9 +58,11 @@ export function createComposerGrip({
56
58
  // The grip's custom height, forgotten only by a double-click.
57
59
  function resetFloor() {
58
60
  setFloor(null);
59
- removeStored(GRIP_KEY);
61
+ forgetPref(COMPOSER_FLOOR, session());
60
62
  fitPrompt();
61
63
  }
64
+ // The floor saved, for the open session (the start page: in memory).
65
+ const saveFloor = (px) => writePref(COMPOSER_FLOOR, session(), String(px || ""));
62
66
 
63
67
  // One release of the grip is one gesture, decided by composer_size.js's
64
68
  // gripGesture: a drag down past the box folds the composer on release (a
@@ -123,7 +127,7 @@ export function createComposerGrip({
123
127
  // The drag asked for a smaller box, but opening it brings back the
124
128
  // height it had before the press: only a double-click forgets it.
125
129
  setFloor(floorBefore);
126
- writeStored(GRIP_KEY, String(floorBefore || ""));
130
+ saveFloor(floorBefore);
127
131
  setComposerFolded(true);
128
132
  } else if (gesture === "open") {
129
133
  cancelPendingFold();
@@ -132,7 +136,7 @@ export function createComposerGrip({
132
136
  } else if (gesture === "reset") {
133
137
  resetFloor();
134
138
  } else if (gesture === "hide") {
135
- writeStored(GRIP_KEY, String(floor() || ""));
139
+ saveFloor(floor());
136
140
  pendingFold = setTimeout(() => {
137
141
  pendingFold = null;
138
142
  setComposerFolded(true);
@@ -140,7 +144,7 @@ export function createComposerGrip({
140
144
  } else if (gesture === "resize") {
141
145
  // A drag that stops short of folding: keep the box at the height it asks for.
142
146
  cancelPendingFold();
143
- writeStored(GRIP_KEY, String(floor() || ""));
147
+ saveFloor(floor());
144
148
  // A pull that opened the box leaves the focus in it, as a tap does.
145
149
  if (opened) promptEl.focus();
146
150
  }
@@ -178,11 +182,11 @@ export function createComposerGrip({
178
182
  // Dragging the composer's grip down folds the session's composer away; the
179
183
  // grip, now the handle on the info bar's top edge, pulled up or clicked, or
180
184
  // typing on the page, brings it back. The user's own choice is saved per
181
- // browser; an archived session opens folded for its visit, and expanding
185
+ // session (chi_composer_collapsed:<session>); an archived session opens folded for its visit, and expanding
182
186
  // there saves nothing. The page's own focus or a restored line opens it
183
187
  // for the visit only. The start page never folds.
184
188
  function composerFoldSaved() {
185
- return readStored(COMPOSER_FOLD_KEY) === "1";
189
+ return readPref(COMPOSER_FOLD, session()) === "1";
186
190
  }
187
191
  function isComposerFolded() {
188
192
  return !!session() && composerFolded({ saved: composerFoldSaved(), archivedVisit: foldVisit.archived, visitOpen: foldVisit.open, cardField: !!cardField });
@@ -231,7 +235,7 @@ export function createComposerGrip({
231
235
  if (foldVisit.archived) {
232
236
  foldVisit.open = !folded;
233
237
  } else {
234
- writeStored(COMPOSER_FOLD_KEY, folded ? "1" : "0");
238
+ writePref(COMPOSER_FOLD, session(), folded ? "1" : "0");
235
239
  foldVisit.open = false;
236
240
  }
237
241
  applyComposerFolded();
@@ -307,9 +311,13 @@ export function createComposerGrip({
307
311
  // A new visit (select(), the start page): nothing opened, not decided.
308
312
  newVisit() {
309
313
  releaseCardField();
314
+ // A click's fold still waiting was for the session left, not this one.
315
+ cancelPendingFold();
310
316
  foldVisit = newFoldVisit();
311
317
  applyComposerFolded();
312
318
  },
319
+ // The open session's saved fold, drawn again (session_prefs.js).
320
+ applyFolded: () => applyComposerFolded(),
313
321
  // The visit's first getSession answer: an archived session opens folded.
314
322
  decideVisit(archived) {
315
323
  if (foldVisit.decided) return;
@@ -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,
@@ -91,9 +91,6 @@ const NOT_CARDS = (item) => item.kind !== "card" && item.kind !== "question";
91
91
  // @param render (data) => that read drawn as a reload draws it (a fragment)
92
92
  // @param cards () => the page's card registry (card_registry.js); without
93
93
  // it, the cards and questions are left out
94
- // @param place unused: an older app.js passes cards_offscreen.js's placer
95
- // @param capabilities () => the page's capabilities (unused now; an older
96
- // app.js passes it)
97
94
  // @param post (id, body) => the counts to chi web
98
95
  export function createReloadCheck({ enabled, sessionId, running, read, render, cards = null, post }) {
99
96
  // The hand-off's pieces (stage_view.js onHandedOff), in their order;
@@ -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 } } : {}),
@@ -0,0 +1,89 @@
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. Each is kept under `<key>:<session>`, so what
4
+ // you do to one session's window never shows in another, and a session never
5
+ // set by hand follows the default: the page's own (the stage fold's comes
6
+ // from config, web.stage_collapsed, as <body data-stage-collapsed="1">), else
7
+ // the module's built-in one (+fallback+).
8
+ //
9
+ // With no session (the start page) nothing is written: the value lives in
10
+ // this page's memory only, until a reload.
11
+ //
12
+ // The old global keys (chi_stage_collapsed, chi_composer_floor,
13
+ // chi_composer_collapsed, chi_working_set_collapsed) are neither read nor
14
+ // written, and left in storage as they are.
15
+ //
16
+ // One sweep for all of its keys (sweepSessionPrefs), with an unscoped session
17
+ // list only: these keys record no project root, so a project's list, which
18
+ // knows its own sessions only, sweeps nothing.
19
+ //
20
+ // A module of its own: static JS is cached at unversioned URLs, and a new
21
+ // export on an old module would blank the page.
22
+ import { readStored, removeStored, storedKeys, writeStored } from "./storage.js";
23
+
24
+ export const STAGE_FOLD = "chi_stage_collapsed";
25
+ export const COMPOSER_FLOOR = "chi_composer_floor";
26
+ export const COMPOSER_FOLD = "chi_composer_collapsed";
27
+ export const WS_RAIL_FOLD = "chi_working_set_collapsed";
28
+ export const PREF_KEYS = [STAGE_FOLD, COMPOSER_FLOOR, COMPOSER_FOLD, WS_RAIL_FOLD];
29
+
30
+ // The page's defaults: <body>'s data attribute that turns a key on ("1").
31
+ const PAGE_DEFAULTS = { [STAGE_FOLD]: "stageCollapsed" };
32
+
33
+ // The start page's values (no session), in memory only.
34
+ const unsaved = new Map();
35
+
36
+ // The stored key for +key+ in +session+, null without one.
37
+ export function prefKey(key, session) {
38
+ return session ? `${key}:${session}` : null;
39
+ }
40
+
41
+ // The page's default for +key+ ("1" when its body attribute is on), else null.
42
+ function pageDefault(key) {
43
+ const attr = PAGE_DEFAULTS[key];
44
+ if (!attr) return null;
45
+ try {
46
+ return globalThis.document?.body?.dataset?.[attr] === "1" ? "1" : null;
47
+ } catch (_) {
48
+ return null;
49
+ }
50
+ }
51
+
52
+ // +session+'s value for +key+ (a string), else the page's default, else +fallback+.
53
+ export function read(key, session, fallback = null) {
54
+ const own = session ? readStored(prefKey(key, session)) : (unsaved.has(key) ? unsaved.get(key) : null);
55
+ if (own !== null) return own;
56
+ return pageDefault(key) ?? fallback;
57
+ }
58
+
59
+ // +value+ (a string) for +key+ in +session+ only; no session: in memory.
60
+ export function write(key, session, value) {
61
+ if (!session) {
62
+ unsaved.set(key, String(value));
63
+ return;
64
+ }
65
+ writeStored(prefKey(key, session), String(value));
66
+ }
67
+
68
+ // +session+'s own value for +key+ forgotten (it follows the default again);
69
+ // no session: the memory's.
70
+ export function forget(key, session) {
71
+ if (!session) {
72
+ unsaved.delete(key);
73
+ return;
74
+ }
75
+ removeStored(prefKey(key, session));
76
+ }
77
+
78
+ // The session list loaded (+sessions+, each {id}): the keys of sessions not
79
+ // in it go. +scoped+ (a project's list): nothing goes.
80
+ export function sweepSessionPrefs(sessions, { scoped = false } = {}) {
81
+ if (scoped) return;
82
+ const ids = new Set((Array.isArray(sessions) ? sessions : []).map((s) => s?.id).filter(Boolean));
83
+ for (const key of PREF_KEYS) {
84
+ const prefix = `${key}:`;
85
+ for (const stored of storedKeys(prefix)) {
86
+ if (!ids.has(stored.slice(prefix.length))) removeStored(stored);
87
+ }
88
+ }
89
+ }
@@ -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(() => {
@@ -21,6 +21,8 @@
21
21
  // bubbles, cards bubbles.js, cards_place.js
22
22
  // cardRegistry the open session's cards as data (card_registry.js): seeded
23
23
  // from a read before its replay, reset with the session; null: none
24
+ // stageMissing the stage's running-with-no-turn check (stage_missing.js);
25
+ // null: no check (the render then says nothing)
24
26
  // markdown markdown_place.js (linkTextRefs, applyFinalMarkdown)
25
27
  // capabilities() the page's capabilities (card.js shownElsewhere, the history's cards)
26
28
  // page: {setReviseAnchor(anchor), renderInitRow(), setMarkdownWarning(warning),
@@ -30,7 +32,9 @@
30
32
  // later: {handlers(), composer(), ownerVerify(), commandList(), initTasks(), resetTurnView()}
31
33
  // the views made after this one, and session_sync.js's resetTurnView
32
34
  //
33
- // @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
34
38
  // Its own module: new exports go in new modules (web-frontend.md).
35
39
 
36
40
  import { emptySessionState, sessionStateFrom } from "./session_state.js";
@@ -46,12 +50,13 @@ import { turnHistoryNodes } from "./turn_block.js";
46
50
  import { lastActivity } from "./time_gaps.js";
47
51
  import { elementOf, emptyAnswerTemplate } from "./turn_html.js";
48
52
  import { stillOn } from "./latest.js";
53
+ import { applyView, captureView, createStageViewMemory } from "./stage_view_memory.js";
49
54
 
50
55
  export function createSessionView(deps) {
51
56
  const {
52
57
  store, historyEl, getSession,
53
58
  liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet = null, wsPreview = null, gapClock,
54
- bubbles, cards, markdown, capabilities, page, later, cardRegistry = null,
59
+ bubbles, cards, markdown, capabilities, page, later, cardRegistry = null, stageMissing = null,
55
60
  } = deps;
56
61
  const { makeUserBubble, addEndBubble, showGuardrailWarning, showRecap } = bubbles;
57
62
  const { placeSnapshotCards, upsertCard } = cards;
@@ -62,6 +67,14 @@ export function createSessionView(deps) {
62
67
  } = page;
63
68
  // The open session's id, for the stale-answer guards (latest.js stillOn).
64
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
+ }
65
78
 
66
79
  // Forget everything the page knew about the open session: its fields (the
67
80
  // info bar, composer, command list), the turn on view, its stream and
@@ -72,6 +85,10 @@ export function createSessionView(deps) {
72
85
  // "delegated by" parent, its commands, its card actions) never shows for
73
86
  // the next one, also when the next one's read fails.
74
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;
75
92
  if (!keepVerify) later.ownerVerify().clear();
76
93
  if (!keepVerify) setReviseAnchor(null);
77
94
  store.batch(() => {
@@ -91,12 +108,24 @@ export function createSessionView(deps) {
91
108
  // The reader and the peek are the session's: another one (or none, the
92
109
  // start page) never finds them over #center, the composer inert under it.
93
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?.();
94
121
  }
95
122
 
96
123
  // A session view: its messages, then the turn in progress and the queued
97
124
  // prompts (a live worker's snapshot) replayed through the stream handlers,
98
125
  // then a pending question.
99
126
  function renderSessionView(data, { kept = [] } = {}) {
127
+ applyPrefs();
128
+ drawnId = store.selected;
100
129
  setMarkdownWarning(data.markdown_warning);
101
130
  markdownTip.show(data.markdown_tip);
102
131
  setCapabilities(data.capabilities, data.editor_url, data.viewer);
@@ -178,6 +207,14 @@ export function createSessionView(deps) {
178
207
  }
179
208
  // A turn ran out of iterations and waits for a yes or no.
180
209
  if (data.continue_offer) questionCards.renderContinue(data.continue_offer);
210
+ // The read is drawn: a running session whose stage holds no turn keeps its
211
+ // bare status row and marks itself (stage_missing.js).
212
+ if (stageMissing) {
213
+ stageMissing.note(data);
214
+ stageMissing.check();
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 });
181
218
  // A whole view drawn: the composer and the bar once more (the working
182
219
  // set's seed may change the bar's chip).
183
220
  store.batch(() => {
@@ -271,6 +308,7 @@ export function createSessionView(deps) {
271
308
  // left the collapsed block (card.js leavesBlock), where a reload puts them.
272
309
  function endTurnView(kind, endText = null, { emptyAnswer = null, stopped = false } = {}) {
273
310
  setTurnRunning(false);
311
+ viewMemory.drop(store.selected);
274
312
  // Every ended turn has a record (completed, canceled, failed); a worker
275
313
  // gone mid-turn is re-rendered (resync), which counts again.
276
314
  if (kind !== "gone") liveTurn.timing.ended += 1;
@@ -289,5 +327,5 @@ export function createSessionView(deps) {
289
327
  if (questionCards.pendingQuestion()) questionCards.resolveQuestion(questionCards.pendingQuestion().id, { cancelled: true, reason: "turn ended" });
290
328
  }
291
329
 
292
- return { forgetSession, renderSessionView, historyOpts, reloadRender, readTurnEnd, endTurnView };
330
+ return { forgetSession, renderSessionView, historyOpts, reloadRender, readTurnEnd, endTurnView, leaveSession };
293
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
@@ -124,12 +127,6 @@ export function createStageAsking({
124
127
  opener.open(handOffOrder({ prompt: promptEl(), block: blockEl, extras: rows }), { follow });
125
128
  }
126
129
 
127
- // A no-op kept one release for a mixed cache (remove in the next one): a
128
- // stale stage_view.js (0.172.1's) calls it at the end of each refresh. The
129
- // drift check it ran is the tests' now (stage_cuts_parity.test.js
130
- // crossCheck, the e2e's stage check).
131
- function reconcileWaiting() {}
132
-
133
130
  // An opened turn's cards that stopped waiting go into the history: one
134
131
  // with a lead-in under it (also after the turn's end, so a card
135
132
  // cancelled by Stop turn sits there), another one at the history's end
@@ -264,7 +261,7 @@ export function createStageAsking({
264
261
  } else {
265
262
  choice = value;
266
263
  revealed = false;
267
- writeStored(COLLAPSE_KEY, value ? "1" : "0");
264
+ writePref(STAGE_FOLD, sessionId(), value ? "1" : "0");
268
265
  }
269
266
  applyCollapsed();
270
267
  // Opened on a waiting card: it shows as it does on arrival.
@@ -273,13 +270,19 @@ export function createStageAsking({
273
270
  }
274
271
 
275
272
  return {
276
- askingGen, asksOf, askedFor, askedText, docks, leadInText, openTurn, reconcileWaiting, settleCards, askingCard, cardOf, foldedText, markOwnToggles,
273
+ askingGen, asksOf, askedFor, askedText, docks, leadInText, openTurn, settleCards, askingCard, cardOf, foldedText, markOwnToggles,
277
274
  isCollapsed, trackFold, drawCollapsed, applyCollapsed, setCollapsed,
278
275
  // A ref's "show in turn" opens a collapsed stage for this turn only.
279
276
  reveal() {
280
277
  revealed = true;
281
278
  applyCollapsed();
282
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
+ },
283
286
  // The stage cleared: a reveal ends with it.
284
287
  unreveal() {
285
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.
@@ -0,0 +1,148 @@
1
+ // A running session whose stage shows nothing of its turn (docs/internals/web-frontend.md,
2
+ // "A running session without a turn"). At the points a turn could have been
3
+ // drawn — the end of a render (session_view.js), the hand-off and the end of a
4
+ // fold (stage_view.js's clearStage) — and again on a resize, a composer that
5
+ // changed size or a status change, it does two things:
6
+ // the safety net: the session's status runs and the stage holds no turn, so
7
+ // the stage keeps its bare status row ("running", Stop turn) instead of
8
+ // vanishing (runningWithoutTurn, stage_view.js), and a status that leaves
9
+ // running takes that row with it;
10
+ // the diagnostic: the stage is marked `data-stage-missing` ("1" for no turn,
11
+ // "covered" for a turn the composer card is over) and, once per session
12
+ // visit, a console.warn with counts only — never a prompt, a message or an
13
+ // answer — saying what the read had (live_read, current_turn, the replay's
14
+ // event types and their counts, the last replayed end event's turn id beside
15
+ // the running turn's) and where the stage sat (its status row's top and
16
+ // bottom, the composer's top, the window's height, the composer's saved floor
17
+ // and fold). The covered case is reported only: a stage the user made tall is
18
+ // their own doing, and the net is for a stage that shows nothing at all.
19
+ //
20
+ // The numbers come from getBoundingClientRect at the call; the pure functions
21
+ // take them as arguments, so a spec can pass its own. Its own module: new
22
+ // exports go in new modules (web-frontend.md).
23
+ import { COMPOSER_FLOOR, COMPOSER_FOLD, read as readPref } from "./session_prefs.js";
24
+
25
+ // The replay events that end a turn.
26
+ const ENDS = ["turn_completed", "turn_canceled", "turn_failed"];
27
+
28
+ // What a show read said, in counts.
29
+ export function readCounts(data = {}) {
30
+ const replay = Array.isArray(data.replay) ? data.replay : [];
31
+ const events = {};
32
+ let lastEndTurn = null;
33
+ for (const event of replay) {
34
+ events[event.type] = (events[event.type] || 0) + 1;
35
+ if (ENDS.includes(event.type)) lastEndTurn = event.turn_id ?? null;
36
+ }
37
+ return {
38
+ liveRead: data.live_read ?? null,
39
+ currentTurn: data.current_turn?.turn_id ?? null,
40
+ replay: replay.length,
41
+ events,
42
+ lastEndTurn,
43
+ };
44
+ }
45
+
46
+ // The stage's status row out of sight: wholly above or below the window, or
47
+ // below the composer card's top edge (the dock puts the stage above it:
48
+ // index.html, .turn-stage). A hidden stage is hidden, not covered; a row with
49
+ // no measured height (a stub, a stage not yet laid out) says nothing.
50
+ export function stageCovered({ hidden, stageTop, stageBottom, composerTop, viewport }) {
51
+ if (hidden) return false;
52
+ if (stageBottom > stageTop && (stageBottom <= 0 || stageTop >= viewport)) return true;
53
+ return composerTop !== null && stageTop > composerTop;
54
+ }
55
+
56
+ // Why the stage shows nothing of a turn, or null when it shows it: "none" (no
57
+ // turn in the stage), "covered" (it holds one, out of sight).
58
+ export function missingReason({ status, holds, hidden, stageTop, stageBottom, composerTop, viewport }) {
59
+ if (status !== "running") return null;
60
+ if (!holds) return "none";
61
+ return stageCovered({ hidden, stageTop, stageBottom, composerTop, viewport }) ? "covered" : null;
62
+ }
63
+
64
+ // The console line: counts, no text from the session.
65
+ export function missingLine({ session, reason, counts, stage, composer }) {
66
+ const events = Object.entries(counts.events || {}).map(([type, n]) => `${type}=${n}`).join(" ") || "none";
67
+ return `stage-missing ${session || "none"} (${reason}) live_read=${counts.liveRead ?? "unknown"} ` +
68
+ `current_turn=${counts.currentTurn ?? "none"} replay=${counts.replay} events=${events} ` +
69
+ `last_end=${counts.lastEndTurn ?? "none"} vs turn=${counts.currentTurn ?? "none"} ` +
70
+ `stage_row=${stage.stageTop}..${stage.stageBottom} composer_top=${stage.composerTop} window=${stage.viewport} ` +
71
+ `composer_floor=${composer.floor ?? "unset"} composer_fold=${composer.fold ?? "unset"}`;
72
+ }
73
+
74
+ // +store+, +turnDom+ the page's views; +composerEl+ the composer card's box;
75
+ // +win+ the page's window; +warn+ where the line goes.
76
+ // @return {note(data), check()}
77
+ export function createStageMissing({ store, turnDom, composerEl, win = globalThis, warn = (line) => console.warn(line) }) {
78
+ const warned = new Set();
79
+ let counts = null;
80
+
81
+ function geometry() {
82
+ const stage = turnDom.root;
83
+ const row = stage.querySelector(".ts-status") || stage;
84
+ const stageRect = row.getBoundingClientRect?.() || { top: 0, bottom: 0 };
85
+ const composerRect = composerEl?.getBoundingClientRect?.() || { top: null, bottom: null };
86
+ return {
87
+ hidden: !!stage.hidden,
88
+ stageTop: stageRect.top ?? 0,
89
+ stageBottom: stageRect.bottom ?? 0,
90
+ // A folded composer shows nothing (composer.css), so it has no top to
91
+ // cover with; neither has one not laid out yet.
92
+ composerTop: composerRect.bottom > composerRect.top ? composerRect.top : null,
93
+ viewport: win?.innerHeight ?? 0,
94
+ };
95
+ }
96
+
97
+ // The stage's state at one of the points a turn could have been drawn.
98
+ function check() {
99
+ const stage = turnDom.root;
100
+ const status = store.current.status;
101
+ if (status !== "running") {
102
+ delete stage.dataset.stageMissing;
103
+ // A status that left running takes the bare row with it: setTurnRunning
104
+ // is not the only writer (turnEndStatus and the hub change the status too).
105
+ turnDom.runningWithoutTurn?.(false);
106
+ return null;
107
+ }
108
+ // The safety net: a session that runs keeps its status row (running and
109
+ // Stop turn) rather than showing nothing. It is a no-op when the stage
110
+ // holds or is folding a turn (stage_view.js's runningWithoutTurn).
111
+ if (!turnDom.holds()) turnDom.runningWithoutTurn?.(true);
112
+ const where = geometry();
113
+ const reason = missingReason({ status, holds: turnDom.holds(), ...where });
114
+ if (!reason) {
115
+ delete stage.dataset.stageMissing;
116
+ return null;
117
+ }
118
+ stage.dataset.stageMissing = reason === "covered" ? "covered" : "1";
119
+ const session = store.selected;
120
+ if (!warned.has(session)) {
121
+ warned.add(session);
122
+ warn(missingLine({
123
+ session, reason, counts: counts || readCounts({}),
124
+ stage: where,
125
+ composer: {
126
+ top: stage.composerTop,
127
+ floor: readPref(COMPOSER_FLOOR, session),
128
+ fold: readPref(COMPOSER_FOLD, session),
129
+ },
130
+ }));
131
+ }
132
+ return reason;
133
+ }
134
+
135
+ // A status write redraws the bar: only a change needs the stage looked at,
136
+ // and only one away from running. A turn that runs is drawn by the render,
137
+ // the hand-off or the fold; a status that comes to running before the replay
138
+ // is drawn would warn about a stage not yet filled.
139
+ let lastStatus = null;
140
+ function checkOnStatus() {
141
+ if (store.current.status === lastStatus) return null;
142
+ lastStatus = store.current.status;
143
+ if (store.current.status === "running") return null;
144
+ return check();
145
+ }
146
+
147
+ return { note: (data) => { counts = readCounts(data); }, check, checkOnStatus };
148
+ }