samagotchi 0.138.0 → 0.139.1

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 (61) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +44 -1
  3. data/docs/architecture.md +33 -7
  4. data/docs/cli.md +6 -2
  5. data/docs/configuration.md +60 -5
  6. data/docs/internals/background-tasks.md +3 -3
  7. data/docs/internals/engine.md +2 -1
  8. data/docs/internals/tool-guardrails.md +2 -2
  9. data/docs/internals/web-push.md +20 -0
  10. data/docs/sessions.md +5 -3
  11. data/lib/samagotchi/bundle_command.rb +21 -21
  12. data/lib/samagotchi/bundles/mcp/manifest.yml +2 -2
  13. data/lib/samagotchi/bundles/mcp/plugin.rb +8 -3
  14. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  15. data/lib/samagotchi/bundles/system/self_map.md +2 -2
  16. data/lib/samagotchi/cancellation_controller.rb +4 -4
  17. data/lib/samagotchi/config.rb +4 -0
  18. data/lib/samagotchi/context_fetch.rb +2 -2
  19. data/lib/samagotchi/cut.rb +21 -0
  20. data/lib/samagotchi/cut_policy.rb +6 -5
  21. data/lib/samagotchi/engine.rb +4 -2
  22. data/lib/samagotchi/engine_peers.rb +2 -1
  23. data/lib/samagotchi/hook_routes.rb +3 -2
  24. data/lib/samagotchi/kernel_loop.rb +8 -6
  25. data/lib/samagotchi/launch_mode.rb +5 -2
  26. data/lib/samagotchi/llm/chat_loop.rb +3 -2
  27. data/lib/samagotchi/llm/openai_chat.rb +1 -1
  28. data/lib/samagotchi/memory_bundle/status.rb +13 -3
  29. data/lib/samagotchi/project_env.rb +16 -2
  30. data/lib/samagotchi/reply_wait/poll.rb +9 -2
  31. data/lib/samagotchi/reply_wait.rb +9 -3
  32. data/lib/samagotchi/steer_cut.rb +2 -1
  33. data/lib/samagotchi/task_finish_note.rb +8 -5
  34. data/lib/samagotchi/task_watch.rb +11 -6
  35. data/lib/samagotchi/testing/boundary.rb +3 -1
  36. data/lib/samagotchi/tool_activity.rb +3 -3
  37. data/lib/samagotchi/tool_declarations.rb +2 -2
  38. data/lib/samagotchi/tools/builtins.rb +2 -1
  39. data/lib/samagotchi/tools/delegate_wait.rb +23 -2
  40. data/lib/samagotchi/tools/execute.rb +51 -9
  41. data/lib/samagotchi/tools/task_runtime.rb +1 -1
  42. data/lib/samagotchi/turn_note.rb +6 -6
  43. data/lib/samagotchi/version.rb +1 -1
  44. data/lib/samagotchi/web/app.rb +30 -158
  45. data/lib/samagotchi/web/auto_update.rb +282 -0
  46. data/lib/samagotchi/web/public/app.js +6 -4
  47. data/lib/samagotchi/web/public/composer.css +1 -1
  48. data/lib/samagotchi/web/public/index.html +10 -9
  49. data/lib/samagotchi/web/public/notifications.js +10 -1
  50. data/lib/samagotchi/web/public/revise_stack.js +6 -5
  51. data/lib/samagotchi/web/public/task_stop.js +3 -3
  52. data/lib/samagotchi/web/public/update_notice.js +10 -4
  53. data/lib/samagotchi/web/public/update_sheet.js +3 -2
  54. data/lib/samagotchi/web/push/notifier.rb +66 -5
  55. data/lib/samagotchi/web/server.rb +45 -1
  56. data/lib/samagotchi/web/session_access_routes.rb +1 -1
  57. data/lib/samagotchi/web/session_hub.rb +20 -3
  58. data/lib/samagotchi/web/update_check.rb +56 -10
  59. data/lib/samagotchi/web/update_ops.rb +240 -0
  60. data/lib/samagotchi/worker_task_wakes.rb +1 -1
  61. metadata +4 -1
