samagotchi 0.173.0 → 0.174.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 (54) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +31 -1
  3. data/docs/architecture.md +2 -2
  4. data/docs/cli.md +9 -2
  5. data/docs/internals/background-tasks.md +0 -3
  6. data/docs/internals/participants.md +3 -1
  7. data/docs/internals/remote-sessions.md +8 -0
  8. data/docs/internals/web-frontend.md +24 -3
  9. data/docs/plugins.md +1 -3
  10. data/docs/scheduling.md +9 -3
  11. data/docs/sessions.md +3 -1
  12. data/docs/testing.md +6 -0
  13. data/lib/samagotchi/bridge.rb +1 -1
  14. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  15. data/lib/samagotchi/child_move.rb +11 -4
  16. data/lib/samagotchi/continued_from.rb +51 -0
  17. data/lib/samagotchi/engine.rb +1 -1
  18. data/lib/samagotchi/note_move.rb +11 -4
  19. data/lib/samagotchi/schedules.rb +13 -16
  20. data/lib/samagotchi/session_access/contract.rb +1 -0
  21. data/lib/samagotchi/session_access/local.rb +9 -1
  22. data/lib/samagotchi/session_access/remote.rb +26 -3
  23. data/lib/samagotchi/session_chain/delete.rb +405 -0
  24. data/lib/samagotchi/session_chain/delete_preview.rb +96 -0
  25. data/lib/samagotchi/session_chain/links.rb +38 -0
  26. data/lib/samagotchi/session_command_catalog.rb +2 -2
  27. data/lib/samagotchi/session_commands.rb +3 -13
  28. data/lib/samagotchi/session_continue.rb +51 -13
  29. data/lib/samagotchi/session_delete_command.rb +82 -17
  30. data/lib/samagotchi/session_manager/removal.rb +137 -31
  31. data/lib/samagotchi/session_stores.rb +2 -0
  32. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +2 -2
  33. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  34. data/lib/samagotchi/terminal_ui/exit_lines.rb +16 -0
  35. data/lib/samagotchi/terminal_ui/local_link.rb +7 -1
  36. data/lib/samagotchi/terminal_ui.rb +3 -3
  37. data/lib/samagotchi/testing/boundary.rb +0 -5
  38. data/lib/samagotchi/testing/bundle.rb +1 -1
  39. data/lib/samagotchi/tools/task_runtime.rb +0 -5
  40. data/lib/samagotchi/version.rb +1 -1
  41. data/lib/samagotchi/web/app.rb +7 -1
  42. data/lib/samagotchi/web/public/app.js +13 -3
  43. data/lib/samagotchi/web/public/chains.js +3 -3
  44. data/lib/samagotchi/web/public/data.js +12 -0
  45. data/lib/samagotchi/web/public/delete_sheet.js +344 -0
  46. data/lib/samagotchi/web/public/format.js +1 -1
  47. data/lib/samagotchi/web/public/index.html +27 -0
  48. data/lib/samagotchi/web/public/info_bar.js +3 -2
  49. data/lib/samagotchi/web/public/lists_view.js +2 -2
  50. data/lib/samagotchi/web/public/more_sheet.js +42 -5
  51. data/lib/samagotchi/web/public/session_actions.js +50 -6
  52. data/lib/samagotchi/web/server.rb +13 -13
  53. data/lib/samagotchi/web/session_control.rb +58 -5
  54. metadata +5 -1
@@ -347,6 +347,9 @@ module Samagotchi
347
347
  ["POST", %r{\A/api/push/presence\z}, :handle_push_presence, :owner],
348
348
  ["GET", %r{\A/api/block_renderers\z}, :handle_block_renderers, :owner],
349
349
  ["GET", %r{\A/api/block_renderers/([^/]+)/([^/]+)\z}, :handle_block_renderer_file, :owner],
350
+ # Before the plain /api/sessions/:id rows; query-only (force).
351
+ ["DELETE", %r{\A/api/sessions/([^/]+)/chain\z}, :handle_delete_chain, :owner, :session],
352
+ ["GET", %r{\A/api/sessions/([^/]+)/delete_plan\z}, :handle_delete_plan, :owner, :session],
350
353
  ["GET", %r{\A/api/sessions/([^/]+)\z}, :handle_show, :participant, :session],
351
354
  ["DELETE", %r{\A/api/sessions/([^/]+)\z}, :handle_delete, :owner, :session]
352
355
  ].freeze
@@ -1098,8 +1101,11 @@ module Samagotchi
1098
1101
  # web without it would ignore one and issue an unbound grant, so chi
1099
1102
  # --remote share --identity asks for this first.
1100
1103
  BOUND_FEATURE = "bound_grants"
1104
+ # DELETE …/chain, and the plain delete's revive and undo (D2/D5): chi
1105
+ # --remote sessions delete --chain asks for this first.
1106
+ CHAIN_DELETE_FEATURE = "chain_delete"
1101
1107
  INFO_FEATURES = ["dir", "newest_workers", SessionAccessRoutes::FEATURE, SessionAccessRoutes::ATTACH_FEATURE,
1102
- BOUND_FEATURE].freeze
1108
+ BOUND_FEATURE, CHAIN_DELETE_FEATURE].freeze
1103
1109
 
1104
1110
  # The models a new session can start on, spelled as chi spells them
1105
1111
  # elsewhere: bare for the default host (what default.model holds), and
