samagotchi 0.182.0 → 0.183.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 (161) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/bin/chi +3 -1
  4. data/docs/architecture.md +16 -6
  5. data/docs/bundle-authoring.md +1 -1
  6. data/docs/bundles.md +103 -4
  7. data/docs/cli.md +28 -6
  8. data/docs/configuration.md +2 -1
  9. data/docs/guardrails.md +16 -1
  10. data/docs/internals/block-renderers.md +58 -3
  11. data/docs/internals/bridge.md +13 -5
  12. data/docs/internals/bundles.md +21 -4
  13. data/docs/internals/engine.md +18 -8
  14. data/docs/internals/remote-sessions.md +24 -5
  15. data/docs/internals/web-frontend.md +88 -28
  16. data/docs/internals/working-set.md +1 -1
  17. data/docs/mcp-server.md +80 -0
  18. data/docs/plugins.md +308 -21
  19. data/docs/sessions.md +3 -3
  20. data/docs/sub-agent.md +9 -0
  21. data/docs/testing.md +3 -1
  22. data/docs/thin-clients.md +146 -0
  23. data/lib/samagotchi/bridge/pending_card.rb +4 -3
  24. data/lib/samagotchi/bridge/sse_writer.rb +16 -15
  25. data/lib/samagotchi/bridge.rb +59 -68
  26. data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
  27. data/lib/samagotchi/bundle_command/check.rb +36 -19
  28. data/lib/samagotchi/bundle_command.rb +50 -21
  29. data/lib/samagotchi/bundle_manifest.rb +101 -4
  30. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  31. data/lib/samagotchi/bundles/mcp/client.rb +260 -0
  32. data/lib/samagotchi/bundles/mcp/content.rb +107 -0
  33. data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
  34. data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
  35. data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
  36. data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
  37. data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
  38. data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
  39. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  40. data/lib/samagotchi/cli/parent_wait.rb +5 -3
  41. data/lib/samagotchi/command_intake.rb +7 -0
  42. data/lib/samagotchi/commands/registry.rb +8 -3
  43. data/lib/samagotchi/continue_offer.rb +24 -15
  44. data/lib/samagotchi/engine/block_fix.rb +4 -4
  45. data/lib/samagotchi/engine/cards.rb +14 -5
  46. data/lib/samagotchi/engine/events.rb +10 -15
  47. data/lib/samagotchi/engine/models.rb +1 -1
  48. data/lib/samagotchi/engine/plugins.rb +3 -0
  49. data/lib/samagotchi/engine/recap.rb +1 -1
  50. data/lib/samagotchi/engine/side_requests.rb +1 -1
  51. data/lib/samagotchi/engine/sign_in.rb +142 -0
  52. data/lib/samagotchi/engine/turn_end.rb +3 -3
  53. data/lib/samagotchi/engine.rb +43 -27
  54. data/lib/samagotchi/engine_snapshots.rb +1 -1
  55. data/lib/samagotchi/guardrail_wiring.rb +3 -1
  56. data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
  57. data/lib/samagotchi/guardrails/verdict.rb +3 -2
  58. data/lib/samagotchi/hold_stop.rb +4 -4
  59. data/lib/samagotchi/idle_recap.rb +19 -11
  60. data/lib/samagotchi/idle_reminders.rb +7 -5
  61. data/lib/samagotchi/idle_scheduler.rb +7 -10
  62. data/lib/samagotchi/installed_bundles/dir.rb +37 -0
  63. data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
  64. data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
  65. data/lib/samagotchi/installed_bundles/record.rb +3 -2
  66. data/lib/samagotchi/installed_bundles/standing.rb +3 -1
  67. data/lib/samagotchi/llm/http.rb +96 -5
  68. data/lib/samagotchi/mcp_command.rb +110 -0
  69. data/lib/samagotchi/mcp_server/http.rb +112 -0
  70. data/lib/samagotchi/mcp_server/protocol.rb +244 -0
  71. data/lib/samagotchi/mcp_server/stdio.rb +92 -0
  72. data/lib/samagotchi/mcp_server/text.rb +155 -0
  73. data/lib/samagotchi/mcp_server/tools.rb +245 -0
  74. data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
  75. data/lib/samagotchi/memory_bundle/builder.rb +20 -2
  76. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  77. data/lib/samagotchi/memory_bundle/installer.rb +16 -3
  78. data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
  79. data/lib/samagotchi/memory_bundle/shas.rb +6 -4
  80. data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
  81. data/lib/samagotchi/memory_bundle/status.rb +15 -6
  82. data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
  83. data/lib/samagotchi/plugin/api.rb +6 -1
  84. data/lib/samagotchi/plugin/card.rb +36 -11
  85. data/lib/samagotchi/plugin/context.rb +63 -6
  86. data/lib/samagotchi/plugin/http.rb +40 -15
  87. data/lib/samagotchi/plugin/http_errors.rb +15 -0
  88. data/lib/samagotchi/plugin/http_stream.rb +86 -0
  89. data/lib/samagotchi/plugin/http_transport.rb +58 -16
  90. data/lib/samagotchi/plugin/loader.rb +18 -11
  91. data/lib/samagotchi/plugin/secrets.rb +266 -0
  92. data/lib/samagotchi/plugin/sign_in.rb +392 -0
  93. data/lib/samagotchi/plugin/sse_reader.rb +103 -0
  94. data/lib/samagotchi/queued_command.rb +28 -4
  95. data/lib/samagotchi/recap_setup.rb +13 -4
  96. data/lib/samagotchi/ref.rb +3 -2
  97. data/lib/samagotchi/relay_verifier.rb +8 -7
  98. data/lib/samagotchi/relay_watcher.rb +4 -4
  99. data/lib/samagotchi/run_options.rb +2 -1
  100. data/lib/samagotchi/send_command.rb +54 -41
  101. data/lib/samagotchi/session_access/ask.rb +244 -0
  102. data/lib/samagotchi/session_access/contract.rb +5 -0
  103. data/lib/samagotchi/session_access/exchange/token.rb +101 -0
  104. data/lib/samagotchi/session_access/exchange.rb +173 -0
  105. data/lib/samagotchi/session_access/local.rb +25 -6
  106. data/lib/samagotchi/session_access/remote.rb +4 -1
  107. data/lib/samagotchi/session_command_catalog.rb +10 -0
  108. data/lib/samagotchi/session_commands.rb +17 -0
  109. data/lib/samagotchi/session_config.rb +4 -4
  110. data/lib/samagotchi/session_observer.rb +27 -0
  111. data/lib/samagotchi/steer_cut.rb +4 -3
  112. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
  113. data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
  114. data/lib/samagotchi/testing/boundary.rb +4 -0
  115. data/lib/samagotchi/testing/bundle.rb +48 -2
  116. data/lib/samagotchi/testing/fake_http.rb +60 -15
  117. data/lib/samagotchi/testing/host.rb +4 -1
  118. data/lib/samagotchi/testing/recorder.rb +45 -5
  119. data/lib/samagotchi/tools/tool_index.rb +14 -3
  120. data/lib/samagotchi/version.rb +1 -1
  121. data/lib/samagotchi/web/app.rb +8 -6
  122. data/lib/samagotchi/web/ask_routes.rb +292 -0
  123. data/lib/samagotchi/web/mcp_route.rb +88 -0
  124. data/lib/samagotchi/web/public/app.js +2 -3
  125. data/lib/samagotchi/web/public/block_frame.js +72 -11
  126. data/lib/samagotchi/web/public/block_host.js +44 -8
  127. data/lib/samagotchi/web/public/block_regions.js +126 -0
  128. data/lib/samagotchi/web/public/card.js +22 -9
  129. data/lib/samagotchi/web/public/card_actions.js +21 -0
  130. data/lib/samagotchi/web/public/card_kinds.js +1 -1
  131. data/lib/samagotchi/web/public/card_registry.js +3 -2
  132. data/lib/samagotchi/web/public/data.js +15 -12
  133. data/lib/samagotchi/web/public/delete_sheet.js +222 -162
  134. data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
  135. data/lib/samagotchi/web/public/format.js +3 -0
  136. data/lib/samagotchi/web/public/index.html +52 -7
  137. data/lib/samagotchi/web/public/more_sheet.js +6 -4
  138. data/lib/samagotchi/web/public/picture_regions.js +243 -0
  139. data/lib/samagotchi/web/public/picture_viewer.js +113 -12
  140. data/lib/samagotchi/web/public/refs.js +5 -3
  141. data/lib/samagotchi/web/public/region_hit.js +144 -0
  142. data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
  143. data/lib/samagotchi/web/public/running_tasks.js +6 -4
  144. data/lib/samagotchi/web/public/session_actions.js +105 -100
  145. data/lib/samagotchi/web/session_access_routes.rb +14 -11
  146. data/lib/samagotchi/web/session_control.rb +31 -9
  147. data/lib/samagotchi/web/session_create.rb +2 -2
  148. data/lib/samagotchi/worker/child_side.rb +3 -2
  149. data/lib/samagotchi/worker/command_queue.rb +13 -13
  150. data/lib/samagotchi/worker/leave.rb +3 -3
  151. data/lib/samagotchi/worker/scratch.rb +6 -6
  152. data/lib/samagotchi/worker/signal_grace.rb +6 -5
  153. data/lib/samagotchi/worker/startup.rb +3 -3
  154. data/lib/samagotchi/worker/wake_turns.rb +4 -4
  155. data/lib/samagotchi/worker.rb +32 -21
  156. data/lib/samagotchi/worker_exit_claim.rb +1 -1
  157. data/lib/samagotchi/worker_idle_exit.rb +18 -9
  158. data/lib/samagotchi/worker_inbound.rb +12 -7
  159. data/lib/samagotchi/worker_participant_gate.rb +9 -7
  160. data/lib/samagotchi/worker_task_wakes.rb +7 -5
  161. metadata +31 -1
