samagotchi 0.106.0 → 0.107.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 (87) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +121 -1
  3. data/bin/chi +2 -0
  4. data/docs/architecture.md +4 -0
  5. data/docs/cli.md +45 -5
  6. data/docs/guardrails.md +8 -2
  7. data/docs/internals/participants.md +126 -30
  8. data/docs/internals/remote-sessions.md +12 -5
  9. data/docs/plugins.md +29 -1
  10. data/docs/releasing.md +2 -0
  11. data/docs/sessions.md +36 -1
  12. data/docs/sub-agent.md +2 -0
  13. data/docs/testing.md +2 -0
  14. data/lib/samagotchi/bridge/turn_accumulator.rb +6 -0
  15. data/lib/samagotchi/bridge.rb +4 -0
  16. data/lib/samagotchi/bridge_client/stream_request.rb +10 -3
  17. data/lib/samagotchi/bundles/coordinator/manifest.yml +6 -5
  18. data/lib/samagotchi/bundles/coordinator/plugin.rb +85 -5
  19. data/lib/samagotchi/bundles/coordinator/skill_coordinator.md +18 -0
  20. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  21. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  22. data/lib/samagotchi/continue_offer.rb +51 -4
  23. data/lib/samagotchi/guardrails/review_boundary.rb +6 -57
  24. data/lib/samagotchi/guardrails/review_paths.rb +93 -0
  25. data/lib/samagotchi/model_profile.rb +5 -3
  26. data/lib/samagotchi/parent_report.rb +23 -1
  27. data/lib/samagotchi/participant_messages.rb +11 -0
  28. data/lib/samagotchi/participants.rb +20 -6
  29. data/lib/samagotchi/plugin/api.rb +2 -1
  30. data/lib/samagotchi/plugin/sessions.rb +25 -0
  31. data/lib/samagotchi/remote_command.rb +1 -1
  32. data/lib/samagotchi/remotes.rb +23 -8
  33. data/lib/samagotchi/review_apply.rb +123 -0
  34. data/lib/samagotchi/review_command.rb +121 -0
  35. data/lib/samagotchi/review_start.rb +161 -0
  36. data/lib/samagotchi/run_options.rb +17 -2
  37. data/lib/samagotchi/send_command/wait_target.rb +5 -0
  38. data/lib/samagotchi/send_command.rb +2 -0
  39. data/lib/samagotchi/session.rb +33 -5
  40. data/lib/samagotchi/session_access/contract.rb +10 -2
  41. data/lib/samagotchi/session_access/dispatch.rb +8 -2
  42. data/lib/samagotchi/session_access/http_transport.rb +10 -1
  43. data/lib/samagotchi/session_access/local.rb +19 -2
  44. data/lib/samagotchi/session_access/remote.rb +15 -1
  45. data/lib/samagotchi/session_access/web_bridge_client.rb +1 -1
  46. data/lib/samagotchi/session_access.rb +23 -10
  47. data/lib/samagotchi/session_chain.rb +10 -2
  48. data/lib/samagotchi/session_continue.rb +4 -3
  49. data/lib/samagotchi/session_manager.rb +30 -8
  50. data/lib/samagotchi/session_review.rb +28 -0
  51. data/lib/samagotchi/share_command.rb +7 -1
  52. data/lib/samagotchi/terminal_ui/attached_loop.rb +4 -1
  53. data/lib/samagotchi/testing/sessions.rb +10 -2
  54. data/lib/samagotchi/turn_checkpoint.rb +13 -0
  55. data/lib/samagotchi/version.rb +1 -1
  56. data/lib/samagotchi/web/app.rb +106 -21
  57. data/lib/samagotchi/web/grants.rb +90 -16
  58. data/lib/samagotchi/web/participant_access.rb +82 -26
  59. data/lib/samagotchi/web/participant_review.rb +45 -2
  60. data/lib/samagotchi/web/participant_stream_filter.rb +118 -17
  61. data/lib/samagotchi/web/participant_view.rb +12 -1
  62. data/lib/samagotchi/web/public/app.js +60 -5
  63. data/lib/samagotchi/web/public/chip_popover.js +10 -3
  64. data/lib/samagotchi/web/public/data.js +10 -2
  65. data/lib/samagotchi/web/public/delivery_line.js +79 -15
  66. data/lib/samagotchi/web/public/index.html +26 -0
  67. data/lib/samagotchi/web/public/info_bar.js +7 -3
  68. data/lib/samagotchi/web/public/info_bar_model.js +7 -1
  69. data/lib/samagotchi/web/public/live_turn.js +3 -0
  70. data/lib/samagotchi/web/public/participant.html +58 -5
  71. data/lib/samagotchi/web/public/participant.js +171 -24
  72. data/lib/samagotchi/web/public/participant_model.js +84 -24
  73. data/lib/samagotchi/web/public/participant_names.js +36 -4
  74. data/lib/samagotchi/web/public/participants_panel.js +84 -16
  75. data/lib/samagotchi/web/public/question_cards.js +1 -0
  76. data/lib/samagotchi/web/public/review_apply.js +34 -0
  77. data/lib/samagotchi/web/public/review_start.js +101 -0
  78. data/lib/samagotchi/web/public/send_turn.js +25 -1
  79. data/lib/samagotchi/web/public/session_actions.js +44 -3
  80. data/lib/samagotchi/web/public/session_state.js +3 -0
  81. data/lib/samagotchi/web/public/start_page.js +38 -2
  82. data/lib/samagotchi/web/public/stream_handlers.js +10 -0
  83. data/lib/samagotchi/web/public/turn_html.js +2 -1
  84. data/lib/samagotchi/web/public/turn_view.js +5 -0
  85. data/lib/samagotchi/web/session_summary.rb +3 -0
  86. data/lib/samagotchi/worker.rb +16 -4
  87. metadata +8 -1
