samagotchi 0.192.0 → 0.194.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 (190) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +128 -1
  3. data/docs/architecture.md +3 -3
  4. data/docs/bundle-authoring.md +1 -1
  5. data/docs/bundles.md +82 -40
  6. data/docs/cli.md +47 -17
  7. data/docs/configuration.md +75 -8
  8. data/docs/context.md +8 -5
  9. data/docs/desktop.md +3 -0
  10. data/docs/guardrails.md +20 -5
  11. data/docs/hooks.md +1 -0
  12. data/docs/internals/bridge.md +3 -1
  13. data/docs/internals/bundles.md +2 -2
  14. data/docs/internals/engine.md +46 -3
  15. data/docs/internals/pages.md +4 -4
  16. data/docs/internals/panes.md +66 -0
  17. data/docs/internals/participants.md +5 -3
  18. data/docs/internals/peers.md +176 -27
  19. data/docs/internals/prompt-caching.md +6 -1
  20. data/docs/internals/remote-sessions.md +6 -0
  21. data/docs/internals/session-lifecycle.md +12 -4
  22. data/docs/internals/web-frontend.md +106 -22
  23. data/docs/internals/working-set.md +5 -1
  24. data/docs/peers.md +150 -27
  25. data/docs/plugins.md +48 -7
  26. data/docs/releasing.md +30 -2
  27. data/docs/scheduling.md +3 -2
  28. data/docs/sessions.md +16 -7
  29. data/docs/sub-agent.md +6 -4
  30. data/docs/system-one.md +4 -0
  31. data/docs/testing.md +38 -3
  32. data/docs/thin-clients.md +27 -11
  33. data/lib/samagotchi/bridge/card_store.rb +1 -1
  34. data/lib/samagotchi/broadcast/triage_model.rb +17 -0
  35. data/lib/samagotchi/bundles/claude-peer/manifest.yml +8 -5
  36. data/lib/samagotchi/bundles/claude-peer/plugin.rb +24 -5
  37. data/lib/samagotchi/bundles/claude-peer/scripts/chi-peer-SKILL.md +61 -24
  38. data/lib/samagotchi/bundles/claude-peer/scripts/pair +31 -8
  39. data/lib/samagotchi/bundles/codex-peer/manifest.yml +8 -5
  40. data/lib/samagotchi/bundles/codex-peer/plugin.rb +62 -6
  41. data/lib/samagotchi/bundles/codex-peer/scripts/chi-peer-SKILL.md +57 -19
  42. data/lib/samagotchi/bundles/codex-peer/scripts/pair +28 -7
  43. data/lib/samagotchi/bundles/coordinator/manifest.yml +2 -2
  44. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +31 -0
  45. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  46. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  47. data/lib/samagotchi/bundles/mcp/plugin.rb +0 -7
  48. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  49. data/lib/samagotchi/chi_invocation.rb +7 -0
  50. data/lib/samagotchi/client.rb +18 -0
  51. data/lib/samagotchi/codex_rollout.rb +93 -0
  52. data/lib/samagotchi/compat.rb +8 -1
  53. data/lib/samagotchi/config.rb +19 -6
  54. data/lib/samagotchi/continue_offer.rb +13 -1
  55. data/lib/samagotchi/delivery.rb +2 -2
  56. data/lib/samagotchi/effective_model.rb +28 -2
  57. data/lib/samagotchi/engine/cards.rb +9 -4
  58. data/lib/samagotchi/engine/hooks.rb +8 -0
  59. data/lib/samagotchi/engine/models.rb +197 -7
  60. data/lib/samagotchi/engine/plugins.rb +2 -0
  61. data/lib/samagotchi/engine/side_requests.rb +72 -13
  62. data/lib/samagotchi/engine/toolkit.rb +1 -1
  63. data/lib/samagotchi/engine/turn_helpers.rb +1 -1
  64. data/lib/samagotchi/engine.rb +11 -8
  65. data/lib/samagotchi/engine_snapshots.rb +16 -3
  66. data/lib/samagotchi/events.rb +1 -0
  67. data/lib/samagotchi/guardrails/pair_boundary.rb +49 -18
  68. data/lib/samagotchi/hooks.rb +3 -1
  69. data/lib/samagotchi/host_registry.rb +146 -16
  70. data/lib/samagotchi/idle_client.rb +13 -2
  71. data/lib/samagotchi/idle_recap.rb +33 -3
  72. data/lib/samagotchi/idle_target.rb +27 -7
  73. data/lib/samagotchi/jsonl_store.rb +13 -2
  74. data/lib/samagotchi/llm/adapter_common.rb +4 -2
  75. data/lib/samagotchi/llm/anthropic_messages.rb +14 -2
  76. data/lib/samagotchi/llm/errors.rb +35 -4
  77. data/lib/samagotchi/llm/model_listing.rb +19 -0
  78. data/lib/samagotchi/llm/openai_chat.rb +8 -2
  79. data/lib/samagotchi/llm/prompt_cache.rb +5 -0
  80. data/lib/samagotchi/model_binding.rb +46 -4
  81. data/lib/samagotchi/model_catalog.rb +68 -8
  82. data/lib/samagotchi/model_profile.rb +35 -0
  83. data/lib/samagotchi/models_command.rb +8 -4
  84. data/lib/samagotchi/pages/launch.rb +1 -1
  85. data/lib/samagotchi/panes/kitty.rb +122 -0
  86. data/lib/samagotchi/panes.rb +185 -0
  87. data/lib/samagotchi/peer_announce.rb +245 -0
  88. data/lib/samagotchi/peer_cold.rb +92 -0
  89. data/lib/samagotchi/peer_command.rb +121 -20
  90. data/lib/samagotchi/peer_continue.rb +42 -16
  91. data/lib/samagotchi/peer_exchanges.rb +7 -0
  92. data/lib/samagotchi/peer_mailbox.rb +50 -10
  93. data/lib/samagotchi/peer_pair_here.rb +149 -0
  94. data/lib/samagotchi/peer_presence.rb +434 -0
  95. data/lib/samagotchi/peer_receipts.rb +33 -6
  96. data/lib/samagotchi/peer_say.rb +46 -21
  97. data/lib/samagotchi/peer_wait_expiry.rb +47 -0
  98. data/lib/samagotchi/plugin/api.rb +13 -1
  99. data/lib/samagotchi/plugin/card.rb +68 -11
  100. data/lib/samagotchi/plugin/context.rb +33 -2
  101. data/lib/samagotchi/plugin/panes.rb +54 -0
  102. data/lib/samagotchi/plugin/peer.rb +170 -63
  103. data/lib/samagotchi/plugin/peer_pairing.rb +290 -0
  104. data/lib/samagotchi/plugin/peer_start.rb +301 -0
  105. data/lib/samagotchi/plugin/peer_start_hook.rb +207 -0
  106. data/lib/samagotchi/plugin/peers.rb +89 -9
  107. data/lib/samagotchi/recap_setup.rb +40 -3
  108. data/lib/samagotchi/self_report.rb +25 -6
  109. data/lib/samagotchi/send_command.rb +6 -6
  110. data/lib/samagotchi/served_lookup.rb +225 -0
  111. data/lib/samagotchi/served_ref.rb +41 -0
  112. data/lib/samagotchi/session_access/contract.rb +6 -0
  113. data/lib/samagotchi/session_access/local.rb +149 -40
  114. data/lib/samagotchi/session_access/remote.rb +4 -4
  115. data/lib/samagotchi/session_access/remote_peers.rb +8 -5
  116. data/lib/samagotchi/session_chain/links.rb +8 -3
  117. data/lib/samagotchi/session_commands.rb +40 -8
  118. data/lib/samagotchi/session_continue.rb +11 -6
  119. data/lib/samagotchi/session_lifecycle/allowed.rb +4 -2
  120. data/lib/samagotchi/session_manager/delivery.rb +5 -0
  121. data/lib/samagotchi/session_manager/lifecycle.rb +58 -7
  122. data/lib/samagotchi/session_manager/removal.rb +3 -0
  123. data/lib/samagotchi/session_manager/spawn.rb +6 -1
  124. data/lib/samagotchi/session_model_settings.rb +7 -3
  125. data/lib/samagotchi/session_stores.rb +25 -11
  126. data/lib/samagotchi/sessions_command.rb +16 -3
  127. data/lib/samagotchi/system_one/http_backend.rb +111 -10
  128. data/lib/samagotchi/system_one/runs.rb +5 -2
  129. data/lib/samagotchi/system_prompt.rb +11 -4
  130. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -1
  131. data/lib/samagotchi/terminal_ui/formatting.rb +26 -12
  132. data/lib/samagotchi/terminal_ui/status_row.rb +20 -3
  133. data/lib/samagotchi/terminal_ui.rb +1 -1
  134. data/lib/samagotchi/testing/boundary.rb +0 -1
  135. data/lib/samagotchi/testing/bundle.rb +6 -2
  136. data/lib/samagotchi/testing/host.rb +1 -0
  137. data/lib/samagotchi/testing/recorder.rb +3 -0
  138. data/lib/samagotchi/turn_endings.rb +6 -2
  139. data/lib/samagotchi/user_typed.rb +29 -0
  140. data/lib/samagotchi/version.rb +1 -1
  141. data/lib/samagotchi/web/app.rb +8 -20
  142. data/lib/samagotchi/web/participant_review.rb +1 -1
  143. data/lib/samagotchi/web/participant_view.rb +1 -1
  144. data/lib/samagotchi/web/peer_routes.rb +40 -15
  145. data/lib/samagotchi/web/public/agent_rows.js +206 -0
  146. data/lib/samagotchi/web/public/agent_runs.js +595 -0
  147. data/lib/samagotchi/web/public/answer_fold.js +41 -44
  148. data/lib/samagotchi/web/public/app.js +4 -4
  149. data/lib/samagotchi/web/public/block_fix.js +1 -1
  150. data/lib/samagotchi/web/public/card.js +26 -10
  151. data/lib/samagotchi/web/public/cards_place.js +6 -4
  152. data/lib/samagotchi/web/public/context_chips.js +24 -2
  153. data/lib/samagotchi/web/public/copy.js +8 -2
  154. data/lib/samagotchi/web/public/data.js +2 -1
  155. data/lib/samagotchi/web/public/format.js +9 -1
  156. data/lib/samagotchi/web/public/history_reveal.js +5 -2
  157. data/lib/samagotchi/web/public/index.html +56 -2
  158. data/lib/samagotchi/web/public/info_bar_model.js +1 -1
  159. data/lib/samagotchi/web/public/model_pick.js +18 -5
  160. data/lib/samagotchi/web/public/model_picker.js +1 -1
  161. data/lib/samagotchi/web/public/page_view.js +1 -1
  162. data/lib/samagotchi/web/public/pages.css +1 -7
  163. data/lib/samagotchi/web/public/peer_chip.js +15 -5
  164. data/lib/samagotchi/web/public/peer_data.js +4 -2
  165. data/lib/samagotchi/web/public/peer_mailbox_api.js +2 -1
  166. data/lib/samagotchi/web/public/peer_note.js +4 -2
  167. data/lib/samagotchi/web/public/peer_row.js +37 -0
  168. data/lib/samagotchi/web/public/peer_wait.js +36 -0
  169. data/lib/samagotchi/web/public/quiet_notes.js +12 -1
  170. data/lib/samagotchi/web/public/revise_stack.js +5 -2
  171. data/lib/samagotchi/web/public/send_turn.js +11 -3
  172. data/lib/samagotchi/web/public/served_ref.js +9 -0
  173. data/lib/samagotchi/web/public/session_fields.js +1 -0
  174. data/lib/samagotchi/web/public/session_state.js +4 -0
  175. data/lib/samagotchi/web/public/stage_missing.js +23 -6
  176. data/lib/samagotchi/web/public/stream_handlers.js +16 -0
  177. data/lib/samagotchi/web/public/turn_block.js +4 -0
  178. data/lib/samagotchi/web/public/version_notices.js +7 -1
  179. data/lib/samagotchi/web/session_control.rb +19 -10
  180. data/lib/samagotchi/web/session_show.rb +20 -0
  181. data/lib/samagotchi/web/update_ops.rb +2 -2
  182. data/lib/samagotchi/worker/command_queue.rb +3 -0
  183. data/lib/samagotchi/worker/mail.rb +24 -1
  184. data/lib/samagotchi/worker.rb +8 -5
  185. data/lib/samagotchi/worker_inbound/mail.rb +34 -6
  186. data/lib/samagotchi/worker_inbound.rb +11 -3
  187. data/lib/samagotchi/worker_link.rb +13 -1
  188. data/lib/samagotchi/worker_wakes.rb +33 -5
  189. metadata +22 -2
  190. data/lib/samagotchi/web/public/pages_group.js +0 -67
