samagotchi 0.110.0 → 0.111.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 (55) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +24 -1
  3. data/docs/architecture.md +8 -5
  4. data/docs/cli.md +3 -0
  5. data/docs/configuration.md +43 -0
  6. data/docs/internals/engine.md +39 -10
  7. data/docs/internals/participants.md +1 -1
  8. data/docs/internals/remote-sessions.md +3 -3
  9. data/docs/internals/web-push.md +200 -0
  10. data/docs/internals/working-set.md +7 -6
  11. data/docs/sessions.md +1 -1
  12. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  13. data/lib/samagotchi/config.rb +4 -0
  14. data/lib/samagotchi/engine.rb +146 -490
  15. data/lib/samagotchi/engine_snapshots.rb +223 -0
  16. data/lib/samagotchi/event_fanout.rb +236 -0
  17. data/lib/samagotchi/model_binding.rb +138 -0
  18. data/lib/samagotchi/send_command/wait_target.rb +10 -3
  19. data/lib/samagotchi/send_command.rb +2 -1
  20. data/lib/samagotchi/session.rb +12 -3
  21. data/lib/samagotchi/session_access/remote.rb +2 -1
  22. data/lib/samagotchi/session_access.rb +7 -3
  23. data/lib/samagotchi/session_manager.rb +5 -0
  24. data/lib/samagotchi/turn_endings.rb +137 -0
  25. data/lib/samagotchi/version.rb +1 -1
  26. data/lib/samagotchi/web/app.rb +27 -1377
  27. data/lib/samagotchi/web/grants.rb +3 -12
  28. data/lib/samagotchi/web/message_display.rb +274 -0
  29. data/lib/samagotchi/web/private_files.rb +31 -0
  30. data/lib/samagotchi/web/public/app.js +30 -6
  31. data/lib/samagotchi/web/public/apple-touch-icon.png +0 -0
  32. data/lib/samagotchi/web/public/icons/chi-180.png +0 -0
  33. data/lib/samagotchi/web/public/icons/chi-192.png +0 -0
  34. data/lib/samagotchi/web/public/icons/chi-512.png +0 -0
  35. data/lib/samagotchi/web/public/index.html +4 -0
  36. data/lib/samagotchi/web/public/manifest.webmanifest +13 -0
  37. data/lib/samagotchi/web/public/notifications.js +137 -3
  38. data/lib/samagotchi/web/public/notify.js +1 -1
  39. data/lib/samagotchi/web/public/push.js +95 -0
  40. data/lib/samagotchi/web/public/stage_view.js +8 -0
  41. data/lib/samagotchi/web/public/sw.js +101 -0
  42. data/lib/samagotchi/web/public/turn_events.js +22 -0
  43. data/lib/samagotchi/web/push/attention.rb +105 -0
  44. data/lib/samagotchi/web/push/client.rb +103 -0
  45. data/lib/samagotchi/web/push/crypto.rb +126 -0
  46. data/lib/samagotchi/web/push/notifier.rb +230 -0
  47. data/lib/samagotchi/web/push/store.rb +285 -0
  48. data/lib/samagotchi/web/push.rb +73 -0
  49. data/lib/samagotchi/web/push_routes.rb +99 -0
  50. data/lib/samagotchi/web/server.rb +26 -2
  51. data/lib/samagotchi/web/session_control.rb +441 -0
  52. data/lib/samagotchi/web/session_create.rb +384 -0
  53. data/lib/samagotchi/web/session_show.rb +411 -0
  54. data/lib/samagotchi/worker.rb +3 -2
  55. metadata +25 -1
