samagotchi 0.172.1 → 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 (143) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -1
  3. data/docs/architecture.md +16 -5
  4. data/docs/cli.md +11 -3
  5. data/docs/configuration.md +1 -1
  6. data/docs/internals/background-tasks.md +16 -6
  7. data/docs/internals/bridge.md +2 -2
  8. data/docs/internals/engine.md +2 -1
  9. data/docs/internals/participants.md +69 -9
  10. data/docs/internals/remote-sessions.md +9 -1
  11. data/docs/internals/web-frontend.md +34 -8
  12. data/docs/plugins.md +1 -1
  13. data/docs/scheduling.md +9 -3
  14. data/docs/sessions.md +5 -3
  15. data/docs/testing.md +32 -10
  16. data/lib/samagotchi/bridge.rb +4 -3
  17. data/lib/samagotchi/bundle_command/try/sandbox.rb +2 -2
  18. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  19. data/lib/samagotchi/bundles/slow-commands/manifest.yml +3 -3
  20. data/lib/samagotchi/bundles/slow-commands/plugin.rb +3 -3
  21. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  22. data/lib/samagotchi/child_move.rb +11 -4
  23. data/lib/samagotchi/continued_from.rb +51 -0
  24. data/lib/samagotchi/engine/participants.rb +2 -2
  25. data/lib/samagotchi/engine.rb +1 -2
  26. data/lib/samagotchi/file_ref.rb +3 -5
  27. data/lib/samagotchi/guardrails/participant_refusal.rb +1 -1
  28. data/lib/samagotchi/memory_usage.rb +2 -1
  29. data/lib/samagotchi/message_parts.rb +5 -3
  30. data/lib/samagotchi/note_move.rb +11 -4
  31. data/lib/samagotchi/objectives_backing.rb +6 -10
  32. data/lib/samagotchi/parent_report.rb +1 -1
  33. data/lib/samagotchi/participant_prompts.rb +101 -0
  34. data/lib/samagotchi/participant_turn_mode.rb +1 -1
  35. data/lib/samagotchi/project_env.rb +7 -5
  36. data/lib/samagotchi/prompt_history.rb +2 -2
  37. data/lib/samagotchi/schedules.rb +13 -16
  38. data/lib/samagotchi/send_command/parent_gate.rb +2 -2
  39. data/lib/samagotchi/send_command.rb +4 -4
  40. data/lib/samagotchi/session_access/contract.rb +1 -0
  41. data/lib/samagotchi/session_access/local.rb +9 -1
  42. data/lib/samagotchi/session_access/remote.rb +26 -3
  43. data/lib/samagotchi/session_chain/delete.rb +405 -0
  44. data/lib/samagotchi/session_chain/delete_preview.rb +96 -0
  45. data/lib/samagotchi/session_chain/links.rb +38 -0
  46. data/lib/samagotchi/session_command_catalog.rb +210 -0
  47. data/lib/samagotchi/session_commands.rb +6 -187
  48. data/lib/samagotchi/session_continue.rb +51 -13
  49. data/lib/samagotchi/session_delete_command.rb +82 -17
  50. data/lib/samagotchi/session_manager/lifecycle.rb +5 -4
  51. data/lib/samagotchi/session_manager/removal.rb +137 -31
  52. data/lib/samagotchi/session_manager.rb +2 -1
  53. data/lib/samagotchi/session_stores.rb +4 -0
  54. data/lib/samagotchi/spawn_env.rb +75 -0
  55. data/lib/samagotchi/task_files.rb +51 -0
  56. data/lib/samagotchi/task_transcript.rb +67 -0
  57. data/lib/samagotchi/task_watch.rb +8 -6
  58. data/lib/samagotchi/terminal_ui/attached_loop/composer.rb +3 -3
  59. data/lib/samagotchi/terminal_ui/attached_loop/exit_commands.rb +2 -2
  60. data/lib/samagotchi/terminal_ui/attached_loop/questions.rb +2 -2
  61. data/lib/samagotchi/terminal_ui/attached_loop.rb +4 -4
  62. data/lib/samagotchi/terminal_ui/exit_lines.rb +16 -0
  63. data/lib/samagotchi/terminal_ui/input_support.rb +1 -1
  64. data/lib/samagotchi/terminal_ui/local_link.rb +7 -1
  65. data/lib/samagotchi/terminal_ui.rb +3 -3
  66. data/lib/samagotchi/testing/boundary.rb +2 -2
  67. data/lib/samagotchi/testing/bundle.rb +1 -1
  68. data/lib/samagotchi/tool_activity.rb +63 -79
  69. data/lib/samagotchi/tool_names.rb +179 -0
  70. data/lib/samagotchi/tool_view.rb +3 -5
  71. data/lib/samagotchi/tools/ask_user_question.rb +2 -1
  72. data/lib/samagotchi/tools/builtins.rb +1 -1
  73. data/lib/samagotchi/tools/cancel_reminder.rb +2 -1
  74. data/lib/samagotchi/tools/cancel_schedule.rb +3 -1
  75. data/lib/samagotchi/tools/context_read.rb +2 -1
  76. data/lib/samagotchi/tools/delegate.rb +2 -1
  77. data/lib/samagotchi/tools/delegate_result.rb +2 -1
  78. data/lib/samagotchi/tools/edit.rb +2 -1
  79. data/lib/samagotchi/tools/execute.rb +22 -28
  80. data/lib/samagotchi/tools/forget_outputs.rb +2 -1
  81. data/lib/samagotchi/tools/list_reminders.rb +2 -1
  82. data/lib/samagotchi/tools/list_schedules.rb +3 -1
  83. data/lib/samagotchi/tools/list_sessions.rb +2 -1
  84. data/lib/samagotchi/tools/memory.rb +3 -2
  85. data/lib/samagotchi/tools/objectives_tool.rb +5 -4
  86. data/lib/samagotchi/tools/read.rb +2 -1
  87. data/lib/samagotchi/tools/register_reminder.rb +2 -1
  88. data/lib/samagotchi/tools/schedule_task.rb +3 -1
  89. data/lib/samagotchi/tools/send_note.rb +2 -1
  90. data/lib/samagotchi/tools/task_create.rb +2 -1
  91. data/lib/samagotchi/tools/task_get.rb +2 -1
  92. data/lib/samagotchi/tools/task_list.rb +2 -1
  93. data/lib/samagotchi/tools/task_runtime.rb +29 -154
  94. data/lib/samagotchi/tools/task_stop.rb +2 -1
  95. data/lib/samagotchi/tools/task_wait.rb +3 -2
  96. data/lib/samagotchi/tools/web_fetch.rb +2 -1
  97. data/lib/samagotchi/tools/write.rb +2 -1
  98. data/lib/samagotchi/turn_checkpoint.rb +1 -1
  99. data/lib/samagotchi/version.rb +1 -1
  100. data/lib/samagotchi/web/app.rb +45 -37
  101. data/lib/samagotchi/web/message_display.rb +1 -7
  102. data/lib/samagotchi/web/participant_access.rb +12 -4
  103. data/lib/samagotchi/web/participant_history.rb +68 -0
  104. data/lib/samagotchi/web/participant_images.rb +2 -1
  105. data/lib/samagotchi/web/participant_show.rb +5 -5
  106. data/lib/samagotchi/web/participants_admin.rb +1 -1
  107. data/lib/samagotchi/web/public/app.js +24 -12
  108. data/lib/samagotchi/web/public/card_registry.js +248 -0
  109. data/lib/samagotchi/web/public/cards_offscreen.js +3 -3
  110. data/lib/samagotchi/web/public/cards_place.js +8 -2
  111. data/lib/samagotchi/web/public/chains.js +3 -3
  112. data/lib/samagotchi/web/public/data.js +12 -0
  113. data/lib/samagotchi/web/public/delete_sheet.js +344 -0
  114. data/lib/samagotchi/web/public/format.js +1 -1
  115. data/lib/samagotchi/web/public/history_shape.js +1 -2
  116. data/lib/samagotchi/web/public/index.html +27 -0
  117. data/lib/samagotchi/web/public/info_bar.js +3 -2
  118. data/lib/samagotchi/web/public/lists_view.js +2 -2
  119. data/lib/samagotchi/web/public/more_sheet.js +42 -5
  120. data/lib/samagotchi/web/public/participant_history.js +27 -0
  121. data/lib/samagotchi/web/public/question_cards.js +1 -15
  122. data/lib/samagotchi/web/public/reload_check.js +90 -72
  123. data/lib/samagotchi/web/public/session_actions.js +50 -6
  124. data/lib/samagotchi/web/public/session_view.js +6 -1
  125. data/lib/samagotchi/web/public/stage_asking.js +6 -20
  126. data/lib/samagotchi/web/public/stage_view.js +2 -2
  127. data/lib/samagotchi/web/public/stage_waiting.js +4 -10
  128. data/lib/samagotchi/web/public/task_stop.js +1 -1
  129. data/lib/samagotchi/web/push_routes.rb +1 -1
  130. data/lib/samagotchi/web/reload_check_route.rb +5 -2
  131. data/lib/samagotchi/web/request_body.rb +72 -0
  132. data/lib/samagotchi/web/server.rb +70 -0
  133. data/lib/samagotchi/web/session_access_routes.rb +13 -11
  134. data/lib/samagotchi/web/session_control.rb +79 -20
  135. data/lib/samagotchi/web/session_create.rb +2 -1
  136. data/lib/samagotchi/web/session_show.rb +8 -8
  137. data/lib/samagotchi/web/viewer.rb +7 -2
  138. data/lib/samagotchi/web/working_set_routes.rb +3 -3
  139. data/lib/samagotchi/worker.rb +49 -182
  140. data/lib/samagotchi/worker_exit_claim.rb +102 -0
  141. data/lib/samagotchi/worker_participant_gate.rb +156 -0
  142. data/lib/samagotchi/worker_task_wakes.rb +2 -2
  143. metadata +17 -1
