samagotchi 0.172.1 → 0.173.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 (115) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +31 -1
  3. data/docs/architecture.md +16 -5
  4. data/docs/cli.md +2 -1
  5. data/docs/configuration.md +1 -1
  6. data/docs/internals/background-tasks.md +19 -6
  7. data/docs/internals/bridge.md +2 -2
  8. data/docs/internals/engine.md +2 -1
  9. data/docs/internals/participants.md +67 -9
  10. data/docs/internals/remote-sessions.md +1 -1
  11. data/docs/internals/web-frontend.md +11 -6
  12. data/docs/plugins.md +3 -1
  13. data/docs/sessions.md +2 -2
  14. data/docs/testing.md +26 -10
  15. data/lib/samagotchi/bridge.rb +3 -2
  16. data/lib/samagotchi/bundle_command/try/sandbox.rb +2 -2
  17. data/lib/samagotchi/bundles/core/manifest.yml +2 -2
  18. data/lib/samagotchi/bundles/slow-commands/manifest.yml +3 -3
  19. data/lib/samagotchi/bundles/slow-commands/plugin.rb +3 -3
  20. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  21. data/lib/samagotchi/engine/participants.rb +2 -2
  22. data/lib/samagotchi/engine.rb +0 -1
  23. data/lib/samagotchi/file_ref.rb +3 -5
  24. data/lib/samagotchi/guardrails/participant_refusal.rb +1 -1
  25. data/lib/samagotchi/memory_usage.rb +2 -1
  26. data/lib/samagotchi/message_parts.rb +5 -3
  27. data/lib/samagotchi/objectives_backing.rb +6 -10
  28. data/lib/samagotchi/parent_report.rb +1 -1
  29. data/lib/samagotchi/participant_prompts.rb +101 -0
  30. data/lib/samagotchi/participant_turn_mode.rb +1 -1
  31. data/lib/samagotchi/project_env.rb +7 -5
  32. data/lib/samagotchi/prompt_history.rb +2 -2
  33. data/lib/samagotchi/send_command/parent_gate.rb +2 -2
  34. data/lib/samagotchi/send_command.rb +4 -4
  35. data/lib/samagotchi/session_command_catalog.rb +210 -0
  36. data/lib/samagotchi/session_commands.rb +12 -183
  37. data/lib/samagotchi/session_manager/lifecycle.rb +5 -4
  38. data/lib/samagotchi/session_manager.rb +2 -1
  39. data/lib/samagotchi/session_stores.rb +2 -0
  40. data/lib/samagotchi/spawn_env.rb +75 -0
  41. data/lib/samagotchi/task_files.rb +51 -0
  42. data/lib/samagotchi/task_transcript.rb +67 -0
  43. data/lib/samagotchi/task_watch.rb +8 -6
  44. data/lib/samagotchi/terminal_ui/attached_loop/composer.rb +3 -3
  45. data/lib/samagotchi/terminal_ui/attached_loop/questions.rb +2 -2
  46. data/lib/samagotchi/terminal_ui/attached_loop.rb +3 -3
  47. data/lib/samagotchi/terminal_ui/input_support.rb +1 -1
  48. data/lib/samagotchi/testing/boundary.rb +5 -0
  49. data/lib/samagotchi/tool_activity.rb +63 -79
  50. data/lib/samagotchi/tool_names.rb +179 -0
  51. data/lib/samagotchi/tool_view.rb +3 -5
  52. data/lib/samagotchi/tools/ask_user_question.rb +2 -1
  53. data/lib/samagotchi/tools/builtins.rb +1 -1
  54. data/lib/samagotchi/tools/cancel_reminder.rb +2 -1
  55. data/lib/samagotchi/tools/cancel_schedule.rb +3 -1
  56. data/lib/samagotchi/tools/context_read.rb +2 -1
  57. data/lib/samagotchi/tools/delegate.rb +2 -1
  58. data/lib/samagotchi/tools/delegate_result.rb +2 -1
  59. data/lib/samagotchi/tools/edit.rb +2 -1
  60. data/lib/samagotchi/tools/execute.rb +22 -28
  61. data/lib/samagotchi/tools/forget_outputs.rb +2 -1
  62. data/lib/samagotchi/tools/list_reminders.rb +2 -1
  63. data/lib/samagotchi/tools/list_schedules.rb +3 -1
  64. data/lib/samagotchi/tools/list_sessions.rb +2 -1
  65. data/lib/samagotchi/tools/memory.rb +3 -2
  66. data/lib/samagotchi/tools/objectives_tool.rb +5 -4
  67. data/lib/samagotchi/tools/read.rb +2 -1
  68. data/lib/samagotchi/tools/register_reminder.rb +2 -1
  69. data/lib/samagotchi/tools/schedule_task.rb +3 -1
  70. data/lib/samagotchi/tools/send_note.rb +2 -1
  71. data/lib/samagotchi/tools/task_create.rb +2 -1
  72. data/lib/samagotchi/tools/task_get.rb +2 -1
  73. data/lib/samagotchi/tools/task_list.rb +2 -1
  74. data/lib/samagotchi/tools/task_runtime.rb +34 -154
  75. data/lib/samagotchi/tools/task_stop.rb +2 -1
  76. data/lib/samagotchi/tools/task_wait.rb +3 -2
  77. data/lib/samagotchi/tools/web_fetch.rb +2 -1
  78. data/lib/samagotchi/tools/write.rb +2 -1
  79. data/lib/samagotchi/turn_checkpoint.rb +1 -1
  80. data/lib/samagotchi/version.rb +1 -1
  81. data/lib/samagotchi/web/app.rb +38 -36
  82. data/lib/samagotchi/web/message_display.rb +1 -7
  83. data/lib/samagotchi/web/participant_access.rb +12 -4
  84. data/lib/samagotchi/web/participant_history.rb +68 -0
  85. data/lib/samagotchi/web/participant_images.rb +2 -1
  86. data/lib/samagotchi/web/participant_show.rb +5 -5
  87. data/lib/samagotchi/web/participants_admin.rb +1 -1
  88. data/lib/samagotchi/web/public/app.js +11 -9
  89. data/lib/samagotchi/web/public/card_registry.js +248 -0
  90. data/lib/samagotchi/web/public/cards_offscreen.js +3 -3
  91. data/lib/samagotchi/web/public/cards_place.js +8 -2
  92. data/lib/samagotchi/web/public/history_shape.js +1 -2
  93. data/lib/samagotchi/web/public/participant_history.js +27 -0
  94. data/lib/samagotchi/web/public/question_cards.js +1 -15
  95. data/lib/samagotchi/web/public/reload_check.js +90 -72
  96. data/lib/samagotchi/web/public/session_view.js +6 -1
  97. data/lib/samagotchi/web/public/stage_asking.js +6 -20
  98. data/lib/samagotchi/web/public/stage_view.js +2 -2
  99. data/lib/samagotchi/web/public/stage_waiting.js +4 -10
  100. data/lib/samagotchi/web/public/task_stop.js +1 -1
  101. data/lib/samagotchi/web/push_routes.rb +1 -1
  102. data/lib/samagotchi/web/reload_check_route.rb +5 -2
  103. data/lib/samagotchi/web/request_body.rb +72 -0
  104. data/lib/samagotchi/web/server.rb +70 -0
  105. data/lib/samagotchi/web/session_access_routes.rb +13 -11
  106. data/lib/samagotchi/web/session_control.rb +21 -15
  107. data/lib/samagotchi/web/session_create.rb +2 -1
  108. data/lib/samagotchi/web/session_show.rb +8 -8
  109. data/lib/samagotchi/web/viewer.rb +7 -2
  110. data/lib/samagotchi/web/working_set_routes.rb +3 -3
  111. data/lib/samagotchi/worker.rb +49 -182
  112. data/lib/samagotchi/worker_exit_claim.rb +102 -0
  113. data/lib/samagotchi/worker_participant_gate.rb +156 -0
  114. data/lib/samagotchi/worker_task_wakes.rb +2 -2
  115. metadata +13 -1
