samagotchi 0.174.0 → 0.176.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 (63) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +38 -1
  3. data/bin/chi +1 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/cli.md +3 -0
  6. data/docs/configuration.md +1 -0
  7. data/docs/internals/bridge.md +10 -3
  8. data/docs/internals/engine.md +2 -2
  9. data/docs/internals/participants.md +11 -5
  10. data/docs/internals/web-frontend.md +44 -11
  11. data/docs/sessions.md +2 -2
  12. data/docs/testing.md +25 -3
  13. data/lib/samagotchi/answer_text.rb +4 -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/llm/stray_tool_call.rb +7 -4
  18. data/lib/samagotchi/llm_context_stale.rb +2 -1
  19. data/lib/samagotchi/message_parts.rb +5 -2
  20. data/lib/samagotchi/model_markup.rb +22 -0
  21. data/lib/samagotchi/model_profile.rb +8 -7
  22. data/lib/samagotchi/participant_uploads.rb +14 -1
  23. data/lib/samagotchi/prompt_literal_guard.rb +7 -6
  24. data/lib/samagotchi/task_transcript.rb +10 -5
  25. data/lib/samagotchi/tool_call_parser.rb +6 -5
  26. data/lib/samagotchi/turn_note.rb +2 -1
  27. data/lib/samagotchi/version.rb +1 -1
  28. data/lib/samagotchi/web/app.rb +15 -2
  29. data/lib/samagotchi/web/participant_images.rb +16 -12
  30. data/lib/samagotchi/web/participant_show.rb +1 -0
  31. data/lib/samagotchi/web/participant_view.rb +31 -3
  32. data/lib/samagotchi/web/public/app.js +18 -4
  33. data/lib/samagotchi/web/public/composer_fold.js +3 -1
  34. data/lib/samagotchi/web/public/composer_grip.js +18 -10
  35. data/lib/samagotchi/web/public/composer_mount.js +17 -6
  36. data/lib/samagotchi/web/public/reload_check.js +0 -3
  37. data/lib/samagotchi/web/public/restore.js +3 -1
  38. data/lib/samagotchi/web/public/session_prefs.js +89 -0
  39. data/lib/samagotchi/web/public/session_sync.js +3 -0
  40. data/lib/samagotchi/web/public/session_view.js +41 -3
  41. data/lib/samagotchi/web/public/stage_asking.js +21 -18
  42. data/lib/samagotchi/web/public/stage_cloud.js +3 -2
  43. data/lib/samagotchi/web/public/stage_missing.js +148 -0
  44. data/lib/samagotchi/web/public/stage_model.js +2 -1
  45. data/lib/samagotchi/web/public/stage_view.js +14 -4
  46. data/lib/samagotchi/web/public/stage_view_memory.js +76 -0
  47. data/lib/samagotchi/web/public/stream_handlers.js +3 -2
  48. data/lib/samagotchi/web/public/turn_events.js +1 -1
  49. data/lib/samagotchi/web/public/working_set_rail.js +22 -7
  50. data/lib/samagotchi/web/public/ws_reader.js +2 -0
  51. data/lib/samagotchi/web/server.rb +6 -2
  52. data/lib/samagotchi/web/session_show.rb +42 -4
  53. data/lib/samagotchi/worker/child_side.rb +123 -0
  54. data/lib/samagotchi/worker/command_queue.rb +346 -0
  55. data/lib/samagotchi/worker/leave.rb +286 -0
  56. data/lib/samagotchi/worker/scratch.rb +99 -0
  57. data/lib/samagotchi/worker/signal_grace.rb +96 -0
  58. data/lib/samagotchi/worker/startup.rb +92 -0
  59. data/lib/samagotchi/worker/wake_turns.rb +190 -0
  60. data/lib/samagotchi/worker.rb +24 -1065
  61. data/lib/samagotchi/worker_exit_claim.rb +12 -0
  62. metadata +12 -2
  63. data/lib/samagotchi/web/public/cards_offscreen.js +0 -69
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../model_markup"
4
+
3
5
  module Samagotchi
