samagotchi 0.173.0 → 0.175.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 (74) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +48 -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/bridge.md +8 -1
  7. data/docs/internals/participants.md +3 -1
  8. data/docs/internals/remote-sessions.md +8 -0
  9. data/docs/internals/web-frontend.md +45 -5
  10. data/docs/plugins.md +1 -3
  11. data/docs/scheduling.md +9 -3
  12. data/docs/sessions.md +3 -1
  13. data/docs/testing.md +31 -3
  14. data/lib/samagotchi/answer_text.rb +4 -2
  15. data/lib/samagotchi/bridge.rb +1 -1
  16. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  17. data/lib/samagotchi/child_move.rb +11 -4
  18. data/lib/samagotchi/continued_from.rb +51 -0
  19. data/lib/samagotchi/engine.rb +1 -1
  20. data/lib/samagotchi/llm/stray_tool_call.rb +7 -4
  21. data/lib/samagotchi/llm_context_stale.rb +2 -1
  22. data/lib/samagotchi/message_parts.rb +5 -2
  23. data/lib/samagotchi/model_markup.rb +22 -0
  24. data/lib/samagotchi/model_profile.rb +8 -7
  25. data/lib/samagotchi/note_move.rb +11 -4
  26. data/lib/samagotchi/prompt_literal_guard.rb +7 -6
  27. data/lib/samagotchi/schedules.rb +13 -16
  28. data/lib/samagotchi/session_access/contract.rb +1 -0
  29. data/lib/samagotchi/session_access/local.rb +9 -1
  30. data/lib/samagotchi/session_access/remote.rb +26 -3
  31. data/lib/samagotchi/session_chain/delete.rb +405 -0
  32. data/lib/samagotchi/session_chain/delete_preview.rb +96 -0
  33. data/lib/samagotchi/session_chain/links.rb +38 -0
  34. data/lib/samagotchi/session_command_catalog.rb +2 -2
  35. data/lib/samagotchi/session_commands.rb +3 -13
  36. data/lib/samagotchi/session_continue.rb +51 -13
  37. data/lib/samagotchi/session_delete_command.rb +82 -17
  38. data/lib/samagotchi/session_manager/removal.rb +137 -31
  39. data/lib/samagotchi/session_stores.rb +2 -0
  40. data/lib/samagotchi/task_transcript.rb +10 -5
  41. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +2 -2
  42. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  43. data/lib/samagotchi/terminal_ui/exit_lines.rb +16 -0
  44. data/lib/samagotchi/terminal_ui/local_link.rb +7 -1
  45. data/lib/samagotchi/terminal_ui.rb +3 -3
  46. data/lib/samagotchi/testing/boundary.rb +0 -5
  47. data/lib/samagotchi/testing/bundle.rb +1 -1
  48. data/lib/samagotchi/tool_call_parser.rb +6 -5
  49. data/lib/samagotchi/tools/task_runtime.rb +0 -5
  50. data/lib/samagotchi/turn_note.rb +2 -1
  51. data/lib/samagotchi/version.rb +1 -1
  52. data/lib/samagotchi/web/app.rb +7 -1
  53. data/lib/samagotchi/web/participant_show.rb +1 -0
  54. data/lib/samagotchi/web/participant_view.rb +4 -2
  55. data/lib/samagotchi/web/public/app.js +27 -5
  56. data/lib/samagotchi/web/public/chains.js +3 -3
  57. data/lib/samagotchi/web/public/data.js +12 -0
  58. data/lib/samagotchi/web/public/delete_sheet.js +344 -0
  59. data/lib/samagotchi/web/public/format.js +1 -1
  60. data/lib/samagotchi/web/public/index.html +27 -0
  61. data/lib/samagotchi/web/public/info_bar.js +3 -2
  62. data/lib/samagotchi/web/public/lists_view.js +2 -2
  63. data/lib/samagotchi/web/public/more_sheet.js +42 -5
  64. data/lib/samagotchi/web/public/reload_check.js +0 -3
  65. data/lib/samagotchi/web/public/session_actions.js +50 -6
  66. data/lib/samagotchi/web/public/session_view.js +9 -1
  67. data/lib/samagotchi/web/public/stage_asking.js +1 -7
  68. data/lib/samagotchi/web/public/stage_missing.js +150 -0
  69. data/lib/samagotchi/web/public/stage_view.js +8 -3
  70. data/lib/samagotchi/web/server.rb +13 -13
  71. data/lib/samagotchi/web/session_control.rb +58 -5
  72. data/lib/samagotchi/web/session_show.rb +42 -4
  73. metadata +7 -2
  74. data/lib/samagotchi/web/public/cards_offscreen.js +0 -69
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "model_profile"
4
+ require_relative "model_markup"
4
5
  require_relative "tools/args"