@@ -376,13 +376,7 @@ module Samagotchi
376
376
  # reply), session-free. {html: nil} when markdown is off or
377
377
  # commonmarker is missing: the page keeps the raw text.
378
378
  def handle_render(req)
379
- too_large = error_response(413, "too_large", "a text to render may be up to #{MAX_RENDER_BYTES / 1024} KB")
380
- return too_large if req.content_length.to_i > MAX_RENDER_BYTES
381
-
382
- raw = request_body(req, MAX_RENDER_BYTES + 1).to_s
383
- return too_large if raw.bytesize > MAX_RENDER_BYTES
384
-
385
- body = parse_json(raw)
379
+ body = parse_json(request_body(req, MAX_RENDER_BYTES, what: "a text to render"))
386
380
  return error_response(400, "invalid_json", "give {text}") unless body.is_a?(Hash) && body["text"].is_a?(String)
387
381
 
388
382
  html = @markdown_renderer.render(body["text"]) if @markdown_renderer.available?
@@ -61,6 +61,8 @@ module Samagotchi
61
61
  # enqueued_id => grant id of the turns participants sent through this
62
62
  # chi web (their dequeue's check); the oldest go past PARTICIPANT_TURNS_KEPT.
63
63
  @participant_turns = {}
64
+ # A participant's own prompts' read-then-write (ParticipantHistory).
65
+ @participant_prompts_mutex = Mutex.new
64
66
  end