4
6
  module LLM
5
7
  # A reply that is nothing but a tool call written as text. The host's
@@ -25,16 +27,17 @@ module Samagotchi
25
27
  # predicate is ChatLoop's.
26
28
  module StrayToolCall
27
29
  # A stray call can only open with the block itself.
28
- OPENS = ["<tool_call>", "<function=", "<parameter="].freeze
30
+ OPENS = [ModelMarkup::TOOL_CALL_OPEN, ModelMarkup::FUNCTION_OPEN, ModelMarkup::PARAMETER_OPEN].freeze
29
31
  # ... and end with the close of that same block: nothing else in the
30
32
  # reply. A `<parameter=` call often closes with `</function>` (the
31
33
  # flavour that mixes the two tags does it mid-block too), and a block
32
34
  # opened by `<function=` or `<parameter=` can also end with the
33
35
  # wrapper's own `</tool_call>` instead of its tag.
34
36
  CLOSES = {
35
- "<tool_call>" => ["</tool_call>"],
36
- "<function=" => ["</function>", "</tool_call>"],
37
- "<parameter=" => ["</parameter>", "</function>", "</tool_call>"]
37
+ ModelMarkup::TOOL_CALL_OPEN => [ModelMarkup::TOOL_CALL_CLOSE],
38
+ ModelMarkup::FUNCTION_OPEN => [ModelMarkup::FUNCTION_CLOSE, ModelMarkup::TOOL_CALL_CLOSE],
39
+ ModelMarkup::PARAMETER_OPEN => [ModelMarkup::PARAMETER_CLOSE, ModelMarkup::FUNCTION_CLOSE,
40
+ ModelMarkup::TOOL_CALL_CLOSE]
38
41
  }.freeze
39
42
  # How much of the reply the warning keeps (KernelLoop's own cap).
40
43
  TAIL_CHARS = 400
@@ -5,6 +5,7 @@ require_relative "tool_response"
5
5
  require_relative "tool_ids"
6
6
  require_relative "llm_context_edit"
7
7
  require_relative "model_profile"
8
+ require_relative "model_markup"
8
9
  require_relative "tool_call_parser"
9
10
  require_relative "tools/builtin_calls"
10
11
  require_relative "tools/tool_path"
@@ -264,7 +265,7 @@ module Samagotchi
264
265
  {}
265
266
  end
266
267
 
267
- QWEN_CALL = "<tool_call>"
268
+ QWEN_CALL = ModelMarkup::TOOL_CALL_OPEN
268
269
  GEMMA_CALL = "<|tool_call>"
269
270
 
270
271
  def native_parser(content)
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "model_profile"
4
+ require_relative "model_markup"
4
5
  require_relative "tool_call_parser"
5
6
  require_relative "tool_activity"
6
7
  require_relative "tool_row_fields"
@@ -106,7 +107,7 @@ module Samagotchi
106
107
 
107
108
  def thinking_of(content)
108
109
  blocks = content.scan(QWEN_THINK).flatten
109
- if blocks.empty? && !content.include?("<think>") && (open = content[QWEN_OPEN_THINK, 1])
110
+ if blocks.empty? && !content.include?(ModelMarkup::THINK_OPEN) && (open = content[QWEN_OPEN_THINK, 1])
110
111
  blocks = [open]
111
112
  end
112
113
  blocks += content.scan(GEMMA_THOUGHT).flatten
@@ -115,7 +116,9 @@ module Samagotchi
115
116
 
116
117
  def markup_tools(content, responses, registry, cwd = nil, marks = {})
117
118
  calls = []
118
- calls.concat(ToolCallParser::Qwen.new(ModelProfile.qwen36).parse(content)) if content.include?("<tool_call>")
119
+ if content.include?(ModelMarkup::TOOL_CALL_OPEN)
120
+ calls.concat(ToolCallParser::Qwen.new(ModelProfile.qwen36).parse(content))
121
+ end
119
122
  calls.concat(ToolCallParser::Gemma.new(ModelProfile.gemma4).parse(content)) if content.include?("<|tool_call>")