@@ -3,6 +3,8 @@
3
3
  require_relative "participant_view"
4
4
  require_relative "participant_stream_filter"
5
5
  require_relative "../session_metrics"
6
+ require_relative "../review_start"
7
+ require_relative "../guardrails/review_paths"
6
8
 
7
9
  module Samagotchi
8
10
  module Web
@@ -19,6 +21,10 @@ module Samagotchi
19
21
  # cursor and its join. Not client_id (a stream named as a TUI's would
20
22
  # count as one), not raw.
21
23
  STREAM_KEYS = %w[from_seq snapshot].freeze
24
+ # How much of each review subject the page gets; the rest is cut
25
+ # (+truncated+).
26
+ SUBJECT_BYTES = 256 * 1024
27
+ MARKDOWN_EXT = %w[.md .markdown .mdown .mkd].freeze
22
28
 
23
29
  private
24
30
 
@@ -38,8 +44,8 @@ module Samagotchi
38
44
 
39
45
  # GET /api/sessions/:id/review: the participant page's data, always
40
46
  # filtered (the owner gets the participant view of it).
41
- # @return {viewer, session, participants, messages, current_turn,
42
- # waiting_for_owner, queued: {mine, others}, last_event_id}
47
+ # @return {viewer, session, subjects, participants, messages,
48
+ # current_turn, waiting_for_owner, queued: {mine, others}, last_event_id}
43
49
  def handle_review(req, id)
44
50
  session = @session_class.load(id, state_dir: default_state_dir)
45
51
  viewer = participant_viewer(req, session)
@@ -55,6 +61,7 @@ module Samagotchi
55
61
  json_response(200, {
56
62
  viewer: review_viewer(req, id),
57
63
  session: { id: session.id, title: participant_title(session), status: displayed_status(session, state) },
64
+ subjects: review_subjects(session, viewer),
58
65
  participants: participant_names(id).map { |entry| entry.slice(:id, :name, :kind) },
59
66
  messages: with_reply_html(ParticipantView.messages(shown, viewer, automatic: automatic)),
60
67
  current_turn: current,
@@ -64,6 +71,42 @@ module Samagotchi
64
71
  })
65
72
  end
66
73
 
