samagotchi 0.175.0 → 0.177.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 (71) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +50 -1
  3. data/bin/chi +1 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/cli.md +11 -4
  6. data/docs/configuration.md +1 -0
  7. data/docs/internals/bridge.md +2 -2
  8. data/docs/internals/engine.md +2 -2
  9. data/docs/internals/participants.md +13 -6
  10. data/docs/internals/prompt-caching.md +3 -0
  11. data/docs/internals/web-frontend.md +38 -11
  12. data/docs/internals/working-set.md +77 -6
  13. data/docs/sessions.md +3 -2
  14. data/lib/samagotchi/bridge.rb +11 -4
  15. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  16. data/lib/samagotchi/config.rb +3 -0
  17. data/lib/samagotchi/engine/models.rb +11 -0
  18. data/lib/samagotchi/engine/session.rb +9 -0
  19. data/lib/samagotchi/engine.rb +1 -0
  20. data/lib/samagotchi/engine_snapshots.rb +3 -0
  21. data/lib/samagotchi/participant_uploads.rb +14 -1
  22. data/lib/samagotchi/prompt_part.rb +66 -0
  23. data/lib/samagotchi/session.rb +10 -1
  24. data/lib/samagotchi/system_prompt.rb +191 -12
  25. data/lib/samagotchi/version.rb +1 -1
  26. data/lib/samagotchi/web/app.rb +15 -2
  27. data/lib/samagotchi/web/participant_images.rb +16 -12
  28. data/lib/samagotchi/web/participant_show.rb +1 -1
  29. data/lib/samagotchi/web/participant_view.rb +27 -1
  30. data/lib/samagotchi/web/public/app.js +7 -2
  31. data/lib/samagotchi/web/public/composer_fold.js +3 -1
  32. data/lib/samagotchi/web/public/composer_grip.js +18 -10
  33. data/lib/samagotchi/web/public/composer_mount.js +17 -6
  34. data/lib/samagotchi/web/public/ctx_tokens.js +33 -0
  35. data/lib/samagotchi/web/public/index.html +43 -9
  36. data/lib/samagotchi/web/public/restore.js +3 -1
  37. data/lib/samagotchi/web/public/session_fields.js +10 -4
  38. data/lib/samagotchi/web/public/session_prefs.js +92 -0
  39. data/lib/samagotchi/web/public/session_state.js +14 -1
  40. data/lib/samagotchi/web/public/session_store.js +1 -1
  41. data/lib/samagotchi/web/public/session_sync.js +3 -0
  42. data/lib/samagotchi/web/public/session_view.js +33 -3
  43. data/lib/samagotchi/web/public/stage_asking.js +20 -11
  44. data/lib/samagotchi/web/public/stage_cloud.js +3 -2
  45. data/lib/samagotchi/web/public/stage_missing.js +3 -5
  46. data/lib/samagotchi/web/public/stage_model.js +2 -1
  47. data/lib/samagotchi/web/public/stage_view.js +6 -1
  48. data/lib/samagotchi/web/public/stage_view_memory.js +76 -0
  49. data/lib/samagotchi/web/public/stream_handlers.js +10 -5
  50. data/lib/samagotchi/web/public/tokens.css +2 -2
  51. data/lib/samagotchi/web/public/turn_events.js +1 -1
  52. data/lib/samagotchi/web/public/working_set.js +51 -7
  53. data/lib/samagotchi/web/public/working_set_rail.js +22 -7
  54. data/lib/samagotchi/web/public/working_set_view.js +188 -58
  55. data/lib/samagotchi/web/public/ws_reader.js +2 -0
  56. data/lib/samagotchi/web/public/ws_sections.js +251 -0
  57. data/lib/samagotchi/web/server.rb +6 -2
  58. data/lib/samagotchi/web/session_show.rb +13 -2
  59. data/lib/samagotchi/worker/child_side.rb +123 -0
  60. data/lib/samagotchi/worker/command_queue.rb +350 -0
  61. data/lib/samagotchi/worker/leave.rb +286 -0
  62. data/lib/samagotchi/worker/scratch.rb +99 -0
  63. data/lib/samagotchi/worker/signal_grace.rb +96 -0
  64. data/lib/samagotchi/worker/startup.rb +92 -0
  65. data/lib/samagotchi/worker/wake_turns.rb +190 -0
  66. data/lib/samagotchi/worker.rb +25 -1065
  67. data/lib/samagotchi/worker_exit_claim.rb +12 -0
  68. data/lib/samagotchi/working_set.rb +32 -4
  69. data/lib/samagotchi/working_set_command.rb +3 -2
  70. data/lib/samagotchi/working_set_steer.rb +21 -3
  71. metadata +13 -1
@@ -16,6 +16,8 @@ require_relative "memory_bundle/index_size"
16
16
  require_relative "thinking"
17
17
  require_relative "prompt_files"
18
18
  require_relative "plugin/prompt_sections"
19
+ require_relative "prompt_part"
20
+ require "json"
19
21
 
20
22
  module Samagotchi
21
23
  # The system prompt an Engine gives its model: the base prompt (tool
@@ -95,7 +97,21 @@ module Samagotchi
95
97
  # plugins' sections it holds, its stable part's length (chat) and the
