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
@@ -1,84 +1,83 @@
1
- // Deleting a link of a session chain (docs/sessions.md, Session chains →
2
- // Deleting a link): Delete on a chained session asks which, instead of the
3
- // browser's confirm. "Delete this link" (first, the default) undoes the
4
- // newest link's continue or splits the chain at a middle one; "Delete the
5
- // whole chain" takes every link. Each says what it leaves behind.
1
+ // The delete sheet (docs/sessions.md, Deleting a session; Session chains →
2
+ // Deleting a link): Delete on any session says, before anything happens,
3
+ // what goes, what is stopped first and what stays, with one button that
4
+ // names the outcome (removal_sheet_model.js has the words). A chained
5
+ // session keeps its two choices: "Delete this link" (first, the default)
6
+ // undoes the newest link's continue or splits the chain at a middle one;
7
+ // "Delete the whole chain" takes every link; each carries its own rows and
8
+ // button words. Archive asks in the same sheet when its 409 says background
9
+ // tasks still run, or why it can't happen now.
6
10
  //
7
11
  // The sheet's words come from GET /api/sessions/:id/delete_plan, the plan
8
12
  // and refusals the server's delete itself runs (SessionChain::Delete::
9
- // Preview), fetched as the sheet opens and only for a chained session: a
10
- // session in no chain keeps today's confirm (session_actions.js). The
11
- // confirmed digest is checked by the delete; a changed plan is re-read and
12
- // shown for a fresh confirmation.
13
+ // Preview), fetched as the sheet opens. The tap sends the shown choice's
14
+ // digest (expect) and, when the choice lists any task, stop_tasks with the
15
+ // running ones' ids: the server stops only those. A changed plan (409
16
+ // plan_changed) or a task that started since (409 tasks_running) is re-read
17
+ // and shown for a fresh tap.
13
18
  //
14
19
  // Where it is drawn (a host): the ⋯ More panel turns into it, with ‹ More to
15
- // go back (more_sheet.js' subview); a card's ✕ opens it at the card, on
16
- // chip_popover.js' shell (createDeleteSheet): a bottom sheet on a phone, a
17
- // popover on a wider window. Pure model and templates plus createDeleteSheet
18
- // and runDeleteFlow, so the specs run them under node --test.
20
+ // go back (more_sheet.js' subview); a card's ✕ (or archive) opens it at the
21
+ // card, on chip_popover.js' shell (createDeleteSheet): a bottom sheet on a
22
+ // phone, a popover on a wider window. Templates plus createDeleteSheet and
23
+ // runDeleteFlow, so the specs run them under node --test.
19
24
 
20
25
  import { html, nothing, render } from "./vendor/lit-html.js";
21
- import { createChipPopover } from "./chip_popover.js";
22
- import { cardName, clip, normalize } from "./format.js";
23
- import { tasksCount, tasksLine } from "./running_tasks.js";
26
+ import { createChipPopover, SHEET_TALL } from "./chip_popover.js";
27
+ import { archiveSheetModel, buttonWords, cantModel, choiceTail, deleteToast as modelToast, sessionSheetModel, sheetTitle,
28
+ stopTasksOptions, stopsFirst } from "./removal_sheet_model.js";
29
+
30
+ // The toast after a delete, for an older cached session_actions.js (0.182.0),
31
+ // which adds the stopped tasks to it itself: without them, so they aren't
32
+ // said twice. This session_actions.js imports removal_sheet_model.js'. Kept
33
+ // until the next release (web-frontend.md, removing an export).
34
+ export function deleteToast(which, result, plan, id) {
35
+ return modelToast(which, result, plan, id, { withTasks: false });
36
+ }
24
37
 
25
38
  const short = (id) => String(id ?? "").slice(0, 8);
26
39
  const count = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
27
40
 
28
41
  // A session is in a chain when it continues a link, or a listed one
29
- // continues it (the page's list holds archived links too).
42
+ // continues it (the page's list holds archived links too). Unused since every
43
+ // delete reads its plan; kept while an older cached session_actions.js may
44
+ // import it (web-frontend.md, removing an export).
30
45
  export function isChained(session, list = []) {
31
46
  if (!session) return false;
32
47
  if (session.continues) return true;
33
48
  return list.some((s) => s.continues === session.id);
34
49
  }
35
50
 