5
6
  require_relative "tools/ask_user_question"
6
7
  require_relative "tools/builtin_calls"
@@ -353,8 +354,8 @@ module Samagotchi
353
354
  results = []
354
355
 
355
356
  pos = 0
356
- tool_open = "<tool_call>"
357
- tool_close = "</tool_call>"
357
+ tool_open = ModelMarkup::TOOL_CALL_OPEN
358
+ tool_close = ModelMarkup::TOOL_CALL_CLOSE
358
359
 
359
360
  while (open_pos = text.index(tool_open, pos))
360
361
  body_start = open_pos + tool_open.length
@@ -383,7 +384,7 @@ module Samagotchi
383
384
  end
384
385
 
385
386
  def strip_tool_calls(text)
386
- ToolCallParser.strip_calls(text, "<tool_call>", "</tool_call>")
387
+ ToolCallParser.strip_calls(text, ModelMarkup::TOOL_CALL_OPEN, ModelMarkup::TOOL_CALL_CLOSE)
387
388
  end
388
389
 
389
390
  def parse_with_recovery(response, partial_fragment)
@@ -420,8 +421,8 @@ module Samagotchi
420
421
  end
421
422
 
422
423
  def qwen_unterminated_tool_call_fragment(text)
423
- open_tag = "<tool_call>"
424
- close_tag = "</tool_call>"
424
+ open_tag = ModelMarkup::TOOL_CALL_OPEN
425
+ close_tag = ModelMarkup::TOOL_CALL_CLOSE
425
426
  pos = 0
426
427
 
427
428
  while (open_pos = text.index(open_tag, pos))
@@ -19,11 +19,6 @@ require_relative "task_record"
19
19
  module Samagotchi
20
20
  module Tools
21
21
  module TaskRuntime
22
- # Moved to TaskFiles; kept here one release for bundles that name
23
- # them (the boundary's stable list). Remove in the release after the
24
- # one that ships TaskFiles, with their stable-list entries.
25
- TASKS_DIR = TaskFiles::TASKS_DIR
26
- EXIT_CODE_FILENAME = TaskFiles::EXIT_CODE_FILENAME
27
22
  STOP_GRACE_SEC = 3.0
28
23
  STOP_POLL_INTERVAL_SEC = 0.1
29
24
  METADATA_VERSION = TaskRecord::METADATA_VERSION
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "model_profile"
4
+ require_relative "model_markup"
4
5
  require_relative "thinking_tails"
5
6
 
6
7
  module Samagotchi
@@ -32,7 +33,7 @@ module Samagotchi
32
33
  STEP_CHARS = ThinkingTails::TAIL_CHARS
33
34
  # A step's native thinking starts with one of these; the cut keeps it,
34
35
  # so the UIs still find the thinking (MessageParts).
35
- THINK_OPENS = ["<think>", ModelProfile::GEMMA_THOUGHT_CHANNEL_OPEN].freeze
36
+ THINK_OPENS = [ModelMarkup::THINK_OPEN, ModelProfile::GEMMA_THOUGHT_CHANNEL_OPEN].freeze
36
37
 
37
38
  module_function
38
39
 
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.173.0"
4
+ VERSION = "0.175.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -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
@@ -58,6 +58,7 @@ module Samagotchi
58
58
  **participant_drawings_field(drawn, messages, viewer),
59
59
  failed_turn: nil,
60
60
  current_turn: current,
61
+ live_read: reads.live_read,
61
62
  replay: participant_replay(turn_snapshot, timing, viewer),
62
63
  queued: participant_queued(queued, viewer),
