samagotchi 0.174.0 → 0.176.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +38 -1
  3. data/bin/chi +1 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/cli.md +3 -0
  6. data/docs/configuration.md +1 -0
  7. data/docs/internals/bridge.md +10 -3
  8. data/docs/internals/engine.md +2 -2
  9. data/docs/internals/participants.md +11 -5
  10. data/docs/internals/web-frontend.md +44 -11
  11. data/docs/sessions.md +2 -2
  12. data/docs/testing.md +25 -3
  13. data/lib/samagotchi/answer_text.rb +4 -2
  14. data/lib/samagotchi/bridge.rb +11 -4
  15. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  16. data/lib/samagotchi/config.rb +3 -0
  17. data/lib/samagotchi/llm/stray_tool_call.rb +7 -4
  18. data/lib/samagotchi/llm_context_stale.rb +2 -1
  19. data/lib/samagotchi/message_parts.rb +5 -2
  20. data/lib/samagotchi/model_markup.rb +22 -0
  21. data/lib/samagotchi/model_profile.rb +8 -7
  22. data/lib/samagotchi/participant_uploads.rb +14 -1
  23. data/lib/samagotchi/prompt_literal_guard.rb +7 -6
  24. data/lib/samagotchi/task_transcript.rb +10 -5
  25. data/lib/samagotchi/tool_call_parser.rb +6 -5
  26. data/lib/samagotchi/turn_note.rb +2 -1
  27. data/lib/samagotchi/version.rb +1 -1
  28. data/lib/samagotchi/web/app.rb +15 -2
  29. data/lib/samagotchi/web/participant_images.rb +16 -12
  30. data/lib/samagotchi/web/participant_show.rb +1 -0
  31. data/lib/samagotchi/web/participant_view.rb +31 -3
  32. data/lib/samagotchi/web/public/app.js +18 -4
  33. data/lib/samagotchi/web/public/composer_fold.js +3 -1
  34. data/lib/samagotchi/web/public/composer_grip.js +18 -10
  35. data/lib/samagotchi/web/public/composer_mount.js +17 -6
  36. data/lib/samagotchi/web/public/reload_check.js +0 -3
  37. data/lib/samagotchi/web/public/restore.js +3 -1
  38. data/lib/samagotchi/web/public/session_prefs.js +89 -0
  39. data/lib/samagotchi/web/public/session_sync.js +3 -0
  40. data/lib/samagotchi/web/public/session_view.js +41 -3
  41. data/lib/samagotchi/web/public/stage_asking.js +21 -18
  42. data/lib/samagotchi/web/public/stage_cloud.js +3 -2
  43. data/lib/samagotchi/web/public/stage_missing.js +148 -0
  44. data/lib/samagotchi/web/public/stage_model.js +2 -1
  45. data/lib/samagotchi/web/public/stage_view.js +14 -4
  46. data/lib/samagotchi/web/public/stage_view_memory.js +76 -0
  47. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  48. data/lib/samagotchi/web/public/turn_events.js +1 -1
  49. data/lib/samagotchi/web/public/working_set_rail.js +22 -7
  50. data/lib/samagotchi/web/public/ws_reader.js +2 -0
  51. data/lib/samagotchi/web/server.rb +6 -2
  52. data/lib/samagotchi/web/session_show.rb +42 -4
  53. data/lib/samagotchi/worker/child_side.rb +123 -0
  54. data/lib/samagotchi/worker/command_queue.rb +346 -0
  55. data/lib/samagotchi/worker/leave.rb +286 -0
  56. data/lib/samagotchi/worker/scratch.rb +99 -0
  57. data/lib/samagotchi/worker/signal_grace.rb +96 -0
  58. data/lib/samagotchi/worker/startup.rb +92 -0
  59. data/lib/samagotchi/worker/wake_turns.rb +190 -0
  60. data/lib/samagotchi/worker.rb +24 -1065
  61. data/lib/samagotchi/worker_exit_claim.rb +12 -0
  62. metadata +12 -2
  63. data/lib/samagotchi/web/public/cards_offscreen.js +0 -69