@@ -0,0 +1,282 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rubygems/version"
4
+ require "time"
5
+ require_relative "../config"
6
+ require_relative "../log"
7
+ require_relative "../version"
8
+
9
+ module Samagotchi
10
+ module Web
11
+ # With update.auto: install, installs the release UpdateCheck found when
12
+ # no turn runs anywhere, and tells the owner's phone how it went. Its own
13
+ # thread beside the checker; every POLL it takes the next step, so what
14
+ # stops it (a turn, another operation) only delays it.
15
+ #
16
+ # The gate: the install isn't blocked (a checkout, Bundler, an unwritable
17
+ # gem dir), no update operation runs, no session's turn runs or waits on
18
+ # a question (`chi update` merges shipped bundles that live workers
19
+ # read), and the release isn't one this already failed on (one automatic
20
+ # try per release: the Update button or a newer release tries again).
21
+ #
22
+ # With update.restart: idle (the default) the install is followed by:
23
+ # 1. the stale workers, only those idle and quiet for QUIET seconds (the
24
+ # worker still refuses atomically when it isn't), the left ones tried
25
+ # again each step for RETRY_FOR;
26
+ # 2. chi web itself, once no operation and no turn runs: a preflight
27
+ # (the newest chi must start and say its version) first, then the
28
+ # exec. The restarted chi web's own AutoUpdate sees phase `web`,
29
+ # counts the workers once more and says "chi updated": the process
30
+ # that survives is the one that speaks, and that proves it is up.
31
+ # A preflight that fails leaves chi web as it is and says so.
32
+ # update.restart: never stops after the install.
33
+ #
34
+ # The run's record lives in update_check.json (UpdateCheck#save_auto),
35
+ # so a chi web restart finds it. See docs/architecture.md.
36
+ class AutoUpdate
37
+ # Seconds between steps, and before the first (the checker's first
38
+ # check is at 30).
39
+ POLL = 300
40
+ FIRST = 60
41
+ # The first step of a chi web restarted by this run (it only has to finish).
42
+ FIRST_RESTARTED = 5
43
+ # A worker restarts unattended only when its session was idle and quiet
44
+ # this long (someone may be about to type), by its updated_at.
45
+ QUIET = 600
46
+ # The workers a run couldn't restart are tried again this long.
47
+ RETRY_FOR = 24 * 3600
48
+ # The phases a run is still in.
49
+ OPEN_PHASES = %w[installed workers web].freeze
50
+
51
+ # @param hub [SessionHub]
52
+ # @param ops [UpdateOps]
53
+ # @param check [UpdateCheck] the answer and the record
54
+ # @param auto [String] update.auto
55
+ # @param restart [String] update.restart (idle or never)
56
+ # @param preflight [#call, nil] `(version) → nil | String`: whether the
57
+ # newest chi starts (nil result), or why not (nil: no check)
58
+ # @param clock [#call] the Time now
59
+ # @param poll [Numeric] seconds between steps
60
+ def initialize(hub:, ops:, check:, auto: Config.get("update.auto"), restart: Config.get("update.restart"),
61
+ preflight: nil, clock: -> { Time.now }, poll: POLL, first: FIRST)
62
+ @hub = hub
63
+ @ops = ops
64
+ @check = check
65
+ @auto = auto
66
+ @restart = restart
67
+ @preflight = preflight
68
+ @clock = clock
69
+ @poll = poll
70
+ @first = first
71
+ @wakeup = Queue.new
72
+ @thread = nil
73
+ @stopped = false
74
+ end
75
+
76
+ def start
77
+ return self unless @auto == "install"
78
+ return self if @thread&.alive?
79
+
80
+ @stopped = false
81
+ @thread = Thread.new { run_loop }
82
+ self
83
+ end
84
+
85
+ def stop
86
+ @stopped = true
87
+ @wakeup << :stop
88
+ thread = @thread
89
+ @thread = nil
90
+ thread&.join(5.0)
91
+ nil
92
+ end
93
+
94
+ # One look at what to do next (the thread's step; specs call it).
95
+ def step
96
+ return unless @auto == "install"
97
+
98
+ record = @check.auto_state
99
+ return carry_on(record) if record && OPEN_PHASES.include?(record[:phase])
100
+
101
+ version = @check.available
102
+ return unless version
103
+ return if @check.auto_failed?(version) || tried?(version)
104
+ return if @ops.blocked_reason || @ops.running? || busy_turn?
105
+
106
+ install(version)
107
+ end
108
+
109
+ private
110
+
111
+ def run_loop
112
+ wait = restarted? ? FIRST_RESTARTED : @first
113
+ until @stopped
114
+ break if @wakeup.pop(timeout: wait) == :stop
115
+
116
+ step
117
+ wait = @poll
118
+ end
119
+ rescue StandardError => e
120
+ Log.exception(:web, "auto_update_failed", e)
121
+ end
122
+
123
+ # A run that this chi web's start finds on its way to the web restart.
124
+ def restarted?
125
+ @check.auto_state&.dig(:phase) == "web"
126
+ end
127
+
128
+ # This release's run is already on record (installed, or given up on).
129
+ def tried?(version)
130
+ @check.auto_state&.dig(:version) == version
131
+ end
132
+
133
+ # A turn runs, or a question waits for its answer, in any session.
134
+ def busy_turn?
135
+ @hub.snapshot.any? do |summary|
136
+ summary[:status] == "running" || !summary[:pending_question].nil?
137
+ end
138
+ end
139
+
140
+ def install(version)
141
+ Log.info(:web, "auto_update_start", version: version, from: VERSION)
142
+ result = @ops.install(version, wait: true, auto: true)
143
+ return Log.info(:web, "auto_update_deferred", version: version, why: result) if result.is_a?(Symbol)
144
+
145
+ rows = result[:rows]
146
+ record = { version: version, from: VERSION, at: @clock.call.iso8601, kept: kept_files(rows) }
147
+ if result[:state] == "done"
148
+ Log.info(:web, "auto_update_installed", version: version, kept: record[:kept].size)
149
+ installed(record)
150
+ else
151
+ failed(record, rows)
152
+ end
153
+ end
154
+
155
+ # Installed. With restart: never the phone is told and the owner's
156
+ # toast and idle exit carry chi web and the workers over; else the
157
+ # restarts follow, here and now when nothing holds them.
158
+ def installed(record)
159
+ return carry_on(save(record.merge(phase: "installed"))) unless @restart == "never"
160
+
161
+ @hub.publish_notice(kind: "installed", version: record[:version], kept: record[:kept].size)
162
+ save(record.merge(phase: "done", pushed: true))
163
+ end
164
+
165
+ # The next step of a run on record.
166
+ def carry_on(record)
167
+ case record[:phase]
168
+ when "installed", "workers" then workers_then_web(record)
169
+ when "web" then finish(record)
170
+ end
171
+ end
172
+
173
+ def workers_then_web(record)
174
+ return if @ops.running?
175
+
176
+ record = restart_workers(record) if record[:phase] == "installed" || workers_left?(record)
177
+ return unless record
178
+
179
+ restart_web(record)
180
+ end
181
+
182
+ def workers_left?(record)
183
+ record.dig(:workers, :left).to_i.positive? && @clock.call - recorded_at(record) < RETRY_FOR
184
+ end
185
+
186
+ def recorded_at(record)
187
+ Time.iso8601(record[:at].to_s)
188
+ rescue ArgumentError
189
+ @clock.call
190
+ end
191
+
192
+ # A pass over the stale workers that are idle and quiet; the counts
193
+ # add up over passes. nil when another operation took the turn.
194
+ def restart_workers(record)
195
+ result = @ops.restart_workers(wait: true, auto: true, select: quiet_filter)
196
+ return if result.is_a?(Symbol)
197
+
198
+ states = result[:rows].map { |row| row["state"] }
199
+ restarted = record.dig(:workers, :restarted).to_i + states.count("restarted")
200
+ save(record.merge(phase: "workers", workers: { restarted: restarted, left: states.size - states.count("restarted") }))
201
+ end
202
+
203
+ # Idle and quiet: no turn, no question, untouched for QUIET seconds.
204
+ def quiet_filter
205
+ summaries = @hub.snapshot.to_h { |summary| [summary[:id], summary] }
206
+ now = @clock.call
207
+ lambda do |worker|
208
+ summary = summaries[worker.session_id]
209
+ next false unless summary && summary[:status] == "idle" && summary[:pending_question].nil?
210
+
211
+ touched = parse_time(summary[:updated_at])
212
+ !touched.nil? && now - touched >= QUIET
213
+ end
214
+ end
215
+
216
+ def parse_time(value)
217
+ Time.iso8601(value.to_s)
218
+ rescue ArgumentError
219
+ nil
220
+ end
221
+
222
+ # chi web itself, once no turn runs anywhere and the newest chi is
223
+ # known to start. The record says `web` before the exec: the process
224
+ # that comes up finishes the run.
225
+ def restart_web(record)
226
+ return if busy_turn?
227
+
228
+ problem = @preflight&.call(record[:version])
229
+ return restart_failed(record, problem, "auto_restart_preflight_failed") if problem
230
+
231
+ save(record.merge(phase: "web"))
232
+ Log.info(:web, "auto_update_restart", version: record[:version])
233
+ case (answer = @ops.restart_web)
234
+ when :started then nil
235
+ when :busy then save(record.merge(phase: "workers"))
236
+ else restart_failed(record, "chi web can't restart itself here (#{answer})", "auto_restart_refused")
237
+ end
238
+ end
239
+
240
+ def restart_failed(record, detail, event)
241
+ Log.warn(:web, event, version: record[:version], detail: detail)
242
+ @hub.publish_notice(kind: "restart_failed", version: record[:version], detail: detail)
243
+ save(record.merge(phase: "failed", detail: detail, pushed: true))
244
+ end
245
+
246
+ # In the restarted chi web: on the version, the workers counted once
247
+ # more, "chi updated" said.
248
+ def finish(record)
249
+ if Gem::Version.new(VERSION) < Gem::Version.new(record[:version])
250
+ return restart_failed(record, "chi web came back on #{VERSION}", "auto_restart_wrong_version")
251
+ end
252
+
253
+ @hub.scan
254
+ record = restart_workers(record) || record
255
+ workers = record[:workers] || {}
256
+ Log.info(:web, "auto_update_done", version: record[:version], restarted: workers[:restarted], left: workers[:left])
257
+ @hub.publish_notice(kind: "updated", version: record[:version], kept: record[:kept].to_a.size,
258
+ restarted: workers[:restarted].to_i, left: workers[:left].to_i)
259
+ save(record.merge(phase: "done", pushed: true))
260
+ end
261
+
262
+ def save(record)
263
+ @check.save_auto(record)
264
+ record
265
+ end
266
+
267
+ def failed(record, rows)
268
+ row = rows.find { |candidate| candidate["failed"] } || rows.first || {}
269
+ detail = row["status"].to_s.lines.first.to_s.strip
270
+ Log.warn(:web, "auto_update_failed_install", version: record[:version], detail: detail)
271
+ gem_installed = rows.any? { |candidate| candidate["component"] == "chi (gem)" && !candidate["failed"] }
272
+ @hub.publish_notice(kind: "failed", version: record[:version], detail: detail.empty? ? nil : detail,
273
+ installed: gem_installed)
274
+ @check.save_auto(record.merge(phase: "failed", detail: detail, pushed: true), failed: record[:version])
275
+ end
276
+
277
+ def kept_files(rows)
278
+ rows.flat_map { |row| Array(row["kept"]).map(&:to_s) }.uniq
279
+ end
280
+ end
281
+ end
282
+ end
@@ -578,7 +578,7 @@ function noticeVersions(data) {
578
578
  Object.assign(versions, mergeVersionState(versions, data));
579
579
  const notice = versionNotice({ loaded: document.body.dataset.version, served: versions.served,
580
580
  installed: versions.installed, available: versions.available,
581
- updateBlocked: versions.updateBlocked, shown: versionNoticesShown });
581
+ updateBlocked: versions.updateBlocked, auto: versions.auto, shown: versionNoticesShown });
582
582
  store.touch("infoBar"); // the worker badge compares with the newest installed
