samagotchi 0.181.0 → 0.182.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 (67) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +26 -1
  3. data/bin/chi +1 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/cli.md +30 -4
  6. data/docs/configuration.md +1 -0
  7. data/docs/internals/block-renderers.md +114 -0
  8. data/docs/internals/bridge.md +10 -0
  9. data/docs/internals/engine.md +11 -0
  10. data/docs/internals/inline-widgets.md +3 -1
  11. data/docs/internals/prompt-caching.md +9 -1
  12. data/docs/internals/remote-sessions.md +14 -2
  13. data/docs/internals/web-frontend.md +33 -3
  14. data/docs/sessions.md +7 -4
  15. data/lib/samagotchi/answer_display.rb +3 -2
  16. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  17. data/lib/samagotchi/block_fix.rb +220 -0
  18. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  19. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  20. data/lib/samagotchi/bridge.rb +11 -2
  21. data/lib/samagotchi/bridge_client.rb +9 -0
  22. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  23. data/lib/samagotchi/config.rb +3 -0
  24. data/lib/samagotchi/continue_intent.rb +8 -0
  25. data/lib/samagotchi/engine/block_fix.rb +332 -0
  26. data/lib/samagotchi/engine/side_requests.rb +7 -5
  27. data/lib/samagotchi/engine.rb +4 -0
  28. data/lib/samagotchi/events.rb +1 -0
  29. data/lib/samagotchi/idle_client.rb +10 -6
  30. data/lib/samagotchi/inline_widgets.rb +12 -0
  31. data/lib/samagotchi/kernel_loop.rb +7 -5
  32. data/lib/samagotchi/llm/chat_loop.rb +2 -0
  33. data/lib/samagotchi/markdown_parser.rb +28 -0
  34. data/lib/samagotchi/session_access/contract.rb +3 -0
  35. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  36. data/lib/samagotchi/session_access/local.rb +13 -0
  37. data/lib/samagotchi/session_access/remote.rb +19 -1
  38. data/lib/samagotchi/session_access.rb +1 -0
  39. data/lib/samagotchi/session_chain/delete.rb +39 -81
  40. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  41. data/lib/samagotchi/session_delete_command.rb +129 -3
  42. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  43. data/lib/samagotchi/session_manager/listing.rb +4 -4
  44. data/lib/samagotchi/session_manager/removal.rb +38 -12
  45. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  46. data/lib/samagotchi/session_manager.rb +1 -0
  47. data/lib/samagotchi/version.rb +1 -1
  48. data/lib/samagotchi/web/app.rb +13 -1
  49. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  50. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  51. data/lib/samagotchi/web/message_display.rb +6 -1
  52. data/lib/samagotchi/web/participant_view.rb +1 -1
  53. data/lib/samagotchi/web/public/app.js +5 -5
  54. data/lib/samagotchi/web/public/block_fix.js +270 -0
  55. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  56. data/lib/samagotchi/web/public/block_frame.js +6 -3
  57. data/lib/samagotchi/web/public/block_host.js +1 -1
  58. data/lib/samagotchi/web/public/block_renderers.css +12 -0
  59. data/lib/samagotchi/web/public/block_watch.js +16 -2
  60. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  61. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  62. data/lib/samagotchi/web/public/turn_block.js +5 -2
  63. data/lib/samagotchi/web/server.rb +6 -4
  64. data/lib/samagotchi/web/session_control.rb +53 -21
  65. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  66. data/lib/samagotchi/worker.rb +10 -3
  67. metadata +12 -1
@@ -70,15 +70,20 @@ module Samagotchi
70
70
  # An archive that can't happen now: a turn runs in the session or in one
71
71
  # of its children (+busy_id+ names which), it is a scratch session, or
72
72
  # (:tasks_running) background tasks it or a delegate started still run
73
- # (+tasks+, a RunningTasks::Listing).
73
+ # (+tasks+, a RunningTasks::Listing; +sessions+, how many sessions the
74
+ # archive would hide: it and its delegates, across every project;
75
+ # +stopped_workers+, every worker it stopped first, for the words).
74
76
  class ArchiveRefused < StandardError
75
- attr_reader :session_id, :reason, :busy_id, :tasks, :stopped_worker
77
+ attr_reader :session_id, :reason, :busy_id, :tasks, :stopped_worker, :sessions, :stopped_workers
76
78
 