@@ -8,6 +8,8 @@ import {
8
8
  stopSessionHolds,
9
9
  restartSession,
10
10
  deleteSession,
11
+ deleteChain,
12
+ deletePlan,
11
13
  archiveSession,
12
14
  unarchiveSession,
13
15
  sendCommand,
@@ -117,6 +119,7 @@ import { createUnqueue } from "./unqueue.js";
117
119
  import { createStartPage } from "./start_page.js";
118
120
  import { createSessionActions } from "./session_actions.js";
119
121
  import { createStopSheet } from "./stop_sheet.js";
122
+ import { createDeleteSheet } from "./delete_sheet.js";
120
123
  import { createVersionNotices } from "./version_notices.js";
121
124
  import { createRename } from "./session_rename.js";
122
125
  import { createSendTurn } from "./send_turn.js";
@@ -180,7 +183,10 @@ const settingsControl = viewer.can("session_controls") ? createSettingsControl({
180
183
  // ⋯ on the info bar, and its menu: the chips and buttons the row has no room for; and the bar's other buttons.
181
184
  const [continueBtn, archiveBtn, stopBtn, deleteBtn, moreBtn] = viewer.controls(
182
185
  ["#infoContinueBtn", "#infoArchiveBtn", "#infoStopBtn", "#infoDeleteBtn", "#infoMoreBtn"].map($), "session_controls");
183
- const moreSheet = moreBtn ? createMoreSheet({ el: $("#infoBar"), button: moreBtn, session: () => store.selected, hash: sessionHash }) : null;
186
+ // Delete on a chained session turns the panel into the delete sheet
187
+ // (session_actions.js deleteIn); sessionActions is made below.
188
+ const moreSheet = moreBtn ? createMoreSheet({ el: $("#infoBar"), button: moreBtn, session: () => store.selected, hash: sessionHash,
189
+ onDelete: (id, host) => sessionActions.deleteIn(id, host) }) : null;
184
190
  // The bar's fold (bar_fold.js): one row, what doesn't fit folded into ⋯. A
185
191
  // resize, the fonts or a zoom refolds it by itself: ⋯ follows on the redraw.
186
192
  const barFold = createBarFold({ barEl: $("#infoBar"), keysFor: barItemKeys, onChange: () => store.touch("infoBar") });
@@ -669,7 +675,7 @@ const lists = createListsView({
669
675
  eventsLive: () => !!eventsControl,
670
676
  refresh: () => refresh(),
671
677
  select: (id) => select(id),
672
- confirmDelete: (id) => confirmDelete(id),
678
+ confirmDelete: (id, options) => confirmDelete(id, options),
673
679
  setArchived: (id, archive) => setArchived(id, archive),
674
680
  archiveOne: (id, archive) => archiveOne(id, archive),
675
681
  updateSessionTitle: () => updateSessionTitle(),
@@ -693,12 +699,15 @@ const stopSheet = createStopSheet({
693
699
  stopSession: (id) => sessionActions.stopSelected(id),
694
700
  });
695
701
 
702
+ // A card's ✕ on a chained session: the delete sheet at the card (delete_sheet.js).
703
+ const deleteSheet = createDeleteSheet({ doc: document, win: window });
704
+
696
705
  const sessionActions = createSessionActions({
697
706
  selected: () => store.selected,
698
707
  store,
699
708
  sessions: () => store.sessions,
700
709
  setSessions: (list) => store.update({ sessions: list }),
701
- api: { continueSession, archiveSession, unarchiveSession, deleteSession, stopSession,
710
+ api: { continueSession, archiveSession, unarchiveSession, deleteSession, deleteChain, deletePlan, stopSession,
702
711
  sessionHolds, stopSessionHolds },
703
712
  eventsLive: () => !!eventsControl,
704
713
  refresh,
@@ -712,6 +721,7 @@ const sessionActions = createSessionActions({
712
721
  closeLiveStream: () => sessionSync.closeLive(),
713
722
  workerGone,
714
723
  stopSheet,
724
+ deleteSheet,
715
725
  });
716
726
  // The title's ✎: /title through the chips' path (session_rename.js), the
717
727
  // input over the title row on screen: the top bar's when it shows the
@@ -131,7 +131,7 @@ export function chainLinks(list, id, nexts = nextsOf(list), byId = new Map(list.
131
131
  // Whether the chain's oldest link the page holds still names a link it does
132
132
  // not: a schedule's prune (docs/scheduling.md, keep_links) or a delete. The
133
133
  // walk stops there, so every count comes from the surviving root, and the page
134
- // says "earlier links pruned" rather than linking to a session that is gone.
134
+ // says "earlier links deleted" rather than linking to a session that is gone.
135
135
  export function linksPruned(links, byId) {
136
136
  const root = links[0];
137
137
  return !!root?.continues && !byId.has(root.continues);
@@ -253,7 +253,7 @@ export function chainChipTemplate(f, { open = false } = {}) {
253
253
  const earlier = at;
254
254
  const later = links.length - 1 - at;
255
255
  const parts = [earlier ? `${earlier} earlier ${earlier === 1 ? "link" : "links"}` : "", later ? `${later} later` : "",
256
- f.chain.pruned ? "earlier links pruned" : ""].filter(Boolean);
256
+ f.chain.pruned ? "earlier links deleted" : ""].filter(Boolean);
257
257
  const title = `Session chain: link ${n} of ${links.length} (${parts.join(", ")}); open the list`;
258
258
  const liveT = live ? html`<span class="cc-live"> · <span class="live-dot" aria-hidden="true"></span>${live} live</span>` : nothing;
259
259
  const waitingT = waiting ? html` · <span class="cc-waiting">${waiting} waiting</span>` : nothing;
@@ -297,7 +297,7 @@ export function chainRowsTemplate(f, { activeId = null, now = Date.now() } = {})
297
297
  });
298
298
  const prunedRow = f?.chain?.pruned
299
299
  ? html`<div class="chain-row chain-pruned" role="listitem"><span class="cr-n" aria-hidden="true">↩</span>
300
- <span class="fr-preview">earlier links pruned</span></div>`
300
+ <span class="fr-preview">earlier links deleted</span></div>`
301
301
  : nothing;
302
302
  return html`<div class="family-rows chain-rows" role="list">${rows}${prunedRow}</div>`;
303
303
  }
@@ -285,6 +285,18 @@ export function deleteSession(id, opts = {}) {
285
285
  return api(`/api/sessions/${encodeURIComponent(id)}?force=true`, { method: "DELETE", ...opts });
286
286
  }
287
287
 
288
+ // Deletes every link of the session's chain with their delegates (running
289
+ // ones are left running); force: the links' workers are stopped first.
290
+ export function deleteChain(id, opts = {}) {
291
+ return api(`/api/sessions/${encodeURIComponent(id)}/chain?force=true`, { method: "DELETE", ...opts });
292
+ }
293
+
294
+ // What deleting a chained session would do, for the delete sheet
295
+ // (delete_sheet.js): the server's own plan and refusals, read now.
296
+ export function deletePlan(id, opts = {}) {
297
+ return api(`/api/sessions/${encodeURIComponent(id)}/delete_plan`, opts);
298
+ }
299
+
288
300
  // One EventSource listener per handler, named by the handler's key (the
289
301
  // event type), so a new event type needs only its handler. Each event's
290
302
  // JSON data goes to its handler (badJson(raw) when it doesn't parse);
@@ -0,0 +1,344 @@
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.
6
+ //
7
+ // The sheet's words come from GET /api/sessions/:id/delete_plan, the plan
8
+ // 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). A stale
11
+ // plan is fine: the delete refuses as it does, and the sheet shows that.
12
+ //
13
+ // Where it is drawn (a host): the ⋯ More panel turns into it, with ‹ More to
14
+ // go back (more_sheet.js' subview); a card's ✕ opens it at the card, on
15
+ // chip_popover.js' shell (createDeleteSheet): a bottom sheet on a phone, a
16
+ // popover on a wider window. Pure model and templates plus createDeleteSheet
17
+ // and runDeleteFlow, so the specs run them under node --test.
18
+
19
+ import { html, nothing, render } from "./vendor/lit-html.js";
20
+ import { createChipPopover } from "./chip_popover.js";
21
+ import { cardName, clip, normalize } from "./format.js";
22
+
23
+ const short = (id) => String(id ?? "").slice(0, 8);
24
+ const count = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
25
+
26
+ // A session is in a chain when it continues a link, or a listed one
27
+ // continues it (the page's list holds archived links too).
28
+ export function isChained(session, list = []) {
29
+ if (!session) return false;
30
+ if (session.continues) return true;
31
+ return list.some((s) => s.continues === session.id);
32
+ }
33
+
34
+ // The session's name as today's confirm says it (format.js cardName).
35
+ function sessionName(session) {
36
+ const name = normalize(session ? cardName(session) : "");
37
+ return clip(name, 41);
38
+ }
39
+
40
+ // What this link's own delegates do (D7): stopped ones go, running ones stay.
41
+ function delegatesWords(deletes, running, { lead }) {
42
+ const parts = [];
43
+ if (deletes) parts.push(`${lead}${count(deletes, "stopped delegate")}`);
44
+ const goes = parts.length ? `${parts.join("")}` : "";
45
+ const stays = running ? `${count(running, "running delegate")} ${running === 1 ? "keeps" : "keep"} running on ${running === 1 ? "its" : "their"} own` : "";
46
+ return { goes, stays };
47
+ }
48
+
49
+ function thisLinkLines(link) {
50
+ const { goes, stays } = delegatesWords(link.deletes, link.left_running, { lead: "its " });
51
+ if (link.previous_id) {
52
+ const took = [link.moved && count(link.moved, "delegate"), link.notes && count(link.notes, "unread note")].filter(Boolean);
53
+ const main = `Undoes the continue: ${short(link.previous_id)} comes back to the lists (not started)` +
54
+ (took.length ? `, with what this link took over from it — its ${took.join(" and ")}.` : ".");
55
+ const own = [goes ? `its turns and ${goes}` : "its turns"].join("");
56
+ return [main, `What this link did itself goes: ${own}.${stays ? ` Its ${stays}.` : ""}`];
57
+ }
58
+ let main;
59
+ if (link.next_id) {
60
+ const earlier = link.earlier ? `${count(link.earlier, "earlier link")} ${link.earlier === 1 ? "stays" : "stay"} archived, and ` : "";
61
+ main = `The chain splits: ${earlier}${short(link.next_id)} goes on as a chain of its own.`;
62
+ } else {
63
+ main = "The earlier links stay as they are.";
64
+ }
65
+ const rest = [goes && `${goes.charAt(0).toUpperCase()}${goes.slice(1)} ${link.deletes === 1 ? "goes" : "go"} with it.`,
66
+ stays && `${stays.charAt(0).toUpperCase()}${stays.slice(1)}.`].filter(Boolean).join(" ");
67
+ return [main, `Nothing is undone.${rest ? ` ${rest}` : ""}`];
68
+ }
69
+
70
+ function chainLines(plan) {
71
+ const { chain } = plan;
72
+ const delegates = chain.deletes ? ` and their ${count(chain.deletes, "stopped delegate")}` : "";
73
+ const running = chain.left_running
74
+ ? ` ${count(chain.left_running, "running delegate")} ${chain.left_running === 1 ? "keeps" : "keep"} running on ${chain.left_running === 1 ? "its" : "their"} own.`
75
+ : "";
76
+ const lines = [plan.cut_off
77
+ ? `These ${count(chain.links, "link")}${delegates ? `, ${delegates.trim()}` : ""}.${running}`
78
+ : `All ${count(chain.links, "link")}${delegates}.${running}`];
79
+ return lines;
80
+ }
81
+
82
+ // Why a choice can't be taken now, in the sheet's words; a schedule says it
83
+ // once, above both.
84
+ function refusedWhy(refusal) {
85
+ if (!refusal) return null;
86
+ if (refusal.reason === "scheduled" || refusal.reason === "chain_scheduled") return "Not while a schedule runs the chain.";
87
+ return refusal.message || "Not now.";
88
+ }
89
+
90
+ // The sheet's model for +session+ from its delete plan (the route's JSON).
91
+ // @return {title, sub, banner, choices: [{act, label, lines, warn, disabled, why, primary}], foot}
92
+ export function deleteChoices(session, plan) {
93
+ const id = session?.id ?? plan.session_id;
94
+ const name = sessionName(session);
95
+ const link = plan.link || {};
96
+ const chain = plan.chain || {};
97
+ // The chain's words first: they say the schedule runs this chain.
98
+ const scheduled = [chain.refusal, link.refusal].find((r) => r && /scheduled$/.test(r.reason));
99
+ return {
100
+ title: `Delete ${short(id)}${name ? ` — "${name}"` : ""}?`,
101
+ sub: `It is link ${plan.position} of ${plan.size} of its chain. This can't be undone.`,
102
+ banner: scheduled ? `${scheduled.message.charAt(0).toUpperCase()}${scheduled.message.slice(1)}.` : null,
103
+ choices: [
104
+ { act: "this", label: "Delete this link", lines: thisLinkLines(link), primary: true,
105
+ disabled: !!link.refusal && link.refusal.reason !== "delegate_unmovable", why: refusedWhy(link.refusal) },
106
+ { act: "chain", label: `Delete the whole chain · ${count(chain.links, "session")}`, lines: chainLines(plan),
107
+ warn: plan.cut_off ? "Earlier links, cut off by a deleted link, are kept (archived)." : null,
108
+ disabled: !!chain.refusal, why: refusedWhy(chain.refusal) },
109
+ ],
110
+ foot: "Running workers are stopped first.",
111
+ };
112
+ }
113
+
114
+ function choiceTemplate(choice) {
115
+ const cls = `ds-choice${choice.primary ? " primary" : ""}`;
116
+ if (choice.disabled) {
117
+ return html`<button type="button" class=${cls} data-act=${`del:${choice.act}`} disabled
118
+ ><span class="ds-label">${choice.label}</span><span class="ds-line">${choice.why}</span></button>`;
119
+ }
120
+ return html`<button type="button" class=${cls} data-act=${`del:${choice.act}`}
121
+ ><span class="ds-label">${choice.label}</span>${choice.lines.map((line, i) => html`<span class=${i ? "ds-line dim" : "ds-line"}>${line}</span>`)
122
+ }${choice.warn ? html`<span class="ds-line warn">${choice.warn}</span>` : nothing}</button>`;
123
+ }
124
+
125
+ // The back row: ‹ More in the More panel, a close × on a card's.
126
+ function headTemplate(back) {
127
+ // The More panel's grip stays on top, as on its list (more-grip).
128
+ return back
129
+ ? html`<div class="more-grip" aria-hidden="true"></div><div class="ds-head"><button type="button" class="ds-back" data-act="del:back">‹ More</button></div>`
130
+ : html`<div class="ds-head"><span></span><button type="button" class="ctx-pop-close" data-act="del:cancel" aria-label="Close">×</button></div>`;
131
+ }
132
+
133
+ // The choices (a lit-html template). +busy+: a delete under way (every
134
+ // button off); +back+: drawn in the More panel.
135
+ export function deleteSheetTemplate(model, { back = false, busy = false } = {}) {
136
+ const allOff = model.choices.every((c) => c.disabled);
137
+ return html`<div class=${`delete-sheet${busy ? " busy" : ""}`}>${headTemplate(back)}
138
+ <div class="ds-title">${model.title}</div>
139
+ <div class="ds-sub">${model.sub}</div>
140
+ ${model.banner ? html`<div class="ds-banner">${model.banner}</div>` : nothing}
141
+ <div class="ds-choices" ?inert=${busy}>${model.choices.map(choiceTemplate)}</div>
142
+ <div class="ds-foot">${allOff ? html`<span></span>` : html`<span class="ds-note">${busy ? "Deleting…" : model.foot}</span>`}
143
+ <button type="button" class="ds-cancel" data-act="del:cancel" ?disabled=${busy}>${allOff ? "Close" : "Cancel"}</button></div>
144
+ </div>`;
145
+ }
146
+
147
+ // While the plan is read.
148
+ export function loadingTemplate({ back = false } = {}) {
149
+ return html`<div class="delete-sheet">${headTemplate(back)}<div class="ds-sub">Reading what this delete would do…</div></div>`;
150
+ }
151
+
152
+ // A refused delete, in the sheet: a moved delegate that can't go back
153
+ // (delegate_unmovable: "Stop its worker, then delete" only when the page
154
+ // can stop it, not a one-turn run's), or any other refusal's own words.
155
+ // @param refusal {reason, message, ids, stoppable}
156
+ // @param previousId the link the delegate would go back to
157
+ export function refusalModel(refusal, previousId = null) {
158
+ if (refusal?.reason === "delegate_unmovable") {
159
+ const id = (refusal.ids || [])[0];
160
+ const back = previousId ? short(previousId) : "the previous link";
161
+ const why = refusal.stoppable
162
+ ? "runs on an older chi worker that can't be moved back"
163
+ : "is in a one-turn chi --non-interactive run; let it finish first";
164
+ return {
165
+ title: `Can't give ${short(id)} back`,
166
+ text: `The delegate ${short(id)}, which this link took over from ${back}, ${why}. Nothing was deleted.`,
167
+ stop: refusal.stoppable
168
+ ? { label: "Stop its worker, then delete",
169
+ line: `Its old worker stops (a running turn ends as stopped); it goes back to ${back} and starts on this chi next time.` }
170
+ : null,
171
+ };
172
+ }
173
+ return { title: "Not deleted", text: refusal?.message || "The delete was refused.", stop: null };
174
+ }
175
+
176
+ export function refusalTemplate(model, { back = false } = {}) {
177
+ return html`<div class="delete-sheet">${headTemplate(back)}
178
+ <div class="ds-title">${model.title}</div>
179
+ <div class="ds-sub">${model.text}</div>
180
+ ${model.stop ? html`<div class="ds-choices"><button type="button" class="ds-choice primary" data-act="del:stop"
181
+ ><span class="ds-label">${model.stop.label}</span><span class="ds-line dim">${model.stop.line}</span></button></div>` : nothing}
182
+ <div class="ds-foot"><span></span><button type="button" class="ds-cancel" data-act="del:cancel">${model.stop ? "Cancel" : "Close"}</button></div>
183
+ </div>`;
184
+ }
185
+
186
+ // The toast after a delete (D1/D5's words). +which+: "this" or "chain";
187
+ // +result+: the route's 200; +plan+: the sheet's.
188
+ // @return {text, back} (back: the link to offer opening, or null)
189
+ export function deleteToast(which, result, plan, id) {
190
+ if (which === "chain") {
191
+ const left = (result.left || []).length;
192
+ const links = Math.max(0, (plan.chain?.links ?? 0) - left);
193
+ const delegates = Math.max(0, (result.deleted || []).length - links);
194
+ let text = `Deleted the chain: ${count(links, "session")}${delegates ? ` and ${count(delegates, "delegate")}` : ""}.`;
195
+ const running = (result.left_running || []).length;
196
+ if (running) text += ` ${count(running, "running delegate")} ${running === 1 ? "was" : "were"} left on ${running === 1 ? "its" : "their"} own.`;
197
+ if (left) text += ` ${count(left, "link")} kept: ${result.refusal}`;
198
+ return { text, back: null };
199
+ }
200
+ const back = (result.unarchived || [])[0] || null;
201
+ if (!back) return { text: `Deleted ${short(id)}.`, back: null };
202
+ // The sheet's count (each moved delegate with its subtree) when it had one.
203
+ const moved = (result.moved_back || []).length ? (plan.link?.moved || result.moved_back.length) : 0;
204
+ const took = [moved && count(moved, "delegate"),
205
+ plan.link?.notes && count(plan.link.notes, "note")].filter(Boolean);
206
+ return { text: `Deleted ${short(id)}. ${short(back)} is back${took.length ? `, with ${took.join(" and ")}` : ""}.`, back };
207
+ }
208
+
209
+ // The list after a delete: the deleted ids gone, the ones back in the lists
210
+ // not archived (session_actions.js' markArchived's flip).
211
+ export function listAfterDelete(list, result) {
212
+ const gone = new Set(result.deleted || [result.session_id]);
213
+ const back = new Set(result.unarchived || []);
214
+ return list.filter((s) => !gone.has(s.id)).map((s) => (back.has(s.id) ? { ...s, archived: false } : s));
215
+ }
216
+
217
+ // The flow in a +host+ ({show(template), close(), back: whether it is the
218
+ // More panel}): reads the plan, shows the choices, runs the one chosen, and
219
+ // shows a refusal in place. +act+ is wired by the host to the returned
220
+ // handler. Hooks: api {deletePlan, deleteSession, deleteChain, stopSession};
221
+ // done(which, result, plan) after a delete; plain() when the plan says no
222
+ // chain (today's confirm); failed(error) when the plan can't be read.
223
+ // @return {act(name)} the host's handler for its data-act="del:*"
224
+ export function runDeleteFlow({ id, session, host, api, done, plain, failed }) {
225
+ let plan = null;
226
+ let model = null;
227
+ let refusal = null;
228
+ let busy = false;
229
+ const back = !!host.back;
230
+ // Whether +host+ still shows this flow: another session's sheet opened in
231
+ // the same shell since (a second card's ✕, the More panel on another
232
+ // session) takes it, and this flow then draws and acts on nothing.
233
+ const live = () => (host.live ? host.live() : true);
234
+ const show = (tpl) => { if (live()) host.show(tpl); };
235
+
236
+ const showChoices = () => show(deleteSheetTemplate(model, { back, busy }));
237
+ const showRefusal = () => show(refusalTemplate(refusalModel(refusal, plan?.link?.previous_id), { back }));
238
+
239
+ show(loadingTemplate({ back }));
240
+ api.deletePlan(id).then((read) => {
241
+ if (!live()) return;
242
+ if (!read?.chained) { host.close(); plain(); return; }
243
+ plan = read;
244
+ model = deleteChoices(session, plan);
245
+ showChoices();
246
+ }, (error) => { if (live()) { host.close(); failed(error); } });
247
+
248
+ // The refusal as the delete's 409 says it; whether the page can stop a
249
+ // moved delegate's worker is its +stoppable+, as the delete saw it.
250
+ function refused(error) {
251
+ refusal = { reason: error.code, message: error.message, ids: error.body?.ids || [], stoppable: error.body?.stoppable === true };
252
+ busy = false;
253
+ showRefusal();
254
+ }
255
+
256
+ async function run(which) {
257
+ if (busy || !live()) return;
258
+ busy = true;
259
+ showChoices();
260
+ try {
261
+ const result = which === "chain" ? await api.deleteChain(id) : await api.deleteSession(id);
262
+ if (live()) host.close();
263
+ done(which, result, plan);
264
+ } catch (error) {
265
+ refused(error);
266
+ }
267
+ }
268
+
269
+ // "Stop its worker, then delete": the delete again only once each worker
270
+ // reads stopped (the stop route's released, after its bounded wait);
271
+ // still running, the refusal says so, and nothing loops.
272
+ async function stopThenDelete() {
273
+ if (busy || !live()) return;
274
+ const ids = refusal?.ids || [];
275
+ busy = true;
276
+ for (const child of ids) {
277
+ let released = false;
278
+ try {
279
+ released = (await api.stopSession(child))?.released === true;
280
+ } catch (_) { released = false; }
281
+ if (!released) {
282
+ refusal = { reason: "still_stopping", message: `${short(child)}'s worker is still running; try again in a moment.`, ids };
283
+ busy = false;
284
+ showRefusal();
285
+ return;
286
+ }
287
+ }
288
+ busy = false;
289
+ run("this");
290
+ }
291
+
292
+ return {
293
+ act(name) {
294
+ if (!live()) return;
295
+ if (name === "cancel") host.close();
296
+ else if (name === "this" || name === "chain") run(name);
297
+ else if (name === "stop") stopThenDelete();
298
+ },
299
+ };
300
+ }
301
+
302
+ // A card's ✕: the flow on a popover of its own at the card (a bottom sheet
303
+ // on a phone). One shell for every card: +openFor+ is the session it shows,
304
+ // and only the newest host is live (a ✕ on another card while one's plan is
305
+ // read takes the shell; the first flow's late answer draws nothing).
306
+ // @return {host(anchorEl, id): a host for runDeleteFlow, close, isOpen, pop}
307
+ export function createDeleteSheet({ doc = globalThis.document, win = globalThis.window, el = doc.createElement("span") } = {}) {
308
+ let view = null;
309
+ let handler = null;
310
+ let current = null;
311
+ let openFor = null;
312
+ const shell = createChipPopover({
313
+ id: "deleteSheet", className: "ctx-popover delete-pop", width: 420, el, anchor: "[data-del]", openers: "[data-del]",
314
+ summary: () => view, sheet: true, label: "Delete the session?", doc, win,
315
+ show: (tpl) => render(tpl, shell.pop),
316
+ onOpen: () => shell.pop.querySelector(".ds-choice:not([disabled]), .ds-cancel")?.focus(),
317
+ onClose: () => { view = null; handler = null; current = null; openFor = null; },
318
+ onAct: (act) => {
319
+ const [what, name] = act.split(":");
320
+ if (what === "del") handler?.act(name);
321
+ },
322
+ });
323
+
324
+ function host(anchorEl, id) {
325
+ if (shell.isOpen() && openFor !== id) shell.close();
326
+ const me = {
327
+ back: false,
328
+ live: () => current === me,
329
+ show(tpl) {
330
+ if (current !== me) return;
331
+ view = tpl;
332
+ if (shell.isOpen()) render(tpl, shell.pop);
333
+ else shell.open(anchorEl);
334
+ },
335
+ close() { if (current === me) shell.close(); },
336
+ wire(next) { if (current === me) handler = next; },
337
+ };
338
+ current = me;
339
+ openFor = id;
340
+ return me;
341
+ }
342
+
343
+ return { host, close: () => shell.close(), isOpen: shell.isOpen, pop: shell.pop, openFor: () => openFor };
344
+ }
@@ -60,7 +60,7 @@ export function firstPreview(text) {
60
60
  // What names a session's card, first found: its title (/title), its auto
61
61
  // title (from the recap call), its recap's first sentence (+recap+), its
62
62
  // first message, its last prompt. Display only.
63
- function cardName(session) {
63
+ export function cardName(session) {
64
64
  return session.title || session.auto_title || session.recap || session.first_preview || session.last_prompt || "";
65
65
  }
66
66
 
@@ -1469,6 +1469,33 @@ body.has-session.composer-folded #infoBar{border-top-color:transparent}
1469
1469
  .ss-cancel{background:transparent}
1470
1470
  .stop-sheet.sheet .ss-acts button{flex:1 1 auto;font-size:14px;padding:10px 12px}
1471
1471
  .ss-foot{font-size:11.5px;color:var(--text-muted);margin-top:6px}
1472
+ .delete-sheet{display:flex;flex-direction:column;gap:10px}
1473
+ .ds-head{display:flex;align-items:center;justify-content:space-between;min-height:24px}
1474
+ .ds-back{background:none;border:none;padding:0;color:var(--accent);font:inherit;cursor:pointer}
1475
+ .ds-title{font-size:14px;font-weight:600;color:var(--text-bright)}
1476
+ .ds-sub{color:var(--text-2)}
1477
+ .ds-banner{padding:8px 10px;border-radius:8px;background:var(--warn-bg);border:1px solid var(--warn-border);color:var(--warn-text)}
1478
+ .ds-choices{display:flex;flex-direction:column;gap:10px}
1479
+ .ds-choice{display:flex;flex-direction:column;gap:4px;text-align:left;padding:10px 12px;border-radius:10px;border:1px solid var(--border-strong);background:none;color:var(--text);font:inherit;cursor:pointer}
1480
+ .ds-choice:hover:not([disabled]){background:var(--bg-hover)}
1481
+ .ds-choice.primary{background:var(--bg-raised);border-color:var(--danger)}
1482
+ .ds-choice.primary .ds-label{color:var(--danger-text)}
1483
+ .ds-choice[disabled]{cursor:default;color:var(--text-muted);border-color:var(--border);background:none}
1484
+ .ds-choice[disabled] .ds-label{color:var(--text-muted)}
1485
+ .ds-label{font-weight:600}
1486
+ .ds-line{color:var(--text-2)}
1487
+ .ds-line.dim{color:var(--text-muted)}
1488
+ .ds-line.warn{color:var(--warn-bright)}
1489
+ .ds-foot{display:flex;align-items:center;gap:8px}
1490
+ .ds-note{flex-grow:1;color:var(--text-muted);font-size:12px}
1491
+ .ds-foot>span:first-child{flex-grow:1}
1492
+ .ds-cancel{padding:6px 14px;border-radius:8px;border:1px solid var(--border-strong);background:none;color:var(--text-2);font:inherit;cursor:pointer}
1493
+ .delete-sheet.busy .ds-choice{opacity:.6}
1494
+ .sheet .ds-choice{min-height:44px;padding:12px 14px;border-radius:12px}
1495
+ .sheet .ds-title{font-size:17px}
1496
+ .sheet .ds-back{min-height:44px}
1497
+ .sheet .ds-foot{flex-wrap:wrap}
1498
+ .sheet .ds-cancel{flex-basis:100%;min-height:48px;border:none;border-radius:12px;background:var(--bg-raised);font-weight:600}
1472
1499
  .ctx-pop-head{display:flex;align-items:baseline;gap:8px}
1473
1500
  .ctx-pop-head strong{font-family:ui-monospace,monospace;color:var(--text-bright)}
1474
1501
  #updateSheet{width:calc(100vw - 32px);max-width:560px;max-height:calc(100dvh - 32px);overflow:auto;margin:auto;padding:14px 16px;border:1px solid var(--border-strong);border-radius:14px;background:var(--bg-panel);color:var(--text);box-shadow:var(--toast-shadow)}
@@ -111,10 +111,11 @@ export function infoBarHtml(bar) {
111
111
  const setup = html`${settingsChip(bar.settings)}<span class=${`model model-name${bar.model.mismatch ? " served-mismatch" : ""}`} title=${bar.model.title}>${bar.model.text}</span>${toolkitChip(bar.toolkit)}${bar.notes ? html`<span class="model notes-chip" title=${bar.notes.title}>${bar.notes.text}</span>` : nothing}${bar.workingSet ? workingSetChipTemplate(bar.workingSet.chip) : memories.length ? html`<span class="model mem-chip" title=${memChipTitle(memories)}>${memChipText(memories)}</span>` : nothing}`;
112
112
  const pruned = !!bar.chain?.pruned && !bar.chain?.prev;
113
113
  const related = !!(bar.chain?.prev || bar.chain?.next || pruned || bar.parent || bar.kids || bar.participants);
114
- // A chain pruned by a schedule (docs/scheduling.md): the link before this one
114
+ // A chain whose earlier link was deleted (by hand, or a schedule's prune:
115
+ // one word for both, the logs say who): the link before this one
115
116
  // is gone, so there is nothing to link to — the bar says so instead.
116
117
  const relations = related
117
- ? html`${sep("relations")}<span class="bar-group relations">${pruned ? html`<span class="model chain-pruned" title="The links before this one were pruned by a schedule">↩ earlier links pruned</span>` : nothing}${bar.chain?.prev ? chainLinkTemplate(bar.chain.prev, PREV, "The previous link of this chain") : nothing}${bar.chain?.next ? chainLinkTemplate(bar.chain.next, NEXT, "The next link of this chain") : nothing}${bar.parent ? html`<a class="model parent" href=${sessionHash(bar.parent.id)} title=${bar.parent.title}>↑ ${String(bar.parent.id).slice(0, 8)}</a>` : nothing}${kidsTemplate(bar.kids)}${participantsChip(bar.participants)}</span>`
118
+ ? html`${sep("relations")}<span class="bar-group relations">${pruned ? html`<span class="model chain-pruned" title="The links before this one were deleted">↩ earlier links deleted</span>` : nothing}${bar.chain?.prev ? chainLinkTemplate(bar.chain.prev, PREV, "The previous link of this chain") : nothing}${bar.chain?.next ? chainLinkTemplate(bar.chain.next, NEXT, "The next link of this chain") : nothing}${bar.parent ? html`<a class="model parent" href=${sessionHash(bar.parent.id)} title=${bar.parent.title}>↑ ${String(bar.parent.id).slice(0, 8)}</a>` : nothing}${kidsTemplate(bar.kids)}${participantsChip(bar.participants)}</span>`
118
119
  : nothing;
119
120
  const trail = html`<span class="dir" title=${bar.dir || ""}><bdi>${bar.dir || ""}</bdi></span>${workerBadgeTemplate(bar.worker)}`;
120
121
  return html`<div class="meta"><span class="bar-group identity">${identity}</span>${sep("setup")}<span class="bar-group setup">${setup}</span>${relations}${sep("trail")}<span class="bar-group trail">${trail}</span></div>`;
@@ -18,7 +18,7 @@
18
18
  // eventsLive() whether the hub's events stream is open
19
19
  // refresh() fetch the list (no events stream)
20
20
  // select(id) open a session
21
- // confirmDelete(id), setArchived(id, archive), archiveOne(id, archive)
21
+ // confirmDelete(id, {anchor}), setArchived(id, archive), archiveOne(id, archive)
22
22
  // updateSessionTitle(), showToast(text, action)
23
23
  // allViewOpen(), openAllView(), closeAllView(), leaveAllView(hash)
24
24
  // renameShown(owner) whether a card's title has its ✎ (session_title.js)
@@ -482,7 +482,7 @@ export function createListsView(deps) {
482
482
  const del = e.target.closest(".card-del");
483
483
  if (del) {
484
484
  e.stopPropagation();
485
- confirmDelete(del.dataset.del);
485
+ confirmDelete(del.dataset.del, { anchor: del });
486
486
  return;
487
487
  }
488
488
  // Archive from the list: the view stays open, the toast has Undo.
@@ -8,7 +8,7 @@
8
8
  //
9
9
  // +folded+ (a Set of BAR_ITEMS keys: the items folded off the row) narrows
10
10
  // the menu to them: a row only for a folded chip (the id, ⚙ when folded, not
11
- // when compact, and "earlier links pruned" included), Continue and Stop only
11
+ // when compact, and "earlier links deleted" included), Continue and Stop only
12
12
  // when folded (Archive and Delete always: they are never on the row), ⋯'s
13
13
  // dot from folded rows alone and its count (moreCount: shown on a desktop
14
14
  // only). Without it (null) the menu has its fixed set: every chip's row but
@@ -113,7 +113,7 @@ export function moreRows(bar, folded = null) {
113
113
  !bar.workingSet && memories.length > 0
114
114
  && { key: "memories", label: "Memories", value: memChipText(memories), info: memoriesTooltip(memories, bar.preloaded, bar.muted) },
115
115
  bar.participants && participantsRow(bar.participants),
116
- folded?.has("pruned") && bar.chain?.pruned && !bar.chain?.prev && { key: "pruned", label: "Earlier links pruned", value: "by a schedule" },
116
+ folded?.has("pruned") && bar.chain?.pruned && !bar.chain?.prev && { key: "pruned", label: "Earlier links deleted", value: "" },
117
117
  bar.chain?.prev && { key: "prev", label: "Previous link", value: `${PREV} ${bar.chain.prev.date || short(bar.chain.prev.id)}`, href: bar.chain.prev.id },
118
118
  bar.chain?.next && { key: "next", label: "Next link", value: `${bar.chain.next.date || short(bar.chain.next.id)} ${NEXT}`, href: bar.chain.next.id },
119
119
  bar.parent && { key: "parent", label: "Delegated by", value: `↑ ${short(bar.parent.id)}`, href: bar.parent.id },
@@ -217,28 +217,65 @@ export function moreSheetTemplate({ bar, buttons, folded = null, shownInfo = nul
217
217
 
218
218
  // ⋯'s sheet. el: where ⋯ is drawn (#infoBar); button: ⋯ itself; session(): the
219
219
  // open session's id; hash: a session's id to its link (route.js sessionHash).
220
+ // onDelete(id, host): Delete on a chained session turns this panel into the
221
+ // delete sheet (delete_sheet.js) instead of clicking #infoDeleteBtn: it
222
+ // answers true when it took the host ({back: true, show(template), close(),
223
+ // wire(handler)}), whose ‹ More (del:back) draws the panel's list again.
220
224
  // @return {update({bar, buttons, folded}), close, isOpen, pop}
221
- export function createMoreSheet({ el, button, session = () => null, hash, doc = document, win = window }) {
225
+ export function createMoreSheet({ el, button, session = () => null, hash, onDelete = null, doc = document, win = window }) {
222
226
  let bar = null;
223
227
  let buttons = null;
224
228
  let folded = null;
225
229
  let shownInfo = null;
230
+ // The delete sheet drawn in the panel's place, its act handler, and the
231
+ // live host (one per Delete: a flow from an earlier one draws nothing).
232
+ let subview = null;
233
+ let subHandler = null;
234
+ let subHost = null;
226
235
 
227
236
  function draw() {
228
- render(moreSheetTemplate({ bar, buttons, folded, shownInfo, hash }), shell.pop);
237
+ render(subview ?? moreSheetTemplate({ bar, buttons, folded, shownInfo, hash }), shell.pop);
238
+ }
239
+
240
+ function makeHost() {
241
+ const me = {
242
+ back: true,
243
+ live: () => subHost === me,
244
+ show(tpl) {
245
+ if (subHost !== me) return;
246
+ subview = tpl;
247
+ draw();
248
+ shell.pop.querySelector(".ds-choice:not([disabled]), .ds-cancel, .ds-back")?.focus();
249
+ },
250
+ close() { if (subHost === me) shell.close(); },
251
+ wire(handler) { if (subHost === me) subHandler = handler; },
252
+ };
253
+ subHost = me;
254
+ return me;
229
255
  }
230
256
 
231
257
  const shell = createChipPopover({
232
258
  id: "moreSheet", className: "ctx-popover more-sheet", width: 400, el, anchor: `#${button.id}`,
233
259
  summary: () => bar, session, show: () => draw(), sheet: true, sheetShare: SHEET_TALL, label: "More about this session",
234
260
  onOpen: () => shell.pop.querySelector(".more-row, .more-act")?.focus(),
235
- onClose: () => { shownInfo = null; },
261
+ onClose: () => { shownInfo = null; subview = null; subHandler = null; subHost = null; },
236
262
  onAct: (act) => {
237
263
  const [what, name] = act.split(":");
238
264
  if (what === "info") {
239
265
  shownInfo = shownInfo === name ? null : name;
240
266
  return draw();
241
267
  }
268
+ if (what === "del") {
269
+ if (name === "back") {
270
+ subview = null;
271
+ subHandler = null;
272
+ subHost = null;
273
+ draw();
274
+ return shell.pop.querySelector(".more-act.delete")?.focus();
275
+ }
276
+ return subHandler?.act(name);
277
+ }
278
+ if (what === "go" && name === "delete" && onDelete?.(session(), makeHost())) return undefined;
242
279
  // After this click is done: it goes on to the document, where what the
243
280
  // target opens would take it as a click outside, and a link still has
244
281
  // to follow its href.