583
583
  if (!notice) return;
584
584
  versionNoticesShown.add(notice.key);
@@ -608,12 +608,12 @@ function updateFrame(data, { snapshot = false } = {}) {
608
608
  const wasOpen = updateSheet.isOpen();
609
609
  if (!updateSheet.receive(data)) return;
610
610
  if (data.operation === "install" && data.state === "done" && data.version) noticeVersions({ installed: data.version });
611
+ const label = `${data.auto ? "Automatic " : ""}${data.operation === "install" ? "chi update" : "worker restart"}`
612
+ .replace(/^./, (c) => c.toUpperCase());
611
613
  if (!wasOpen && data.state === "running") {
612
- const label = data.operation === "install" ? "Chi update" : "Worker restart";
613
614
  showToast(`${label} in progress`, { label: "View", run: () => updateSheet.view() }, { sticky: true });
614
615
  } else if (!snapshot && !wasOpen && ["done", "failed"].includes(data.state)
615
616
  && !(data.operation === "install" && data.state === "done")) {
616
- const label = data.operation === "install" ? "Chi update" : "Worker restart";
617
617
  showToast(`${label} ${data.state}`, { label: "View", run: () => updateSheet.view() }, { sticky: true });
618
618
  }
619
619
  }
@@ -822,7 +822,9 @@ function claimOpts() {
822
822
  // active (it opens in the browser their review link was opened in: one
823
823
  // link per browser, the cookie), else this page's own.
824
824
  function claimLinkFor(source, range) {
825
- if (!store.selected || !["answer", "step", "user"].includes(source.kind) || !historyEl.contains(source.root)) return null;
825
+ // Not in a Revise stack's switched copy (revise_switch.js: view only, no claim key; Verify isn't offered there either).
826
+ if (!store.selected || !["answer", "step", "user"].includes(source.kind) || !historyEl.contains(source.root)
827
+ || source.root.closest("[data-stack-view]")) return null;
826
828
  const turnId = turnIdOf(historyEl, source.root);
827
829
  if (!turnId) return null;
828
830
  const claim = { turnId, ...selectionClaim(source.root, range, claimOpts()) };
@@ -31,7 +31,7 @@ body.has-session #composer{flex-wrap:wrap;row-gap:6px}
31
31
  .revise-chip.refused{border-color:var(--warn-border);background:var(--warn-bg);color:var(--warn-text)}
32
32
  .revise-chip-text{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
33
33
  .revise-chip-clear{flex:none;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;min-height:0;padding:0;border:0;border-radius:999px;background:transparent;color:var(--text-muted);font-size:11px;cursor:pointer}
34
- .revise-chip-clear:hover{background:var(--bg-raised);color:var(--text-bright);filter:none}
34
+ .revise-chip-clear:hover{filter:none}@media(hover:hover){.revise-chip-clear:hover{background:var(--bg-raised);color:var(--text-bright)}}
35
35
  .chip{display:inline-flex;align-items:center;gap:6px;background:var(--accent-bg);border:1px solid var(--border-strong);border-radius:8px;padding:3px 4px 3px 3px;font-size:12px;max-width:220px}
36
36
  .chip img{width:32px;height:32px;object-fit:cover;border-radius:5px}
37
37
  .chip .chip-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
@@ -61,7 +61,7 @@ main{flex:1;display:flex;flex-direction:column;gap:16px;padding:16px;overflow:au
61
61
  /* Folded: the bubble hidden, an answer or a delegate report (#history's: outranks .bubble.user's display). */
62
62
  #history>.bubble.folded{display:none}
63
63
  .answer-fold{display:flex;align-items:baseline;gap:0;align-self:stretch;max-width:100%;min-width:0;margin:0;padding:12px 14px;font:inherit;font-size:13px;font-weight:600;line-height:1.5;color:var(--text-muted);text-align:left;cursor:pointer;user-select:none;background:var(--bg-panel);border:1px solid var(--border);border-left:3px solid var(--accent-strong);border-radius:12px}
64
- .answer-fold:hover .answer-fold-size{color:var(--text-2)}
64
+ @media(hover:hover){.answer-fold:hover .answer-fold-size{color:var(--text-2)}}
65
65
  .answer-fold:focus-visible{outline:2px solid var(--accent-ring);outline-offset:1px}
66
66
  .answer-fold::before{content:"▾\00a0";color:var(--accent);flex:none}
67
67
  .answer-fold.folded::before{content:"▸\00a0"}
@@ -92,7 +92,7 @@ main{flex:1;display:flex;flex-direction:column;gap:16px;padding:16px;overflow:au
92
92
  .revise-row.stacked{height:auto;margin-top:-6px;justify-content:flex-start}
93
93
  .revise-btn{min-height:0;height:22px;padding:0 8px;border-radius:6px;font-size:11px;line-height:20px;background:var(--bg-raised);border:1px solid var(--border-strong);color:var(--text-muted);cursor:pointer;opacity:0;transition:opacity .12s ease,color .12s ease}
94
94
  .revise-row:not(.stacked) .revise-btn{position:absolute;right:14px;top:-10px;z-index:1;height:20px;line-height:18px}
95
- .revise-btn:hover:not(:disabled){color:var(--text-bright);filter:none}
95
+ .revise-btn:hover:not(:disabled){filter:none}@media(hover:hover){.revise-btn:hover:not(:disabled){color:var(--text-bright)}}
96
96
  .revise-btn:disabled{cursor:default}
97
97
  .revise-btn.armed,.revise-btn.armed:hover:not(:disabled){opacity:1;color:var(--on-solid);background:var(--accent-strong);border-color:var(--accent-strong)}
98
98
  .bubble.output:hover+.revise-row .revise-btn,.revise-row:hover .revise-btn,.revise-row.stacked .revise-btn,.revise-btn:focus-visible{opacity:1}
@@ -110,7 +110,7 @@ main{flex:1;display:flex;flex-direction:column;gap:16px;padding:16px;overflow:au
110
110
  /* The ‹ N/M › switcher (revise_switch.js): an earlier version's answer read in the top one's place; its copy dashed, the top hidden. */
111
111
  .stack-switch{display:inline-flex;align-items:center;gap:2px;font-size:12px;color:var(--text-2);font-variant-numeric:tabular-nums}
112
112
  .stack-switch-btn{min-height:0;height:22px;min-width:24px;padding:0 6px;border-radius:6px;border:1px solid var(--border-strong);background:var(--bg-raised);color:var(--text-2);font:inherit;font-size:14px;line-height:20px;cursor:pointer}
113
- .stack-switch-btn:hover:not([aria-disabled="true"]){color:var(--text-bright);filter:none}
113
+ .stack-switch-btn:hover:not([aria-disabled="true"]){filter:none}@media(hover:hover){.stack-switch-btn:hover:not([aria-disabled="true"]){color:var(--text-bright)}}
114
114
  .stack-switch-btn:focus-visible{outline:2px solid var(--accent-ring);outline-offset:1px}
115
115
  .stack-switch-btn[aria-disabled="true"]{opacity:.4;cursor:default}
116
116
  .stack-switch-n{min-width:2.6em;text-align:center}
@@ -277,12 +277,12 @@ button.system-one-wrong,.system-one-wrong.marked{flex:none;padding:1px 6px;borde
277
277
  /* A reloaded row's ✂ mark (an LLM context edit on its output), one line above the output. */
278
278
  .activity-edit{flex:1 1 100%;min-width:0;margin:2px 0 0 var(--row-gutter);font-size:12px;color:var(--text-3);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:help}
279
279
  .activity-diff>summary{cursor:pointer;font-size:12px;color:var(--text-muted);width:max-content;font-variant-numeric:tabular-nums}
280
- .activity-diff>summary:hover{color:var(--text-2)}
280
+ @media(hover:hover){.activity-diff>summary:hover{color:var(--text-2)}}
281
281
  .activity-diff[open]>summary{margin-bottom:4px}
282
282
  /* A read of the file as-is: its numbered lines, closed under the preview (read_view.js); open, they stand for it. */
283
283
  .activity-read{flex:1 1 100%;min-width:0;margin:2px 0 2px var(--row-gutter)}
284
284
  .activity-read>summary{cursor:pointer;font-size:12px;color:var(--text-muted);width:max-content;font-variant-numeric:tabular-nums}
285
- .activity-read>summary:hover{color:var(--text-2)}
285
+ @media(hover:hover){.activity-read>summary:hover{color:var(--text-2)}}
286
286
  .activity-read[open]>summary{margin-bottom:4px}
287
287
  .activity-row:has(>.activity-read[open])>.activity-output{display:none}
288
288
  .read-lines{margin:0;padding:4px 0;background:var(--bg-inset);border:1px solid var(--border);border-radius:6px;font-size:12px;line-height:1.45;overflow:auto;max-height:420px}
@@ -305,7 +305,7 @@ button.system-one-wrong,.system-one-wrong.marked{flex:none;padding:1px 6px;borde
305
305
  .has-steps .activity-command-cwd{flex:1 1 auto;min-width:0;margin:0;overflow-wrap:anywhere}
306
306
  .activity-command-cwd>.activity-command-sep{font-family:inherit;color:var(--text-faint)}
307
307
  .activity-command-raw{flex:none;display:inline-flex;align-items:center;height:18px;padding:0 7px;border:1px solid var(--border-strong);border-radius:9px;font-size:11px;color:var(--text-muted);cursor:pointer;user-select:none;-webkit-user-select:none}
308
- .activity-command-raw:hover{color:var(--text-2)}
308
+ @media(hover:hover){.activity-command-raw:hover{color:var(--text-2)}}
309
309
  .activity-command-raw input{position:absolute;opacity:0;width:0;height:0;margin:0}
310
310
  .activity-command-raw:has(input:focus-visible){outline:2px solid var(--accent);outline-offset:1px}
311
311
  .activity-command-raw:has(input:checked){color:var(--accent);border-color:var(--accent-border);background:var(--accent-tint)}
@@ -618,7 +618,7 @@ button.system-one-wrong,.system-one-wrong.marked{flex:none;padding:1px 6px;borde
618
618
  .bubble.output,.bubble.user{position:relative}
619
619
  .copy-btn{position:absolute;top:6px;right:6px;z-index:1;display:inline-flex;align-items:center;justify-content:center;height:24px;min-width:24px;padding:0 5px;border-radius:6px;background:var(--bg-raised);border:1px solid var(--border-strong);color:var(--text-muted);font-size:11px;line-height:1;white-space:nowrap;user-select:none;-webkit-user-select:none;opacity:0;transition:opacity .12s ease,color .12s ease}
620
620
  .copy-btn svg{display:block}
621
- .copy-btn:hover:not(:disabled){filter:none;color:var(--text-bright)}
621
+ .copy-btn:hover:not(:disabled){filter:none}@media(hover:hover){.copy-btn:hover:not(:disabled){color:var(--text-bright)}}
622
622
  .bubble:hover>.copy-btn,.code-wrap:hover>.copy-btn,.copy-btn:focus-visible,.copy-btn[data-copied]{opacity:1}
623
623
  .copy-btn[data-copied],.copy-btn[data-copied]:hover:not(:disabled){color:var(--ok-text)}
624
624
  .copy-btn[data-copied] svg{display:none}
@@ -847,8 +847,9 @@ body.stage-view .turn-stage{position:absolute;left:0;right:0;bottom:100%;margin-
847
847
  .ts-extras>.bubble.user>.copy-btn{display:none}
848
848
  .ts-extras>.bubble.user .user-message{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;line-clamp:2;overflow:hidden;white-space:normal}
849
849
  /* A line's markdown (a delegate report's) reads as a plain row in the clamped rows: its blocks run inline at the
850
- row's own size, a space between them, rules and copy buttons gone. The prompt line shown whole keeps it. */
851
- :is(.ts-extras>.bubble.user,.ts-prompt:not(.full)>.bubble.user)>.user-message.markdown :is(p,h1,h2,h3,h4,h5,h6,ul,ol,li,blockquote,pre,table,thead,tbody,tr,th,td,.code-wrap){display:inline;margin:0;padding:0;border:0;border-radius:0;background:transparent;font-size:inherit;font-weight:inherit;line-height:inherit;color:inherit;white-space:normal}
850
+ row's own size, font and baseline (a pre's monospace or a cell's middle alignment would make the line box taller), a
851
+ space between them, rules and copy buttons gone. The prompt line shown whole keeps it. */
852
+ :is(.ts-extras>.bubble.user,.ts-prompt:not(.full)>.bubble.user)>.user-message.markdown :is(p,h1,h2,h3,h4,h5,h6,ul,ol,li,blockquote,pre,table,thead,tbody,tr,th,td,.code-wrap){display:inline;margin:0;padding:0;border:0;border-radius:0;background:transparent;font-family:inherit;font-size:inherit;font-weight:inherit;line-height:inherit;color:inherit;white-space:normal;vertical-align:baseline}
852
853
  :is(.ts-extras>.bubble.user,.ts-prompt:not(.full)>.bubble.user)>.user-message.markdown :is(p,h1,h2,h3,h4,h5,h6,li,blockquote,pre,td,th)::after{content:" "}
853
854
  :is(.ts-extras>.bubble.user,.ts-prompt:not(.full)>.bubble.user)>.user-message.markdown :is(hr,img,.copy-btn){display:none}
854
855
  /* Inside the dock's own blur a second backdrop-filter sees nothing: the cards are opaque here (as #commandList is). */
@@ -200,7 +200,16 @@ export function createNotifications({
200
200
  button.hidden = state === "unsupported";
201
201
  button.dataset.state = state;
202
202
  button.title = (push ? PUSH_TITLES : NOTIFY_TITLES)[state] || "";
203
- button.setAttribute("aria-pressed", state === "on" ? "true" : "false");
203
+ // In a tab the bell is a toggle (aria-pressed); in the app it opens the
204
+ // notifications sheet, whose shell (chip_popover.js) keeps its
205
+ // aria-expanded, as every popover opener's: one state, never both.
206
+ if (push) {
207
+ button.removeAttribute("aria-pressed");
208
+ button.setAttribute("aria-haspopup", "dialog");
209
+ if (!button.hasAttribute("aria-expanded")) button.setAttribute("aria-expanded", "false");
210
+ } else {
211
+ button.setAttribute("aria-pressed", state === "on" ? "true" : "false");
212
+ }
204
213
  }
205
214
 
206
215
  async function toggleNotify() {
@@ -94,9 +94,10 @@ export function stubText({ version, label = "", lines = 0, top }) {
94
94
  return `v${version}${said}${size} — superseded by v${top}`;
95
95
  }
96
96
 
97
- // The version chip's words: "v3 · 2 earlier".
98
- export function versionChipText(count) {
99
- return `v${count} · ${count - 1} earlier`;
97
+ // The version chip's words for version +at+ (0-based) on view of +count+:
98
+ // the newest, "v3 · 2 earlier"; an earlier one the switcher shows, "v1 of 3".
99
+ export function versionChipText(count, at = count - 1) {
100
+ return at >= count - 1 ? `v${count} · ${count - 1} earlier` : `v${at + 1} of ${count}`;
100
101
  }
101
102
 
102
103
  // The composer's chip: "Revising: ‹label›", or the refusal (+unavailable+:
@@ -236,12 +237,12 @@ export function installReviseStacks({
236
237
  function drawRow(row, { id, answer, chain, openings }) {
237
238
  const off = unavailable();
238
239
  const isArmed = armed() === id;
240
+ const at = chain ? (shown.get(id) ?? chain.length - 1) : 0;
239
241
  const versions = chain
240
- ? html`<details class="stack-versions"><summary>${versionChipText(chain.length)}</summary><div class="stack-versions-list" role="list">${chain.map((vid, k) => html`<button type="button" role="listitem" class=${vid === id ? "stack-version current" : "stack-version"} data-stack-pick=${vid} ?disabled=${vid === id}><span class="stack-version-n">v${k + 1}</span> ${promptLabel(openings.get(vid))}</button>`)}</div></details>`
242
+ ? html`<details class="stack-versions"><summary>${versionChipText(chain.length, at)}</summary><div class="stack-versions-list" role="list">${chain.map((vid, k) => html`<button type="button" role="listitem" class=${vid === id ? "stack-version current" : "stack-version"} data-stack-pick=${vid} ?disabled=${vid === id}><span class="stack-version-n">v${k + 1}</span> ${promptLabel(openings.get(vid))}</button>`)}</div></details>`
241
243
  : nothing;
242
244
  const button = html`<button type="button" class=${isArmed ? "revise-btn armed" : "revise-btn"} data-revise=${id} ?disabled=${off} title=${off ? REVISE_UNAVAILABLE : "Rewrite this answer: your next message revises it, and the earlier version folds away"}>${isArmed ? "Revising…" : "Revise"}</button>`;
243
245
  row.classList.toggle("stacked", !!chain);
244
- const at = chain ? (shown.get(id) ?? chain.length - 1) : 0;
245
246
  render(html`${chain ? switcherTemplate(id, at, chain.length) : nothing}${versions}${button}`, row);
246
247
  rowAnswer.set(row, answer);
247
248
  }
@@ -23,12 +23,12 @@ export function stopTarget(row, features) {
23
23
  // A task_wait row's title without its wait ("npm test · up to 600s").
24
24
  const WAIT_SUFFIX = / · up to \d+s$/;
25
25
 
26
- // The first line of an execute that was still running at its limit and
27
- // went on as a task (Tools::Execute::HANDED_OVER), then its task_id line.
26
+ // The first line of an execute that was still running at its limit (or when
27
+ // a message from the user waited: "4s mark") and went on as a task (Tools::Execute::HANDED_OVER), then its task_id line.
28
28
  // Anchored at the start, an optional "ran as: …" line and "[execute]" lead
29
29
  // before it: a "task_id:" line anywhere else is the command's own output.
30
30
  // The twin of TaskRuntime.handed_over_id.
31
- const HANDED_OVER = /^(?:ran as: [^\n]*\n)?(?:\[execute\]\n)?Still running at the \d+s limit:[^\n]*\ntask_id: (\S+)/;
31
+ const HANDED_OVER = /^(?:ran as: [^\n]*\n)?(?:\[execute\]\n)?Still running at the \d+s (?:limit|mark):[^\n]*\ntask_id: (\S+)/;
32
32
 
33
33
  // The task id an execute row's output hands over, else null.
34
34
  export function handedOverId(output) {
@@ -15,6 +15,7 @@ export function mergeVersionState(current = {}, frame = {}) {
15
15
  if (has(frame, "installed")) next.installed = known(frame.installed) ? frame.installed : null;
16
16
  if (has(frame, "available")) next.available = known(frame.available) ? frame.available : null;
17
17
  if (has(frame, "update_blocked")) next.updateBlocked = known(frame.update_blocked) ? frame.update_blocked : null;
18
+ if (has(frame, "auto")) next.auto = frame.auto === "install" ? "install" : "off";
18
19
  return next;
19
20
  }
20
21
 
@@ -46,11 +47,13 @@ export function newerVersion(a, b) {
46
47
  // - loaded ≠ served: chi web restarted on another version; reload the page;
47
48
  // - installed newer than served: chi web runs an older chi than installed;
48
49
  // restart its workers or chi web;
49
- // - available newer than served: install it, unless the install is blocked.
50
+ // - available newer than served: install it, unless the install is blocked;
51
+ // with update.auto: install (and not blocked) chi web installs it by itself
52
+ // once no turn runs: the notice says so, with no Update button.
50
53
  // Each has a key; one in +shown+ (a Set: what this tab already showed, as
51
54
  // every reconnect's snapshot says it again) is not shown twice.
52
55
  // @return {{key, text, reload: boolean} | null}
53
- export function versionNotice({ loaded, served, installed, available, updateBlocked, shown = new Set() } = {}) {
56
+ export function versionNotice({ loaded, served, installed, available, updateBlocked, auto, shown = new Set() } = {}) {
54
57
  let notice = null;
55
58
  if (known(loaded) && known(served) && loaded !== served) {
56
59
  notice = { key: `reload:${served}`, text: `chi was updated to ${served}`, reload: true };
@@ -68,13 +71,16 @@ export function versionNotice({ loaded, served, installed, available, updateBloc
68
71
  gem_dir_not_writable: ["the RubyGems directory is not writable", `gem install samagotchi -v ${available}`],
69
72
  };
70
73
  const blocked = commands[updateBlocked];
74
+ const automatic = auto === "install" && !blocked;
71
75
  const command = blocked?.[1] || "chi update";
72
76
  notice = {
73
77
  key: `available:${available}`,
74
78
  text: blocked
75
79
  ? `chi ${available} is available (you run ${served}); ${blocked[0]}. Run ${command}.`
76
- : `chi ${available} is available (you run ${served}).`,
77
- ...(blocked ? { command } : { updateVersion: available }),
80
+ : automatic
81
+ ? `chi ${available} is available (you run ${served}); it installs by itself once no turn is running.`
82
+ : `chi ${available} is available (you run ${served}).`,
83
+ ...(blocked ? { command } : automatic ? {} : { updateVersion: available }),
78
84
  releaseUrl: `https://rubygems.org/gems/samagotchi/versions/${encodeURIComponent(available)}`,
79
85
  reload: false,
80
86
  };
@@ -25,8 +25,9 @@ function workerRow(row) {
25
25
  }
26
26
 
27
27
  function operationTitle(model) {
28
- if (model.operation === "install") return `Update chi${model.version ? ` to ${model.version}` : ""}`;
29
- if (model.operation === "workers") return "Restart workers";
28
+ const automatic = model.auto ? " (automatic)" : "";
29
+ if (model.operation === "install") return `Update chi${model.version ? ` to ${model.version}` : ""}${automatic}`;
30
+ if (model.operation === "workers") return `Restart workers${automatic}`;
30
31
  return "Restart chi web";
31
32
  }
32
33
 
@@ -48,6 +48,46 @@ module Samagotchi
48
48
  EVENT_TTL = 600
49
49
  # A newly available chi is useful for a day while the phone is away.
50
50
  UPDATE_TTL = 24 * 3600
51
+ # The kinds of AutoUpdate's notices: [key kind, title, body] from the version and the notice's notes.
52
+ AUTO_NOTICES = {
53
+ "installed" => lambda do |version, notes|
54
+ ["installed", "chi #{version} is installed",
55
+ "chi web and its sessions switch over when you restart them.#{kept_words(notes[:kept])}"]
56
+ end,
57
+ "updated" => lambda do |version, notes|
58
+ ["updated", "chi updated to #{version}", "#{restarted_words(notes[:restarted], notes[:left])}#{kept_words(notes[:kept])}"]
59
+ end,
60
+ "restart_failed" => lambda do |version, notes|
61
+ ["restart_failed", "chi #{version} is installed; chi web didn't restart",
62
+ "#{notes[:detail] || "chi web didn't restart"}. Restart chi web in its terminal."]
63
+ end,
64
+ "failed" => lambda do |version, notes|
65
+ ["update_failed", notes[:installed] ? "chi #{version} installed with a problem" : "chi #{version} didn't install",
66
+ "#{notes[:detail] || "chi update failed"}. Open chi web for details."]
67
+ end
68
+ }.freeze
69
+
70
+ # "chi web and 3 sessions restarted; 1 restarts when idle."
71
+ def self.restarted_words(restarted, left)
72
+ sessions = restarted.to_i
73
+ words = if sessions.positive?
74
+ "chi web and #{sessions} #{sessions == 1 ? "session" : "sessions"} restarted"
75
+ else
76
+ "chi web restarted"
77
+ end
78
+ words += "; #{left} #{left == 1 ? "restarts" : "restart"} when idle" if left.to_i.positive?
79
+ "#{words}."
80
+ end
81
+
82
+ # " Kept your edits in 2 files." ("" for none).
83
+ def self.kept_words(count)
84
+ if count.to_i.positive?
85
+ " Kept your edits in #{count} #{count == 1 ? "file" : "files"}."
86
+ else
87
+ ""
88
+ end
89
+ end
90
+
51
91
  # A show carries +open+ only while its JSON stays this small: one
52
92
  # aes128gcm record leaves 3993 bytes of plaintext under Web Push's
53
93
  # 4096 (86 header, 1 delimiter, 16 tag). Longer, it goes without
@@ -191,19 +231,40 @@ module Samagotchi
191
231
  @queue << Close.new(keys: keys) unless keys.empty?
192
232
  when "chi"
193
233
  notice_update(event)
234
+ when "chi_notice"
235
+ notice_auto_update(event)
194
236
  end
195
237
  end
196
238
 
197
239
  def notice_update(event)
198
240
  return unless event.data[:update_notice]
241
+ # With update.auto: install (and an install that can run) the page says it will install on its own,
242
+ # and the result is what the phone hears: no "available" first.
243
+ return if event.data[:auto] == "install" && !event.data[:update_blocked]
199
244
 
200
245
  version = event.data[:available]
201
- return unless version.is_a?(String) && !version.empty? && !@updates_seen[version]
246
+ return unless version.is_a?(String) && !version.empty?
247
+
248
+ enqueue_update("chi:update:#{version}", "chi #{version} is available", update_body(event.data[:update_blocked]))
249
+ end
250
+
251
+ # AutoUpdate's word (SessionHub#publish_notice): installed, updated, restart_failed or failed.
252
+ def notice_auto_update(event)
253
+ data = event.data
254
+ version = data[:version]
255
+ return unless version.is_a?(String) && !version.empty?
256
+
257
+ kind, title, body = AUTO_NOTICES.fetch(data[:kind], nil)&.call(version, data)
258
+ enqueue_update("chi:#{kind}:#{version}", title, body) if kind
259
+ end
260
+
261
+ # Once per key in this process (AutoUpdate keeps its own record across restarts).
262
+ def enqueue_update(key, title, body)
263
+ return if @updates_seen[key]
202
264
 
203
- @updates_seen[version] = true
204
- attention = Attention::Event.new(reason: "update", session_id: nil, key: "chi:update:#{version}", hold: nil)
205
- @queue << Show.new(attention: attention, title: "chi #{version} is available",
206
- body: update_body(event.data[:update_blocked]), at: @now.call, url: "/")
265
+ @updates_seen[key] = true
266
+ attention = Attention::Event.new(reason: "update", session_id: nil, key: key, hold: nil)
267
+ @queue << Show.new(attention: attention, title: title, body: body, at: @now.call, url: "/")
207
268
  end
208
269
 
209
270
  # A blocked install (a checkout, Bundler, an unwritable gem dir) names its own command on the page.