63
64
  queued_commands: [],
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../output_formatter"
4
+ require_relative "../model_markup"
4
5
  require_relative "../steer"
5
6
  require_relative "../turn_origin"
6
7
  require_relative "../revise_anchor"
@@ -692,10 +693,11 @@ module Samagotchi
692
693
  OutputFormatter::GEMMA_TOOL_CALL_RE, OutputFormatter::GEMMA_THOUGHT_RE)
693
694
  # A close with no open before it: what came before was thinking (the
694
695
  # raw loop saves prefill + response).
695
- BARE_CLOSES = ["</think>", "<channel|>"].freeze
696
+ BARE_CLOSES = [ModelMarkup::THINK_CLOSE, "<channel|>"].freeze
696
697
  # An open with no close after it (a cut-off thought, a tool call the
697
698
  # loop recovered): everything from it on is the model's own.
698
- OPENS = ["<think>", "<tool_call>", "<|tool_call>", "<|channel>", "<|tool_response>", "<tool_response>", "<|think|>"].freeze
699
+ OPENS = [ModelMarkup::THINK_OPEN, ModelMarkup::TOOL_CALL_OPEN, "<|tool_call>", "<|channel>",
700
+ "<|tool_response>", ModelMarkup::TOOL_RESPONSE_OPEN, "<|think|>"].freeze
699
701
 
700
702
  # A saved model message's raw content as a participant may read it:
701
703
  # closed blocks kept (the display strips them, its tool rows come from
@@ -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,
@@ -49,6 +51,7 @@ import { normalize, cantText } from "./format.js";
49
51
  import { createBubbles } from "./bubbles.js";
50
52
  import { createCardsPlace } from "./cards_place.js";
51
53
  import { createStageView } from "./stage_view.js";
54
+ import { createStageMissing } from "./stage_missing.js";
52
55
  import { createReloadCheck } from "./reload_check.js";
53
56
  import { createCardRegistry, observeCards } from "./card_registry.js";
54
57
  import { createWorkingSet } from "./working_set_view.js";
@@ -117,6 +120,7 @@ import { createUnqueue } from "./unqueue.js";
117
120
  import { createStartPage } from "./start_page.js";
118
121
  import { createSessionActions } from "./session_actions.js";
119
122
  import { createStopSheet } from "./stop_sheet.js";
123
+ import { createDeleteSheet } from "./delete_sheet.js";
120
124
  import { createVersionNotices } from "./version_notices.js";
121
125
  import { createRename } from "./session_rename.js";
122
126
  import { createSendTurn } from "./send_turn.js";