77
- def initialize(session_id, reason, busy_id: nil, tasks: RunningTasks::EMPTY, worker_stopped: false)
79
+ def initialize(session_id, reason, busy_id: nil, tasks: RunningTasks::EMPTY, worker_stopped: false, sessions: nil,
80
+ stopped_workers: [])
78
81
  @session_id = session_id
79
82
  @reason = reason
80
83
  @busy_id = busy_id
81
84
  @tasks = tasks
85
+ @sessions = sessions
86
+ @stopped_workers = stopped_workers
82
87
  @stopped_worker = RunningTasks.stopped_worker(session_id, worker_stopped)
83
88
  super(archive_refused_message)
84
89
  end
@@ -97,7 +102,9 @@ module Samagotchi
97
102
  when :offer_child then "its delegate #{@busy_id[0, 8]} waits for an answer to its step-limit question; answer it first"
98
103
  when :starting then "its worker is starting; try again in a moment"
99
104
  when :starting_child then "its delegate #{@busy_id[0, 8]}'s worker is starting; try again in a moment"
100
- when :tasks_running then "#{RunningTasks.words(@session_id, @tasks)}#{RunningTasks.worker_words(@session_id, @stopped_worker)}"
105
+ when :tasks_running
106
+ "#{RunningTasks.words(@session_id, @tasks)}" \
107
+ "#{RunningTasks.worker_words(@session_id, @stopped_worker, all: @stopped_workers)}"
101
108
  else "a turn is running; wait for it or cancel it first"
102
109
  end
103
110
  end
@@ -138,18 +145,19 @@ module Samagotchi
138
145
  # tree started that still run: IGNORE (left running), REFUSE
139
146
  # (ArchiveRefused :tasks_running before anything changes), or a stop
140
147
  # (after the workers let go, or the wait ran out: their own waiters
141
- # then record the stop from the flag on disk), before the marker
148
+ # then record the stop from the flag on disk), before the marker; a
149
+ # stop with +only+ refuses there on a task it wasn't given
142
150
  def archive_session(id_or_prefix, state_dir: nil, wait: 5, except: [], running_tasks: RunningTasks::Policy::IGNORE)
143
151
  sd = state_dir || Session.default_state_dir
144
152
  id = archive_target(id_or_prefix, sd)
145
153
  tree, owners = archivable!(id, sd, except: except)
146
154
  RunningTasks.check!(tree, state_dir: sd, policy: running_tasks) do |listing|
147
- ArchiveRefused.new(id, :tasks_running, tasks: listing)
155
+ ArchiveRefused.new(id, :tasks_running, tasks: listing, sessions: tree.size)
148
156
  end
149
157
  stopped = tree.select { |sid| owners[sid] }
150
158
  # With +wait+, stop_session waits for the owner to let go.
151
159
  stopped.each { |sid| stop_session(sid, state_dir: sd, wait: wait) }
152
- RunningTasks.stop!(RunningTasks.of(tree, state_dir: sd), policy: running_tasks) if running_tasks.stop?
160
+ stop_archived_tasks!(id, tree, stopped, sd, running_tasks) if running_tasks.stop?
153
161
  archived, discarded = tree.partition { |sid| ArchiveStore.archive(sid, state_dir: sd) }
154
162
  # A restart's reminders hand-off no successor took (the stop above
155
163
  # removes a live one's): archived sessions keep no reminders.
@@ -159,6 +167,20 @@ module Samagotchi
159
167
  ArchiveResult.new(id: id, archived: archived, stopped: stopped, discarded: discarded, **running_tasks.result_fields)
160
168
  end
161
169
 
170
+ # An archive's stop, after the workers let go: a stop with +only+
171
+ # refuses (ArchiveRefused :tasks_running, saying whose worker it
172
+ # stopped) on a running task it wasn't given, before any is stopped.
173
+ private def stop_archived_tasks!(id, tree, stopped, state_dir, running_tasks)
174
+ listing = RunningTasks.of(tree, state_dir: state_dir)
175
+ unless running_tasks.unnamed(listing).empty?
176
+ worker = stopped.include?(id) || stopped.first || false
177
+ raise ArchiveRefused.new(id, :tasks_running, tasks: listing, worker_stopped: worker, sessions: tree.size,
178
+ stopped_workers: stopped)
179
+ end
180
+
181
+ RunningTasks.stop!(listing, policy: running_tasks)
182
+ end
183
+
162
184
  # The session and its descendants, with their owners, when they can be
