samagotchi 0.174.0 → 0.175.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9ebb4dcd3b901ac27f433f7113beb88393c67c41aea586513c1fcbae51e5b2d0
4
- data.tar.gz: 6d8de5adbdcb40dc3fe433cb66bee2c187173a7bc3ac737f299a91fa975c04f3
3
+ metadata.gz: 37fbe4f66f3709c6c9d31f106af298d34664b9bfe6817f264fdbf3e51803e462
4
+ data.tar.gz: ec4cdea784346d7713c93f38c891245dbc55a9f074a35ea7fb38b2ea032f8968
5
5
  SHA512:
6
- metadata.gz: e0e438e9eb659466bf9c96bd228ca14f64707a4204be9cb71487c08eb5e1a93a3a4b98a41b29b5217d98b93c6a0caad921d739c4f6d11baaf621f8428db55370
7
- data.tar.gz: 14fbc691fe2a5a140f53f7985307bb95930ca4e14d9f0aba2f3a327f46e738e07cf27d53607e40ded8527708abd59911c8315cc0ed3167b40fe7ac51c63cf357
6
+ metadata.gz: 6534996033040eed2533845e1ebe0f9af8e3066d3fb5f07c33af243651bcb949fd5e2f2678115596ad28167adb63abccec528e127eabb9516d7f8b80dbf0f280
7
+ data.tar.gz: 95c59df9d40e1fd9b13ffc7e265ebca25008265d775fbe62b6d21f9145305eb35ae4c9fc2a4d6a3ccbb6679e67db9cfb7c3f876888aa4680932b34e9c316a862
data/CHANGELOG.md CHANGED
@@ -8,6 +8,22 @@ and commands may change between minor versions. How releases are made:
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.175.0] - 2026-11-16
12
+
13
+ ### Added
14
+
15
+ - chi web: the page's session read says how the live worker's snapshot read went (`live_read`: ok, none, failed),
16
+ and a failed one logs the why and the elapsed ms to chi web's debug log.
17
+
18
+ ### Fixed
19
+
20
+ - chi web: a running session always has its stage — the turn in progress, or a bare "running" row with Stop turn
21
+ when the page has nothing to draw — so a turn missing from the stage no longer leaves the page with nothing. The
22
+ stage marks itself when that happens (`data-stage-missing`), and says once in the console what the read had.
23
+ - Tool output with invalid UTF-8 no longer breaks task tracking or finishing a background task.
24
+
25
+ Update with `chi update`.
26
+
11
27
  ## [0.174.0] - 2026-11-15
12
28
 
13
29
  ### Added
@@ -6417,7 +6433,8 @@ and long-lived sessions.
6417
6433
  - A macOS desktop helper (`chi desktop install`): a "Send to chi" Service and a
6418
6434
  hotkey panel that send selected text or the clipboard to your sessions.
6419
6435
 
6420
- [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.174.0...HEAD
6436
+ [Unreleased]: https://github.com/dm1try/samagotchi/compare/v0.175.0...HEAD
6437
+ [0.175.0]: https://github.com/dm1try/samagotchi/compare/v0.174.0...v0.175.0
6421
6438
  [0.174.0]: https://github.com/dm1try/samagotchi/compare/v0.173.0...v0.174.0
6422
6439
  [0.173.0]: https://github.com/dm1try/samagotchi/compare/v0.172.1...v0.173.0
6423
6440
  [0.172.1]: https://github.com/dm1try/samagotchi/compare/v0.172.0...v0.172.1
@@ -156,7 +156,14 @@ no line for (an older worker's, one from before drawings, a dropped one) gets on
156
156
  cursor and the unfold reads a Set of stamped ids, so a long session's show is linear in its turns; a made-up line
157
157
  is memoized per range (`Synth.memoized`), so a show after a turn end makes no old turn again. What each step did
158
158
  as message parts (`MessageParts`, `parts: true`) is the participant review's only (`ParticipantReview`, frozen on
159
- its message model).
159
+ its message model). The read also says how the snapshot read went, as `live_read`: `ok` (a live worker's snapshot
160
+ came), `none` (no worker owns the session) or `failed` (a live worker's Bridge answered with no snapshot). The
161
+ snapshot is asked for once — `SessionShow#live_snapshot` uses `bridge_get`, the status it needs for the why is
162
+ the same reply's, never a second GET. A
163
+ failed one logs `web live_snapshot_failed` with the why — the Bridge's status, or no reply at all (a refused
164
+ connect, a timeout, a cut reply; the record's ms tells them apart) — and the elapsed ms, so a page showing a running session with nothing on its
165
+ stage can be told from a stream that replayed the turn's end; the page's `stage_missing.js` reads the key
166
+ (internals/web-frontend.md, "A running session without a turn"). Participants get the same key.
160
167
  - **Compat.** An older worker writes nothing, a continue (a note, no turns) copies no drawings, and
161
168
  an older chi's fork or one-shot wrote none: their turns are made from their messages. A `/btw keep` child forked
162
169
  before its first turn (saved without its system head) draws its turns made from its messages, without CardStore
@@ -29,7 +29,7 @@ page. A factory dep a new version stops passing is the same hazard the other way
29
29
  out of `send_turn.js`, `session_actions.js` and `lists_view.js`); a page loaded before keeps all its old modules
30
30
  until a reload, so the risk is a mixed cache, not an open tab. `answer_fold.js`, `details_motion.js`,
31
31
  `turn_range.js`, `history_reveal.js`, `latest.js`, `session_payload.js`, `method_api.js`, `session_store.js`,
