samagotchi 0.175.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 (48) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +21 -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 +2 -2
  8. data/docs/internals/engine.md +2 -2
  9. data/docs/internals/participants.md +11 -5
  10. data/docs/internals/web-frontend.md +23 -9
  11. data/docs/sessions.md +2 -2
  12. data/lib/samagotchi/bridge.rb +11 -4
  13. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  14. data/lib/samagotchi/config.rb +3 -0
  15. data/lib/samagotchi/participant_uploads.rb +14 -1
  16. data/lib/samagotchi/version.rb +1 -1
  17. data/lib/samagotchi/web/app.rb +15 -2
  18. data/lib/samagotchi/web/participant_images.rb +16 -12
  19. data/lib/samagotchi/web/participant_view.rb +27 -1
  20. data/lib/samagotchi/web/public/app.js +4 -2
  21. data/lib/samagotchi/web/public/composer_fold.js +3 -1
  22. data/lib/samagotchi/web/public/composer_grip.js +18 -10
  23. data/lib/samagotchi/web/public/composer_mount.js +17 -6
  24. data/lib/samagotchi/web/public/restore.js +3 -1
  25. data/lib/samagotchi/web/public/session_prefs.js +89 -0
  26. data/lib/samagotchi/web/public/session_sync.js +3 -0
  27. data/lib/samagotchi/web/public/session_view.js +32 -2
  28. data/lib/samagotchi/web/public/stage_asking.js +20 -11
  29. data/lib/samagotchi/web/public/stage_cloud.js +3 -2
  30. data/lib/samagotchi/web/public/stage_missing.js +3 -5
  31. data/lib/samagotchi/web/public/stage_model.js +2 -1
  32. data/lib/samagotchi/web/public/stage_view.js +6 -1
  33. data/lib/samagotchi/web/public/stage_view_memory.js +76 -0
  34. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  35. data/lib/samagotchi/web/public/turn_events.js +1 -1
  36. data/lib/samagotchi/web/public/working_set_rail.js +22 -7
  37. data/lib/samagotchi/web/public/ws_reader.js +2 -0
  38. data/lib/samagotchi/web/server.rb +6 -2
  39. data/lib/samagotchi/worker/child_side.rb +123 -0
  40. data/lib/samagotchi/worker/command_queue.rb +346 -0
  41. data/lib/samagotchi/worker/leave.rb +286 -0
  42. data/lib/samagotchi/worker/scratch.rb +99 -0
  43. data/lib/samagotchi/worker/signal_grace.rb +96 -0
  44. data/lib/samagotchi/worker/startup.rb +92 -0
  45. data/lib/samagotchi/worker/wake_turns.rb +190 -0
  46. data/lib/samagotchi/worker.rb +24 -1065
  47. data/lib/samagotchi/worker_exit_claim.rb +12 -0
  48. metadata +10 -1
@@ -20,9 +20,12 @@ module Samagotchi
20
20
  module ParticipantImages
21
21
  # One upload's answer: +ref+ when accepted, else +status+, +code+ and
22
22
  # +detail+; +bytes+ the stored size (for the audit line).
23
- Upload = Data.define(:status, :code, :detail, :ref, :bytes) do
24
- def self.refused(status, code, detail) = new(status: status, code: code, detail: detail, ref: nil, bytes: nil)
25
- def self.accepted(ref) = new(status: 201, code: nil, detail: nil, ref: ref, bytes: ref[:bytes])
23
+ Upload = Data.define(:status, :code, :detail, :ref, :bytes, :audit) do
24
+ def self.refused(status, code, detail, audit: true)
25
+ new(status: status, code: code, detail: detail, ref: nil, bytes: nil, audit: audit)
26
+ end
27
+
28
+ def self.accepted(ref) = new(status: 201, code: nil, detail: nil, ref: ref, bytes: ref[:bytes], audit: true)
26
29
  end
27
30
 
28
31
  private
@@ -48,9 +51,9 @@ module Samagotchi
48
51
  # unsupported_image: chi converts those with an external tool), no
49
52
  # size in its header or over MAX_PARTICIPANT_PIXELS / _SIDE (422