96
98
  # Tools::ToolSurface it declares (the tools, the not-loaded line, the
97
99
  # kit's prompt text).
98
- Built = Data.define(:prompt, :memory_index, :notes, :files, :sections, :stable_length, :surface)
100
+ #
101
+ # parts: the Sections the prompt is joined from (stable ones, then the
102
+ # volatile ones), in prompt order; Gemma's tail declarations are not one.
103
+ # prompt_parts: the same as sizes, one PromptPart per memory, file and
104
+ # plugin section, the tools part first (#prompt_parts).
105
+ Built = Data.define(:prompt, :memory_index, :notes, :files, :sections, :stable_length, :surface, :memory_names, :parts,
106
+ :prompt_parts)
107
+
108
+ # One part of the prompt: its kind (KINDS), what it was made from (the
109
+ # memory names of identity and preloads, the files of agents and
110
+ # appended, the notes of notes, the plugins' Built of plugins; nil
111
+ # elsewhere) and its text, as the prompt holds it.
112
+ Section = Data.define(:kind, :ref, :text)
113
+
114
+ KINDS = %i[base identity notes preloads agents appended kit plugins indexes participants model location session].freeze
99
115
 
100
116
  # The full prompt: #base wrapped with the index and the rest. Built once
101
117
  # per loop and level (until #reset!) so the prompt prefix, and the
@@ -120,6 +136,7 @@ module Samagotchi
120
136
  built = cache[key] || (cache[key] = build_prompt(chat: chat, thinking: thinking, layers: layers))
121
137
  @memory_index = built.memory_index
122
138
  @last = built
139
+ @last_prompt_memory_names = built.memory_names
123
140
  built.prompt
124
141
  end
125
142
 
@@ -137,6 +154,19 @@ module Samagotchi
137
154
  # @return [Array<ModelNotes::Note>, nil]
138
155
  def prompt_notes = @last&.notes
139
156
 
157
+ # The sizes of the parts the prompt #build returned last is made of
158
+ # (PromptPart: the tools first, then each memory, file and plugin
159
+ # section in prompt order; chars at TokenUsage's one ratio). Worked out
160
+ # once with the prompt, kept with it. [] before a build and after
161
+ # #reset!.
162
+ # @return [Array<PromptPart>]
163
+ def prompt_parts = @last&.prompt_parts || []
164
+
165
+ # The identity and preloaded memories the last prompt build actually
166
+ # rendered; retained across reset! until another build completes.
167
+ # @return [Array<String>]
168
+ def prompt_memory_names = @last_prompt_memory_names || []
169
+
140
170
  # The files whose text the prompt #build returned last holds, as
141
171
  # absolute paths in prompt order: the AGENTS.md chain, then the
142
172
  # appended files (append_system_prompt:, --append-system-prompt). [] before a
@@ -192,16 +222,108 @@ module Samagotchi
192
222
  # @section_* and @measured_* scratch is this build's (the turn thread's)
193
223
  # alone: #reset! never touches it.
194
224
  def build_prompt(chat:, thinking:, layers:)
225
+ @section_identity_memory_name = nil
226
+ @section_activated_memory_names = []
195
227
  @section_notes = nil
196
228
  @section_files = []
197
229
  @section_plugins = []
198
230
  @measured_stable_length = nil
231
+ @section_parts = []
232
+ @section_file_chars = []
233
+ @section_item_chars = {}
234
+ @section_preload_chars = []
235
+ @section_preload_scopes = []
236
+ @section_index_chars = {}
199
237
  surface = tool_surface(layers)
200
238
  prompt = system_prompt_with_index(assist_system_prompt(chat: chat, surface: surface),
201
239
  chat: chat, thinking: thinking, surface: surface)
