samagotchi 0.164.0 → 0.166.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 (100) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +88 -1
  3. data/docs/architecture.md +7 -5
  4. data/docs/cli.md +23 -12
  5. data/docs/configuration.md +8 -2
  6. data/docs/guardrails.md +19 -18
  7. data/docs/internals/block-renderers.md +1 -1
  8. data/docs/internals/bridge.md +10 -3
  9. data/docs/internals/bundles.md +4 -2
  10. data/docs/internals/inline-widgets.md +8 -1
  11. data/docs/internals/remote-sessions.md +1 -1
  12. data/docs/internals/web-frontend.md +73 -13
  13. data/docs/memory.md +12 -7
  14. data/docs/plugins.md +6 -4
  15. data/docs/releasing.md +17 -4
  16. data/docs/scheduling.md +25 -3
  17. data/docs/sessions.md +12 -10
  18. data/docs/testing.md +37 -4
  19. data/lib/samagotchi/block_renderers.rb +3 -6
  20. data/lib/samagotchi/bridge/card_store.rb +2 -1
  21. data/lib/samagotchi/bridge/turn_accumulator.rb +7 -8
  22. data/lib/samagotchi/bridge.rb +45 -3
  23. data/lib/samagotchi/bundle_command/installed_check.rb +2 -1
  24. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  25. data/lib/samagotchi/chi_home.rb +44 -2
  26. data/lib/samagotchi/client_id.rb +34 -3
  27. data/lib/samagotchi/compat.rb +34 -0
  28. data/lib/samagotchi/context_command.rb +3 -0
  29. data/lib/samagotchi/context_providers.rb +5 -6
  30. data/lib/samagotchi/context_sources.rb +2 -2
  31. data/lib/samagotchi/continue_intent.rb +50 -5
  32. data/lib/samagotchi/events.rb +4 -4
  33. data/lib/samagotchi/extension_load.rb +2 -1
  34. data/lib/samagotchi/guardrails/approvals.rb +36 -9
  35. data/lib/samagotchi/guardrails/child_boundary.rb +7 -27
  36. data/lib/samagotchi/guardrails/rules.rb +11 -9
  37. data/lib/samagotchi/guardrails/targets.rb +3 -4
  38. data/lib/samagotchi/inline_widgets.rb +16 -1
  39. data/lib/samagotchi/memory_bundle/provenance.rb +46 -4
  40. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  41. data/lib/samagotchi/memory_command.rb +3 -0
  42. data/lib/samagotchi/memory_orphans.rb +4 -7
  43. data/lib/samagotchi/memory_paths.rb +64 -7
  44. data/lib/samagotchi/memory_usage.rb +1 -1
  45. data/lib/samagotchi/plugin/sessions.rb +8 -3
  46. data/lib/samagotchi/project_command.rb +4 -1
  47. data/lib/samagotchi/project_id_clash.rb +37 -26
  48. data/lib/samagotchi/project_init.rb +24 -7
  49. data/lib/samagotchi/reply_wait/poll.rb +4 -14
  50. data/lib/samagotchi/reply_wait.rb +0 -23
  51. data/lib/samagotchi/run_options.rb +1 -1
  52. data/lib/samagotchi/schedules.rb +124 -106
  53. data/lib/samagotchi/send_command.rb +71 -18
  54. data/lib/samagotchi/session.rb +3 -2
  55. data/lib/samagotchi/session_access/local.rb +19 -2
  56. data/lib/samagotchi/session_access/remote.rb +13 -17
  57. data/lib/samagotchi/session_chain/links.rb +109 -0
  58. data/lib/samagotchi/session_chain.rb +7 -19
  59. data/lib/samagotchi/session_continue.rb +138 -54
  60. data/lib/samagotchi/session_inbox.rb +1 -1
  61. data/lib/samagotchi/session_inbox_delivery.rb +57 -38
  62. data/lib/samagotchi/session_manager/delivery.rb +104 -18
  63. data/lib/samagotchi/session_manager/removal.rb +13 -7
  64. data/lib/samagotchi/session_manager.rb +1 -0
  65. data/lib/samagotchi/session_retention.rb +20 -10
  66. data/lib/samagotchi/session_setup.rb +31 -1
  67. data/lib/samagotchi/state_format.rb +12 -8
  68. data/lib/samagotchi/terminal_ui/attach_launcher.rb +6 -7
  69. data/lib/samagotchi/terminal_ui.rb +20 -9
  70. data/lib/samagotchi/tools/delegate.rb +2 -3
  71. data/lib/samagotchi/verify_fresh.rb +4 -1
  72. data/lib/samagotchi/version.rb +1 -1
  73. data/lib/samagotchi/web/public/activity.js +2 -2
  74. data/lib/samagotchi/web/public/app.js +28 -21
  75. data/lib/samagotchi/web/public/auth_lost.js +3 -1
  76. data/lib/samagotchi/web/public/bar_fold.js +293 -0
  77. data/lib/samagotchi/web/public/card.js +1 -1
  78. data/lib/samagotchi/web/public/chip_popover.js +5 -1
  79. data/lib/samagotchi/web/public/composer_mode.js +5 -7
  80. data/lib/samagotchi/web/public/delivery_line.js +19 -4
  81. data/lib/samagotchi/web/public/index.html +242 -94
  82. data/lib/samagotchi/web/public/info_bar.js +28 -16
  83. data/lib/samagotchi/web/public/info_bar_model.js +76 -2
  84. data/lib/samagotchi/web/public/live_timing.js +3 -0
  85. data/lib/samagotchi/web/public/more_sheet.js +98 -40
  86. data/lib/samagotchi/web/public/resync_reach.js +59 -0
  87. data/lib/samagotchi/web/public/session_fields.js +1 -0
  88. data/lib/samagotchi/web/public/session_state.js +5 -0
  89. data/lib/samagotchi/web/public/stage_frame.js +4 -2
  90. data/lib/samagotchi/web/public/stage_stall.js +134 -0
  91. data/lib/samagotchi/web/public/stage_view.js +78 -7
  92. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  93. data/lib/samagotchi/web/public/turn_events.js +0 -122
  94. data/lib/samagotchi/web/public/turn_model.js +1 -1
  95. data/lib/samagotchi/web/public/widget_picks.js +18 -3
  96. data/lib/samagotchi/web/session_control.rb +15 -2
  97. data/lib/samagotchi/web/session_create.rb +4 -2
  98. data/lib/samagotchi/web/token.rb +2 -2
  99. data/lib/samagotchi/web/update_check.rb +27 -8
  100. metadata +5 -1