120
123
  return [] if calls.empty?
121
124
 
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ # The plain Qwen-style markup tokens, apart from the model-specific token
5
+ # formats. ModelProfile, ToolCallParser, StrayToolCall, PromptLiteralGuard,
6
+ # TurnNote, MessageParts, AnswerText, LLMContextStale and ParticipantView
7
+ # read them here without loading a tool class.
8
+ #
9
+ # No requires: it is a leaf every client can load.
10
+ module ModelMarkup
11
+ TOOL_CALL_OPEN = "<tool_call>"
12
+ TOOL_CALL_CLOSE = "</tool_call>"
13
+ FUNCTION_OPEN = "<function="
14
+ FUNCTION_CLOSE = "</function>"
15
+ PARAMETER_OPEN = "<parameter="
16
+ PARAMETER_CLOSE = "</parameter>"
17
+ TOOL_RESPONSE_OPEN = "<tool_response>"
18
+ TOOL_RESPONSE_CLOSE = "</tool_response>"
19
+ THINK_OPEN = "<think>"
20
+ THINK_CLOSE = "</think>"
21
+ end
22
+ end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "log"
4
+ require_relative "model_markup"
4
5
  module Samagotchi
5
6
  # Encapsulates all model-specific token formats and parsing behavior.
6
7
  # Each profile maps to a model family; ModelProfile.resolve picks one
@@ -108,13 +109,13 @@ module Samagotchi
108
109
  name: "qwen36",
109
110
  turn_start: "",
110
111
  turn_end: "",
111
- tool_call_open: "<tool_call>",
112
- tool_call_close: "</tool_call>",
113
- tool_response_open: "<tool_response>",
114
- tool_response_close: "</tool_response>",
112
+ tool_call_open: ModelMarkup::TOOL_CALL_OPEN,
113
+ tool_call_close: ModelMarkup::TOOL_CALL_CLOSE,
114
+ tool_response_open: ModelMarkup::TOOL_RESPONSE_OPEN,
115
+ tool_response_close: ModelMarkup::TOOL_RESPONSE_CLOSE,
115
116
  string_delim: nil,
116
- thought_open: "<think>",
117
- thought_close: "</think>",
117
+ thought_open: ModelMarkup::THINK_OPEN,
118
+ thought_close: ModelMarkup::THINK_CLOSE,
118
119
  system_prefix: "<|im_start|>system\n",
119
120
  user_prefix: "<|im_start|>user\n",
120
121
  assistant_prefix: "<|im_start|>assistant\n",
@@ -377,7 +378,7 @@ module Samagotchi
377
378
  # <eos> or <turn|>, depending on who packed it). llama.cpp itself detects
378
379
  # Gemma 4 by '<|tool_call>call:'.
379
380
  FINGERPRINTS = {
380
- "qwen36" => ["<|im_start|>", "<function="],
381
+ "qwen36" => ["<|im_start|>", ModelMarkup::FUNCTION_OPEN],
381
382
  "gemma4" => ["<|turn>", "<|tool_call>"]
382
383
  }.freeze
383
384
 
@@ -36,6 +36,8 @@ module Samagotchi
36
36
  def owned?(file, grant_id) = entries.any? { |entry| entry.file == file && entry.grant_id == grant_id }
37
37
  end
38
38
  BROKEN = State.new(entries: [].freeze, attempts: {}.freeze, broken: true)
39
+ WARNED_UNREADABLE = Set.new
40
+ WARNED_UNREADABLE_MUTEX = Mutex.new
39
41
 
40
42
  module_function
41
43
 
@@ -55,10 +57,21 @@ module Samagotchi
55
57
 
56
58
  State.new(entries: entries, attempts: attempts.transform_values(&:to_i), broken: false)