65
67
 
66
68
  PARTICIPANT_TURNS_KEPT = 1000
@@ -307,7 +309,8 @@ module Samagotchi
307
309
  # D10). Of the body only the prompt, the delivery and images they
308
310
  # uploaded count: the author and client id are the grant's
309
311
  # (participant:<id>), no no_interrupt; the owner's prompt history never
310
- # sees it. The delivery
312
+ # sees it: an accepted one goes into their own (ParticipantHistory),
313
+ # unless the body's history is false (an image-only send). The delivery
311
314
  # is queue or next step (none: next step): the worker puts a next-step
312
315
  # message into a running turn only when that turn is theirs, else it
313
316
  # runs as their own turn after it (Bridge#same_author_steer?; an older
@@ -340,7 +343,8 @@ module Samagotchi
340
343
  pending_limit: grant.queue_limit + 1,
341
344
  state_dir: @state_dir, manager: @manager,
342
345
  bridge: -> { live_bridge_client(id) })
343
- participant_turn_result(grant, prompt, result, images: images.empty? ? nil : images.size, revises: revises)
346
+ participant_turn_result(grant, prompt, result, images: images.empty? ? nil : images.size, revises: revises,
347
+ record: body["history"] != false)
344
348
  rescue SessionManager::OwnedByTUI => e
345
349
  owned_by_tui(e)
346
350
  end
@@ -404,13 +408,17 @@ module Samagotchi
404
408
  end
405
409
 
406
410
  # +images+: how many the turn carried (nil: none), +revises+ the turn
407
- # id its Revise draft named, for the audit line.
408
- def participant_turn_result(grant, prompt, result, images: nil, revises: nil)
411
+ # id its Revise draft named, for the audit line; +record+: whether an
412
+ # accepted one goes into their own prompts (ParticipantHistory). A
413
+ # turn the worker refuses later (at its start) or they take back stays
414
+ # recorded: chi web accepted it, as the owner's record_history.
415
+ def participant_turn_result(grant, prompt, result, images: nil, revises: nil, record: true)
409
416
  case result.status
410
417
  when :accepted
411
418
  enqueued_id = result.ack["enqueued_id"]
412
419
  remember_participant_turn(enqueued_id, grant.id)
413
420
  audit_turn(grant, prompt, status: "accepted", enqueued_id: enqueued_id, images: images, revises: revises)
421
+ record_participant_prompt(grant, prompt) if record
414
422
  # What the worker says will happen (a turn of its own, or into
415
423
  # their running turn at its next step); a file (no worker yet)
416
424
  # runs as the next turn, which reads as a queue.
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../participant_messages"
4
+ require_relative "../participant_prompts"
5
+ require_relative "../redact"
6
+ require_relative "../session"
7
+ require_relative "../log"
8
+
9
+ module Samagotchi
10
+ module Web
11
+ # A participant's own prompts for their composer's ↑/↓, mixed into App:
12
+ # recorded when chi web accepts their turn (ParticipantAccess#
13
+ # participant_turn_result), keyed by their grant's id, never by a body
14
+ # field. The owner's machine-wide PromptHistory (GET /api/history, an
15
+ # :owner route) is never read or written for a participant, and this
16
+ # route serves only the caller's own list, redacted. Uses App's @grants,
17
+ # @hub, @session_class, #default_state_dir, #principal, #owner_secrets
18
+ # (ParticipantReview) and @participant_prompts_mutex (set in
19
+ # ParticipantAccess#init_participant_access). See
20
+ # docs/internals/participants.md (A participant's prompt history).
21
+ module ParticipantHistory
22
+ # GET /api/sessions/:id/prompt_history (:participant, :session: the
23
+ # router answers another session's id as unknown first): the
24
+ # caller's own prompts, oldest first, each as their conversation shows
25
+ # it (Redact.text with their viewer: secret shapes, the owner's token
26
+ # and cookie, the session folder relative, home as ~), as {entries}.
27
+ # Keyed by the principal's grant only; no query or body is read. The
28
+ # owner's list is GET /api/history: here a plain 403 (no audit line,
29
+ # there's no grant to audit against).
30
+ def handle_prompt_history(req, _id)
31
+ principal = principal(req)
32
+ return error_response(403, "not_permitted", ParticipantMessages::NOT_PERMITTED) if principal.owner?
33
+
34
+ grant = principal.grant
35
+ dir = Session.session_dir(grant.session_id, state_dir: default_state_dir)
36
+ viewer = Redact::Viewer.new(author: grant.author, cwd: prompt_history_cwd(grant.session_id), secrets: owner_secrets)
37
+ json_response(200, { entries: ParticipantPrompts.entries(dir, grant.id).map { |entry| Redact.text(entry, viewer) } })
38
+ end
39
+
40
+ private
41
+
42
+ # The session's folder for the redaction: the hub's cached session (no
43
+ # session load), else (no hub, or one that hasn't seen it) the saved
44
+ # session's, as the show's viewer reads it (ParticipantReview#
45
+ # participant_viewer). A missing session raises ArgumentError: the
46
+ # :session route's unknown session.
47
+ def prompt_history_cwd(id)
48
+ @hub&.working_directory(id) || @session_class.load(id, state_dir: default_state_dir).working_directory
49
+ end
50
+
51
+ # Records +prompt+ as +grant+'s newest (ParticipantPrompts#append),
52
+ # with the session's grants the store still knows as the live ones
53
+ # (the others' lists are pruned). An over-long prompt is skipped before
54
+ # the lock. A failed write never fails the send.
55
+ def record_participant_prompt(grant, prompt)
56
+ return unless ParticipantPrompts.recordable(prompt)
57
+
58
+ dir = Session.session_dir(grant.session_id, state_dir: default_state_dir)
59
+ live = @grants.list(session_id: grant.session_id).map(&:id)
60
+ @participant_prompts_mutex.synchronize do
61
+ ParticipantPrompts.append(dir, grant_id: grant.id, text: prompt, live_grant_ids: live)
62
+ end
63
+ rescue StandardError => e
64
+ Log.warn(:web, "participant_prompt_write_failed", error: e.class.name, msg: e.message)
65
+ end
66
+ end
67
+ end
68
+ end
@@ -7,6 +7,7 @@ require_relative "../participant_uploads"
7
7
  require_relative "../participants"