50
53
  # image_too_big), their quota (429 too_many_images; a file they own
51
- # already is accepted again, no new entry). Every answer is audited,
52
- # an exception too (internal_error, then raised). The reply is the ref
53
- # without source, mime or bytes.
54
+ # already is accepted again, no new entry). Answers are audited except
55
+ # repeated refusals after the attempts cap; exceptions too (internal_error,
56
+ # then raised). The reply is the ref without source, mime or bytes.
54
57
  def participant_image_upload(req, id, session_dir)
55
58
  grant = principal(req).grant
56
59
  upload = begin
@@ -59,7 +62,7 @@ module Samagotchi
59
62
  audit_image(id, grant, Upload.refused(500, "internal_error", nil))
60
63
  raise
61
64
  end
62
- audit_image(id, grant, upload)
65
+ audit_image(id, grant, upload) if upload.audit
63
66
  return error_response(upload.status, upload.code, upload.detail) unless upload.ref
64
67
 
65
68
  json_response(201, upload.ref.slice(:file, :name, :width, :height))
@@ -72,17 +75,18 @@ module Samagotchi
72
75
  end
73
76
 
74
77
  def participant_upload(req, dir, grant)
75
- over = @participant_images_mutex.synchronize do
78
+ over, first_over = @participant_images_mutex.synchronize do
76
79
  record = ParticipantUploads.read(dir)
77
80
  tried = record.attempts_of(grant.id)
78
- ParticipantUploads.attempt!(dir, grant.id, state: record) if tried < Grants::MAX_IMAGE_ATTEMPTS
79
- tried >= Grants::MAX_IMAGE_ATTEMPTS
81
+ ParticipantUploads.attempt!(dir, grant.id, state: record) if tried <= Grants::MAX_IMAGE_ATTEMPTS
82
+ [tried >= Grants::MAX_IMAGE_ATTEMPTS, tried == Grants::MAX_IMAGE_ATTEMPTS]
80
83
  end
81
84
  if (cap = participant_cap_refusal(grant))
82
- return Upload.refused(*cap)
85
+ return Upload.refused(*cap, audit: !over || first_over)
83
86
  end
84
87
  if over
85
- return Upload.refused(429, "too_many_image_attempts", ParticipantMessages::TOO_MANY_IMAGE_ATTEMPTS)
88
+ return Upload.refused(429, "too_many_image_attempts", ParticipantMessages::TOO_MANY_IMAGE_ATTEMPTS,
89
+ audit: first_over)
86
90
  end
87
91
 
88
92
  bytes = image_upload_bytes(req)
@@ -63,6 +63,9 @@ module Samagotchi
63
63
  # prompts are theirs).
64
64
  "turn_enqueued" => :turn_enqueued,
65
65
  "turn_dequeued" => :turn_dequeued,
66
+ # A failed turn's prompt handed back: the viewer's own turn only
67
+ # (#prompt_restored).
68
+ "prompt_restored" => :prompt_restored,
66
69
  "input_merged" => :input_merged,
67
70
  # The owner's question, approval or Continue offer: "waiting for the
68
71
  # owner" and for what kind of thing (#waiting_kind), nothing of it.
@@ -85,7 +88,7 @@ module Samagotchi
85
88
  card command_output command_queued command_ran context_added empty_answer_retry
86
89
  generation_cancelled generation_progress generation_started guardrail_warning hook_notice
87
90
  llm_context_edited merged_input objectives_updated participants_changed pending_input_merged plugin_init_finished
88
- plugin_init_started plugin_init_wait prompt_restored question question_relay reasoning_history_refused
91
+ plugin_init_started plugin_init_wait question question_relay reasoning_history_refused
89
92
  recap_ready reminder_injected sampling_refused session_end session_start side_usage steer_cut thinking_dropped
90
93
  thinking_refused tool_dispatch_completed tool_dispatch_started used_memories_updated
91
94
  ].freeze
@@ -131,6 +134,29 @@ module Samagotchi
131
134
  { "type" => "turn_dequeued", **seq(event), "enqueued_id" => enqueued_id }
132
135
  end
133
136
 