57
59
  rescue JSON::ParserError, SystemCallError, TypeError, KeyError, NoMethodError => e
58
- Log.warn(:web, "participant_images_unreadable", file: path, msg: e.message)
60
+ warn_unreadable(path, e)
59
61
  BROKEN
60
62
  end
61
63
 
64
+ def warn_unreadable(path, error)
65
+ stat = begin
66
+ File.stat(path)
67
+ rescue SystemCallError
68
+ nil
69
+ end
70
+ key = [path, stat&.size, stat&.mtime]
71
+ first = WARNED_UNREADABLE_MUTEX.synchronize { WARNED_UNREADABLE.add?(key) }
72
+ Log.warn(:web, "participant_images_unreadable", file: path, msg: error.message) if first
73
+ end
74
+
62
75
  # Distinct files +grant_id+ uploaded; a broken record reads as at quota.
63
76
  def count(dir, grant_id) = read(dir).count(grant_id)
64
77
 
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "model_profile"
4
+ require_relative "model_markup"
4
5
 
5
6
  module Samagotchi
6
7
  # Escapes literal control-token text when arbitrary source/output is embedded
@@ -25,12 +26,12 @@ module Samagotchi
25
26
  QWEN_TOKEN_PAIRS = [
26
27
  ["[[SAMAGOTCHI_LITERAL_IM_START]]", "<|im_start|>"],
27
28
  ["[[SAMAGOTCHI_LITERAL_IM_END]]", "<|im_end|>"],
28
- ["[[SAMAGOTCHI_LITERAL_TOOL_CALL_OPEN]]", "<tool_call>"],
29
- ["[[SAMAGOTCHI_LITERAL_TOOL_CALL_CLOSE]]", "</tool_call>"],
30
- ["[[SAMAGOTCHI_LITERAL_TOOL_RESPONSE_OPEN]]", "<tool_response>"],
31
- ["[[SAMAGOTCHI_LITERAL_TOOL_RESPONSE_CLOSE]]", "</tool_response>"],
32
- ["[[SAMAGOTCHI_LITERAL_THINK_OPEN]]", "<think>"],
33
- ["[[SAMAGOTCHI_LITERAL_THINK_CLOSE]]", "</think>"],
29
+ ["[[SAMAGOTCHI_LITERAL_TOOL_CALL_OPEN]]", ModelMarkup::TOOL_CALL_OPEN],
30
+ ["[[SAMAGOTCHI_LITERAL_TOOL_CALL_CLOSE]]", ModelMarkup::TOOL_CALL_CLOSE],
31
+ ["[[SAMAGOTCHI_LITERAL_TOOL_RESPONSE_OPEN]]", ModelMarkup::TOOL_RESPONSE_OPEN],
32
+ ["[[SAMAGOTCHI_LITERAL_TOOL_RESPONSE_CLOSE]]", ModelMarkup::TOOL_RESPONSE_CLOSE],
33
+ ["[[SAMAGOTCHI_LITERAL_THINK_OPEN]]", ModelMarkup::THINK_OPEN],
34
+ ["[[SAMAGOTCHI_LITERAL_THINK_CLOSE]]", ModelMarkup::THINK_CLOSE],
34
35
  ["[[SAMAGOTCHI_LITERAL_VISION_START]]", "<|vision_start|>"],
35
36
  ["[[SAMAGOTCHI_LITERAL_VISION_END]]", "<|vision_end|>"]
36
37
  ].freeze
@@ -28,7 +28,7 @@ module Samagotchi
28
28
  Array(messages).flat_map do |message|
29
29
  next [] unless (message[:role] || message["role"]).to_s == "tool_response"
30
30
 
31
- (message[:content] || message["content"]).to_s.split("\n\n---\n\n").filter_map do |block|
31
+ utf8(message[:content] || message["content"]).split("\n\n---\n\n").filter_map do |block|
32
32
  block[CREATED_BLOCK, 1] || handed_over_id(block)
33
33
  end
34
34
  end.uniq