240
+ prompt_parts = Degrade.call(:prompt, "prompt_parts_failed", fallback: []) do
241
+ prompt_parts_for(@section_parts, chat: chat, surface: surface)
242
+ end
202
243
  Built.new(prompt: prompt, memory_index: @measured_index, notes: @section_notes || [],
203
244
  files: @section_files.freeze, sections: @section_plugins.freeze, stable_length: @measured_stable_length,
204
- surface: surface)
245
+ surface: surface, memory_names: [@section_identity_memory_name, *@section_activated_memory_names].compact.uniq.freeze,
246
+ parts: @section_parts.freeze, prompt_parts: prompt_parts.freeze)
247
+ end
248
+
249
+ # ── The parts' sizes ───────────────────────────────────────────────────────
250
+
251
+ LABELS = { base: "base prompt", kit: "toolkit prompt", participants: "participants", model: "model",
252
+ location: "location", session: "session" }.freeze
253
+
254
+ # The PromptParts of +sections+ (a build's), the tools part first. A
255
+ # multi-item section is one part per item; its headings and joins go
256
+ # into its first part, so the parts sum to the section's text.
257
+ def prompt_parts_for(sections, chat:, surface:)
258
+ tools_chars = tools_chars(chat: chat, surface: surface)
259
+ parts = sections.flat_map { |part| section_parts(part) }
260
+ if tools_chars[:from_base]
261
+ base = parts.index { |part| part.kind == "base" }
262
+ parts[base] = PromptPart.build(kind: :base, label: parts[base].label, chars: parts[base].chars - tools_chars[:chars]) if base
263
+ end
264
+ [PromptPart.build(kind: :tools, label: "#{surface.declared_names.size} declared", chars: tools_chars[:chars]), *parts]
265
+ end
266
+
267
+ # The tool declarations' size, once. chat: the schemas as the request's
268
+ # tools field sends them. Native: the declarations text, inside the base
269
+ # prompt (from_base: its chars move out of the base part) or, on Gemma,
270
+ # after the last section (nothing to move).
271
+ def tools_chars(chat:, surface:)
272
+ return { chars: JSON.generate(surface.schemas).length, from_base: false } if chat
273
+
274
+ { chars: tool_declarations(surface).length, from_base: !gemma_tail_declarations? }
275
+ end
276
+
277
+ def section_parts(section)
278
+ items = section_items(section)
279
+ return [PromptPart.build(kind: section.kind, label: LABELS.fetch(section.kind, section.kind), chars: section.text.length)] if items.nil?
280
+
281
+ # The first item's own chars are the rest of the text.
282
+ rest = items.drop(1).sum { |item| item[2] }
283
+ items.each_with_index.map do |(label, ref, chars, scope), index|
284
+ PromptPart.build(kind: section.kind, label: label, ref: ref, scope: scope,
285
+ chars: index.zero? ? section.text.length - rest : chars)
286
+ end
287
+ end
288
+
289
+ # [label, ref, own chars, scope] per item of a section made of several
290
+ # (scope: a memory part's, else nil), nil for a section that is one part.
291
+ def section_items(section)
292
+ case section.kind
293
+ when :identity then [[section.ref.to_s, section.ref, section.text.length, "system"]] if section.ref
294
+ when :notes
295
+ # In the text's order: it groups the notes by scope.
296
+ Array(section.ref).group_by(&:scope).values.flatten(1).map do |note|
297
+ [note.name, note.name, "## #{note.name}\n#{note.body}".length, note.scope]
298
+ end
299
+ when :preloads
300
+ scopes = @section_preload_scopes
301
+ item_list(Array(section.ref), @section_preload_chars) { |name| [name, name] }
302
+ &.each_with_index&.map { |item, index| [*item, scopes&.[](index)] }
303
+ when :agents, :appended
304
+ top = MemoryPaths.work_tree_root(Dir.pwd)
305
+ item_list(Array(section.ref), @section_item_chars[section.kind]) { |path| [file_label(path, top), path] }
306
+ when :plugins
307
+ Array(section.ref).map { |built| ["#{built.bundle}: #{built.name}", "#{built.bundle}/#{built.name}", built.prompt_text.length] }
308
+ when :indexes
309
+ [["project memory index", "project", @section_index_chars[:project]], ["system memory index", "system", @section_index_chars[:system]]]
310
+ end&.then { |items| items.empty? ? nil : items }
311
+ end
312
+
313
+ # A file part's label: its path under the work tree +top+ (AGENTS.md,
314
+ # docs/rules.md), else with ~ for the home directory.
315
+ def file_label(path, top)
316
+ return Paths.tilde(path) unless top && path.start_with?("#{top}/")
317
+
318
+ path.delete_prefix("#{top}/")
319
+ end
320
+
321
+ # [label, ref, chars] per ref (+yield+ gives label and ref), nil when
322
+ # the recorded chars don't line up with the refs.
323
+ def item_list(refs, chars)
324
+ return nil unless chars && chars.size == refs.size
325
+
326
+ refs.each_with_index.map { |ref, index| [*yield(ref), chars[index]] }
205
327
  end
206
328
 
207
329
  # The session's tools as a build under +layers+ declares them, read
@@ -348,21 +470,59 @@ module Samagotchi
348
470
  thinking_token = chat ? "" : Thinking.native(thinking || turn_thinking, profile).system_token
349
471
  indexes = { project: read_memory_index("project"), system: read_memory_index("system") }
350
472
  @measured_index = measure_indexes(indexes)
351
- memory_sections = [
352
- "Project memories:\n#{indexes[:project]}",
353
- "System memories:\n#{indexes[:system]}"
354
- ].join("\n\n")
355
- stable = [thinking_token + base, not_loaded_line(surface), rg_guidance, system_identity_section, model_notes_section, explicit_memory_section,
356
- project_specific_description, appended_section, kit_prompt_section(surface), plugin_prompt_section, memory_sections]
357
- stable_text = stable.compact.join("\n")
358
- volatile = [participants_section, current_model, project_location, current_session].compact
473
+ memory_sections = %i[project system].map { |scope| memory_sections_head(indexes, scope) }.join("\n\n")
474
+ # Built eagerly and in this order: the builders set the @section_* scratch.
475
+ base_text = [thinking_token + base, not_loaded_line(surface), rg_guidance].compact.join("\n")
476
+ @section_index_chars = { project: memory_sections_head(indexes, :project).length,
477
+ system: memory_sections_head(indexes, :system).length }
478
+ stable = [
479
+ Section.new(kind: :base, ref: nil, text: base_text),
480
+ section(:identity, -> { @section_identity_memory_name }) { system_identity_section },
481
+ section(:notes, -> { @section_notes }) { model_notes_section },
482
+ section(:preloads, -> { Array(@section_activated_memory_names).dup }) { explicit_memory_section },
483
+ files_section(:agents) { project_specific_description },
484
+ files_section(:appended) { appended_section },
485
+ section(:kit, nil) { kit_prompt_section(surface) },
486
+ section(:plugins, -> { @section_plugins }) { plugin_prompt_section },
487
+ Section.new(kind: :indexes, ref: %i[project system], text: memory_sections)
488
+ ].compact
489
+ stable_text = stable.map(&:text).join("\n")
490
+ volatile = [section(:participants, nil) { participants_section }, section(:model, nil) { current_model },
491
+ section(:location, nil) { project_location }, section(:session, nil) { current_session }].compact
492
+ @section_parts = stable + volatile
359
493
  return with_tail_declarations(stable_text, chat: chat, surface: surface) if volatile.empty?