74
+ # A review session's subjects as the page shows them (the Plan view):
75
+ # each {path, text, html (markdown only), truncated}, or {path,
76
+ # missing: true} for one that is gone or that ReviewPaths refuses now
77
+ # (it became a symlink out of the project, say): checked at every
78
+ # read, as a review turn's read is. The text is cut at SUBJECT_BYTES
79
+ # and redacted like everything else a participant gets; [] for a
80
+ # session that isn't a review session.
81
+ def review_subjects(session, viewer)
82
+ review = session.review or return []
83
+ root = ReviewStart.root_for(session.working_directory)
84
+ check = Guardrails::ReviewPaths.new(root: root)
85
+ review.subjects.map do |path|
86
+ # The real path is checked and read, the file with O_NOFOLLOW: a
87
+ # symlink swapped in for it after the check isn't followed. Only
88
+ # the last component: a folder swapped for a symlink in between
89
+ # still is, which takes write access to the project (the owner's).
90
+ real = File.realpath(File.expand_path(path, root))
91
+ next { path: path, missing: true } unless File.file?(real) && check.refusal([real]).nil?
92
+
93
+ review_subject(path, real, viewer)
94
+ rescue SystemCallError
95
+ { path: path, missing: true }
96
+ end
97
+ end
98
+
99
+ def review_subject(path, full, viewer)
100
+ raw = File.open(full, File::RDONLY | File::NOFOLLOW | File::BINARY) { |file| file.read(SUBJECT_BYTES + 1) }.to_s
101
+ text = ParticipantView::Redact.text(raw.byteslice(0, SUBJECT_BYTES).force_encoding(Encoding::UTF_8).scrub, viewer)
102
+ entry = { path: path, text: text, truncated: raw.bytesize > SUBJECT_BYTES }
103
+ markdown = MARKDOWN_EXT.include?(File.extname(path).downcase)
104
+ entry[:html] = @markdown_renderer.render(text) if markdown && @markdown_renderer.available?
105
+ entry
106
+ rescue SystemCallError
107
+ { path: path, missing: true }
108
+ end
109
+
67
110
  # The saved messages with each model message's content as a
68
111
  # participant may read it (ParticipantView.visible_raw: no cut-off
69
112
  # thought or tool call left as text).
@@ -15,10 +15,15 @@ module Samagotchi
15
15
  #
16
16
  # The reply's text is sent by whole lines: a secret the model streams
17
17
  # over two chunks is redacted as one (Redact sees the line), and a
18
- # private key block is withheld from its BEGIN line to its END line.
18
+ # private key block is withheld from its BEGIN line to its END line (a
19
+ # block left open, to the turn's end: TURN_BOUNDARY).
19
20
  # The rest of a line waits for its end, a boundary (a tool call, the
20
21
  # turn's end, the owner's question) or MAX_HELD characters (then up to
21
- # its last space).
22
+ # its last space). A cut never splits a secret: never inside what
23
+ # Redact would redact in the held text, nor after a key word whose
24
+ # value is still to come (Redact::OPEN_VALUE); past MAX_HELD * 4 with
25
+ # no such space, the held text goes out redacted but its last unbroken
26
+ # run, which with the rest of its line is one [redacted].
22
27
  #
23
28
  # One per stream (it keeps the partial frame and line between chunks),
24
29
  # called from the stream's one thread.
@@ -34,6 +39,10 @@ module Samagotchi
34
39
  # The events before which the held text goes out.
35
40
  FLUSH_BEFORE = %w[tool_call_started turn_completed turn_canceled turn_failed question_requested continue_offered
36
41
  snapshot reset].freeze
42
+ # A turn's start and end: a private key block the reply left open is
43
+ # withheld to here (fail closed within the turn), not to the stream's
44
+ # end.
45
+ TURN_BOUNDARY = %w[turn_started turn_completed turn_canceled turn_failed].freeze
37
46
  PEM_BEGIN = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/
38
47
  PEM_END = /-----END [A-Z0-9 ]*PRIVATE KEY-----/
39
48
 
@@ -44,6 +53,10 @@ module Samagotchi
44
53
  @held = +""
45
54
  @held_iteration = nil
46
55
  @in_key = false
56
+ # While a hard cut drops the rest of its line (#hard_cut): the last
57
+ # of what it dropped, and whether that holds a key's BEGIN line.
58
+ @dropped = nil
59
+ @dropped_key = false
47
60
  end
48
61
 
49
62
  # @param chunk [String] the Bridge's next read
@@ -90,20 +103,23 @@ module Samagotchi
90
103
 
91
104
  if shown["type"] == "generation_retrying" && shown["restarted"]
92
105
  @held = +""
106
+ @dropped = nil
93
107
  return frame(id, shown)
94
108
  end
95
- return flush + frame(id, shown) if FLUSH_BEFORE.include?(shown["type"])
109
+ boundary = TURN_BOUNDARY.include?(shown["type"])
110
+ return frame(id, shown) unless boundary || FLUSH_BEFORE.include?(shown["type"])
96
111
 