36
- // The session's name as today's confirm says it (format.js cardName).
37
- function sessionName(session) {
38
- const name = normalize(session ? cardName(session) : "");
39
- return clip(name, 41);
40
- }
41
-
42
- // What this link's own delegates do (D7): stopped ones go, running ones stay.
43
- function delegatesWords(deletes, running, { lead }) {
44
- const parts = [];
45
- if (deletes) parts.push(`${lead}${count(deletes, "stopped delegate")}`);
46
- const goes = parts.length ? `${parts.join("")}` : "";
47
- const stays = running ? `${count(running, "running delegate")} ${running === 1 ? "keeps" : "keep"} running on ${running === 1 ? "its" : "their"} own` : "";
48
- return { goes, stays };
49
- }
50
-
51
- function thisLinkLines(link) {
52
- const { goes, stays } = delegatesWords(link.deletes, link.left_running, { lead: "its " });
51
+ // The link's own first lines (what comes back, how the chain splits, what
52
+ // goes), then what is stopped first and what stays (choiceTail).
53
+ function thisLinkLines(link, id) {
54
+ const goes = { cls: "dim", text: `Goes: its turns${link.deletes ? ` and its ${count(link.deletes, "stopped delegate")}` : ""}.` };
55
+ let main;
53
56
  if (link.previous_id) {
54
57
  const took = [link.moved && count(link.moved, "delegate"), link.notes && count(link.notes, "unread note")].filter(Boolean);
55
- const main = `Undoes the continue: ${short(link.previous_id)} comes back to the lists (not started)` +
56
- (took.length ? `, with what this link took over from it — its ${took.join(" and ")}.` : ".");
57
- const own = [goes ? `its turns and ${goes}` : "its turns"].join("");
58
- return [main, `What this link did itself goes: ${own}.${stays ? ` Its ${stays}.` : ""}`];
59
- }
60
- let main;
61
- if (link.next_id) {
58
+ main = `Undoes the continue: ${short(link.previous_id)} comes back to the lists (not started)` +
59
+ (took.length ? `, with its ${took.join(" and ")}.` : ".");
60
+ } else if (link.next_id) {
62
61
  const earlier = link.earlier ? `${count(link.earlier, "earlier link")} ${link.earlier === 1 ? "stays" : "stay"} archived, and ` : "";
63
- main = `The chain splits: ${earlier}${short(link.next_id)} goes on as a chain of its own.`;
62
+ main = `The chain splits: ${earlier}${short(link.next_id)} goes on as a chain of its own. Nothing is undone.`;
64
63
  } else {
65
- main = "The earlier links stay as they are.";
64
+ main = "The earlier links stay as they are. Nothing is undone.";
66
65
  }
67
- const rest = [goes && `${goes.charAt(0).toUpperCase()}${goes.slice(1)} ${link.deletes === 1 ? "goes" : "go"} with it.`,
68
- stays && `${stays.charAt(0).toUpperCase()}${stays.slice(1)}.`].filter(Boolean).join(" ");
69
- return [main, `Nothing is undone.${rest ? ` ${rest}` : ""}`];
66
+ return [{ cls: "", text: main }, goes, ...choiceTail(link, id)];
70
67
  }
71
68
 
72
- function chainLines(plan) {
69
+ function chainLines(plan, id) {
73
70
  const { chain } = plan;
74
71
  const delegates = chain.deletes ? ` and their ${count(chain.deletes, "stopped delegate")}` : "";
75
- const running = chain.left_running
76
- ? ` ${count(chain.left_running, "running delegate")} ${chain.left_running === 1 ? "keeps" : "keep"} running on ${chain.left_running === 1 ? "its" : "their"} own.`
77
- : "";
78
- const lines = [plan.cut_off
79
- ? `These ${count(chain.links, "link")}${delegates ? `, ${delegates.trim()}` : ""}.${running}`
80
- : `All ${count(chain.links, "link")}${delegates}.${running}`];
81
- return lines;
72
+ const text = plan.cut_off ? `Goes: these ${count(chain.links, "link")}${delegates}.` : `Goes: all ${count(chain.links, "link")}${delegates}.`;
73
+ return [{ cls: "dim", text }, ...choiceTail(chain, id)];
74
+ }
75
+
76
+ // The stopped delegates a choice deletes with it (its ids; an older plan's
77
+ // count): its button counts them (case 2's rule, every session the tap takes).
78
+ function stoppedDelegates(choice) {
79
+ const ids = choice?.delegates?.delete;
80
+ return Array.isArray(ids) ? ids.length : choice?.deletes || 0;
82
81
  }
83
82
 
84
83
  // Why a choice can't be taken now, in the sheet's words; a schedule says it
@@ -89,41 +88,38 @@ function refusedWhy(refusal) {
89
88
  return refusal.message || "Not now.";
90
89
  }
91
90
 
92
- // The sheet's model for +session+ from its delete plan (the route's JSON).
93
- // @return {title, sub, banner, choices: [{act, label, lines, warn, disabled, why, primary}], foot}
94
- export function deleteChoices(session, plan) {
91
+ // The sheet's model for +session+ from its delete plan (the route's JSON);
92
+ // +sessions+ the page's list (it names the delegates).
93
+ // A session in no chain: removal_sheet_model.js sessionSheetModel ({title,
94
+ // groups, button, stops, foot, tasks}, or the Can't delete view {title, sub,
95
+ // close}). A chained one: {title, sub, banner, choices: [{act, label, lines,
96
+ // warn, disabled, why, primary, stops, tasks}], foot}.
97
+ export function deleteChoices(session, plan, sessions = []) {
95
98
  const id = session?.id ?? plan.session_id;
96
- const name = sessionName(session);
99
+ if (!plan.chained) return sessionSheetModel(session ?? { id }, plan, sessions);
97
100
  const link = plan.link || {};
98
101
  const chain = plan.chain || {};
99
102
  // The chain's words first: they say the schedule runs this chain.
100
103
  const scheduled = [chain.refusal, link.refusal].find((r) => r && /scheduled$/.test(r.reason));
101
104
  return {
102
- title: `Delete ${short(id)}${name ? ` — "${name}"` : ""}?`,
105
+ title: sheetTitle("Delete", id, session),
103
106
  sub: `It is link ${plan.position} of ${plan.size} of its chain. This can't be undone.`,
104
107
  banner: scheduled ? `${scheduled.message.charAt(0).toUpperCase()}${scheduled.message.slice(1)}.` : null,
105
108
  choices: [
106
- { act: "this", label: "Delete this link", lines: thisLinkLines(link), primary: true,
107
- disabled: !!link.refusal && link.refusal.reason !== "delegate_unmovable", why: refusedWhy(link.refusal) },
108
- { act: "chain", label: `Delete the whole chain · ${count(chain.links, "session")}`, lines: chainLines(plan),
109
+ { act: "this", label: buttonWords(link, { object: "this link", sessions: 1 + stoppedDelegates(link) }), lines: thisLinkLines(link, id), primary: true,
110
+ disabled: !!link.refusal && link.refusal.reason !== "delegate_unmovable", why: refusedWhy(link.refusal),
111
+ stops: stopsFirst(link), tasks: link.tasks || null },
112
+ { act: "chain", label: buttonWords(chain, { object: "the whole chain", sessions: (chain.links || 0) + stoppedDelegates(chain) }), lines: chainLines(plan, id),
109
113
  warn: plan.cut_off ? "Earlier links, cut off by a deleted link, are kept (archived)." : null,
110
- disabled: !!chain.refusal, why: refusedWhy(chain.refusal) },
114
+ disabled: !!chain.refusal, why: refusedWhy(chain.refusal), stops: stopsFirst(chain), tasks: chain.tasks || null },
111
115
  ],
112
116
  foot: "Running workers are stopped first.",
113
117
  };
114
118
  }
115
119
 
116
- function unchainedChoices(session, plan) {
117
- const id = session?.id ?? plan?.session_id;
118
- const name = sessionName(session);
119
- return {
120
- title: `Delete ${short(id)}${name ? ` — "${name}"` : ""}?`,
121
- sub: "This session is no longer in a chain. This can't be undone.",
122
- banner: null,
123
- choices: [{ act: "this", label: "Delete this session", lines: ["Its turns and session data will be permanently deleted."],
124
- primary: true }],
125
- foot: "This can't be undone.",
126
- };
120
+ function lineTemplate(line, i) {
121
+ if (typeof line === "string") return html`<span class=${i ? "ds-line dim" : "ds-line"}>${line}</span>`;
122
+ return html`<span class=${line.cls ? `ds-line ${line.cls}` : "ds-line"}>${line.text}</span>`;
127
123
  }
128
124
 
129
125
  function choiceTemplate(choice) {
@@ -133,7 +129,7 @@ function choiceTemplate(choice) {
133
129
  ><span class="ds-label">${choice.label}</span><span class="ds-line">${choice.why}</span></button>`;
134
130
  }
135
131
  return html`<button type="button" class=${cls} data-act=${`del:${choice.act}`}
136
- ><span class="ds-label">${choice.label}</span>${choice.lines.map((line, i) => html`<span class=${i ? "ds-line dim" : "ds-line"}>${line}</span>`)
132
+ ><span class="ds-label">${choice.label}</span>${choice.lines.map(lineTemplate)
137
133
  }${choice.warn ? html`<span class="ds-line warn">${choice.warn}</span>` : nothing}</button>`;
138
134
  }
139
135
 
@@ -145,9 +141,42 @@ function headTemplate(back) {
145
141
  : html`<div class="ds-head"><span></span><button type="button" class="ctx-pop-close" data-act="del:cancel" aria-label="Close">×</button></div>`;
146
142
  }
147
143
 
148
- // The choices (a lit-html template). +busy+: a delete under way (every
149
- // button off); +back+: drawn in the More panel.
150
- export function deleteSheetTemplate(model, { back = false, busy = false, notice = null } = {}) {
144
+ // A row's line: its parts (a string, {b} bold, {dim}).
145
+ function partsTemplate(parts) {
146
+ return parts.map((part) => {
147
+ if (typeof part === "string") return part;
148
+ if (part.b) return html`<b>${part.b}</b>`;
149
+ return html`<span class="dim">${part.dim}</span>`;
150
+ });
151
+ }
152
+
153
+ function groupsTemplate(groups) {
154
+ return html`<ul class="ds-groups">${groups.map((g) => html`<li class="ds-group" data-group=${g.key}
155
+ ><span class=${`ds-k ${g.key}`}>${g.label}</span><span class="ds-v">${g.lines.map((line, i) => html`${i ? html`<br>` : nothing}${partsTemplate(line)}`)}</span></li>`)}</ul>`;
156
+ }
157
+
158
+ // One session's sheet (a session in no chain, archive's ask) or the Can't …
159
+ // view. +busy+: the tap under way (its button says Stopping… / Deleting…).
160
+ function singleTemplate(model, { back, busy, notice, act }) {
161
+ const going = model.warn ? "Archiving…" : "Deleting…";
162
+ return html`<div class=${`delete-sheet${busy ? " busy" : ""}`}>${headTemplate(back)}
163
+ <div class="ds-title">${model.title}</div>
164
+ ${model.sub ? html`<div class="ds-sub">${model.sub}</div>` : nothing}
165
+ ${notice ? html`<div class="ds-banner">${notice}</div>` : nothing}
166
+ ${model.groups ? groupsTemplate(model.groups) : nothing}
167
+ <div class="ds-acts">${model.close ? nothing : html`<button type="button" class=${`ds-go ${model.warn ? "warn" : "danger"}`}
168
+ data-act=${`del:${act}`} ?disabled=${busy}>${busy ? (model.stops ? "Stopping…" : going) : model.button}</button>`
169
+ }<button type="button" class="ds-cancel" data-act="del:cancel" ?disabled=${busy}>${model.close ? "Close" : "Cancel"}</button></div>
170
+ ${model.foot ? html`<div class="ds-foot"><span class="ds-note">${model.foot}</span></div>` : nothing}
171
+ </div>`;
172
+ }
173
+
174
+ // The sheet (a lit-html template) for deleteChoices' model, or archive's.
175
+ // +busy+: a delete under way (every button off); +back+: drawn in the More
176
+ // panel; +notice+: a banner above (the plan changed); +act+: the one
177
+ // button's data-act name ("this"; "archive" for archive's).
178
+ export function deleteSheetTemplate(model, { back = false, busy = false, notice = null, act = "this", stopping = false } = {}) {
179
+ if (!model.choices) return singleTemplate(model, { back, busy, notice, act });
151
180
  const allOff = model.choices.every((c) => c.disabled);
152
181
  return html`<div class=${`delete-sheet${busy ? " busy" : ""}`}>${headTemplate(back)}
153
182
  <div class="ds-title">${model.title}</div>
@@ -155,8 +184,8 @@ export function deleteSheetTemplate(model, { back = false, busy = false, notice
155
184
  ${notice ? html`<div class="ds-banner">${notice}</div>` : nothing}
156
185
  ${model.banner ? html`<div class="ds-banner">${model.banner}</div>` : nothing}
157
186
  <div class="ds-choices" ?inert=${busy}>${model.choices.map(choiceTemplate)}</div>
158
- <div class="ds-foot">${allOff ? html`<span></span>` : html`<span class="ds-note">${busy ? "Deleting…" : model.foot}</span>`}
159
- <button type="button" class="ds-cancel" data-act="del:cancel" ?disabled=${busy}>${allOff ? "Close" : "Cancel"}</button></div>
187
+ <div class="ds-acts"><button type="button" class="ds-cancel" data-act="del:cancel" ?disabled=${busy}>${allOff ? "Close" : "Cancel"}</button></div>
188
+ ${allOff ? nothing : html`<div class="ds-foot"><span class="ds-note">${busy ? (stopping ? "Stopping…" : "Deleting…") : model.foot}</span></div>`}
160
189
  </div>`;
161
190
  }
162
191
 
@@ -167,22 +196,10 @@ export function loadingTemplate({ back = false } = {}) {
167
196
 
168
197
  // A refused delete, in the sheet: a moved delegate that can't go back
169
198
  // (delegate_unmovable: "Stop its worker, then delete" only when the page
170
- // can stop it, not a one-turn run's), background tasks the delete takes
171
- // still running (tasks_running: "Stop them and delete"), or any other
172
- // refusal's own words.
173
- // @param refusal {reason, message, ids, stoppable, tasks, sessionId}
199
+ // can stop it, not a one-turn run's), or any other refusal's own words.
200
+ // @param refusal {reason, message, ids, stoppable, sessionId}
174
201
  // @param previousId the link the delegate would go back to
175
202
  export function refusalModel(refusal, previousId = null) {
176
- if (refusal?.reason === "tasks_running") {
177
- const n = tasksCount(refusal.tasks);
178
- return {
179
- title: "Background tasks still running",
180
- text: `${count(n, "background task")} this delete takes ${n === 1 ? "is" : "are"} still running: ` +
181
- `${tasksLine(refusal.tasks, refusal.sessionId)}. Nothing was deleted.`,
182
- stop: { label: n === 1 ? "Stop it and delete" : "Stop them and delete",
183
- line: `${n === 1 ? "It is" : "They are"} stopped (TERM, then KILL after 3 s), then the session goes.` },
184
- };
185
- }
186
203
  if (refusal?.reason === "delegate_unmovable") {
187
204
  const id = (refusal.ids || [])[0];
188
205
  const back = previousId ? short(previousId) : "the previous link";
@@ -207,33 +224,10 @@ export function refusalTemplate(model, { back = false } = {}) {
207
224
  <div class="ds-sub">${model.text}</div>
208
225
  ${model.stop ? html`<div class="ds-choices"><button type="button" class="ds-choice primary" data-act="del:stop"
209
226
  ><span class="ds-label">${model.stop.label}</span><span class="ds-line dim">${model.stop.line}</span></button></div>` : nothing}
210
- <div class="ds-foot"><span></span><button type="button" class="ds-cancel" data-act="del:cancel">${model.stop ? "Cancel" : "Close"}</button></div>
227
+ <div class="ds-acts"><button type="button" class="ds-cancel" data-act="del:cancel">${model.stop ? "Cancel" : "Close"}</button></div>
211
228
  </div>`;
212
229
  }
213
230
 
214
- // The toast after a delete (D1/D5's words). +which+: "this" or "chain";
215
- // +result+: the route's 200; +plan+: the sheet's.
216
- // @return {text, back} (back: the link to offer opening, or null)
217
- export function deleteToast(which, result, plan, id) {
218
- if (which === "chain") {
219
- const left = (result.left || []).length;
220
- const links = Math.max(0, (plan.chain?.links ?? 0) - left);
221
- const delegates = Math.max(0, (result.deleted || []).length - links);
222
- let text = `Deleted the chain: ${count(links, "session")}${delegates ? ` and ${count(delegates, "delegate")}` : ""}.`;
223
- const running = (result.left_running || []).length;
224
- if (running) text += ` ${count(running, "running delegate")} ${running === 1 ? "was" : "were"} left on ${running === 1 ? "its" : "their"} own.`;
225
- if (left) text += ` ${count(left, "link")} kept: ${result.refusal}`;
226
- return { text, back: null };
227
- }
228
- const back = (result.unarchived || [])[0] || null;
229
- if (!back) return { text: `Deleted ${short(id)}.`, back: null };
230
- // The sheet's count (each moved delegate with its subtree) when it had one.
231
- const moved = (result.moved_back || []).length ? (plan.link?.moved || result.moved_back.length) : 0;
232
- const took = [moved && count(moved, "delegate"),
233
- plan.link?.notes && count(plan.link.notes, "note")].filter(Boolean);
234
- return { text: `Deleted ${short(id)}. ${short(back)} is back${took.length ? `, with ${took.join(" and ")}` : ""}.`, back };
235
- }
236
-
237
231
  // The list after a delete: the deleted ids gone, the ones back in the lists
238
232
  // not archived (session_actions.js' markArchived's flip).
239
233
  export function listAfterDelete(list, result) {
@@ -242,82 +236,138 @@ export function listAfterDelete(list, result) {
242
236
  return list.filter((s) => !gone.has(s.id)).map((s) => (back.has(s.id) ? { ...s, archived: false } : s));
243
237
  }
244
238
 
239
+ const CHANGED = { delete: "What this deletes changed; check again.", archive: "What this archives changed; check again." };
240
+
245
241
  // The flow in a +host+ ({show(template), close(), back: whether it is the
246
- // More panel}): reads the plan, shows the choices, runs the one chosen, and
242
+ // More panel}): reads the plan, shows the sheet, runs the choice tapped, and
247
243
  // shows a refusal in place. +act+ is wired by the host to the returned
248
- // handler. Hooks: api {deletePlan, deleteSession, deleteChain, stopSession};
249
- // done(which, result, plan) after a delete; plain() when the plan says no
250
- // chain (today's confirm); failed(error) when the plan can't be read.
244
+ // handler. Hooks: api {deletePlan, deleteSession, deleteChain, stopSession;
245
+ // archive(id, opts) for +archive+}; done(which, result, plan) after a
246
+ // delete (which: "this", "chain", "archive"); +sessions+ the page's list
247
+ // (names). +archive+: archive's ask from its first 409 (+archive.refusal+):
248
+ // no plan is read, the button archives stopping the named tasks.
249
+ // failed(error): a plan that can't be read, said in the sheet too; or a tap
250
+ // refused after its sheet was closed, drawn nowhere.
251
251
  // @return {act(name)} the host's handler for its data-act="del:*"
252
- export function runDeleteFlow({ id, session, host, api, done, plain, failed }) {
252
+ export function runDeleteFlow({ id, session, host, api, done, failed = () => {}, sessions = [], archive = null }) {
253
253
  let plan = null;
254
254
  let model = null;
255
255
  let notice = null;
256
256
  let refusal = null;
257
257
  let busy = false;
258
+ let stopping = false;
258
259
  const back = !!host.back;
260
+ const op = archive ? "archive" : "delete";
259
261
  // Whether +host+ still shows this flow: another session's sheet opened in
260
262
  // the same shell since (a second card's ✕, the More panel on another
261
263
  // session) takes it, and this flow then draws and acts on nothing.
262
264
  const live = () => (host.live ? host.live() : true);
263
265
  const show = (tpl) => { if (live()) host.show(tpl); };
264
266
 
265
- const showChoices = () => show(deleteSheetTemplate(model, { back, busy, notice }));
267
+ const list = () => (typeof sessions === "function" ? sessions() : sessions);
268
+ const showSheet = () => show(deleteSheetTemplate(model, { back, busy, notice, stopping, act: archive ? "archive" : "this" }));
266
269
  const showRefusal = () => show(refusalTemplate(refusalModel(refusal, plan?.link?.previous_id), { back }));
270
+ // A plan that can't be read: why, in the sheet, and only Close.
271
+ const cant = (error) => {
272
+ busy = false;
273
+ model = cantModel(op, id, error);
274
+ notice = null;
275
+ showSheet();
276
+ failed(error);
277
+ };
267
278
 
268
- show(loadingTemplate({ back }));
269
- api.deletePlan(id).then((read) => {
270
- if (!live()) return;
271
- if (!read?.chained) { host.close(); plain(); return; }
272
- plan = read;
273
- model = deleteChoices(session, plan);
274
- showChoices();
275
- }, (error) => { if (live()) { host.close(); failed(error); } });
279
+ if (archive) {
280
+ model = archiveSheetModel(session ?? { id }, archive.refusal, list());
281
+ showSheet();
282
+ } else {
283
+ show(loadingTemplate({ back }));
284
+ api.deletePlan(id).then((read) => {
285
+ if (!live()) return;
286
+ plan = read;
287
+ model = deleteChoices(session, plan, list());
288
+ showSheet();
289
+ }, (error) => { if (live()) cant(error); });
290
+ }
276
291
 
277
292
  // The refusal as the delete's 409 says it; whether the page can stop a
278
293
  // moved delegate's worker is its +stoppable+, as the delete saw it.
279
- // A tasks_running refusal keeps its tasks and the choice it refused
280
- // (+which+), so "Stop them and delete" sends that choice again.
281
- function refused(error, which) {
294
+ function refused(error) {
282
295
  refusal = { reason: error.code, message: error.message, ids: error.body?.ids || [], stoppable: error.body?.stoppable === true,
283
- tasks: error.body?.tasks || null, sessionId: id, which };
296
+ sessionId: id };
284
297
  busy = false;
285
298
  showRefusal();
286
299
  }
287
300
 
288
- // +stopTasks+: the same choice and digest, the tasks stopped first.
289
- async function run(which, { stopTasks = false } = {}) {
301
+ // The choice tapped (+which+), what it shows: its digest and its tasks.
302
+ function chosen(which) {
303
+ if (!model) return null;
304
+ if (!model.choices) return model.close ? null : { tasks: model.tasks, stops: model.stops, digest: plan?.link?.digest };
305
+ const choice = model.choices.find((c) => c.act === which);
306
+ if (!choice || choice.disabled) return null;
307
+ return { tasks: choice.tasks, stops: choice.stops, digest: which === "chain" ? plan?.chain?.digest : plan?.link?.digest };
308
+ }
309
+
310
+ async function run(which) {
290
311
  if (busy || !live()) return;
312
+ const choice = chosen(which);
313
+ if (!choice) return;
291
314
  busy = true;
292
- showChoices();
315
+ stopping = !!choice.stops;
316
+ showSheet();
317
+ const tasks = stopTasksOptions(choice.tasks);
293
318
  try {
294
- const digest = which === "chain" ? plan?.chain?.digest : plan?.link?.digest;
295
- const opts = stopTasks ? { expect: digest, stopTasks: true } : { expect: digest };
296
- const result = which === "chain" ? await api.deleteChain(id, opts) : await api.deleteSession(id, opts);
319
+ let result;
320
+ if (archive) result = await api.archive(id, tasks);
321
+ else {
322
+ const opts = { expect: choice.digest, ...tasks };
323
+ result = which === "chain" ? await api.deleteChain(id, opts) : await api.deleteSession(id, opts);
324
+ }
297
325
  if (live()) host.close();
298
326
  done(which, result, plan);
299
327
  } catch (error) {
300
- if (error.code === "plan_changed") {
301
- await refreshPlan();
328
+ // The sheet was closed while the tap ran (×, ‹ More, Esc): nothing
329
+ // happened, and the caller says why (session_actions.js: a sticky toast).
330
+ if (!live()) {
331
+ busy = false;
332
+ failed(error);
302
333
  return;
303
334
  }
304
- refused(error, which);
335
+ if (error.code === "plan_changed" || error.code === "tasks_running") {
336
+ await refreshPlan(error);
337
+ return;
338
+ }
339
+ if (archive) {
340
+ busy = false;
341
+ model = archiveSheetModel(session ?? { id }, error, list());
342
+ notice = null;
343
+ showSheet();
344
+ return;
345
+ }
346
+ refused(error);
305
347
  }
306
348
  }
307
349
 
308
- async function refreshPlan() {
350
+ // The sheet as it is now, with "changed; check again" on top: the plan
351
+ // read again (a delete), or the 409's own tasks (an archive's).
352
+ async function refreshPlan(error) {
353
+ if (archive) {
354
+ busy = false;
355
+ model = archiveSheetModel(session ?? { id }, error, list());
356
+ notice = CHANGED.archive;
357
+ showSheet();
358
+ return;
359
+ }
309
360
  show(loadingTemplate({ back }));
310
361
  try {
311
362
  const read = await api.deletePlan(id);
312
363
  if (!live()) return;
313
364
  plan = read;
314
- model = read?.chained ? deleteChoices(session, plan) : unchainedChoices(session, plan);
315
- notice = "What this deletes changed; check again";
365
+ model = deleteChoices(session, plan, list());
366
+ notice = CHANGED.delete;
316
367
  busy = false;
317
- showChoices();
318
- } catch (error) {
319
- busy = false;
320
- if (live()) { host.close(); failed(error); }
368
+ showSheet();
369
+ } catch (readError) {
370
+ if (live()) cant(readError);
321
371
  }
322
372
  }
323
373
 
@@ -348,15 +398,14 @@ export function runDeleteFlow({ id, session, host, api, done, plain, failed }) {
348
398
  act(name) {
349
399
  if (!live()) return;
350
400
  if (name === "cancel") host.close();
351
- else if (name === "this" || name === "chain") run(name);
352
- else if (name === "stop" && refusal?.reason === "tasks_running") run(refusal.which, { stopTasks: true });
401
+ else if (name === "this" || name === "chain" || name === "archive") run(name);
353
402
  else if (name === "stop") stopThenDelete();
354
403
  },
355
404
  };
356
405
  }
357
406
 
358
- // A card's ✕: the flow on a popover of its own at the card (a bottom sheet
359
- // on a phone). One shell for every card: +openFor+ is the session it shows,
407
+ // A card's ✕ (or its archive): the flow on a popover of its own at the
408
+ // card (a bottom sheet on a phone); ⋯ when the open session's. One shell for every card: +openFor+ is the session it shows,
360
409
  // and only the newest host is live (a ✕ on another card while one's plan is
361
410
  // read takes the shell; the first flow's late answer draws nothing).
362
411
  // @return {host(anchorEl, id): a host for runDeleteFlow, close, isOpen, pop}
@@ -365,12 +414,21 @@ export function createDeleteSheet({ doc = globalThis.document, win = globalThis.
365
414
  let handler = null;
366
415
  let current = null;
367
416
  let openFor = null;
417
+ // Focus on the way out, so a stray Enter never deletes or archives: the ×
418
+ // while the plan is read, then Cancel once it shows (once per open).
419
+ let toCancel = false;
420
+ const settleFocus = () => {
421
+ if (!toCancel) return;
422
+ const cancel = shell.pop.querySelector(".ds-cancel:not([disabled])");
423
+ if (cancel) toCancel = false;
424
+ (cancel || shell.pop.querySelector(".ctx-pop-close"))?.focus();
425
+ };
368
426
  const shell = createChipPopover({
369
- id: "deleteSheet", className: "ctx-popover delete-pop", width: 420, el, anchor: "[data-del]", openers: "[data-del]",
370
- summary: () => view, sheet: true, label: "Delete the session?", doc, win,
427
+ id: "deleteSheet", className: "ctx-popover delete-pop", width: 420, el, anchor: "[data-del]", openers: "[data-del], #infoDeleteBtn",
428
+ summary: () => view, sheet: true, sheetShare: SHEET_TALL, label: "Delete or archive the session", doc, win,
371
429
  show: (tpl) => render(tpl, shell.pop),
372
- onOpen: () => shell.pop.querySelector(".ds-choice:not([disabled]), .ds-cancel")?.focus(),
373
- onClose: () => { view = null; handler = null; current = null; openFor = null; },
430
+ onOpen: () => { toCancel = true; settleFocus(); },
431
+ onClose: () => { view = null; handler = null; current = null; openFor = null; toCancel = false; },
374
432
  onAct: (act) => {
375
433
  const [what, name] = act.split(":");
376
434
  if (what === "del") handler?.act(name);
@@ -385,8 +443,10 @@ export function createDeleteSheet({ doc = globalThis.document, win = globalThis.
385
443
  show(tpl) {
386
444
  if (current !== me) return;
387
445
  view = tpl;
388
- if (shell.isOpen()) render(tpl, shell.pop);
389
- else shell.open(anchorEl);
446
+ if (shell.isOpen()) {
447
+ render(tpl, shell.pop);
448
+ settleFocus();
449
+ } else shell.open(anchorEl);
390
450
  },
391
451
  close() { if (current === me) shell.close(); },
392
452
  wire(next) { if (current === me) handler = next; },
@@ -0,0 +1,28 @@
1
+ // The drawn diagrams' wiring, so app.js holds one line of it (its size cap):
2
+ // the block host (block_host.js) with the picture viewer as its openPicture, and
3
+ // the viewer closed on a system theme change (the diagram behind is redrawn; the
4
+ // viewer holds the old picture). docs/internals/block-renderers.md.
5
+ //
6
+ // The viewer is made by app.js, not here: createSessionView reads it at once,
7
+ // before this runs (boot order). Its regions' layer (picture_regions.js) is made
8
+ // here and given to it; an older cached picture_viewer.js has no useLayer and
9
+ // shows pictures as before.
10
+ //
11
+ // A module of its own: static JS is cached at unversioned URLs.
12
+
13
+ import { createBlockHost } from "./block_host.js";
14
+ import { createRegionLayer } from "./picture_regions.js";
15
+
16
+ // @param roots the turn roots
17
+ // @param sessionId () => the open session's id
18
+ // @param drawers the core drawers (inline_widgets.js), asked before the bundles'
19
+ // @param renderers false for a page without the bundles' renderers (a participant's)
20
+ // @param pictures the picture viewer (picture_viewer.js createPictureViewer)
21
+ // @return {host, layer} the block host and the regions' layer
22
+ export function wireDiagrams({ roots, sessionId, drawers = [], renderers = true, pictures, win = window, doc = document, ...hostOpts }) {
23
+ const host = createBlockHost({ roots, sessionId, drawers, renderers, win, openPicture: (p, o) => pictures.open(p, o), ...hostOpts });
24
+ win.matchMedia?.("(prefers-color-scheme: dark)").addEventListener?.("change", () => pictures.close());
25
+ const layer = createRegionLayer({ doc, win });
26
+ pictures.useLayer?.(layer);
27
+ return { host, layer };
28
+ }
@@ -84,6 +84,9 @@ const DELETE_PREVIEW_CHARS = 40;
84
84
  // The confirm before deleting a session (the info bar's and a card's). The
85
85
  // list's owner can be stale (a worker idle-exits), so a worker is only
86
86
  // "stopped if it's still running", never promised.
87
+ // Unused since the delete sheet (delete_sheet.js); kept while an older
88
+ // cached session_actions.js may import it (web-frontend.md); goes at the
89
+ // next release.
87
90
  export function deleteConfirmText(session) {
88
91
  const n = normalize(cardName(session));
89
92
  const preview = clip(n, DELETE_PREVIEW_CHARS + 1);