163
185
  # archived now (#archive_refusal for each), else the refusal. Public for
164
186
  # SessionContinue, which checks before its recap wait.
@@ -230,10 +252,12 @@ module Samagotchi
230
252
  # @param allow_scheduled [Boolean] internal rollback of a failed continue
231
253
  # @param revive_previous [Boolean] a user's delete (CLI, web, TUI) of a
232
254
  # chain's newest link brings the previous one back to the lists and
233
- # undoes the continue (SessionChain::Delete.link, D2/D5); any chained
234
- # link's own delegates follow SessionChain::Delete::DELEGATES. The
235
- # result then also has unarchived:, moved_back:, deleted: and
236
- # left_running: (ids)
255
+ # undoes the continue (SessionChain::Delete.link, D2/D5). With either
256
+ # keyword (a user's delete) the session's own delegates, chained or
257
+ # not, follow SessionManager::DELEGATES: the stopped ones go with it,
258
+ # the running ones stay; without them (the automatic deletes) they
259
+ # are left. The result then also has unarchived:, moved_back:,
260
+ # deleted: and left_running: (ids)
237
261
  # @param refuse_continuing [Boolean] a user's delete refuses
238
262
  # (:continuing) while a continue of the session is in flight
239
263
  # @raise [DeleteRefused] also :scheduled for a schedule's anchor or
@@ -437,7 +461,8 @@ module Samagotchi
437
461
  # @return [Array<String>] the paths removed
438
462
  # @raise [DeleteRefused] a worker took the lock, or a start was
439
463
  # claimed, after the caller's check, or +still+ no longer holds, or
440
- # (:tasks_running, REFUSE) a task started since the op's check.
464
+ # (:tasks_running) REFUSE: a task started since the op's check; a
465
+ # stop with +only+: a running task it wasn't given.
441
466
  # SessionChain::Delete lists its whole batch under its locks first
442
467
  # and passes RunningTasks.after_check (no re-check here, so no id is
443
468
  # refused after another of the batch went).
@@ -451,6 +476,7 @@ module Samagotchi
451
476
  unless running_tasks.ignore?
452
477
  listing = RunningTasks.of([id], state_dir: state_dir)
453
478
  raise DeleteRefused.new(id, :tasks_running, tasks: listing) if running_tasks.refuse? && !listing.empty?
479
+ raise DeleteRefused.new(id, :tasks_running, tasks: listing) unless running_tasks.unnamed(listing).empty?
454
480
 
455
481
  RunningTasks.stop!(listing, policy: running_tasks) if running_tasks.stop?
456
482
  end
@@ -87,14 +87,28 @@ module Samagotchi
87
87
  # How an op treats running tasks: :ignore (today's: they keep
88
88
  # running), :refuse (DeleteRefused/ArchiveRefused :tasks_running) or
89
89
  # :stop (stopped by +by+, "user", "retention" or "scratch", their
90
- # outcomes in +tally+).
91
- Policy = Data.define(:mode, :by, :tally) do
92
- def self.stop(by:) = new(mode: :stop, by: by.to_s, tally: Tally.new)
90
+ # outcomes in +tally+). A stop with +only+ (task ids: the ones the
91
+ # delete sheet named) refuses, :tasks_running, where it would stop a
92
+ # verified task not in it, before anything of the op's batch goes;
93
+ # without it (--stop-tasks, an older page) it stops whatever runs.
94
+ Policy = Data.define(:mode, :by, :tally, :only) do
95
+ def initialize(mode:, by:, tally:, only: nil) = super
96
+
97
+ def self.stop(by:, only: nil) = new(mode: :stop, by: by.to_s, tally: Tally.new, only: only&.map(&:to_s)&.freeze)
93
98
 
94
99
  def ignore? = mode == :ignore
95
100
  def refuse? = mode == :refuse
96
101
  def stop? = mode == :stop
97
102
 