@@ -76,7 +76,7 @@ export function createModelPicker({ button, panel, input, list, composer, center
76
76
  ? html`<span class="model-host">${markedTemplate(row.host, hostMarks)}</span><span class="model-dot"> · </span>` : nothing;
77
77
  const noteText = rowNote(row, defaultName);
78
78
  const note = noteText ? html`<span class="model-note">${noteText}</span>` : nothing;
79
- const cls = `model-option${i === active ? " active" : ""}${row.name === chosen ? " chosen" : ""}${row.unavailable ? " unavailable" : ""}`;
79
+ const cls = `model-option${i === active ? " active" : ""}${row.name === chosen ? " chosen" : ""}${row.unavailable ? " unavailable" : ""}${row.served ? " served" : ""}`;
80
80
  return html`<div class=${cls} role="option" id=${`model-option-${i}`} aria-selected=${String(i === active)} data-index=${i} title=${rowTitle(row) || nothing}><span class="model-id">${host}${markedTemplate(row.id, idMarks)}</span>${note}</div>`;
81
81
  }
82
82
 
@@ -26,7 +26,7 @@ import { tableTemplate } from "./page_table.js";
26
26
  import { nextSort } from "./page_table_model.js";
27
27
  import { changedText, errorCopy, failureParts, keptAfterFailure, metaText } from "./page_model.js";
28
28
 
29
- // Mirrors Pages::NAME (lib/samagotchi/pages.rb).
29
+ // Mirrors Pages::NAME (lib/samagotchi/pages.rb); pinned by spec/pages_name_sync_spec.rb.
30
30
  const PAGE_NAME = /^[a-z0-9][a-z0-9-]{0,39}$/;
31
31
 
32
32
  export function createPageView({
@@ -70,13 +70,7 @@ button.pg-row-main:focus-visible{outline:2px solid var(--accent);outline-offset:
70
70
  /* The meta wraps under the title, on a line of its own. */
71
71
  .pg-meta{order:5;flex-basis:100%;white-space:normal}
72
72
  }
73
- /* A page card (the Pages list's), and All sessions' former Pages group (pages_group.js, kept for an older cached app.js:
74
- remove the group's rules after 0.189.0): one row of cards that scrolls sideways. Their own card rules: the session
75
- cards' are scoped to #allList .card. */
76
- #pagesGroup{display:flex;flex-direction:column;gap:8px;flex:none;min-width:0}
77
- #pagesGroup[hidden]{display:none}
78
- .pg-group-label{font-size:11px;font-weight:600;line-height:1;letter-spacing:.06em;text-transform:uppercase;color:var(--text-faint)}
79
- .pg-cards{display:flex;gap:8px;overflow-x:auto;padding-bottom:2px;scrollbar-width:thin}
73
+ /* A page card (the Pages list's). The session cards' rules are scoped to #allList .card. */
80
74
  .pg-card{all:unset;box-sizing:border-box;flex:0 0 190px;display:flex;flex-direction:column;gap:2px;min-width:0;padding:9px 11px;border:1px solid var(--accent-border);border-radius:10px;background:var(--bg-panel);font-size:12.5px;color:var(--text-muted);cursor:pointer}
81
75
  .pg-card b{display:block;font-size:13px;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
82
76
  .pg-card:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
@@ -20,10 +20,11 @@ export const peerKey = (name) => `peer:${name}`;
20
20
  export const POPOVER_EXCHANGES = 8;
21
21
 
22
22
  // The peers model's rows as chips' groups: {key, name, label, peer} for each
23
- // paired one (its link.json: paired_at), in the model's order. A peer that
24
- // was unpaired keeps its messages but has no chip.
23
+ // paired one (its link.json: paired_at) or one the session waits for
24
+ // (waiting: /claude pair's mark, peer_wait.js), in the model's order. A peer
25
+ // that was unpaired keeps its messages but has no chip.
25
26
  export function peerGroups(peers) {
26
- return (peers || []).filter((peer) => peer?.name && peer.paired_at)
27
+ return (peers || []).filter((peer) => peer?.name && (peer.paired_at || peer.waiting))
27
28
  .map((peer) => ({ key: peerKey(peer.name), name: peer.name, label: peer.label || peer.name, peer }));
28
29
  }
29
30
 
@@ -51,6 +52,9 @@ const since = (iso, now) => {
51
52
  };
52
53
 
53
54
  // The chip of +group+: the first state that applies.
55
+ // - ended: its peer is gone (the server's `ended`: its inbox socket missing;
56
+ // the peer-handshake mock-up's scene 5, "Claude · ended"): Start one in kitty
57
+ // and Unpair are on the status card;
54
58
  // - answers-only: the pairing has no address (chi can't send);
55
59
  // - cant-send: the newest send failed (the transport refused it);
56
60
  // - waiting: the newest validate or question send has no answer (its age the send's);
@@ -65,7 +69,11 @@ export function peerChipModel(group, exchanges = [], now = Date.now()) {
65
69
  let state = "paired";
66
70
  let words = "paired";
67
71
  let why = "paired: chi can send to it and it answers with chi peer say";
68
- if (!group.peer?.can_send) {
72
+ if (group.peer?.ended) {
73
+ state = "ended";
74
+ words = "ended";
75
+ why = `that ${group.label} session ended: its status card starts another or unpairs`;
76
+ } else if (!group.peer?.can_send) {
69
77
  state = "answers-only";
70
78
  words = "answers only";
71
79
  why = "paired with no address chi can reach: it answers, chi can't send to it";
@@ -120,7 +128,9 @@ export function peerPopoverTemplate(group, exchanges = [], { text = null, status
120
128
  const all = sends(exchanges);
121
129
  const lastSent = all.find((ex) => ex.state !== "failed");
122
130
  const failing = peer.can_send && cantSend(group, exchanges);
123
- const sendsLine = !peer.can_send
131
+ const sendsLine = peer.ended
132
+ ? `can't: that ${group.label} session ended (start another from its status card)`
133
+ : !peer.can_send
124
134
  ? "can't: it paired with no address chi can reach"
125
135
  : failing
126
136
  ? `the last send didn't go through: pair again from ${group.label}`
@@ -51,9 +51,11 @@ export function createPeers({ sessionId, hasPeer = () => false, onChange = () =>
51
51
  tick = null;
52
52
  }
53
53
 
54
- // One interval while an exchange waits, none otherwise.
54
+ // One interval while an exchange waits or the session waits for a peer
55
+ // (/claude pair: the chip turns paired, or goes, with no focus event on a
56
+ // phone), none otherwise.
55
57
  function syncTick() {
56
- const waiting = current().some((peer) => (peer.exchanges || []).some((ex) => ex?.state === "waiting"));
58
+ const waiting = current().some((peer) => peer?.waiting || (peer.exchanges || []).some((ex) => ex?.state === "waiting"));
57
59
  if (!waiting) stopTick();
58
60
  else if (tick === null && win.setInterval) tick = win.setInterval(() => refresh(), tickMs);
59
61
  }
@@ -14,7 +14,8 @@ export function getPeerMessage(id, name, serial, box = null, opts = {}) {
14
14
  return api(`${base(id, name)}/messages/${encodeURIComponent(serial)}${query}`, opts);
15
15
  }
16
16
 
17
- // DELETE …/peers/NAME (Unpair) → {unpaired}: the pairing ends, its messages stay.
17
+ // DELETE …/peers/NAME (Unpair) → {unpaired, forwarded_to}: the pairing ends, its messages stay; forwarded_to names
18
+ // the chain's live link whose pairing ended too, when the session was continued (absent otherwise).
18
19
  export function unpairPeer(id, name, opts = {}) {
19
20
  return api(base(id, name), { ...opts, method: "DELETE" });
20
21
  }
@@ -16,7 +16,9 @@
16
16
  // (a live context_added, an older server) as plain text that peer_links.js
17
17
  // swaps for its markdown; its source kept in data-peer-md. The fold shows
18
18
  // the rest, and the bubble is marked data-peer-inline (no "Read the full
19
- // answer").
19
+ // answer"). A summary the peer didn't send (`.note-text` is then the
20
+ // note's first line) is marked data-fallback (answer_fold.js's row reads the
21
+ // peer's text instead).
20
22
  // Its own module: new exports go in new modules (web-frontend.md).
21
23
 
22
24
  import { html, nothing } from "./vendor/lit-html.js";
@@ -65,5 +67,5 @@ export function peerNoteTemplate(note) {
65
67
  : rendered ? html`<div class="peer-text markdown md-compact" data-peer-md=${block.text}>${unsafeHTML(rendered)}</div>`
66
68
  : html`<div class="peer-text" data-peer-md=${block.text}>${block.text}</div>`;
67
69
  const told = block ? block.rest : (note.content ?? "");
68
- return html`<div class=${cls} title=${fullTime(note.at) || nothing} data-opening-id=${opening} data-peer-source=${attr(source)} data-peer-name=${attr(peer.peer)} data-peer-re=${attr(peer.re)} data-peer-serial=${attr(peer.serial)} data-peer-box=${attr(peer.box)} data-peer-inline=${block ? "1" : nothing}><div class="peer-head"><span class="peer-who">${name} answered</span><span class="peer-up-slot" data-peer-slot="up"></span>${verdictTemplate(peer)}</div><div class="note-text">${peerSummaryText(note)}</div>${body}<div class="peer-foot"><span class="peer-full-slot" data-peer-slot="full"></span><details class="peer-told"><summary>what chi told the agent</summary><div class="peer-told-text">${told}</div></details></div></div>`;
70
+ return html`<div class=${cls} title=${fullTime(note.at) || nothing} data-opening-id=${opening} data-peer-source=${attr(source)} data-peer-name=${attr(peer.peer)} data-peer-re=${attr(peer.re)} data-peer-serial=${attr(peer.serial)} data-peer-box=${attr(peer.box)} data-peer-inline=${block ? "1" : nothing}><div class="peer-head"><span class="peer-who">${name} answered</span><span class="peer-up-slot" data-peer-slot="up"></span>${verdictTemplate(peer)}</div><div class="note-text" data-fallback=${String(peer.summary ?? "").trim() ? nothing : "1"}>${peerSummaryText(note)}</div>${body}<div class="peer-foot"><span class="peer-full-slot" data-peer-slot="full"></span><details class="peer-told"><summary>what chi told the agent</summary><div class="peer-told-text">${told}</div></details></div></div>`;
69
71
  }
@@ -0,0 +1,37 @@
1
+ // A peer's answer as its closed row (answer_fold.js draws it): "<name> ·
2
+ // <verdict> · <summary> · N lines". Pure, no DOM. The summary is the one the
3
+ // peer sent without the verdict it wrote into it (PeerNote.payload parses
4
+ // the verdict out of the summary, so the row would say it twice); no summary,
5
+ // the first line of the peer's text. N counts the peer's own text only (the
6
+ // note's body), never the bubble's copy text; no body, no length.
7
+ // docs/internals/web-frontend.md, The peer exchange.
8
+ // Its own module: new exports go in new modules (web-frontend.md).
9
+ import { verdictWord } from "./peer_exchange.js";
10
+
11
+ // PeerNote::VERDICT, the Ruby side's: `VERDICT CHANGES`, `VERDICT: OK`; a
12
+ // copied template's `VERDICT OK|CHANGES` is none.
13
+ const VERDICT = /\bVERDICT:?\s*([A-Z]+)(?![A-Za-z|])/g;
14
+
15
+ const squash = (s) => s.replace(/\s+/g, " ").trim();
16
+
17
+ // +summary+ without its last verdict mark when that mark is +verdict+ (the
18
+ // server's word: the last mark it parsed), the punctuation it leaves tidied.
19
+ export function summaryWithoutVerdict(summary, verdict) {
20
+ const s = String(summary ?? "");
21
+ const last = [...s.matchAll(VERDICT)].at(-1);
22
+ if (!last || !verdict || last[1] !== verdict) return squash(s);
23
+ const before = s.slice(0, last.index).replace(/[\s([]+$/, "");
24
+ const after = s.slice(last.index + last[0].length).replace(/^[\s)\]]*[,;.:—–-]?\s*/, "");
25
+ const joined = squash(`${before} ${after}`).replace(/\(\s*\)|\[\s*\]/g, "");
26
+ return squash(joined.replace(/[\s,;:—–-]+$/, ""));
27
+ }
28
+
29
+ // The row's words: {name, verdict, summary, size}. +verdict+: the server's
30
+ // word (OK, CHANGES, UNSURE) or none; +summary+: the summary the peer sent,
31
+ // or none; +first+: the first line of the peer's text (no summary);
32
+ // +lines+: the peer's text's lines, null with no text.
33
+ export function peerRowWords({ name = "", verdict = null, summary = "", first = "", lines = null } = {}) {
34
+ const said = summaryWithoutVerdict(summary, verdict);
35
+ const size = lines === null || lines === undefined ? "" : `${lines} line${lines === 1 ? "" : "s"}`;
36
+ return { name: squash(String(name ?? "")), verdict: verdictWord(verdict), summary: said || squash(String(first ?? "")), size };
37
+ }
@@ -0,0 +1,36 @@
1
+ // A session that waits for a peer (/claude pair, PeerPresence's mark; its row's `waiting: {until}` in GET …/peers):
2
+ // the waiting chip, "Claude · waiting 8 min", and its popover with Cancel (scene 4 of the peer-handshake mock-up).
3
+ // Pure templates and models: context_chips.js draws them; Cancel is the Unpair route (DELETE …/peers/NAME ends the
4
+ // wait too). docs/internals/web-frontend.md, The peer exchange. Its own module: new exports go in new modules.
5
+
6
+ import { html } from "./vendor/lit-html.js";
7
+
8
+ // The peer's app as its bundle words it (chi web loads no plugins); else its label.
9
+ const APPS = { claude: "Claude Code" };
10
+ const appOf = (group) => APPS[group?.name] || group?.label || group?.name || "peer";
11
+
12
+ // The whole minutes left until +until+ (rounded up, at least 1 while it waits); 0 past it or unparsable.
13
+ export function waitMinutesLeft(until, now = Date.now()) {
14
+ const end = Date.parse(until || "");
15
+ if (Number.isNaN(end) || end <= now) return 0;
16
+ return Math.max(1, Math.ceil((end - now) / 60_000));
17
+ }
18
+
19
+ // The waiting chip of +group+ (peer_chip.js peerGroups): its own state, "awaiting", apart from a send's "waiting".
20
+ // @return {key, name, state, label, title, dot, peer}
21
+ export function waitingChipModel(group, now = Date.now()) {
22
+ const minutes = waitMinutesLeft(group?.peer?.waiting?.until, now);
23
+ return { key: group.key, name: group.key, state: "awaiting", label: `${group.label} · waiting ${minutes} min`,
24
+ title: `waiting for a ${appOf(group)} session: one that starts in this project pairs on its own`, dot: false,
25
+ peer: true };
26
+ }
27
+
28
+ // The waiting chip's popover: the wait, the minutes left, Cancel (data-act="cancel": no confirm, it pairs nothing).
29
+ export function waitingPopoverTemplate(group, now = Date.now()) {
30
+ const minutes = waitMinutesLeft(group?.peer?.waiting?.until, now);
31
+ return html`<div class="ctx-pop-head"><strong>${group.label}</strong><span class="ctx-pop-kind">waiting</span
32
+ ><button type="button" class="ctx-pop-close" data-act="close" aria-label="Close">×</button></div
33
+ ><div class="peer-wait"><div class="peer-wait-txt"><div class="peer-wait-main">Waiting for a ${appOf(group)} session</div
34
+ ><div class="peer-wait-sub">Start one in this project and it pairs on its own · ${minutes} min left</div></div
35
+ ><button type="button" class="ghost" data-act="cancel">Cancel</button></div>`;
36
+ }
@@ -90,6 +90,13 @@ export function rowLabel(items) {
90
90
  return { count: items.length, names, warn };
91
91
  }
92
92
 
93
+ // A stretch's segments: [{kind, items, ...its words}]. One kind today, the
94
+ // notes (rowLabel's words), drawn as the row. Not exported (the mixed-cache
95
+ // rule): agent_runs.js has the segment line.
96
+ function segments(items) {
97
+ return [{ kind: "notes", items, ...rowLabel(items) }];
98
+ }
99
+
93
100
  export function rowTemplate({ count, names, warn }) {
94
101
  return html`<span class="qn-count">${count} ${count === 1 ? "note" : "notes"}</span><span class="qn-names">· ${names.join(", ")}</span>${warn > 0 ? html`<span class="qn-warn">⚠ ${warn}</span>` : nothing}`;
95
102
  }
@@ -104,6 +111,9 @@ export function revealQuiet(el) {
104
111
  if (row && !row.classList.contains("open")) row.click();
105
112
  }
106
113
 
114
+ // The page installs agent_runs.js (the one owner of the notes rows, reports
115
+ // and peer answers) instead; this one is kept for an older cached app.js
116
+ // until the next release's baseline refresh.
107
117
  // @param historyEl the history (#history)
108
118
  // @return {settle()} (the observer runs it; specs call it)
109
119
  export function installQuietNotes({ historyEl }) {
@@ -139,7 +149,8 @@ export function installQuietNotes({ historyEl }) {
139
149
  }
140
150
 
141
151
  function drawRow(row, items) {
142
- const label = rowLabel(items);
152
+ const [{ count, names, warn }] = segments(items);
153
+ const label = { count, names, warn };
143
154
  const words = JSON.stringify(label);
144
155
  if (drawn.get(row) !== words) {
145
156
  render(rowTemplate(label), row);
@@ -165,7 +165,9 @@ export function historyTurns(historyEl) {
165
165
  };
166
166
  for (const el of historyEl.children) {
167
167
  if ([STUB_CLASS, ROW_CLASS, VIEW_CLASS, QUIET_ROW].some((c) => el.classList.contains(c))) continue;
168
- if (el.classList.contains(FOLD_ROW) && el.nextElementSibling?.matches(OPENING)) continue;
168
+ // An opening's row (a report's, a peer answer's that opens a wake turn
169
+ // or sits between turns) is its head, never the turn before's element.
170
+ if (el.classList.contains(FOLD_ROW) && el.nextElementSibling?.matches(`${OPENING}, ${NOTE_BOUNDARY}`)) continue;
169
171
  const opening = el.matches(OPENING) ? el : el.querySelector(OPENING);
170
172
  if (opening || el.matches(NOTE_BOUNDARY)) {
171
173
  close();
@@ -326,7 +328,8 @@ export function installReviseStacks({
326
328
  let gapText = "";
327
329
  if (gap?.classList.contains("time-gap")) {
328
330
  let before = gap.previousElementSibling;
329
- while (before?.classList.contains(HIDDEN_CLASS)) before = before.previousElementSibling;
331
+ // (A run's line or notes row hidden with its version, agent_runs.js, is hidden too.)
332
+ while (before?.matches(`.${HIDDEN_CLASS}, .quiet-hidden`)) before = before.previousElementSibling;
330
333
  const fold = !turn.stub.classList.contains("open") && !!before?.matches(`.${STUB_CLASS}:not(.open)`);
331
334
  gap.classList.toggle(GAP_HIDDEN_CLASS, fold);
332
335
  if (fold) gapText = gap.textContent.replace(/[─\s]+$/u, "").replace(/^[─\s]+/u, "");
@@ -231,9 +231,17 @@ export function createSendTurn({
231
231
  store.update({ current: { owner: "tui" } });
232
232
  return;
233
233
  }
234
- // A stale tab sent into a session deleted meanwhile: the start page
235
- // says so, and the line stays in the composer.
236
- if (e.code === "not_found") return leaveGoneSession(sentTo, "not_found");
234
+ // A stale tab sent into a session deleted meanwhile: if this session
235
+ // is open, leave it as before; elsewhere, preserve the line in the
236
+ // start-page draft and say where it went.
237
+ if (e.code === "not_found") {
238
+ if (sentTo !== session()) {
239
+ composer.move?.(sentTo, "");
240
+ toast(`Session ${sentTo.slice(0, 8)} is gone; your message is in the new-session draft`, null, { sticky: true });
241
+ return;
242
+ }
243
+ return leaveGoneSession(sentTo, "not_found");
244
+ }
237
245
  if (sentTo === session() && closesOn?.(e)) return;
238
246
  // A /queue to a worker that can't queue (it would steer): its words, the text kept.
239
247
  if (e.code === "delivery_unavailable" && sentTo === session()) return addCommandBubble({ label: null, line, text: e.body?.detail || e.message, failed: true });
@@ -0,0 +1,9 @@
1
+ // The model value `served` ("main:served": whatever that host serves now;
2
+ // docs/configuration.md). A module of its own: a new export of an old
3
+ // module would leave a cached copy without it (docs/internals/web-frontend.md).
4
+
5
+ // Whether +name+, a session's stored model ref, is a served one ("served",
6
+ // "main:served"; ServedRef.stored? in Ruby).
7
+ export function isServedRef(name) {
8
+ return /^([^:]+:)?served$/i.test(String(name || "").trim());
9
+ }
@@ -76,6 +76,7 @@ export const FIELDS = {
76
76
  writers: "stream_handlers.js command_ran (a new model also syncModelPick: an event, D9)",
77
77
  },
78
78
  served: { redraws: ["infoBar"], writers: "stream_handlers.js (command_ran, generation_completed)" },
79
+ modelServed: { redraws: ["infoBar"], writers: "stream_handlers.js (command_ran's model_served, generation_completed's requested_model)" },
79
80
  dir: { source: (d) => d.session?.working_directory, redraws: ["infoBar"], writers: "the payload" },
80
81
  owner: {
81
82
  card: (sess) => sess.owner || null,
@@ -51,6 +51,9 @@ export function emptySessionState() {
51
51
  model: "",
52
52
  // What the worker's server said it served for a model name: [served, asked].
53
53
  served: null,
54
+ // The id a served model (main:served) runs on now, or null (any other
55
+ // model; an older worker's payload).
56
+ modelServed: null,
54
57
  dir: "",
55
58
  // Who holds the session: "worker" (shared), "tui" (a plain terminal chi;
56
59
  // sending would be refused) or null.
@@ -104,6 +107,7 @@ export function sessionStateFrom(data) {
104
107
  status: s.status,
105
108
  model: s.model_name,
106
109
  served: s.served_model ? [s.served_model, s.served_model_for, s.served_expected_by || null] : null,
110
+ modelServed: s.model_served || null,
107
111
  dir: s.working_directory,
108
112
  owner: s.owner || null,
109
113
  // Its live worker's chi and features (null and [] without one): a
@@ -116,20 +116,37 @@ export function createStageMissing({ store, turnDom, composerEl, win = globalThi
116
116
  return null;
117
117
  }
118
118
  stage.dataset.stageMissing = reason === "covered" ? "covered" : "1";
119
- const session = store.selected;
120
- if (!warned.has(session)) {
119
+ sayLater();
120
+ return reason;
121
+ }
122
+
123
+ // The line waits for the task's own work to end: a re-read resets the turn
124
+ // view and draws its read in one go (session_sync.js resync), and the check
125
+ // the reset's clearStage makes sees the stage before the read filled it.
126
+ // The render's own check (session_view.js) then clears the mark, and the
127
+ // line, once per visit, goes only for a mark still there, with what the
128
+ // stage shows then.
129
+ let saying = false;
130
+ function sayLater() {
131
+ if (saying) return;
132
+ saying = true;
133
+ queueMicrotask(() => {
134
+ saying = false;
135
+ const stage = turnDom.root;
136
+ const mark = stage.dataset.stageMissing;
137
+ const session = store.selected;
138
+ if (!mark || store.current.status !== "running" || warned.has(session)) return;
121
139
  warned.add(session);
122
140
  warn(missingLine({
123
- session, reason, counts: counts || readCounts({}),
124
- stage: where,
141
+ session, reason: mark === "covered" ? "covered" : "none", counts: counts || readCounts({}),
142
+ stage: geometry(),
125
143
  composer: {
126
144
  top: stage.composerTop,
127
145
  floor: readPref(COMPOSER_FLOOR, session),
128
146
  fold: readPref(COMPOSER_FOLD, session),
129
147
  },
130
148
  }));
131
- }
132
- return reason;
149
+ });
133
150
  }
134
151
 
135
152
  // A status write redraws the bar: only a change needs the stage looked at,
@@ -52,6 +52,7 @@ import { routeChunk } from "./chunk_router.js";
52
52
  import { extractCtxPct, generationTokens } from "./ctx.js";
53
53
  import { ctxTokensOf } from "./ctx_tokens.js";
54
54
  import { failedTurnText, fullTime } from "./format.js";
55
+ import { isServedRef } from "./served_ref.js";
55
56
  import { cancelLineText } from "./timing.js";
56
57
  import { keepFollowing } from "./scroll.js";
57
58
  import { shownElsewhere } from "./card.js";
@@ -67,6 +68,11 @@ import { isParticipantAuthor } from "./participant_model.js";
67
68
  import { stillOn } from "./latest.js";
68
69
  import { peerRef } from "./peer_exchange.js";
69
70
 
71
+ // The peer bundles' names: a card or a line of theirs may change the peers model (chi web knows no bundle command).
72
+ const PEER_SOURCES = ["claude-peer", "codex-peer"];
73
+ // A hook notice's hook names the bundle as "plugin.rb (bundle claude-peer)".
74
+ const peerHook = (hook) => PEER_SOURCES.some((name) => hook === name || String(hook || "").endsWith(`(bundle ${name})`));
75
+
70
76
  export function createStreamHandlers(deps) {
71
77
  const {
72
78
  selected, store, clientId, capabilities, historyEl,
@@ -132,6 +138,10 @@ export function createStreamHandlers(deps) {
132
138
  patch.timing = { ...current.timing, tokens, ...(segments ? { modelSegments: segments } : {}) };
133
139
  }
134
140
  if (data?.served_model) patch.served = [data.served_model, data.requested_model, data.served_expected_by || null];
141
+ // A served model's generation was asked for the id it runs on now. A
142
+ // served model is a served ref, or one whose id came (an alias of
143
+ // main:served: command_ran's model_name is the alias typed).
144
+ if (data?.requested_model && (current.modelServed || isServedRef(current.model))) patch.modelServed = String(data.requested_model);
135
145
  store.update({ current: patch });
136
146
  turnDom.generationCompleted();
137
147
  },
@@ -319,6 +329,8 @@ export function createStreamHandlers(deps) {
319
329
  // /llm-context: workingSetStrategy).
320
330
  const patch = {};
321
331
  if (view.modelName && view.modelName !== store.current.model) Object.assign(patch, { model: view.modelName, served: null });
332
+ // A served model's id now (none: another model, or an older worker).
333
+ if (view.modelName) patch.modelServed = data.model_served || null;
322
334
  // /llm-context changed what the next turn runs under.
323
335
  if (data.llm_context) patch.llmContext = data.llm_context;
324
336
  // /thinking (or /model) changed the level the next turn runs at.
@@ -470,6 +482,8 @@ export function createStreamHandlers(deps) {
470
482
  // shows elsewhere (a hook's links in the rendered answer) isn't drawn,
471
483
  // not even in the stage trail; a joined turn's notices come here too.
472
484
  hook_notice: (data) => {
485
+ // A peer bundle's line (a /claude pair wait ran out): the waiting chip goes.
486
+ if (peerHook(data.hook)) peers?.refresh();
473
487
  // A plugin put the session on another toolkit (ctx.use_toolkit).
474
488
  if ("toolkit" in data) {
475
489
  store.update({ current: { toolkit: data.toolkit || null } });
@@ -498,6 +512,8 @@ export function createStreamHandlers(deps) {
498
512
  card: (data) => {
499
513
  upsertCard(data);
500
514
  if (data.body) refreshCardBodies();
515
+ // A peer bundle's card (/claude pair's list): the waiting chip may have come.
516
+ if (PEER_SOURCES.includes(data.source)) peers?.refresh();
501
517
  },
502
518
  // The stream's cursor could not be replayed: render from scratch.
503
519
  reset: () => resync(),
@@ -661,6 +661,10 @@ export function createTurnBlock({
661
661
  const kept = [];
662
662
  if (blockEl) {
663
663
  updateBlockSummary();
664
+ // Its tool calls, counted (the run line's "N calls", agent_runs.js:
665
+ // never parsed from the summary's words); stamped before `done`, whose
666
+ // class change is what the history's observers settle on.
667
+ blockEl.dataset.calls = String(turn.gens.reduce((n, gen) => n + gen.tools.length, 0));
664
668
  blockEl.classList.add("done");
665
669
  // How it ended (completed, canceled, failed), live and reloaded alike.
666
670
  blockEl.dataset.end = kind;
@@ -108,6 +108,12 @@ export function createVersionNotices({
108
108
  return workerBadgeFor(store.selected, store.current, versions);
109
109
  }
110
110
 
111
+ // What a restart's 200 says: a stopped session (was_stopped) was started again.
112
+ function restartedText(result) {
113
+ if (result.was_stopped) return result.version ? `Started again on chi ${result.version}` : "Starting again: its worker is starting";
114
+ return result.version ? `Restarted on chi ${result.version}` : "Restarting: the new worker is starting";
115
+ }
116
+
111
117
  // Restart: the session moves to a new worker on the newest chi; the page
112
118
  // follows it (its bridge_up), the composer's draft stays as it is.
113
119
  async function restart() {
@@ -119,7 +125,7 @@ export function createVersionNotices({
119
125
  store.touch("infoBar");
120
126
  try {
121
127
  const result = await api.restartSession(id);
122
- toast(result.version ? `Restarted on chi ${result.version}` : "Restarting: the new worker is starting");
128
+ toast(restartedText(result));
123
129
  } catch (e) {
124
130
  toast(cantText("restart", e), null, { sticky: true });
125
131
  } finally {
@@ -526,20 +526,29 @@ module Samagotchi
526
526
  # POST /api/sessions/:id/restart: hand the session to a new worker on
527
527
  # the newest chi installed (SessionManager.restart_session). 200
528
528
  # {status: "restarted", session_id, from_version, version} (version nil:
529
- # the new worker is still starting; its bridge_up follows); 409
529
+ # the new worker is still starting; its bridge_up follows), with
530
+ # was_stopped: true when a stopped session was started again; 409
530
531
  # {error: "held" | "not_running" | "unsupported" | "failed", reason, detail} in words (a stopped
531
- # worker: held, reason stopped, its pid; a stop marked: held, reason stop_marked;
532
- # deleting: held, reason deleting); 409
533
- # owned_by_tui; 404.
534
- def handle_restart(_req, id)
535
- result = @manager.restart_session(id, state_dir: @state_dir, client_id: ClientId::WEB_RESTART)
532
+ # worker: held, reason stopped, its pid; a stop marked and the body
533
+ # {start_stopped: false} (an agent's chi --remote): held, reason
534
+ # stop_marked; a stopping worker that didn't leave: held, reason
535
+ # still_stopping; deleting: held, reason deleting); 409
536
+ # owned_by_tui; 404. Without that body (the page's Restart, a
537
+ # person's chi --remote) a stopped session is started again.
538
+ def handle_restart(req, id)
539
+ body = parse_json(request_body(req, 4096))
540
+ start_stopped = !(body.is_a?(Hash) && body["start_stopped"] == false)
541
+ result = @manager.restart_session(id, state_dir: @state_dir, client_id: ClientId::WEB_RESTART,
542
+ start_stopped: start_stopped)
536
543
  @hub&.touch(id)
537
- json_response(200, { status: "restarted", session_id: id, from_version: result.from_version,
538
- version: result.version })
544
+ body = { status: "restarted", session_id: id, from_version: result.from_version, version: result.version }
545
+ body[:was_stopped] = true if result.was_stopped
546
+ json_response(200, body)
539
547
  rescue SessionManager::RestartRefused => e
540
548
  error = %i[not_running unsupported failed].include?(e.reason) ? e.reason.to_s : "held"
541
- refusal_response(409, error, e, reason: e.reason.to_s, session_id: id, version: e.version, holds: e.holds,
542
- pid: e.pid)
549
+ # detail: for the person at the page (its next step); message: the words alone.
550
+ refusal_response(409, error, e, detail: e.words_for(agent: false), reason: e.reason.to_s, session_id: id,
551
+ version: e.version, holds: e.holds, pid: e.pid)
543
552
  rescue SessionManager::OwnedByTUI => e
544
553
  owned_by_tui(e)
545
554
  end
@@ -297,6 +297,22 @@ module Samagotchi
297
297
  refs.empty? ? pending.except(key) : pending.merge(key => refs)
298
298
  end
299
299
 
300
+ # The id a served session (main:served) last ran on, for a session no
301
+ # worker runs: its last turn record's model_ref ("main:<id>",
302
+ # analytics.json) when that names the served ref's host; nil otherwise.
303
+ def saved_model_served(session, persisted)
304
+ Degrade.call(:web, "model_served_unreadable") do
305
+ registry = host_registry
306
+ model = session.model_name.to_s
307
+ next nil if !persisted.is_a?(Hash) || model.empty? || !registry.served?(model)
308
+
309
+ ref = Array(persisted["turn_records"]).reverse_each.map { |r| r.is_a?(Hash) ? r["model_ref"].to_s : "" }.find { |r| !r.empty? }
310
+ prefix = "#{registry.served_entry(model).name}:"
311
+ id = ref&.start_with?(prefix) ? ref.delete_prefix(prefix) : nil
312
+ id unless id.nil? || id.empty? || ServedRef.word?(id)
313
+ end
314
+ end
315
+
300
316
  # The session file's prompt parts as the wire has them ([] for a file
301
317
  # without the field).
302
318
  def saved_prompt_parts(session) = Array(session.prompt_parts).map(&:to_h)
@@ -312,6 +328,8 @@ module Samagotchi
312
328
  if snapshot
313
329
  session_json = session_json.merge(served_model: snapshot["served_model"], served_model_for: snapshot["served_model_for"],
314
330
  served_expected_by: snapshot["served_expected_by"])
331
+ # A served model's id now; an older worker's snapshot has none.
332
+ session_json = session_json.merge(model_served: snapshot["model_served"]) if snapshot["model_served"]
315
333
  # The model notes its prompt carries now (a /model there changes them).
316
334
  session_json = session_json.merge(prompt_notes: snapshot["prompt_notes"]) if snapshot["prompt_notes"].is_a?(Array)
317
335
  # And the sizes of its parts (the head view's "From the start"); an
@@ -325,6 +343,8 @@ module Samagotchi
325
343
  session_json = session_json.merge(context_status: snapshot["context_status"]) if snapshot.key?("context_status")
326
344
  else
327
345
  session_json = session_json.merge(saved_served_model(session, persisted), prompt_parts: saved_prompt_parts(session))
346
+ served_id = saved_model_served(session, persisted)
347
+ session_json = session_json.merge(model_served: served_id) if served_id
328
348
  end
329
349
  # The per-session settings' chips (the info bar's ⚙ chip: llm ctx, think
330
350
  # and reasoning; the tools chip): the worker's, else worked out here from the
@@ -248,9 +248,9 @@ module Samagotchi
248
248
  { "session_id" => restarted.session_id, "state" => "restarted", "from_version" => restarted.from_version,
249
249
  "version" => restarted.version }
250
250
  rescue SessionManager::RestartRefused => e
251
- # detail: the refusal's own words (RestartRefused.words), the reason code for clients.
251
+ # detail: the refusal's own words and the page's next step (RestartRefused#words_for), the reason code for clients.
252
252
  { "session_id" => worker.session_id, "state" => "refused", "reason" => e.reason.to_s,
253
- "detail" => e.message, "holds" => e.holds.map(&:to_s) }
253
+ "detail" => e.words_for(agent: false), "holds" => e.holds.map(&:to_s) }
254
254
  rescue SessionManager::OwnedByTUI => e
255
255
  { "session_id" => worker.session_id, "state" => "owned_by_tui", "detail" => e.message }
256
256
  rescue StandardError => e
@@ -324,6 +324,9 @@ module Samagotchi
324
324
  event = { type: :command_ran, **command.event_fields, status: status, output: command_output_shown(text),
325
325
  changed: changed.map(&:to_s), model_name: @engine.effective_model_name }
326
326
  event[:anytime] = true if anytime
327
+ # A served model's id now (the UIs' "served · <id>"); none for any other.
328
+ served_id = @engine.served_model_id if @engine.respond_to?(:served_model_id)
329
+ event[:model_served] = served_id if served_id
327
330
  # The session's title after /title (nil: cleared), for the TUIs' row.
328
331
  event[:title] = @engine.session&.title if changed.include?(:title)
329
332
  # Its line was shown at its command_queued (waits: turn_end).
@@ -2,17 +2,31 @@
2
2
 
3
3
  require_relative "../log"
4
4
  require_relative "../peer_receipts"
5
+ require_relative "../peer_wait_expiry"
5
6
 
6
7
  module Samagotchi
7
8
  class Worker
8
9
  # A peer's mail on the worker's side: the absorb and the mail wake turn
9
10
  # it may start (WorkerInbound#absorb_mail), the hold a pass gives, and
10
- # the receipts' end of every turn (PeerReceipts#turn_ended). Reads
11
+ # the receipts' end of every turn (PeerReceipts#turn_ended), and the
12
+ # peer wake count's save (#save_peer_wakes), and a /<peer> pair wait
13
+ # that ran out (#expire_peer_waits, from #idle_pass). Reads
11
14
  # @inbound, @exit_claim and @peer_receipts, and @unmarked_this_turn
12
15
  # (#run_wake sets it). See docs/internals/peers.md.
13
16
  module MailPart
14
17
  private
15
18
 
19
+ # This session's /<peer> pair waits past their 10 minutes, between
20
+ # turns (PeerWaitExpiry): removed, and the peer's bundle says so once
21
+ # (Engine#peer_wait_ended). A failure is logged; the loop goes on.
22
+ def expire_peer_waits
23
+ @peer_waits ||= PeerWaitExpiry.new(session_id: @session_id, state_dir: @state_dir, registry: @engine.peer_registry,
24
+ on_ended: ->(peer) { @engine.peer_wait_ended(peer) })
25
+ @peer_waits.call
26
+ rescue StandardError => e
27
+ Log.exception(:peer, "peer_wait_expiry_failed", e, sid: @session_id)
28
+ end
29
+
16
30
  # A peer's mail (WorkerInbound#absorb_mail), and the mail wake turn it
17
31
  # may start. A failure to read or write it (or in that turn) is logged:
18
32
  # the next pass tries again.
@@ -48,6 +62,15 @@ module Samagotchi
48
62
  Log.exception(:worker, "peer_receipts_failed", e)
49
63
  end
50
64
 
65
+ # WorkerWakes' on_peer_count: the peer wake turns in a row, saved so
66
+ # the next worker starts from them (PeerReceipts#peer_wakes=). Logged,
67
+ # never raised: a lost save is a reset of the count.
68
+ def save_peer_wakes(count)
69
+ @peer_receipts.peer_wakes = count
70
+ rescue SystemCallError, IOError => e
71
+ Log.exception(:worker, "peer_wakes_not_saved", e)
72
+ end
73
+
51
74
  def settle_peer_turn(id, result, error)
52
75
  yielded = false
53
76
  yield