@@ -39,8 +39,9 @@ module Samagotchi
39
39
  # handed_over_id. nil for any other tool or output.
40
40
  # @return [String, nil]
41
41
  def created_id(tool, text)
42
+ text = utf8(text)
42
43
  case tool
43
- when "task_create" then text.to_s[CREATED_OUTPUT, 1]
44
+ when "task_create" then text[CREATED_OUTPUT, 1]
44
45
  when ToolNames::Execute::NAME then handed_over_id(text)
45
46
  end
46
47
  end
@@ -52,16 +53,20 @@ module Samagotchi
52
53
  # web/public/task_stop.js has the JS twin (handedOverId).
53
54
  # @return [String, nil]
54
55
  def handed_over_id(text)
56
+ text = utf8(text)
57
+ text[handed_over_pattern, 1]
58
+ end
59
+
60
+ def utf8(text)
55
61
  text = text.to_s
56
62
  # A regexp raises on bytes that aren't UTF-8 (a command's raw output).
57
- text = text.scrub unless text.valid_encoding?
58
- text[handed_over_pattern, 1]
63
+ text.valid_encoding? ? text : text.scrub
59
64
  end
60
65
 
61
66
  def handed_over_pattern
62
67
  @handed_over_pattern ||= /\A#{RAN_AS_LINE}(?:\[#{ToolNames::Execute::NAME}\]\n)?#{Regexp.escape(ToolNames::Execute::HANDED_OVER)} #{ToolNames::Execute::HANDED_OVER_AFTER}[^\n]*\ntask_id: (\S+)/
63
68
  end
64
69
 
65
- private_class_method :handed_over_pattern
70
+ private_class_method :utf8, :handed_over_pattern
66
71
  end
67
72
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "model_profile"
4
+ require_relative "model_markup"
4
5
  require_relative "tools/args"
5
6
  require_relative "tools/ask_user_question"
6
7
  require_relative "tools/builtin_calls"
@@ -353,8 +354,8 @@ module Samagotchi
353
354
  results = []
354
355
 
355
356
  pos = 0
356
- tool_open = "<tool_call>"
357
- tool_close = "</tool_call>"
357
+ tool_open = ModelMarkup::TOOL_CALL_OPEN
358
+ tool_close = ModelMarkup::TOOL_CALL_CLOSE
358
359
 
359
360
  while (open_pos = text.index(tool_open, pos))
360
361
  body_start = open_pos + tool_open.length
@@ -383,7 +384,7 @@ module Samagotchi
383
384
  end
384
385
 
385
386
  def strip_tool_calls(text)
386
- ToolCallParser.strip_calls(text, "<tool_call>", "</tool_call>")
387
+ ToolCallParser.strip_calls(text, ModelMarkup::TOOL_CALL_OPEN, ModelMarkup::TOOL_CALL_CLOSE)
387
388
  end
388
389
 
389
390
  def parse_with_recovery(response, partial_fragment)
@@ -420,8 +421,8 @@ module Samagotchi
420
421
  end
421
422
 
422
423
  def qwen_unterminated_tool_call_fragment(text)
423
- open_tag = "<tool_call>"
424
- close_tag = "</tool_call>"
424
+ open_tag = ModelMarkup::TOOL_CALL_OPEN
425
+ close_tag = ModelMarkup::TOOL_CALL_CLOSE
425
426
  pos = 0
426
427
 
427
428
  while (open_pos = text.index(open_tag, pos))
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "model_profile"
4
+ require_relative "model_markup"
4
5
  require_relative "thinking_tails"
5
6
 
6
7
  module Samagotchi
@@ -32,7 +33,7 @@ module Samagotchi
32
33
  STEP_CHARS = ThinkingTails::TAIL_CHARS
33
34
  # A step's native thinking starts with one of these; the cut keeps it,
34
35
  # so the UIs still find the thinking (MessageParts).
