samagotchi 0.164.0 → 0.165.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 (85) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +52 -1
  3. data/docs/architecture.md +7 -5
  4. data/docs/cli.md +20 -13
  5. data/docs/configuration.md +5 -1
  6. data/docs/guardrails.md +13 -16
  7. data/docs/internals/block-renderers.md +1 -1
  8. data/docs/internals/bridge.md +4 -3
  9. data/docs/internals/bundles.md +4 -2
  10. data/docs/internals/inline-widgets.md +8 -1
  11. data/docs/internals/web-frontend.md +36 -9
  12. data/docs/memory.md +12 -7
  13. data/docs/plugins.md +6 -4
  14. data/docs/releasing.md +6 -2
  15. data/docs/scheduling.md +25 -3
  16. data/docs/sessions.md +8 -6
  17. data/docs/testing.md +28 -4
  18. data/lib/samagotchi/block_renderers.rb +3 -6
  19. data/lib/samagotchi/bridge/card_store.rb +2 -1
  20. data/lib/samagotchi/bridge/turn_accumulator.rb +7 -8
  21. data/lib/samagotchi/bridge.rb +45 -3
  22. data/lib/samagotchi/bundle_command/installed_check.rb +2 -1
  23. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  24. data/lib/samagotchi/chi_home.rb +44 -2
  25. data/lib/samagotchi/client_id.rb +34 -3
  26. data/lib/samagotchi/compat.rb +36 -0
  27. data/lib/samagotchi/context_command.rb +3 -0
  28. data/lib/samagotchi/context_providers.rb +5 -6
  29. data/lib/samagotchi/context_sources.rb +2 -2
  30. data/lib/samagotchi/continue_intent.rb +50 -5
  31. data/lib/samagotchi/events.rb +4 -4
  32. data/lib/samagotchi/extension_load.rb +2 -1
  33. data/lib/samagotchi/guardrails/child_boundary.rb +7 -27
  34. data/lib/samagotchi/guardrails/rules.rb +11 -9
  35. data/lib/samagotchi/guardrails/targets.rb +3 -4
  36. data/lib/samagotchi/inline_widgets.rb +16 -1
  37. data/lib/samagotchi/memory_bundle/provenance.rb +46 -4
  38. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  39. data/lib/samagotchi/memory_command.rb +3 -0
  40. data/lib/samagotchi/memory_orphans.rb +4 -7
  41. data/lib/samagotchi/memory_paths.rb +64 -7
  42. data/lib/samagotchi/memory_usage.rb +1 -1
  43. data/lib/samagotchi/plugin/sessions.rb +4 -2
  44. data/lib/samagotchi/project_command.rb +4 -1
  45. data/lib/samagotchi/project_id_clash.rb +37 -26
  46. data/lib/samagotchi/project_init.rb +24 -7
  47. data/lib/samagotchi/reply_wait/poll.rb +2 -1
  48. data/lib/samagotchi/schedules.rb +124 -106
  49. data/lib/samagotchi/send_command.rb +71 -18
  50. data/lib/samagotchi/session.rb +3 -2
  51. data/lib/samagotchi/session_access/local.rb +19 -2
  52. data/lib/samagotchi/session_access/remote.rb +15 -4
  53. data/lib/samagotchi/session_chain/links.rb +109 -0
  54. data/lib/samagotchi/session_chain.rb +7 -19
  55. data/lib/samagotchi/session_continue.rb +138 -54
  56. data/lib/samagotchi/session_inbox_delivery.rb +57 -38
  57. data/lib/samagotchi/session_manager/delivery.rb +104 -18
  58. data/lib/samagotchi/session_manager/removal.rb +13 -7
  59. data/lib/samagotchi/session_manager.rb +1 -0
  60. data/lib/samagotchi/session_retention.rb +20 -10
  61. data/lib/samagotchi/session_setup.rb +31 -1
  62. data/lib/samagotchi/state_format.rb +12 -8
  63. data/lib/samagotchi/terminal_ui/attach_launcher.rb +6 -7
  64. data/lib/samagotchi/terminal_ui.rb +20 -9
  65. data/lib/samagotchi/tools/delegate.rb +2 -1
  66. data/lib/samagotchi/verify_fresh.rb +4 -1
  67. data/lib/samagotchi/version.rb +1 -1
  68. data/lib/samagotchi/web/public/activity.js +2 -2
  69. data/lib/samagotchi/web/public/app.js +13 -13
  70. data/lib/samagotchi/web/public/bar_fold.js +293 -0
  71. data/lib/samagotchi/web/public/card.js +1 -1
  72. data/lib/samagotchi/web/public/composer_mode.js +5 -7
  73. data/lib/samagotchi/web/public/index.html +132 -65
  74. data/lib/samagotchi/web/public/info_bar.js +28 -16
  75. data/lib/samagotchi/web/public/info_bar_model.js +70 -1
  76. data/lib/samagotchi/web/public/more_sheet.js +98 -40
  77. data/lib/samagotchi/web/public/stage_view.js +3 -1
  78. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  79. data/lib/samagotchi/web/public/turn_events.js +0 -122
  80. data/lib/samagotchi/web/public/turn_model.js +1 -1
  81. data/lib/samagotchi/web/public/widget_picks.js +18 -3
  82. data/lib/samagotchi/web/session_control.rb +15 -2
  83. data/lib/samagotchi/web/session_create.rb +4 -2
  84. data/lib/samagotchi/web/update_check.rb +27 -8
  85. metadata +3 -1