32
- `session_fields.js`, `feature_gates.js`, `revise_stack.js`, `revise_switch.js`, `shell_command.js`, `stale_params.js`, `popover_modal.js`, `more_sheet.js`, `delete_sheet.js` (Deleting a chained session, below), `hash_intent.js` (what the hash asks for: session, all, start or keep), `worker_features.js`, `version_notices.js`, `owner_claim.js`, `owner_verify.js`, `composer_mode.js`, `strip_hidden.js`, `block_open.js`, `text_roots.js`, `block_source.js`, `block_frame.js`, `block_host.js`, `block_watch.js`, `card_stamps.js`, `recap_stamp.js` (a saved recap's place by its `opening_id` stamp, else its count), `inline_widgets.js`, `widget_walk.js`, `widget_picks.js`, `history_shape.js` (the history's shape, live against a reload: the e2e reload checks and the opt-in reload check share its normalizer and its `ACCEPTED` allowlist), `turn_pieces.js` (a finished turn's one order and its answer rule: the live hand-off's `handOffOrder` and `turnEnded`, and a reload's `turnHistoryNodes`), `reload_check.js` (the opt-in `web.reload_check`: after the stage's hand-off, the turn against a reload of it, the counts posted; the history without its cards and questions, and those as data: the page's `card_registry.js` against one seeded from the read, this turn's entries, a capped read's missing keys skipped), `cards_offscreen.js` (the reload check's old placer, which nothing imports now: kept one release for a stale `app.js` that still imports it, then deleted), `turn_drawing.js` (a finished turn's drawing, `turn_drawings` in the show: its fold into steps and its end kind; `turn_block.js` draws it), `stage_stall.js` (the stage's quiet signal), `stage_quiet_clock.js`, `stage_dom.js`, `stage_answer.js`, `stage_pager.js`, `stage_cloud.js`, `stage_handoff.js`, `stage_place.js`, `stage_probe.js` (the stage's features: below, The stage's modules), `card_kinds.js` (what a card waits as, from its data: the kind, approval and folded-row text the stage's registry takes; the node's read is its cross-check), `card_registry.js` (the open session's cards as data, an observer of the stream's card events and a read's seed: Where state lives), `history_end.js` (the stage's one move of pieces to the history's end), `stage_opened.js` (a running turn opened in the history while a card waits: the lead-in bubble, the moves, the end fold), `stage_asking.js` (the stage's docked card and its fold: the docking and lead-in rules, the opening, a waiting card's own toggle, the folded row's text per kind, the fold's choice, reveal and the docked card's fold; `stage_view.js` wires it), `stage_waiting.js` (the stage's waiting cards as data, keyed by `data-qid` / `data-card-id`: kind, docked, approval, the stage's order, the shown card and its pager, the docked card's fold, kept for this tab in `chi_asking_fold:<session>`; `front`, `count`, `shown`, `blocking`), `stage_cards.js` (the cards that wait in the stage: `PENDING`, `ASKS`, `waitsInStage`, read by `stage_model.js placeKind`), `resync_reach.js` (a re-read that can't reach chi web keeps the drawn history; the status chip says retrying / offline, outside a turn), `session_sync.js` (the open session's sync: `select`, `resync` and its retries, the stream's life; the stream handle and the re-read bookkeeping are its own), `session_view.js` (the open session's view: `renderSessionView` draws a read, `forgetSession` resets the page for another session, `readTurnEnd`, `endTurnView`; app.js makes both right after the cards, each reaching the other and the later views through getters), `participant_main.js`, `participant_bar.js`, `viewer_self.js`, `participant_history.js` (a participant's ↑/↓ list), `stage_owner_wait.js`, `participant_revise.js` (a participant's page: The participant's page, below), `ws_timeline.js`, `ws_cards.js`, `ws_peek.js`, `ws_reader.js`, `ws_way_in.js` (what chi has of a working-set item: below, The working set's reader), `no_contact_fill.js` (a text field that isn't a contact form: autocomplete off and a name with no contact word, against iOS Safari's AutoFill Contact bar; a template's fields carry the same attributes, and its spec checks the page's markup for them) and the `objectives_*.js` modules are new modules for that reason. The last four `block_*` draw fenced blocks (`block_watch.js` finds and watches them, `block_host.js` is its frame drawer for a bundle's renderers): [block-renderers.md](block-renderers.md). `inline_widgets.js` is its core drawer for `chi-ui` blocks, drawing `widget_walk.js`'s and `widget_picks.js`'s widgets in a shadow root styled by `widgets.css`: [inline-widgets.md](inline-widgets.md).
32
+ `session_fields.js`, `feature_gates.js`, `revise_stack.js`, `revise_switch.js`, `shell_command.js`, `stale_params.js`, `popover_modal.js`, `more_sheet.js`, `delete_sheet.js` (Deleting a chained session, below), `hash_intent.js` (what the hash asks for: session, all, start or keep), `worker_features.js`, `version_notices.js`, `owner_claim.js`, `owner_verify.js`, `composer_mode.js`, `strip_hidden.js`, `block_open.js`, `text_roots.js`, `block_source.js`, `block_frame.js`, `block_host.js`, `block_watch.js`, `card_stamps.js`, `recap_stamp.js` (a saved recap's place by its `opening_id` stamp, else its count), `inline_widgets.js`, `widget_walk.js`, `widget_picks.js`, `history_shape.js` (the history's shape, live against a reload: the e2e reload checks and the opt-in reload check share its normalizer and its `ACCEPTED` allowlist), `turn_pieces.js` (a finished turn's one order and its answer rule: the live hand-off's `handOffOrder` and `turnEnded`, and a reload's `turnHistoryNodes`), `reload_check.js` (the opt-in `web.reload_check`: after the stage's hand-off, the turn against a reload of it, the counts posted; the history without its cards and questions, and those as data: the page's `card_registry.js` against one seeded from the read, this turn's entries, a capped read's missing keys skipped), `turn_drawing.js` (a finished turn's drawing, `turn_drawings` in the show: its fold into steps and its end kind; `turn_block.js` draws it), `stage_stall.js` (the stage's quiet signal), `stage_quiet_clock.js`, `stage_dom.js`, `stage_answer.js`, `stage_pager.js`, `stage_cloud.js`, `stage_handoff.js`, `stage_place.js`, `stage_probe.js` (the stage's features: below, The stage's modules), `card_kinds.js` (what a card waits as, from its data: the kind, approval and folded-row text the stage's registry takes; the node's read is its cross-check), `card_registry.js` (the open session's cards as data, an observer of the stream's card events and a read's seed: Where state lives), `history_end.js` (the stage's one move of pieces to the history's end), `stage_opened.js` (a running turn opened in the history while a card waits: the lead-in bubble, the moves, the end fold), `stage_asking.js` (the stage's docked card and its fold: the docking and lead-in rules, the opening, a waiting card's own toggle, the folded row's text per kind, the fold's choice, reveal and the docked card's fold; `stage_view.js` wires it), `stage_waiting.js` (the stage's waiting cards as data, keyed by `data-qid` / `data-card-id`: kind, docked, approval, the stage's order, the shown card and its pager, the docked card's fold, kept for this tab in `chi_asking_fold:<session>`; `front`, `count`, `shown`, `blocking`), `stage_cards.js` (the cards that wait in the stage: `PENDING`, `ASKS`, `waitsInStage`, read by `stage_model.js placeKind`), `resync_reach.js` (a re-read that can't reach chi web keeps the drawn history; the status chip says retrying / offline, outside a turn), `session_sync.js` (the open session's sync: `select`, `resync` and its retries, the stream's life; the stream handle and the re-read bookkeeping are its own), `session_view.js` (the open session's view: `renderSessionView` draws a read, `forgetSession` resets the page for another session, `readTurnEnd`, `endTurnView`; app.js makes both right after the cards, each reaching the other and the later views through getters), `participant_main.js`, `participant_bar.js`, `viewer_self.js`, `participant_history.js` (a participant's ↑/↓ list), `stage_owner_wait.js`, `participant_revise.js` (a participant's page: The participant's page, below), `ws_timeline.js`, `ws_cards.js`, `ws_peek.js`, `ws_reader.js`, `ws_way_in.js` (what chi has of a working-set item: below, The working set's reader), `no_contact_fill.js` (a text field that isn't a contact form: autocomplete off and a name with no contact word, against iOS Safari's AutoFill Contact bar; a template's fields carry the same attributes, and its spec checks the page's markup for them) and the `objectives_*.js` modules are new modules for that reason. The last four `block_*` draw fenced blocks (`block_watch.js` finds and watches them, `block_host.js` is its frame drawer for a bundle's renderers): [block-renderers.md](block-renderers.md). `inline_widgets.js` is its core drawer for `chi-ui` blocks, drawing `widget_walk.js`'s and `widget_picks.js`'s widgets in a shadow root styled by `widgets.css`: [inline-widgets.md](inline-widgets.md).
33
33
 
34
34
  ## One page, every viewer
35
35
 
@@ -429,6 +429,26 @@ from `emptySlots`.** `npm run lint` holds it (`samagotchi/stage-size`: every `st
429
429
  - `stage_probe.js`: the perf probe (`?stage_probe=1`, kept for the tab, or `<body data-stage-probe="1">`: `measured`,
430
430
  `chiStageProbe.report()`), around
431
431
  `refresh`; `script/stage-perf-probe` drives it ([testing.md](../testing.md)).
432
+ - `stage_missing.js`: the "the session runs, the stage shows nothing of it" check — the bare status row
433
+ (`runningWithoutTurn`), the `data-stage-missing` mark and one console line per session visit. Its rules
434
+ (`missingReason`, `stageCovered`, `readCounts`) are pure; the numbers come from `getBoundingClientRect`.
435
+
436
+ ## A running session without a turn
437
+
438
+ A session whose status is running should always have its stage: the turn in progress, or, when the page has nothing
439
+ to draw, the bare status row ("running" plus Stop turn). `stage_missing.js` checks at the end of a render
440
+ (`session_view.js renderSessionView`), at the hand-off (`onHandedOff`) and at the end of a fold
441
+ (`stage_view.js clearStage`), then again on a resize, a composer that changed size or a status change. When the
442
+ session runs and `turnDom.holds()` is false, it calls `runningWithoutTurn(true)` (a no-op while a turn is held or
443
+ folding); a status that leaves running — through `turnEndStatus` or the hub, not only `setTurnRunning` — clears the
444
+ row. It also marks the stage `data-stage-missing`: `"1"` when it holds no turn, `"covered"` when it holds one but
445
+ its status row's rect is off the window or below the composer card's top edge (the user's own tall or folded
446
+ composer: reported, not fixed), and warns once per visit with counts only — `live_read`, whether `current_turn`
447
+ came, the replay's event types with their counts, the last replayed end event's turn id beside the running turn's,
448
+ the stage's and the composer's rects and the composer's saved floor and fold. The show's `live_read`
449
+ (`SessionShow#live_snapshot`: "ok", "none", "failed") says whether the snapshot read that fills the page came from
450
+ a live worker; chi web logs the why and the elapsed ms when it did not (bridge.md, The show). The e2e stage check
451
+ (`spec/e2e/support/fixtures.js`) reads the mark.
432
452
 
433
453
  ## The stage's height
434
454
 
@@ -524,8 +544,7 @@ that leave, `session_view.js endTurnView`'s cancel of a question still pending g
524
544
  `emptySlots` resets it (a resync's and `workerGone`'s reset too). Nothing on the page reads the slots back against
525
545
  it: the tests do (`stage_cuts_parity.test.js`, after every event and at each cut: no entry without its waiting card in
526
546
  the extras or the tail, no waiting card there without its entry; the e2e's stage check at each test's end, reading the
527
- registry off the stage's node, `#turnStage.chiWaiting()`). `stage_asking.js reconcileWaiting` is a no-op kept one
528
- release for a stale `stage_view.js` that still calls it.
547
+ registry off the stage's node, `#turnStage.chiWaiting()`).
529
548
  The registry's order is the stage's: blocking cards before the asking ones, arrival order within each, and `place`
530
549
  puts a blocking card before check-in's in the slot, so a live page and a reload agree whatever the replay's order. The
531
550
  asking form's card is the shown docked entry, the fold is the folded key (`stageCollapsed` compares keys); `opener`'s
data/docs/testing.md CHANGED
@@ -678,8 +678,30 @@ matched and those that match nothing: delete a stale one.
678
678
 
679
679
  **The thin client load budgets.** `spec/require_cycle_spec.rb` loads the attached TUI's files
680
680
  (`terminal_ui/attach_launcher`, `attached_loop`) and chi web's (`web/app`) in a fresh ruby and fails when either
681
- loads the turn loop (`kernel_loop`), the bundle updater (`memory_bundle/shipped_update`), or a tool that runs:
682
- `tools/execute`, `tools/builtins`, `tools/task_runtime`. A client that needs a tool's name or result text reads
683
- `ToolNames`; one that needs a session command's name or the built-ins' registry reads `SessionCommandCatalog`;
684
681
  task files and transcripts are `TaskFiles` and `TaskTranscript`. A require that breaks a budget is a sign the
685
682
  reader wants one of those, not the class.
683
+
684
+ ## The partial-use probes
685
+
686
+ A tech-debt audit round also runs `script/partial-use`, which reads the same files with the same Prism scan and
687
+ never loads them, and looks for two smells that hint an abstraction wants splitting:
688
+
689
+ - **`script/partial-use doors`** — a narrow door that drags a subtree. For every load-time `require` A → B, `added`
690
+ is the files B brings to A that A would not reach without that edge (B itself counted), and `names` the names A
691
+ takes from what B pulls in: the constants A names that are defined there, and the methods A calls on them. Ranked
692
+ by `added`, then by the fewest names. `--min-files` (1) drops the doors that add nothing, `--entry FILE` walks one
693
+ client's closure only (`bin/chi`, `lib/samagotchi/web/app.rb`), `--limit` (20) caps the rows. A reader under
694
+ `lib/samagotchi/testing/` is a spec helper, not a product path, so its doors are left out unless
695
+ `--include-testing` asks for them.
696
+ - **`script/partial-use wide`** — a wide class each client barely uses. Every namespace with at least `--min-public`
697
+ (15) public `def`s counts (`def self.x` and `module_function` are public; `attr_accessor` and `define_method` are
698
+ not read). Each file that names it, the files defining it apart, is a client, with `share` the public method names
699
+ it calls on it directly (`Const.m`) and `any` the same names called on any receiver in that file. A class used
700
+ through an object scores 0 in `share` by construction, so the ranking is by the smallest `any` share, then by the
701
+ widest class. `--min-clients` (2) drops a namespace only one file names, since one client is not a split worth
702
+ making, and the engine's own top-level `Samagotchi` module is not reported: its "public methods" are the whole
703
+ engine.
704
+
705
+ Matching is by name, never by execution, so every number is an upper bound: a row is a lead for a human to read, not
706
+ a finding. Like `script/dead-code` it is a report, always exits 0, and CI does not run it. Its spec is
707
+ `spec/script/partial_use_spec.rb`.
@@ -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 "output_formatter"
5
6
  require_relative "tool_call_parser"
6
7
 
@@ -22,11 +23,12 @@ module Samagotchi
22
23
  # @return [String] "" when nothing was visible
23
24
  def visible(text)
24
25
  text = text.to_s.scrub
25
- template_opened = !text.include?("<think>")
26
+ template_opened = !text.include?(ModelMarkup::THINK_OPEN)
26
27
  gemma = ToolCallParser::Gemma.new(ModelProfile.gemma4)
27
28
  text = gemma.strip_thought(text).gsub(OutputFormatter::QWEN_THINK_RE, "")
28
29
  text = text.sub(TEMPLATE_OPENED_THINK, "") if template_opened
29
- text = ToolCallParser.strip_calls(gemma.strip_tool_calls(text), "<tool_call>", "</tool_call>")
30
+ text = ToolCallParser.strip_calls(gemma.strip_tool_calls(text), ModelMarkup::TOOL_CALL_OPEN,
31
+ ModelMarkup::TOOL_CALL_CLOSE)
30
32
  OutputFormatter.strip_markup(text) # drops a thought cut off before it closed
31
33
  end
32
34
  end
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: samagotchi-system
3
- version: 0.174.0
3
+ version: 0.175.0
4
4
  scope: system
5
5
  description: Default system memories — identity, self map, config modification protocol, memory guide and the delegated-session rules
6
6
  files:
@@ -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
 
@@ -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.175.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -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"
@@ -692,10 +693,11 @@ module Samagotchi
692
693
  OutputFormatter::GEMMA_TOOL_CALL_RE, OutputFormatter::GEMMA_THOUGHT_RE)
693
694
  # A close with no open before it: what came before was thinking (the
694
695
  # raw loop saves prefill + response).
695
- BARE_CLOSES = ["</think>", "<channel|>"].freeze
696
+ BARE_CLOSES = [ModelMarkup::THINK_CLOSE, "<channel|>"].freeze
696
697
  # An open with no close after it (a cut-off thought, a tool call the
697
698
  # 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
699
+ OPENS = [ModelMarkup::THINK_OPEN, ModelMarkup::TOOL_CALL_OPEN, "<|tool_call>", "<|channel>",
700
+ "<|tool_response>", ModelMarkup::TOOL_RESPONSE_OPEN, "<|think|>"].freeze
699
701
 
700
702
  # A saved model message's raw content as a participant may read it:
701
703
  # 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";
@@ -359,7 +360,10 @@ const workingSet = document.body.dataset.workingSet === "1" && viewer.can("worki
359
360
  wsPreview?.attach(workingSet);
360
361
  document.body.classList.toggle("working-set", !!workingSet);
361
362
  // The running turn's DOM: the stage pinned above the composer
362
- // (stage_view.js), the turn block (turn_block.js) in its cloud.
363
+ // (stage_view.js), the turn block (turn_block.js) in its cloud. The
364
+ // running-with-no-turn check (stage_missing.js) hangs on its hooks, so it is
365
+ // made right after the stage.
366
+ let stageMissing = null;
363
367
  const turnDom = createStageView({
364
368
  historyEl,
365
369
  isNearBottom: () => atHistoryEnd(),
@@ -376,10 +380,18 @@ const turnDom = createStageView({
376
380
  // Stop turn in its status row (disabled until the request settles).
377
381
  onCancel: viewer.can("stop_any_turn") || viewer.can("stop_own_turn") ? () => handleCancel() : null,
378
382
  canCancel: () => !participant || participant.canCancel(), ownerWait: () => participant?.ownerWait() ?? null,
379
- onHandedOff: (handed) => reloadCheck.handedOff(handed),
383
+ onHandedOff: (handed) => { reloadCheck.handedOff(handed); stageMissing?.check(); },
384
+ onStageCleared: () => stageMissing?.check(),
380
385
  // The quiet signal (stage_stall.js): the stream, what the turn waits on, a joiner's step clock.
381
386
  streamLive: () => sessionSync.streamLive(), timingNote: () => liveTurn.timing.note, serverGen: () => liveTurn.serverGen,
382
387
  });
388
+ // The stage's own look at "running, nothing on it" (stage_missing.js): the
389
+ // bare status row, the mark and one console line per session visit. A status
390
+ // that leaves running, a resize or a composer that changed size looks again.
391
+ stageMissing = createStageMissing({ store, turnDom, composerEl });
392
+ store.on("infoBar", stageMissing.checkOnStatus);
393
+ window.addEventListener("resize", () => stageMissing.check());
394
+ if (window.ResizeObserver) new window.ResizeObserver(() => stageMissing.check()).observe(composerEl);
383
395
  // The open session's cards as data (card_registry.js: fed by the stream's card events and renderSessionView's seed).
384
396
  const cardRegistry = createCardRegistry();
385
397
  // The opt-in reload check (web.reload_check): a handed-off turn against a
@@ -91,9 +91,6 @@ const NOT_CARDS = (item) => item.kind !== "card" && item.kind !== "question";
91
91
  // @param render (data) => that read drawn as a reload draws it (a fragment)
92
92
  // @param cards () => the page's card registry (card_registry.js); without
93
93
  // it, the cards and questions are left out
94
- // @param place unused: an older app.js passes cards_offscreen.js's placer
95
- // @param capabilities () => the page's capabilities (unused now; an older
96
- // app.js passes it)
97
94
  // @param post (id, body) => the counts to chi web
98
95
  export function createReloadCheck({ enabled, sessionId, running, read, render, cards = null, post }) {
99
96
  // The hand-off's pieces (stage_view.js onHandedOff), in their order;
@@ -21,6 +21,8 @@
21
21
  // bubbles, cards bubbles.js, cards_place.js
22
22
  // cardRegistry the open session's cards as data (card_registry.js): seeded
23
23
  // from a read before its replay, reset with the session; null: none
24
+ // stageMissing the stage's running-with-no-turn check (stage_missing.js);
25
+ // null: no check (the render then says nothing)
24
26
  // markdown markdown_place.js (linkTextRefs, applyFinalMarkdown)
25
27
  // capabilities() the page's capabilities (card.js shownElsewhere, the history's cards)
26
28
  // page: {setReviseAnchor(anchor), renderInitRow(), setMarkdownWarning(warning),
@@ -51,7 +53,7 @@ export function createSessionView(deps) {
51
53
  const {
52
54
  store, historyEl, getSession,
53
55
  liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet = null, wsPreview = null, gapClock,
54
- bubbles, cards, markdown, capabilities, page, later, cardRegistry = null,
56
+ bubbles, cards, markdown, capabilities, page, later, cardRegistry = null, stageMissing = null,
55
57
  } = deps;
56
58
  const { makeUserBubble, addEndBubble, showGuardrailWarning, showRecap } = bubbles;
57
59
  const { placeSnapshotCards, upsertCard } = cards;
@@ -178,6 +180,12 @@ export function createSessionView(deps) {
178
180
  }
179
181
  // A turn ran out of iterations and waits for a yes or no.
180
182
  if (data.continue_offer) questionCards.renderContinue(data.continue_offer);
183
+ // The read is drawn: a running session whose stage holds no turn keeps its
184
+ // bare status row and marks itself (stage_missing.js).
185
+ if (stageMissing) {
186
+ stageMissing.note(data);
187
+ stageMissing.check();
188
+ }
181
189
  // A whole view drawn: the composer and the bar once more (the working
182
190
  // set's seed may change the bar's chip).
183
191
  store.batch(() => {
@@ -124,12 +124,6 @@ export function createStageAsking({
124
124
  opener.open(handOffOrder({ prompt: promptEl(), block: blockEl, extras: rows }), { follow });
125
125
  }
126
126
 
127
- // A no-op kept one release for a mixed cache (remove in the next one): a
128
- // stale stage_view.js (0.172.1's) calls it at the end of each refresh. The
129
- // drift check it ran is the tests' now (stage_cuts_parity.test.js
130
- // crossCheck, the e2e's stage check).
131
- function reconcileWaiting() {}
132
-
133
127
  // An opened turn's cards that stopped waiting go into the history: one
134
128
  // with a lead-in under it (also after the turn's end, so a card
135
129
  // cancelled by Stop turn sits there), another one at the history's end
@@ -273,7 +267,7 @@ export function createStageAsking({
273
267
  }
274
268
 
275
269
  return {
276
- askingGen, asksOf, askedFor, askedText, docks, leadInText, openTurn, reconcileWaiting, settleCards, askingCard, cardOf, foldedText, markOwnToggles,
270
+ askingGen, asksOf, askedFor, askedText, docks, leadInText, openTurn, settleCards, askingCard, cardOf, foldedText, markOwnToggles,
277
271
  isCollapsed, trackFold, drawCollapsed, applyCollapsed, setCollapsed,
278
272
  // A ref's "show in turn" opens a collapsed stage for this turn only.
279
273
  reveal() {
@@ -0,0 +1,150 @@
1
+ // A running session whose stage shows nothing of its turn (docs/internals/web-frontend.md,
2
+ // "A running session without a turn"). At the points a turn could have been
3
+ // drawn — the end of a render (session_view.js), the hand-off and the end of a
4
+ // fold (stage_view.js's clearStage) — and again on a resize, a composer that
5
+ // changed size or a status change, it does two things:
6
+ // the safety net: the session's status runs and the stage holds no turn, so
7
+ // the stage keeps its bare status row ("running", Stop turn) instead of
8
+ // vanishing (runningWithoutTurn, stage_view.js), and a status that leaves
9
+ // running takes that row with it;
10
+ // the diagnostic: the stage is marked `data-stage-missing` ("1" for no turn,
11
+ // "covered" for a turn the composer card is over) and, once per session
12
+ // visit, a console.warn with counts only — never a prompt, a message or an
13
+ // answer — saying what the read had (live_read, current_turn, the replay's
14
+ // event types and their counts, the last replayed end event's turn id beside
15
+ // the running turn's) and where the stage sat (its status row's top and
16
+ // bottom, the composer's top, the window's height, the composer's saved floor
17
+ // and fold). The covered case is reported only: a stage the user made tall is
18
+ // their own doing, and the net is for a stage that shows nothing at all.
19
+ //
20
+ // The numbers come from getBoundingClientRect at the call; the pure functions
21
+ // take them as arguments, so a spec can pass its own. Its own module: new
22
+ // exports go in new modules (web-frontend.md).
23
+ import { readStored } from "./storage.js";
24
+ import { COMPOSER_FOLD_KEY } from "./composer_fold.js";
25
+ import { GRIP_KEY } from "./composer_grip.js";
26
+
27
+ // The replay events that end a turn.
28
+ const ENDS = ["turn_completed", "turn_canceled", "turn_failed"];
29
+
30
+ // What a show read said, in counts.
31
+ export function readCounts(data = {}) {
32
+ const replay = Array.isArray(data.replay) ? data.replay : [];
33
+ const events = {};
34
+ let lastEndTurn = null;
35
+ for (const event of replay) {
36
+ events[event.type] = (events[event.type] || 0) + 1;
37
+ if (ENDS.includes(event.type)) lastEndTurn = event.turn_id ?? null;
38
+ }
39
+ return {
40
+ liveRead: data.live_read ?? null,
41
+ currentTurn: data.current_turn?.turn_id ?? null,
42
+ replay: replay.length,
43
+ events,
44
+ lastEndTurn,
45
+ };
46
+ }
47
+
48
+ // The stage's status row out of sight: wholly above or below the window, or
49
+ // below the composer card's top edge (the dock puts the stage above it:
50
+ // index.html, .turn-stage). A hidden stage is hidden, not covered; a row with
51
+ // no measured height (a stub, a stage not yet laid out) says nothing.
52
+ export function stageCovered({ hidden, stageTop, stageBottom, composerTop, viewport }) {
53
+ if (hidden) return false;
54
+ if (stageBottom > stageTop && (stageBottom <= 0 || stageTop >= viewport)) return true;
55
+ return composerTop !== null && stageTop > composerTop;
56
+ }
57
+
58
+ // Why the stage shows nothing of a turn, or null when it shows it: "none" (no
59
+ // turn in the stage), "covered" (it holds one, out of sight).
60
+ export function missingReason({ status, holds, hidden, stageTop, stageBottom, composerTop, viewport }) {
61
+ if (status !== "running") return null;
62
+ if (!holds) return "none";
63
+ return stageCovered({ hidden, stageTop, stageBottom, composerTop, viewport }) ? "covered" : null;
64
+ }
65
+
66
+ // The console line: counts, no text from the session.
67
+ export function missingLine({ session, reason, counts, stage, composer }) {
68
+ const events = Object.entries(counts.events || {}).map(([type, n]) => `${type}=${n}`).join(" ") || "none";
69
+ return `stage-missing ${session || "none"} (${reason}) live_read=${counts.liveRead ?? "unknown"} ` +
70
+ `current_turn=${counts.currentTurn ?? "none"} replay=${counts.replay} events=${events} ` +
71
+ `last_end=${counts.lastEndTurn ?? "none"} vs turn=${counts.currentTurn ?? "none"} ` +
72
+ `stage_row=${stage.stageTop}..${stage.stageBottom} composer_top=${stage.composerTop} window=${stage.viewport} ` +
73
+ `composer_floor=${composer.floor ?? "unset"} composer_fold=${composer.fold ?? "unset"}`;
74
+ }
75
+
76
+ // +store+, +turnDom+ the page's views; +composerEl+ the composer card's box;
77
+ // +win+ the page's window; +warn+ where the line goes.
78
+ // @return {note(data), check()}
79
+ export function createStageMissing({ store, turnDom, composerEl, win = globalThis, warn = (line) => console.warn(line) }) {
80
+ const warned = new Set();
81
+ let counts = null;
82
+
83
+ function geometry() {
84
+ const stage = turnDom.root;
85
+ const row = stage.querySelector(".ts-status") || stage;
86
+ const stageRect = row.getBoundingClientRect?.() || { top: 0, bottom: 0 };
87
+ const composerRect = composerEl?.getBoundingClientRect?.() || { top: null, bottom: null };
88
+ return {
89
+ hidden: !!stage.hidden,
90
+ stageTop: stageRect.top ?? 0,
91
+ stageBottom: stageRect.bottom ?? 0,
92
+ // A folded composer shows nothing (composer.css), so it has no top to
93
+ // cover with; neither has one not laid out yet.
94
+ composerTop: composerRect.bottom > composerRect.top ? composerRect.top : null,
95
+ viewport: win?.innerHeight ?? 0,
96
+ };
97
+ }
98
+
99
+ // The stage's state at one of the points a turn could have been drawn.
100
+ function check() {
101
+ const stage = turnDom.root;
102
+ const status = store.current.status;
103
+ if (status !== "running") {
104
+ delete stage.dataset.stageMissing;
105
+ // A status that left running takes the bare row with it: setTurnRunning
106
+ // is not the only writer (turnEndStatus and the hub change the status too).
107
+ turnDom.runningWithoutTurn?.(false);
108
+ return null;
109
+ }
110
+ // The safety net: a session that runs keeps its status row (running and
111
+ // Stop turn) rather than showing nothing. It is a no-op when the stage
112
+ // holds or is folding a turn (stage_view.js's runningWithoutTurn).
113
+ if (!turnDom.holds()) turnDom.runningWithoutTurn?.(true);
114
+ const where = geometry();
115
+ const reason = missingReason({ status, holds: turnDom.holds(), ...where });
116
+ if (!reason) {
117
+ delete stage.dataset.stageMissing;
118
+ return null;
119
+ }
120
+ stage.dataset.stageMissing = reason === "covered" ? "covered" : "1";
121
+ const session = store.selected;
122
+ if (!warned.has(session)) {
123
+ warned.add(session);
124
+ warn(missingLine({
125
+ session, reason, counts: counts || readCounts({}),
126
+ stage: where,
127
+ composer: {
128
+ top: stage.composerTop,
129
+ floor: readStored(GRIP_KEY),
130
+ fold: readStored(COMPOSER_FOLD_KEY),
131
+ },
132
+ }));
133
+ }
134
+ return reason;
135
+ }
136
+
137
+ // A status write redraws the bar: only a change needs the stage looked at,
138
+ // and only one away from running. A turn that runs is drawn by the render,
139
+ // the hand-off or the fold; a status that comes to running before the replay
140
+ // is drawn would warn about a stage not yet filled.
141
+ let lastStatus = null;
142
+ function checkOnStatus() {
143
+ if (store.current.status === lastStatus) return null;
144
+ lastStatus = store.current.status;
145
+ if (store.current.status === "running") return null;
146
+ return check();
147
+ }
148
+
149
+ return { note: (data) => { counts = readCounts(data); }, check, checkOnStatus };
150
+ }
@@ -25,7 +25,8 @@
25
25
  // the cloud stage_cloud.js's, the docked card and the fold stage_asking.js's,
26
26
  // its pager stage_pager.js's, the waiting cards as data stage_waiting.js's,
27
27
  // the answer's reading stage_answer.js's, the quiet signal stage_stall.js's
28
- // and its clocks stage_quiet_clock.js's, the perf probe stage_probe.js's. A new
28
+ // and its clocks stage_quiet_clock.js's, the perf probe stage_probe.js's and the
29
+ // running-with-no-turn check stage_missing.js's. A new
29
30
  // stage feature goes into its own stage_<feature>.js, wired here in a few
30
31
  // lines; each module resets itself from emptySlots.
31
32
  import { createTurnBlock } from "./turn_block.js";
@@ -69,6 +70,8 @@ const FLASH_MS = 4000;
69
70
  // status row's Stop turn (a promise of the cancel request; the button is
70
71
  // disabled until it settles); null: no Stop turn. +onHandedOff+({pieces,
71
72
  // immediate}): a turn's pieces reached the history (reload_check.js).
73
+ // +onStageCleared+(): the stage just went empty (the fold's end, a release):
74
+ // app.js's stage_missing.js looks at it then.
72
75
  // The quiet signal's inputs (stage_quiet_clock.js): +clock+() the page's time,
73
76
  // +streamLive+() the session's stream is open, +timingNote+() what the turn
74
77
  // waits on (live_timing.js note), +serverGen+() a joiner's generation.
@@ -78,7 +81,7 @@ const FLASH_MS = 4000;
78
81
  // factory (stage_waiting.js; a test passes an older one's shape).
79
82
  export function createStageView({
80
83
  historyEl, isNearBottom: historyNearBottom, sawText, sessionId, dockEl, centerEl, taskStop = null,
81
- renderMarkdown, linkRefs, workingSet = null, onCancel = null, onHandedOff = null,
84
+ renderMarkdown, linkRefs, workingSet = null, onCancel = null, onHandedOff = null, onStageCleared = null,
82
85
  clock = () => Date.now(), streamLive = () => true, timingNote = () => "", serverGen = () => null,
83
86
  canCancel = () => true, ownerWait = () => null, createWaiting = createStageWaiting,
84
87
  }) {
@@ -521,7 +524,8 @@ export function createStageView({
521
524
  view.reset();
522
525
  }
523
526
 
524
- // The stage empty and hidden, its frame free.
527
+ // The stage empty and hidden, its frame free. The page then looks at it
528
+ // (stage_missing.js): a session that still runs gets its bare status row back.
525
529
  function clearStage() {
526
530
  dropBare();
527
531
  handoff.cancelFold();
@@ -529,6 +533,7 @@ export function createStageView({
529
533
  stage.hidden = true;
530
534
  frame.frameFree();
531
535
  ask.unreveal();
536
+ onStageCleared?.();
532
537
  }
533
538
 
534
539
  function release() {
@@ -26,8 +26,9 @@ module Samagotchi
26
26
  # worker's turn snapshot and state snapshot (both nil without one), the
27
27
  # messages shown (the snapshot's, else the file's) and the stream cursor
28
28
  # the page goes on from (+event_seq+, and the snapshot's +event_id+
29
- # `<seq>-<epoch>`). Each assembler makes its own payload from it.
30
- ShowReads = Data.define(:id, :session, :turn_snapshot, :state, :event_seq, :event_id, :raw_messages) do
29
+ # `<seq>-<epoch>`), and how the snapshot read went (+live_read+: "ok",
30
+ # "failed" or "none"). Each assembler makes its own payload from it.
31
+ ShowReads = Data.define(:id, :session, :turn_snapshot, :state, :event_seq, :event_id, :raw_messages, :live_read) do
31
32
  # The turn in progress, as the worker's snapshot has it (nil: none).
32
33
  def current_turn = turn_snapshot && turn_snapshot["current_turn"]
33
34
 
@@ -79,7 +80,7 @@ module Samagotchi
79
80
  # behind it, all at one event_seq the client streams on from.
80
81
  # @return [ShowReads]
81
82
  def show_reads(id, session)
82
- live = bridge_get_json(id, "snapshot")
83
+ live, live_read = live_snapshot(id)
83
84
  turn_snapshot = live && live["snapshot"]
84
85
  state = live && live["session_state_snapshot"]
85
86
  ShowReads.new(
@@ -88,10 +89,42 @@ module Samagotchi
88
89
  # The stream cursor `<seq>-<epoch>`: a later worker resets it
89
90
  # instead of taking the seq as its own. Only the snapshot has it.
90
91
  event_id: turn_snapshot && turn_snapshot["event_id"],
91
- raw_messages: live_or_saved(turn_snapshot, "messages") { session.messages }
92
+ raw_messages: live_or_saved(turn_snapshot, "messages") { session.messages },
93
+ live_read: live_read
92
94
  )
93
95
  end
94
96
 
97
+ # The live worker's turn snapshot and what its read did: [snapshot,
98
+ # live_read] — "ok" when a snapshot came, "none" when no worker owns the
99
+ # session, "failed" when a live worker's Bridge answered with none. One
100
+ # GET of the Bridge, never two: a worker that is busy is hit once, not
101
+ # twice. The page's stage_missing.js reads live_read, so a running session
102
+ # whose stage shows no turn (this read had no current_turn, and so no
103
+ # replay and no stream cursor) is not mistaken for one whose stream
104
+ # replayed the turn's end. A failed read logs, at debug level, the why from
105
+ # that same request (no reply: a refused connect, a timeout, a cut reply;
106
+ # 200 with no JSON body; another status) and the elapsed ms.
107
+ # @return [Array(Hash, String)]
108
+ def live_snapshot(id)
109
+ return [nil, "none"] unless bridge_client(id)
110
+
111
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
112
+ status, body = bridge_get(id, "snapshot")
113
+ live = status == 200 && body.is_a?(Hash) ? body : nil
114
+ return [live, "ok"] if live
115
+
116
+ ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
117
+ why = if status.nil?
118
+ "no reply"
119
+ elsif status == 200
120
+ "no snapshot in the answer"
121
+ else
122
+ "status #{status}"
123
+ end
124
+ Log.debug(:web, "live_snapshot_failed", sid: id, why: why, ms: ms)
125
+ [nil, "failed"]
126
+ end
127
+
95
128
  # Every finished turn of +reads+ drawn from a line (a real one, else
96
129
  # one made from its messages, #drawn_lines): its items are stamped,
97
130
  # and its drawing goes in turn_drawings. The running turn has none yet.
@@ -124,6 +157,11 @@ module Samagotchi
124
157
  **turn_drawings_field(drawn, messages),
125
158
  failed_turn: failed_turn_for(session, raw_messages),
126
159
  current_turn: reads.current_turn,
160
+ # What the live snapshot read gave: "ok", "none" (no live worker) or
161
+ # "failed" (a live worker answered with no snapshot): the page's
162
+ # stage_missing.js tells a turn that never reached the stage from one
163
+ # whose stream replayed its end (docs/internals/bridge.md, The show).
164
+ live_read: reads.live_read,
127
165
  # The page's join: the turn in progress and the queue behind it as
128
166
  # the live events that draw them (TurnAccumulator.join_events, one
129
167
  # unfold, here: any worker's snapshot works).
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: samagotchi
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.174.0
4
+ version: 0.175.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dmitry Dedov
@@ -553,6 +553,7 @@ files:
553
553
  - lib/samagotchi/model_catalog.rb
554
554
  - lib/samagotchi/model_list_store.rb
555
555
  - lib/samagotchi/model_lookup.rb
556
+ - lib/samagotchi/model_markup.rb
556
557
  - lib/samagotchi/model_match.rb
557
558
  - lib/samagotchi/model_notes.rb
558
559
  - lib/samagotchi/model_overlay.rb
@@ -944,7 +945,6 @@ files:
944
945
  - lib/samagotchi/web/public/card_kinds.js
945
946
  - lib/samagotchi/web/public/card_registry.js
946
947
  - lib/samagotchi/web/public/card_stamps.js
947
- - lib/samagotchi/web/public/cards_offscreen.js
948
948
  - lib/samagotchi/web/public/cards_place.js
949
949
  - lib/samagotchi/web/public/chains.js
950
950
  - lib/samagotchi/web/public/chip_popover.js
@@ -1069,6 +1069,7 @@ files:
1069
1069
  - lib/samagotchi/web/public/stage_dom.js
1070
1070
  - lib/samagotchi/web/public/stage_frame.js
1071
1071
  - lib/samagotchi/web/public/stage_handoff.js
1072
+ - lib/samagotchi/web/public/stage_missing.js
1072
1073
  - lib/samagotchi/web/public/stage_model.js
1073
1074
  - lib/samagotchi/web/public/stage_opened.js
1074
1075
  - lib/samagotchi/web/public/stage_owner_wait.js
@@ -1,69 +0,0 @@
1
- // A snapshot's cards placed into a holder that is not the page (cards_offscreen.js):
2
- // the old reload check's placer. Nothing imports it now (reload_check.js compares
3
- // the turn's cards as data, card_registry.js); it stays one release for a stale
4
- // app.js that still imports it (a 404 would blank the page), then it goes.
5
- //
6
- // It is the real placer, not a copy: createCardsPlace, createBubbles and
7
- // createQuestionCards over a detached holder, with every page hook made inert:
8
- // no stage (turnDom answers "nothing holds it", and has no settleFold/settleWaiting
9
- // — cards_place.js calls those with `?.`), no scroll, no hint, no info bar, no
10
- // session id, no api. Nothing outside +holder+ is read or written; the page's
11
- // questionCards, its turnDom and its appendToHistory are never touched.
12
- import { createBubbles } from "./bubbles.js";
13
- import { createCardsPlace } from "./cards_place.js";
14
- import { createQuestionCards } from "./question_cards.js";
15
- import { splitSnapshotCards } from "./card.js";
16
-
17
- // +cards+ the read's snapshot (data.cards); +capabilities+ the page's, for the
18
- // notices it shows elsewhere (splitSnapshotCards); +answers+ whether this viewer
19
- // may answer cards at all (viewer.js answer_cards).
20
- export function placeCardsOffscreen(holder, cards, { capabilities = null, answers = true, doc = globalThis.document } = {}) {
21
- const shared = {
22
- historyEl: holder,
23
- findInTurnRoots: (selector) => [...holder.querySelectorAll(selector)],
24
- isNearBottom: () => false,
25
- selected: () => null,
26
- clientId: null,
27
- };
28
- // No running turn here: nothing holds a piece, nothing takes a card or a steer.
29
- const turnDom = { card: () => false, steer: () => false, holds: () => false };
30
- const bubbles = createBubbles({
31
- ...shared,
32
- appendToHistory: (el) => holder.appendChild(el),
33
- turnDom,
34
- shownTexts: { shows: () => false },
35
- liveTurn: { timing: { el: null } },
36
- });
37
- const questionCards = createQuestionCards({
38
- ...shared,
39
- sessionId: () => null,
40
- place: (card) => { holder.appendChild(card); return false; },
41
- scrollToEnd: () => {},
42
- removeHintIfEmpty: () => {},
43
- askingText: () => "",
44
- renderMarkdown: () => Promise.resolve(null),
45
- onPending: () => {},
46
- onSettled: () => {},
47
- answers,
48
- doc,
49
- // A card's button is inert here: a placed card is a comparison, not a live ask.
50
- api: {
51
- sendAnswer: () => Promise.reject(new Error("offscreen card")),
52
- dismissQuestion: () => Promise.reject(new Error("offscreen card")),
53
- sendCommand: () => Promise.reject(new Error("offscreen card")),
54
- },
55
- });
56
- const place = createCardsPlace({
57
- ...shared,
58
- turnDom,
59
- questionCards,
60
- bubbles,
61
- followWokenWorker: () => {},
62
- api: {
63
- getSession: () => Promise.reject(new Error("offscreen card")),
64
- sendCommand: () => Promise.reject(new Error("offscreen card")),
65
- },
66
- });
67
- place.placeSnapshotCards(splitSnapshotCards(cards, capabilities).placed, { before: null });
68
- return holder;
69
- }