35
- THINK_OPENS = ["<think>", ModelProfile::GEMMA_THOUGHT_CHANNEL_OPEN].freeze
36
+ THINK_OPENS = [ModelMarkup::THINK_OPEN, ModelProfile::GEMMA_THOUGHT_CHANNEL_OPEN].freeze
36
37
 
37
38
  module_function
38
39
 
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.174.0"
4
+ VERSION = "0.176.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)
@@ -58,6 +58,7 @@ module Samagotchi
58
58
  **participant_drawings_field(drawn, messages, viewer),
59
59
  failed_turn: nil,
60
60
  current_turn: current,
61
+ live_read: reads.live_read,
61
62
  replay: participant_replay(turn_snapshot, timing, viewer),
62
63
  queued: participant_queued(queued, viewer),
63
64
  queued_commands: [],
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../output_formatter"
4
+ require_relative "../model_markup"
4
5
  require_relative "../steer"
5
6
  require_relative "../turn_origin"
6
7
  require_relative "../revise_anchor"
@@ -62,6 +63,9 @@ module Samagotchi
62
63
  # prompts are theirs).
63
64
  "turn_enqueued" => :turn_enqueued,
64
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,
65
69
  "input_merged" => :input_merged,
66
70
  # The owner's question, approval or Continue offer: "waiting for the
67
71
  # owner" and for what kind of thing (#waiting_kind), nothing of it.
@@ -84,7 +88,7 @@ module Samagotchi
84
88
  card command_output command_queued command_ran context_added empty_answer_retry
85
89
  generation_cancelled generation_progress generation_started guardrail_warning hook_notice
86
90
  llm_context_edited merged_input objectives_updated participants_changed pending_input_merged plugin_init_finished
87
- 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
88
92
  recap_ready reminder_injected sampling_refused session_end session_start side_usage steer_cut thinking_dropped
89
93
  thinking_refused tool_dispatch_completed tool_dispatch_started used_memories_updated
90
94
  ].freeze
@@ -130,6 +134,29 @@ module Samagotchi
130
134
  { "type" => "turn_dequeued", **seq(event), "enqueued_id" => enqueued_id }
131
135
  end
132
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
+
133
160
  # Input merged into the running turn: the viewer's own lines (their
134
161
  # origins' enqueued ids) and how many, bare when none is theirs. The
135
162
  # others' (a delegate's report, another person's line) are not named
@@ -692,10 +719,11 @@ module Samagotchi
692
719
  OutputFormatter::GEMMA_TOOL_CALL_RE, OutputFormatter::GEMMA_THOUGHT_RE)
693
720
  # A close with no open before it: what came before was thinking (the
694
721
  # raw loop saves prefill + response).
695
- BARE_CLOSES = ["</think>", "<channel|>"].freeze
722
+ BARE_CLOSES = [ModelMarkup::THINK_CLOSE, "<channel|>"].freeze
696
723
  # An open with no close after it (a cut-off thought, a tool call the
697
724
  # loop recovered): everything from it on is the model's own.
698
- OPENS = ["<think>", "<tool_call>", "<|tool_call>", "<|channel>", "<|tool_response>", "<tool_response>", "<|think|>"].freeze
725
+ OPENS = [ModelMarkup::THINK_OPEN, ModelMarkup::TOOL_CALL_OPEN, "<|tool_call>", "<|channel>",
726
+ "<|tool_response>", ModelMarkup::TOOL_RESPONSE_OPEN, "<|think|>"].freeze
699
727
 
700
728
  # A saved model message's raw content as a participant may read it:
701
729
  # closed blocks kept (the display strips them, its tool rows come from
@@ -51,6 +51,7 @@ import { normalize, cantText } from "./format.js";
51
51
  import { createBubbles } from "./bubbles.js";
52
52
  import { createCardsPlace } from "./cards_place.js";
53
53
  import { createStageView } from "./stage_view.js";
54
+ import { createStageMissing } from "./stage_missing.js";
54
55
  import { createReloadCheck } from "./reload_check.js";
55
56
  import { createCardRegistry, observeCards } from "./card_registry.js";