@@ -0,0 +1,441 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../bridge_client"
4
+ require_relative "../client_id"
5
+ require_relative "../delivery"
6
+ require_relative "../image_store"
7
+ require_relative "../prompt_history"
8
+ require_relative "../session"
9
+ require_relative "../session_commands"
10
+ require_relative "../session_manager"
11
+
12
+ module Samagotchi
13
+ module Web
14
+ # The owner's routes that act on a session's worker: answer or dismiss
15
+ # its question, run a command, send a turn (and its images), cancel, stop
16
+ # a task, dequeue a queued turn, stop, restart, archive, unarchive and
17
+ # delete (handle_question_answer … handle_delete), with the refusals they
18
+ # answer (owned_by_repl, owned_by_tui, archive_refused). Included in App:
19
+ # its ROUTES name the handlers, and its helpers (json_response,
20
+ # error_response, parse_json, request_body, relay, not_live,
21
+ # bridge_error, reply_detail, worker_timeout, bridge_client,
22
+ # live_bridge_client, session_owner, record_history, …) and ivars
23
+ # (@manager, @session_class, @state_dir, @hub) answer. A participant's
24
+ # turn goes to ParticipantAccess (handle_participant_turn). See
25
+ # docs/architecture.md (chi web's routes) and docs/internals/remote-sessions.md.
26
+ module SessionControl
27
+ # An uploaded image may be this big before it is downscaled.
28
+ MAX_IMAGE_UPLOAD_BYTES = 20 * 1024 * 1024
29
+
30
+ IMAGE_NAME_RE = /\A[0-9a-f]{16}\.(png|jpe?g|gif|webp)\z/
31
+
32
+ IMAGE_TYPES = { "png" => "image/png", "jpg" => "image/jpeg", "jpeg" => "image/jpeg", "gif" => "image/gif",
33
+ "webp" => "image/webp" }.freeze
34
+
35
+ # POST /stop waits this long for the worker to let go of the session
36
+ # when the body names no wait (the page's Stop: it shows the stop at
37
+ # once, and a Rack thread isn't held for it). A CLI through --remote
38
+ # sends its own, SessionManager::STOP_WAIT at most, so chi sessions
39
+ # stop waits as long as here.
40
+ STOP_WAIT_SECONDS = 2.0
41
+
42
+ # A task id as TaskRuntime.generate_task_id makes it.
43
+ TASK_ID = /\A\d{14}-\h{8}\z/
44
+
45
+ private
46
+
47
+ def handle_question_answer(req, id)
48
+ session = @session_class.load(id, state_dir: default_state_dir) rescue nil
49
+ return error_response(404, "not_found", "Session not found: #{id}") unless session
50
+
51
+ body = parse_json(request_body(req))
52
+ return error_response(400, "invalid_json", "invalid JSON body") unless body.is_a?(Hash)
53
+
54
+ qid = body["id"]
55
+ return error_response(400, "missing_fields", "id is required") if qid.to_s.strip.empty?
56
+
57
+ # client_id: only chi answer's (a parent agent's answer, which the
58
+ # worker holds to its guardrails.parent_answers) is passed on; any
59
+ # other is dropped, so a forward can only tighten (an answer never
60
+ # passes for the user's own by it).
61
+ client_id = body["client_id"] == ClientId::CLI_ANSWER ? ClientId::CLI_ANSWER : nil
62
+ request = once_more_on_late do |client|
63
+ client.answer(id: qid, selected: body["selected"], freeform: body["freeform"], client_id: client_id)
64
+ end
65
+ relay(id, bridge_client(id), request, what: "the answer was not sent", cant: "answer questions") do |reply|
66
+ case reply.status
67
+ when 200 then json_response(200, { status: "answered", session_id: id, id: qid })
68
+ # Another client answered first (or the question was cancelled).
69
+ when 409 then error_response(409, "question_not_pending", reply_detail(reply, "question not pending"))
70
+ when 400 then error_response(400, "invalid_answer", reply_detail(reply, "answer rejected"))
71
+ # The worker's guardrails.parent_answers refused a parent's option.
72
+ when 403 then json_response(403, { error: "parent_answer_refused", reason: reply.json&.dig("reason"),
73
+ detail: reply_detail(reply, "the worker refused that option") })
74
+ end
75
+ end
76
+ end
77
+
78
+ # A request to the worker sent once more when the worker dropped it as
79
+ # past its deadline (408), as chi answer does on this machine
80
+ # (SessionAccess::Local#answer); a second 408 is #relay's 504
81
+ # worker_timeout. The question stays open either way.
82
+ def once_more_on_late
83
+ lambda do |client|
84
+ reply = yield client
85
+ reply.status == 408 ? yield(client) : reply
86
+ end
87
+ end
88
+
89
+ # Leave the pending question unanswered (the card's Dismiss). A question
90
+ # only exists while its worker waits on it, so this needs a live bridge.
91
+ def handle_question_dismiss(req, id)
92
+ body = parse_json(request_body(req))
93
+ return error_response(400, "invalid_json", "invalid JSON body") unless body.is_a?(Hash)
94
+
95
+ qid = body["id"].to_s
96
+ return error_response(400, "missing_fields", "id is required") if qid.strip.empty?
97
+
98
+ request = once_more_on_late { |client| client.dismiss_question(id: qid) }
99
+ relay(id, bridge_client(id), request, what: "the question was not dismissed", cant: "dismiss questions") do |reply|
100
+ case reply.status
101
+ when 200 then json_response(200, { status: "dismissed", session_id: id, id: qid })
102
+ when 409
103
+ # The step-limit question can't be left unanswered.
104
+ code = reply.json&.dig("error") == "not_dismissable" ? "not_dismissable" : "question_not_pending"
105
+ error_response(409, code, reply_detail(reply, "question not pending"))
106
+ end
107
+ end
108
+ end
109
+
110
+ # A session command typed in the composer (/model, /models, !rollback,
111
+ # !cmd, /continue): the worker runs it (woken as for a turn) and every
112
+ # UI gets its :command_ran. Needs the worker's Bridge.
113
+ def handle_command(req, id)
114
+ body = parse_json(request_body(req))
115
+ return error_response(400, "invalid_json", "invalid JSON body") unless body.is_a?(Hash)
116
+
117
+ line = body["line"].to_s.strip
118
+ return error_response(400, "missing_fields", "line is required") if line.empty?
119
+
120
+ @manager.resume_session(id, state_dir: @state_dir)
121
+ # card: a card's action; its command events say so (no echo).
122
+ request = ->(client) { client.post_command(line: line, client_id: body["client_id"], card: body["card"] == true) }
123
+ relay(id, live_bridge_client(id), request, what: "the command was not run", cant: "run commands") do |reply|
124
+ case reply.status
125
+ when 202
126
+ record_history(body, line) if PromptHistory.shell_line?(line)
127
+ json_response(202, reply.json || { status: "accepted" })
128
+ when 400
129
+ # One of this chi's own commands the worker doesn't know: it runs an
130
+ # older chi. command: which one, so a remote TUI names it as its
131
+ # Bridge's own 400 unknown_command would (WebBridgeClient).
132
+ name = reply.json&.dig("error") == "unknown_command" && SessionCommands.builtin_name(line)
133
+ next older_worker_command(id, name) if name
134
+
135
+ error_response(400, reply.json&.dig("error") || "unknown_command", reply_detail(reply, "not a session command"))
136
+ end
137
+ end
138
+ rescue SessionManager::OwnedByTUI => e
139
+ owned_by_tui(e)
140
+ end
141
+
142
+ # 501 not_supported for a builtin +name+ ("/title") the worker lacks.
143
+ def older_worker_command(id, name)
144
+ words = BridgeClient.stale_worker_message(id, cant: "run #{name}")
145
+ json_response(501, { error: "not_supported", detail: words, message: words, command: name })
146
+ end
147
+
148
+ def handle_turn(req, id)
149
+ body = parse_json(request_body(req))
150
+ unless body.is_a?(Hash)
151
+ return error_response(400, "invalid_json", "invalid JSON body")
152
+ end
153
+ # A participant's review turn: its own path, which takes from the
154
+ # body only the prompt (ParticipantAccess#handle_participant_turn).
155
+ return handle_participant_turn(req, id, body) unless principal(req).owner?
156
+
157
+ prompt = body["prompt"] || body[:prompt]
158
+ client_id = body["client_id"] || body[:client_id]
159
+ if prompt.to_s.strip.empty?
160
+ return error_response(400, "missing_fields", "prompt is required")
161
+ end
162
+
163
+ images = turn_images(id, body["images"])
164
+ return error_response(400, "bad_images", images) if images.is_a?(String)
165
+
166
+ delivery = body["delivery"] || body[:delivery]
167
+ if (refused = Delivery.refusal(delivery))
168
+ return error_response(400, refused[:error], refused[:detail])
169
+ end
170
+
171
+ refused = turn_refusal(id, body, prompt.to_s, images)
172
+ return refused if refused
173
+
174
+ # no_interrupt: an attached TUI's --no-interrupt (chi --remote --attach).
175
+ # author: the principal's (nil for the owner), never the body's.
176
+ result = SessionManager.deliver_turn(id, prompt: prompt.to_s, client_id: client_id, images: images,
177
+ delivery: delivery, no_interrupt: body["no_interrupt"] == true,
178
+ author: principal(req).author,
179
+ state_dir: @state_dir, manager: @manager,
180
+ bridge: -> { live_bridge_client(id) })
181
+ case result.status
182
+ when :accepted
183
+ record_history(body, prompt)
184
+ # via: bridge or file (the worker was gone: its input file), which
185
+ # names the turn a remote chi send --wait follows (WaitTarget).
186
+ json_response(202, result.ack.merge("via" => result.via.to_s))
187
+ when :refused then json_response(result.code, result.ack)
188
+ when :timeout then error_response(504, "worker_timeout", result.detail)
189
+ else error_response(500, "enqueue_failed", "could not write turn input")
190
+ end
191
+ rescue SessionManager::OwnedByTUI => e
192
+ owned_by_tui(e)
193
+ end
194
+
195
+ # A turn refused before it goes in, as chi send refuses it on its own
196
+ # machine: a chi send line #parent_gate refuses (the session's own
197
+ # parent_answers), and with check_vision: true images to a model known
198
+ # not to take them (422 no_vision). The page sends neither.
199
+ # @return [Array, nil] the response, or nil to go on
200
+ def turn_refusal(id, body, prompt, images)
201
+ vision = body["check_vision"] == true && !images.empty?
202
+ return nil unless vision || App::CLI_SEND_IDS.include?(body["client_id"])
203
+
204
+ session = @session_class.load(id, state_dir: default_state_dir)
205
+ refused = parent_gate(prompt, client_id: body["client_id"], values: [session.parent_answers])
206
+ return refused if refused
207
+
208
+ vision ? vision_refused(session.model_name, session.model_typed) : nil
209
+ end
210
+
211
+ # A turn's images as [{file:, name:}] (refs to uploads already in the
212
+ # session's images/), or a String saying what's wrong. Never a path.
213
+ def turn_images(id, raw)
214
+ return [] if raw.nil?
215
+
216
+ session_dir = image_session_dir(id)
217
+ return "unknown session" unless session_dir
218
+
219
+ ImageStore.check_refs(session_dir, raw)
220
+ end
221
+
222
+ # The session's folder, or nil for an id that isn't one.
223
+ def image_session_dir(id)
224
+ return nil unless App::SESSION_ID_RE.match?(id.to_s)
225
+
226
+ @session_class.load(id, state_dir: default_state_dir)
227
+ Session.session_dir(id, state_dir: default_state_dir)
228
+ rescue ArgumentError
229
+ nil
230
+ end
231
+
232
+ # POST /api/sessions/:id/images: the raw image as the body (a paste or
233
+ # a drop), ?name= for its file name. Stored like any other image
234
+ # (converted, downscaled); answers the ref the turn then names.
235
+ def handle_image_upload(req, id)
236
+ session_dir = image_session_dir(id)
237
+ return error_response(404, "not_found", "unknown session") unless session_dir
238
+
239
+ length = req.content_length.to_i
240
+ if length > MAX_IMAGE_UPLOAD_BYTES
241
+ return error_response(413, "too_large", "an image may be up to #{MAX_IMAGE_UPLOAD_BYTES / 1024 / 1024} MB")
242
+ end
243
+
244
+ bytes = request_body(req, MAX_IMAGE_UPLOAD_BYTES + 1).to_s.b
245
+ if bytes.bytesize > MAX_IMAGE_UPLOAD_BYTES
246
+ return error_response(413, "too_large", "an image may be up to #{MAX_IMAGE_UPLOAD_BYTES / 1024 / 1024} MB")
247
+ end
248
+
249
+ name = File.basename(req.params["name"].to_s)[0, 120]
250
+ ref = ImageStore.ingest(session_dir, bytes: bytes, name: name.empty? ? "image" : name, source: "user")
251
+ json_response(201, ref)
252
+ rescue ImageStore::Error => e
253
+ error_response(422, "bad_image", e.message)
254
+ end
255
+
256
+ # GET /api/sessions/:id/images/<hash>.<ext>: a stored image (only
257
+ # raster types; never svg), for the page's thumbnails.
258
+ def handle_image(_req, id, name)
259
+ session_dir = image_session_dir(id)
260
+ return not_found(path: "images/#{name}") unless session_dir && IMAGE_NAME_RE.match?(name.to_s)
261
+
262
+ path = File.join(session_dir, ImageStore::DIR, name)
263
+ return not_found(path: "images/#{name}") unless File.file?(path) && !File.symlink?(path)
264
+
265
+ body = File.binread(path)
266
+ [200, { "Content-Type" => IMAGE_TYPES.fetch(File.extname(name).delete(".")), "Content-Length" => body.bytesize.to_s,
267
+ "X-Content-Type-Options" => "nosniff", "Cache-Control" => "private, max-age=86400" }, [body]]
268
+ end
269
+
270
+ # The Bridge decides the reason (Bridge::CANCEL_REASONS; anything
271
+ # else is manual) and the reply echoes its choice. No reason: user.
272
+ def handle_cancel(req, id)
273
+ @session_class.load(id, state_dir: default_state_dir)
274
+
275
+ parsed = parse_json(request_body(req))
276
+ reason = (parsed["reason"] if parsed.is_a?(Hash)).to_s.strip
277
+ reason = "user" if reason.empty?
278
+
279
+ request = ->(client) { client.cancel(reason: reason) }
280
+ relay(id, bridge_client(id), request, what: "the turn was not cancelled", cant: "cancel turns") do |reply|
281
+ case reply.status
282
+ when 202
283
+ json_response(202, { status: "cancel_requested", session_id: id, reason: reply.json&.dig("reason"), via: "bridge" })
284
+ # No active turn to cancel.
285
+ when 409 then json_response(409, { error: "not_running", detail: "no active turn to cancel", session_id: id })
286
+ end
287
+ end
288
+ end
289
+
290
+ # The stop-task button: the worker stops the task as the user
291
+ # (Bridge#handle_task_stop) and its task_wait returns. Its own 404
292
+ # (not this conversation's task) and 409 (already ended) pass through;
293
+ # a 404 from a worker without the route is the stale worker's 501.
294
+ def handle_task_stop(_req, id, task_id)
295
+ return error_response(400, "invalid_task_id", "not a task id: #{task_id.to_s[0, 80]}") unless TASK_ID.match?(task_id)
296
+
297
+ @session_class.load(id, state_dir: default_state_dir)
298
+ request = ->(client) { client.stop_task(task_id) }
299
+ relay(id, bridge_client(id), request, what: "the task was not stopped", cant: "stop tasks") do |reply|
300
+ body = reply.json || {}
301
+ case reply.status
302
+ when 200 then json_response(200, { status: body["status"], stop_reason: body["stop_reason"], task_id: task_id, session_id: id })
303
+ when 404 then (error_response(404, "task_not_found", "no task #{task_id} in this conversation") if body["error"] == "task_not_found")
304
+ when 409 then json_response(409, { error: "not_running", status: body["status"], task_id: task_id, session_id: id })
305
+ end
306
+ end
307
+ end
308
+
309
+ # POST /api/sessions/:id/turn/:enqueued_id/dequeue {client_id?}: the ×
310
+ # on a queued bubble takes the message back before it runs
311
+ # (Bridge#handle_dequeue_turn). Straight to the live worker, never
312
+ # through deliver_turn: a removal must not wake one, and a stopped
313
+ # worker's queued file is the next worker's (503 not_live). 200
314
+ # {status, enqueued_id, prompt}; 409 already_started / not_queued and
315
+ # 404 unknown_enqueued_id pass through; the rest as every relay.
316
+ def handle_dequeue_turn(req, id, enqueued_id)
317
+ @session_class.load(id, state_dir: default_state_dir)
318
+ parsed = parse_json(request_body(req))
319
+ client_id = (parsed["client_id"] if parsed.is_a?(Hash))
320
+ # A participant takes back only their own queued turns, by chi web's
321
+ # record of who sent each (never a body's client id).
322
+ unless (who = principal(req)).owner?
323
+ return not_permitted_for(req, who) unless own_turn?(who.grant, id, enqueued_id)
324
+
325
+ client_id = ClientId.review(who.grant.id)
326
+ end
327
+
328
+ request = ->(client) { client.dequeue(enqueued_id: enqueued_id, client_id: client_id) }
329
+ relay(id, bridge_client(id), request, what: "the message was not removed", cant: "remove queued messages") do |reply|
330
+ body = reply.json || {}
331
+ case reply.status
332
+ when 200 then json_response(200, { status: body["status"], enqueued_id: enqueued_id, prompt: body["prompt"].to_s, session_id: id })
333
+ when 409 then json_response(409, { error: body["error"] || "already_started", detail: body["detail"], enqueued_id: enqueued_id, session_id: id }.compact)
334
+ when 404
335
+ json_response(404, { error: "unknown_enqueued_id", enqueued_id: enqueued_id, session_id: id }) if body["error"] == "unknown_enqueued_id"
336
+ end
337
+ end
338
+ end
339
+
340
+ # POST /api/sessions/:id/stop {wait?}: 200 {status: "stopped",
341
+ # session_id, released}: released, whether the worker let go of the
342
+ # session within the wait (STOP_WAIT_SECONDS, or the body's seconds up
343
+ # to SessionManager::STOP_WAIT: chi sessions stop's two wordings); 409
344
+ # owned_by_tui.
345
+ def handle_stop(req, id)
346
+ # Bounded, so a Rack thread isn't held long; a worker still exiting
347
+ # after it just means an immediate resume finds it (rare).
348
+ released = @manager.stop_session(id, state_dir: @state_dir, wait: stop_wait(req))
349
+ @hub&.touch(id)
350
+ json_response(200, { status: "stopped", session_id: id, released: released == true })
351
+ rescue SessionManager::OwnedByTUI => e
352
+ owned_by_tui(e)
353
+ end
354
+
355
+ # The body's wait (a number of seconds), capped at
356
+ # SessionManager::STOP_WAIT; STOP_WAIT_SECONDS without one.
357
+ def stop_wait(req)
358
+ body = parse_json(request_body(req, 4096))
359
+ wait = body["wait"] if body.is_a?(Hash)
360
+ wait.is_a?(Numeric) && wait.positive? ? [wait, SessionManager::STOP_WAIT].min : STOP_WAIT_SECONDS
361
+ end
362
+
363
+ # POST /api/sessions/:id/restart: hand the session to a new worker on
364
+ # the newest chi installed (SessionManager.restart_session). 200
365
+ # {status: "restarted", session_id, from_version, version} (version nil:
366
+ # the new worker is still starting; its bridge_up follows); 409
367
+ # {error: "held" | "not_running" | "unsupported" | "failed", reason, detail} in words; 409
368
+ # owned_by_tui; 404.
369
+ def handle_restart(_req, id)
370
+ result = @manager.restart_session(id, state_dir: @state_dir, client_id: ClientId::WEB_RESTART)
371
+ @hub&.touch(id)
372
+ json_response(200, { status: "restarted", session_id: id, from_version: result.from_version,
373
+ version: result.version })
374
+ rescue SessionManager::RestartRefused => e
375
+ error = %i[not_running unsupported failed].include?(e.reason) ? e.reason.to_s : "held"
376
+ refusal_response(409, error, e, reason: e.reason.to_s, session_id: id, version: e.version)
377
+ rescue SessionManager::OwnedByTUI => e
378
+ owned_by_tui(e)
379
+ end
380
+
381
+ # POST /api/sessions/:id/archive: hide it (and its delegates) from the
382
+ # lists, keep it for good. A live idle worker is stopped first; a turn
383
+ # running in it or a delegate, a chi REPL's session and a scratch one
384
+ # are refused (409).
385
+ def handle_archive(_req, id)
386
+ result = @manager.archive_session(id, state_dir: @state_dir, wait: STOP_WAIT_SECONDS)
387
+ (result[:archived] + result[:discarded]).each { |sid| @hub&.touch(sid) }
388
+ json_response(200, { status: "archived", session_id: result[:id], archived: result[:archived],
389
+ stopped: result[:stopped], discarded: result[:discarded] })
390
+ rescue SessionManager::OwnedByTUI => e
391
+ owned_by_repl(id, e)
392
+ rescue SessionManager::ArchiveRefused => e
393
+ archive_refused(e)
394
+ end
395
+
396
+ # POST /api/sessions/:id/unarchive: back to the lists, delegates too.
397
+ def handle_unarchive(_req, id)
398
+ result = @manager.unarchive_session(id, state_dir: @state_dir)
399
+ result[:unarchived].each { |sid| @hub&.touch(sid) }
400
+ json_response(200, { status: "unarchived", session_id: result[:id], unarchived: result[:unarchived] })
401
+ end
402
+
403
+ # DELETE /api/sessions/:id?force=true: the session for good. With
404
+ # force a live worker is stopped first (the page sends it: its confirm
405
+ # says so); without it a live worker's session is refused, 409
406
+ # worker_running, as chi sessions delete without --force. A chi REPL's
407
+ # session is always refused.
408
+ def handle_delete(req, id)
409
+ result = @manager.delete_session(id, state_dir: @state_dir, stop: truthy_param?(req.params["force"]),
410
+ wait: STOP_WAIT_SECONDS)
411
+ @hub&.touch(result[:id])
412
+ json_response(200, { status: "deleted", session_id: result[:id], stopped: result[:stopped] })
413
+ rescue SessionManager::OwnedByTUI => e
414
+ owned_by_repl(id, e)
415
+ rescue SessionManager::DeleteRefused => e
416
+ detail = e.reason == :still_stopping ? "#{e.message}; try again in a moment" : e.message
417
+ refusal_response(409, e.reason.to_s, e, detail: detail, session_id: e.session_id, reason: e.reason.to_s)
418
+ end
419
+
420
+ # 409 owned_by_tui in the words a refused archive, delete or continue
421
+ # shows (stop, restart, a turn and a command show OwnedByTUI's own).
422
+ def owned_by_repl(id, error = nil)
423
+ named = SessionManager::OwnedByTUI.new(id)
424
+ error ||= named
425
+ refusal_response(409, "owned_by_tui", error, detail: named.message, session_id: error.session_id)
426
+ end
427
+
428
+ # 409 owned_by_tui in OwnedByTUI's own words (stop, restart, a turn, a
429
+ # command).
430
+ def owned_by_tui(error) = refusal_response(409, "owned_by_tui", error, session_id: error.session_id)
431
+
432
+ # 409 scratch or busy (every other reason: a turn, a queued prompt, an
433
+ # open step-limit question, in it or a delegate, +busy_id+), with the
434
+ # reason for a remote client.
435
+ def archive_refused(error)
436
+ refusal_response(409, error.reason == :scratch ? "scratch" : "busy", error, session_id: error.session_id,
437
+ reason: error.reason.to_s, busy_id: error.busy_id)
438
+ end
439
+ end
440
+ end
441
+ end