@@ -1,8 +1,18 @@
1
- // The phone's session bar keeps id, status, model and ⚙ on its row; the rest
2
- // sits behind ⋯ (#infoMoreBtn, index.html's CSS shows it at the page's phone
3
- // width only). This is its bottom sheet, on chip_popover.js' shell as the ⚙
4
- // panel is: a row for each chip the row folded away, one telemetry line, and
5
- // the bar's four actions.
1
+ // The session bar's ⋯ (#infoBar's #infoMoreBtn, on the row at every width):
2
+ // what the row folded away (bar_fold.js), as a popover above the phone's
3
+ // width and a bottom sheet under it, on chip_popover.js' shell as the ⚙ panel
4
+ // is. A row per folded chip, a telemetry line for the folded ones of speed,
5
+ // the clock and the folder, and the bar's actions; which rows and actions
6
+ // exist, and in what order, is info_bar_model.js BAR_ITEMS (menuOrder), the
7
+ // bar's one list of its items.
8
+ //
9
+ // +folded+ (a Set of BAR_ITEMS keys: the items folded off the row) narrows
10
+ // the menu to them: a row only for a folded chip (the id, ⚙ when folded, not
11
+ // when compact, and "earlier links pruned" included), Continue and Stop only
12
+ // when folded (Archive and Delete always: they are never on the row), ⋯'s
13
+ // dot from folded rows alone and its count (moreCount: shown on a desktop
14
+ // only). Without it (null) the menu has its fixed set: every chip's row but
15
+ // those three, the whole telemetry line and all four actions.
6
16
  //
7
17
  // The chips and the buttons stay where they are, display:none: a row or an
8
18
  // action clicks the real one (`go:`), so its handlers, confirmations and state
@@ -10,22 +20,26 @@
10
20
  // the same way). What a chip then opens places itself and gives focus back at
11
21
  // ⋯, chip_popover.js' stand-in for an anchor with no box ([data-anchor-stand-in]).
12
22
  // A chip with a tooltip and no popover (🧰, memories, model notes) unfolds its
13
- // tooltip under the row (`info:`): a phone has no tooltips. The model has a row
14
- // too: its chip stays on the bar but is the first to give way, cut short.
23
+ // tooltip under the row (`info:`): a phone has no tooltips.
15
24
  //
16
25
  // app.js's updateInfoBar calls update() on every redraw (every second while a
17
- // turn runs): lit writes only what changed, into slots that keep their place,
18
- // so an open sheet stays current and keeps its focus. A module of its own: the
19
- // page's modules are cached at unversioned URLs (docs/internals/web-frontend.md).
26
+ // turn runs), after the fold's: lit writes only what changed, into slots that
27
+ // keep their place, so an open menu stays current and keeps its focus. A
28
+ // module of its own: the page's modules are cached at unversioned URLs
29
+ // (docs/internals/web-frontend.md).
20
30
 
21
31
  import { createChipPopover, SHEET_TALL } from "./chip_popover.js";
22
32
  import { memChipText } from "./format.js";
23
33
  import { CLOCK_NONE, memoriesTooltip, NEXT, PREV } from "./info_bar.js";
34
+ import { BAR_ITEMS } from "./info_bar_model.js";
35
+ import { chipModel as settingsChip } from "./settings_chip.js";
24
36
  import { chipModel as toolkitChip } from "./toolkit_chip.js";
25
37
  import { html, nothing, render } from "./vendor/lit-html.js";
26
38
 
27
39
  // The real element each `go:` act clicks.
