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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 37fbe4f66f3709c6c9d31f106af298d34664b9bfe6817f264fdbf3e51803e462
4
- data.tar.gz: ec4cdea784346d7713c93f38c891245dbc55a9f074a35ea7fb38b2ea032f8968
3
+ metadata.gz: 2e1850bcf8edb0c1a3e30952863bd2fe7e29131b950418af91e8dbc01f19718d
4
+ data.tar.gz: c92e1d3c88c3c9681e89a369a2703a8a5db045201c7a9d363fac3fc54e69f5c2
5
5
  SHA512:
6
- metadata.gz: 6534996033040eed2533845e1ebe0f9af8e3066d3fb5f07c33af243651bcb949fd5e2f2678115596ad28167adb63abccec528e127eabb9516d7f8b80dbf0f280
7
- data.tar.gz: 95c59df9d40e1fd9b13ffc7e265ebca25008265d775fbe62b6d21f9145305eb35ae4c9fc2a4d6a3ccbb6679e67db9cfb7c3f876888aa4680932b34e9c316a862
6
+ metadata.gz: 8b75fbca421b355602e5f58dfd8da360162656600c79fa248eab4220f3857eec01845521aeb9f2329100c22af6d7ddb25a24d16a43604bf272c31aa6ebb9ad89
7
+ data.tar.gz: '08dbb752d378c526265e975bef160ec17ce2c87dfcce110bd1d224ea5faf1dab97bb7d7008b383b2513ebcafe273bf53c82d64fa5185933f38ad98bfc2126063'
data/CHANGELOG.md CHANGED
@@ -8,6 +8,25 @@ and commands may change between minor versions. How releases are made:
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.176.0] - 2026-11-16
12
+
13
+ ### Added
14
+
15
+ - chi web: `web.stage_collapsed` (off by default) starts every session's stage folded to its status row, a
16
+ participant's page too; a session you fold or unfold by hand keeps its own.
17
+
18
+ ### Changed
19
+
20
+ - chi web: the stage's fold, the working-set rail's, the composer's fold and its dragged height are kept per
21
+ session (per browser): what you do in one session no longer shows in another, and coming back finds it as you
22
+ left it. A running turn's opened cloud, the steps opened in it and the working-set reader come back too when you
23
+ switch away and back during the same turn (this tab only). The old page-wide choices are not carried over.
24
+
25
+ ### Fixed
26
+
27
+ - chi web: a participant's failed turn puts their text and images back in their composer (it gave them nothing
28
+ back before); only their own turn does, never the owner's or another participant's.
29
+
11
30
  ## [0.175.0] - 2026-11-16
12
31
 
13
32
  ### Added
@@ -6433,7 +6452,8 @@ and long-lived sessions.
6433
6452
  - A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
6434
6453
  hotkey panel that send selected text or the clipboard to your sessions.
6435
6454
 