103
+ # +listing+'s verified tasks this stop was not given (none without
104
+ # +only+): the ones it refuses on. Unverified and unreadable ones are
105
+ # never signalled, so never refused on.
106
+ def unnamed(listing)
107
+ return [] unless stop? && only
108
+
109
+ listing.running.reject { |task| only.include?(task.id) }
110
+ end
111
+
98
112
  # The result keys a delete adds for a stop: the tasks the op
99
113
  # stopped, did not stop and found ended ({} unless +stop?+, so a
100
114
  # delete's result is today's).
@@ -127,29 +141,36 @@ module Samagotchi
127
141
  end
128
142
 
129
143
  # "; its worker was stopped" (+stopped_worker+ is +session_id+),
130
- # "; 9d0e1f2a's worker was stopped" (another), "" (none).
131
- def worker_words(session_id, stopped_worker)
144
+ # "; 9d0e1f2a's worker was stopped" (another), "" (none); with +all+
145
+ # of more than one (an archive's tree), "; 2 workers were stopped: its
146
+ # own, 9d0e1f2a".
147
+ def worker_words(session_id, stopped_worker, all: [])
132
148
  return "" unless stopped_worker
149
+
150
+ if all.size > 1
151
+ names = all.map { |sid| sid.to_s == session_id.to_s ? "its own" : sid.to_s[0, 8] }
152
+ return "; #{all.size} workers were stopped: #{cut(names)}"
153
+ end
133
154
  return "; its worker was stopped" if stopped_worker == session_id.to_s
134
155
 
135
156
  "; #{stopped_worker[0, 8]}'s worker was stopped"
136
157
  end
137
158
 
138
159
  # The policy a batch's removals get once the batch was listed under its
139
- # locks (SessionChain::Delete): a REFUSE already checked does no
140
- # per-id re-check; IGNORE and a stop are unchanged.
141
- def after_check(policy) = policy.refuse? ? Policy::IGNORE : policy
142
-
143
- # REFUSE's one listing of a whole batch under its locks: the batch's
144
- # DeleteRefused :tasks_running (+refusal+ builds it) before anything of
145
- # it goes. Nothing for another policy.
146
- def refuse_batch!(ids, state_dir:, policy:, &refusal)
147
- return unless policy.refuse?
148
-
149
- listing = of(ids, state_dir: state_dir)
150
- raise yield(listing) unless listing.empty?
160
+ # locks (SessionChain::Delete): the batch's check was the last word, so
161
+ # no id is refused after another of the batch went. A REFUSE does no
162
+ # per-id re-check, a stop with +only+ stops what each id runs (the same
163
+ # tally); IGNORE and a plain stop are unchanged.
164
+ def after_check(policy)
165
+ return Policy::IGNORE if policy.refuse?
166
+
167
+ policy.stop? && policy.only ? policy.with(only: nil) : policy
151
168
  end
152
169
 
170
+ # The last word on a whole batch under its locks (SessionChain::Delete):
171
+ # #check! again, before anything of it goes.
172
+ def refuse_batch!(ids, state_dir:, policy:, &) = check!(ids, state_dir: state_dir, policy: policy, &)
173
+
153
174
  # The tasks the sessions +ids+ started that may still run; never
154
175
  # writes, never loads TaskRuntime. A session with no file (a folder
155
176
  # left alone) is skipped, one that can't be read too (with a warn).
@@ -172,14 +193,19 @@ module Samagotchi
172
193
  end
173
194
 
174
195
  # +listing+ of +ids+ when +policy+ refuses on it, raised as the op's
175
- # refusal (+refusal+ builds it from the listing); else the listing
176
- # (EMPTY unless the policy refuses: a stop lists again where it stops).
196
+ # refusal (+refusal+ builds it from the listing): REFUSE on any task, a
197
+ # stop with +only+ on a running one it wasn't given (Policy#unnamed),
198
+ # so an op refuses up front, before a worker is stopped or anything
199
+ # goes; the op's check under its lock stays the last word. Else the
200
+ # listing (EMPTY for IGNORE and a plain stop, which lists again where
201
+ # it stops).
177
202
  # @return [Listing]
178
203
  def check!(ids, state_dir:, policy:, &refusal)
179
- return EMPTY unless policy.refuse?
204
+ return EMPTY unless policy.refuse? || (policy.stop? && policy.only)
180
205
 
181
206
  listing = of(ids, state_dir: state_dir)