8
8
  require_relative "../send_command"
9
9
  require_relative "../session"
10
+ require_relative "request_body"
10
11
 
11
12
  module Samagotchi
12
13
  module Web
@@ -85,7 +86,7 @@ module Samagotchi
85
86
  end
86
87
 
87
88
  bytes = image_upload_bytes(req)
88
- return Upload.refused(413, "too_large", image_too_large_detail) unless bytes
89
+ return Upload.refused(413, "too_large", bytes.message) if bytes.is_a?(RequestBody::BodyTooLarge)
89
90
 
90
91
  participant_store(dir, grant, bytes, upload_name(req))
91
92
  end
@@ -27,10 +27,10 @@ module Samagotchi
27
27
  private
28
28
 
29
29
  def participant_show_read(req, id)
30
- return participant_show(id) if req.params["brief"] == "1"
31
- return participant_cards_read(id) if req.params["cards"] == "1"
32
- return participant_tail_read(req, id) if req.params["tail"] == "1"
33
- return participant_timing_read(req, id) if req.params["timing"] == "1"
30
+ return participant_show(id) if req.GET["brief"] == "1"
31
+ return participant_cards_read(id) if req.GET["cards"] == "1"
32
+ return participant_tail_read(req, id) if req.GET["tail"] == "1"
33
+ return participant_timing_read(req, id) if req.GET["timing"] == "1"
34
34
 
35
35
  session = @session_class.load(id, state_dir: default_state_dir)
36
36
  participant_main_show(req, show_reads(id, session))
@@ -191,7 +191,7 @@ module Samagotchi
191
191
  session = @session_class.load(id, state_dir: default_state_dir)
192
192
  reads = show_reads(id, session)
193
193
  viewer = participant_viewer(req, session)
194
- turn_id = req.params["turn_id"].to_s.strip
194
+ turn_id = req.GET["turn_id"].to_s.strip
195
195
  raw = visible_replies(reads.raw_messages)
196
196
  shown = messages_for_display(raw, parts: true, cwd: session.working_directory, markdown: false)
197
197
  messages = ParticipantView.messages(shown, viewer)
@@ -90,7 +90,7 @@ module Samagotchi
90
90
  # /api/participants: revokes one participant, a session's or every
91
91
  # one's; their open streams end within a poll.
92
92
  def handle_participants_revoke(req, id = nil)
93
- grant_id = req.params["id"]
93
+ grant_id = req.GET["id"]
94
94
  if grant_id && !Grants::ID_RE.match?(grant_id.to_s)
95
95
  return error_response(400, "invalid_participant", "not a participant id: #{grant_id.to_s[0, 40]}")
96
96
  end
@@ -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,
@@ -50,7 +52,7 @@ import { createBubbles } from "./bubbles.js";
50
52
  import { createCardsPlace } from "./cards_place.js";
51
53
  import { createStageView } from "./stage_view.js";
52
54
  import { createReloadCheck } from "./reload_check.js";
53
- import { placeCardsOffscreen } from "./cards_offscreen.js";
55
+ import { createCardRegistry, observeCards } from "./card_registry.js";
54
56
  import { createWorkingSet } from "./working_set_view.js";
55
57
  import { createWorkingSetPreview } from "./ws_reader.js";
56
58
  import { createObjectives } from "./objectives_wiring.js";