@@ -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
@@ -50,7 +50,7 @@ import { createBubbles } from "./bubbles.js";
50
50
  import { createCardsPlace } from "./cards_place.js";
51
51
  import { createStageView } from "./stage_view.js";
52
52
  import { createReloadCheck } from "./reload_check.js";
53
- import { placeCardsOffscreen } from "./cards_offscreen.js";
53
+ import { createCardRegistry, observeCards } from "./card_registry.js";
54
54
  import { createWorkingSet } from "./working_set_view.js";
55
55
  import { createWorkingSetPreview } from "./ws_reader.js";
56
56
  import { createObjectives } from "./objectives_wiring.js";
@@ -77,6 +77,7 @@ import { answerLabel, installReviseStacks, reviseChipTemplate, reviseWorkerUnava
77
77
  import { createQuestionCards } from "./question_cards.js";
78
78
  import { PROMPT_LINE_PX, PROMPT_MIN_PX } from "./composer_size.js";
79
79
  import { mountComposer } from "./composer_mount.js";
80
+ import { hasHistory, historyLoader } from "./participant_history.js";
80
81
  import { createCommandList } from "./command_list.js";
81
82
  import { ALL_SESSIONS_HASH, sessionHash } from "./route.js";
82
83
  import { hashIntent } from "./hash_intent.js";
@@ -373,6 +374,8 @@ const turnDom = createStageView({
373
374
  // The quiet signal (stage_stall.js): the stream, what the turn waits on, a joiner's step clock.
374
375
  streamLive: () => sessionSync.streamLive(), timingNote: () => liveTurn.timing.note, serverGen: () => liveTurn.serverGen,
375
376
  });
377
+ // The open session's cards as data (card_registry.js: fed by the stream's card events and renderSessionView's seed).
378
+ const cardRegistry = createCardRegistry();
376
379
  // The opt-in reload check (web.reload_check): a handed-off turn against a
377
380
  // reload of it, the counts to chi web (reload_check.js).
378
381
  const reloadCheck = createReloadCheck({
@@ -381,8 +384,7 @@ const reloadCheck = createReloadCheck({
381
384
  running: () => liveTurn.running,
382
385
  read: (id) => getSession(id),
383
386
  render: (data) => sessionView.reloadRender(data),
384
- place: (holder, entries) => placeCardsOffscreen(holder, entries, { capabilities: pageCapabilities, answers: viewer.can("answer_cards") }),
385
- capabilities: () => pageCapabilities,
387
+ cards: () => cardRegistry,
386
388
  post: (id, body) => api(`/api/sessions/${id}/reload_check`, { method: "POST", body: JSON.stringify(body) }),
387
389
  });
388
390
  // The history's bottom reserve and the toast's place follow the composer
@@ -443,7 +445,7 @@ const deliveryControl = createDeliveryControl({
443
445
  };
444
446
  },
445
447
  composerEmpty: () => !composer.hasDraft(),
446
- history: viewer.can("prompt_history"),
448
+ history: hasHistory(viewer),
447
449
  send: (delivery) => handleSendTurn({ delivery }),
448
450
  });
449
451
 
@@ -515,7 +517,7 @@ turnRoots().forEach((root) => root.addEventListener("click", cards.onCardAction)
515
517
  const sessionView = createSessionView({
516
518
  store, historyEl, getSession,
517
519
  liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet, wsPreview, gapClock,
518
- bubbles, cards, markdown: markdownPlace,
520
+ bubbles, cards, markdown: markdownPlace, cardRegistry,
519
521
  capabilities: () => pageCapabilities,
520
522
  page: {
521
523
  setReviseAnchor, renderInitRow, setMarkdownWarning, setCapabilities, findInTurnRoots, appendToHistory,
@@ -1133,7 +1135,7 @@ function turnEndStatus(data) {
1133
1135
 
1134
1136
  // The stream's event handlers (stream_handlers.js); renderSessionView
1135
1137
  // replays a snapshot through them too.
1136
- const streamHandlers = (participant ? participant.wrapHandlers : (handlers) => handlers)(createStreamHandlers({
1138
+ const streamHandlers = observeCards(cardRegistry, (participant ? participant.wrapHandlers : (handlers) => handlers)(createStreamHandlers({
1137
1139
  selected: () => store.selected,
1138
1140
  store,
1139
1141
  clientId,
@@ -1184,7 +1186,7 @@ const streamHandlers = (participant ? participant.wrapHandlers : (handlers) => h
1184
1186
  syncModelPick: startPage.commandRan,
1185
1187
  objectivesUpdated: (data) => objectives.update(data),
1186
1188
  cardActionFailed: cards.actionFailed,
1187
- }));
1189
+ })));
1188
1190
 
1189
1191
  async function refreshTimingFromSession() {
1190
1192
  if (!store.selected) return;
@@ -1339,8 +1341,8 @@ const composer = mountComposer({
1339
1341
  minPx: promptMinPx,
1340
1342
  toast: (text) => showToast(text),
1341
1343
  onWrite: () => noteDraft(),
1342
- // ↑/↓: the prompt history shared with the TUI.
1343
- loadHistory: viewer.can("prompt_history") ? fetchHistory : null,
1344
+ // ↑/↓: the owner's prompt history shared with the TUI; a participant's own messages here.
1345
+ loadHistory: historyLoader(viewer, { fetchHistory, selected: () => store.selected }),
1344
1346
  imagesOff: viewer.can("images") ? null : IMAGES_NOT_HERE,
1345
1347
  // Alt/Option+Enter: queued for after the running turn (D6), only to a
1346
1348
  // 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.
@@ -89,8 +89,7 @@ function rowItem(el) {
89
89
 
90
90
  function cardItem(el) {
91
91
  const card = item("card", `${el.dataset.cardId || ""} ${textOf(el.querySelector(".card-title"))}`.trim());
92
- // Its id on its own (already in the text): the reload check keeps a turn's
93
- // own cards by it and drops the rest (reload_check.js).
92
+ // Its id on its own (already in the text).
94
93
  card.id = el.dataset.cardId || "";
95
94
  return card;
96
95
  }
@@ -0,0 +1,27 @@
1
+ // A participant's ↑/↓ list: their own accepted messages in this session,
2
+ // oldest first, as their conversation shows them (redacted), from
3
+ // GET /api/sessions/<id>/prompt_history (Web::ParticipantHistory; the
4
+ // viewer's own_prompt_history). Never the owner's /api/history. A module of
5
+ // its own for the mixed-cache rule (docs/internals/web-frontend.md).
6
+ import { api } from "./data.js";
7
+
8
+ export function fetchOwnHistory(id, opts = {}) {
9
+ return api(`/api/sessions/${encodeURIComponent(id)}/prompt_history`, opts)
10
+ .then((j) => (Array.isArray(j.entries) ? j.entries : []));
11
+ }
12
+
13
+ // The composer's loadHistory for +viewer+: the owner's shared history, a
14
+ // participant's own for the selected session, or null (no ↑ list).
15
+ export function historyLoader(viewer, { fetchHistory, selected }) {
16
+ if (viewer.can("prompt_history")) return fetchHistory;
17
+ if (!viewer.can("own_prompt_history")) return null;
18
+ return () => {
19
+ const id = selected();
20
+ return id ? fetchOwnHistory(id) : Promise.resolve([]);
21
+ };
22
+ }
23
+
24
+ // Whether the delivery line's idle hint names ↑ history.
25
+ export function hasHistory(viewer) {
26
+ return viewer.can("prompt_history") || viewer.can("own_prompt_history");
27
+ }
@@ -24,8 +24,7 @@ import { clientLabel, isOwn } from "./turn_events.js";
24
24
  import { continueLine } from "./commands.js";
25
25
  import { plainText } from "./plain_line.js";
26
26
  import { noContactFill } from "./no_contact_fill.js";
27
- import { CONTINUE_KEY, foldKey, questionKey } from "./stage_waiting.js";
28
- import { readSession, removeSession } from "./storage.js";
27
+ import { CONTINUE_KEY, questionKey } from "./stage_waiting.js";
29
28
  import { continueWait, questionText, questionWait } from "./card_kinds.js";
30
29
 
31
30
  // A card's text fields' name: not a contact field (no_contact_fill.js).
@@ -625,18 +624,6 @@ export function createQuestionCards({
625
624
  continueEl = null;
626
625
  }
627
626
 
628
- // Mixed cache, for one release (remove in A1 phase 5): the fold kept for the
629
- // old continue card goes here too, so a stale app.js or stage_waiting.js
630
- // (no done) can't leave it behind. Only that card's: a question's fold is
631
- // the stage's (stage_waiting.js settle). No session, no key ("null").
632
- function dropContinueFold() {
633
- const fold = foldKey(sessionId());
634
- if (!fold) return;
635
- try {
636
- if (JSON.parse(readSession(fold) || "null")?.key === CONTINUE_KEY) removeSession(fold);
637
- } catch (_) { /* unreadable: left as it is */ }
638
- }
639
-
640
627
  function renderContinueCard(offer) {
641
628
  if (!answers || continueEl?.isConnected) return;
642
629
  // A step-limit question is up: it is the card (an older worker has none).
@@ -703,7 +690,6 @@ export function createQuestionCards({
703
690
  continueEl = null;
704
691
  if (!card) return;
705
692
  card.classList.add("resolved");
706
- dropContinueFold();
707
693
  onSettled(CONTINUE_KEY, { done: true });
708
694
  card.querySelectorAll("button, input").forEach((el) => { el.disabled = true; });
709
695
  const note = doc.createElement("div");