360
494
 
361
- prompt = "#{stable_text}\n#{volatile.join("\n")}"
495
+ prompt = "#{stable_text}\n#{volatile.map(&:text).join("\n")}"
362
496
  @measured_stable_length = stable_text.length + 1 if chat
363
497
  with_tail_declarations(prompt, chat: chat, surface: surface)
364
498
  end
365
499
 
500
+ # One scope's block of the indexes section.
501
+ def memory_sections_head(indexes, scope)
502
+ "#{scope.to_s.capitalize} memories:\n#{indexes[scope]}"
503
+ end
504
+
505
+ # A Section of +kind+ with what the block (a builder) returns, nil when
506
+ # that is nil (never when it is empty: an "" part stays in the prompt).
507
+ # +ref+ is read after the block ran, so it may name what the builder set.
508
+ def section(kind, ref = nil, &)
509
+ text = yield
510
+ if text.nil?
511
+ nil
512
+ else
513
+ Section.new(kind: kind, ref: ref.respond_to?(:call) ? ref.call : ref, text: text)
514
+ end
515
+ end
516
+
517
+ # A Section whose ref is the files its builder added to @section_files.
518
+ def files_section(kind, &block)
519
+ before = @section_files&.size || 0
520
+ section(kind, nil, &block)&.then do |part|
521
+ @section_item_chars[kind] = Array(@section_file_chars)[before..].dup if @section_item_chars
522
+ part.with(ref: Array(@section_files)[before..].dup)
523
+ end
524
+ end
525
+
366
526
  # The tools the session's toolkit leaves out, named once right after the
367
527
  # base prompt: sessions on another toolkit already differ at the tools,
368
528
  # and nothing later (a memory write) moves it. nil when none are (full):
@@ -432,6 +592,7 @@ module Samagotchi
432
592
  next if body.start_with?("Error:")
433
593
  next if body.strip.empty?
434
594
 
595
+ @section_identity_memory_name = name
435
596
  return "System identity (auto-loaded, scope=system):\n#{body}"
436
597
  end
437
598
  nil
@@ -546,7 +707,11 @@ module Samagotchi
546
707
  # status line. The memory-body injection itself stays here — the
547
708
  # SystemPrompt is the single source of truth for the system prompt.
548
709
  @activated_memory_names << actual_name
549
- entries << "this memory is required by the user in the current context: memory name: #{actual_name}\n#{body}"
710
+ @section_activated_memory_names << actual_name
711
+ entry = "this memory is required by the user in the current context: memory name: #{actual_name}\n#{body}"
712
+ @section_preload_chars&.push(entry.length)
713
+ @section_preload_scopes&.push(scope || answered_scope(body, actual_name))
714
+ entries << entry
550
715
  end
551
716
  end
552
717
 
@@ -555,6 +720,18 @@ module Samagotchi
555
720
  entries.join("\n\n")
556
721
  end
557
722
 
723
+ # The scope whose file answered a bare preload's read (memory_read
724
+ # falls back project -> system): its file under the project's memories
725
+ # is the project's, else the system's. nil without the read's record (a
726
+ # plain String body).
727
+ def answered_scope(body, name)
728
+ read = body.respond_to?(:reads) ? body.reads[name] : nil
729
+ return nil unless read.is_a?(Hash)
730
+
731
+ dir = read[:project_dir]
732
+ dir && read[:path].to_s.start_with?("#{dir}/") ? "project" : "system"
733
+ end
734
+
558
735
  def split_memory_scope(raw)
559
736
  value = raw.to_s.strip
560
737
  if value.include?("/")
@@ -577,6 +754,7 @@ module Samagotchi
577
754
  return nil if sections.empty?
578
755
 
579
756
  @section_files&.concat(sections.map(&:path))
757
+ @section_file_chars&.concat(sections.map { |section| section.text.length })
580
758
  sections.map(&:text).join("\n\n")
581
759
  end
582
760
  end
@@ -603,6 +781,7 @@ module Samagotchi
603
781
  next unless text
604
782
 
605
783
  @section_files&.push(path)
784
+ @section_file_chars&.push(text.length)
606
785
  sections << text
607
786
  end
608
787
  sections.empty? ? nil : sections.join("\n\n")
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.175.0"
4
+ VERSION = "0.177.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -160,6 +160,9 @@ module Samagotchi
160
160
  # freshly-spawned worker's bridge before answering POST /api/sessions.
161
161
  # @param working_set [Boolean] the stage view's working set