@@ -0,0 +1,144 @@
1
+ // A diagram's regions under a point, by maths (picture_regions.js): pure, no
2
+ // DOM, `node --test`. The viewer keeps its pointer capture, so a drag, a pinch
3
+ // and a double tap work as before, and a finger's tap can take the nearest node.
4
+ //
5
+ // Points and boxes are fractions of the picture (block_regions.js); +size+ is the
6
+ // picture's shown size in px, {width, height}, so tolerances are screen px.
7
+ // Nodes and notes win over arrows, arrows over groups; the nearest wins within
8
+ // its kind, and between two at one distance (a node inside a node) the smaller.
9
+ // A finger's margin is the exception: an arrow right under it beats a node only
10
+ // near it (hitRegion).
11
+ //
12
+ // A module of its own: its exports are new (docs/internals/web-frontend.md).
13
+
14
+ import { freeBox } from "./pan_zoom.js";
15
+
16
+ // An arrow's line is this easy to hit at least, whatever the pointer.
17
+ export const EDGE_TOLERANCE = 7;
18
+ // How far a selected box stays above the card.
19
+ export const REVEAL_MARGIN = 12;
20
+ // An arrow key's move needs a region at least this far that way (px).
21
+ const MIN_ALONG = 4;
22
+
23
+ const area = (r) => (r.box ? r.box[2] * r.box[3] : 0);
24
+
25
+ // Two regions that select together: one object, or one kind and one non-empty
26
+ // id (a sequence participant's top and bottom box).
27
+ export function sameRegion(a, b) {
28
+ if (!a || !b) return false;
29
+ return a === b || (a.kind === b.kind && a.id !== "" && a.id === b.id);
30
+ }
31
+
32
+ function boxDistance([x, y, w, h], p, size) {
33
+ const dx = Math.max(x - p.x, 0, p.x - (x + w)) * size.width;
34
+ const dy = Math.max(y - p.y, 0, p.y - (y + h)) * size.height;
35
+ return Math.hypot(dx, dy);
36
+ }
37
+
38
+ function segmentDistance(p, a, b, size) {
39
+ const px = p.x * size.width;
40
+ const py = p.y * size.height;
41
+ const ax = a[0] * size.width;
42
+ const ay = a[1] * size.height;
43
+ const bx = b[0] * size.width;
44
+ const by = b[1] * size.height;
45
+ const len = (bx - ax) ** 2 + (by - ay) ** 2;
46
+ const t = len > 0 ? Math.max(0, Math.min(1, ((px - ax) * (bx - ax) + (py - ay) * (by - ay)) / len)) : 0;
47
+ return Math.hypot(px - (ax + (bx - ax) * t), py - (ay + (by - ay) * t));
48
+ }
49
+
50
+ function lineDistance(points, p, size) {
51
+ let best = Infinity;
52
+ for (let i = 1; i < points.length; i++) best = Math.min(best, segmentDistance(p, points[i - 1], points[i], size));
53
+ return best;
54
+ }
55
+
56
+ const within = (d, limit) => (d <= limit ? d : Infinity);
57
+ const nodeAt = (point, size, limit) => (r) => (r.kind === "node" || r.kind === "note" ? within(boxDistance(r.box, point, size), limit) : Infinity);
58
+ const groupAt = (point, size) => (r) => (r.kind === "group" ? within(boxDistance(r.box, point, size), 0) : Infinity);
59
+ // An edge's distance: its line's within +line+ px, or its label box's within +label+.
60
+ const edgeAt = (point, size, line, label) => (r) => {
61
+ if (r.kind !== "edge") return Infinity;
62
+ const onLine = within(lineDistance(r.points, point, size), line);
63
+ return r.box ? Math.min(onLine, within(boxDistance(r.box, point, size), label)) : onLine;
64
+ };
65
+
66
+ // The nearest region by +dist+ (Infinity: not one), the smaller between two at
67
+ // one distance; or null.
68
+ function nearest(regions, dist) {
69
+ let best = null;
70
+ let bestD = Infinity;
71
+ for (const r of regions) {
72
+ const d = dist(r);
73
+ if (d < bestD || (d !== Infinity && d === bestD && area(r) < area(best))) { best = r; bestD = d; }
74
+ }
75
+ return best;
76
+ }
77
+
78
+ // The region under +point+ ({x, y} in fractions), within +tol+ px, or null.
79
+ // A pointer whose tolerance is within an arrow's own (a mouse) takes the nodes
80
+ // at it first, then the arrows. A wider one (a finger) takes a node only on its
81
+ // box first: an arrow's line or label right under it (7 px) beats a node that is
82
+ // only within the finger's margin, so an arrow between two close nodes can be
83
+ // tapped at a phone's fit; then the nodes and the arrows at its margin.
84
+ export function hitRegion(regions, point, size, tol) {
85
+ if (!regions?.length || !point) return null;
86
+ const inner = tol > EDGE_TOLERANCE ? 0 : tol;
87
+ const direct = nearest(regions, nodeAt(point, size, inner)) ?? nearest(regions, edgeAt(point, size, EDGE_TOLERANCE, Math.min(tol, EDGE_TOLERANCE)));
88
+ if (direct) return direct;
89
+ const margin = inner === tol ? null : nearest(regions, nodeAt(point, size, tol)) ?? nearest(regions, edgeAt(point, size, tol, tol));
90
+ return margin ?? nearest(regions, groupAt(point, size));
91
+ }
92
+
93
+ // A region's centre in fractions: its box's, an edge's label box's, else the
94
+ // middle of its line.
95
+ export function regionCentre(r) {
96
+ if (r.box) return { x: r.box[0] + r.box[2] / 2, y: r.box[1] + r.box[3] / 2 };
97
+ const p = r.points[Math.floor(r.points.length / 2)];
98
+ return { x: p[0], y: p[1] };
99
+ }
100
+
101
+ const DIRECTIONS = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] };
102
+
103
+ // The region nearest +from+ along an arrow key's way (along + 2 × across, in
104
+ // px through +size+), or null: none that way, or not an arrow key. A group is
105
+ // the move only when nothing else is that way: its centre is near everything
106
+ // it holds.
107
+ export function nearestInDirection(regions, from, key, size = { width: 1, height: 1 }) {
108
+ return nearestOf(regions.filter((r) => r.kind !== "group"), from, key, size) ?? nearestOf(regions, from, key, size);
109
+ }
110
+
111
+ function nearestOf(regions, from, key, size) {
112
+ const dir = DIRECTIONS[key];
113
+ if (!dir || !from) return null;
114
+ const me = regionCentre(from);
115
+ let best = null;
116
+ let score = Infinity;
117
+ for (const r of regions) {
118
+ if (sameRegion(r, from)) continue;
119
+ const c = regionCentre(r);
120
+ const dx = (c.x - me.x) * size.width;
121
+ const dy = (c.y - me.y) * size.height;
122
+ const along = dx * dir[0] + dy * dir[1];
123
+ if (along < MIN_ALONG) continue;
124
+ const s = along + 2 * Math.abs(dx * dir[1] + dy * dir[0]);
125
+ if (s < score) { score = s; best = r; }
126
+ }
127
+ return best;
128
+ }
129
+
130
+ // How far up (px) the view moves so +box+ clears the card, whose top is at
131
+ // +cover+ in the stage's px; 0 when it is clear, or when the picture fits the
132
+ // free height (clampView centres it there, so a move would be undone). The box's
133
+ // top never goes above the free area for it.
134
+ export function revealOffset(box, view, picture, stage, cover) {
135
+ if (!box) return 0;
136
+ const free = freeBox(stage);
137
+ const shown = picture.height * view.scale;
138
+ if (shown <= free.height) return 0;
139
+ const top = view.y + box[1] * shown;
140
+ const bottom = view.y + (box[1] + box[3]) * shown;
141
+ const need = bottom + REVEAL_MARGIN - cover;
142
+ if (need <= 0) return 0;
143
+ return Math.max(0, Math.min(need, top - (free.top + REVEAL_MARGIN)));
144
+ }
@@ -0,0 +1,275 @@
1
+ // The delete / archive sheet's words (docs/internals/web-frontend.md, The
2
+ // delete sheet), DOM-free: the rows (Goes / Stopped first / Stays; Hidden
3
+ // for an archive), the button's words, the archive's model and the toast
4
+ // after a delete. delete_sheet.js draws them (its templates, its flow and its
5
+ // shell); session_actions.js starts it. A module of its own: the page's
6
+ // modules are cached at unversioned URLs ("New exports go in new modules").
7
+ //
8
+ // What it reads is the server's (GET …/delete_plan, SessionChain::Delete::
9
+ // Preview): each choice's +delegates+ ({delete: [ids], leave: [{id,
10
+ // running}]}), +tasks+ ({running, unverified, unreadable}, RunningTasks'
11
+ // wire form), +worker+ ("turn" / "idle" / null; a chain's {idle, turn}) and
12
+ // +refusal+; an archive's 409 tasks_running (+tasks+, +sessions+). A card's
13
+ // name is the page's rule (format.js cardName) from its own list, else the
14
+ // short id.
15
+ //
16
+ // A row's line is a list of parts: a string, {b} (bold) or {dim}.
17
+
18
+ import { cardName, clip, normalize } from "./format.js";
19
+ import { NAMED_MAX, tasksCount, tasksLine, tasksStoppedSuffix } from "./running_tasks.js";
20
+
21
+ const short = (id) => String(id ?? "").slice(0, 8);
22
+ const count = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
23
+ const capital = (text) => (text ? `${text.charAt(0).toUpperCase()}${text.slice(1)}` : text);
24
+ // A server's refusal words (lower case, no stop) as a sentence.
25
+ const sentence = (text) => {
26
+ const s = capital(String(text ?? "").trim());
27
+ return s && !/[.!?]$/.test(s) ? `${s}.` : s;
28
+ };
29
+
30
+ export const UNDONE = "This can't be undone.";
31
+
32
+ // The session's name as the list shows it, cut for a sheet's title.
33
+ export function sessionName(session) {
34
+ return clip(normalize(session ? cardName(session) : ""), 41);
35
+ }
36
+
37
+ // "Delete 3f2a91c0 — "Nightly triage"?" (+verb+ Delete / Archive).
38
+ export function sheetTitle(verb, id, session) {
39
+ const name = sessionName(session);
40
+ return `${verb} ${short(id)}${name ? ` — "${name}"` : ""}?`;
41
+ }
42
+
43
+ // The sessions +ids+ named as the list names them (9d0e1f2a "run the
44
+ // specs"), NAMED_MAX at most, then "+N more".
45
+ export function namesLine(ids, sessions = []) {
46
+ const byId = new Map(sessions.map((s) => [s.id, s]));
47
+ const names = ids.map((id) => {
48
+ const name = clip(normalize(byId.has(id) ? cardName(byId.get(id)) : ""), 30);
49
+ return name ? `${short(id)} "${name}"` : short(id);
50
+ });
51
+ const more = names.length - NAMED_MAX;
52
+ return `${names.slice(0, NAMED_MAX).join(" · ")}${more > 0 ? ` +${more} more` : ""}`;
53
+ }
54
+
55
+ // A choice's tasks split as the sheet says them: the running ones it stops,
56
+ // the ones chi can't verify or read it leaves (never signalled).
57
+ function taskParts(listing) {
58
+ if (Array.isArray(listing)) return { running: listing, unsure: { unverified: [], unreadable: [] } };
59
+ return {
60
+ running: listing?.running || [],
61
+ unsure: { unverified: listing?.unverified || [], unreadable: listing?.unreadable || [] },
62
+ };
63
+ }
64
+
65
+ // The running tasks' ids a stop is given (the tap stops only those).
66
+ export function runningTaskIds(listing) {
67
+ return taskParts(listing).running.map((task) => task.id).filter(Boolean);
68
+ }
69
+
70
+ // What a tap sends with its delete or archive: stopTasks and the named ids
71
+ // whenever the choice lists any task (also when it holds only records chi
72
+ // can't verify: the server refuses on those too, and a stop never signals
73
+ // them), else nothing.
74
+ export function stopTasksOptions(listing) {
75
+ return tasksCount(listing) > 0 ? { stopTasks: true, tasks: runningTaskIds(listing) } : {};
76
+ }
77
+
78
+ // The delegates a choice leaves: the running ones, and the stopped ones under
79
+ // them (they stay with their running delegate). Without +delegates+ (an
80
+ // older server) its count reads as running ones.
81
+ function leftDelegates(choice) {
82
+ const leave = choice?.delegates?.leave;
83
+ if (!Array.isArray(leave)) return { running: [], under: 0, n: choice?.left_running || 0 };
84
+ const running = leave.filter((d) => d.running !== false).map((d) => d.id);
85
+ return { running, under: leave.length - running.length, n: running.length };
86
+ }
87
+
88
+ function goneDelegates(choice) {
89
+ const ids = choice?.delegates?.delete;
90
+ return Array.isArray(ids) ? ids : [];
91
+ }
92
+
93
+ function turnCount(worker) {
94
+ if (worker === "turn") return 1;
95
+ return worker && typeof worker === "object" ? worker.turn || 0 : 0;
96
+ }
97
+
98
+ // The rows of one session's choice (the plan's +link+ for a session in no
99
+ // chain): Goes, Stopped first, Stays, each only when it applies.
100
+ // @return [{key: "goes"|"stop"|"stays", label, lines: [[part]]}]
101
+ export function sheetGroups(choice, { sessions = [], sessionId = null } = {}) {
102
+ const groups = [];
103
+ const gone = goneDelegates(choice);
104
+ const goes = [["Its history, notes and images."]];
105
+ if (gone.length) goes.push([{ b: count(gone.length, "stopped delegate") }, `: ${namesLine(gone, sessions)}`]);
106
+ groups.push({ key: "goes", label: "Goes", lines: goes });
107
+
108
+ const { running, unsure } = taskParts(choice?.tasks);
109
+ const stop = [];
110
+ if (choice?.worker === "turn") stop.push([{ b: "Its running turn" }, ": it ends as stopped, its worker goes."]);
111
+ else if (choice?.worker === "idle") stop.push(["Its worker ", { dim: "(idle)" }, "."]);
112
+ if (running.length) stop.push([{ b: count(running.length, "background task") }, `: ${tasksLine({ running }, sessionId)}`]);
113
+ if (stop.length) groups.push({ key: "stop", label: "Stopped first", lines: stop });
114
+
115
+ const stays = [];
116
+ const left = leftDelegates(choice);
117
+ if (left.n) {
118
+ const one = left.n === 1;
119
+ const under = left.under ? `, with ${one ? "its" : "their"} ${count(left.under, "delegate")}` : "";
120
+ const named = left.running.length ? ` ${namesLine(left.running, sessions)}` : "";
121
+ stays.push([{ b: `${count(left.n, "running delegate")}${under}` },
122
+ `:${named} ${one ? "keeps" : "keep"} running on ${one ? "its" : "their"} own, without a parent.`]);
123
+ }
124
+ const n = tasksCount(unsure);
125
+ if (n) {
126
+ stays.push([{ b: `${count(n, "task")} chi can't verify` },
127
+ `: ${tasksLine(unsure, sessionId)}. chi leaves ${n === 1 ? "it as it is" : "them as they are"}.`]);
128
+ }
129
+ if (stays.length) groups.push({ key: "stays", label: "Stays", lines: stays });
130
+ return groups;
131
+ }
132
+
133
+ // The button's words (decision 3): it names the running work it ends (the
134
+ // tasks, a turn); an idle worker is only a row. +op+: "delete" or
135
+ // "archive"; +object+: what a chain's choice deletes ("this link", "the
136
+ // whole chain"), "" for one session; +sessions+: how many sessions the tap
137
+ // takes (" · 3 sessions" from 2).
138
+ export function buttonWords(choice, { op = "delete", object = "", sessions = 1 } = {}) {
139
+ const tasks = taskParts(choice?.tasks).running.length;
140
+ const turns = turnCount(choice?.worker);
141
+ const target = object ? `${op} ${object}` : op;
142
+ let words;
143
+ if (object) {
144
+ const ends = [turns && (turns === 1 ? "the turn" : count(turns, "turn")), tasks && count(tasks, "task")].filter(Boolean);
145
+ words = ends.length ? `Stop ${ends.join(" and ")} and ${target}` : capital(target);
146
+ } else if (tasks && turns) {
147
+ words = `Stop the turn and tasks and ${target}`;
148
+ } else if (tasks) {
149
+ words = `Stop ${tasks === 1 ? "it" : "them"} and ${target}`;
150
+ } else if (turns) {
151
+ words = `Stop the turn and ${target}`;
152
+ } else {
153
+ words = capital(target);
154
+ }
155
+ return sessions > 1 ? `${words} · ${count(sessions, "session")}` : words;
156
+ }
157
+
158
+ // Whether a tap stops running work first: the sheet then says "Stopping…".
159
+ export function stopsFirst(choice) {
160
+ return taskParts(choice?.tasks).running.length > 0 || turnCount(choice?.worker) > 0;
161
+ }
162
+
163
+ // A refusal the plan carries (a one-turn run, a schedule, a continue), or a
164
+ // plan that can't be read: why, and only Close.
165
+ // @return {title, sub, close: true}
166
+ export function cantModel(verb, id, refusal) {
167
+ return { title: `Can't ${verb} ${short(id)} now`, sub: sentence(refusal?.message) || "Not now.", close: true };
168
+ }
169
+
170
+ // The sheet for a session in no chain, from its plan's +link+.
171
+ // @return {title, groups, button, stops, foot, tasks} | cantModel's
172
+ export function sessionSheetModel(session, plan, sessions = []) {
173
+ const id = session?.id ?? plan?.session_id;
174
+ const link = plan?.link || {};
175
+ if (link.refusal && link.refusal.reason !== "delegate_unmovable") return cantModel("delete", id, link.refusal);
176
+ return {
177
+ title: sheetTitle("Delete", id, session),
178
+ groups: sheetGroups(link, { sessions, sessionId: id }),
179
+ button: buttonWords(link, { sessions: 1 + goneDelegates(link).length }),
180
+ stops: stopsFirst(link),
181
+ foot: UNDONE,
182
+ tasks: link.tasks || null,
183
+ };
184
+ }
185
+
186
+ // A chain's choice's own lines (the mock-up's case 8): what is stopped first
187
+ // and what stays, after its first lines. [{cls, text}]
188
+ export function choiceTail(choice, sessionId = null) {
189
+ const lines = [];
190
+ const { running, unsure } = taskParts(choice?.tasks);
191
+ const stop = [turnCount(choice?.worker) && (turnCount(choice.worker) === 1 ? "its running turn" : count(turnCount(choice.worker), "running turn")),
192
+ running.length && tasksLine({ running }, sessionId)].filter(Boolean);
193
+ if (stop.length) lines.push({ cls: "stop", text: `Stopped first: ${stop.join(" · ")}` });
194
+ const left = leftDelegates(choice);
195
+ const stays = [];
196
+ if (left.n) {
197
+ const one = left.n === 1;
198
+ stays.push(`${count(left.n, "running delegate")}${left.under ? `, with ${one ? "its" : "their"} ${count(left.under, "delegate")}` : ""}, on ${one ? "its" : "their"} own`);
199
+ }
200
+ const n = tasksCount(unsure);
201
+ if (n) stays.push(`${count(n, "task")} chi can't verify (${tasksLine(unsure, sessionId)})`);
202
+ if (stays.length) lines.push({ cls: "stays", text: `Stays: ${stays.join("; ")}.` });
203
+ return lines;
204
+ }
205
+
206
+ // Archive's ask, from its 409 (+refusal+: the error, its body the route's):
207
+ // tasks_running is the sheet in Archive's words (Hidden, Stopped first, and
208
+ // Stays for a task chi can't verify); any other refusal is Can't archive.
209
+ // @return {title, groups, button, stops, foot, tasks, warn: true} | cantModel's
210
+ export function archiveSheetModel(session, refusal, sessions = []) {
211
+ const id = session?.id ?? refusal?.body?.session_id;
212
+ if (refusal?.code !== "tasks_running") return cantModel("archive", id, refusal);
213
+ const body = refusal.body || {};
214
+ const tasks = body.tasks || null;
215
+ const others = Math.max(0, (Number.isInteger(body.sessions) ? body.sessions : 1) - 1);
216
+ const hidden = others
217
+ ? ["It and its ", { b: count(others, "delegate") }, " leave the lists and are kept for good."]
218
+ : ["It leaves the lists and is kept for good."];
219
+ const choice = { tasks };
220
+ const groups = [{ key: "hidden", label: "Hidden", lines: [hidden] },
221
+ ...sheetGroups(choice, { sessions, sessionId: id }).filter((g) => g.key !== "goes")];
222
+ return {
223
+ title: sheetTitle("Archive", id, session),
224
+ groups,
225
+ button: buttonWords(choice, { op: "archive" }),
226
+ stops: stopsFirst(choice),
227
+ foot: `Undo brings the ${others ? "sessions" : "session"} back. Stopped tasks stay stopped.`,
228
+ tasks,
229
+ warn: true,
230
+ };
231
+ }
232
+
233
+ // The delegates a delete left that still run: +left_running+ is the running
234
+ // ones with their subtrees, so the stopped ones the plan's choice lists
235
+ // (+delegates.leave+, running false) stay with theirs, unsaid.
236
+ function stillRunning(result, choice) {
237
+ const leave = choice?.delegates?.leave;
238
+ const stopped = new Set(Array.isArray(leave) ? leave.filter((d) => d.running === false).map((d) => d.id) : []);
239
+ return (result.left_running || []).filter((sid) => !stopped.has(sid));
240
+ }
241
+
242
+ // The toast after a delete (the mock-up's case 14): what went, what was
243
+ // stopped, what stays. +which+: "this" or "chain"; +result+: the route's
244
+ // 200; +plan+: the sheet's. +back+: a session to offer opening (the link
245
+ // that came back, else a delegate left running), or null; +sticky+ true for
246
+ // a chain delete that kept a link part-way. +withTasks+ false
247
+ // leaves the stopped tasks out (an older cached caller adds them itself).
248
+ // @return {text, back, sticky?}
249
+ export function deleteToast(which, result, plan, id, { withTasks = true } = {}) {
250
+ const tasks = withTasks ? tasksStoppedSuffix(result) : "";
251
+ const running = stillRunning(result, which === "chain" ? plan?.chain : plan?.link);
252
+ const keeps = running.length === 1
253
+ ? ` · ${short(running[0])} keeps running`
254
+ : running.length ? ` · ${count(running.length, "delegate")} keep running` : "";
255
+ if (which === "chain") {
256
+ const left = (result.left || []).length;
257
+ const links = Math.max(0, (plan?.chain?.links ?? 0) - left);
258
+ const delegates = Math.max(0, (result.deleted || []).length - links);
259
+ let text = `Deleted the chain: ${count(links, "session")}${delegates ? ` and ${count(delegates, "delegate")}` : ""}${tasks}${keeps}.`;
260
+ const back = running.length === 1 ? running[0] : null;
261
+ // A link kept part-way (the server's race): its reason stays until closed.
262
+ if (left) return { text: `${text} ${count(left, "link")} kept: ${result.refusal}`, back, sticky: true };
263
+ return { text, back };
264
+ }
265
+ const back = (result.unarchived || [])[0] || null;
266
+ if (back) {
267
+ // The sheet's count (each moved delegate with its subtree) when it had one.
268
+ const moved = (result.moved_back || []).length ? (plan?.link?.moved || result.moved_back.length) : 0;
269
+ const took = [moved && count(moved, "delegate"), plan?.link?.notes && count(plan.link.notes, "note")].filter(Boolean);
270
+ return { text: `Deleted ${short(id)}${tasks}${keeps}. ${short(back)} is back${took.length ? `, with ${took.join(" and ")}` : ""}.`, back };
271
+ }
272
+ const delegates = (result.deleted || []).filter((sid) => sid !== id).length;
273
+ return { text: `Deleted ${short(id)}${delegates ? ` and ${count(delegates, "delegate")}` : ""}${tasks}${keeps}`,
274
+ back: running.length === 1 ? running[0] : null };
275
+ }
@@ -1,10 +1,9 @@
1
1
  // A session's background tasks a delete or an archive was refused for
