samagotchi 0.188.0 → 0.189.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 (77) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +42 -1
  3. data/docs/architecture.md +5 -3
  4. data/docs/bundle-authoring.md +1 -1
  5. data/docs/bundles.md +15 -0
  6. data/docs/cli.md +23 -5
  7. data/docs/guardrails.md +3 -2
  8. data/docs/internals/bundles.md +3 -3
  9. data/docs/internals/pages.md +65 -18
  10. data/docs/internals/session-lifecycle.md +19 -6
  11. data/docs/internals/web-frontend.md +3 -3
  12. data/docs/internals/web-push.md +11 -5
  13. data/docs/pages.md +68 -15
  14. data/docs/peers.md +3 -0
  15. data/docs/plugins.md +25 -1
  16. data/docs/releasing.md +1 -1
  17. data/docs/scheduling.md +71 -8
  18. data/docs/sessions.md +4 -4
  19. data/docs/testing.md +1 -1
  20. data/lib/samagotchi/bundle_manifest.rb +34 -5
  21. data/lib/samagotchi/bundles/schedules/manifest.yml +11 -0
  22. data/lib/samagotchi/bundles/schedules/scripts/schedules.rb +159 -0
  23. data/lib/samagotchi/bundles/system/manifest.yml +3 -3
  24. data/lib/samagotchi/bundles/system/self_map.md +2 -2
  25. data/lib/samagotchi/bundles/system/skill_pages.md +9 -4
  26. data/lib/samagotchi/installed_bundles/manifest.rb +8 -1
  27. data/lib/samagotchi/memory_bundle/asset_installer.rb +3 -2
  28. data/lib/samagotchi/memory_bundle/builder.rb +1 -0
  29. data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
  30. data/lib/samagotchi/page_command.rb +9 -6
  31. data/lib/samagotchi/pages/bundled.rb +83 -0
  32. data/lib/samagotchi/pages/launch.rb +14 -2
  33. data/lib/samagotchi/pages/runner.rb +7 -2
  34. data/lib/samagotchi/pages/runtime.rb +83 -0
  35. data/lib/samagotchi/pages/store.rb +18 -5
  36. data/lib/samagotchi/pages.rb +47 -3
  37. data/lib/samagotchi/peer_continue.rb +14 -8
  38. data/lib/samagotchi/run_options.rb +1 -1
  39. data/lib/samagotchi/schedule_command.rb +79 -37
  40. data/lib/samagotchi/schedule_display.rb +69 -0
  41. data/lib/samagotchi/schedules/busy_part.rb +146 -0
  42. data/lib/samagotchi/schedules/edit_part.rb +120 -0
  43. data/lib/samagotchi/schedules/history_part.rb +51 -0
  44. data/lib/samagotchi/schedules/listing_part.rb +52 -0
  45. data/lib/samagotchi/schedules/notices_part.rb +116 -0
  46. data/lib/samagotchi/schedules/protection_part.rb +103 -0
  47. data/lib/samagotchi/schedules/recurrence.rb +103 -0
  48. data/lib/samagotchi/schedules.rb +134 -330
  49. data/lib/samagotchi/session_access/local.rb +9 -1
  50. data/lib/samagotchi/session_access/remote.rb +2 -1
  51. data/lib/samagotchi/session_chain/delete.rb +7 -5
  52. data/lib/samagotchi/session_lifecycle/allowed.rb +2 -1
  53. data/lib/samagotchi/session_lifecycle.rb +3 -2
  54. data/lib/samagotchi/session_manager/removal.rb +16 -9
  55. data/lib/samagotchi/session_protection.rb +99 -0
  56. data/lib/samagotchi/session_retention.rb +21 -6
  57. data/lib/samagotchi/sessions_command.rb +4 -0
  58. data/lib/samagotchi/testing/boundary.rb +13 -0
  59. data/lib/samagotchi/tools/cancel_schedule.rb +5 -2
  60. data/lib/samagotchi/turn_outcome.rb +41 -0
  61. data/lib/samagotchi/version.rb +1 -1
  62. data/lib/samagotchi/web/page_routes.rb +13 -8
  63. data/lib/samagotchi/web/public/app.js +12 -18
  64. data/lib/samagotchi/web/public/index.html +11 -2
  65. data/lib/samagotchi/web/public/owner_claim.js +7 -5
  66. data/lib/samagotchi/web/public/page_links.js +1 -1
  67. data/lib/samagotchi/web/public/page_view.js +8 -5
  68. data/lib/samagotchi/web/public/pages.css +9 -2
  69. data/lib/samagotchi/web/public/pages_group.js +21 -19
  70. data/lib/samagotchi/web/public/pages_list.js +73 -0
  71. data/lib/samagotchi/web/public/pages_model.js +54 -0
  72. data/lib/samagotchi/web/public/pages_wiring.js +66 -0
  73. data/lib/samagotchi/web/public/views.js +77 -23
  74. data/lib/samagotchi/web/push/notifier.rb +4 -3
  75. data/lib/samagotchi/web/server.rb +3 -1
  76. data/lib/samagotchi/web/session_hub.rb +64 -19
  77. metadata +17 -1
@@ -553,7 +553,15 @@ module Samagotchi
553
553
  end