6436
- [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.175.0...HEAD
6455
+ [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.176.0...HEAD
6456
+ [0.176.0]: https://github.com/dm1try/samagotchi/compare/v0.175.0...v0.176.0
6437
6457
  [0.175.0]: https://github.com/dm1try/samagotchi/compare/v0.174.0...v0.175.0
6438
6458
  [0.174.0]: https://github.com/dm1try/samagotchi/compare/v0.173.0...v0.174.0
6439
6459
  [0.173.0]: https://github.com/dm1try/samagotchi/compare/v0.172.1...v0.173.0
data/bin/chi CHANGED
@@ -267,6 +267,7 @@ if options[:web]
267
267
  exit Samagotchi::Web::Server.launch(port: port, scope: options[:scope] || "project", open_browser: options[:web_open],
268
268
  markdown: markdown, new_token: options[:new_token], tunnel: options[:tunnel],
269
269
  working_set: Samagotchi::Config.get("web.working_set"),
270
+ stage_collapsed: Samagotchi::Config.get("web.stage_collapsed"),
270
271
  reload_check: Samagotchi::Config.get("web.reload_check"),
271
272
  annotate_presets: Samagotchi::Config.get("web.annotate_presets"),
272
273
  editor: Samagotchi::Config.get("web.editor"),
data/docs/architecture.md CHANGED
@@ -651,7 +651,7 @@ A map of the parts the overview above doesn't name (paths under `lib/samagotchi/
651
651
 
652
652
  | Component | Main file(s) | What it is |
653
653
  |---|---|---|
654
- | Worker | `worker.rb` (`worker_boot.rb`, `worker_idle_exit.rb`, `worker_inbound.rb`, `worker_signals.rb`, `worker_wakes.rb`, `worker_task_wakes.rb`, `task_watch.rb`, `worker_participant_gate.rb`, `worker_exit_claim.rb`) | A session's background process: builds the `Engine` and `Bridge`, runs queued turns and the wake turns nobody typed (delegate reports, a background task that finished unseen: [Finish wake](internals/background-tasks.md#finish-wake), attached context), exits when idle. A spawned one traps TERM, HUP and INT (`WorkerSignals`, installed by `WorkerBoot.run_session_loop` when `SAMAGOTCHI_WORKER_PROCESS=1`): the running turn stops as a Stop with reason `signal`, is saved, and the worker leaves (`:signal`, exit 0; a new worker only for input already queued). A running turn is checkpointed at its iteration boundaries (`TurnCheckpoint`, the `interrupted_turn` mark), and the next worker settles a turn its predecessor died in (`TurnCheckpoint.settle`). The session is saved from the turn's thread, Bridge threads and a signal's thread; `Session#save` takes a per-session lock around its snapshot and write, so an older snapshot never lands over a newer one. `WorkerParticipantGate` is the one seat for "may this participant act" (a queued turn as it starts, the drain, the mid-turn stop, the Continue: [internals/participants.md](internals/participants.md)); `WorkerExitClaim` is the exit claim (`POST /exit`): one lock for the kind being taken and the exit taken. Threads: the gate is loop-thread only (a turn runs on the loop; no lock), the claim is safe from any thread (its own mutex, taken after the event lock). |
654
+ | Worker | `worker.rb` (`worker_boot.rb`, `worker_idle_exit.rb`, `worker_inbound.rb`, `worker_signals.rb`, `worker_wakes.rb`, `worker_task_wakes.rb`, `task_watch.rb`, `worker_participant_gate.rb`, `worker_exit_claim.rb`) | A session's background process: builds the `Engine` and `Bridge`, runs queued turns and the wake turns nobody typed (delegate reports, a background task that finished unseen: [Finish wake](internals/background-tasks.md#finish-wake), attached context), exits when idle. A spawned one traps TERM, HUP and INT (`WorkerSignals`, installed by `WorkerBoot.run_session_loop` when `SAMAGOTCHI_WORKER_PROCESS=1`): the running turn stops as a Stop with reason `signal`, is saved, and the worker leaves (`:signal`, exit 0; a new worker only for input already queued). A running turn is checkpointed at its iteration boundaries (`TurnCheckpoint`, the `interrupted_turn` mark), and the next worker settles a turn its predecessor died in (`TurnCheckpoint.settle`). The session is saved from the turn's thread, Bridge threads and a signal's thread; `Session#save` takes a per-session lock around its snapshot and write, so an older snapshot never lands over a newer one. `WorkerParticipantGate` is the one seat for "may this participant act" (a queued turn as it starts, the drain, the mid-turn stop, the Continue: [internals/participants.md](internals/participants.md)); `WorkerExitClaim` is the exit claim (`POST /exit`): one lock for the kind being taken and the exit taken. Threads: the gate is loop-thread only (a turn runs on the loop; no lock), the claim is safe from any thread (its own mutex, taken after the event lock). The concerns are `include`d parts in `lib/samagotchi/worker/` (`Worker::LeavePart`: exit and leave; `Worker::WakeTurnsPart`: the turns nobody typed; `Worker::StartupPart`: the start-up settle; `Worker::SignalGracePart`: a signal's grace; `Worker::ScratchPart`: a scratch worker whose terminal left; `Worker::ChildSidePart`: a delegate child's rings, Verify fresh verdicts; `Worker::CommandQueuePart`: session commands between turns). `worker.rb` keeps the loop, the wiring, the prompt turns and the drain. They share Worker's ivars, and each header says what it writes and reads. |
655
655
  | Config | `config.rb`, `config/restart_watch.rb` | Every setting as an `Entry`: env, config.yml and CLI layers ([configuration.md](configuration.md)); the notice a worker or chi web gets when config.yml changes a setting it reads only at its start. With `log.rb` it is the bottom layer: nothing it references reaches back to it, so `hosts:` and `models:` entries parse next to their types (`HostConfig.all`, `ModelSettings.all`). |
656
656
  | Paths | `paths.rb` (`Paths`) | The XDG base dirs chi's files live under, read from the env on every call: `Paths.state_home` (`$XDG_STATE_HOME`, else `~/.local/state`) and `Paths.config_home` (`$XDG_CONFIG_HOME`, else `~/.config`), both defaults under `Dir.home`; a blank variable counts as unset, a relative one is made absolute from the current directory. `Paths.tilde` shows a path with `~` for the home folder. `SessionManager` hands a spawned worker the spawner's `XDG_STATE_HOME` / `XDG_CONFIG_HOME`, when set, made absolute, so a relative one isn't read from the session's folder. |
657
657
  | MemoryBundle | `memory_bundle.rb`, `memory_bundle/{installer,builder,installed_bundle,plugin_ref,bundle_hook}.rb` (`Installer`, `Builder`, `InstalledBundle`, `PluginRef`, `BundleHook`) | Installing, building and reading bundles of memories, rules, plugins and scripts (`BundleHook`: an older record's retired class-file hook). |
data/docs/cli.md CHANGED
@@ -17,6 +17,7 @@
17
17
  - `chi web push ls [--format json]`, `chi web push rm ID`, `chi web push test [ID]` — the phones chi web pushes to (see [Phone notifications](configuration.md#phone-notifications-web-push)): list them (short id, label, origin, added, last delivery, done turns, last error; `stale` for one made on another public URL than chi web's now: never sent to), remove one, or send a test notification to ID or to every device not stale. chi web need not run; nothing printed holds a device's push address or keys. A usage error exits 2; a store others can read, a corrupt one, an unknown device or a failed test push exit 1. This machine only: `chi --remote X web push` exits 2
18
18
  - `chi web --web-markdown` / `--no-web-markdown` — opt in to, or opt out of, sanitized Markdown rendering for completed assistant messages, the stage's asking text and a resolved question card's reply (`web.markdown`, off by default; `--no-web-markdown` turns a config's `web.markdown: true` off for this run)
19
19
  - `chi web --no-web-working-set` — turns the stage view's working set off (on by default; `--web-working-set` turns a config's `web.working_set: false` back on): what each turn brought into the model's context, in the stage and under each finished turn; `?working_set=1|0` on the page URL overrides it (see [The working set](#the-working-set))
20
+ - `chi web --web-stage-collapsed` / `--no-web-stage-collapsed` — every session's stage starts folded to its status row, or not (`web.stage_collapsed`, off by default); a session folded or unfolded by hand keeps its own fold in that browser
20
21
  - `chi sessions list|stop|restart|archive|unarchive|delete|prune|clean|stats` — manage persisted sessions; `list` shows this git project's, `list --scope=all` every one, a delegated session with `↳ <parent>`, `list --archived` the archived ones too (see [Sessions](sessions.md)); one line per session (`<id> <state> <ctx> <updated_at> <text> [flags] ↳ … ↪ …`) and one footer (`N session(s) (sort=… order=…)`, or the project note) for the plain list, the `--live`/`--cwd` text and `--remote`. `stats ID` prints a session's cost, tokens and progress, and its own settings (`--set`; a `settings:` line), from a live worker's `GET stats`, else its saved `analytics.json` (`--format json` one object, with `settings`), without running a model turn. A usage error (an unknown subcommand or flag, a flag missing its value, `stop`, `restart` or `delete` with no ids, a bad `list --format`, `--scope`, `--sort` or `--order`, a `--days`, `--keep` or `--limit` that isn't a whole number) exits 2; an unknown or refused session exits 1
21
22
  - `chi note [--source NAME] [-m TEXT] (ID|PREFIX)... | --all` — add a context note (TEXT or stdin) to sessions: background the model sees on its next turn; it starts no turn (see [Sessions: Context notes](sessions.md#context-notes))
22
23
  - `chi broadcast [-m TEXT] [--all] [--dry-run]`, `chi broadcast log [--last N] [--format json]`, `chi broadcast deliver BROADCAST_ID (ID|PREFIX)...` — share one piece of information (TEXT or stdin) with every session it may concern, as a context note from `broadcast` (see [Broadcast](broadcast.md))
@@ -1627,6 +1628,8 @@ CHI_REMOTE=studio chi context push claude-outbox ab12 < answer.json
1627
1628
  project's sessions there (`--scope=project --cwd DIR` one project's), each
1628
1629
  on the same line a list here prints. `context` takes the session ids (no default session),
1629
1630
  and a URL resolves through that machine's bundles.
1631
+ - A participant token can send `--image` too: each file uploads to that grant's
1632
+ participant image route before the turn is sent.
1630
1633
  - That machine's config.yml decides what it checks for `send` and `answer`:
1631
1634
  a parent agent's `/continue yes` and options (`guardrails.parent_answers`),
1632
1635
  a loosening `/parent-answers`, images to a model that can't see them. Each
@@ -2383,6 +2383,7 @@ column says so, a `--kebab-name` flag. The maps (`hosts:`, `models:`,
2383
2383
  | `web.host` | `127.0.0.1` | yes | `127.0.0.1`, `::1` or `localhost`; `lan` (this machine's private IPv4 address) or one of its IPv4 addresses also opens `chi web` to the network, with an access token, asked of this machine's 127.0.0.1 too (its `Local:` link carries a one-time code; `chi web --new-token` replaces the token; it is chi web's one access token, also used by `--tunnel` and `web.public_url`/a proxy). Anything else binds `127.0.0.1` with a warning. See [CLI: chi web on your phone](cli.md#chi-web-on-your-phone). |
2384
2384
  | `web.markdown` | `false` | yes | Render answers as Markdown in `chi web`. |
2385
2385
  | `web.working_set` | `true` | yes | The stage view's working set: the files, memories and URLs a turn brought into the model's context, in a rail in the stage, a footprint as each finished turn's block summary and a `set N` chip in place of the mem chip; `false` brings the mem chip back. `?working_set=1` or `?working_set=0` on the page URL overrides it for that page load. See [CLI: the working set](cli.md#the-working-set). |
2386
+ | `web.stage_collapsed` | `false` | yes | Every session's stage in `chi web` starts folded to its status row (the running turn's prompt, steps and cloud behind ▴), a participant's page too. A session you fold or unfold by hand keeps its own fold in that browser (`chi_stage_collapsed:<session>`), whatever this says; one never touched follows it. Read when `chi web` starts: restart it after a change. |
2386
2387
  | `web.reload_check` | `false` | yes | Opt-in: once each finished turn has moved into the history, the page reads the session again (one full read per turn end), draws that turn as a reload would and compares the two, strictly: a known divergence counts as a mismatch too. `chi web` logs one `reload_checked` line per check and a `reload_mismatch` line naming the kinds that differed, `excused` (the known divergences, `history_shape.js` `ACCEPTED`, that would explain them) and `explained` (all of them had one), with `turn_id`, `drawn` (the turn came back from its drawing, so a mismatch with `drawn: true` is a drawing bug), `undrawn` (how many of the reload's rows came without their turn's drawing, the page's plain fallback: 0 unless chi web missed a turn) and the worker's version: counts only, never content. The count is `grep -c reload_mismatch` over `grep -c reload_checked` in chi web's log, split by `excused`. The turn's own cards and questions are compared as data, apart from the history: what the page's stream said (`card_registry.js`) against what the read lists (CardStore), each card or question of this turn (`of_turn`) by its id, its kind, its status (answered, cancelled, still asking) and its summary line (a card's title); a difference counts as `card` or `question`. Bodies, buttons, folds, the tag a card is drawn in and where it sits are ignored (the history's compare leaves cards and questions out on both sides; their place is the specs'). A read that lists CardStore's cap of cards and questions may have lost an older one: a card the page has and such a read doesn't is no difference. A question the read gives no turn and no opening stamp for (an older worker) leaves the questions out. A page whose `app.js` is older than its `reload_check.js` (a mixed cache) compares no cards: its `reload_checked` line says `cards_compared: false`. Between-turn cards and notices stay with the e2e reload checks. Every open owner tab runs the check; `chi web` logs a turn's first report only, and starts over when it restarts. |
2387
2388
  | `web.annotate_presets` | `Agreed\|Could you please elaborate?` | yes | Quick replies next to Annotate in `chi web`, `\|`-separated (a YAML list works too); `""` in the file or on the CLI leaves only Annotate (an empty env value means the default). See [CLI](cli.md#web-annotate-presets). |
2388
2389
  | `web.editor` | `vscode` | yes | What a file ref in `chi web` (a file tool row's title, a diff line) opens, for a viewer on this machine: a preset (`vscode`, `vscode-insiders`, `cursor`, `zed`) or a URL template with `{path}` and an optional `{line}`; `none` turns refs off. See [Opening files from chi web](#opening-files-from-chi-web). |
@@ -455,14 +455,14 @@ The Bridge exposes:
455
455
  `:command_ran` names, `400` when the line isn't one. `client_id` is required: without one (or a blank one) `400
456
456
  missing_client_id` (`Bridge::UNNAMED_COMMAND`); from a sender that may not send commands (`CommandIntake.allowed?`:
457
457
  only the owner's senders, `web:`, `tui:`, `cli:send`, and chi answer's `cli:answer`) `403 command_not_permitted`, its
458
- detail `CommandIntake::COMMAND_REFUSED` (`CommandIntake::REFUSED` for a `!` line), nothing queued. A `:command_ran`'s `output` is the command's, up to `Worker::COMMAND_OUTPUT_LIMIT` (64 KiB of chars; past it
458
+ detail `CommandIntake::COMMAND_REFUSED` (`CommandIntake::REFUSED` for a `!` line), nothing queued. A `:command_ran`'s `output` is the command's, up to `Worker::CommandQueuePart::COMMAND_OUTPUT_LIMIT` (64 KiB of chars; past it
459
459
  the text ends with a `[cut: N of M chars: …]` line, which the UIs print as they print the rest). It carries `thinking`, `reasoning_history` and `llm_context`
460
460
  (the summaries the next turn runs under) when the command changed them or the model, and
461
461
  `confirm: {line, text}` when a `/thinking` or `/reasoning-history` change from a `web:` or `tui:`
462
462
  client asks first (`CacheConfirm`; nothing changed, `line` applies it).
463
463
  - `POST /session/:id/exit` — ask the worker to exit now (`{client_id:, delete?, restart?, deadline?}`; `delete`:
464
464
  `/exit --delete`, no recap written; `restart: true`: hand the session to a new worker on the newest chi
465
- installed, `200 {status: "restarting"}`; an empty session's `exiting` carries `discard: true`). The worker checks with
465
+ installed, `200 {status: "restarting"}`; an empty session's `exiting` carries `discard: true`; a `stop: "all"` exit's `exiting` carries `stopped`, read with the event log held right after the accept, so a later exit's list is never its own). The worker checks with
466
466
  the event log held (`WorkerIdleExit#hold_for_request`): `200 {status: "exiting"}` and it leaves
467
467
  like an idle exit, or `409 {status: "held", reason:}` with `turn_running`, `input_queued`,
468
468
  `continue_offered`, `client_connected` (a stream not named by the asker), `reminders`,
@@ -131,10 +131,10 @@ A Stop (Engine#cancel_current_turn!, the Bridge's POST cancel) or a hook's stop_
131
131
  A worker's TERM, HUP or INT (WorkerSignals, a spawned worker only):
132
132
  → a Stop with reason :signal (Worker#signalled, off the trap, retried until the loop leaves); saved as after any
133
133
  turn; Worker#run returns :signal (:stopped with the stop marker) and takes no new work
134
- → not ended within Worker::SIGNAL_GRACE (a turn already in its after_turn hooks gets SIGNAL_HARD_EXIT more,
134
+ → not ended within Worker::SignalGracePart::SIGNAL_GRACE (a turn already in its after_turn hooks gets SIGNAL_HARD_EXIT more,
135
135
  uncanceled): the session saved as it is, SignalException raised in the loop's thread, only while the loop runs
136
136
  (never into start, serve or the teardown, which runs whole)
137
- → exit! Worker::SIGNAL_HARD_EXIT (10 s) after that at the latest; a signal after the loop left brings only that
137
+ → exit! Worker::SignalGracePart::SIGNAL_HARD_EXIT (10 s) after that at the latest; a signal after the loop left brings only that
138
138
  hard exit
139
139
  → WorkerBoot.run_session_loop restores the default handlers; exit 0, no discard; input queued behind the stopped turn
140
140
  wakes a new worker
@@ -452,8 +452,9 @@ is still downscaled by `ImageStore.fit`, so the tool does read their bytes: thei
452
452
  magick reading the sniffed format's coder under `-limit memory 256MiB -limit disk 1GiB -limit area 64MP`. An
453
453
  upload that raises is audited (`internal_error`) before chi web's 500. The quota is checked under `@participant_images_mutex`, the
454
454
  image ingested, then checked again and recorded under it (a race past it is refused there; the stored file may stay
455
- in `images/`, unreachable to them). Each answer is an `image` audit line. The reply is the ref without `source`,
456
- `mime` or `bytes`.
455
+ in `images/`, unreachable to them). The first upload past the attempts cap is audited; later uploads are not, even
456
+ when another refusal takes precedence, so uploads add at most `MAX_IMAGE_ATTEMPTS + 1` audit lines per grant. The
457
+ reply is the ref without `source`, `mime` or `bytes`.
457
458
 
458
459
  **Read back** (`GET …/images/<name>`, `SessionControl#handle_image`): a participant gets the file only when
459
460
  `ParticipantUploads.owned?` says they uploaded it (the record proves they had the bytes), with `Cache-Control:
@@ -462,8 +463,8 @@ headers alike. A revoked or expired grant is refused by the gate (401) as on eve
462
463
 
463
464
  **Their turn** takes only refs they uploaded ([Turns](#turns)); **what they see** is their own images as thumbnails
464
465
  and anyone else's as "N images" ([What a participant sees](#what-a-participant-sees)). A corrupt or unreadable
465
- record fails closed (every grant at quota, owning nothing, `Log.warn`); the owner can delete the file. Not covered:
466
- a participant's `chi --remote … --image`; a failed turn of theirs gives the text back without its chips.
466
+ record fails closed (every grant at quota, owning nothing, `Log.warn`); the owner can delete the file. A failed turn
467
+ of theirs gives the text back with its chips (`prompt_restored`, below).
467
468
 
468
469
  ## What a participant sees
469
470
 
@@ -490,6 +491,10 @@ fields: a field added to an event later reaches nobody until it is named there.
490
491
  `enqueued_id`, `client_id`, `prompt`, `delivery`, `author`, their image refs; `turn_dequeued`: its `enqueued_id`, never
491
492
  the client that took it back, the filter knowing their ids from the `turn_enqueued` it sent them and from
492
493
  `ParticipantAccess#own_turn?`; `input_merged`: the count and origins of their own lines only), anyone else's bare;
494
+ `prompt_restored` (a failed turn's prompt handed back, **their own turn only**: the origin's server-stamped author
495
+ is theirs; another person's, the owner's and an author-less one's give nothing; carries `prompt`, `images` as their
496
+ own refs (`.image_refs`), `revises: {turn_id}` and `origin: {client_id, enqueued_id, author}`, never `source`, the
497
+ error, a Verify claim's quote or any other field; the page refills its composer as the owner's, `restore.js`);
493
498
  `question_requested` and `continue_offered` with one derived `kind` (`.waiting_kind`: `approval` for a guardrail's
494
499
  approval or a relayed one, `continue` for the step-limit question and every offer, `question` else); the main
495
500
  page's numbers (`context_status`: usage's `estimated_pct` and token counts, `bucket`, a switch's
@@ -567,7 +572,8 @@ verdicts' (`fresh_running`, `session.verify_unavailable`).
567
572
  the editor.
568
573
 
569
574
  The main page's `<body>` for a participant (`App#participant_index_data`): `version`, `session`,
570
- `session-title`, the Annotate presets, the viewer and `working-set` (the owner's `web.working_set`); nothing of the
575
+ `session-title`, the Annotate presets, the viewer, `working-set` (the owner's `web.working_set`) and
576
+ `stage-collapsed` (the owner's `web.stage_collapsed`: a layout default, not a secret); nothing of the
571
577
  owner's machine (`home`, the folders, `project-*`, `back-*`).
572
578
  - **Their usage** (`viewer.usage`, `ParticipantReview#review_usage`, built from named fields by the exposure policy
573
579
  beside `ParticipantView`'s): the fields their grant's exposure shows
@@ -29,7 +29,7 @@ page. A factory dep a new version stops passing is the same hazard the other way
29
29
  out of `send_turn.js`, `session_actions.js` and `lists_view.js`); a page loaded before keeps all its old modules
30
30
  until a reload, so the risk is a mixed cache, not an open tab. `answer_fold.js`, `details_motion.js`,
31
31
  `turn_range.js`, `history_reveal.js`, `latest.js`, `session_payload.js`, `method_api.js`, `session_store.js`,
32
- `session_fields.js`, `feature_gates.js`, `revise_stack.js`, `revise_switch.js`, `shell_command.js`, `stale_params.js`, `popover_modal.js`, `more_sheet.js`, `delete_sheet.js` (Deleting a chained session, below), `hash_intent.js` (what the hash asks for: session, all, start or keep), `worker_features.js`, `version_notices.js`, `owner_claim.js`, `owner_verify.js`, `composer_mode.js`, `strip_hidden.js`, `block_open.js`, `text_roots.js`, `block_source.js`, `block_frame.js`, `block_host.js`, `block_watch.js`, `card_stamps.js`, `recap_stamp.js` (a saved recap's place by its `opening_id` stamp, else its count), `inline_widgets.js`, `widget_walk.js`, `widget_picks.js`, `history_shape.js` (the history's shape, live against a reload: the e2e reload checks and the opt-in reload check share its normalizer and its `ACCEPTED` allowlist), `turn_pieces.js` (a finished turn's one order and its answer rule: the live hand-off's `handOffOrder` and `turnEnded`, and a reload's `turnHistoryNodes`), `reload_check.js` (the opt-in `web.reload_check`: after the stage's hand-off, the turn against a reload of it, the counts posted; the history without its cards and questions, and those as data: the page's `card_registry.js` against one seeded from the read, this turn's entries, a capped read's missing keys skipped), `turn_drawing.js` (a finished turn's drawing, `turn_drawings` in the show: its fold into steps and its end kind; `turn_block.js` draws it), `stage_stall.js` (the stage's quiet signal), `stage_quiet_clock.js`, `stage_dom.js`, `stage_answer.js`, `stage_pager.js`, `stage_cloud.js`, `stage_handoff.js`, `stage_place.js`, `stage_probe.js` (the stage's features: below, The stage's modules), `card_kinds.js` (what a card waits as, from its data: the kind, approval and folded-row text the stage's registry takes; the node's read is its cross-check), `card_registry.js` (the open session's cards as data, an observer of the stream's card events and a read's seed: Where state lives), `history_end.js` (the stage's one move of pieces to the history's end), `stage_opened.js` (a running turn opened in the history while a card waits: the lead-in bubble, the moves, the end fold), `stage_asking.js` (the stage's docked card and its fold: the docking and lead-in rules, the opening, a waiting card's own toggle, the folded row's text per kind, the fold's choice, reveal and the docked card's fold; `stage_view.js` wires it), `stage_waiting.js` (the stage's waiting cards as data, keyed by `data-qid` / `data-card-id`: kind, docked, approval, the stage's order, the shown card and its pager, the docked card's fold, kept for this tab in `chi_asking_fold:<session>`; `front`, `count`, `shown`, `blocking`), `stage_cards.js` (the cards that wait in the stage: `PENDING`, `ASKS`, `waitsInStage`, read by `stage_model.js placeKind`), `resync_reach.js` (a re-read that can't reach chi web keeps the drawn history; the status chip says retrying / offline, outside a turn), `session_sync.js` (the open session's sync: `select`, `resync` and its retries, the stream's life; the stream handle and the re-read bookkeeping are its own), `session_view.js` (the open session's view: `renderSessionView` draws a read, `forgetSession` resets the page for another session, `readTurnEnd`, `endTurnView`; app.js makes both right after the cards, each reaching the other and the later views through getters), `participant_main.js`, `participant_bar.js`, `viewer_self.js`, `participant_history.js` (a participant's ↑/↓ list), `stage_owner_wait.js`, `participant_revise.js` (a participant's page: The participant's page, below), `ws_timeline.js`, `ws_cards.js`, `ws_peek.js`, `ws_reader.js`, `ws_way_in.js` (what chi has of a working-set item: below, The working set's reader), `no_contact_fill.js` (a text field that isn't a contact form: autocomplete off and a name with no contact word, against iOS Safari's AutoFill Contact bar; a template's fields carry the same attributes, and its spec checks the page's markup for them) and the `objectives_*.js` modules are new modules for that reason. The last four `block_*` draw fenced blocks (`block_watch.js` finds and watches them, `block_host.js` is its frame drawer for a bundle's renderers): [block-renderers.md](block-renderers.md). `inline_widgets.js` is its core drawer for `chi-ui` blocks, drawing `widget_walk.js`'s and `widget_picks.js`'s widgets in a shadow root styled by `widgets.css`: [inline-widgets.md](inline-widgets.md).
32
+ `session_fields.js`, `feature_gates.js`, `revise_stack.js`, `revise_switch.js`, `shell_command.js`, `stale_params.js`, `popover_modal.js`, `more_sheet.js`, `delete_sheet.js` (Deleting a chained session, below), `hash_intent.js` (what the hash asks for: session, all, start or keep), `worker_features.js`, `version_notices.js`, `owner_claim.js`, `owner_verify.js`, `composer_mode.js`, `strip_hidden.js`, `block_open.js`, `text_roots.js`, `block_source.js`, `block_frame.js`, `block_host.js`, `block_watch.js`, `card_stamps.js`, `recap_stamp.js` (a saved recap's place by its `opening_id` stamp, else its count), `inline_widgets.js`, `widget_walk.js`, `widget_picks.js`, `history_shape.js` (the history's shape, live against a reload: the e2e reload checks and the opt-in reload check share its normalizer and its `ACCEPTED` allowlist), `turn_pieces.js` (a finished turn's one order and its answer rule: the live hand-off's `handOffOrder` and `turnEnded`, and a reload's `turnHistoryNodes`), `reload_check.js` (the opt-in `web.reload_check`: after the stage's hand-off, the turn against a reload of it, the counts posted; the history without its cards and questions, and those as data: the page's `card_registry.js` against one seeded from the read, this turn's entries, a capped read's missing keys skipped), `turn_drawing.js` (a finished turn's drawing, `turn_drawings` in the show: its fold into steps and its end kind; `turn_block.js` draws it), `stage_stall.js` (the stage's quiet signal), `stage_quiet_clock.js`, `stage_dom.js`, `stage_answer.js`, `stage_pager.js`, `stage_cloud.js`, `stage_handoff.js`, `stage_place.js`, `stage_probe.js` (the stage's features: below, The stage's modules), `card_kinds.js` (what a card waits as, from its data: the kind, approval and folded-row text the stage's registry takes; the node's read is its cross-check), `card_registry.js` (the open session's cards as data, an observer of the stream's card events and a read's seed: Where state lives), `history_end.js` (the stage's one move of pieces to the history's end), `stage_opened.js` (a running turn opened in the history while a card waits: the lead-in bubble, the moves, the end fold), `stage_asking.js` (the stage's docked card and its fold: the docking and lead-in rules, the opening, a waiting card's own toggle, the folded row's text per kind, the fold's choice, reveal and the docked card's fold; `stage_view.js` wires it), `stage_waiting.js` (the stage's waiting cards as data, keyed by `data-qid` / `data-card-id`: kind, docked, approval, the stage's order, the shown card and its pager, the docked card's fold, kept for this tab in `chi_asking_fold:<session>`; `front`, `count`, `shown`, `blocking`), `stage_cards.js` (the cards that wait in the stage: `PENDING`, `ASKS`, `waitsInStage`, read by `stage_model.js placeKind`), `resync_reach.js` (a re-read that can't reach chi web keeps the drawn history; the status chip says retrying / offline, outside a turn), `session_sync.js` (the open session's sync: `select`, `resync` and its retries, the stream's life; the stream handle and the re-read bookkeeping are its own), `session_view.js` (the open session's view: `renderSessionView` draws a read, `forgetSession` resets the page for another session, `readTurnEnd`, `endTurnView`; app.js makes both right after the cards, each reaching the other and the later views through getters), `participant_main.js`, `participant_bar.js`, `viewer_self.js`, `participant_history.js` (a participant's ↑/↓ list), `stage_owner_wait.js`, `participant_revise.js` (a participant's page: The participant's page, below), `ws_timeline.js`, `ws_cards.js`, `ws_peek.js`, `ws_reader.js`, `ws_way_in.js` (what chi has of a working-set item: below, The working set's reader), `session_prefs.js` (a session's own view settings, `<key>:<session>`: Storage keys, below), `stage_view_memory.js` (what was opened of a running turn, per session, in memory: Where state lives), `no_contact_fill.js` (a text field that isn't a contact form: autocomplete off and a name with no contact word, against iOS Safari's AutoFill Contact bar; a template's fields carry the same attributes, and its spec checks the page's markup for them) and the `objectives_*.js` modules are new modules for that reason. The last four `block_*` draw fenced blocks (`block_watch.js` finds and watches them, `block_host.js` is its frame drawer for a bundle's renderers): [block-renderers.md](block-renderers.md). `inline_widgets.js` is its core drawer for `chi-ui` blocks, drawing `widget_walk.js`'s and `widget_picks.js`'s widgets in a shadow root styled by `widgets.css`: [inline-widgets.md](inline-widgets.md).
33
33
 
34
34
  ## One page, every viewer
35
35
 
@@ -55,7 +55,8 @@ their viewer (The viewer, below), their show and stream are filtered (`Web::Part
55
55
  | **The history DOM** | the conversation as drawn (a running turn's reason bubble, `.bubble.said`, is live only: see A turn opened in the history): which turn a bubble belongs to (`data-turn-id`, `data-answer-turn`), what opens a turn (`TURN_PROMPT`, `bubbles.js`: a prompt or a wake's note, the same turns `Steer.turn_opening?` counts for a card's `turns_since`), an opening's id for a card's and the saved recap's stamp (`data-turn-id` on a prompt, `data-opening-id` on a wake's note or `/continue no`'s reason line; `card_stamps.js` places a snapshot's card after the stamped opening, `recap_stamp.js` the saved recap after the last turn it covers, each by its count (`turns_since`) only without one), kept command bubbles, which texts were shown, unnamed badges, folded answers and long prompts (`.folded`), Revise stamps (`data-revises` on a prompt; a Verify turn's `data-verify`) and the stacks' folded versions (`.stack-hidden`, `.stack-stub.open`); the switcher's version on view is `revise_stack.js`'s own (a copy `.stack-view` before the top answer, the top `.stack-swapped`; never stored) | `bubbles.js`, `cards_place.js`, `question_cards.js`, `turn_block.js`/`stage_view.js`, `answer_fold.js`, `revise_stack.js`, `stream_handlers.js` (a live `turn_completed`'s `revises` and `verify` onto its prompt) | read back as state: `turn_range.js turnElements` (one walker for a turn's elements), `keptCommandBubbles`, `seedSeenFromDom`, `nameUnnamedBadges`/`nameVerdictCards`, `answer_fold.js` and `revise_stack.js` (their observers decorate every path that fills `#history`; the stacks are `stacks()` of the stamps, read again on each change, never a store field), `history_reveal.js revealInHistory` (the one way a jump unfolds what hides its target) |
56
56
  | **A drawn turn** (`turn_drawings` of the full read) | every finished turn, as live drew it: `turnGroups` groups by the stamps only, a turn's stamped items (`drawn: <turn_id>`) one group, and `turnHistoryNodes` draws it by feeding its drawing's events to a live turn block offscreen (`turn_block.js drawnTurnNodes`: the block's own handlers, as the stage's), the stage's extras (a reminder, merged lines, a card that asks or warns) and end as live, then the answer, the merged lines and the steps' texts from their saved items (markdown, refs). Each of its top-level elements carries `data-drawn`: `cards_place.js` leaves that turn's in-turn CardStore entries (`of_turn`) to it, and a kept reminder bubble of that turn (`data-turn-id`) stays out after a resync. chi web sends a drawing for every finished turn (one made from its messages where live wrote none): `drawnGroup` pairs the record the end names (`end.record_id`, by place for a turn saved before turn ids), else by the turn's id, and the answer's `data-answer-turn` is the end's own `turn_id` only (a made-up id, `m…` or `…~N`, keys none: no Revise). Nothing is rebuilt from messages: an item that comes unstamped is a `plain` group drawn as a plain row of its text (its prompt or answer bubble, no steps), the running turn's as expected (`runningTurnId`, the show's `current_turn`: it has no line yet), any other a miss, marked `data-undrawn`, logged once per render (`console.warn`) and counted by the reload check (`undrawn`), never a throw; a drawing with no parts (a minimal line) draws its prompt, answer and end | chi web (the show) | `renderHistory`, the reload check's render |
57
57
  | **The cards as data** (`card_registry.js`; app.js `cardRegistry`) | every question, continue offer and plugin card of the open session, keyed as `stage_waiting.js` keys them (`q:<id>`, `c:<id>`, `continue`): its kind and folded text (`card_kinds.js`), status (pending, answered, cancelled; resolved or dropped for the continue offer; asks or shown for a plugin card), `of_turn`, `opening_id`, step, `relayed_to` | `observeCards` around the stream handlers (outside the participant wrap: the page's handler first, then `apply`), so a read's replay feeds it too; `session_view.js renderSessionView` seeds it from the read right before the replay (`seed`: CardStore's listing, the pending question, the continue offer; it replaces), `forgetSession` resets it. Idempotent: a merge per key, a final status never back to pending, the first `of_turn`/`opening_id`/step kept, so seed then replay is what live holds. A question still pending at its turn's end is cancelled (the page cancels the card, no event comes) | an observer: nothing on the page draws from it; its one reader is the opt-in reload check (`reload_check.js`: this turn's entries against a registry seeded from a fresh read). `stage_cuts_parity.test.js` checks it against the stage's waiting cards at each cut, `card_registry.test.js` the events against each cut's seed and replay |
58
- | **localStorage** (`storage.js` `readStored`/`writeStored`, guarded) | per-browser choices only | the module that owns the choice | read at start (see Storage keys) |
58
+ | **What was opened of a running turn** (`stage_view_memory.js`, in `session_view.js`) | per session, for this tab: the cloud open, the steps opened in it, the working set's reader on an item; a Map of at most 20 sessions, nothing stored or sent (the peek isn't kept: it closes with its popover) | `session_view.js leaveSession`, from `session_sync.js select` and from `forgetSession` itself for the session it drew last (so the start page, `clearSelection`, keeps it too) before its reset (`captureView`); dropped by `endTurnView` | `renderSessionView`, once the read is drawn: put back (`applyView`) only when the read's running turn (`current_turn.turn_id`) is the one saved; taken either way |
59
+ | **localStorage** (`storage.js` `readStored`/`writeStored`, guarded) | per-browser choices only; a session's view settings per session (`session_prefs.js`) | the module that owns the choice | read at start, a session's view settings again when its view is drawn (see Storage keys) |
59
60
  | **SSE** | see Streams | the server | events go into the DOM directly (a participant's through `participant_main.js wrapHandlers` first) |
60
61
 
61
62
  The objectives' strip keeps the list in its own closure (`objectives_strip.js`, seeded by `renderSessionView`, reset by
@@ -470,8 +471,10 @@ edge, with **a shrink for each asking form and after an answer** (`forgetContent
470
471
 
471
472
  **The stage's fold** (`stage_model.js stageCollapsed`, `stage_asking.js`): collapsed to its status row the stage holds no
472
473
  frame (`frameTarget` returns null) and an unfold refits to what shows. Three things decide it, kept apart: the user's
473
- **choice** (the ▾ by hand, in memory, written to `chi_stage_collapsed`; never read back from storage to decide, so
474
- another tab's write doesn't apply live), **revealed** (a ref's "show in turn" opened it for this turn; the choice stays)
474
+ **choice** (the ▾ by hand, in memory, written to the session's `chi_stage_collapsed:<session>`; read again only when
475
+ a session's view is drawn, `stage_asking.js reloadChoice` from `session_view.js applyPrefs`, never to decide
476
+ meanwhile, so another tab's write doesn't apply live; a session never folded by hand takes the page's default,
477
+ `web.stage_collapsed`), **revealed** (a ref's "show in turn" opened it for this turn; the choice stays)
475
478
  and **the docked card's fold** (the waiting card the user folded, by its key, held in `chi_asking_fold:<session>`
476
479
  in sessionStorage: this tab's own, so a reload or a resync mid-turn draws it folded as it was — `stage_waiting.js`
477
480
  writes it on the fold and reads it back in `trackFold` once the replay has drawn the card; it goes when that card is
@@ -480,7 +483,7 @@ fold that names that card, so a replay or a history question answering another c
480
483
  when the turn hands off (`clearFold`), and when the page opens another session (`session_sync.js select`, only when a
481
484
  session was open); `reset` clears the memory only, so the replay can take the fold back). In the
482
485
  asking form only that fold counts: the ▾ and a tap on the folded row set or clear it and write nothing to
483
- `chi_stage_collapsed` (another blocking card that comes to wait meanwhile
486
+ `chi_stage_collapsed:<session>` (another blocking card that comes to wait meanwhile
484
487
  drops it, so the stage opens on the front card), so a card always arrives open (in the card's task, before
485
488
  `question_cards.js focusWhenIdle` focuses it) and a new one never matches an old fold; the same card drawn again with its
486
489
  id keeps it. The fold reads the registry, which every answer settles in its own task, so a card answered in the same
@@ -685,16 +688,27 @@ reach another device or the server.
685
688
  | Key | Module | What |
686
689
  |---|---|---|
687
690
  | `chi_model`, `chi_model_recent` | `model_pick.js`, `model_picker.js`, `start_page.js` | the start page's model and its recent list |
688
- | `chi_composer_collapsed` | `composer_fold.js` | the composer folded (a card's text field folds it for the time it has the focus on a narrow or touch screen, `composer_grip.js watchCardField`, on top of this and of the visit's state: neither is written) |
689
- | `chi_composer_floor` | `composer_grip.js`, `composer_mount.js` | the composer's dragged height |
691
+ | `chi_composer_collapsed:<session>` | `composer_grip.js` (through `session_prefs.js`) | the session's composer folded (a card's text field folds it for the time it has the focus on a narrow or touch screen, `composer_grip.js watchCardField`, on top of this and of the visit's state: neither is written) |
692
+ | `chi_composer_floor:<session>` | `composer_grip.js`, `composer_mount.js` (through `session_prefs.js`) | the session's composer's dragged height (the start page's: in memory) |
690
693
  | `chi_strip_hidden` (`chi_zen`: the old name, read once) | `strip_hidden.js` | the session strip hidden |
691
- | `chi_stage_collapsed` | `stage_asking.js` | the stage collapsed by hand (not written from the asking form, whose fold is that question's only) |
692
- | `chi_working_set_collapsed` | `working_set_rail.js` | the working set rail collapsed |
694
+ | `chi_stage_collapsed:<session>` | `stage_asking.js` (through `session_prefs.js`) | the session's stage collapsed or opened by hand (not written from the asking form, whose fold is that question's only); none: the page's default, `<body data-stage-collapsed="1">` (`web.stage_collapsed`), else open |
695
+ | `chi_working_set_collapsed:<session>` | `working_set_rail.js` (through `session_prefs.js`) | the session's working set rail collapsed |
693
696
  | `chi_markdown_tip_dismissed` | `markdown_tip.js` | the markdown tip dismissed |
694
697
  | `chi_update_available_shown` | `version_notices.js` | update notices already shown |
695
698
  | `chi_notify`, `chi_push_device` | `notifications.js` (an injected storage) | the bell's state, this device's push id |
696
699
  | `chi_answer_fold:<session>` | `answer_fold.js`, `revise_stack.js` | the answers and long prompts (`<turn id>:prompt`) folded by hand, and the Revise stubs unfolded by hand (`stub:<turn id>`) (swept with the session list) |
697
700
 
701
+ **A session's view settings** (`session_prefs.js`): the four `<key>:<session>` keys above. `read(key, session)` is the
702
+ session's own value, else the page's default (only the stage fold has one: `web.stage_collapsed` on `<body>`), else
703
+ the module's; `write(key, session, value)` writes the session's key only; with no session (the start page) the value
704
+ stays in memory until a reload. Each module reads its value again when a session's view is drawn (`session_view.js
705
+ applyPrefs`: at the end of `forgetSession`, so on a select once the new session is set, and at the start of each
706
+ `renderSessionView`): `stage_view.js applyPrefs` (the stage's fold, `stage_asking.js reloadChoice`, and the rail's),
707
+ `composer_mount.js applyPrefs` (the floor; the fold is read at each call). One sweep for the four
708
+ (`sweepSessionPrefs`, app.js `sweepFoldsOnce`, next to `sweepAnswerFolds`): only on an unscoped list, since these keys
709
+ hold no project root. The old page-wide keys (`chi_stage_collapsed`, `chi_composer_floor`, `chi_composer_collapsed`,
710
+ `chi_working_set_collapsed`, no `:<session>`) are no longer read or written, and left in storage as they were.
711
+
698
712
  sessionStorage (this tab only, `storage.js` `readSession`/`writeSession`/`removeSession`, guarded the same way):
699
713
  `chi_client_id` (`turn_events.js`: this tab's client id, kept over a reload mid-turn),
700
714
  `chi_asking_fold:<session>` (`stage_waiting.js`: the docked card the user folded and how many cards waited at the
data/docs/sessions.md CHANGED
@@ -6,7 +6,7 @@ Sessions are plain files — no DB. Each session is `~/.local/state/samagotchi/s
6
6
 
7
7
  **Verify verdicts:** a web Verify turn stamps its opening user message with `verify: {turn_id, quote}` (the selected source turn and quote; metadata only, never added to the prompt). When that turn completes and the final assistant reply's last non-empty line is a valid `Verdict: confirmed|refuted|unclear — <reason>`, the session file appends `{anchor: {turn_id, quote}, verdict, reason, by, check_turn_id, at}` to its optional `verdicts` array. `by` is the turn's author (nil for the owner), `check_turn_id` names the Verify turn, and `at` is its timestamp. The array is append-only; older files without it have no saved verdicts. An `unclear` verdict can be checked again by **Verify fresh** (a delegate child that gets only the claim; see *Delegating*): its verdict is appended to the parent's `verdicts` with `fresh: true`, `of` (the verdict it checked again) and `child_id`, from the parent's `fresh_verdicts/` dir, which its worker takes between turns. Verdicts are display state: none enters a prompt.
8
8
 
9
- **Revise stacks:** a web Revise turn (POST /turn `revises: {turn_id}`, the answer it rewrites) stamps its opening message (its prompt) with `revises: {turn_id}` at the turn's end, only when the turn completed with an answer (`AnswerTail`): a failed, canceled or empty turn revised nothing (`TurnStages::VerifyAnchors#stamp_opening`). A draft no prompt carries (a stale page, a rolled-back turn) is no target: no stamp. A draft a stamped turn already revised is re-targeted to its stack's top, the newest version, so a stack is a chain `v1 ← v2 ← v3`. Like `verify`, it is metadata only, never added to the prompt (no change to a request's bytes); chi web's history passes it on the opening message (and on a wake turn's note), and `:turn_completed` carries the stamped `revises` (the participant view's too). The history also marks a Verify turn's opening `verify: true`, and so does its live end event (`:turn_completed`'s `verify: true`, with its `turn_id`): the page offers no Revise on its answer. The web page draws the stacks from these stamps (docs/cli.md, Revise). Like a Verify turn's, a Revise message waits for the running turn's end (`SessionInbox.turn_end_data?`; the Bridge takes either as `delivery: queue`, so it never cuts and its ack and `:turn_enqueued` say it queues), is sent only to a worker whose `bridge.json` names the `revise` feature (else 409 `revise_unavailable`), and a failed turn gives it back (`:prompt_restored`'s `revises`). A participant's Revise is theirs only (`ParticipantRevise`, from the authors the server stamped): the answer to their own message (not a Verify turn's), with only their own turn openings after it (an owner's `!` line, which they never see, counts for nothing). chi web checks it at the send against the live worker's snapshot (403 `revise_not_own`, the same for a missing turn; 409 `revise_overtaken`; 409 `revise_unavailable` for a live worker without the `participant_revise` feature), and the worker checks it again at the stamp, up to the Revise turn itself. A Revise someone else's turn overtook after the send silently becomes a plain turn: it runs and answers, but nothing folds, no stack is drawn and neither they nor the owner get a notice; only a `revise_anchor_rejected` log line (reason `overtaken` or `not_own`) records it. It isn't refused at the start because a participant gets no `prompt_restored`, so their text would be lost. A delivery to a live worker without `participant_revise` is refused too (`SessionManager::Delivery`, 409 `revise_unavailable` in their words). The owner's Revise is unchanged, of anyone's answer. Both anchors travel as one `TurnAnchors` inside chi; on the wire and in an input file each keeps its own key (`verify`, `revises`).
9
+ **Revise stacks:** a web Revise turn (POST /turn `revises: {turn_id}`, the answer it rewrites) stamps its opening message (its prompt) with `revises: {turn_id}` at the turn's end, only when the turn completed with an answer (`AnswerTail`): a failed, canceled or empty turn revised nothing (`TurnStages::VerifyAnchors#stamp_opening`). A draft no prompt carries (a stale page, a rolled-back turn) is no target: no stamp. A draft a stamped turn already revised is re-targeted to its stack's top, the newest version, so a stack is a chain `v1 ← v2 ← v3`. Like `verify`, it is metadata only, never added to the prompt (no change to a request's bytes); chi web's history passes it on the opening message (and on a wake turn's note), and `:turn_completed` carries the stamped `revises` (the participant view's too). The history also marks a Verify turn's opening `verify: true`, and so does its live end event (`:turn_completed`'s `verify: true`, with its `turn_id`): the page offers no Revise on its answer. The web page draws the stacks from these stamps (docs/cli.md, Revise). Like a Verify turn's, a Revise message waits for the running turn's end (`SessionInbox.turn_end_data?`; the Bridge takes either as `delivery: queue`, so it never cuts and its ack and `:turn_enqueued` say it queues), is sent only to a worker whose `bridge.json` names the `revise` feature (else 409 `revise_unavailable`), and a failed turn gives it back (`:prompt_restored`'s `revises`). A participant's Revise is theirs only (`ParticipantRevise`, from the authors the server stamped): the answer to their own message (not a Verify turn's), with only their own turn openings after it (an owner's `!` line, which they never see, counts for nothing). chi web checks it at the send against the live worker's snapshot (403 `revise_not_own`, the same for a missing turn; 409 `revise_overtaken`; 409 `revise_unavailable` for a live worker without the `participant_revise` feature), and the worker checks it again at the stamp, up to the Revise turn itself. A Revise someone else's turn overtook after the send silently becomes a plain turn: it runs and answers, but nothing folds, no stack is drawn and neither they nor the owner get a notice; only a `revise_anchor_rejected` log line (reason `overtaken` or `not_own`) records it. It isn't refused at the start (a turn can overtake it after the send). A delivery to a live worker without `participant_revise` is refused too (`SessionManager::Delivery`, 409 `revise_unavailable` in their words). The owner's Revise is unchanged, of anyone's answer. Both anchors travel as one `TurnAnchors` inside chi; on the wire and in an input file each keeps its own key (`verify`, `revises`).
10
10
 
11
11
  **Input files:** a message for a session's worker waits in `input/<timestamp>.json` (`SessionInbox.write_input`: `prompt`, `client_id`, `enqueued_id`, and `images`, `no_interrupt` and `delivery` when they apply; `delivery` is written only for `"queue"`). While a turn runs, the worker merges them at each step boundary in name order, except a queued one, one with images or one whose author isn't the running turn's (a participant's goes only into their own turn, and a participant's turn takes nobody else's: `SessionInbox.turn_end_data?`): those wait for the turn's end and run one turn each, in name order, and a file after them still merges (`Worker#pending_input_drain`). For each file it merges, before deleting it, the drain records which turn took it: `input/merged/<enqueued_id>` = `{"into": the turn's enqueued_id, "at"}` (`SessionInbox.mark_merged`; none for a turn without an id), so a wait for that message waits for that turn (`ReplyWait::Poll#follow_merge`). A turn nobody typed (a reminder, a wake turn: a delegate report's, an attached context change's, a finished task's) gets an `enqueued_id` its worker mints as it runs, `wake-` and 16 hex digits (`Worker#wake_origin`), for its mark, `last_turn`, reply file and settle; the reports it merges keep id-less origins. Such a file, with a prompt, from the user, `chi send` or a delegating parent, also ends a running `task_wait` or `delegate_result` and hands a running `execute` over as a task after 3 s (`SessionInbox.steer_waiting?`, a peek the worker's turn polls through `Engine#input_waiting?`; in a participant's turn only their own line): the file stays for the drain. A queue is sent only to a worker whose `bridge.json` names the `delivery` feature; an older one would steer it, so `SessionManager.deliver_turn` refuses it (409 `delivery_unavailable`), and any other 4xx the Bridge answers is a refusal too, never a fallback file (except a 413, a body over its size limit: that one still goes in as a file, its `delivery` kept). A session command recognized in a file runs without a turn; its outcome is kept at `input/settled/<enqueued_id>` (`completed`, `failed` for a command error, `canceled` with `cancel_reason` `busy` or `dropped` for one refused mid-turn or dropped as the worker left; `origin: command`) so `chi send --wait` ends instead of waiting for a turn that will not run, its detail saying `the command failed` or `the command was refused (busy)` rather than a turn's words. **Reply files:** a turn that ends with visible text leaves its reply in `output/<timestamp>.txt`, or `output/<timestamp>-<enqueued_id>.txt` when the turn ran an input file with an id (`SessionInbox.write_output`), and the session's `last_turn` keeps that `enqueued_id`; so a wait for one queued message (`chi send --queue --wait`, `ReplyWait`'s `turn:`) finds its own turn's reply or end, never another turn's. The names still sort by time, and every reader takes `*.txt`.
12
12
 
@@ -106,7 +106,7 @@ chi sessions clean --dry-run --days 7 # test sessions older than 7 da
106
106
  - Web notifications: when a session needs you while the tab is hidden or behind another window (a question or a guardrail approval, a plugin card with buttons during a turn such as check-in's, a failed turn, a turn done after 10 s or more; a delegated session only for its questions, a canceled turn never), the page title counts it, `(N) Chi`, until you come back to the tab. The bell at the right of the top bar also turns on OS notifications ("needs an answer", "needs approval", "needs you", "turn failed", "done in 42 s", under the session's first message; a click opens the session): its first click asks the browser for the permission, and the choice is kept per browser. Any session of the page's scope counts, not only the open one. What was already so when the page loaded never counts, and several chi tabs show one notification per event. A chi tab in front tells the others (a `BroadcastChannel`), so while you look at one, the ones behind neither notify nor count what it shows; coming back to a tab clears those events in the other tabs' titles too. The hub's `session` frames carry what this needs: `pending_question` (`{id, kind}`, kind `question` or `approval`), `pending_card` (`{id, bundle}`: the running turn's card with actions, from `pending_card.json` that the worker keeps in the session's folder while one is open; a card without actions, such as loop-guard's, never counts) and `last_turn` (`{outcome, ended_at, seconds, origin}`, saved in the session's JSON as the engine ends each turn).
107
107
  - The web frontend is a zero-build ES-module stack in `lib/samagotchi/web/public/`: `data.js` (retrieval, typed SSE `openStream` for a session and `openEvents` for the session list), `sessions_list.js` (the list as a pure reducer over `GET /api/events`: a snapshot replaces it, an upsert keeps a known card in place, a removal drops it; `families()` groups delegates under their parent), `families_view.js` (a parent's family chip, its rows and the strip's popover; the chip and rows as lit-html templates), `keep_focus.js` (lit reuses a list's nodes by position: a redraw keeps the focus on the same item by its `data-id` / `data-name`), `chains.js` (session chains: the links from `continues`, the cards folded into the latest link's, its `#N` chip and rows as lit-html templates, the info bar's ← → links, a refused continue, and the fresh-link rule), `notify.js` (which of those events needs the user, for the notifications), `app.js` (presentation/state; a session with no live stream gets one when its `session` event says `bridge_up`, after one re-read: `event_seq` starts over in each worker, so a dropped stream is never resumed with its old cursor), `bubbles.js` (the history's bubbles between the turns' rows: output chunks, end lines, every client's prompt bubbles by `enqueued_id` with their queued/steered badges, the idle recap, guardrail warnings, hooks' notices, plugins' steers, command and note bubbles; lit-html templates, put in the history with the sticky follow by `createBubbles`), `cards_place.js` (where plugin cards and a snapshot's notices go in the history: a card added or updated in place by its id, a running turn's into its step, a snapshot's each above the first turn after it, a finished turn's notice in its step's rows and its question resolved where it was asked; a card's action buttons), `format.js` (pure formatters such as `previewOf`), `plain_line.js` (markdown out of the plain one-line places: the stage headline, a closed step's title, an answered question card's kept-reply line), `prompt_history.js` (the composer's ↑/↓ over the shared prompt history), `commands.js` (session commands: which composer lines are commands, the page's own replies, a `command_ran`'s bubble, the page's command bubbles kept across a re-read), `composer.js` (where a composer line goes, `routeComposerLine`: /cut and /queue, the start page's own replies, a session command or `!cmd`, a typo hint, else a turn; and a session command sent from the composer or a chip), `delivery_line.js` (the composer's row above the text field in a session, always there so the composer keeps its height (on a phone no row: the line lies over the session bar's left while a turn runs and you type or have a choice armed): the key hint while idle, and the delivery line while a turn runs: where a message typed now goes in, from the step's phase, clock and size, whether "cut in now" can land, and the queue link for a worker with the `delivery` feature, as a pure `deliveryLine`, its lit-html template and `createDeliveryControl`, which ticks it and keeps a choice armed from a link; see docs/cli.md, "Typing during a turn"), `restore.js` (a failed turn's prompt handed back into this tab's composer, before or after its `/turn` ack), `lists_view.js` (the session lists: the strip and its pill, all sessions with its search, count and select mode, their cards, the family and chain popovers; the cards, tile and pill as lit-html templates, drawn as new nodes each time, and the lists' orders as pure functions), `stream_handlers.js` (the open session's stream event handlers, by event type, over the page's views and hooks; a snapshot replays through them too), `stage_view.js` (the stage view: the running turn pinned above the composer, with Stop turn in its status row while it runs, then handed off into the history; its pure rules and texts in `stage_model.js`, its live slots (headline, now row, trail, ticks) in `stage_slots.js`, its cap and held height in `stage_frame.js`, the in-use watch that times the hand-off in `stage_watch.js`), `info_bar.js` (the session bar's info line as a lit-html template over a plain model, three groups with hairlines between them, on one line above a phone's width (the folder gives way first): the setup (id, status, model, the ⚙ and 🧰 chips, notes, the memory or working-set chip), the relations (chain links, the parent as `↑ <id>`, delegates, participants; only when there is one) and the telemetry (folder, ctx, speed, the session's time, worker badge)), `settings_chip.js` (the session bar's ⚙ chip and its panel over `settings_panel.js`: a tap runs that row's command, one field), `toolkit_chip.js` (the session bar's 🧰 chip: the kit against `toolkit.default`), `info_bar_model.js` (that model and the bar's buttons' states, built from the page's session state, its list and its in-flight continues and restarts (the restarting set is `version_notices.js`'s) as pure functions; `app.js`'s `updateInfoBar` applies them every second while a turn runs), `session_state.js` (what the page knows about the open session: its empty state, and `sessionStateFrom`, the fields a `GET /sessions/:id` payload sets), `refs.js` (refs: a kind and a target on the element, a plugin's ref data (label, http(s) URL actions) bound in a WeakMap by `bindRef`, the targets per kind, show in turn, one delegated set of click, key and hover listeners), `ref_menu.js` (a ref's `▾` and its menu), `ref_scan.js` (the `path:line` refs in an answer's or a step's text that name a file the session's rows touched), `answer_refs.js` (the refs a plugin attached to an answer, its `display_refs`: bound to the answer's bubble, paired with its links and text, bound with `bindRef`), `markdown_place.js` (where rendered markdown and its refs go: a text as markdown HTML, its `path:line` refs, a final answer's rendering), `images.js` (image chips in the composer: paste, drop and the image button, the upload before a turn, the thumbnails and the lightbox), `composer_grip.js` (the composer's grip and fold: the drag, tap and keys, the fold per visit), `composer_mount.js` (the composer mounted on a page's markup: the message box and its height, the image chips from a paste, a drop or the image button, the grip and fold, ↑/↓ over the prompt history and the keys; the page's own parts come in as hooks: what Enter and Send do, keys taken first, Esc, where the history comes from, the info bar's drop while folded, typing anywhere to open it; its styles, the card it sits in (`.composer-card`, its footer and its line above the text field) included, are the shared `composer.css`, linked after `tokens.css` by `index.html`), `strip_grip.js` (the latest-sessions strip's grip, the composer grip's twin: hides and shows the strip), `strip_hidden.js` (the strip hidden or shown: the saved choice, the short window's own hide, the grip and the body's class), `storage.js` (the page's per-browser choices in localStorage, guarded: a choice that can't be read or written is not remembered), `unqueue.js` (the × on a message queued for after the turn: takes it back, its text into an empty composer or a toast), `toasts.js` (the page's toast stack: a timer each, sticky ones until acted on, the same text reusing its item), `toast_place.js` (where the toast sits: above the composer card, the stage and an open model panel), `dock_reserve.js` (what floats over the history: the history's bottom reserve (`--dock-h`) at the composer card's and the showing stage's height, a reader at the end kept there, and the toast's place measured for `toast_place.js`), `notice_links.js` (a hook notice line's http(s) URLs as links), `start_page.js` (the start page's model picker, its ⚙ panel's and 🧰 list's choices for the next new session only and their override chips; a fresh chain link's picker and its `/model`), `start_settings.js` (the start page's ⚙ panel: thinking and LLM context as rows of segments, applied at once, the Apply and budget disclosure; the override chips' words and ⚙'s dot), `settings_panel.js` (the panel's rows as lit-html templates, shared: the segments, the disclosure, a hidden row's sent-anyway line; the caller passes its rows and applies the picks), `start_toolkit.js` (the start page's 🧰 list: Auto with suggest on, the kits, the default marked; a pick closes it; its override chip and dot), `session_actions.js` (Continue, Archive and its Undo, Delete and Stop, and the start page when the open session is gone), `send_turn.js` (the composer's send: a new session first on the start page, the route, the echo, the image upload, the `/turn` ack, a fast failure's restore and each error's place). Unit-tested via `npm test` (`spec/web/public/*.test.js`).
108
108
  - Selecting a session in the web UI is read-only: `GET /api/sessions/:id` never spawns a worker (it reads a live worker's snapshot when one runs, else the session file). A prompt (`POST /turn`) or a command (`POST /command`) wakes the worker, and `/stream` briefly waits for a freshly-spawned bridge before answering. A caught-up SSE reconnect holds the stream open; `reset` markers are only sent for reconnects behind the ring window, or with a cursor from another worker (event ids are `<event_seq>-<epoch>`, one epoch per worker).
109
- - The web session page's message box folds away for room to read. Drag the grip on its top edge (the pill that shows on hover; always on a phone) down, past the box by 32 px: the pill turns accent while releasing would hide it, and on release the box folds and the info bar stays as the page's bottom edge. The grip stays as a handle on the info bar's top edge, drawn always: pull it up (8 px opens it, and the box follows the pointer in the same gesture), click or tap it (opens it and focuses the box), or just type on the page (the key lands in the box) to bring it back; Enter or Space on the focused grip folds or opens too. A draft (text or images, which folding never clears) colours the handle with the accent, a session waiting on you with the attention colour; its tooltip says so. Stop turn isn't the message box's: it sits in the running turn's stage, at the right edge of its status row beside the fold caret (collapsed stage or not), while the turn runs, and goes when the turn ends A turn the page knows runs but has nothing of to draw (a reload whose session payload carries no current turn) shows that status row alone, `running` and Stop turn. The fold is remembered per browser (`chi_composer_collapsed`), an archived session opens folded for the visit, and opening it there, like the page opening it itself (a restored line, a quote, continue →'s opener), is for that visit only. The fold keeps the height the grip set (`chi_composer_floor`): the box opens again at the height it had, and only a double-click on the grip forgets it. That height never takes more than half of the window the box is drawn in: a floor saved in a bigger window is held to that half in a smaller one (a rotated phone, a resized window, another device on the same origin), and the saved floor itself stays, so the height comes back when the room does. A click on the expanded grip hides the box as well: it folds 250 ms after the press, so a second click inside that window is read as a double-click and resets the height instead (a drag, Enter or Space act at once, and a drag after a click takes the wait back). The start page's grip only resizes.
109
+ - The web session page's message box folds away for room to read. Drag the grip on its top edge (the pill that shows on hover; always on a phone) down, past the box by 32 px: the pill turns accent while releasing would hide it, and on release the box folds and the info bar stays as the page's bottom edge. The grip stays as a handle on the info bar's top edge, drawn always: pull it up (8 px opens it, and the box follows the pointer in the same gesture), click or tap it (opens it and focuses the box), or just type on the page (the key lands in the box) to bring it back; Enter or Space on the focused grip folds or opens too. A draft (text or images, which folding never clears) colours the handle with the accent, a session waiting on you with the attention colour; its tooltip says so. Stop turn isn't the message box's: it sits in the running turn's stage, at the right edge of its status row beside the fold caret (collapsed stage or not), while the turn runs, and goes when the turn ends A turn the page knows runs but has nothing of to draw (a reload whose session payload carries no current turn) shows that status row alone, `running` and Stop turn. The fold is each session's own, remembered per browser (`chi_composer_collapsed:<session>`: folding one session's box leaves the others' as they were), an archived session opens folded for the visit, and opening it there, like the page opening it itself (a restored line, a quote, continue →'s opener), is for that visit only. The fold keeps the height the grip set, also the session's own (`chi_composer_floor:<session>`; the start page's lasts until a reload): the box opens again at the height it had, and only a double-click on the grip forgets it. That height never takes more than half of the window the box is drawn in: a floor saved in a bigger window is held to that half in a smaller one (a rotated phone, a resized window, another device on the same origin), and the saved floor itself stays, so the height comes back when the room does. A click on the expanded grip hides the box as well: it folds 250 ms after the press, so a second click inside that window is read as a double-click and resets the height instead (a drag, Enter or Space act at once, and a drag after a click takes the wait back). The start page's grip only resizes.
110
110
 
111
111
  **Test-session hygiene:**
112
112
 
@@ -150,13 +150,16 @@ module Samagotchi
150
150
  # session, /exit --delete) or stop: ("all": stop everything the user
151
151
  # can stop first), returns nil when the worker will leave or
152
152
  # what keeps it up (a WorkerIdleExit::Hold: #reason, #tasks, #hint,
153
- # #holds); called with the event log held. Without one, POST /exit
153
+ # #holds); called with the event log held, and +exit_stopped+ is read
154
+ # there too, right after the accept. Without one, POST /exit
154
155
  # answers 501
155
156
  # @param exit_discards [#call, nil] after an exit the worker agreed to:
156
157
  # whether it will delete the session as empty (the 200 says
157
158
  # +discard+); without one the reply leaves the field out
158
159
  # @param exit_stopped [#call, nil] after a stop-all exit: what it stopped
159
- # (a HoldStop::Stopped) for the 200's +stopped+; nil leaves it out
160
+ # (a HoldStop::Stopped) for the 200's +stopped+; nil leaves it out. Read
161
+ # with the event log held, right after the accept (not for a restart),
162
+ # so a later exit's list is never this 200's
160
163
  # @param on_holds [#call, nil] what the user could stop in this worker
161
164
  # right now (WorkerIdleExit#stoppable_holds) for GET /holds; without
162
165
  # one that route answers 501
@@ -1169,11 +1172,16 @@ module Samagotchi
1169
1172
  deadline = fetched(parsed, "deadline")
1170
1173
  return BAD_DEADLINE unless deadline_valid?(deadline)
1171
1174
 
1175
+ stopped = nil
1172
1176
  hold = @engine.synchronize_events do
1173
1177
  raise IntakeClosed if stopped?
1174
1178
  next :expired if expired?("exit_expired", deadline, sid: session_id, client_id: client_id)
1175
1179
 
1176
- @on_exit_request.call(client_id, **options)
1180
+ hold = @on_exit_request.call(client_id, **options)
1181
+ # Read here, right after the accept: every accept runs with the log
1182
+ # held, so no later exit's list can be the one this 200 carries.
1183
+ stopped = @exit_stopped&.call if hold.nil? && !restart
1184
+ next hold
1177
1185
  end
1178
1186
  return deadline_passed("exit request") if hold == :expired
1179
1187
 
@@ -1182,7 +1190,6 @@ module Samagotchi
1182
1190
 
1183
1191
  body = { status: "exiting", session_id: @session_id }
1184
1192
  body[:discard] = @exit_discards.call == true if @exit_discards
1185
- stopped = @exit_stopped&.call
1186
1193
  body[:stopped] = stopped.to_h if stopped
1187
1194
  return [{}, 200, body]
1188
1195
  end
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.175.0
3
+ version: 0.176.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
@@ -388,6 +388,9 @@ module Samagotchi
388
388
  # The stage view's working set (files, memories and URLs the turn brought into context): a rail in the stage, a
389
389
  # footprint under each finished turn and a "set N" chip in place of the mem chip; ?working_set=1|0 overrides it per page load.
390
390
  Entry.new(key: "web.working_set", yaml_path: %w[web working_set], type: :bool, default: true, expose: %i[env config cli], lifecycle: :web_start),
391
+ # Every session's stage starts folded to its status row in chi web (a session folded or unfolded by hand keeps
392
+ # its own, per browser: session_prefs.js); participants' pages too.
393
+ Entry.new(key: "web.stage_collapsed", yaml_path: %w[web stage_collapsed], type: :bool, default: false, expose: %i[env config cli], lifecycle: :web_start),
391
394
  # Opt-in: the page checks each finished turn against a reload of it (one full read per turn end) and chi web logs
392
395
  # reload_checked, with reload_mismatch and the kinds that differed (counts only, no content).
393
396
  Entry.new(key: "web.reload_check", yaml_path: %w[web reload_check], type: :bool, default: false, expose: %i[env config cli], lifecycle: :web_start),
@@ -36,6 +36,8 @@ module Samagotchi
36
36
  def owned?(file, grant_id) = entries.any? { |entry| entry.file == file && entry.grant_id == grant_id }
37
37
  end
38
38
  BROKEN = State.new(entries: [].freeze, attempts: {}.freeze, broken: true)
39
+ WARNED_UNREADABLE = Set.new
40
+ WARNED_UNREADABLE_MUTEX = Mutex.new
39
41
 
40
42
  module_function
41
43
 
@@ -55,10 +57,21 @@ module Samagotchi
55
57
 
56
58
  State.new(entries: entries, attempts: attempts.transform_values(&:to_i), broken: false)
57
59
  rescue JSON::ParserError, SystemCallError, TypeError, KeyError, NoMethodError => e
58
- Log.warn(:web, "participant_images_unreadable", file: path, msg: e.message)
60
+ warn_unreadable(path, e)
59
61
  BROKEN
60
62
  end
61
63
 
64
+ def warn_unreadable(path, error)
65
+ stat = begin
66
+ File.stat(path)
67
+ rescue SystemCallError
68
+ nil
69
+ end
70
+ key = [path, stat&.size, stat&.mtime]
71
+ first = WARNED_UNREADABLE_MUTEX.synchronize { WARNED_UNREADABLE.add?(key) }
72
+ Log.warn(:web, "participant_images_unreadable", file: path, msg: error.message) if first
73
+ end
74
+
62
75
  # Distinct files +grant_id+ uploaded; a broken record reads as at quota.
63
76
  def count(dir, grant_id) = read(dir).count(grant_id)
64
77
 
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.175.0"
4
+ VERSION = "0.176.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -160,6 +160,9 @@ module Samagotchi
160
160
  # freshly-spawned worker's bridge before answering POST /api/sessions.
161
161
  # @param working_set [Boolean] the stage view's working set
162
162
  # (web.working_set); ?working_set=1|0 overrides it for one page load
163
+ # @param stage_collapsed [Boolean] every session's stage starts folded
164
+ # to its status row (web.stage_collapsed: the page's default; a
165
+ # session folded by hand keeps its own, session_prefs.js)
163
166
  # @param reload_check [Boolean] the page checks each finished turn
164
167
  # against a reload of it and posts the counts (web.reload_check,
165
168
  # opt-in; POST /api/sessions/:id/reload_check logs them)
@@ -202,6 +205,7 @@ module Samagotchi
202
205
  registry: nil, models_wait_timeout: MODELS_WAIT_TIMEOUT, lan: nil,
203
206
  working_set: Config::BY_KEY["web.working_set"].default, wait_poll_interval: ReplyWait::POLL_INTERVAL,
204
207
  reload_check: Config::BY_KEY["web.reload_check"].default,
208
+ stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
205
209
  grants: nil, public_url: nil, public_token: nil, push: nil, start_dir: nil, update_runner: nil,
206
210
  update_blocked: nil, update_ops: nil)
207
211
  @start_dir = start_dir
@@ -218,6 +222,7 @@ module Samagotchi
218
222
  @markdown_renderer = MarkdownRenderer.new(enabled: markdown)
219
223
  @working_set = working_set
220
224
  @reload_check = reload_check
225
+ @stage_collapsed = stage_collapsed
221
226
  @reload_checks = ReloadCheckRoute::Seen.new
222
227
  @annotate_presets = annotate_presets.is_a?(Array) ? annotate_presets.join("|") : annotate_presets.to_s
223
228
  @editor_url = Editor.template(editor)
@@ -1925,6 +1930,7 @@ module Samagotchi
1925
1930
  attrs["working-set"] = "1" if working_set?(req.GET["working_set"])
1926
1931
  # The opt-in reload check (reload_check.js): only when on.
1927
1932
  attrs["reload-check"] = "1" if @reload_check
1933
+ attrs.merge!(stage_collapsed_data)
1928
1934
  attrs.merge!(annotate_presets_data)
1929
1935
  # Who looks and what they may do (Viewer; viewer.js reads it at boot).
1930
1936
  attrs.merge!(Viewer.for(principal(req)).body_attributes)
@@ -1952,8 +1958,9 @@ module Samagotchi
1952
1958
 
1953
1959
  # A participant's <body> data for index.html: who they are (Viewer), their
1954
1960
  # grant's session and its participant title (the tab's), the version
1955
- # and the Annotate presets, and whether the working set is on
1956
- # (web.working_set: their stage's file column, as the owner's).
1961
+ # and the Annotate presets, whether the working set is on
1962
+ # (web.working_set: their stage's file column, as the owner's) and the
1963
+ # stage's fold default (web.stage_collapsed, the owner's).
1957
1964
  # Nothing of the owner's machine: no home, folders, project or way
1958
1965
  # back (sessions-dir, server-dir, home, scope-dir, project-*, back-*).
1959
1966
  def participant_index_data(req)
@@ -1964,6 +1971,7 @@ module Samagotchi
1964
1971
  participant_title(@session_class.load(grant.session_id, state_dir: default_state_dir))
1965
1972
  end
1966
1973
  attrs["session-title"] = title if title
1974
+ attrs.merge!(stage_collapsed_data)
1967
1975
  attrs.merge!(annotate_presets_data)
1968
1976
  attrs.merge!(Viewer.for(principal(req)).body_attributes)
1969
1977
  body_data(attrs)
@@ -1972,6 +1980,11 @@ module Samagotchi
1972
1980
  # +attrs+ as <body> data attributes, each value escaped.
1973
1981
  def body_data(attrs) = attrs.map { |key, value| %(data-#{key}="#{Rack::Utils.escape_html(value)}") }.join(" ")
1974
1982
 
1983
+ # The stage's fold default (web.stage_collapsed) for the page's <body>,
1984
+ # the owner's and a participant's (a layout choice, not a secret): only
1985
+ # when on; the page reads its presence (session_prefs.js).
1986
+ def stage_collapsed_data = @stage_collapsed ? { "stage-collapsed" => "1" } : {}
1987
+
1975
1988
  # The Annotate presets (web.annotate_presets) for the page's <body>,
1976
1989
  # the owner's and a participant's. Always there: an empty one means
1977
1990
  # no presets, not the default.