@@ -77,6 +79,7 @@ import { answerLabel, installReviseStacks, reviseChipTemplate, reviseWorkerUnava
77
79
  import { createQuestionCards } from "./question_cards.js";
78
80
  import { PROMPT_LINE_PX, PROMPT_MIN_PX } from "./composer_size.js";
79
81
  import { mountComposer } from "./composer_mount.js";
82
+ import { hasHistory, historyLoader } from "./participant_history.js";
80
83
  import { createCommandList } from "./command_list.js";
81
84
  import { ALL_SESSIONS_HASH, sessionHash } from "./route.js";
82
85
  import { hashIntent } from "./hash_intent.js";
@@ -116,6 +119,7 @@ import { createUnqueue } from "./unqueue.js";
116
119
  import { createStartPage } from "./start_page.js";
117
120
  import { createSessionActions } from "./session_actions.js";
118
121
  import { createStopSheet } from "./stop_sheet.js";
122
+ import { createDeleteSheet } from "./delete_sheet.js";
119
123
  import { createVersionNotices } from "./version_notices.js";
120
124
  import { createRename } from "./session_rename.js";
121
125
  import { createSendTurn } from "./send_turn.js";
@@ -179,7 +183,10 @@ const settingsControl = viewer.can("session_controls") ? createSettingsControl({
179
183
  // ⋯ on the info bar, and its menu: the chips and buttons the row has no room for; and the bar's other buttons.
180
184
  const [continueBtn, archiveBtn, stopBtn, deleteBtn, moreBtn] = viewer.controls(
181
185
  ["#infoContinueBtn", "#infoArchiveBtn", "#infoStopBtn", "#infoDeleteBtn", "#infoMoreBtn"].map($), "session_controls");
182
- 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;
183
190
  // The bar's fold (bar_fold.js): one row, what doesn't fit folded into ⋯. A
184
191
  // resize, the fonts or a zoom refolds it by itself: ⋯ follows on the redraw.
185
192
  const barFold = createBarFold({ barEl: $("#infoBar"), keysFor: barItemKeys, onChange: () => store.touch("infoBar") });
@@ -373,6 +380,8 @@ const turnDom = createStageView({
373
380
  // The quiet signal (stage_stall.js): the stream, what the turn waits on, a joiner's step clock.
374
381
  streamLive: () => sessionSync.streamLive(), timingNote: () => liveTurn.timing.note, serverGen: () => liveTurn.serverGen,
375
382
  });
383
+ // The open session's cards as data (card_registry.js: fed by the stream's card events and renderSessionView's seed).
384
+ const cardRegistry = createCardRegistry();
376
385
  // The opt-in reload check (web.reload_check): a handed-off turn against a
377
386
  // reload of it, the counts to chi web (reload_check.js).
378
387
  const reloadCheck = createReloadCheck({
@@ -381,8 +390,7 @@ const reloadCheck = createReloadCheck({
381
390
  running: () => liveTurn.running,
382
391
  read: (id) => getSession(id),
383
392
  render: (data) => sessionView.reloadRender(data),
384
- place: (holder, entries) => placeCardsOffscreen(holder, entries, { capabilities: pageCapabilities, answers: viewer.can("answer_cards") }),
385
- capabilities: () => pageCapabilities,
393
+ cards: () => cardRegistry,
386
394
  post: (id, body) => api(`/api/sessions/${id}/reload_check`, { method: "POST", body: JSON.stringify(body) }),
387
395
  });
388
396
  // The history's bottom reserve and the toast's place follow the composer
@@ -443,7 +451,7 @@ const deliveryControl = createDeliveryControl({
443
451
  };
444
452
  },
445
453
  composerEmpty: () => !composer.hasDraft(),
446
- history: viewer.can("prompt_history"),
454
+ history: hasHistory(viewer),
447
455
  send: (delivery) => handleSendTurn({ delivery }),
448
456
  });
449
457
 
@@ -515,7 +523,7 @@ turnRoots().forEach((root) => root.addEventListener("click", cards.onCardAction)
515
523
  const sessionView = createSessionView({
516
524
  store, historyEl, getSession,
517
525
  liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet, wsPreview, gapClock,
518
- bubbles, cards, markdown: markdownPlace,
526
+ bubbles, cards, markdown: markdownPlace, cardRegistry,
519
527
  capabilities: () => pageCapabilities,
520
528
  page: {
521
529
  setReviseAnchor, renderInitRow, setMarkdownWarning, setCapabilities, findInTurnRoots, appendToHistory,
@@ -667,7 +675,7 @@ const lists = createListsView({
667
675
  eventsLive: () => !!eventsControl,
668
676
  refresh: () => refresh(),
669
677
  select: (id) => select(id),
670
- confirmDelete: (id) => confirmDelete(id),
678
+ confirmDelete: (id, options) => confirmDelete(id, options),
671
679
  setArchived: (id, archive) => setArchived(id, archive),
672
680
  archiveOne: (id, archive) => archiveOne(id, archive),
673
681
  updateSessionTitle: () => updateSessionTitle(),
@@ -691,12 +699,15 @@ const stopSheet = createStopSheet({
691
699
  stopSession: (id) => sessionActions.stopSelected(id),
692
700
  });
693
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
+
694
705
  const sessionActions = createSessionActions({
695
706
  selected: () => store.selected,
696
707
  store,
697
708
  sessions: () => store.sessions,
698
709
  setSessions: (list) => store.update({ sessions: list }),
699
- api: { continueSession, archiveSession, unarchiveSession, deleteSession, stopSession,
710
+ api: { continueSession, archiveSession, unarchiveSession, deleteSession, deleteChain, deletePlan, stopSession,
700
711
  sessionHolds, stopSessionHolds },
701
712
  eventsLive: () => !!eventsControl,
702
713
  refresh,
@@ -710,6 +721,7 @@ const sessionActions = createSessionActions({
710
721
  closeLiveStream: () => sessionSync.closeLive(),
711
722
  workerGone,
712
723
  stopSheet,
724
+ deleteSheet,
713
725
  });
714
726
  // The title's ✎: /title through the chips' path (session_rename.js), the
715
727
  // input over the title row on screen: the top bar's when it shows the
@@ -1133,7 +1145,7 @@ function turnEndStatus(data) {
1133
1145
 
1134
1146
  // The stream's event handlers (stream_handlers.js); renderSessionView
1135
1147
  // replays a snapshot through them too.
1136
- const streamHandlers = (participant ? participant.wrapHandlers : (handlers) => handlers)(createStreamHandlers({
1148
+ const streamHandlers = observeCards(cardRegistry, (participant ? participant.wrapHandlers : (handlers) => handlers)(createStreamHandlers({
1137
1149
  selected: () => store.selected,
1138
1150
  store,
1139
1151
  clientId,
@@ -1184,7 +1196,7 @@ const streamHandlers = (participant ? participant.wrapHandlers : (handlers) => h
1184
1196
  syncModelPick: startPage.commandRan,
1185
1197
  objectivesUpdated: (data) => objectives.update(data),
1186
1198
  cardActionFailed: cards.actionFailed,
1187
- }));
1199
+ })));
1188
1200
 
1189
1201
  async function refreshTimingFromSession() {
1190
1202
  if (!store.selected) return;
@@ -1339,8 +1351,8 @@ const composer = mountComposer({
1339
1351
  minPx: promptMinPx,
1340
1352
  toast: (text) => showToast(text),
1341
1353
  onWrite: () => noteDraft(),
1342
- // ↑/↓: the prompt history shared with the TUI.
1343
- loadHistory: viewer.can("prompt_history") ? fetchHistory : null,
1354
+ // ↑/↓: the owner's prompt history shared with the TUI; a participant's own messages here.
1355
+ loadHistory: historyLoader(viewer, { fetchHistory, selected: () => store.selected }),
1344
1356
  imagesOff: viewer.can("images") ? null : IMAGES_NOT_HERE,
1345
1357
  // Alt/Option+Enter: queued for after the running turn (D6), only to a
1346
1358
  // worker that queues (else it would steer): the text stays, a note says why.
@@ -0,0 +1,248 @@
1
+ // The open session's cards as data (A2 step 1): every question, continue
2
+ // offer and plugin card the page heard of, keyed as stage_waiting.js keys
3
+ // them (q:<id>, c:<id>, continue), with what it waits as (card_kinds.js) and
4
+ // where it stands. An observer: fed by the stream's card events
5
+ // (observeCards, around app.js's stream handlers, so a snapshot's replay
6
+ // feeds it too) and by a read (+seed+, session_view.js renderSessionView,
7
+ // right before the replay); reset when the page leaves the session
8
+ // (forgetSession). Its one reader is the opt-in reload check
9
+ // (reload_check.js): the turn's entries live against a registry seeded from a
10
+ // fresh read. Nothing on the page draws from it. Pure: no DOM.
11
+ //
12
+ // An entry: {key, kind, status, of_turn, opening_id, step, relayed_to,
13
+ // summary, actions?}. +status+: pending, answered, cancelled (questions),
14
+ // pending, resolved, dropped (the continue offer: dropped when the step
15
+ // limit's own question asks the same), asks / shown (a plugin card with or
16
+ // without actions it waits on). +of_turn+: the turn the card is a row of (a
17
+ // read's CardStore of_turn; live, the running turn's id when the card came
18
+ // in it: a live card or question carries none). +step+: {iteration, calls}
19
+ // of that turn when it came (CardStore's place), null outside a turn.
20
+ //
21
+ // Idempotent: an event or a read applied on an existing key merges; a final
22
+ // status (answered, cancelled, resolved, dropped) never goes back to pending
23
+ // (but the continue key, which has no id: a new offer after a resolved one
24
+ // is a new card); of_turn, opening_id and step keep the first non-null. So a
25
+ // read seeded then its replay applied is the registry live had at that point
26
+ // (card_registry.test.js, every stage cut).
27
+ //
28
+ // The turn's end: a question still pending when its turn ends is cancelled
29
+ // (session_view.js endTurnView cancels its card on the page, no event comes;
30
+ // CardStore lists it with neither answer nor cancel, and +seed+ reads such
31
+ // an entry of a turn that isn't running as cancelled too).
32
+ import { cardWait, continueWait, questionWait } from "./card_kinds.js";
33
+ import { measured, probing } from "./stage_probe.js";
34
+
35
+ const FINAL = new Set(["answered", "cancelled", "resolved", "dropped"]);
36
+ const CONTINUE_KEY = "continue";
37
+ const questionKey = (id) => (id == null || id === "" ? null : `q:${id}`);
38
+ const cardKey = (id) => (id == null || id === "" ? null : `c:${id}`);
39
+ const TURN_ENDS = ["turn_completed", "turn_canceled", "turn_failed"];
40
+
41
+ // The card events the registry takes (observeCards wraps these).
42
+ export const CARD_EVENTS = [
43
+ "turn_started", ...TURN_ENDS, "generation_started", "tool_call_started",
44
+ "question_requested", "question_answered", "question_cancelled", "question_relay",
45
+ "continue_offered", "continue_resolved", "card",
46
+ ];
47
+
48
+ // A card's actions as the entry keeps them: label and command only.
49
+ const actionsOf = (card) => (Array.isArray(card?.actions) ? card.actions.filter(Boolean).map((a) => ({ label: a.label ?? null, command: a.command ?? null })) : []);
50
+
51
+ export function createCardRegistry() {
52
+ const entries = new Map();
53
+ // The running turn (its id, null: none, or an older worker's turn with
54
+ // none) and the step it is on.
55
+ let turn = null;
56
+ let running = false;
57
+ let step = null;
58
+
59
+ const firstOf = (was, now) => (was ?? now ?? null);
60
+
61
+ // +key+ as +patch+ says (its undefined fields left out), merged into what
62
+ // was there.
63
+ function put(key, given) {
64
+ if (!key) return;
65
+ const patch = Object.fromEntries(Object.entries(given).filter(([, v]) => v !== undefined));
66
+ const was = entries.get(key);
67
+ if (!was) {
68
+ entries.set(key, {
69
+ key, kind: null, status: "pending", of_turn: null, opening_id: null, step: null, relayed_to: null, summary: "", ...patch,
70
+ });
71
+ return;
72
+ }
73
+ const status = FINAL.has(was.status) && !FINAL.has(patch.status ?? was.status) ? was.status : patch.status ?? was.status;
74
+ entries.set(key, {
75
+ ...was, ...patch, status,
76
+ of_turn: firstOf(was.of_turn, patch.of_turn), opening_id: firstOf(was.opening_id, patch.opening_id), step: firstOf(was.step, patch.step),
77
+ });
78
+ }
79
+
80
+ // A question's entry from its pending question (+pq+), with +extra+.
81
+ function putQuestion(pq, extra = {}) {
82
+ const key = questionKey(pq?.id);
83
+ if (!key) return;
84
+ const { kind, summary } = questionWait(pq);
85
+ const relayed = "relayed_to" in (pq || {}) ? { relayed_to: pq.relayed_to || null } : {};
86
+ put(key, { kind, summary, ...relayed, ...extra });
87
+ // The step limit's question asks what the old continue card asks.
88
+ if (kind === "continue") dropContinue();
89
+ }
90
+
91
+ function dropContinue() {
92
+ const was = entries.get(CONTINUE_KEY);
93
+ if (was && was.status === "pending") entries.set(CONTINUE_KEY, { ...was, status: "dropped" });
94
+ }
95
+
96
+ const pendingContinueQuestion = () => [...entries.values()].some((e) => e.kind === "continue" && e.key !== CONTINUE_KEY && e.status === "pending");
97
+
98
+ function putContinue(offer) {
99
+ const was = entries.get(CONTINUE_KEY);
100
+ // No id: a new offer after a settled one is a new card.
101
+ if (was && FINAL.has(was.status) && was.status !== "dropped") entries.delete(CONTINUE_KEY);
102
+ const { kind, summary } = continueWait(offer);
103
+ put(CONTINUE_KEY, { kind, summary, status: "pending" });
104
+ if (pendingContinueQuestion()) dropContinue();
105
+ }
106
+
107
+ // A plugin card (+card+: a live card event or a read's entry).
108
+ function putCard(card, extra = {}) {
109
+ const key = cardKey(card?.id);
110
+ if (!key) return;
111
+ const { kind, summary } = cardWait(card);
112
+ put(key, { kind, summary, status: kind === "asks" ? "asks" : "shown", actions: actionsOf(card), ...extra });
113
+ }
114
+
115
+ // Live: a card of the running turn takes the turn's id and its step.
116
+ const liveTurnOf = (inTurn) => (inTurn && running ? { of_turn: turn, step } : {});
117
+
118
+ function endTurn(data) {
119
+ const ended = data?.turn_id || turn;
120
+ if (ended) {
121
+ for (const e of entries.values()) {
122
+ if (e.of_turn === ended && e.status === "pending" && e.key.startsWith("q:")) entries.set(e.key, { ...e, status: "cancelled" });
123
+ }
124
+ }
125
+ turn = null;
126
+ running = false;
127
+ step = null;
128
+ }
129
+
130
+ // Only a question the registry knows (its request or a read listed it).
131
+ function settleQuestion(id, status) {
132
+ const key = questionKey(id);
133
+ if (key && entries.has(key)) put(key, { status });
134
+ }
135
+
136
+ const APPLY = {
137
+ turn_started: (data) => {
138
+ turn = data?.turn_id || null;
139
+ running = true;
140
+ step = null;
141
+ },
142
+ turn_completed: endTurn,
143
+ turn_canceled: endTurn,
144
+ turn_failed: endTurn,
145
+ generation_started: (data) => {
146
+ if (running) step = { iteration: data?.iteration ?? null, calls: 0 };
147
+ },
148
+ tool_call_started: (data) => {
149
+ if (running) step = { iteration: data?.iteration ?? step?.iteration ?? null, calls: Number(data?.call_index) || 0 };
150
+ },
151
+ question_requested: (data) => {
152
+ const pq = data?.pending_question;
153
+ if (pq?.id) putQuestion(pq, liveTurnOf(true));
154
+ },
155
+ question_answered: (data) => settleQuestion(data?.id, "answered"),
156
+ question_cancelled: (data) => settleQuestion(data?.id, "cancelled"),
157
+ question_relay: (data) => {
158
+ const key = questionKey(data?.id);
159
+ if (key && entries.has(key)) put(key, { relayed_to: data.relayed_to || null });
160
+ },
161
+ continue_offered: (data) => putContinue(data),
162
+ continue_resolved: () => {
163
+ if (entries.has(CONTINUE_KEY) && entries.get(CONTINUE_KEY).status === "pending") put(CONTINUE_KEY, { status: "resolved" });
164
+ },
165
+ card: (data) => putCard(data, liveTurnOf(!!data?.in_turn)),
166
+ };
167
+
168
+ // A read's question entry (CardStore: its pending question, answer or
169
+ // cancel; of_turn, opening_id, its step).
170
+ function seedQuestion(entry, runningId) {
171
+ const pq = entry.pending_question;
172
+ const status = entry.answer ? "answered" : entry.cancelled ? "cancelled"
173
+ // Neither: open while its turn runs, else its turn ended on it.
174
+ : entry.current || (entry.of_turn && entry.of_turn === runningId) ? "pending" : "cancelled";
175
+ putQuestion(pq, { status, ...placeOf(entry) });
176
+ }
177
+
178
+ const placeOf = (entry) => ({
179
+ of_turn: entry.of_turn ?? null,
180
+ opening_id: entry.opening_id ?? null,
181
+ step: entry.iteration == null ? null : { iteration: entry.iteration, calls: Number(entry.calls) || 0 },
182
+ });
183
+
184
+ function seedFrom(read) {
185
+ entries.clear();
186
+ const runningId = read?.current_turn ? read.current_turn.turn_id || null : null;
187
+ turn = runningId;
188
+ running = !!read?.current_turn;
189
+ step = null;
190
+ for (const entry of Array.isArray(read?.cards) ? read.cards : []) {
191
+ if (entry?.type === "question" && entry.pending_question?.id) seedQuestion(entry, runningId);
192
+ else if (entry?.type === "card") putCard(entry, placeOf(entry));
193
+ }
194
+ const pq = read?.pending_question;
195
+ if (pq?.id && pq.status === "pending") putQuestion(pq, { status: "pending" });
196
+ if (read?.continue_offer) putContinue(read.continue_offer);
197
+ }
198
+
199
+ return {
200
+ // One stream event (+type+, +data+), as observeCards hands them.
201
+ apply(type, data) {
202
+ APPLY[type]?.(data || {});
203
+ },
204
+ // A read of the session (the full GET, or a stage cut's show): its
205
+ // CardStore listing, its pending question and continue offer. Replaces
206
+ // what was there.
207
+ seed(read) {
208
+ measured("cards:seed", () => seedFrom(read));
209
+ return this;
210
+ },
211
+ reset() {
212
+ entries.clear();
213
+ turn = null;
214
+ running = false;
215
+ step = null;
216
+ },
217
+ get: (key) => (entries.has(key) ? { ...entries.get(key) } : null),
218
+ // Every entry, in the order the registry first heard of it.
219
+ list: () => [...entries.values()].map((e) => ({ ...e })),
220
+ // The entries that are rows of +turnId+ (of_turn).
221
+ forTurn: (turnId) => [...entries.values()].filter((e) => turnId != null && e.of_turn === turnId).map((e) => ({ ...e })),
222
+ size: () => entries.size,
223
+ // The running turn's id (null: none running, or it has no id).
224
+ turn: () => (running ? turn : null),
225
+ };
226
+ }
227
+
228
+ // +handlers+ (the stream's, app.js) with the card events wrapped: the
229
+ // page's handler first, then the registry's apply (a throw in apply never
230
+ // reaches the page). Like participant_main.js wrapHandlers. With the perf
231
+ // probe on (stage_probe.js), each apply is timed ("cards:apply") and the
232
+ // page gets globalThis.chiCardRegistry: its size and its entries' JSON bytes.
233
+ export function observeCards(registry, handlers) {
234
+ if (!registry) return handlers;
235
+ if (probing()) globalThis.chiCardRegistry = { size: () => registry.size(), bytes: () => JSON.stringify(registry.list()).length };
236
+ const wrapped = { ...handlers };
237
+ for (const type of CARD_EVENTS) {
238
+ const original = handlers[type];
239
+ wrapped[type] = (data) => {
240
+ const out = original?.(data);
241
+ try {
242
+ measured("cards:apply", () => registry.apply(type, data));
243
+ } catch (_) { /* an observer never breaks the page */ }
244
+ return out;
245
+ };
246
+ }
247
+ return wrapped;
248
+ }
@@ -1,7 +1,7 @@
1
1
  // A snapshot's cards placed into a holder that is not the page (cards_offscreen.js):
2
- // the opt-in reload check (reload_check.js) draws a handed-off turn offscreen and
3
- // compares it with what the page has. A reload's render (turnHistoryNodes) doesn't
4
- // run the placement (cards_place.js placeSnapshotCards), so the check needs its own.
2
+ // the old reload check's placer. Nothing imports it now (reload_check.js compares
3
+ // the turn's cards as data, card_registry.js); it stays one release for a stale
4
+ // app.js that still imports it (a 404 would blank the page), then it goes.
5
5
  //
6
6
  // It is the real placer, not a copy: createCardsPlace, createBubbles and
7
7
  // createQuestionCards over a detached holder, with every page hook made inert:
@@ -168,9 +168,13 @@ export function createCardsPlace({
168
168
  if (!pq?.id || !(entry.answer || entry.cancelled)) return;
169
169
  const turnEls = reloadedTurnEls(historyEl, before);
170
170
  const asked = Number(entry.iteration) || 1;
171
+ const block = turnEls.find((el) => el.matches(".turn-work"));
171
172
  // The reply that asked: its step's text in the reloaded block (the card
172
- // keeps it, as live), never the running turn's.
173
- const said = stepText(turnEls.find((el) => el.matches(".turn-work")), asked);
173
+ // keeps it, as live), never the running turn's; the step's first card
174
+ // only, as live (stage_asking.js askingGen: a step's text goes to one card).
175
+ const taken = block ? keptSteps.get(block) || new Set() : null;
176
+ const said = taken?.has(asked) ? "" : stepText(block, asked);
177
+ if (block && said) keptSteps.set(block, taken.add(asked));
174
178
  questionCards.renderQuestion(pq, { said });
175
179
  const card = questionCards.questionCard();
176
180
  if (!card || card.dataset.qid !== String(pq.id)) return;
@@ -178,6 +182,8 @@ export function createCardsPlace({
178
182
  const later = turnEls.find((el) => el.matches(".bubble.user.steered") && Number(el.dataset.step) > asked);
179
183
  historyEl.insertBefore(card, later || turnAnswerEl(turnEls) || before);
180
184
  }
185
+ // The steps whose reply a reloaded question card kept, by block.
186
+ const keptSteps = new WeakMap();
181
187
 
182
188
  // A live card's body comes as text; the worker's snapshot (through the
183
189
  // server) has it rendered. One re-read for a burst of cards.
@@ -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
  }