182
- raise yield(listing) unless listing.empty?
207
+ refused = policy.refuse? ? !listing.empty? : !policy.unnamed(listing).empty?
208
+ raise yield(listing) if refused
183
209
 
184
210
  listing
185
211
  end
@@ -340,8 +366,9 @@ module Samagotchi
340
366
 
341
367
  def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
342
368
 
343
- private_class_method :stop_thread, :named_tasks, :command_name, :short_task, :cut, :readable_session,
344
- :classify, :liveness, :monotonic
369
+ # command_name, short_task and cut stay public: chi sessions delete
370
+ # --dry-run names a plan's tasks with them.
371
+ private_class_method :stop_thread, :named_tasks, :readable_session, :classify, :liveness, :monotonic
345
372
  end
346
373
  end
347
374
  end
@@ -154,5 +154,6 @@ require_relative "session_manager/worker_command"
154
154
  require_relative "session_manager/listing"
155
155
  require_relative "session_manager/delivery"
156
156
  require_relative "session_manager/lifecycle"
157
+ require_relative "session_manager/delegate_rule"
157
158
  require_relative "session_manager/removal"
158
159
  require_relative "session_manager/emptiness"
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.181.0"
4
+ VERSION = "0.182.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -81,6 +81,7 @@ require_relative "session_show"
81
81
  require_relative "session_create"
82
82
  require_relative "session_control"
83
83
  require_relative "verify_fresh_routes"
84
+ require_relative "block_fix_routes"
84
85
  require_relative "reload_check_route"
85
86
  require_relative "working_set_routes"
86
87
  require_relative "push_routes"
@@ -121,6 +122,7 @@ module Samagotchi
121
122
  include SessionCreate
122
123
  include SessionControl
123
124
  include VerifyFreshRoutes
125
+ include BlockFixRoutes
124
126
  include ReloadCheckRoute
125
127
  include WorkingSetRoutes
126
128
  include PushRoutes
@@ -166,6 +168,8 @@ module Samagotchi
166
168
  # @param reload_check [Boolean] the page checks each finished turn
167
169
  # against a reload of it and posts the counts (web.reload_check,
168
170
  # opt-in; POST /api/sessions/:id/reload_check logs them)
171
+ # @param block_fix [String] "auto": the owner's page asks again for a
172
+ # block it couldn't draw in the newest answer (web.block_fix); "off": never
169
173
  # @param annotate_presets [String, Array] the quick replies next to
170
174
  # Annotate (web.annotate_presets, "|"-separated); "" shows none. The
171
175
  # page parses them (annotate_presets.js).
@@ -205,6 +209,7 @@ module Samagotchi
205
209
  registry: nil, models_wait_timeout: MODELS_WAIT_TIMEOUT, lan: nil,
206
210
  working_set: Config::BY_KEY["web.working_set"].default, wait_poll_interval: ReplyWait::POLL_INTERVAL,
207
211
  reload_check: Config::BY_KEY["web.reload_check"].default,
212
+ block_fix: Config::BY_KEY["web.block_fix"].default,
208
213
  stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
209
214
  grants: nil, public_url: nil, public_token: nil, push: nil, start_dir: nil, update_runner: nil,
210
215
  update_blocked: nil, update_ops: nil)
@@ -222,6 +227,7 @@ module Samagotchi
222
227
  @markdown_renderer = MarkdownRenderer.new(enabled: markdown)
223
228
  @working_set = working_set
224
229
  @reload_check = reload_check
230
+ @block_fix = block_fix.to_s
225
231
  @stage_collapsed = stage_collapsed
226
232
  @reload_checks = ReloadCheckRoute::Seen.new
227
233
  @annotate_presets = annotate_presets.is_a?(Array) ? annotate_presets.join("|") : annotate_presets.to_s
@@ -313,6 +319,7 @@ module Samagotchi
313
319
  ["POST", %r{\A/api/sessions/([^/]+)/wait/prepare\z}, :handle_wait_prepare, :participant, :session],
314
320
  ["POST", %r{\A/api/sessions/([^/]+)/wait\z}, :handle_wait, :participant, :session],
315
321
  ["POST", %r{\A/api/sessions/([^/]+)/verdicts/([^/]+)/fresh\z}, :handle_verify_fresh, :participant, :session],