@@ -0,0 +1,134 @@
1
+ // The stage's quiet signal (stage_view.js): a running turn that has sent no
2
+ // event for a while says so, since the dot blinks the same whether the
3
+ // model works or the line went dead (the Bridge's idle `: ping` never
4
+ // reaches EventSource's JS, and a running tool sends nothing between its
5
+ // start and end). The code says "stall" (stallOf, .ts-stall, data-stall);
6
+ // the user reads "quiet" (liveSlots' `quiet` and stage_model's QUIET_MS are
7
+ // other things). The rule is pure (stallOf, stallState); createStageStall
8
+ // draws it: a right-aligned span in the now row, its short text in the
9
+ // status row for a collapsed or plain stage, and the running call's clock.
10
+ // Its own module: new exports go in new modules (web-frontend.md).
11
+ import { clockText, genAge } from "./delivery_line.js";
12
+ import { node } from "./stage_slots.js";
13
+
14
+ // The levels' thresholds (ms) per kind: A, streamed or between steps; B,
15
+ // no first token yet in the step (a long prompt read, hidden reasoning).
16
+ export const STALL_MS = { A: [30000, 90000], B: [45000, 180000] };
17
+ // The stream down this long reads "reconnecting…" (a resync's own blink
18
+ // between workerGone and the new stream stays unsaid).
19
+ export const NET_MS = 1000;
20
+ // After the page shows again (visibilitychange): a background tab's
21
+ // stream may still be catching up.
22
+ export const GRACE_MS = 5000;
23
+ // The running call's clock shows from this far into it.
24
+ export const TOOL_CLOCK_MS = 10000;
25
+
26
+ const NONE = Object.freeze({ level: 0, long: "", short: "" });
27
+ const NET = Object.freeze({ level: "net", long: "reconnecting… · events paused", short: "reconnecting…" });
28
+
29
+ // The signal for a running turn: level 0 (nothing to say), 1, 2 or "net",
30
+ // and its texts (+long+ the stage's, +short+ a phone's and the status
31
+ // row's). A stream not live wins (no count: the events, not the model, are
32
+ // what paused); an explained silence says nothing: a running tool (its
33
+ // clock speaks), a blocking card, a timing note (a retry, plugins' setup),
34
+ // the end, the grace after a return.
35
+ export function stallOf({ kind = "A", silentMs = 0, toolRunning = false, blocked = false, note = "", streamLive = true, ended = false, graceUntil = 0, nowMs = 0 } = {}) {
36
+ if (ended) return NONE;
37
+ if (!streamLive) return NET;
38
+ if (toolRunning || blocked || note || nowMs < graceUntil) return NONE;
39
+ const b = kind === "B";
40
+ const [l1, l2] = STALL_MS[b ? "B" : "A"];
41
+ if (!(silentMs >= l1)) return NONE;
42
+ const clock = clockText(silentMs / 1000);
43
+ const short = b ? `thinking quietly ${clock}` : `quiet ${clock}`;
44
+ return { level: silentMs >= l2 ? 2 : 1, long: `${short} · ${b ? "no tokens yet" : "no new events"}`, short };
45
+ }
46
+
47
+ // B while the step has had no token (no gen yet, or an open one with no
48
+ // text, thinking or call); else A (a closed step: between steps).
49
+ export function stallKind(gen) {
50
+ if (!gen) return "B";
51
+ return !gen.closed && !gen.text && !gen.thinking && !gen.tools?.length ? "B" : "A";
52
+ }
53
+
54
+ // The running call's clock ("0:12") from TOOL_CLOCK_MS on; "" before, or
55
+ // without a start (a replayed call the page didn't time).
56
+ export function toolClockText(startedAt, nowMs) {
57
+ if (startedAt == null) return "";
58
+ const ms = nowMs - startedAt;
59
+ return ms >= TOOL_CLOCK_MS ? clockText(ms / 1000) : "";
60
+ }
61
+
62
+ // What a tick shows for +turn+ (turn_model.js's): the stall (stallOf) and
63
+ // the running call's clock (+toolClock+). +lastEventAt+: the page's clock
64
+ // at the turn's last event; +streamDownMs+: how long the stream hasn't been
65
+ // live (null: it is); +serverGen+: the snapshot's generation (a joiner's
66
+ // step clock, delivery_line.js genAge): before the first token a joiner
67
+ // counts from it, not from its own replay.
68
+ export function stallState({ turn, lastEventAt, nowMs, blocked = false, note = "", streamDownMs = null, ended = false, graceUntil = 0, serverGen = null }) {
69
+ const gens = turn?.gens || [];
70
+ const gen = gens[gens.length - 1];
71
+ const running = gens.flatMap((g) => g.tools || []).reverse().find((row) => row.status === "running") || null;
72
+ const kind = stallKind(gen);
73
+ let silentMs = nowMs - lastEventAt;
74
+ if (kind === "B") {
75
+ const age = genAge(gen, serverGen, nowMs);
76
+ if (age !== null) silentMs = Math.max(silentMs, age * 1000);
77
+ }
78
+ const streamLive = streamDownMs == null || streamDownMs < NET_MS;
79
+ const stall = stallOf({ kind, silentMs, toolRunning: !!running, blocked, note, streamLive, ended, graceUntil, nowMs });
80
+ return { ...stall, toolClock: running && !ended ? toolClockText(running.startedAt, nowMs) : "" };
81
+ }
82
+
83
+ // The drawer. +stage+: the stage's root (.stalled, data-stall: the hooks);
84
+ // +nowEl+: the now row (stage_slots.js drawNow rebuilds it: each draw puts
85
+ // its spans back when they were taken out); +timingSlot+: the status row's
86
+ // timing line, the head goes after it. A draw writes only when a text
87
+ // changes, so the 1 Hz tick under the threshold writes nothing.
88
+ export function createStageStall({ stage, nowEl, timingSlot }) {
89
+ const stallEl = node("span", "ts-stall");
90
+ const longEl = node("span", "long", stallEl);
91
+ const shortEl = node("span", "short", stallEl);
92
+ const clockEl = node("span", "ts-tool-clock");
93
+ const head = node("span", "ts-stall-head");
94
+ timingSlot.after(head);
95
+ let shown = { key: null, clock: null, level: 0 };
96
+
97
+ function drawLevel({ level, long, short }) {
98
+ const key = `${level}|${long}`;
99
+ if (shown.key === key) return;
100
+ shown.key = key;
101
+ shown.level = level;
102
+ stage.classList.toggle("stalled", !!level);
103
+ if (level) {
104
+ stage.dataset.stall = String(level);
105
+ nowEl.dataset.stall = String(level);
106
+ } else {
107
+ delete stage.dataset.stall;
108
+ delete nowEl.dataset.stall;
109
+ }
110
+ longEl.textContent = long;
111
+ shortEl.textContent = short;
112
+ head.textContent = short;
113
+ }
114
+
115
+ function draw(state) {
116
+ drawLevel(state);
117
+ if (state.level && stallEl.parentNode !== nowEl) nowEl.appendChild(stallEl);
118
+ else if (!state.level && stallEl.parentNode) stallEl.remove();
119
+ const clock = state.toolClock || "";
120
+ if (shown.clock !== clock) {
121
+ shown.clock = clock;
122
+ clockEl.textContent = clock;
123
+ }
124
+ if (clock && clockEl.parentNode !== nowEl) nowEl.insertBefore(clockEl, nowEl.querySelector(":scope > .task-stop"));
125
+ else if (!clock && clockEl.parentNode) clockEl.remove();
126
+ }
127
+
128
+ function reset() {
129
+ draw({ ...NONE, toolClock: "" });
130
+ shown = { key: null, clock: null, level: 0 };
131
+ }
132
+
133
+ return { draw, reset, level: () => shown.level };
134
+ }
@@ -20,6 +20,7 @@ import { chipLabelText, flashOf, handOffDue, handOffOrder, headlineOf, isPlain,
20
20
  import { createStageSlots, node } from "./stage_slots.js";
21
21
  import { createStageFrame, reducedMotion } from "./stage_frame.js";
22
22
  import { createInUseWatch } from "./stage_watch.js";
23
+ import { createStageStall, GRACE_MS, stallState } from "./stage_stall.js";
23
24
  import { formatDuration } from "./timing.js";
24
25
  import { easeScrollTo } from "./scroll.js";
25
26
  import { readStored, writeStored } from "./storage.js";
@@ -69,9 +70,13 @@ function readCollapsed() {
69
70
  // status row's Stop turn (a promise of the cancel request; the button is
70
71
  // disabled until it settles); null: no Stop turn. +onHandedOff+({pieces,
71
72
  // immediate}): a turn's pieces reached the history (reload_check.js).
73
+ // The quiet signal's inputs (stage_stall.js): +clock+() the page's time,
74
+ // +streamLive+() the session's stream is open, +timingNote+() what the turn
75
+ // waits on (live_timing.js note), +serverGen+() a joiner's generation.
72
76
  export function createStageView({
73
77
  historyEl, isNearBottom: historyNearBottom, sawText, sessionId, dockEl, centerEl, taskStop = null,
74
78
  renderMarkdown, linkRefs, workingSet = null, onCancel = null, onHandedOff = null,
79
+ clock = () => Date.now(), streamLive = () => true, timingNote = () => "", serverGen = () => null,
75
80
  }) {
76
81
  // The dock becomes a clear column: the stage's card, then the composer's
77
82
  // (its rows moved into .dock-card, which wears the glass and the focus ring).
@@ -168,6 +173,8 @@ export function createStageView({
168
173
  // Below the turn's card: the lines queued for after it (placeKind
169
174
  // "queued"), each to run as a turn of its own; they hand off last.
170
175
  const queuedSlot = node("div", "ts-queued", stage);
176
+ // The quiet signal: its span in the now row, its head after the timing line.
177
+ const stall = createStageStall({ stage, nowEl: now, timingSlot });
171
178
  const slotsView = createStageSlots({
172
179
  headline, asking, now, trail, ticks, taskStop, renderMarkdown, linkRefs,
173
180
  gens: () => view.current().turn?.gens,
@@ -212,6 +219,11 @@ export function createStageView({
212
219
  // grows to it), and whether the room's card is in the stage's view.
213
220
  let arrived = null;
214
221
  let cardInSight = true;
222
+ // The quiet signal's clocks: the turn's last event, since when the stream
223
+ // isn't live (null: it is), the grace after the page shows again.
224
+ let lastEventAt = 0;
225
+ let downSince = null;
226
+ let graceUntil = 0;
215
227
 
216
228
  const view = createTurnBlock({
217
229
  historyEl,
@@ -378,6 +390,7 @@ export function createStageView({
378
390
  raiseForApproval(blocked);
379
391
  drawPill();
380
392
  slotsView.drawNow(slots.tool, slots.quiet);
393
+ drawStall(clock(), blocked);
381
394
  slotsView.drawTrail(slots.trail, flash);
382
395
  slotsView.drawTicks(slots.ticks);
383
396
  if (rail) {
@@ -419,7 +432,9 @@ export function createStageView({
419
432
  if (!slot.firstChild) return;
420
433
  slot.scrollTop = slot.scrollHeight;
421
434
  const end = slot.offsetTop + slot.offsetHeight;
422
- if (scroller.scrollTop <= end - ANSWERED_LINE) return;
435
+ // Strictly below: offsetTop/offsetHeight are rounded, so a scroll exactly
436
+ // at the line's edge can leave it a fraction of a pixel above the view.
437
+ if (scroller.scrollTop < end - ANSWERED_LINE) return;
423
438
  scroller.scrollTop = Math.max(0, Math.min(slot.lastElementChild.offsetTop, end - ANSWERED_LINE) - ANSWERED_GAP);
424
439
  }
425
440
 
@@ -444,6 +459,31 @@ export function createStageView({
444
459
  frame.forgetContent();
445
460
  }
446
461
 
462
+ // ── the quiet signal (stage_stall.js) ─────────────────────────────────────
463
+
464
+ // At +nowMs+ (the tick's, a refresh's): what the turn's silence says.
465
+ function drawStall(nowMs, blocked = pendingCard()) {
466
+ const { turn } = view.current();
467
+ if (!holding || !turn) return;
468
+ if (streamLive()) downSince = null;
469
+ else downSince ??= nowMs;
470
+ stall.draw(stallState({
471
+ turn, lastEventAt, nowMs, blocked, note: timingNote() || "", ended: !!endKind, graceUntil, serverGen: serverGen(),
472
+ streamDownMs: downSince === null ? null : nowMs - downSince,
473
+ }));
474
+ }
475
+
476
+ // A turn event arrived (a replay's too): the silence starts over, and a
477
+ // stall shown clears at once.
478
+ function alive() {
479
+ lastEventAt = clock();
480
+ if (stall.level()) drawStall(lastEventAt);
481
+ }
482
+
483
+ document.addEventListener("visibilitychange", () => {
484
+ if (!document.hidden) graceUntil = clock() + GRACE_MS;
485
+ });
486
+
447
487
  // One line in the trail for FLASH_MS, ahead of the calls (a newer flash
448
488
  // takes its place).
449
489
  function flashTrail(what) {
@@ -629,6 +669,8 @@ export function createStageView({
629
669
  cancel.hidden = true;
630
670
  chipLabel.textContent = "";
631
671
  slotsView.reset();
672
+ stall.reset();
673
+ downSince = null;
632
674
  rail?.reset();
633
675
  promptSlot.classList.remove("full");
634
676
  thinkingLine = null;
@@ -769,6 +811,7 @@ export function createStageView({
769
811
  settled = true;
770
812
  startedAt = Date.parse(data?.started_at) || Date.now();
771
813
  emptySlots();
814
+ lastEventAt = clock();
772
815
  // The turn's prompt bubble (app.js found or drew it) sits in the prompt
773
816
  // line until the hand-off takes it back first.
774
817
  if (data?.promptBubble) promptSlot.appendChild(data.promptBubble);
@@ -782,14 +825,30 @@ export function createStageView({
782
825
  refresh();
783
826
  },
784
827
  generationStarted(data, now = null) {
828
+ alive();
785
829
  releaseHeldWait();
786
830
  view.generationStarted(data, now);
787
831
  },
788
- chunk: (data) => view.chunk(data),
789
- generationRestarted: (data) => view.generationRestarted(data),
790
- generationCompleted: () => view.generationCompleted(),
791
- toolStarted: (data) => view.toolStarted(data),
792
- toolCompleted: (data) => view.toolCompleted(data),
832
+ chunk(data) {
833
+ alive();
834
+ return view.chunk(data);
835
+ },
836
+ generationRestarted(data) {
837
+ alive();
838
+ return view.generationRestarted(data);
839
+ },
840
+ generationCompleted() {
841
+ alive();
842
+ return view.generationCompleted();
843
+ },
844
+ toolStarted(data) {
845
+ alive();
846
+ return view.toolStarted(data);
847
+ },
848
+ toolCompleted(data) {
849
+ alive();
850
+ return view.toolCompleted(data);
851
+ },
793
852
  turnEnded(args) {
794
853
  const kept = view.turnEnded(args) || [];
795
854
  if (!holding) return kept;
@@ -814,18 +873,23 @@ export function createStageView({
814
873
  // A hook's notice and a plugin's nudge go into their step inside the
815
874
  // closed cloud; they flash in the trail meanwhile (flashOf).
816
875
  notice(data) {
876
+ alive();
817
877
  const placed = view.notice(data);
818
878
  if (placed) flashTrail(flashOf("notice", data));
819
879
  return placed;
820
880
  },
821
881
  steer(data) {
882
+ alive();
822
883
  const placed = view.steer(data);
823
884
  if (placed) flashTrail(flashOf("steer", data));
824
885
  return placed;
825
886
  },
826
887
  // A warn card (a plugin's warning) stays in sight: false puts it in the
827
888
  // extras (place), not in its step inside the closed cloud.
828
- card: (el) => !el.classList.contains("warn") && view.card(el),
889
+ card(el) {
890
+ alive();
891
+ return !el.classList.contains("warn") && view.card(el);
892
+ },
829
893
  flush: () => view.flush(),
830
894
  answerReady() {
831
895
  settled = true;
@@ -835,6 +899,7 @@ export function createStageView({
835
899
  askingText: () => view.askingText(),
836
900
  // The asking slot pairs them on its next draw.
837
901
  questionRefs(refs) {
902
+ alive();
838
903
  view.questionRefs(refs);
839
904
  scheduleRefresh();
840
905
  },
@@ -858,6 +923,7 @@ export function createStageView({
858
923
  if (folding) finishFold();
859
924
  const where = placeFor({ live: holding, handingOff: false, kind: placeKind(el) });
860
925
  if (where === "history") return false;
926
+ alive();
861
927
  if (where === "queued") {
862
928
  ensureQueuedSlot();
863
929
  queuedSlot.appendChild(el);
@@ -915,6 +981,11 @@ export function createStageView({
915
981
  cancel.hidden = !onCancel;
916
982
  show();
917
983
  },
984
+ // The page's clock ticks (app.js, the live timing's 200 ms / 1 s): the
985
+ // quiet signal and the running call's clock.
986
+ tick(nowMs = clock()) {
987
+ drawStall(nowMs);
988
+ },
918
989
  handOff,
919
990
  root: stage,
920
991
  scrollEl: scroller,
@@ -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
@@ -10,10 +10,10 @@ require_relative "../redacted_inspect"
10
10
 
11
11
  module Samagotchi
12
12
  module Web
13
- # The access token of `chi web` on the LAN (web.host: lan): anyone
13
+ # The one access token of `chi web` (LAN link, --tunnel, public_url/proxy): anyone
14
14
  # who has it can run commands as you, so it lives in one file only you
15
15
  # can read, $XDG_STATE_HOME/samagotchi/web-token (0600). It is made on
16
- # the first LAN start and kept, so a phone's bookmark survives
16
+ # the first start that needs it and kept, so a phone's bookmark survives
17
17
  # restarts; `chi web --new-token` replaces it. A loopback-only chi web
18
18
  # never reads it. The owner's cookie for this machine's 127.0.0.1
19
19
  # holds #loopback_cookie, never the token: a server on any other local