@@ -125,7 +125,8 @@ export function stepSlotText({ step, ended, chipHidden }) {
125
125
  // none) only when the user folded that card (+askingFold+: the folded key,
126
126
  // null: none), so a
127
127
  // question always arrives open and a new one never matches an old fold;
128
- // else the user's +choice+ (chi_stage_collapsed, as set by hand), unless a
128
+ // else the user's +choice+ (the session's fold by hand, else the page's
129
+ // default: session_prefs.js chi_stage_collapsed:<session>), unless a
129
130
  // ref's "show in turn" opened it for this turn (+revealed+).
130
131
  export function stageCollapsed({ choice, revealed, asking = null, askingFold = null }) {
131
132
  if (asking) return askingFold === asking;
@@ -25,7 +25,8 @@
25
25
  // the cloud stage_cloud.js's, the docked card and the fold stage_asking.js's,
26
26
  // its pager stage_pager.js's, the waiting cards as data stage_waiting.js's,
27
27
  // the answer's reading stage_answer.js's, the quiet signal stage_stall.js's
28
- // and its clocks stage_quiet_clock.js's, the perf probe stage_probe.js's. A new
28
+ // and its clocks stage_quiet_clock.js's, the perf probe stage_probe.js's and the
29
+ // running-with-no-turn check stage_missing.js's. A new
29
30
  // stage feature goes into its own stage_<feature>.js, wired here in a few
30
31
  // lines; each module resets itself from emptySlots.
31
32
  import { createTurnBlock } from "./turn_block.js";
@@ -69,6 +70,8 @@ const FLASH_MS = 4000;
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
+ // +onStageCleared+(): the stage just went empty (the fold's end, a release):
74
+ // app.js's stage_missing.js looks at it then.
72
75
  // The quiet signal's inputs (stage_quiet_clock.js): +clock+() the page's time,
73
76
  // +streamLive+() the session's stream is open, +timingNote+() what the turn
74
77
  // waits on (live_timing.js note), +serverGen+() a joiner's generation.
@@ -78,7 +81,7 @@ const FLASH_MS = 4000;
78
81
  // factory (stage_waiting.js; a test passes an older one's shape).
79
82
  export function createStageView({
80
83
  historyEl, isNearBottom: historyNearBottom, sawText, sessionId, dockEl, centerEl, taskStop = null,
81
- renderMarkdown, linkRefs, workingSet = null, onCancel = null, onHandedOff = null,
84
+ renderMarkdown, linkRefs, workingSet = null, onCancel = null, onHandedOff = null, onStageCleared = null,
82
85
  clock = () => Date.now(), streamLive = () => true, timingNote = () => "", serverGen = () => null,
83
86
  canCancel = () => true, ownerWait = () => null, createWaiting = createStageWaiting,
84
87
  }) {
@@ -102,7 +105,7 @@ export function createStageView({
102
105
  // The working set's rail: out of the live slots' flow on their right (a
103
106
  // row under the trail in a narrow stage), so it never sets their height.
104
107
  const rail = workingSet
105
- ? createWorkingSetRail({ live, stage, onOpen: (el) => workingSet.openTurn(el), onChange: () => scheduleRefresh() })
108
+ ? createWorkingSetRail({ live, stage, onOpen: (el) => workingSet.openTurn(el), onChange: () => scheduleRefresh(), sessionId })
106
109
  : null;
107
110
  if (rail) {
108
111
  workingSet.setSeen(rail.seenAt);
@@ -206,6 +209,7 @@ export function createStageView({
206
209
  const ask = createStageAsking({
207
210
  stage, extras, tail, scroller, fold, view, opener, frame: () => frame, isOpened: () => opened, setOpened,
208
211
  isEnded: () => !!endKind, promptEl: () => promptEl, setCloud: (open) => cloudView.setCloud(open), scheduleRefresh, pendingCard, waiting,
212
+ sessionId,
209
213
  });
210
214
  const {
211
215
  askedText, settleCards, askingCard, cardOf, foldedText, markOwnToggles,
@@ -521,7 +525,8 @@ export function createStageView({
521
525
  view.reset();
522
526
  }
523
527
 
524
- // The stage empty and hidden, its frame free.
528
+ // The stage empty and hidden, its frame free. The page then looks at it
529
+ // (stage_missing.js): a session that still runs gets its bare status row back.
525
530
  function clearStage() {
526
531
  dropBare();
527
532
  handoff.cancelFold();
@@ -529,6 +534,7 @@ export function createStageView({
529
534
  stage.hidden = true;
530
535
  frame.frameFree();
531
536
  ask.unreveal();
537
+ onStageCleared?.();
532
538
  }
533
539
 
534
540
  function release() {
@@ -684,6 +690,8 @@ export function createStageView({
684
690
  // The turn model and its live phase as the status row reads it (the
685
691
  // composer's delivery line).
686
692
  current: () => view.current(),
693
+ // The cloud and a step's nodes (stage_view_memory.js: what was opened, put back).
694
+ cloud: cloudView, step: (i) => view.step(i),
687
695
  // Only a card that blocks says "goes in once the card above is
688
696
  // answered": check-in leaves the composer free.
689
697
  phase: () => liveSlots(view.current().turn, { pending: pendingCard() }).phase,
@@ -694,6 +702,8 @@ export function createStageView({
694
702
  handoff.reset();
695
703
  release();
696
704
  },
705
+ // The open session's own view settings (session_prefs.js), read again as its view is drawn (session_view.js).
706
+ applyPrefs: () => { ask.reloadChoice(); rail?.applyPrefs?.(); },
697
707
  // The stage's extras while it holds a turn, its queued slot, an opened
698
708
  // turn's history end; false: the history takes it (stage_place.js).
699
709
  place: (el) => placer.place(el),
@@ -0,0 +1,76 @@
1
+ // What the user had opened of a running turn, per session, for this tab
2
+ // only: the cloud open, the steps opened in it, the working set's reader on
3
+ // an item. A switch rebuilds the stage from the server's read (session_sync.js
4
+ // select → resync → session_view.js renderSessionView); this puts back what
5
+ // was opened, when the page comes back to the same turn.
6
+ //
7
+ // Saved when the page leaves a session (select, and forgetSession for the
8
+ // session it drew last, e.g. the start page: before the reset of the stage
9
+ // and the reader), taken when renderSessionView has drawn
10
+ // the read: applied only when the read's running turn is the one saved, and
11
+ // dropped either way (a different or ended turn has nothing to put back). A
12
+ // turn that ends on the page drops its session's entry (endTurnView).
13
+ //
14
+ // A plain Map keyed by session id, the oldest going past +cap+: nothing
15
+ // written to storage, nothing sent. The working set's peek isn't kept: it
16
+ // closes with its popover, which the tap that leaves the session closes.
17
+ //
18
+ // A module of its own: static JS is cached at unversioned URLs, and a new
19
+ // export on an old module would blank the page.
20
+
21
+ export const VIEW_MEMORY_CAP = 20;
22
+
23
+ // What the page shows now of its running turn ({turnId, cloud, steps,
24
+ // reader}), or null: no turn held, or nothing opened. +stage+: the stage
25
+ // view (stage_view.js: holds, current, cloud, step); +turnId+ the running
26
+ // turn's id; +reader+: the working set's reader (ws_reader.js), or null.
27
+ export function captureView({ stage, turnId, reader = null }) {
28
+ if (!turnId || !stage?.holds?.() || !stage.cloud || !stage.step) return null;
29
+ const count = stage.current?.()?.turn?.gens?.length || 0;
30
+ const steps = [];
31
+ for (let i = 0; i < count; i++) if (stage.step(i)?.el?.open) steps.push(i);
32
+ const cloud = !!stage.cloud.isOpen?.();
33
+ const item = reader?.isOpen?.() ? reader.openItem?.() || null : null;
34
+ if (!cloud && !item) return null;
35
+ return { turnId, cloud, steps: cloud ? steps : [], reader: item };
36
+ }
37
+
38
+ // Puts +view+ back on the page (captureView's shape): the cloud, then each
39
+ // step it had open that the replay drew closed (a hand toggle, as a click on
40
+ // its row), then the reader's item.
41
+ export function applyView(view, { stage, reader = null }) {
42
+ if (!view) return;
43
+ if (view.cloud && stage?.holds?.() && stage.cloud) {
44
+ stage.cloud.setCloud(true);
45
+ for (const i of view.steps) {
46
+ const step = stage.step(i);
47
+ if (step?.el && !step.el.open) step.summary?.click();
48
+ }
49
+ }
50
+ if (view.reader && reader?.open) reader.open(view.reader);
51
+ }
52
+
53
+ // The memory: +leave(session, now)+ keeps what +now+ (captureView) says for
54
+ // +session+ (null: forgets it); +take(session, turnId)+ the entry for that
55
+ // turn, else null, and the entry goes; +drop(session)+.
56
+ export function createStageViewMemory({ cap = VIEW_MEMORY_CAP } = {}) {
57
+ const entries = new Map();
58
+ return {
59
+ leave(session, now) {
60
+ if (!session) return;
61
+ entries.delete(session);
62
+ if (!now) return;
63
+ entries.set(session, now);
64
+ while (entries.size > cap) entries.delete(entries.keys().next().value);
65
+ },
66
+ take(session, turnId) {
67
+ const entry = entries.get(session) || null;
68
+ entries.delete(session);
69
+ return entry && turnId && entry.turnId === turnId ? entry : null;
70
+ },
71
+ drop(session) {
72
+ entries.delete(session);
73
+ },
74
+ size: () => entries.size,
75
+ };
76
+ }
@@ -264,7 +264,7 @@ export function createStreamHandlers(deps) {
264
264
  prompt_restored: async (data) => {
265
265
  const id = selected();
266
266
  keepEarlyRestore(data, earlyRestores, { myId: clientId, sentIds });
267
- const { refill, label, images: restoredImages, verify, revises } = restoreAction(data, { myId: clientId, sentIds, composerEmpty: composer.empty() });
267
+ const { refill, label, own, author, images: restoredImages, verify, revises } = restoreAction(data, { myId: clientId, sentIds, composerEmpty: composer.empty() });
268
268
  if (refill) composer.refill(refill);
269
269
  if (refill && verify) deps.restoreVerify?.(verify);
270
270
  // A Revise turn's draft too: its chip comes back with the text.
@@ -285,7 +285,8 @@ export function createStreamHandlers(deps) {
285
285
  }
286
286
  // Not an echo waiting for its turn_enqueued: it keeps its enqueued_id, so
287
287
  // a resend's echo isn't matched to it.
288
- makeUserBubble(data.prompt || "", { state: "failed", label, enqueuedId: data.origin?.enqueued_id || `failed:${Date.now()}`, images: data.images });
288
+ // A participant's own failed bubble takes their badge from the viewer (own), anyone else's from the event.
289
+ makeUserBubble(data.prompt || "", { state: "failed", label, author: own ? null : author, own: own && !!author, enqueuedId: data.origin?.enqueued_id || `failed:${Date.now()}`, images: data.images });
289
290
  if (failedText) addEndBubble(failedText);
290
291
  },
291
292
  // A session command ran in the worker (any client's). One that changed
@@ -304,7 +304,7 @@ export function initWaitLine({ tasks } = {}) {
304
304
  // no "steered" badge, as a reload shows it).
305
305
  // A participant's prompt's badge, as an op's field ({author}); {} for the
306
306
  // owner's, so their ops stay as they were.
307
- function authorOf(author, name = null, mode = null) {
307
+ export function authorOf(author, name = null, mode = null) {
308
308
  const badge = authorBadge(author, name, mode);
309
309
  return badge ? { author: badge } : {};
310
310
  }
@@ -6,7 +6,7 @@
6
6
  // keyed by their label's id and patched only when what they show changes,
7
7
  // so nothing restarts; a fold fades the absorbed lines out in place and the
8
8
  // lines below slide up once (each line sits at its slot by a transform).
9
- // Collapsed (kept per browser), it is its head line only, with the newest
9
+ // Collapsed (kept per session, per browser: session_prefs.js), it is its head line only, with the newest
10
10
  // entry ticking through it. Read-only: steering is the expanded view's; a
11
11
  // line with a pending op (a /working-set line queued for the turn's end) is
12
12
  // dashed, its title saying what applies next turn; an item added that the
@@ -32,9 +32,11 @@ export function addLabels(items, pending) {
32
32
  n: 1, edited: 0, cut: 0, state: "live", members: [], added: true,
33
33
  }));
34
34
  }
35
- import { readStored, writeStored } from "./storage.js";
35
+ import { WS_RAIL_FOLD, read as readPref, write as writePref } from "./session_prefs.js";
36
36
  import { reducedMotion } from "./stage_frame.js";
37
37
 
38
+ // session_prefs.js WS_RAIL_FOLD's name (chi_working_set_collapsed:<session>),
39
+ // kept for an older importer.
38
40
  export const COLLAPSE_KEY = "chi_working_set_collapsed";
39
41
  // The stage width (px) under which the rail is a row; the phone's
40
42
  // (index.html, under 600 px of window) shows neither.
@@ -96,8 +98,9 @@ export function createRing(parent) {
96
98
  // +live+: the stage's live block (the rail goes last in it); +stage+: the
97
99
  // stage (its width picks the form); +onOpen(railEl)+: the expanded view;
98
100
  // +onChange()+: redraw (the stage's scheduleRefresh), for the fresh cue's
99
- // end and a form change.
100
- export function createWorkingSetRail({ live, stage, onOpen, onChange }) {
101
+ // end and a form change. +sessionId()+: the open session's id, whose fold is
102
+ // kept (null: in memory only).
103
+ export function createWorkingSetRail({ live, stage, onOpen, onChange, sessionId = () => null }) {
101
104
  const rail = el("div", "ts-ws", live);
102
105
  rail.setAttribute("role", "button");
103
106
  rail.setAttribute("aria-haspopup", "dialog");
@@ -112,7 +115,8 @@ export function createWorkingSetRail({ live, stage, onOpen, onChange }) {
112
115
  foldBtn.type = "button";
113
116
  const list = el("div", "ws-list", rail);
114
117
 
115
- let collapsed = readStored(COLLAPSE_KEY) === "1";
118
+ const savedCollapsed = () => readPref(WS_RAIL_FOLD, sessionId(), "0") === "1";
119
+ let collapsed = savedCollapsed();
116
120
  let width = 0;
117
121
  // The turn's fold so far (its groups stay), each line's node by label id
118
122
  // and what it shows, the items' first sight (the fresh cue), and when the
@@ -146,7 +150,7 @@ export function createWorkingSetRail({ live, stage, onOpen, onChange }) {
146
150
 
147
151
  function setCollapsed(value) {
148
152
  collapsed = value;
149
- writeStored(COLLAPSE_KEY, value ? "1" : "0");
153
+ writePref(WS_RAIL_FOLD, sessionId(), value ? "1" : "0");
150
154
  applyCollapsed();
151
155
  shownHead = null;
152
156
  onChange?.();
@@ -303,5 +307,16 @@ export function createWorkingSetRail({ live, stage, onOpen, onChange }) {
303
307
  // For the expanded view: when an item was first seen (its fresh cue).
304
308
  const seenAt = (item) => seen.get(`${item.kind}:${item.key}`);
305
309
 
306
- return { el: rail, draw, reset, seenAt, form, isCollapsed: () => collapsed };
310
+ // The open session's own fold, read again as its view is drawn
311
+ // (stage_view.js applyPrefs); redrawn only when it changed.
312
+ function applyPrefs() {
313
+ const next = savedCollapsed();
314
+ if (next === collapsed) return;
315
+ collapsed = next;
316
+ applyCollapsed();
317
+ shownHead = null;
318
+ onChange?.();
319
+ }
320
+
321
+ return { el: rail, draw, reset, seenAt, form, applyPrefs, isCollapsed: () => collapsed };
307
322
  }
@@ -306,6 +306,8 @@ export function createWorkingSetPreview({ centerEl, session, state = () => ({}),
306
306
  open: openItem,
307
307
  close,
308
308
  isOpen: () => !el.hidden,
309
+ // The open item ({kind, key}), null: none (stage_view_memory.js).
310
+ openItem: () => (!el.hidden && open ? { ...open } : null),
309
311
  // The ref ▾ menu's "What chi has" (refs.js): a file ref whose path is
310
312
  // an item of the set.
311
313
  whatChiHas: {
@@ -170,6 +170,7 @@ module Samagotchi
170
170
  annotate_presets: Config::BY_KEY["web.annotate_presets"].default,
171
171
  editor: Config::BY_KEY["web.editor"].default, new_token: false,
172
172
  working_set: Config::BY_KEY["web.working_set"].default, tunnel: nil, start_dir_from: :flag,
173
+ stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
173
174
  reload_check: Config::BY_KEY["web.reload_check"].default,
174
175
  restarted: false, restart_argv: ["web"], exec: nil)
175
176
  handed_on = false # a :restart leaves Serve to the next process, a run turns it off itself
@@ -230,7 +231,8 @@ module Samagotchi
230
231
  Push.preflight!(public_url)
231
232
  options = { port: port, host: host, url: url, open_browser: open_browser, markdown: markdown,
232
233
  annotate_presets: annotate_presets, editor: editor, lan: lan, working_set: working_set,
233
- reload_check: reload_check, public_url: public_url, start_dir: start_dir }
234
+ stage_collapsed: stage_collapsed, reload_check: reload_check, public_url: public_url,
235
+ start_dir: start_dir }
234
236
  started = if plan
235
237
  with_tunnel(provider, plan) do |up|
236
238
  start(**options, public_notes: provider.start_lines(plan, restarted: restarted), on_bound: up)
@@ -459,6 +461,7 @@ module Samagotchi
459
461
  annotate_presets: Config::BY_KEY["web.annotate_presets"].default, hub: nil, lan: nil,
460
462
  editor: Config::BY_KEY["web.editor"].default, token_path: Token.path,
461
463
  working_set: Config::BY_KEY["web.working_set"].default, public_url: nil, public_notes: [],
464
+ stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
462
465
  reload_check: Config::BY_KEY["web.reload_check"].default,
463
466
  on_bound: nil, start_dir: Dir.pwd, update_check: nil, auto_update: nil)
464
467
  config_restart_unsubscribe = ConfigFile.watch_restart_settings!(process: :web) do |message|
@@ -476,7 +479,8 @@ module Samagotchi
476
479
  push = push_runtime(public_url, state_dir)
477
480
  app = App.new(manager: manager, state_dir: state_dir, markdown: markdown,
478
481
  annotate_presets: annotate_presets, editor: editor, hub: hub, lan: lan_option, working_set: working_set,
479
- reload_check: reload_check, public_url: public_url, public_token: public_token, push: push, start_dir: start_dir)
482
+ stage_collapsed: stage_collapsed, reload_check: reload_check, public_url: public_url,
483
+ public_token: public_token, push: push, start_dir: start_dir)
480
484
  # update.auto: install; a stand-in app (a spec's) has no operations to run.
481
485
  auto_update ||= AutoUpdate.new(hub: hub, ops: app.update_ops, check: update_check, preflight: method(:restart_preflight)) if app.respond_to?(:update_ops)
482
486
  webrick = nil
@@ -26,8 +26,9 @@ module Samagotchi
26
26
  # worker's turn snapshot and state snapshot (both nil without one), the
27
27
  # messages shown (the snapshot's, else the file's) and the stream cursor
28
28
  # the page goes on from (+event_seq+, and the snapshot's +event_id+
29
- # `<seq>-<epoch>`). Each assembler makes its own payload from it.
30
- ShowReads = Data.define(:id, :session, :turn_snapshot, :state, :event_seq, :event_id, :raw_messages) do
29
+ # `<seq>-<epoch>`), and how the snapshot read went (+live_read+: "ok",
30
+ # "failed" or "none"). Each assembler makes its own payload from it.
31
+ ShowReads = Data.define(:id, :session, :turn_snapshot, :state, :event_seq, :event_id, :raw_messages, :live_read) do
31
32
  # The turn in progress, as the worker's snapshot has it (nil: none).
32
33
  def current_turn = turn_snapshot && turn_snapshot["current_turn"]
33
34
 
@@ -79,7 +80,7 @@ module Samagotchi
79
80
  # behind it, all at one event_seq the client streams on from.
80
81
  # @return [ShowReads]
81
82
  def show_reads(id, session)
82
- live = bridge_get_json(id, "snapshot")
83
+ live, live_read = live_snapshot(id)
83
84
  turn_snapshot = live && live["snapshot"]
84
85
  state = live && live["session_state_snapshot"]
85
86
  ShowReads.new(
@@ -88,10 +89,42 @@ module Samagotchi
88
89
  # The stream cursor `<seq>-<epoch>`: a later worker resets it
89
90
  # instead of taking the seq as its own. Only the snapshot has it.
90
91
  event_id: turn_snapshot && turn_snapshot["event_id"],
91
- raw_messages: live_or_saved(turn_snapshot, "messages") { session.messages }
92
+ raw_messages: live_or_saved(turn_snapshot, "messages") { session.messages },
93
+ live_read: live_read
92
94
  )
93
95
  end
94
96
 
97
+ # The live worker's turn snapshot and what its read did: [snapshot,
98
+ # live_read] — "ok" when a snapshot came, "none" when no worker owns the
99
+ # session, "failed" when a live worker's Bridge answered with none. One
100
+ # GET of the Bridge, never two: a worker that is busy is hit once, not
101
+ # twice. The page's stage_missing.js reads live_read, so a running session
102
+ # whose stage shows no turn (this read had no current_turn, and so no
103
+ # replay and no stream cursor) is not mistaken for one whose stream
104
+ # replayed the turn's end. A failed read logs, at debug level, the why from
105
+ # that same request (no reply: a refused connect, a timeout, a cut reply;
106
+ # 200 with no JSON body; another status) and the elapsed ms.
107
+ # @return [Array(Hash, String)]
108
+ def live_snapshot(id)
109
+ return [nil, "none"] unless bridge_client(id)
110
+
111
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
112
+ status, body = bridge_get(id, "snapshot")
113
+ live = status == 200 && body.is_a?(Hash) ? body : nil
114
+ return [live, "ok"] if live
115
+
116
+ ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
117
+ why = if status.nil?
118
+ "no reply"
119
+ elsif status == 200
120
+ "no snapshot in the answer"
121
+ else
122
+ "status #{status}"
123
+ end
124
+ Log.debug(:web, "live_snapshot_failed", sid: id, why: why, ms: ms)
125
+ [nil, "failed"]
126
+ end
127
+
95
128
  # Every finished turn of +reads+ drawn from a line (a real one, else
96
129
  # one made from its messages, #drawn_lines): its items are stamped,
97
130
  # and its drawing goes in turn_drawings. The running turn has none yet.
@@ -124,6 +157,11 @@ module Samagotchi
124
157
  **turn_drawings_field(drawn, messages),
125
158
  failed_turn: failed_turn_for(session, raw_messages),
126
159
  current_turn: reads.current_turn,
160
+ # What the live snapshot read gave: "ok", "none" (no live worker) or
161
+ # "failed" (a live worker answered with no snapshot): the page's
162
+ # stage_missing.js tells a turn that never reached the stage from one
163
+ # whose stream replayed its end (docs/internals/bridge.md, The show).
164
+ live_read: reads.live_read,
127
165
  # The page's join: the turn in progress and the queue behind it as
128
166
  # the live events that draw them (TurnAccumulator.join_events, one
129
167
  # unfold, here: any worker's snapshot works).
@@ -0,0 +1,123 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+
5
+ require_relative "../child_reports"
6
+ require_relative "../client_id"
7
+ require_relative "../continue_offer"
8
+ require_relative "../llm/errors"
9
+ require_relative "../log"
10
+ require_relative "../verify_fresh"
11
+
12
+ module Samagotchi
13
+ class Worker
14
+ # A delegate child's rings to its parent and the Verify fresh hand-off:
15
+ # #forward_fresh_verdicts (the child's side), #absorb_fresh_verdicts (the
16
+ # parent's half), #settle_child_reports, #merges_lost?,
17
+ # #ring_parent_after_turn, #reports_to_parent? and #ring_question. The
18
+ # name is the audit's; #absorb_fresh_verdicts is the parent's half of the
19
+ # Verify fresh hand-off. Writes @owes_parent, @asked_parent and
20
+ # @reporting_turn (also written by #run_engine_turn, with @initial_turn
21
+ # from #run_initial_prompt; #initialize sets them). Reads @session,
22
+ # @state_dir, @session_dir, @engine, @child_reports and @initial_turn.
23
+ module ChildSidePart
24
+ private
25
+
26
+ # A Verify fresh child's verdicts this turn recorded go to its parent
27
+ # (VerifyFresh.forward), after the save: the parent's card shows them.
28
+ # A fresh child never rings (ChildRing.ring): nothing enters the
29
+ # parent's conversation.
30
+ def forward_fresh_verdicts(before)
31
+ return unless @session.verify_fresh
32
+
33
+ added = @session.verdicts.drop(before)
34
+ VerifyFresh.forward(@session, added, state_dir: @state_dir) unless added.empty?
35
+ end
36
+
37
+ # The parent's side, between turns: the verdicts its Verify fresh
38
+ # children forwarded join the session's (saved, then their files go)
39
+ # and the UIs hear each (:verdict_recorded).
40
+ def absorb_fresh_verdicts
41
+ added, files = VerifyFresh.take(@session, @session_dir)
42
+ return if files.empty?
43
+
44
+ return unless save_or_log(:fresh_verdicts) { save_session }
45
+
46
+ FileUtils.rm_f(files)
47
+ added.each { |record| @engine.announce(type: :verdict_recorded, verdict: record) }
48
+ rescue StandardError => e
49
+ Log.warn(:worker, "fresh_verdicts_failed", error: e.class.name, msg: e.message)
50
+ end
51
+
52
+ # The delegate reports this turn took: a kept turn moves the cursors on
53
+ # and deletes their rings; a rolled-back one leaves the rings for the
54
+ # next turn. Once either way: the model reads a report in the
55
+ # conversation, or the next turn brings it (unless a later !rollback
56
+ # erases a kept turn, which drops what it read).
57
+ def settle_child_reports(rolled_back:)
58
+ rolled_back ? @child_reports.release : @child_reports.commit
59
+ end
60
+
61
+ # Whether +error+ ended the turn without its loop's conversation: a
62
+ # failure the loops didn't mark (LLM::FailedTurn), one past their end
63
+ # (the Engine's own end of the turn, say). The Engine kept the turn's
64
+ # start only, so the reports its loop merged are not in the
65
+ # conversation: their rings stay for the next turn, even when the turn
66
+ # itself stays (a reminder or continue turn). Not one raised after the
67
+ # turn ended (the Engine's post-turn work): the turn was kept as it
68
+ # ended, completed or canceled, the reports in it (a turn TurnFlow
69
+ # takes back is a restore, above).
70
+ def merges_lost?(error)
71
+ return false if error.nil? || error.is_a?(LLM::FailedTurn)
72
+
73
+ !KEPT_TURN_OUTCOMES.include?(@session.last_turn&.outcome)
74
+ end
75
+
76
+ # The Engine's turn endings that keep the turn's conversation (#merges_lost?).
77
+ KEPT_TURN_OUTCOMES = %w[completed canceled].freeze
78
+
79
+ # A delegate child's turn that was its parent's (#reports_to_parent?)
80
+ # rings the parent, after the save: the parent reads a settled child.
81
+ # A question it rang about that still waits makes the next turn ring
82
+ # too, whoever starts it (the user answering Continue on the web).
83
+ def ring_parent_after_turn
84
+ ChildRing.ring(@session, why: "turn_end", state_dir: @state_dir) if @reporting_turn
85
+ @owes_parent = @asked_parent && !@session.pending_question.nil?
86
+ @asked_parent = false
87
+ @reporting_turn = false
88
+ end
89
+
90
+ # Whether the turn starting now is a delegate child's parent's: its
91
+ # task (the initial prompt), a follow-up, a continue the parent
92
+ # answered, a reminder, anything but a human typing into the child
93
+ # (ClientId.human?), and any turn after a question the parent
94
+ # was rung about.
95
+ def reports_to_parent?(origin)
96
+ return false unless @session.delegate?
97
+
98
+ @initial_turn || @owes_parent || !ClientId.human?(origin.client_id)
99
+ end
100
+
101
+ # The Engine published a question (after the question desk saved it).
102
+ # In a turn that reports to the parent, the model's own question, the
103
+ # step-limit continue and a hook's question ring it (the parent reports
104
+ # or relays a hook's: ChildReports). Approvals don't: the relay takes
105
+ # them while the parent waits. Nor does a card relayed from this
106
+ # session's own child (relay set): the hop is the parent's wait.
107
+ def ring_question(event)
108
+ return unless @reporting_turn
109
+
110
+ pending = event[:pending_question] || {}
111
+ kind = pending[:kind].to_s
112
+ return unless RINGING_KINDS.include?(kind)
113
+ return if pending[:relay]
114
+
115
+ ChildRing.ring(@session, why: "question", state_dir: @state_dir)
116
+ @asked_parent = true
117
+ end
118
+
119
+ # The kinds of question that ring a delegate child's parent (#ring_question).
120
+ RINGING_KINDS = ["", ContinueOffer::KIND, "hook"].freeze
121
+ end
122
+ end
123
+ end