137
+ # A failed turn of the viewer's own handing its prompt back: the text,
138
+ # their image refs (#image_refs), the Revise draft's turn id and the
139
+ # origin's ids the page matches it by (restore.js restoreAction). nil
140
+ # for anyone else's, the owner's or an automatic turn (decided by the
141
+ # origin's author, which chi web stamped). Never source, the error, a
142
+ # Verify claim's quote or anything else the owner's event carries.
143
+ def prompt_restored(event, viewer)
144
+ origin = field(event, :origin)
145
+ return nil unless origin.is_a?(Hash)
146
+
147
+ author = field(origin, :author)
148
+ return nil unless viewer.own?(author) && Steer.participant_author?(author)
149
+
150
+ out = { "type" => "prompt_restored", **seq(event), "prompt" => field(event, :prompt).to_s }
151
+ images = image_refs(field(event, :images), author, viewer)
152
+ out["images"] = images if images
153
+ revises = ReviseAnchor.from(field(event, :revises))
154
+ out["revises"] = { "turn_id" => revises.turn_id } if revises
155
+ out["origin"] = { "client_id" => field(origin, :client_id).to_s, "enqueued_id" => field(origin, :enqueued_id).to_s,
156
+ "author" => author.to_s }
157
+ out
158
+ end
159
+
134
160
  # Input merged into the running turn: the viewer's own lines (their
135
161
  # origins' enqueued ids) and how many, bare when none is theirs. The
136
162
  # others' (a delegate's report, another person's line) are not named
@@ -75,6 +75,7 @@ import { createBlockHost } from "./block_host.js";
75
75
  import { createWidgetDrawer } from "./inline_widgets.js";
76
76
  import { copyText, installCopy } from "./copy.js";
77
77
  import { installAnswerFold, sweepAnswerFolds } from "./answer_fold.js";
78
+ import { sweepSessionPrefs } from "./session_prefs.js";
78
79
  import { installDetailsMotion } from "./details_motion.js";
79
80
  import { answerLabel, installReviseStacks, reviseChipTemplate, reviseWorkerUnavailable } from "./revise_stack.js";
80
81
  import { createQuestionCards } from "./question_cards.js";
@@ -579,13 +580,14 @@ const scope = {
579
580
  };
580
581
  // The server refused ?dir (a folder deleted since the link was made).
581
582
  let scopeError = null;
582
- // The list's first load sweeps the folded answers of sessions gone since
583
- // (answer_fold.js), once per page.
583
+ // The list's first load sweeps the folded answers and the view settings of
584
+ // sessions gone since (answer_fold.js, session_prefs.js), once per page.
584
585
  let foldsSwept = false;
585
586
  function sweepFoldsOnce() {
586
587
  if (foldsSwept) return;
587
588
  foldsSwept = true;
588
589
  sweepAnswerFolds(store.sessions, { scoped: !!scope.dir });
590
+ sweepSessionPrefs(store.sessions, { scoped: !!scope.dir });
589
591
  }
590
592
 
591
593
  // The list by fetching: the fallback when there is no events stream (a
@@ -1,12 +1,14 @@
1
1
  // The session's composer can fold away for room to read (the info bar under
2
2
  // it stays and becomes the page's bottom edge). The user's own fold or
3
- // unfold is saved per browser (chi_composer_collapsed); an archived
3
+ // unfold is saved per session, per browser (session_prefs.js,
4
+ // chi_composer_collapsed:<session>); an archived
4
5
  // session opens folded for that visit; the page expanding it by itself (a
5
6
  // focus, a restored line, a quote) opens it for the visit only. A visit is
6
7
  // one select() call. A card's text field with the focus on a narrow or touch
7
8
  // screen folds it for that time, on top of all of these (+cardField+): the
8
9
  // keyboard is up and the card needs the rows; nothing is saved.
9
10
 
11
+ // session_prefs.js COMPOSER_FOLD's name, kept for an older importer.
10
12
  export const COMPOSER_FOLD_KEY = "chi_composer_collapsed";
11
13
 
12
14
  // Whether the composer is folded: the saved choice or an archived visit,
@@ -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,
@@ -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(() => {
@@ -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(() => {
@@ -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;