322
+ ["POST", %r{\A/api/sessions/([^/]+)/blocks/fix\z}, :handle_block_fix, :owner, :session],
316
323
  ["POST", %r{\A/api/sessions/([^/]+)/notes\z}, :handle_notes, :owner, :session],
317
324
  ["POST", %r{\A/api/sessions/([^/]+)/wake\z}, :handle_wake, :owner, :session],
318
325
  ["GET", %r{\A/api/sessions/([^/]+)/worker\z}, :handle_worker, :owner, :session],
@@ -1114,8 +1121,12 @@ module Samagotchi
1114
1121
  # tasks_running) and take stop_tasks: chi --remote sessions
1115
1122
  # delete|archive --stop-tasks asks for this first.
1116
1123
  STOP_TASKS_FEATURE = "stop_tasks"
1124
+ # GET …/delete_plan answers for every session (a session in no chain:
1125
+ # {chained: false, link}), and a delete takes a plain session's stopped
1126
+ # delegates: chi --remote sessions delete --dry-run asks for this first.
1127
+ DELETE_PLAN_FEATURE = "delete_plan_all"
1117
1128
  INFO_FEATURES = ["dir", "newest_workers", SessionAccessRoutes::FEATURE, SessionAccessRoutes::ATTACH_FEATURE,
1118
- BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE].freeze
1129
+ BOUND_FEATURE, CHAIN_DELETE_FEATURE, STOP_TASKS_FEATURE, DELETE_PLAN_FEATURE].freeze
1119
1130
 
1120
1131
  # The models a new session can start on, spelled as chi spells them
1121
1132
  # elsewhere: bare for the default host (what default.model holds), and
@@ -1947,6 +1958,7 @@ module Samagotchi
1947
1958
  attrs["working-set"] = "1" if working_set?(req.GET["working_set"])
1948
1959
  # The opt-in reload check (reload_check.js): only when on.
1949
1960
  attrs["reload-check"] = "1" if @reload_check
1961
+ attrs["block-fix"] = @block_fix
1950
1962
  attrs.merge!(stage_collapsed_data)
1951
1963
  attrs.merge!(annotate_presets_data)
1952
1964
  # Who looks and what they may do (Viewer; viewer.js reads it at boot).
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../block_fix"
4
+ require_relative "request_body"
5
+
6
+ module Samagotchi
7
+ module Web
8
+ # POST /api/sessions/:id/blocks/fix {turn_id, lang, source, reason},
9
+ # mixed into App: the owner's page asks again, once, for a block it
10
+ # couldn't draw in the newest answer, relayed to the worker's Bridge
11
+ # (Bridge::BlockFixRoute; docs/internals/block-renderers.md, A failed
12
+ # block is asked for again). With web.block_fix off it answers 404, as
13
+ # an unknown route.
14
+ module BlockFixRoutes
15
+ # The worker's answers passed through as they are; any other is 502.
16
+ PASSED = [200, 202].freeze
17
+ REFUSED = [400, 409, 413, 429].freeze
18
+
19
+ private
20
+
21
+ def handle_block_fix(req, id)
22
+ return not_found(path: req.path) unless @block_fix == "auto"
23
+
24
+ body = parse_json(request_body(req, RequestBody::SMALL_BODY_LIMIT))
25
+ return error_response(400, "invalid_json", "invalid JSON body") unless body.is_a?(Hash)
26
+
27
+ fields = body.slice("turn_id", "lang", "source", "reason").transform_keys(&:to_sym)
28
+ request = ->(client) { client.fix_block(turn_id: nil, lang: nil, source: nil, reason: nil, **fields) }
29
+ relay(id, bridge_client(id), request, what: "the fix was not asked for", cant: "fix blocks") do |reply|
30
+ if PASSED.include?(reply.status)
31
+ json_response(reply.status, reply.json || {})
32
+ elsif REFUSED.include?(reply.status)
33
+ error_response(reply.status, reply.json&.dig("error") || "refused", reply_detail(reply, "the fix was refused"))
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
@@ -2,8 +2,10 @@
2
2
 
3
3
  require "nokogiri"
4
4
  require "uri"
5
+ require_relative "../block_fix"
5
6
  require_relative "../block_renderers"
6
7
  require_relative "../inline_widgets"
8
+ require_relative "../markdown_parser"
7
9
 
8
10
  module Samagotchi
9
11
  module Web