162
162
  # (web.working_set); ?working_set=1|0 overrides it for one page load
163
+ # @param stage_collapsed [Boolean] every session's stage starts folded
164
+ # to its status row (web.stage_collapsed: the page's default; a
165
+ # session folded by hand keeps its own, session_prefs.js)
163
166
  # @param reload_check [Boolean] the page checks each finished turn
164
167
  # against a reload of it and posts the counts (web.reload_check,
165
168
  # opt-in; POST /api/sessions/:id/reload_check logs them)
@@ -202,6 +205,7 @@ module Samagotchi
202
205
  registry: nil, models_wait_timeout: MODELS_WAIT_TIMEOUT, lan: nil,
203
206
  working_set: Config::BY_KEY["web.working_set"].default, wait_poll_interval: ReplyWait::POLL_INTERVAL,
204
207
  reload_check: Config::BY_KEY["web.reload_check"].default,
208
+ stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
205
209
  grants: nil, public_url: nil, public_token: nil, push: nil, start_dir: nil, update_runner: nil,
206
210
  update_blocked: nil, update_ops: nil)
207
211
  @start_dir = start_dir
@@ -218,6 +222,7 @@ module Samagotchi
218
222
  @markdown_renderer = MarkdownRenderer.new(enabled: markdown)
219
223
  @working_set = working_set
220
224
  @reload_check = reload_check
225
+ @stage_collapsed = stage_collapsed
221
226
  @reload_checks = ReloadCheckRoute::Seen.new
222
227
  @annotate_presets = annotate_presets.is_a?(Array) ? annotate_presets.join("|") : annotate_presets.to_s
223
228
  @editor_url = Editor.template(editor)
@@ -1925,6 +1930,7 @@ module Samagotchi
1925
1930
  attrs["working-set"] = "1" if working_set?(req.GET["working_set"])
1926
1931
  # The opt-in reload check (reload_check.js): only when on.
1927
1932
  attrs["reload-check"] = "1" if @reload_check
1933
+ attrs.merge!(stage_collapsed_data)
1928
1934
  attrs.merge!(annotate_presets_data)
1929
1935
  # Who looks and what they may do (Viewer; viewer.js reads it at boot).
1930
1936
  attrs.merge!(Viewer.for(principal(req)).body_attributes)
@@ -1952,8 +1958,9 @@ module Samagotchi
1952
1958
 
1953
1959
  # A participant's <body> data for index.html: who they are (Viewer), their
1954
1960
  # grant's session and its participant title (the tab's), the version
1955
- # and the Annotate presets, and whether the working set is on
1956
- # (web.working_set: their stage's file column, as the owner's).
1961
+ # and the Annotate presets, whether the working set is on
1962
+ # (web.working_set: their stage's file column, as the owner's) and the
1963
+ # stage's fold default (web.stage_collapsed, the owner's).
1957
1964
  # Nothing of the owner's machine: no home, folders, project or way
1958
1965
  # back (sessions-dir, server-dir, home, scope-dir, project-*, back-*).
1959
1966
  def participant_index_data(req)
@@ -1964,6 +1971,7 @@ module Samagotchi
1964
1971
  participant_title(@session_class.load(grant.session_id, state_dir: default_state_dir))
1965
1972
  end
1966
1973
  attrs["session-title"] = title if title
1974
+ attrs.merge!(stage_collapsed_data)
1967
1975
  attrs.merge!(annotate_presets_data)
1968
1976
  attrs.merge!(Viewer.for(principal(req)).body_attributes)
1969
1977
  body_data(attrs)
@@ -1972,6 +1980,11 @@ module Samagotchi
1972
1980
  # +attrs+ as <body> data attributes, each value escaped.