97
- frame(id, shown)
112
+ out = flush
113
+ @in_key = @dropped_key = false if boundary
114
+ out + frame(id, shown)
98
115
  end
99
116
 
100
117
  # A reply chunk: its text joins the held line; the whole lines go out.
101
118
  def chunk(event, shown, id)
102
119
  @held_iteration = shown["iteration"]
103
- @held << event["text"].to_s
104
- cut = @held.rindex("\n")
105
- cut ||= @held.rindex(/\s/) if @held.size > MAX_HELD
106
- cut ||= @held.size - 1 if @held.size > MAX_HELD * 4
120
+ @held << undropped(event["text"].to_s)
121
+ cut = safe_cut
122
+ return hard_cut(id, shown) if cut.nil? && @held.size > MAX_HELD * 4
107
123
  return "" unless cut
108
124
 
109
125
  text = @held[0..cut]
@@ -112,8 +128,80 @@ module Samagotchi
112
128
  out.empty? ? "" : frame(id, shown.merge("text" => out))
113
129
  end
114
130
 
131
+ # MAX_HELD * 4 held with no safe cut (one unbroken run, mostly): the
132
+ # held text goes out redacted but for its last run, which with the rest
133
+ # of its line is one MARK (fail closed: it may be a secret's start).
134
+ def hard_cut(id, shown)
135
+ text = @held.sub(/\S*\z/, "")
136
+ # A key word or a key's BEGIN line before that run goes with it.
137
+ open = ParticipantView::Redact::OPEN_VALUE.match(text[-80..] || text)
138
+ text = text[0, text.size - open[0].size] if open
139
+ @dropped = +""
140
+ @dropped_key = false
141
+ dropping = @held[text.size..]
142
+ @held = +""
143
+ @held << undropped(dropping)
144
+ frame(id, shown.merge("text" => "#{lines_of(text)}#{ParticipantView::Redact::MARK}"))
145
+ end
146
+
147
+ # The last newline (past MAX_HELD, the last space) the held text may
148
+ # be cut after: not inside a secret Redact would match in it, and not
149
+ # where a secret's value would follow. nil: hold on.
150
+ def safe_cut
151
+ spaces = (@held.size > MAX_HELD ? /\s/ : /\n/)
152
+ spans = nil
153
+ at = @held.size
154
+ while (at = at.positive? && @held.rindex(spaces, at - 1))
155
+ spans ||= secret_spans(@held)
156
+ return at unless spans.any? { |from, to| from <= at && at < to } || open_value?(at)
157
+ end
158
+ nil
159
+ end
160
+
161
+ # Whether the held text up to +at+ (a cut's last character) ends where
162
+ # a secret's value would go on.
163
+ def open_value?(at)
164
+ from = [at - 80, 0].max
165
+ ParticipantView::Redact::OPEN_VALUE.match?(@held[from..at])
166
+ end
167
+
168
+ SPAN_PATTERNS = (ParticipantView::Redact::PATTERNS - [ParticipantView::Redact::PRIVATE_KEY] +
169
+ ParticipantView::Redact::VALUES).freeze
170
+
171
+ # [from, to) of every match Redact would redact in +text+ (but a
172
+ # private key's block: lines_of withholds it by its lines).
173
+ def secret_spans(text)
174
+ literals = @viewer.secrets.map { |secret| Regexp.new(Regexp.escape(secret)) }
175
+ (literals + SPAN_PATTERNS).flat_map do |pattern|
176
+ text.to_enum(:scan, pattern).map { Regexp.last_match.offset(0) }
177
+ end
178
+ end
179
+
180
+ # +text+ without what a hard cut drops: the rest of its line. A
181
+ # private key's BEGIN line in what it dropped (read through a window:
182
+ # the line may be long) withholds its block still.
183
+ def undropped(text)
184
+ return text unless @dropped
185
+
186
+ line_end = text.index("\n")
187
+ window = @dropped + text[0, line_end || text.size]
188
+ last_begin = window.rindex(PEM_BEGIN)
189
+ last_end = window.rindex(PEM_END)
190
+ @dropped_key = (last_begin || -1) > (last_end || -1) if last_begin || last_end
191
+ @dropped = window[-DROPPED_WINDOW..] || window
192
+ return "" unless line_end
193
+
194
+ @in_key = true if @dropped_key
195
+ @dropped = nil
196
+ text[line_end..]
197
+ end
198
+
199
+ # Longer than a BEGIN or END line.
200
+ DROPPED_WINDOW = 80
201
+
115
202
  # The held text as a chunk of its own (no cursor), before a boundary.