554
554
  return PeerPaired.new(status: :old_worker) if old_peer_worker?(id)
555
555
 
556
- PeerPaired.new(status: :paired, link: PeerMailbox.pair(id, peer, address: address, from: from, state_dir: state_dir!))
556
+ link = PeerMailbox.pair(id, peer, address: address, from: from, state_dir: state_dir!)
557
+ location = ContextSources.session_location(id, state_dir: state_dir!)
558
+ # These are exactly the bundles' LEGACY_INBOX and LEGACY_OUTBOX names.
559
+ ["#{peer}-inbox", "#{peer}-outbox"].each do |name|
560
+ location.remove(name)
561
+ rescue SystemCallError
562
+ nil
563
+ end
564
+ PeerPaired.new(status: :paired, link: link)
557
565
  end
558
566
 
559
567
  # Ends the pairing (link.json); the messages stay.
@@ -840,7 +840,8 @@ module Samagotchi
840
840
  raise SessionManager::ScratchSession, sid if json["scratch"] == true
841
841
 
842
842
  raise SessionManager::OwnedByTUI, sid
843
- when "worker_running", "still_stopping", "scheduled", "continuing", "delegate_unmovable", "chain_scheduled"
843
+ when "worker_running", "still_stopping", "scheduled", "continuing", "delegate_unmovable", "chain_scheduled",
844
+ "protection_unreadable"
844
845
  raise SessionManager::DeleteRefused.new(sid, reason || error.to_sym, message: message, ids: ids_of(json["ids"]),
845
846
  schedule_id: json["schedule_id"])
846
847
  when "tasks_running" then raise tasks_refusal(json, sid)
@@ -10,6 +10,7 @@ require_relative "../continued_from"
10
10
  require_relative "../note_move"
11
11
  require_relative "../owner_lock"
12
12
  require_relative "../session"
13
+ require_relative "../session_protection"
13
14
  require_relative "../starting_marker"
14
15
  require_relative "../worker_presence"
15
16
 
@@ -18,7 +19,6 @@ module Samagotchi
18
19
  # (a require cycle otherwise), and session_continue requires session_manager.
19
20
  autoload :SessionManager, File.expand_path("../session_manager", __dir__)
20
21
  autoload :SessionContinue, File.expand_path("../session_continue", __dir__)
21
- autoload :Schedules, File.expand_path("../schedules", __dir__)
22
22
 
23
23
  module SessionChain
24
24
  # A user's delete of a session (the CLI, the web, the TUI's /exit
@@ -145,7 +145,7 @@ module Samagotchi
145
145
  # task the link or such a delegate started that still runs.
146
146
  # @raise [SessionManager::DeleteRefused, SessionManager::OwnedByTUI]
147
147
  def check_link!(plan, state_dir, running_tasks: SessionManager::RunningTasks::Policy::IGNORE)
148
- SessionManager.refuse_scheduled!(plan.id, state_dir)
148
+ SessionManager.refuse_protected!(plan.id, state_dir)
149
149
  refuse_unmovable!(plan.id, plan.moved, state_dir)
150
150
  precheck!(plan.delegates.delete, state_dir)