1973
1981
  def body_data(attrs) = attrs.map { |key, value| %(data-#{key}="#{Rack::Utils.escape_html(value)}") }.join(" ")
1974
1982
 
1983
+ # The stage's fold default (web.stage_collapsed) for the page's <body>,
1984
+ # the owner's and a participant's (a layout choice, not a secret): only
1985
+ # when on; the page reads its presence (session_prefs.js).
1986
+ def stage_collapsed_data = @stage_collapsed ? { "stage-collapsed" => "1" } : {}
1987
+
1975
1988
  # The Annotate presets (web.annotate_presets) for the page's <body>,
1976
1989
  # the owner's and a participant's. Always there: an empty one means
1977
1990
  # no presets, not the default.
@@ -20,9 +20,12 @@ module Samagotchi
20
20
  module ParticipantImages
21
21
  # One upload's answer: +ref+ when accepted, else +status+, +code+ and
22
22
  # +detail+; +bytes+ the stored size (for the audit line).
23
- Upload = Data.define(:status, :code, :detail, :ref, :bytes) do
24
- def self.refused(status, code, detail) = new(status: status, code: code, detail: detail, ref: nil, bytes: nil)
25
- def self.accepted(ref) = new(status: 201, code: nil, detail: nil, ref: ref, bytes: ref[:bytes])
23
+ Upload = Data.define(:status, :code, :detail, :ref, :bytes, :audit) do
24
+ def self.refused(status, code, detail, audit: true)
25
+ new(status: status, code: code, detail: detail, ref: nil, bytes: nil, audit: audit)
26
+ end
27
+
28
+ def self.accepted(ref) = new(status: 201, code: nil, detail: nil, ref: ref, bytes: ref[:bytes], audit: true)
26
29
  end
27
30
 
28
31
  private
@@ -48,9 +51,9 @@ module Samagotchi
48
51
  # unsupported_image: chi converts those with an external tool), no
49
52
  # size in its header or over MAX_PARTICIPANT_PIXELS / _SIDE (422
50
53
  # image_too_big), their quota (429 too_many_images; a file they own
51
- # already is accepted again, no new entry). Every answer is audited,
52
- # an exception too (internal_error, then raised). The reply is the ref
53
- # without source, mime or bytes.
54
+ # already is accepted again, no new entry). Answers are audited except
55
+ # repeated refusals after the attempts cap; exceptions too (internal_error,
56
+ # then raised). The reply is the ref without source, mime or bytes.
54
57
  def participant_image_upload(req, id, session_dir)
55
58
  grant = principal(req).grant
56
59
  upload = begin
@@ -59,7 +62,7 @@ module Samagotchi
59
62
  audit_image(id, grant, Upload.refused(500, "internal_error", nil))
60
63
  raise
61
64
  end
62
- audit_image(id, grant, upload)
65
+ audit_image(id, grant, upload) if upload.audit
63
66
  return error_response(upload.status, upload.code, upload.detail) unless upload.ref
64
67
 
65
68
  json_response(201, upload.ref.slice(:file, :name, :width, :height))
@@ -72,17 +75,18 @@ module Samagotchi
72
75
  end
73
76
 
74
77
  def participant_upload(req, dir, grant)
75
- over = @participant_images_mutex.synchronize do
78
+ over, first_over = @participant_images_mutex.synchronize do
76
79
  record = ParticipantUploads.read(dir)
77
80
  tried = record.attempts_of(grant.id)
78
- ParticipantUploads.attempt!(dir, grant.id, state: record) if tried < Grants::MAX_IMAGE_ATTEMPTS
79
- tried >= Grants::MAX_IMAGE_ATTEMPTS
81
+ ParticipantUploads.attempt!(dir, grant.id, state: record) if tried <= Grants::MAX_IMAGE_ATTEMPTS
82
+ [tried >= Grants::MAX_IMAGE_ATTEMPTS, tried == Grants::MAX_IMAGE_ATTEMPTS]
80
83
  end
81
84
  if (cap = participant_cap_refusal(grant))
82
- return Upload.refused(*cap)
85
+ return Upload.refused(*cap, audit: !over || first_over)
83
86
  end
84
87
  if over
85
- return Upload.refused(429, "too_many_image_attempts", ParticipantMessages::TOO_MANY_IMAGE_ATTEMPTS)
88
+ return Upload.refused(429, "too_many_image_attempts", ParticipantMessages::TOO_MANY_IMAGE_ATTEMPTS,
89
+ audit: first_over)
86
90
  end
87
91
 
88
92
  bytes = image_upload_bytes(req)
@@ -201,7 +201,7 @@ module Samagotchi
201
201
  status = Session::STATUS_IDLE if status == Session::STATUS_RUNNING && reads.turn_snapshot && reads.current_turn.nil?
202
202
  json_response(200, {
203
203
  tail: true,
204
- session: { id: id, status: status, used_memory_names: [], prompt_notes: [] },
204
+ session: { id: id, status: status, used_memory_names: [], prompt_notes: [], prompt_parts: [] },
205
205
  messages: with_reply_html([answer].compact),
206
206
  # The owner's chi web's own setup notes: never a participant's.
207
207
  markdown_warning: nil,
@@ -63,6 +63,9 @@ module Samagotchi
63
63
  # prompts are theirs).
64
64
  "turn_enqueued" => :turn_enqueued,
65
65
  "turn_dequeued" => :turn_dequeued,
66
+ # A failed turn's prompt handed back: the viewer's own turn only
67
+ # (#prompt_restored).
68
+ "prompt_restored" => :prompt_restored,
66
69
  "input_merged" => :input_merged,
67
70
  # The owner's question, approval or Continue offer: "waiting for the
68
71
  # owner" and for what kind of thing (#waiting_kind), nothing of it.
@@ -85,7 +88,7 @@ module Samagotchi
85
88
  card command_output command_queued command_ran context_added empty_answer_retry
86
89
  generation_cancelled generation_progress generation_started guardrail_warning hook_notice
87
90
  llm_context_edited merged_input objectives_updated participants_changed pending_input_merged plugin_init_finished
88
- plugin_init_started plugin_init_wait prompt_restored question question_relay reasoning_history_refused
91
+ plugin_init_started plugin_init_wait question question_relay reasoning_history_refused
89
92
  recap_ready reminder_injected sampling_refused session_end session_start side_usage steer_cut thinking_dropped
90
93
  thinking_refused tool_dispatch_completed tool_dispatch_started used_memories_updated
91
94
  ].freeze
@@ -131,6 +134,29 @@ module Samagotchi
131
134
  { "type" => "turn_dequeued", **seq(event), "enqueued_id" => enqueued_id }
132
135
  end
133
136
 
137
+ # A failed turn of the viewer's own handing its prompt back: the text,
138
+ # their image refs (#image_refs), the Revise draft's turn id and the
139
+ # origin's ids the page matches it by (restore.js restoreAction). nil
140
+ # for anyone else's, the owner's or an automatic turn (decided by the
141
+ # origin's author, which chi web stamped). Never source, the error, a
142
+ # Verify claim's quote or anything else the owner's event carries.
143
+ def prompt_restored(event, viewer)
144
+ origin = field(event, :origin)
145
+ return nil unless origin.is_a?(Hash)
146
+
147
+ author = field(origin, :author)
148
+ return nil unless viewer.own?(author) && Steer.participant_author?(author)
149
+
150
+ out = { "type" => "prompt_restored", **seq(event), "prompt" => field(event, :prompt).to_s }
151
+ images = image_refs(field(event, :images), author, viewer)
152
+ out["images"] = images if images
153
+ revises = ReviseAnchor.from(field(event, :revises))
154
+ out["revises"] = { "turn_id" => revises.turn_id } if revises
155
+ out["origin"] = { "client_id" => field(origin, :client_id).to_s, "enqueued_id" => field(origin, :enqueued_id).to_s,
156
+ "author" => author.to_s }
157
+ out
158
+ end
159
+
134
160
  # Input merged into the running turn: the viewer's own lines (their
135
161
  # origins' enqueued ids) and how many, bare when none is theirs. The
136
162
  # others' (a delegate's report, another person's line) are not named
@@ -75,6 +75,7 @@ import { createBlockHost } from "./block_host.js";
75
75
  import { createWidgetDrawer } from "./inline_widgets.js";
76
76
  import { copyText, installCopy } from "./copy.js";
77
77
  import { installAnswerFold, sweepAnswerFolds } from "./answer_fold.js";
78
+ import { sweepSessionPrefs } from "./session_prefs.js";
78
79
  import { installDetailsMotion } from "./details_motion.js";
79
80
  import { answerLabel, installReviseStacks, reviseChipTemplate, reviseWorkerUnavailable } from "./revise_stack.js";
80
81
  import { createQuestionCards } from "./question_cards.js";
@@ -579,13 +580,14 @@ const scope = {
579
580
  };
580
581
  // The server refused ?dir (a folder deleted since the link was made).
581
582
  let scopeError = null;
582
- // The list's first load sweeps the folded answers of sessions gone since
583
- // (answer_fold.js), once per page.
583
+ // The list's first load sweeps the folded answers and the view settings of
584
+ // sessions gone since (answer_fold.js, session_prefs.js), once per page.
584
585
  let foldsSwept = false;
585
586
  function sweepFoldsOnce() {
586
587
  if (foldsSwept) return;
587
588
  foldsSwept = true;
588
589
  sweepAnswerFolds(store.sessions, { scoped: !!scope.dir });
590
+ sweepSessionPrefs(store.sessions, { scoped: !!scope.dir });
589
591
  }
590
592
 
591
593
  // The list by fetching: the fallback when there is no events stream (a
@@ -1597,6 +1599,9 @@ store.on("paintActive", () => lists.paintActive());
1597
1599
  store.on("settingsPanel", () => settingsControl?.refresh());
1598
1600
  // The working set's list offers pin only under forget.
1599
1601
  store.on("workingSetStrategy", () => workingSet?.strategyChanged());
1602
+ store.on("workingSet", () => workingSet?.sessionChanged());
1603
+ // ?.(): a page holding an older working_set_view.js cached (the mixed-cache rule).
1604
+ store.on("workingSetTokens", () => workingSet?.tokensChanged?.());
1600
1605
  store.on("featureGates", () => featureGates.check(store.current));
1601
1606
  store.on("composer", composerMode.update);
1602
1607
  store.on("composer", () => objectives.redraw());
@@ -1,12 +1,14 @@
1
1
  // The session's composer can fold away for room to read (the info bar under
2
2
  // it stays and becomes the page's bottom edge). The user's own fold or
3
- // unfold is saved per browser (chi_composer_collapsed); an archived
3
+ // unfold is saved per session, per browser (session_prefs.js,
4
+ // chi_composer_collapsed:<session>); an archived
4
5
  // session opens folded for that visit; the page expanding it by itself (a
5
6
  // focus, a restored line, a quote) opens it for the visit only. A visit is
6
7
  // one select() call. A card's text field with the focus on a narrow or touch
7
8
  // screen folds it for that time, on top of all of these (+cardField+): the
8
9
  // keyboard is up and the card needs the rows; nothing is saved.
9
10
 
11
+ // session_prefs.js COMPOSER_FOLD's name, kept for an older importer.
10
12
  export const COMPOSER_FOLD_KEY = "chi_composer_collapsed";
11
13
 
12
14
  // Whether the composer is folded: the saved choice or an archived visit,
@@ -1,11 +1,13 @@
1
1
  import { GRIP_CLICK_FOLD_MS, GRIP_OPEN_PX, gripFloor, gripFolds, gripGesture } from "./composer_size.js";
2
- import { COMPOSER_FOLD_KEY, composerFolded, foldHandle, opensOnKey } from "./composer_fold.js";
3
- import { readStored, removeStored, writeStored } from "./storage.js";
2
+ import { composerFolded, foldHandle, opensOnKey } from "./composer_fold.js";
3
+ import { COMPOSER_FLOOR, COMPOSER_FOLD, forget as forgetPref, read as readPref, write as writePref } from "./session_prefs.js";
4
4
 
5
5
  // The composer's grip and fold (made by composer_mount.js): the grip's drag, click
6
6
  // and keys, the fold's state per visit and its page-wide listeners. The mount keeps
7
7
  // the box's height (fitPrompt) and the grip's floor (+floor+ / +setFloor+), which
8
- // fitPrompt reads; the floor is saved under GRIP_KEY.
8
+ // fitPrompt reads; the floor is saved per session (session_prefs.js
9
+ // COMPOSER_FLOOR, chi_composer_floor:<session>; the start page's in memory).
10
+ // GRIP_KEY: its name, kept for an older importer.
9
11
  export const GRIP_KEY = "chi_composer_floor";
10
12
  // A card's text field with the focus folds the composer on these screens.
11
13
  const CARD_FIELD_SCREEN = "(max-width: 600px), (hover: none) and (pointer: coarse)";
@@ -56,9 +58,11 @@ export function createComposerGrip({
56
58
  // The grip's custom height, forgotten only by a double-click.
57
59
  function resetFloor() {
58
60
  setFloor(null);
59
- removeStored(GRIP_KEY);
61
+ forgetPref(COMPOSER_FLOOR, session());
60
62
  fitPrompt();
61
63
  }
64
+ // The floor saved, for the open session (the start page: in memory).
65
+ const saveFloor = (px) => writePref(COMPOSER_FLOOR, session(), String(px || ""));
62
66
 
63
67
  // One release of the grip is one gesture, decided by composer_size.js's
64
68
  // gripGesture: a drag down past the box folds the composer on release (a
@@ -123,7 +127,7 @@ export function createComposerGrip({
123
127
  // The drag asked for a smaller box, but opening it brings back the
124
128
  // height it had before the press: only a double-click forgets it.
125
129
  setFloor(floorBefore);
126
- writeStored(GRIP_KEY, String(floorBefore || ""));
130
+ saveFloor(floorBefore);
127
131
  setComposerFolded(true);
128
132
  } else if (gesture === "open") {
129
133
  cancelPendingFold();
@@ -132,7 +136,7 @@ export function createComposerGrip({
132
136
  } else if (gesture === "reset") {
133
137
  resetFloor();
134
138
  } else if (gesture === "hide") {
135
- writeStored(GRIP_KEY, String(floor() || ""));
139
+ saveFloor(floor());
136
140
  pendingFold = setTimeout(() => {
137
141
  pendingFold = null;
138
142
  setComposerFolded(true);
@@ -140,7 +144,7 @@ export function createComposerGrip({
140
144
  } else if (gesture === "resize") {
141
145
  // A drag that stops short of folding: keep the box at the height it asks for.
142
146
  cancelPendingFold();
143
- writeStored(GRIP_KEY, String(floor() || ""));
147
+ saveFloor(floor());
144
148
  // A pull that opened the box leaves the focus in it, as a tap does.
145
149
  if (opened) promptEl.focus();
146
150
  }
@@ -178,11 +182,11 @@ export function createComposerGrip({
178
182
  // Dragging the composer's grip down folds the session's composer away; the
179
183
  // grip, now the handle on the info bar's top edge, pulled up or clicked, or
180
184
  // typing on the page, brings it back. The user's own choice is saved per
181
- // browser; an archived session opens folded for its visit, and expanding
185
+ // session (chi_composer_collapsed:<session>); an archived session opens folded for its visit, and expanding
182
186
  // there saves nothing. The page's own focus or a restored line opens it
183
187
  // for the visit only. The start page never folds.
184
188
  function composerFoldSaved() {
185
- return readStored(COMPOSER_FOLD_KEY) === "1";
189
+ return readPref(COMPOSER_FOLD, session()) === "1";
186
190
  }
187
191
  function isComposerFolded() {
188
192
  return !!session() && composerFolded({ saved: composerFoldSaved(), archivedVisit: foldVisit.archived, visitOpen: foldVisit.open, cardField: !!cardField });
@@ -231,7 +235,7 @@ export function createComposerGrip({
231
235
  if (foldVisit.archived) {
232
236
  foldVisit.open = !folded;
233
237
  } else {
234
- writeStored(COMPOSER_FOLD_KEY, folded ? "1" : "0");
238
+ writePref(COMPOSER_FOLD, session(), folded ? "1" : "0");
235
239
  foldVisit.open = false;
236
240
  }
237
241
  applyComposerFolded();
@@ -307,9 +311,13 @@ export function createComposerGrip({
307
311
  // A new visit (select(), the start page): nothing opened, not decided.
308
312
  newVisit() {
309
313
  releaseCardField();
314
+ // A click's fold still waiting was for the session left, not this one.
315
+ cancelPendingFold();
310
316
  foldVisit = newFoldVisit();
311
317
  applyComposerFolded();
312
318
  },
319
+ // The open session's saved fold, drawn again (session_prefs.js).
320
+ applyFolded: () => applyComposerFolded(),
313
321
  // The visit's first getSession answer: an archived session opens folded.
314
322
  decideVisit(archived) {
315
323
  if (foldVisit.decided) return;