116
203
  def flush
204
+ @dropped = nil
117
205
  return "" if @held.empty?
118
206
 
119
207
  text = lines_of(@held)
@@ -123,19 +211,32 @@ module Samagotchi
123
211
  frame(nil, { "type" => "generation_chunk", "text" => text, **(@held_iteration ? { "iteration" => @held_iteration } : {}) })
124
212
  end
125
213
 
126
- # +text+'s lines redacted, a private key block's withheld whole.
214
+ # +text+ redacted (each run of lines as one, so a secret over a line
215
+ # break is redacted as one), a private key block's withheld whole.
127
216
  def lines_of(text)
128
- text.each_line.map do |line|
217
+ out = +""
218
+ run = +""
219
+ text.each_line do |line|
129
220
  if @in_key
130
- @in_key = false if PEM_END.match?(line)
131
- next ""
132
- end
133
- if PEM_BEGIN.match?(line) && !PEM_END.match?(line)
221
+ @in_key = opens_key?(line) if PEM_END.match?(line)
222
+ elsif opens_key?(line)
223
+ out << ParticipantView::Redact.text(run, @viewer)
224
+ run = +""
134
225
  @in_key = true
135
- next "#{ParticipantView::Redact::MARK}#{"\n" if line.end_with?("\n")}"
226
+ out << "#{ParticipantView::Redact::MARK}#{"\n" if line.end_with?("\n")}"
227
+ else
228
+ run << line
136
229
  end
137
- ParticipantView::Redact.text(line, @viewer)
138
- end.join
230
+ end
231
+ out << ParticipantView::Redact.text(run, @viewer)
232
+ end
233
+
234
+ # Whether +line+ leaves a private key block open: a BEGIN line with
235
+ # no END after it (an END and the next BEGIN may share a line).
236
+ def opens_key?(line)
237
+ last_begin = line.rindex(PEM_BEGIN) or return false
238
+ last_end = line.rindex(PEM_END)
239
+ last_end.nil? || last_begin > last_end
139
240
  end
140
241
 
141
242
  def frame(id, shown)
@@ -346,6 +346,12 @@ module Samagotchi
346
346
  out.gsub(/\u0000(\d+)\u0000/) { held[Regexp.last_match(1).to_i] }
347
347
  end
348
348
 
349
+ # A turn's saved reply (the reply file a wait reads) as a participant
350
+ # may read it: no cut-off or closed thinking or tool call, redacted.
351
+ def reply(text, viewer)
352
+ Redact.text(OutputFormatter.strip_markup(visible_raw(text)), viewer)
353
+ end
354
+
349
355
  def field(hash, key)
350
356
  return nil unless hash.is_a?(Hash)
351
357
 
@@ -358,8 +364,9 @@ module Samagotchi
358
364
  # in a reply, or one in a prompt.
359
365
  module Redact
360
366
  MARK = "[redacted]"
367
+ PRIVATE_KEY = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----.*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|\z)/m
361
368
  PATTERNS = [
362
- /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----.*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|\z)/m,
369
+ PRIVATE_KEY,
363
370
  /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}/,
364
371
  /\bgh[pousr]_[A-Za-z0-9]{20,}/,
365
372
  /\bgithub_pat_[A-Za-z0-9_]{20,}/,
@@ -378,6 +385,10 @@ module Samagotchi
378
385
  # A URL's password: scheme://user:PASSWORD@host.