@@ -57,7 +59,11 @@ module Samagotchi
57
59
  commonmarker_installed? ? TIP : TIP_GEM
58
60
  end
59
61
 
60
- def render(markdown)
62
+ # @param block_fixes [Array<Hash>, nil] the answer's block fix stamp
63
+ # (BlockFix.stamps): a block that is a fix gets data-block-fixed, one
64
+ # whose fix failed data-block-fix-failed. Only an answer's own render
65
+ # (MessageDisplay) passes it.
66
+ def render(markdown, block_fixes: nil)
61
67
  return nil unless available?
62
68
 
63
69
  html = Commonmarker.to_html(markdown.to_s, options: OPTIONS, plugins: {
@@ -68,7 +74,7 @@ module Samagotchi
68
74
  })
69
75
  return nil unless html
70
76
 
71
- sanitize(html, fences(markdown.to_s))
77
+ sanitize(html, fences(markdown.to_s), Array(block_fixes))
72
78
  end
73
79
 
74
80
  private
@@ -76,10 +82,7 @@ module Samagotchi
76
82
  def load_bundled_commonmarker!
77
83
  return @commonmarker_available unless @commonmarker_available.nil?
78
84
 
79
- require "commonmarker"
80
- @commonmarker_available = true
81
- rescue LoadError
82
- @commonmarker_available = false
85
+ @commonmarker_available = MarkdownParser.available?
83
86
  end
84
87
 
85
88
  def commonmarker_installed?
@@ -109,7 +112,7 @@ module Samagotchi
109
112
  # After the walk, which drops every attribute it doesn't know. Blocks and
110
113
  # fences pair by position; a count that differs says the two parses
111
114
  # disagree, and then no block gets one (it shows as source).
112
- def mark_languages(fragment, fences)
115
+ def mark_languages(fragment, fences, block_fixes = [])
113
116
  blocks = fragment.css("pre")
114
117
  return unless blocks.size == fences.size
115
118
 
@@ -118,6 +121,18 @@ module Samagotchi
118
121
 
119
122
  pre["data-lang"] = fence.language
120
123
  mark_widget(pre, fence.literal) if fence.language == InlineWidgets::LANG
124
+ mark_fix(pre, fence, block_fixes) unless block_fixes.empty?
125
+ end
126
+ end
127
+
128
+ # The stamp's word on this block: the fix of a failed one, or one
129
+ # whose fix didn't help. One SHA-256 per fenced block of a stamped answer.
130
+ def mark_fix(pre, fence, block_fixes)
131
+ key = BlockFix.key(fence.language, fence.literal)
132
+ if block_fixes.any? { |entry| entry[:fixed_key] == key }
133
+ pre["data-block-fixed"] = ""
134
+ elsif block_fixes.any? { |entry| entry[:key] == key && entry[:state] == "failed" }
135
+ pre["data-block-fix-failed"] = ""
121
136
  end
122
137
  end
123
138
 
@@ -134,7 +149,7 @@ module Samagotchi
134
149
  pre["data-widget-lenient"] = "" if widget.lenient?
135
150
  end
136
151
 
137
- def sanitize(html, fences)
152
+ def sanitize(html, fences, block_fixes = [])
138
153
  fragment = Nokogiri::HTML5.fragment(html)
139
154
  fragment.traverse do |node|
140
155
  next unless node.element?
@@ -147,7 +162,7 @@ module Samagotchi
147
162
  sanitize_attributes(node)
148
163
  end
149
164
  end
150
- mark_languages(fragment, fences)
165
+ mark_languages(fragment, fences, block_fixes)
151
166
  fragment.to_html
152
167
  end
153
168
 
@@ -3,6 +3,7 @@
3
3
  require_relative "../session"
4
4
  require_relative "../answer_refs"
5
5
  require_relative "../answer_tail"
6
+ require_relative "../block_fix/stamp"
6
7
  require_relative "../context_note"
7
8
  require_relative "../image_store"
8
9
  require_relative "../message_parts"
@@ -223,7 +224,11 @@ module Samagotchi
223
224
  shown = display.is_a?(String) ? Samagotchi::OutputFormatter.strip_markup(display) : ""
224
225
  message[:display] = shown unless shown.strip.empty?
225
226
  rendered = message[:display] || stripped