@@ -180,7 +184,10 @@ const settingsControl = viewer.can("session_controls") ? createSettingsControl({
180
184
  // ⋯ on the info bar, and its menu: the chips and buttons the row has no room for; and the bar's other buttons.
181
185
  const [continueBtn, archiveBtn, stopBtn, deleteBtn, moreBtn] = viewer.controls(
182
186
  ["#infoContinueBtn", "#infoArchiveBtn", "#infoStopBtn", "#infoDeleteBtn", "#infoMoreBtn"].map($), "session_controls");
183
- const moreSheet = moreBtn ? createMoreSheet({ el: $("#infoBar"), button: moreBtn, session: () => store.selected, hash: sessionHash }) : null;
187
+ // Delete on a chained session turns the panel into the delete sheet
188
+ // (session_actions.js deleteIn); sessionActions is made below.
189
+ const moreSheet = moreBtn ? createMoreSheet({ el: $("#infoBar"), button: moreBtn, session: () => store.selected, hash: sessionHash,
190
+ onDelete: (id, host) => sessionActions.deleteIn(id, host) }) : null;
184
191
  // The bar's fold (bar_fold.js): one row, what doesn't fit folded into ⋯. A
185
192
  // resize, the fonts or a zoom refolds it by itself: ⋯ follows on the redraw.
186
193
  const barFold = createBarFold({ barEl: $("#infoBar"), keysFor: barItemKeys, onChange: () => store.touch("infoBar") });
@@ -353,7 +360,10 @@ const workingSet = document.body.dataset.workingSet === "1" && viewer.can("worki
353
360
  wsPreview?.attach(workingSet);
354
361
  document.body.classList.toggle("working-set", !!workingSet);
355
362
  // The running turn's DOM: the stage pinned above the composer
356
- // (stage_view.js), the turn block (turn_block.js) in its cloud.
363
+ // (stage_view.js), the turn block (turn_block.js) in its cloud. The
364
+ // running-with-no-turn check (stage_missing.js) hangs on its hooks, so it is
365
+ // made right after the stage.
366
+ let stageMissing = null;
357
367
  const turnDom = createStageView({
358
368
  historyEl,
359
369
  isNearBottom: () => atHistoryEnd(),
@@ -370,10 +380,18 @@ const turnDom = createStageView({
370
380
  // Stop turn in its status row (disabled until the request settles).
371
381
  onCancel: viewer.can("stop_any_turn") || viewer.can("stop_own_turn") ? () => handleCancel() : null,
372
382
  canCancel: () => !participant || participant.canCancel(), ownerWait: () => participant?.ownerWait() ?? null,
373
- onHandedOff: (handed) => reloadCheck.handedOff(handed),
383
+ onHandedOff: (handed) => { reloadCheck.handedOff(handed); stageMissing?.check(); },
384
+ onStageCleared: () => stageMissing?.check(),
374
385
  // The quiet signal (stage_stall.js): the stream, what the turn waits on, a joiner's step clock.
375
386
  streamLive: () => sessionSync.streamLive(), timingNote: () => liveTurn.timing.note, serverGen: () => liveTurn.serverGen,
376
387
  });
388
+ // The stage's own look at "running, nothing on it" (stage_missing.js): the
389
+ // bare status row, the mark and one console line per session visit. A status
390
+ // that leaves running, a resize or a composer that changed size looks again.
391
+ stageMissing = createStageMissing({ store, turnDom, composerEl });
392
+ store.on("infoBar", stageMissing.checkOnStatus);
393
+ window.addEventListener("resize", () => stageMissing.check());
394
+ if (window.ResizeObserver) new window.ResizeObserver(() => stageMissing.check()).observe(composerEl);
377
395
  // The open session's cards as data (card_registry.js: fed by the stream's card events and renderSessionView's seed).
378
396
  const cardRegistry = createCardRegistry();
379
397
  // The opt-in reload check (web.reload_check): a handed-off turn against a
@@ -669,7 +687,7 @@ const lists = createListsView({
669
687
  eventsLive: () => !!eventsControl,
670
688
  refresh: () => refresh(),
671
689
  select: (id) => select(id),
672
- confirmDelete: (id) => confirmDelete(id),
690
+ confirmDelete: (id, options) => confirmDelete(id, options),
673
691
  setArchived: (id, archive) => setArchived(id, archive),
674
692
  archiveOne: (id, archive) => archiveOne(id, archive),
675
693
  updateSessionTitle: () => updateSessionTitle(),
@@ -693,12 +711,15 @@ const stopSheet = createStopSheet({
693
711
  stopSession: (id) => sessionActions.stopSelected(id),
694
712
  });
695
713
 
714
+ // A card's ✕ on a chained session: the delete sheet at the card (delete_sheet.js).
715
+ const deleteSheet = createDeleteSheet({ doc: document, win: window });
716
+
696
717
  const sessionActions = createSessionActions({
697
718
  selected: () => store.selected,
698
719
  store,
699
720
  sessions: () => store.sessions,
700
721
  setSessions: (list) => store.update({ sessions: list }),
701
- api: { continueSession, archiveSession, unarchiveSession, deleteSession, stopSession,
722
+ api: { continueSession, archiveSession, unarchiveSession, deleteSession, deleteChain, deletePlan, stopSession,
702
723
  sessionHolds, stopSessionHolds },
703
724
  eventsLive: () => !!eventsControl,
704
725
  refresh,
@@ -712,6 +733,7 @@ const sessionActions = createSessionActions({
712
733
  closeLiveStream: () => sessionSync.closeLive(),
713
734
  workerGone,
714
735
  stopSheet,
736
+ deleteSheet,
715
737
  });
716
738
  // The title's ✎: /title through the chips' path (session_rename.js), the
717
739
  // 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