56
57
  import { createWorkingSet } from "./working_set_view.js";
@@ -74,6 +75,7 @@ import { createBlockHost } from "./block_host.js";
74
75
  import { createWidgetDrawer } from "./inline_widgets.js";
75
76
  import { copyText, installCopy } from "./copy.js";
76
77
  import { installAnswerFold, sweepAnswerFolds } from "./answer_fold.js";
78
+ import { sweepSessionPrefs } from "./session_prefs.js";
77
79
  import { installDetailsMotion } from "./details_motion.js";
78
80
  import { answerLabel, installReviseStacks, reviseChipTemplate, reviseWorkerUnavailable } from "./revise_stack.js";
79
81
  import { createQuestionCards } from "./question_cards.js";
@@ -359,7 +361,10 @@ const workingSet = document.body.dataset.workingSet === "1" && viewer.can("worki
359
361
  wsPreview?.attach(workingSet);
360
362
  document.body.classList.toggle("working-set", !!workingSet);
361
363
  // The running turn's DOM: the stage pinned above the composer
362
- // (stage_view.js), the turn block (turn_block.js) in its cloud.
364
+ // (stage_view.js), the turn block (turn_block.js) in its cloud. The
365
+ // running-with-no-turn check (stage_missing.js) hangs on its hooks, so it is
366
+ // made right after the stage.
367
+ let stageMissing = null;
363
368
  const turnDom = createStageView({
364
369
  historyEl,
365
370
  isNearBottom: () => atHistoryEnd(),
@@ -376,10 +381,18 @@ const turnDom = createStageView({
376
381
  // Stop turn in its status row (disabled until the request settles).
377
382
  onCancel: viewer.can("stop_any_turn") || viewer.can("stop_own_turn") ? () => handleCancel() : null,
378
383
  canCancel: () => !participant || participant.canCancel(), ownerWait: () => participant?.ownerWait() ?? null,
379
- onHandedOff: (handed) => reloadCheck.handedOff(handed),
384
+ onHandedOff: (handed) => { reloadCheck.handedOff(handed); stageMissing?.check(); },
385
+ onStageCleared: () => stageMissing?.check(),
380
386
  // The quiet signal (stage_stall.js): the stream, what the turn waits on, a joiner's step clock.
381
387
  streamLive: () => sessionSync.streamLive(), timingNote: () => liveTurn.timing.note, serverGen: () => liveTurn.serverGen,
382
388
  });
389
+ // The stage's own look at "running, nothing on it" (stage_missing.js): the
390
+ // bare status row, the mark and one console line per session visit. A status
391
+ // that leaves running, a resize or a composer that changed size looks again.
392
+ stageMissing = createStageMissing({ store, turnDom, composerEl });
393
+ store.on("infoBar", stageMissing.checkOnStatus);
394
+ window.addEventListener("resize", () => stageMissing.check());
395
+ if (window.ResizeObserver) new window.ResizeObserver(() => stageMissing.check()).observe(composerEl);
383
396
  // The open session's cards as data (card_registry.js: fed by the stream's card events and renderSessionView's seed).
384
397
  const cardRegistry = createCardRegistry();
385
398
  // The opt-in reload check (web.reload_check): a handed-off turn against a
@@ -567,13 +580,14 @@ const scope = {
567
580
  };
568
581
  // The server refused ?dir (a folder deleted since the link was made).
569
582
  let scopeError = null;
570
- // The list's first load sweeps the folded answers of sessions gone since
571
- // (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.
572
585
  let foldsSwept = false;
573
586
  function sweepFoldsOnce() {
574
587
  if (foldsSwept) return;
575
588
  foldsSwept = true;
576
589
  sweepAnswerFolds(store.sessions, { scoped: !!scope.dir });
590
+ sweepSessionPrefs(store.sessions, { scoped: !!scope.dir });
577
591
  }
578
592
 
579
593
  // The list by fetching: the fallback when there is no events stream (a
@@ -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,