379
386
  %r{(\b[a-z][a-z0-9+.-]*://[^/\s:@]+:)[^@\s/]+(?=@)}i
380
387
  ].freeze
388
+ # A text that ends where one of VALUES' values (or a private key's
389
+ # BEGIN line) would go on: a stream cut there would send the value
390
+ # on its own, unredacted (ParticipantStreamFilter never cuts there).
391
+ OPEN_VALUE = /(?:\bAuthorization:\s*(?:(?:Bearer|Basic|Token)\s*)?|[A-Za-z0-9_-]*?(?:token|api[_-]?key|access[_-]?key|secret|password|passwd)["']?\s*(?:[=:]\s*["']?)?|-----BEGIN [A-Z0-9 ]*)\z/i
381
392
 
382
393
  module_function
383
394
 
@@ -13,6 +13,7 @@ import {
13
13
  openEvents,
14
14
  createIdleSession,
15
15
  continueSession,
16
+ startReview,
16
17
  uploadImage,
17
18
  listModels,
18
19
  fetchHistory,
@@ -46,6 +47,8 @@ import { createMarkdownPlace } from "./markdown_place.js";
46
47
  import { openerFill, openTitle, restoredComposer } from "./chains.js";
47
48
  import { createTaskStopper } from "./task_stop.js";
48
49
  import { appendQuote } from "./annotations.js";
50
+ import { applyComposerText, applyRowTemplate, fetchApply } from "./review_apply.js";
51
+ import { authorBadge, nameUnnamedBadges } from "./participant_names.js";
49
52
  import { parsePresets } from "./annotate_presets.js";
50
53
  import { createAnnotateBar } from "./annotate_bar.js";
51
54
  import { actionLine, annotationActions, composerWithAction } from "./annotate_actions.js";
@@ -147,6 +150,10 @@ const participantsControl = createParticipantsControl({
147
150
  el: infoTextEl,
148
151
  session: () => selected,
149
152
  api: { list: listParticipants, invite: inviteParticipant, revoke: revokeParticipant, cap: setParticipantCap },
153
+ startReview: (opts) => sessionActions.reviewSelected(opts),
154
+ reviewing: () => sessionActions.reviewing.has(selected),
155
+ // An older prompt drawn before the list came says "a participant": named now.
156
+ onNames: () => nameUnnamedBadges(document),
150
157
  onChange: () => updateInfoBar(),
151
158
  toast: (text) => showToast(text),
152
159
  });
@@ -161,6 +168,7 @@ const startPage = createStartPage({
161
168
  centerEl: $("#center"),
162
169
  llmContextEl: $("#llmContextNew"),
163
170
  thinkingEl: $("#thinkingNew"),
171
+ reviewEl: $("#reviewNew"),
164
172
  selected: () => selected,
165
173
  state: () => current,
166
174
  running: () => liveTurn.running,
@@ -311,10 +319,12 @@ const deliveryControl = createDeliveryControl({
311
319
  serverGen: liveTurn.serverGen,
312
320
  canQueue: current.workerFeatures.includes("delivery"),
313
321
  model: current.model,
322
+ participantTurn: !!liveTurn.participantTurn,
314
323
  };
315
324
  },
316
325
  composerEmpty: () => !promptEl.value.trim() && !chips.length,
317
326
  send: (delivery) => handleSendTurn({ delivery }),
327
+ session: () => selected,
318
328
  });
319
329
 
320
330
  // This tab's id in the session's events: tells its own prompts from the
@@ -526,7 +536,7 @@ const sessionActions = createSessionActions({
526
536
  state: () => current,
527
537
  sessions: () => allSessions,
528
538
  setSessions: (list) => { allSessions = list; },
529
- api: { continueSession, archiveSession, unarchiveSession, deleteSession, stopSession },
539
+ api: { continueSession, startReview, archiveSession, unarchiveSession, deleteSession, stopSession },
530
540
  eventsLive: () => !!eventsControl,
531
541
  refresh,
532
542
  lists,
@@ -799,6 +809,10 @@ function clearNotice() {
799
809
  }
800
810
  promptEl.addEventListener("input", clearNotice);
801
811
  promptEl.addEventListener("input", () => noteDraft());
812
+ // An emptied composer lets go of its Apply turn.
813
+ promptEl.addEventListener("input", () => {
814
+ if (!promptEl.value.trim()) deliveryControl.release();
815
+ });
802
816
 
803
817
  async function select(id) {
804
818
  clearNotice();
@@ -1101,6 +1115,36 @@ infoTextEl.addEventListener("click", async (e) => {
1101
1115
  setTimeout(updateInfoBar, 2000);
1102
1116
  });
1103
1117
 
1118
+ // Apply (review_apply.js) under a participant's review turn that just
1119
+ // ended live ({turn_id, author, author_name}, from its turn_started), once:
1120
+ // a reload draws it from the history (turn_view.js).
1121
+ function placeApply(data) {
1122
+ const badge = authorBadge(data.author, data.author_name);
1123
+ if (!badge || historyEl.querySelector(`.review-apply[data-apply-turn="${CSS.escape(data.turn_id)}"]`)) return;
1124
+ appendToHistory(elementOf(applyRowTemplate(data.turn_id, badge)));
1125
+ }
1126
+
1127
+ // Apply: the owner's Apply turn into the composer, after what is typed
1128
+ // there; never sent from here.
1129
+ historyEl.addEventListener("click", async (e) => {
1130
+ const button = e.target.closest(".review-apply-btn");
1131
+ if (!button || !selected) return;
1132
+ const id = selected;
1133
+ button.disabled = true;
1134
+ try {
1135
+ const text = await fetchApply(id, button.dataset.applyTurn);
1136
+ if (id === selected) {
1137
+ fillComposer(applyComposerText(promptEl.value, text));
1138
+ // The owner's own turn: queued after a running one, never steered in.
1139
+ deliveryControl.hold();
1140
+ }
1141
+ } catch (err) {
1142
+ showToast(err.message);
1143
+ } finally {
1144
+ button.disabled = false;
1145
+ }
1146
+ });
1147
+
1104
1148
  // The open session's worker badge (info_bar_model.js workerBadgeFor).
1105
1149
  function currentWorkerBadge() {
1106
1150
  return workerBadgeFor(selected, current, versions);
@@ -1315,6 +1359,7 @@ const streamHandlers = createStreamHandlers({
1315
1359
  reasoningHistoryControl,
1316
1360
  workingSet,
1317
1361
  participantsControl,
1362
+ placeApply,
1318
1363
  sentIds,
1319
1364
  earlyRestores,
1320
1365
  stream: {
@@ -1461,9 +1506,19 @@ function runSessionCommand(line) {
1461
1506
 
1462
1507
  function clearComposer() {
1463
1508
  promptEl.value = "";
1509
+ deliveryControl.release();
1464
1510
  fitPrompt();
1465
1511
  }
1466
1512
 
1513
+ // A queue (Alt+Enter, or an Apply turn's Enter) to a worker that can't
1514
+ // queue (it would steer): not sent, the text kept, a note says why.
1515
+ function queueRefused(altKey) {
1516
+ if (!selected || !liveTurn.running || current.workerFeatures.includes("delivery")) return false;
1517
+ if (!altKey && !deliveryControl.held()) return false;
1518
+ addCommandBubble({ label: null, line: promptEl.value.trim(), text: QUEUE_NEEDS_WORKER, failed: true });
1519
+ return true;
1520
+ }
1521
+
1467
1522
  async function handleCancel() {
1468
1523
  if (!selected) return;
1469
1524
  cancelBtn.disabled = true;
@@ -1489,7 +1544,9 @@ $("#newBtn").addEventListener("click", () => {
1489
1544
  startPage.loadModels({ asked: true });
1490
1545
  });
1491
1546
 
1492
- actionBtn.addEventListener("click", () => handleSendTurn());
1547
+ actionBtn.addEventListener("click", () => {
1548
+ if (!queueRefused(false)) handleSendTurn();
1549
+ });
1493
1550
 
1494
1551
  // ── Images: paste or drop into the composer, chips until sent ─────────────
1495
1552
  const chipsEl = $("#chips");
@@ -1672,9 +1729,7 @@ promptEl.addEventListener("keydown", (e) => {
1672
1729
  if (!selected) handleSendTurn();
1673
1730
  // Alt/Option+Enter: queued for after the running turn (D6), only to a
1674
1731
  // worker that queues (else it would steer): the text stays, a note says why.
1675
- else if (e.altKey && liveTurn.running && !current.workerFeatures.includes("delivery")) {
1676
- addCommandBubble({ label: null, line: promptEl.value.trim(), text: QUEUE_NEEDS_WORKER, failed: true });
1677
- } else handleSendTurn(e.altKey ? { delivery: "queue" } : {});
1732
+ else if (!queueRefused(e.altKey)) handleSendTurn(e.altKey ? { delivery: "queue" } : {});
1678
1733
  }
1679
1734
  });
1680
1735
  $("#infoStopBtn").addEventListener("click", () => sessionActions.stopSelected());
@@ -44,15 +44,17 @@ export function sheetPlace({ innerWidth, innerHeight }) {
44
44
  // show(data, opening): draws the form into the popover (opening: a fresh
45
45
  // open, else a refresh with a newer summary); onClose(): the caller forgets
46
46
  // its open state; onSubmit(form); onAct(name): a data-act other than close.
47
- // sheet: a bottom sheet in a narrow window (sheetPlace).
47
+ // sheet: a bottom sheet in a narrow window (sheetPlace). label: the
48
+ // dialog's accessible name (aria-label), none by default.
48
49
  // @return {pop, open, close, refresh, isOpen, opener}
49
50
  export function createChipPopover({ id, className, width: widest, el, anchor: anchorSel, openers = anchorSel, summary,
50
51
  session = () => null, show, onClose = () => {}, onSubmit, onAct = () => {},
51
- sheet = false, doc = document, win = window }) {
52
+ sheet = false, label = null, doc = document, win = window }) {
52
53
  const pop = doc.createElement("div");
53
54
  pop.id = id;
54
55
  pop.className = className;
55
56
  pop.setAttribute("role", "dialog");
57
+ if (label) pop.setAttribute("aria-label", label);
56
58
  pop.hidden = true;
57
59
  doc.body.appendChild(pop);
58
60
  // The session the open form is for, and the element that opened it.
@@ -136,13 +138,18 @@ export function createChipPopover({ id, className, width: widest, el, anchor: an
136
138
  e.preventDefault();
137
139
  onSubmit(e.target);
138
140
  });
141
+ let ownClick = null;
139
142
  pop.addEventListener("click", (e) => {
143
+ ownClick = e;
140
144
  const act = e.target.closest("[data-act]")?.dataset.act;
141
145
  if (act === "close") close();
142
146
  else if (act) onAct(act);
143
147
  });
148
+ // A click the popover itself had is inside, even when its act redrew the
149
+ // clicked button away (Cap swapped for its field): by the time it reaches
150
+ // the document that button is no longer in the popover.
144
151
  doc.addEventListener("click", (e) => {
145
- if (isOpen() && !pop.contains(e.target) && !e.target.closest?.(openers)) close();
152
+ if (isOpen() && e !== ownClick && !pop.contains(e.target) && !e.target.closest?.(openers)) close();
146
153
  });
147
154
  doc.addEventListener("keydown", (e) => {
148
155
  if (e.key === "Escape" && isOpen()) close({ refocus: true });
@@ -41,8 +41,10 @@ export function listSessions(sort, order, { dir, ...opts } = {}) {
41
41
  // session's own LLM context words ({strategy, apply, budget}), when the
42
42
  // start page's chip set some; thinking: its own level ("low"), when the
43
43
  // start page's think chip set one.
44
- export function createIdleSession({ dir, model, preview, llm_context: llmContext, thinking, ...opts } = {}) {
45
- const body = { idle: true, ...(dir ? { dir } : {}), ...(model ? { model } : {}), ...(preview ? { preview } : {}),
44
+ // review: {subjects} makes it a review session (it starts idle; no preview).
45
+ export function createIdleSession({ dir, model, preview, llm_context: llmContext, thinking, review, ...opts } = {}) {
46
+ const start = review ? { review } : { idle: true, ...(preview ? { preview } : {}) };
47
+ const body = { ...start, ...(dir ? { dir } : {}), ...(model ? { model } : {}),
46
48
  ...(llmContext ? { llm_context: llmContext } : {}), ...(thinking ? { thinking } : {}) };
47
49
  return api("/api/sessions", { method: "POST", body: JSON.stringify(body), ...opts });
48
50
  }
@@ -56,6 +58,12 @@ export function continueSession(id, opts = {}) {
56
58
  return api("/api/sessions", { method: "POST", body: JSON.stringify({ continues: id, idle: true }), ...opts });
57
59
  }
58
60
 
61
+ // A review fork of +id+ (docs/sessions.md, Review sessions): a new session in
62
+ // its folder, seeded with its recap, not its transcript; +id+ keeps running.
63
+ export function startReview(id, opts = {}) {
64
+ return api("/api/sessions", { method: "POST", body: JSON.stringify({ review: { from: id } }), ...opts });
65
+ }
66
+
59
67
  // The models a new session can start on: {default, models: [{name, host, id}],
60
68
  // warning?} (a host that failed is in the warning, the list has the rest).
61
69
  export function listModels(opts = {}) {