226
- message[:html] = @markdown_renderer.render(rendered) if markdown && !rendered.empty? && @markdown_renderer.available?
227
+ fixes = Samagotchi::BlockFix.stamps(m)
228
+ message[:html] = @markdown_renderer.render(rendered, block_fixes: fixes) if markdown && !rendered.empty? && @markdown_renderer.available?
229
+ # A block was fixed in it: a reload's drawn turn takes this answer
230
+ # even though what streamed differs (turn_block.js savedAnswer).
231
+ message[:block_fixed] = true if fixes.any? { |entry| entry[:state] == "fixed" }
227
232
  # The refs after_turn hooks attached (AnswerRefs), checked again:
228
233
  # a stored file is never trusted. Never raises.
229
234
  refs = Samagotchi::AnswerRefs.for_display(m[:display_refs] || m["display_refs"], cwd: cwd)
@@ -83,7 +83,7 @@ module Samagotchi
83
83
  # fails for a new one until it is decided here or in EVENTS. Not
84
84
  # named is dropped all the same.
85
85
  DROPPED = %w[
86
- after_generation after_tool_call after_turn answer_display before_generation before_tool_call before_turn
86
+ after_generation after_tool_call after_turn answer_display before_generation before_tool_call before_turn block_fix
87
87
  card command_output command_queued command_ran context_added empty_answer_retry
88
88
  generation_cancelled generation_progress generation_started guardrail_warning hook_notice
89
89
  llm_context_edited merged_input objectives_updated part_settled participants_changed pending_input_merged plugin_init_finished
@@ -2,14 +2,11 @@ import {
2
2
  listSessions,
3
3
  getSession,
4
4
  sendTurn,
5
- stopTurn,
6
- stopSession,
5
+ stopTurn, stopSession,
7
6
  sessionHolds,
8
7
  stopSessionHolds,
9
8
  restartSession,
10
- deleteSession,
11
- deleteChain,
12
- deletePlan,
9
+ deleteSession, deleteChain, deletePlan,
13
10
  archiveSession,
14
11
  unarchiveSession,
15
12
  sendCommand,
@@ -72,6 +69,7 @@ import { createAnnotateBar } from "./annotate_bar.js";
72
69
  import { VERIFY_PRESET, VERIFY_UNAVAILABLE, verifyWorkerUnavailable, withVerify } from "./verify_preset.js";
73
70
  import { actionLine, annotationActions, composerWithAction } from "./annotate_actions.js";
74
71
  import { createBlockHost } from "./block_host.js";
72
+ import { wireBlockFix } from "./block_fix.js";
75
73
  import { createWidgetDrawer } from "./inline_widgets.js";
76
74
  import { copyText, installCopy } from "./copy.js";
77
75
  import { installAnswerFold, sweepAnswerFolds } from "./answer_fold.js";
@@ -1224,6 +1222,7 @@ const streamHandlers = observeCards(cardRegistry, (participant ? participant.wra
1224
1222
  syncModelPick: startPage.commandRan,
1225
1223
  objectivesUpdated: (data) => objectives.update(data),
1226
1224
  cardActionFailed: cards.actionFailed,
1225
+ blockFix: (data) => blockFix?.onEvent(data),
1227
1226
  })));
1228
1227
 
1229
1228
  async function refreshTimingFromSession() {
@@ -1544,6 +1543,7 @@ turnRoots().forEach((root) => installCopy(root));
1544
1543
  // renderers; a picks' Fill reply only fills the composer.
1545
1544
  const widgets = createWidgetDrawer({ roots: turnRoots(), composerText: () => promptEl.value, fillComposer });
1546
1545
  createBlockHost({ roots: turnRoots(), sessionId: () => store.selected, drawers: [widgets], renderers: viewer.can("block_renderers"), openPicture: (p, o) => pictures.open(p, o) });
1546
+ const blockFix = wireBlockFix({ viewer, roots: turnRoots(), store, getSession, composerText: () => promptEl.value, fillComposer, linkTextRefs: markdownPlace.linkTextRefs });
1547
1547
  window.matchMedia?.("(prefers-color-scheme: dark)").addEventListener?.("change", () => pictures.close()); // a redrawn diagram's old picture
1548
1548
  // A steps block, a thinking block and the recap open and close by hand
1549
1549
  // with their height animated (details_motion.js), in the history and on