2
2
  // (the 409 tasks_running, SessionManager::RunningTasks), in the page's
3
- // words: their one line, the second confirm, the toast's suffix after a
4
- // stop. DOM-free (no lit-html): format.js-style text helpers, a module of
3
+ // words: their one line and the toast's suffix after a stop (the delete
4
+ // sheet, removal_sheet_model.js, names them with tasksLine). DOM-free (no lit-html): format.js-style text helpers, a module of
5
5
  // their own (docs/internals/web-frontend.md, "New exports go in new modules").
6
- // session_actions.js asks the confirm; delete_sheet.js' refusal view and
7
- // stop_sheet.js' cut share NAMED_MAX and cutCommand.
6
+ // The delete sheet and stop_sheet.js' cut share NAMED_MAX and cutCommand.
8
7
 
9
8
  // At most this many tasks (or holds of a kind) named in a line; the rest
10
9
  // are one "+N more" (stop_sheet.js MAX_NAMED, RunningTasks::MAX_NAMED).
@@ -51,6 +50,9 @@ function taskEntries(listing) {
51
50
  // The second confirm of a delete or an archive refused for background tasks
52
51
  // still running (409 tasks_running): which, and whether to stop them and
53
52
  // +verb+ ("delete" / "archive") the session. +listing+ is the 409's tasks.
53
+ // Unused since the delete sheet; kept while an older cached
54
+ // session_actions.js may import it (web-frontend.md); goes at the next
55
+ // release.
54
56
  export function tasksConfirmText(id, listing, verb) {
55
57
  const n = tasksCount(listing);
56
58
  const one = n === 1;