28
40
  const TARGETS = {
41
+ id: "#infoText .id",
42
+ settings: "#infoText .settings-chip",
29
43
  workingSet: "#infoText .ws-chip",
30
44
  participants: "#infoText .participants-chip",
31
45
  delegates: "#infoText .children-chip",
@@ -36,9 +50,16 @@ const TARGETS = {
36
50
  delete: "#infoDeleteBtn",
37
51
  };
38
52
 
39
- // Every row, in the sheet's order; each draws into a slot of its own.
40
- const ROW_KEYS = ["model", "toolkit", "workingSet", "memories", "participants", "prev", "next", "parent", "delegates", "notes", "worker"];
41
- const ACTION_KEYS = ["continue", "archive", "stop", "delete"];
53
+ // Every row and every action, in the sheet's order (BAR_ITEMS' menuOrder);
54
+ // each draws into a slot of its own.
55
+ const inMenu = (actions) => BAR_ITEMS
56
+ .filter((item) => item.menuOrder !== null && (item.group === "actions") === actions)
57
+ .sort((a, b) => a.menuOrder - b.menuOrder)
58
+ .map((item) => item.key);
59
+ export const ROW_KEYS = Object.freeze(inMenu(false));
60
+ export const ACTION_KEYS = Object.freeze(inMenu(true));
61
+ // The actions every sheet has; the others only when folded.
62
+ const ALWAYS_ACTIONS = new Set(["archive", "delete"]);
42
63
 
43
64
  const short = (id) => String(id).slice(0, 8);
44
65
  const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
@@ -79,16 +100,20 @@ function workerRow({ badge, busy }) {
79
100
  // session has its chip: {key, label, value, and how a tap acts: go (a TARGETS
80
101
  // key), href, info (the text it unfolds), restart ({busy}); attention: "accent"
81
102
  // or "warn" when the chip asks for a look; icon: a chip icon's class}.
82
- export function moreRows(bar) {
103
+ export function moreRows(bar, folded = null) {
83
104
  if (!bar) return [];
84
105
  const memories = bar.memories || [];
85
- return [
106
+ const gear = folded?.has("settings") && bar.settings && settingsChip(bar.settings);
107
+ const rows = [
108
+ folded?.has("id") && { key: "id", label: "Session id", value: short(bar.id), go: "id" },
86
109
  bar.model && modelRow(bar.model),
110
+ gear && { key: "settings", label: "Settings", value: gear.text || "follows the model", go: "settings" },
87
111
  bar.toolkit && toolkitRow(bar.toolkit),
88
112
  bar.workingSet?.chip && workingSetRow(bar.workingSet.chip),
89
113
  !bar.workingSet && memories.length > 0
90
114
  && { key: "memories", label: "Memories", value: memChipText(memories), info: memoriesTooltip(memories, bar.preloaded, bar.muted) },
91
115
  bar.participants && participantsRow(bar.participants),
116
+ folded?.has("pruned") && bar.chain?.pruned && !bar.chain?.prev && { key: "pruned", label: "Earlier links pruned", value: "by a schedule" },
92
117
  bar.chain?.prev && { key: "prev", label: "Previous link", value: `${PREV} ${bar.chain.prev.date || short(bar.chain.prev.id)}`, href: bar.chain.prev.id },
93
118
  bar.chain?.next && { key: "next", label: "Next link", value: `${bar.chain.next.date || short(bar.chain.next.id)} ${NEXT}`, href: bar.chain.next.id },
94
119
  bar.parent && { key: "parent", label: "Delegated by", value: `↑ ${short(bar.parent.id)}`, href: bar.parent.id },
@@ -96,13 +121,15 @@ export function moreRows(bar) {
96
121
  bar.notes && { key: "notes", label: "Model notes", value: bar.notes.text.replace(/^notes: /, ""), info: bar.notes.title },
97
122
  bar.worker?.badge && workerRow(bar.worker),
98
123
  ].filter(Boolean);
124
+ return folded ? rows.filter((row) => folded.has(row.key)) : rows;
99
125
  }
100
126
 
101
127
  // ⋯'s dot: what behind it asks for a look. {kind} is the strongest ("warn":
102
128
  // a delegate waiting, an older worker; "accent": the working set changed, a
103
129
  // participant here; null: none), {label} ⋯'s accessible name, which says why.
104
- export function moreAttention(bar) {
105
- const rows = moreRows(bar).filter((row) => row.attention);
130
+ // With +folded+, only the folded rows count: a chip on the row shows its own.
131
+ export function moreAttention(bar, folded = null) {
132
+ const rows = moreRows(bar, folded).filter((row) => row.attention);
106
133
  const kind = rows.some((row) => row.attention === "warn") ? "warn" : rows.length ? "accent" : null;
107
134
  const why = rows.map((row) => `${row.label}: ${row.value}`).join(", ");
108
135
  return { kind, label: why ? `More: ${why}` : "More" };
@@ -110,15 +137,16 @@ export function moreAttention(bar) {
110
137
 
111
138
  // The four actions as the sheet draws them from +buttons+ (info_bar_model.js
112
139
  // infoButtons), each with the rule its button has; Continue takes the accent
113
- // on an archived session, where it is the thing to do.
114
- export function moreActions(buttons) {
140
+ // on an archived session, where it is the thing to do. With +folded+,
141
+ // Continue and Stop only when folded (on the row they are their own buttons).
142
+ export function moreActions(buttons, folded = null) {
115
143
  const all = [
116
144
  buttons.continue.shown && { key: "continue", text: capital(buttons.continue.text.replace(/ →$/, "")), disabled: buttons.continue.disabled, accent: !!buttons.archive.archived },
117
145
  buttons.archive.shown && { key: "archive", text: capital(buttons.archive.text), title: buttons.archive.title },
118
146
  buttons.stop.shown && { key: "stop", text: "Stop" },
119
147
  buttons.delete.shown && { key: "delete", text: "Delete" },
120
- ];
121
- return all.filter(Boolean);
148
+ ].filter(Boolean);
149
+ return folded ? all.filter((act) => ALWAYS_ACTIONS.has(act.key) || folded.has(act.key)) : all;
122
150
  }
123
151
 
124
152
  function rowBody(row) {
@@ -129,32 +157,57 @@ function rowBody(row) {
129
157
 
130
158
  function rowTemplate(row, { shownInfo, hash }) {
131
159
  const cls = `more-row${row.attention ? ` ${row.attention}` : ""}`;
132
- if (row.href) return html`<a class=${cls} href=${hash(row.href)} data-act="link">${rowBody(row)}</a>`;
133
- if (row.go) return html`<button type="button" class=${cls} data-act=${`go:${row.go}`}>${rowBody(row)}</button>`;
160
+ if (row.href) return html`<a class=${cls} href=${hash(row.href)} data-act="link" data-row=${row.key}>${rowBody(row)}</a>`;
161
+ if (row.go) return html`<button type="button" class=${cls} data-act=${`go:${row.go}`} data-row=${row.key}>${rowBody(row)}</button>`;
134
162
  if (row.restart) {
135
- return html`<div class=${cls}>${rowBody(row)}<button type="button" class="more-restart" data-act="go:restart" ?disabled=${row.restart.busy}>${row.restart.busy ? "restarting…" : "Restart"}</button></div>`;
163
+ return html`<div class=${cls} data-row=${row.key}>${rowBody(row)}<button type="button" class="more-restart" data-act="go:restart" ?disabled=${row.restart.busy}>${row.restart.busy ? "restarting…" : "Restart"}</button></div>`;
136
164
  }
137
- if (!row.info) return html`<div class=${cls}>${rowBody(row)}</div>`;
165
+ if (!row.info) return html`<div class=${cls} data-row=${row.key}>${rowBody(row)}</div>`;
138
166
  const open = shownInfo === row.key;
139
- return html`<button type="button" class=${cls} data-act=${`info:${row.key}`} aria-expanded=${open ? "true" : "false"}>${rowBody(row)}</button>${open ? html`<div class="more-info">${row.info}</div>` : nothing}`;
167
+ return html`<button type="button" class=${cls} data-act=${`info:${row.key}`} data-row=${row.key} aria-expanded=${open ? "true" : "false"}>${rowBody(row)}</button>${open ? html`<div class="more-info">${row.info}</div>` : nothing}`;
168
+ }
169
+
170
+ // The sheet for +bar+ and +buttons+ (each row carries data-row, its key: the
171
+ // e2e's way to it) (+folded+: moreRows'). +shownInfo+: the
172
+ // key of the row whose tooltip is unfolded; +hash+: a session's id to its link.
173
+ // The telemetry line's parts for +bar+: ctx, speed, the clock, the folder;
174
+ // with +folded+ only the folded ones of speed, the clock and the folder (ctx
175
+ // is pinned on the row).
176
+ export function moreTelemetry(bar, folded = null) {
177
+ if (!bar) return [];
178
+ const parts = [
179
+ { key: "ctx", show: true },
180
+ { key: "speed", show: !!bar.speed },
181
+ { key: "time", show: true },
182
+ { key: "dir", show: true },
183
+ ];
184
+ return parts.filter((p) => p.show && (!folded || (p.key !== "ctx" && folded.has(p.key)))).map((p) => p.key);
185
+ }
186
+
187
+ // The count on ⋯ (a desktop's; none at 0): the entries the menu has for
188
+ // folded items: their rows, telemetry and actions (Archive and Delete, never
189
+ // on the row, don't count). 0 without a fold.
190
+ export function moreCount(bar, buttons, folded) {
191
+ if (!bar || !folded) return 0;
192
+ const acts = buttons ? moreActions(buttons, folded).filter((act) => !ALWAYS_ACTIONS.has(act.key)).length : 0;
193
+ return moreRows(bar, folded).length + moreTelemetry(bar, folded).length + acts;
140
194
  }
141
195
 
142
- // The sheet for +bar+ and +buttons+. +shownInfo+: the key of the row whose
143
- // tooltip is unfolded; +hash+: a session's id to its link.
144
- export function moreSheetTemplate({ bar, buttons, shownInfo = null, hash }) {
145
- const rows = moreRows(bar);
146
- const actions = moreActions(buttons);
196
+ export function moreSheetTemplate({ bar, buttons, folded = null, shownInfo = null, hash }) {
197
+ const rows = moreRows(bar, folded);
198
+ const actions = moreActions(buttons, folded);
199
+ const tele = new Set(moreTelemetry(bar, folded));
147
200
  const speed = bar.speed;
148
201
  return html`<div class="more-grip" aria-hidden="true"></div
149
202
  ><div class="more-rows">${ROW_KEYS.map((key) => {
150
203
  const row = rows.find((r) => r.key === key);
151
204
  return row ? rowTemplate(row, { shownInfo, hash }) : nothing;
152
205
  })}</div
153
- ><div class="more-telemetry"><span class="more-ctx" title=${bar.ctx.tip}>${bar.ctx.text}</span
154
- >${speed ? html`<span class="more-speed" title=${speed.tip}>${speed.text}</span>` : nothing
155
- }<span class="more-clock">${bar.clock || CLOCK_NONE}</span
156
- ><span class="more-dir" title=${bar.dir || ""}><bdi>${bar.dir || ""}</bdi></span></div
157
- ><div class="more-actions">${ACTION_KEYS.map((key) => {
206
+ >${tele.size ? html`<div class="more-telemetry">${tele.has("ctx") ? html`<span class="more-ctx" title=${bar.ctx.tip}>${bar.ctx.text}</span>` : nothing
207
+ }${tele.has("speed") ? html`<span class="more-speed" title=${speed.tip}>${speed.text}</span>` : nothing
208
+ }${tele.has("time") ? html`<span class="more-clock">${bar.clock || CLOCK_NONE}</span>` : nothing
209
+ }${tele.has("dir") ? html`<span class="more-dir" title=${bar.dir || ""}><bdi>${bar.dir || ""}</bdi></span>` : nothing}</div>` : nothing
210
+ }<div class="more-actions">${ACTION_KEYS.map((key) => {
158
211
  const act = actions.find((a) => a.key === key);
159
212
  if (!act) return nothing;
160
213
  return html`<button type="button" class=${`more-act ${key}${act.accent ? " accent" : ""}`} data-act=${`go:${key}`}
@@ -164,14 +217,15 @@ export function moreSheetTemplate({ bar, buttons, shownInfo = null, hash }) {
164
217
 
165
218
  // ⋯'s sheet. el: where ⋯ is drawn (#infoBar); button: ⋯ itself; session(): the
166
219
  // open session's id; hash: a session's id to its link (route.js sessionHash).
167
- // @return {update({bar, buttons}), close, isOpen, pop}
220
+ // @return {update({bar, buttons, folded}), close, isOpen, pop}
168
221
  export function createMoreSheet({ el, button, session = () => null, hash, doc = document, win = window }) {
169
222
  let bar = null;
170
223
  let buttons = null;
224
+ let folded = null;
171
225
  let shownInfo = null;
172
226
 
173
227
  function draw() {
174
- render(moreSheetTemplate({ bar, buttons, shownInfo, hash }), shell.pop);
228
+ render(moreSheetTemplate({ bar, buttons, folded, shownInfo, hash }), shell.pop);
175
229
  }
176
230
 
177
231
  const shell = createChipPopover({
@@ -199,10 +253,14 @@ export function createMoreSheet({ el, button, session = () => null, hash, doc =
199
253
  function update(next) {
200
254
  bar = next.bar;
201
255
  buttons = next.buttons;
202
- const { kind, label } = moreAttention(bar);
256
+ folded = next.folded || null;
257
+ const { kind, label } = moreAttention(bar, folded);
203
258
  if (kind) button.dataset.attention = kind;
204
259
  else delete button.dataset.attention;
205
- button.setAttribute("aria-label", label);
260
+ const count = moreCount(bar, buttons, folded);
261
+ const countEl = button.querySelector(".more-count");
262
+ if (countEl) countEl.textContent = count ? String(count) : "";
263
+ button.setAttribute("aria-label", count ? `${label} (${count} folded)` : label);
206
264
  button.title = label;
207
265
  // Another session, or none, closes it; else the open sheet follows.
208
266
  shell.refresh();
@@ -419,7 +419,9 @@ export function createStageView({
419
419
  if (!slot.firstChild) return;
420
420
  slot.scrollTop = slot.scrollHeight;
421
421
  const end = slot.offsetTop + slot.offsetHeight;
422
- if (scroller.scrollTop <= end - ANSWERED_LINE) return;
422
+ // Strictly below: offsetTop/offsetHeight are rounded, so a scroll exactly
423
+ // at the line's edge can leave it a fraction of a pixel above the view.
424
+ if (scroller.scrollTop < end - ANSWERED_LINE) return;
423
425
  scroller.scrollTop = Math.max(0, Math.min(slot.lastElementChild.offsetTop, end - ANSWERED_LINE) - ANSWERED_GAP);
424
426
  }
425
427
 
@@ -477,7 +477,7 @@ export function createStreamHandlers(deps) {
477
477
  },
478
478
  // The stream's cursor could not be replayed: render from scratch.
479
479
  reset: () => resync(),
480
- // Synthetic (snapshotEvents): a prompt merged into the turn in progress.
480
+ // Synthetic (a join's replay, TurnAccumulator.join_events): a prompt merged into the turn in progress.
481
481
  merged_input: (data) => {
482
482
  const origin = (data.origins || [])[0] || {};
483
483
  const own = isOwn(origin.client_id, clientId);
@@ -2,7 +2,6 @@
2
2
  // stay thin and the logic runs under `node --test`.
3
3
 
4
4
  import { authorBadge } from "./participant_names.js";
5
- import { ACTIVITY_FIELDS, EVENT_FIELDS, pickFields } from "./activity.js";
6
5
 
7
6
  // Read turn_summary.output; Bridge::ClientEvent omits result for clients.
8
7
  export function turnOutput(data) {
@@ -350,127 +349,6 @@ export function replaysDrawnTurn(event, turnRecords = []) {
350
349
  return turnRecords.some((record) => record.id === event.turn_id);
351
350
  }
352
351
 
353
- // REMOVE one release after chi web sends replay (see
354
- // ~/.claude/plans/arch-turn-records.md): chi web's show sends these events
355
- // itself (`replay`, TurnAccumulator.join_events); kept exported meanwhile, as
356
- // an old cached app.js imports it from this module.
357
- // A session view from the server (GET /api/sessions/:id on a live worker)
358
- // as the live events that would have drawn it: the turn in progress (its
359
- // parts in order), then the prompts queued behind it. app.js feeds these to
360
- // its stream handlers, so a join renders exactly like watching live.
361
- // `merged_input` is the one synthetic type: a prompt merged into the turn.
362
- // A `notice` part carries its event as it came (TurnNotice). The TUI replays
363
- // a turn the same way (TurnAccumulator.replay_events); spec/shared/
364
- // turn_snapshot.json pins both.
365
- export function snapshotEvents({ current_turn: turn = null, queued = [], queued_commands: commands = [], started_at = undefined } = {}) {
366
- const events = [];
367
- if (turn) {
368
- // The run's cut wait (TurnAccumulator, as turn_started carried it): the
369
- // composer's delivery line reads it.
370
- const cutAfter = turn.cut_after != null ? { cut_after: turn.cut_after } : {};
371
- const turnId = turn.turn_id ? { turn_id: turn.turn_id } : {};
372
- // A participant's turn names them (TurnAccumulator keeps author, author_name).
373
- const author = turn.author ? { author: turn.author, ...(turn.author_name ? { author_name: turn.author_name } : {}),
374
- ...(turn.participant_mode ? { participant_mode: turn.participant_mode } : {}) } : {};
375
- // Its wall time (TurnAccumulator keeps turn_started's at): the gap divider before it.
376
- const at = typeof turn.at === "string" ? { at: turn.at } : {};
377
- events.push(withImages({ type: "turn_started", prompt: turn.prompt, origin: turn.origin, continue: !!turn.continue, started_at, ...at, ...cutAfter, ...turnId, ...author }, turn.images));
378
- let textIteration = null; // a text bubble is open for this iteration
379
- const closeText = () => {
380
- if (textIteration !== null) events.push({ type: "generation_completed" });
381
- textIteration = null;
382
- };
383
- for (const part of turn.parts || []) {
384
- switch (part.kind) {
385
- // A generation the model is on: a join during a hold (no chunk yet)
386
- // shows its live step.
387
- case "generation":
388
- closeText();
389
- events.push({ type: "generation_started", iteration: part.iteration ?? null });
390
- break;
391
- // The chunks carry the part's iteration, so the turn block groups a
392
- // join like the live stream (turn_model.js).
393
- case "thinking":
394
- events.push({ type: "generation_chunk", text: "", thinking: part.text, iteration: part.iteration ?? null });
395
- break;
396
- case "text":
397
- if (textIteration !== null && textIteration !== part.iteration) closeText();
398
- textIteration = part.iteration;
399
- events.push({ type: "generation_chunk", text: part.text, thinking: "", iteration: part.iteration ?? null });
400
- break;
401
- case "tool": {
402
- closeText();
403
- const call = { iteration: part.iteration, call_index: part.call_index, tool: part.tool };
404
- if (part.label) call.label = part.label;
405
- // Its row fields, each in its place (activity.js ACTIVITY_FIELDS,
406
- // EVENT_FIELDS), as the live events carry them.
407
- const title = pickFields(part, ACTIVITY_FIELDS);
408
- const fields = pickFields(part, EVENT_FIELDS);
409
- // A running call's time so far (TurnAccumulator elapsed_ms): a join
410
- // clocks it from its start (activity.js markStart).
411
- const elapsed = part.status === "running" && part.elapsed_ms != null ? { elapsed_ms: part.elapsed_ms } : {};
412
- events.push({ type: "tool_call_started", ...call, params: part.params, ...title, ...fields, ...elapsed });
413
- if (part.status !== "running") {
414
- // The activity as the live event had it; action and duration_ms
415
- // only in snapshots from a worker that keeps them (the TUI's
416
- // row; the web times rows from the turn's tool records).
417
- const action = part.action ? { action: part.action } : {};
418
- const completed = {
419
- type: "tool_call_completed", ...call, output: part.output, output_truncated: !!part.output_truncated,
420
- activity: { ...action, tool: part.tool, status: part.status, params: part.params, ...title },
421
- };
422
- // A grep that found nothing: its row stays muted "no match".
423
- if (part.no_match) completed.activity.no_match = true;
424
- if (part.guardrail) completed.activity.guardrail = part.guardrail;
425
- if (part.duration_ms != null) completed.duration_ms = part.duration_ms;
426
- if (part.diff) completed.diff = part.diff;
427
- Object.assign(completed, fields);
428
- events.push(withImages(completed, part.images));
429
- }
430
- break;
431
- }
432
- case "input":
433
- closeText();
434
- events.push({ type: "merged_input", content: part.text, origins: part.origins || [] });
435
- break;
436
- case "reminder":
437
- closeText();
438
- events.push({ type: "reminder_injected", reminders: part.reminders || [] });
439
- break;
440
- // One of the turn's rows (a hook's notice, an empty-answer retry, a
441
- // question and its answer): the event itself, which the live
442
- // handler draws where it drew it live.
443
- case "notice":
444
- closeText();
445
- if (part.event?.type) events.push({ ...part.event });
446
- break;
447
- // A plugin's steer: a steer-only merge, as live.
448
- case "steer":
449
- closeText();
450
- events.push({ type: "pending_input_merged", count: 0, content: null, steers: [{ source: part.source, text: part.text }] });
451
- break;
452
- // A join draws the turn's cards from the snapshot's (CardStore), as
453
- // TurnAccumulator.replay_events leaves them out.
454
- case "card":
455
- break;
456
- default:
457
- break;
458
- }
459
- }
460
- }
461
- for (const entry of queued || []) {
462
- const delivery = entry.delivery ? { delivery: entry.delivery } : {};
463
- const author = entry.author ? { author: entry.author } : {};
464
- events.push(withImages({ type: "turn_enqueued", enqueued_id: entry.enqueued_id, client_id: entry.client_id, prompt: entry.prompt, ...delivery, ...author }, entry.images));
465
- }
466
- // Commands waiting for the turn's end: their bubbles, as live.
467
- for (const entry of commands || []) {
468
- const author = entry.author ? { author: entry.author } : {};
469
- events.push({ type: "command_queued", command_id: entry.command_id, client_id: entry.client_id, line: entry.line, waits: "turn_end", ...author });
470
- }
471
- return events;
472
- }
473
-
474
352
  // +object+ with `images` when there are any (the shapes stay as they were
475
353
  // for a turn without).
476
354
  export function withImages(object, images) {
@@ -1,7 +1,7 @@
1
1
  // The generations of one turn, as the turn block shows them: a list of gens
2
2
  // (one per model generation: its thinking, its narration, its tool rows),
3
3
  // the last one live until the next opens or the turn ends. Pure: fed by the
4
- // same events live and on a join (turn_events.js snapshotEvents), no DOM, so
4
+ // same events live and on a join (chi web's `replay`, TurnAccumulator.join_events), no DOM, so
5
5
  // `node --test` covers the grouping rules. turn_block.js draws it.
6
6
  //
7
7
  // Rules:
@@ -16,15 +16,30 @@ export function initialPicks(rows) {
16
16
  return (rows || []).map((r) => ({ pick: r.recommended != null ? String(r.recommended) : null, note: "" }));
17
17
  }
18
18
 
19
+ // What a row's id may not start with in the reply: a shell line's ! and a
20
+ // session command's / (and the spaces between them). The server's normaliser
21
+ // drops them already (InlineWidgets#row_id); this holds to it here too, as
22
+ // the reply leads the composer (audit r19, R4).
23
+ const COMMAND_LEAD = /^[!/\s]+/;
24
+
25
+ // A row's id as the page shows it and as the reply leads with: the raw id
26
+ // without its leading ! / and the spaces between them, or the row's number
27
+ // when nothing is left. One rule, so the chip's label and the filled reply
28
+ // never disagree.
29
+ function rowId(row, k) {
30
+ return String(row.id ?? "").replace(COMMAND_LEAD, "") || String(k + 1);
31
+ }
32
+
19
33
  // The reply the picks make: "id: option (note)" per picked row, " · " between
20
- // them; a row with no pick is left out.
34
+ // them; a row with no pick is left out. It never starts with ! or /: an id's
35
+ // leading ones are dropped, and an id of only those is its row's number.
21
36
  export function replyText(rows, picks) {
22
37
  return (rows || [])
23
38
  .map((r, k) => {
24
39
  const { pick, note } = picks[k] || {};
25
40
  if (!pick) return null;
26
41
  const said = String(note ?? "").replace(/\s+/g, " ").trim();
27
- return `${r.id ?? k + 1}: ${pick}${said ? ` (${said})` : ""}`;
42
+ return `${rowId(r, k)}: ${pick}${said ? ` (${said})` : ""}`;
28
43
  })
29
44
  .filter(Boolean)
30
45
  .join(" · ");
@@ -67,7 +82,7 @@ export function drawPicks(picks, { fill, doc = document }) {
67
82
 
68
83
  const list = el(doc, "div", "wp-list");
69
84
  const chips = rows.map((r, k) => {
70
- const id = String(r.id ?? k + 1);
85
+ const id = rowId(r, k);
71
86
  const row = el(doc, "div", "wp-row");
72
87
  const text = el(doc, "div", "wp-text");
73
88
  text.append(el(doc, "div", null, r.text || ""));
@@ -142,7 +142,8 @@ module Samagotchi
142
142
 
143
143
  @manager.resume_session(id, state_dir: @state_dir)
144
144
  # card: a card's action; its command events say so (no echo).
145
- request = ->(client) { client.post_command(line: line, client_id: body["client_id"], card: body["card"] == true) }
145
+ client_id = owner_sender(body)
146
+ request = ->(client) { client.post_command(line: line, client_id: client_id, card: body["card"] == true) }
146
147
  relay(id, live_bridge_client(id), request, what: "the command was not run", cant: "run commands") do |reply|
147
148
  case reply.status
148
149
  when 202
@@ -162,6 +163,15 @@ module Samagotchi
162
163
  owned_by_tui(e)
163
164
  end
164
165
 
166
+ # Who sent the owner's turn or command: the body's client_id (the page
167
+ # names its tab, chi --remote names chi send), or WEB_UNNAMED for an
168
+ # owner's script that names none: named here, never a nil sender
169
+ # (deliver_turn refuses it; CommandIntake would read it as a person's).
170
+ def owner_sender(body)
171
+ client_id = (body["client_id"] || body[:client_id]).to_s
172
+ client_id.empty? ? ClientId::WEB_UNNAMED : client_id
173
+ end
174
+
165
175
  # 501 not_supported for a builtin +name+ ("/title") the worker lacks.
166
176
  def older_worker_command(id, name)
167
177
  words = BridgeClient.stale_worker_message(id, cant: "run #{name}")
@@ -178,7 +188,7 @@ module Samagotchi
178
188
  return handle_participant_turn(req, id, body) unless principal(req).owner?
179
189
 
180
190
  prompt = body["prompt"] || body[:prompt]
181
- client_id = body["client_id"] || body[:client_id]
191
+ client_id = owner_sender(body)
182
192
  if prompt.to_s.strip.empty?
183
193
  return error_response(400, "missing_fields", "prompt is required")
184
194
  end
@@ -197,10 +207,13 @@ module Samagotchi
197
207
  # no_interrupt: an attached TUI's --no-interrupt (chi --remote --attach).
198
208
  # author: the principal's (nil for the owner), never the body's.
199
209
  # anchors: a Verify turn's claim, a Revise turn's draft (TurnAnchors).
210
+ # follow: a chi --remote send to the head its resolve?head=1 named
211
+ # (the page never sends it: a person on that page means that session).
200
212
  result = SessionManager.deliver_turn(id, prompt: prompt.to_s, client_id: client_id, images: images,
201
213
  delivery: delivery, no_interrupt: body["no_interrupt"] == true,
202
214
  author: principal(req).author,
203
215
  anchors: TurnAnchors.from(body),
216
+ follow: body["follow"] == true,
204
217
  state_dir: @state_dir, manager: @manager,
205
218
  bridge: -> { live_bridge_client(id) })
206
219
  case result.status
@@ -112,8 +112,10 @@ module Samagotchi
112
112
  # until that turn is saved.
113
113
  preview = idle ? body["preview"].to_s.strip : ""
114
114
  folder[:preview] = preview unless preview.empty?
115
- setup = SessionSetup.new(llm_context: llm_context, thinking: thinking, settings: settings, toolkit: toolkit,
116
- parent_answers: parent_answers)
115
+ # A create takes no memories, mutes or prompt files (paths of this
116
+ # machine's terminal), nor reasoning_history.
117
+ setup = SessionSetup.from_request(llm_context: llm_context, thinking: thinking, settings: settings, toolkit: toolkit,
118
+ parent_answers: parent_answers)
117
119
  folder[:setup] = setup unless setup.empty?
118
120
  begin
119
121
  session = if review
@@ -11,6 +11,7 @@ require_relative "../installed_gem"
11
11
  require_relative "../installed_versions"
12
12
  require_relative "../log"
13
13
  require_relative "../paths"
14
+ require_relative "../state_format"
14
15
  require_relative "../version"
15
16
  require_relative "auto_update_record"
16
17
 
@@ -29,6 +30,20 @@ module Samagotchi
29
30
  FIRST_CHECK = 30
30
31
  # A failed check (offline at start) tries again this soon, not a whole check_hours later.
31
32
  RETRY = 3600
33
+ # update_check.json's format. A file with no version is one from
34
+ # before it (the same members); a newer chi's keeps its version and
35
+ # the keys this one doesn't know through a write.
36
+ STATE_FORMAT_VERSION = 1
37
+ STATE_FORMAT = StateFormat.new(
38
+ version: STATE_FORMAT_VERSION, members: [],
39
+ document_members: [
40
+ StateFormat.added(:checked_at, in_version: 1, default: nil),
41
+ StateFormat.added(:available, in_version: 1, default: nil),
42
+ StateFormat.added(:notified, in_version: 1, default: []),
43
+ StateFormat.added(:auto, in_version: 1, default: nil),
44
+ StateFormat.added(:auto_failed, in_version: 1, default: [])
45
+ ]
46
+ )
32
47
 
33
48
  # @param enabled [Boolean] update.notify: the answer goes to the page
34
49
  # @param auto [Boolean] update.auto is install: check even when +enabled+ is not
@@ -205,18 +220,21 @@ module Samagotchi
205
220
  def blocked_reason = self.class.blocked_reason(gem_spec: @gem_spec, bundler: @bundler, gem_dir: @gem_dir)
206
221
 
207
222
  def load_state
223
+ @document = STATE_FORMAT.read({}, collection: nil)
208
224
  return empty_state unless File.file?(@state_file)
209
225
 
210
- data = JSON.parse(File.read(@state_file))
226
+ @document = STATE_FORMAT.read(JSON.parse(File.read(@state_file)), collection: nil)
227
+ data = @document.attributes
211
228
  {
212
- checked_at: data["checked_at"],
213
- available: data["available"],
214
- notified: strings(data["notified"]),
215
- auto: AutoUpdateRecord.from_h(data["auto"]),
216
- auto_failed: strings(data["auto_failed"])
229
+ checked_at: data[:checked_at],
230
+ available: data[:available],
231
+ notified: strings(data[:notified]),
232
+ auto: AutoUpdateRecord.from_h(data[:auto]),
233
+ auto_failed: strings(data[:auto_failed])
217
234
  }
218
- rescue JSON::ParserError, SystemCallError => e
235
+ rescue JSON::ParserError, SystemCallError, StateFormat::InvalidDocument => e
219
236
  Log.warn(:web, "update_check_failed", error: e.class.name, msg: e.message)
237
+ @document = STATE_FORMAT.read({}, collection: nil)
220
238
  empty_state
221
239
  end
222
240
 
@@ -226,7 +244,8 @@ module Samagotchi
226
244
 
227
245
  def persist(state)
228
246
  FileUtils.mkdir_p(File.dirname(@state_file))
229
- AtomicFile.write(@state_file, JSON.generate(state.merge(auto: state[:auto]&.to_store)), perm: 0o600)
247
+ stored = @document.with(attributes: state.merge(auto: state[:auto]&.to_store))
248
+ AtomicFile.write(@state_file, JSON.generate(STATE_FORMAT.write(stored, collection: nil, updated_at: nil)), perm: 0o600)
230
249
  @state = state
231
250
  end
232
251
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: samagotchi
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.164.0
4
+ version: 0.165.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dmitry Dedov
@@ -668,6 +668,7 @@ files:
668
668
  - lib/samagotchi/session_access/web_bridge_client.rb
669
669
  - lib/samagotchi/session_archive_command.rb
670
670
  - lib/samagotchi/session_chain.rb
671
+ - lib/samagotchi/session_chain/links.rb
671
672
  - lib/samagotchi/session_commands.rb
672
673
  - lib/samagotchi/session_config.rb
673
674
  - lib/samagotchi/session_continue.rb
@@ -911,6 +912,7 @@ files:
911
912
  - lib/samagotchi/web/public/app.js
912
913
  - lib/samagotchi/web/public/apple-touch-icon.png
913
914
  - lib/samagotchi/web/public/auth_lost.js
915
+ - lib/samagotchi/web/public/bar_fold.js
914
916
  - lib/samagotchi/web/public/block_frame.js
915
917
  - lib/samagotchi/web/public/block_host.js
916
918
  - lib/samagotchi/web/public/block_open.js