151
151
  SessionManager::RunningTasks.check!([*plan.delegates.delete, plan.id], state_dir: state_dir,
@@ -218,8 +218,11 @@ module Samagotchi
218
218
  def precheck!(ids, state_dir)
219
219
  ids.each do |sid|
220
220
  begin
221
- SessionManager.refuse_scheduled!(sid, state_dir)
221
+ SessionManager.refuse_protected!(sid, state_dir)
222
222
  rescue SessionManager::DeleteRefused => e
223
+ # Only a schedule names the delegate; any other refusal keeps its words.
224
+ raise unless e.reason == :scheduled
225
+
223
226
  raise SessionManager::DeleteRefused.new(
224
227
  sid, :scheduled, schedule_id: e.schedule_id,
225
228
  message: "its delegate #{sid[0, 8]} is the target of an enabled schedule; " \
@@ -356,8 +359,7 @@ module Samagotchi
356
359
  # a background task any of them started that still runs.
357
360
  # @raise [SessionManager::DeleteRefused, SessionManager::OwnedByTUI]
358
361
  def check_chain!(plan, state_dir, stop:, running_tasks: SessionManager::RunningTasks::Policy::IGNORE)
359
- schedule = Schedules.new(state_dir: state_dir).for_chain(plan.id).first
360
- raise SessionManager::DeleteRefused.new(plan.id, :chain_scheduled, schedule_id: schedule.id) if schedule
362
+ SessionManager.refuse_protected!(plan.id, state_dir, chain: true)
361
363
 
362
364
  plan.links.each do |link|
363
365
  presence = WorkerPresence.read(link, state_dir: state_dir, owner: SessionManager.session_owner(link, state_dir: state_dir))
@@ -25,7 +25,8 @@ module Samagotchi
25
25
  # or offer, not SIGSTOPped, features restart and activity, an idle worker
26
26
  # with no streams). For schedules, worker_busy is "its worker is starting
27
27
  # or leaving", deleting is DeliverResult::DELETING's detail, and
28
- # worker_newer is WorkerLink::Skew#short_message. Resume's live is "a
28
+ # worker_newer is WorkerLink::Skew#short_message (Schedules::BusyPart's
29
+ # BUSY_WORDS; Schedules#busy_cell reads these two columns). Resume's live is "a
29
30
  # worker holds it"; restart's fallback is its unresponsive-worker path,
30
31
  # its stop_marked a stop marked and its deleting a deleter holds the lock
31
32
  # (it reads this table: restart_session's precheck); attach's gone_* are
@@ -12,8 +12,9 @@ module Samagotchi
12
12
  # stored: see docs/internals/session-lifecycle.md (Derived states).
13
13
  #
14
14
  # A read only: it writes, clears and unlinks nothing (the marker writers
15
- # are pinned in spec/session_lifecycle_writers_spec.rb). One decider
16
- # reads it (restart_session's precheck, ALLOWED[:restart]); ALLOWED is what
15
+ # are pinned in spec/session_lifecycle_writers_spec.rb). Two deciders
16
+ # read it (restart_session's precheck, ALLOWED[:restart]; a schedule's busy
17
+ # check, Schedules#busy_cell, ALLOWED[:sched_chain] / [:sched_same]); ALLOWED is what
17
18
  # each operation does in each state, pinned against the deciders by
18
19
  # spec/session_lifecycle/matrix_spec.rb.
19
20
  module SessionLifecycle
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../session_protection"
3
4
  require_relative "../session_stores"
4
5
  require_relative "running_tasks"
5
6
 
@@ -14,7 +15,9 @@ module Samagotchi
14
15
  # the previous one a delete would bring back), :delegate_unmovable (a
15
16
  # delegate the deleted link's continue moved can't go back: +ids+,
16
17
  # +detail+ says why), :chain_scheduled (a schedule is on the chain a
17
- # chain delete would take: +schedule_id+), :plan_changed (the plan no
18
+ # chain delete would take: +schedule_id+), :protection_unreadable (a
19
+ # SessionProtection protector's store doesn't read: its own words),
20
+ # :plan_changed (the plan no
18
21
  # longer matches the digest the caller confirmed), :tasks_running
19
22
  # (background tasks it or a session the delete takes started still run:
20
23
  # +tasks+, a RunningTasks::Listing; +worker_stopped+ when a worker was
@@ -327,7 +330,7 @@ module Samagotchi
327
330
  sd = state_dir
328
331
  path = Session.session_file(id, state_dir: sd)
329
332
  dir = Session.session_dir(id, state_dir: sd)
330
- refuse_scheduled!(id, sd) unless allow_scheduled
333
+ refuse_protected!(id, sd) unless allow_scheduled
331
334
  RunningTasks.check!([id], state_dir: sd, policy: running_tasks) do |listing|
332
335
  DeleteRefused.new(id, :tasks_running, tasks: listing)
333
336
  end
@@ -391,13 +394,17 @@ module Samagotchi
391
394
  # @return [Array<String>]
392
395
  def delete_tree_ids(id, state_dir) = [*descendant_ids(id, state_dir).reverse, id]
393
396
 
394
- # DeleteRefused :scheduled when an enabled schedule's target, anchor
395
- # or head is +id+: deleting a head would make the schedule fall back to
396
- # an archived link and lose the links after it.
397
- def refuse_scheduled!(id, state_dir)
398
- require_relative "../schedules"
399
- schedule = Schedules.new(state_dir: state_dir).protecting_link(id)
400
- raise DeleteRefused.new(id, :scheduled, schedule_id: schedule.id) if schedule
397
+ # DeleteRefused with the reason a SessionProtection protector holds +id+
398
+ # for (:scheduled: an enabled schedule's target, anchor or head;
399
+ # deleting a head would make the schedule fall back to an archived link
400
+ # and lose the links after it), or with +chain+ the chain +id+ is in
401
+ # (:chain_scheduled). A protector's store that doesn't read refuses it
402
+ # too (:protection_unreadable, its words); any other raise raises here.
403
+ def refuse_protected!(id, state_dir, chain: false)
404
+ hold = chain ? SessionProtection.chain_hold(id, state_dir: state_dir) : SessionProtection.hold(id, state_dir: state_dir)
405
+ raise DeleteRefused.new(id, hold.reason, schedule_id: hold.ref) if hold
406
+ rescue SessionProtection::Unreadable => e
407
+ raise DeleteRefused.new(id, :protection_unreadable, message: e.message)
401
408
  end
402
409
 
403
410
  # Remove every store with state scoped to +id+. The file and sidecar
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "log"
4
+
5
+ module Samagotchi
6
+ # Who protects a session from a delete (docs/sessions.md, "Deleting a
7
+ # session"): the sibling of SessionStores, which says what a delete
8
+ # removes; this says what refuses it. The retention sweep keeps every
9
+ # protected id, a link's delete is refused by its first #hold and a chain's
10
+ # by its first #chain_hold (SessionManager::DeleteRefused, whose reasons
11
+ # hold the words).
12
+ #
13
+ # A protector is what a PROTECTORS entry builds for a state dir, answering
14
+ # three questions: #protected_ids (Array<String>), #hold(session_id) and
15
+ # #chain_hold(session_id) (a Hold or nil). Schedules is the one protector
16
+ # (Schedules::ProtectionPart: an enabled schedule's anchor, head and
17
+ # resolved target).
18
+ #
19
+ # Fail-closed: a protector that raises is logged and the error re-raised,
20
+ # never read as "unprotected". The sweep (SessionRetention.sweep_if_due)
21
+ # logs retention_failed and deletes nothing (an Unreadable store:
22
+ # retention_skipped, once per sweep interval); a delete raises to its
23
+ # caller, and a store that is there but doesn't read (Unreadable) is its
24
+ # refusal (DeleteRefused :protection_unreadable,
25
+ # SessionManager.refuse_protected!). A missing store protects nothing.
26
+ module SessionProtection
27
+ # +session_id+ the session held, +reason+ the DeleteRefused reason the
28
+ # holder asks for (:scheduled for a link, :chain_scheduled for a chain),
29
+ # +ref+ the holder's id for the words (the schedule id).
30
+ Hold = Data.define(:session_id, :reason, :ref)
31
+
32
+ # A protector's store is there but doesn't read (schedules.json not
33
+ # JSON, not a schedules document, a file chi can't open, or one schedule
34
+ # in it that doesn't read): who it protects is unknown, so no session is
35
+ # deleted until it is fixed. Its words, one per condition: the whole
36
+ # file, or one entry (+entry+, its id) and the way to drop that entry.
37
+ class Unreadable < StandardError
38
+ # @param file [String] the store's name, for the words
39
+ # @param error [String] why it doesn't read
40
+ # @param entry [String, nil] the id of the one entry that doesn't read
41
+ def initialize(file, error, entry: nil)
42
+ if entry
43
+ super("schedule entry #{entry} in #{file} is unreadable (#{error}): chi schedule cancel #{entry}, " \
44
+ "or fix the file, before deleting sessions")
45
+ else
46
+ super("#{file} is unreadable (#{error}): fix or remove it before deleting sessions")
47
+ end
48
+ end
49
+ end
50
+
51
+ module_function
52
+
53
+ # Deferred: schedules.rb requires session_manager, whose removal part
54
+ # requires this file.
55
+ def schedule_protector(state_dir)
56
+ require_relative "schedules"
57
+ Schedules.new(state_dir: state_dir)
58
+ end
59
+
60
+ PROTECTORS = { schedule: method(:schedule_protector) }.freeze
61
+
62
+ # @return [Array<String>] every id some protector holds (retention keeps them)
63
+ def protected_ids(state_dir:)
64
+ PROTECTORS.flat_map { |name, build| ask(name, build, state_dir, &:protected_ids) }.uniq
65
+ end
66
+
67
+ # @return [Hold, nil] the first protector's hold on a delete of +session_id+
68
+ def hold(session_id, state_dir:)
69
+ first_hold(session_id, state_dir) { |protector| protector.hold(session_id) }
70
+ end
71
+
72
+ # @return [Hold, nil] the first protector's hold on a delete of the chain
73
+ # +session_id+ belongs to
74
+ def chain_hold(session_id, state_dir:)
75
+ first_hold(session_id, state_dir) { |protector| protector.chain_hold(session_id) }
76
+ end
77
+
78
+ def first_hold(session_id, state_dir, &question)
79
+ PROTECTORS.each do |name, build|
80
+ found = ask(name, build, state_dir, sid: session_id, &question)
81
+ return found if found
82
+ end
83
+ nil
84
+ end
85
+ private_class_method :first_hold
86
+
87
+ # An Unreadable store is logged once, by the caller (retention_skipped,
88
+ # or the delete's refusal), not here.
89
+ def ask(name, build, state_dir, sid: nil)
90
+ yield build.call(state_dir)
91
+ rescue Unreadable
92
+ raise
93
+ rescue StandardError => e
94
+ Log.warn(:worker, "protector_failed", protector: name, sid: sid, error: e.class.name, msg: e.message)
95
+ raise
96
+ end
97
+ private_class_method :ask
98
+ end
99
+ end
@@ -10,6 +10,7 @@ require_relative "config"
10
10
  require_relative "log"
11
11
  require_relative "model_profile"
12
12
  require_relative "session_manager"
13
+ require_relative "session_protection"
13
14
  require_relative "system_one/runs"
14
15
 
15
16
  module Samagotchi
@@ -143,9 +144,15 @@ module Samagotchi
143
144
  age = Time.now - File.mtime(marker)
144
145
  return if age < interval
145
146
  end
146
- result = prune(state_dir: sd)
147
+ result = begin
148
+ prune(state_dir: sd)
149
+ rescue SessionProtection::Unreadable => e
150
+ skipped_round(sd, e)
151
+ end
147
152
  sweep_runs(sd)
148
153
  FileUtils.touch(marker)
154
+ return nil if result.nil?
155
+
149
156
  if result[:deleted].any?
150
157
  stops = result[:tasks_stopped].to_i
151
158
  suffix = stops.positive? ? "; stopped #{stops} background tasks" : ""
@@ -157,6 +164,16 @@ module Samagotchi
157
164
  nil
158
165
  end
159
166
 
167
+ # A protector's store doesn't read: no session is deleted this round,
168
+ # logged once (the next try is at the next interval, the marker touched
169
+ # as for a sweep that ran); the parts that ask no protector still run
170
+ # (the skeleton-only dirs here, the saved runs after).
171
+ private_class_method def self.skipped_round(state_dir, error)
172
+ Log.warn(:worker, "retention_skipped", msg: error.message)
173
+ prune_orphan_dirs(state_dir, dry_run: false) if SessionManager.discard_empty?
174
+ nil
175
+ end
176
+
160
177
  # System 1's saved runs last as long as sessions, by day file. Never a
161
178
  # reason the session sweep fails.
162
179
  private_class_method def self.sweep_runs(state_dir)
@@ -214,9 +231,7 @@ module Samagotchi
214
231
  def self.apply(state_dir: Session.default_state_dir, days: DEFAULT_RETENTION_DAYS, max_count: DEFAULT_MAX_COUNT,
215
232
  keep_status: DEFAULT_KEEP_STATUS, dry_run: false, test_only: false, alive_check: nil,
216
233
  empty_check: nil, any_age: false, now: Time.now)
217
- require_relative "schedules"
218
- schedules = Schedules.new(state_dir: state_dir)
219
- scheduled_targets = schedules.protected_session_ids
234
+ protected_ids = SessionProtection.protected_ids(state_dir: state_dir)
220
235
  keep_status = Array(keep_status).map(&:to_s)
221
236
  # Fetch all sessions sorted newest-first for count logic
222
237
  all = Session.list(state_dir: state_dir, sort: "updated_at", order: "desc")
@@ -243,7 +258,7 @@ module Samagotchi
243
258
  next
244
259
  end
245
260
 
246
- if scheduled_targets.include?(session.id)
261
+ if protected_ids.include?(session.id)
247
262
  kept << session.id
248
263
  next
249
264
  end
@@ -318,7 +333,7 @@ module Samagotchi
318
333
  # once, at the start): resumed or taken by a worker since, it stays.
319
334
  elsif held?(session.id, state_dir, alive_check)
320
335
  kept << session.id
321
- elsif scheduled_targets.include?(session.id)
336
+ elsif protected_ids.include?(session.id)
322
337
  kept << session.id
323
338
  else
324
339
  policy = SessionManager::RunningTasks::Policy.stop(by: "retention")
@@ -4,6 +4,7 @@ require "json"
4
4
  require_relative "session"
5
5
  require_relative "session_row"
6
6
  require_relative "session_manager"
7
+ require_relative "session_protection"
7
8
  require_relative "session_retention"
8
9
  require_relative "project_scope"
9
10
  require_relative "analytics_file"
@@ -364,6 +365,9 @@ module Samagotchi
364
365
  @stdout.puts "\nRun without --dry-run to delete."
365
366
  end
366
367
  0
368
+ rescue Samagotchi::SessionProtection::Unreadable => e
369
+ @stderr.puts e.message
370
+ 1
367
371
  end
368
372
  end
369
373
  end
@@ -115,6 +115,19 @@ module Samagotchi
115
115
  "Samagotchi::ProjectEnv.respond_to?" => "checks the worker has ProjectEnv.spawn_env (an older chi doesn't)",
116
116
  "Samagotchi::ProjectEnv.spawn_env" => "starts a server in the session's project env: needs a ctx tools-env API"
117
117
  },
118
+ # The kit has no page runner: the page's spec runs it through chi's own (Pages::Launch).
119
+ "schedules" => {
120
+ 'require "samagotchi/memory_bundle/installer"' => "spec: installs the bundle as chi does (the page is listed from the record)",
121
+ "Samagotchi::MemoryBundle::Installer.new" => "spec: installs the bundle as chi does",
122
+ 'require "samagotchi/pages"' => "spec: for Pages",
123
+ 'require "samagotchi/pages/launch"' => "spec: for Pages::Launch",
124
+ "Samagotchi::Pages::Launch.run" => "spec: a run as chi web's Refresh starts it: a kit page runner could replace it",
125
+ "Samagotchi::Pages::Store" => "spec: the page as listed and stored",
126
+ "Samagotchi::Pages.scripts_dir" => "spec: the owner's pages folder stays unmade",
127
+ "Samagotchi::Pages::MAX_OUTPUT_BYTES" => "spec: the output cap the page stays under",
128
+ "Samagotchi::Pages::MAX_TEXT_BYTES" => "spec: the text block cap the off and unreadable texts stay under",
129
+ "Samagotchi::Paths.state_dir" => "spec: where the fixture schedules.json goes"
130
+ },
118
131
  "slow-commands" => {
119
132
  'require "samagotchi/guardrails/shell_lex"' => "for ShellLex",
120
133
  "Samagotchi::Guardrails::ShellLex" => "splits a command into its parts: needs a stable shell-parsing helper",
@@ -25,8 +25,10 @@ module Samagotchi
25
25
  entry = schedules.lookup(name)
26
26
  return "No schedule named #{name}." if entry.nil?
27
27
 
28
+ # nil: gone since the lookup (another cancel in between).
28
29
  if want_all || peers&.session_id.nil?
29
- schedules.cancel(name)
30
+ return "No schedule named #{name}." unless schedules.cancel(name)
31
+
30
32
  return "Cancelled #{entry.id} (#{entry.title || entry.recurrence_words})."
31
33
  end
32
34
 
@@ -35,7 +37,8 @@ module Samagotchi
35
37
  "chi schedule cancel #{entry.id} cancels it, or say all: true if you meant it."
36
38
  end
37
39
 
38
- schedules.cancel(name)
40
+ return "No schedule named #{name}." unless schedules.cancel(name)
41
+
39
42
  "Cancelled #{entry.id} (#{entry.title || entry.recurrence_words})."
40
43
  rescue StandardError => e
41
44
  "Error: #{e.message}"
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "session_inbox"
4
+ require_relative "turn_checkpoint"
5
+
6
+ module Samagotchi
7
+ # What a queued turn came to, from its files: whether it left a reply
8
+ # (SessionInbox.reply_for) and the turn it settled as (the session's
9
+ # last_turn when it is that turn, else TurnCheckpoint.settled_turn). A
10
+ # schedule's pending firing reads it (Schedules#resolve_pending, which
11
+ # keeps its own order around it: the reply, its question window, the turn,
12
+ # expiry).
13
+ # @!attribute replied [Boolean] a reply file names the turn
14
+ # @!attribute turn [LastTurn, nil] the settled turn, nil while it runs
15
+ TurnOutcome = Data.define(:replied, :turn) do
16
+ # @param session [Session] the session the turn was queued in
17
+ # @param turn_id [String] its enqueued id
18
+ # @param session_dir [String] that session's sidecar dir
19
+ # @return [TurnOutcome]
20
+ def self.for(session, turn_id, session_dir:)
21
+ turn = session.last_turn if session.last_turn&.enqueued_id == turn_id
22
+ turn ||= TurnCheckpoint.settled_turn(session_dir, turn_id)
23
+ new(replied: !SessionInbox.reply_for(session_dir, turn_id).nil?, turn: turn)
24
+ end
25
+
26
+ def settled? = replied || !turn.nil?
27
+
28
+ # The settled turn completed (the turn alone: a reply is #replied).
29
+ def completed? = turn&.outcome == "completed"
30
+
31
+ # The words of a settled outcome, nil before it settles.
32
+ # @return [String, nil]
33
+ def detail
34
+ return nil unless settled?
35
+ return "turn completed" if replied || completed?
36
+
37
+ reason = [turn.outcome, turn.error_kind, turn.cancel_reason, turn.stopped_by].compact.join(": ")
38
+ "turn #{reason.empty? ? "did not complete" : reason}"
39
+ end
40
+ end
41
+ end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.188.0"
4
+ VERSION = "0.189.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -7,7 +7,7 @@ require_relative "../pages/launch"
7
7
  module Samagotchi
8
8
  module Web
9
9
  # The pages routes, mixed into App (docs/internals/pages.md, chi web): the
10
- # list for All sessions' Pages group, a page as stored (opening runs
10
+ # list for the Pages list and the pages pill, a page as stored (opening runs
11
11
  # nothing), Refresh (one run through Pages::Launch, inside the request)
12
12
  # and Delete. All the owner's: a participant never sees pages. The name
13
13
  # is checked (Pages.valid_name?) before anything builds a path; one that
@@ -26,18 +26,19 @@ module Samagotchi
26
26
  private
27
27
 
28
28
  # GET /api/pages: {pages: [{name, title, state, ran_at, failed_at,
29
- # changed, error_line}]}, by name.
29
+ # changed, error_line, bundle}]}, by name (+bundle+: the bundle whose
30
+ # page it is, Pages::Bundled; nil for the owner's own).
30
31
  def handle_pages_list(_req)
31
32
  rows = Pages::Store.list.map do |page|
32
33
  { name: page.name, title: page.title, state: page.state.to_s, ran_at: page.ran_at, failed_at: page.error&.at,
33
- changed: page.changed?, error_line: page.error&.line }
34
+ changed: page.changed?, error_line: page.error&.line, bundle: page.bundle }
34
35
  end
35
36
  json_response(200, { pages: rows })
36
37
  end
37
38
 
38
39
  # GET /api/pages/NAME: the page as stored (#page_json); 404 page_missing.
39
40
  def handle_page_show(_req, name)
40
- return page_missing(name) unless Pages.valid_name?(name) && File.file?(Pages.script_path(name))
41
+ return page_missing(name) unless Pages.valid_name?(name) && Pages.exists?(name)
41
42
 
42
43
  json_response(200, page_json(Pages::Store.read(name)))
43
44
  end
@@ -63,7 +64,8 @@ module Samagotchi
63
64
  end
64
65
 
65
66
  # DELETE /api/pages/NAME: the script and its result. {removed: NAME};
66
- # 409 page_busy, 404 page_missing.
67
+ # 409 page_busy, 409 page_bundled (a bundle's page: Pages::FromBundle),
68
+ # 404 page_missing.
67
69
  def handle_page_delete(_req, name)
68
70
  return page_missing(name) unless Pages.valid_name?(name)
69
71
 
@@ -73,6 +75,8 @@ module Samagotchi
73
75
  error_response(404, "page_missing", e.message)
74
76
  rescue Pages::Busy => e
75
77
  error_response(409, "page_busy", e.message)
78
+ rescue Pages::FromBundle => e
79
+ error_response(409, "page_bundled", e.message)
76
80
  end
77
81
 
78
82
  def page_missing(name) = error_response(404, "page_missing", Pages::Missing.new(name).message)
@@ -80,12 +84,13 @@ module Samagotchi
80
84
  # A page for the view. +changed+: the result came from an older script
81
85
  # (Stored#changed?); +changed_after_failure+: the script differs from
82
86
  # the one that failed, so the view needs no sha. +script_changed_at+:
83
- # the script file's mtime. A text block carries +html+ (sanitised)
84
- # when Markdown rendering is available.
87
+ # the script file's mtime. +bundle+: the bundle whose page it is (the
88
+ # view offers no Delete), nil for the owner's own. A text block carries
89
+ # +html+ (sanitised) when Markdown rendering is available.
85
90
  def page_json(page)
86
91
  error = page.error
87
92
  { name: page.name, title: page.title, state: page.state.to_s, ran_at: page.ran_at, duration_ms: page.duration_ms,
88
- changed: page.changed?,
93
+ changed: page.changed?, bundle: page.bundle,
89
94
  changed_after_failure: !error.nil? && !error.script_sha.nil? && !page.current_sha.nil? &&
90
95
  error.script_sha != page.current_sha,
91
96
  script_changed_at: script_mtime(page.name),
@@ -84,9 +84,7 @@ import { hasHistory, historyLoader } from "./participant_history.js";
84
84
  import { createCommandList } from "./command_list.js";
85
85
  import { sessionHash } from "./route.js";
86
86
  import { createViews } from "./views.js";
87
- import { createPageView } from "./page_view.js";
88
- import { createPagesGroup } from "./pages_group.js";
89
- import { installPageLinks } from "./page_links.js";
87
+ import { wirePages } from "./pages_wiring.js";
90
88
  import { createOwnerClaim } from "./owner_claim.js";
91
89
  import { createOwnerVerify } from "./owner_verify.js";
92
90
  import { scopeDir, scopeTemplate } from "./scope.js";
@@ -632,6 +630,7 @@ function openSessionEvents() {
632
630
  snapshot: (data) => store.batch(() => {
633
631
  versionNotices.notice(data);
634
632
  versionNotices.reconnected(data.version);
633
+ pagesUi?.snapshot();
635
634
  if (data.chi_update) versionNotices.frame(data.chi_update, { snapshot: true });
636
635
  notifications?.noticeSessions("snapshot", data);
637
636
  store.update({ sessions: applySessionEvent(store.sessions, "snapshot", data) });
@@ -652,6 +651,7 @@ function openSessionEvents() {
652
651
  },
653
652
  chi: (data) => versionNotices.notice(data),
654
653
  chi_update: (data) => versionNotices.frame(data),
654
+ pages: () => pagesUi?.changed(), // a page script made or removed (pages_wiring.js)
655
655
  }, {
656
656
  dir: scope.dir,
657
657
  onError: () => {
@@ -780,27 +780,21 @@ window.addEventListener("resize", () => rename.reposition());
780
780
 
781
781
  const { confirmDelete, leaveGoneSession, continueSelected, archiveOne, setArchived } = sessionActions;
782
782
 
783
- // A page, #/p/NAME, in place of the session area (page_view.js): the pages capability's.
784
- const pageView = viewer.can("pages") ? createPageView({
785
- root: $("#pageView"), api, toast: (text) => showToast(text), copyText, back: () => closePage(), gone: () => leavePage(),
786
- backLabel: () => pageBackLabel(), phone: () => !!window.matchMedia?.("(max-width: 600px)").matches,
787
- }) : null;
783
+ // The pages capability's parts (pages_wiring.js): the pages pill, the Pages list at #/pages, a page at #/p/NAME, the #/p/ links.
784
+ const pagesUi = wirePages({ viewer, $, api, toast: (text) => showToast(text), copyText, turnRoots, views: () => views });
788
785
  // The views by hash: All sessions, a page and the session's own (views.js).
789
- const {
790
- allViewOpen, openAllView, closeAllView, leaveAllView, setSessionHash, selectFromHash, applyView,
791
- pageOpen, openPage, closePage, leavePage, pageBackLabel,
792
- } = createViews({
786
+ const views = createViews({
793
787
  participant, store, lists, topStripEl, pictures, eventsLive: () => !!eventsControl, refresh, updateSessionTitle,
794
- select, clearSelection, ownerClaim: () => ownerClaim, pages: pageView, allViewOpened: () => pagesGroup?.load(),
788
+ select, clearSelection, ownerClaim: () => ownerClaim, pages: pagesUi?.pageView ?? null, pagesList: pagesUi?.pagesList ?? null,
789
+ allViewOpened: () => pagesUi?.allViewOpened(),
795
790
  });
796
- // All sessions' Pages group (pages_group.js), and a #/p/ link opening its page in place (page_links.js).
797
- const pagesGroup = pageView && createPagesGroup({ root: $("#pagesGroup"), filterEl: $("#filter"), api, open: (name) => openPage(name) });
798
- if (pageView) installPageLinks([...turnRoots(), $("#pageView")], { open: (name) => openPage(name) });
791
+ const { allViewOpen, openAllView, closeAllView, leaveAllView, setSessionHash, selectFromHash, applyView, pageOpen, pagesAreaOpen } = views;
799
792
  // The page's claim links (owner_claim.js): one opened here, once drawn, and
800
793
  // annotate's Copy link.
801
794
  const ownerClaim = createOwnerClaim({
802
795
  historyEl, store, claimTarget: () => participantsControl?.claimTarget() ?? null,
803
- toast: (...args) => showToast(...args), copyText, allViewOpen, home: document.body.dataset.home || "",
796
+ toast: (...args) => showToast(...args), copyText, allViewOpen, pagesAreaOpen,
797
+ home: document.body.dataset.home || "",
804
798
  });
805
799
 
806
800
  // The composer's placeholder, hint, buttons and delivery row (composer_mode.js).
@@ -1296,7 +1290,7 @@ async function handleCancel() {
1296
1290
  // The typed draft stays in the composer: paste in a session, then + new session
1297
1291
  // starts from it (with the model picker). clearSelection leaves #prompt alone.
1298
1292
  viewer.control($("#newBtn"), "sessions")?.addEventListener("click", () => {
1299
- if (allViewOpen() || pageOpen()) leaveAllView("");
1293
+ if (allViewOpen() || pageOpen() || views.listOpen?.()) leaveAllView("");
1300
1294
  clearSelection();
1301
1295
  startPage.loadModels({ asked: true });
1302
1296
  });
@@ -2003,6 +2003,12 @@ body.strip-hidden #topStrip{display:none}
2003
2003
  /* In the all view the pill is the view's own button, pressed (app.js applyView), whatever the strip's state: a click goes
2004
2004
  back to the chat (lists_view.js), as Esc does. */
2005
2005
  body.all-view #stripStatus{display:block}
2006
+ /* The pages pill (pages_wiring.js): the sessions pill's look and size, shown in every view while there is a page (not tied
2007
+ to the strip or the all view); hidden while there is none. */
2008
+ #pagesBtn{display:block;align-self:center;height:28px;min-height:0;padding:0 10px;font-size:12px;line-height:26px;white-space:nowrap;flex-shrink:0}
2009
+ #pagesBtn[hidden]{display:none}
2010
+ #pagesBtn:not([aria-pressed="true"]){border-color:var(--border-strong)}
2011
+ #pagesBtn:hover{filter:none}
2006
2012
  .strip-toggle[aria-pressed="true"]{color:var(--accent);background:var(--accent-bg);border-color:var(--accent-border)}
2007
2013
  .strip-toggle[aria-pressed="true"]:hover{color:var(--accent);border-color:var(--accent)}
2008
2014
  /* The strip's grip (strip_grip.js, app.js): the handle on the edge between the
@@ -2185,8 +2191,8 @@ a{color:var(--accent)}
2185
2191
  #notifyBtn::after{content:"";position:absolute;inset:-7px}
2186
2192
  #scope .scope-all{position:relative}
2187
2193
  #scope .scope-all::after{content:"";position:absolute;inset:-14px -4px -11px -3px}
2188
- #stripStatus{position:relative}
2189
- #stripStatus::after{content:"";position:absolute;inset:-2px 0}
2194
+ #stripStatus,#pagesBtn{position:relative}
2195
+ #stripStatus::after,#pagesBtn::after{content:"";position:absolute;inset:-2px 0}
2190
2196
  #newBtn{position:relative}
2191
2197
  #newBtn::after{content:"";position:absolute;inset:-3px}
2192
2198
  /* The pill: its box 40px tall and borderless (no border at all: a transparent one would put the ::before 1px inside, a
@@ -2256,6 +2262,7 @@ body.participant-view .bubble.user:not(.by-participant)>.origin-label{color:var(
2256
2262
  <button type="button" id="newBtn" class="brand" title="New session" aria-label="New session"><span class="brand-name">chi</span><span class="brand-new"><svg class="brand-plus" viewBox="0 0 12 12" aria-hidden="true"><path d="M6 1.5v9M1.5 6h9"/></svg><span class="brand-new-word">new session</span></span></button>
2257
2263
  <div id="scope" hidden></div>
2258
2264
  <button type="button" class="strip-toggle" id="stripStatus" title="All sessions, with search"><span class="pill-count">sessions</span></button>
2265
+ <button type="button" class="strip-toggle" id="pagesBtn" title="Pages" aria-pressed="false" hidden>pages</button>
2259
2266
  <span id="sessionTitleRow" hidden><span id="sessionTitle"></span><button type="button" id="titleRenameBtn" class="title-rename" title="Rename this session" aria-label="Rename this session" hidden>✎</button></span>
2260
2267
  <div id="allHead">
2261
2268
  <input id="filter" name="chi-filter" type="search" placeholder="Search preview, id or status" aria-label="Search sessions" autocomplete="off">
@@ -2328,7 +2335,9 @@ body.participant-view .bubble.user:not(.by-participant)>.origin-label{color:var(
2328
2335
  </div>
2329
2336
  </section>
2330
2337
  <section id="pageView" aria-label="Page"></section>
2338
+ <section id="pagesList" aria-label="Pages"></section>
2331
2339
  <section id="allView" aria-label="All sessions">
2340
+ <!-- Inert: an older cached app.js draws All sessions' Pages group into it (pages_group.js). Remove after 0.189.0. -->
2332
2341
  <div id="pagesGroup" hidden></div>
2333
2342
  <div id="allList"></div>
2334
2343
  <div id="allPath" hidden>Stored in <code></code></div>