samagotchi 0.164.0 → 0.166.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 (100) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +88 -1
  3. data/docs/architecture.md +7 -5
  4. data/docs/cli.md +23 -12
  5. data/docs/configuration.md +8 -2
  6. data/docs/guardrails.md +19 -18
  7. data/docs/internals/block-renderers.md +1 -1
  8. data/docs/internals/bridge.md +10 -3
  9. data/docs/internals/bundles.md +4 -2
  10. data/docs/internals/inline-widgets.md +8 -1
  11. data/docs/internals/remote-sessions.md +1 -1
  12. data/docs/internals/web-frontend.md +73 -13
  13. data/docs/memory.md +12 -7
  14. data/docs/plugins.md +6 -4
  15. data/docs/releasing.md +17 -4
  16. data/docs/scheduling.md +25 -3
  17. data/docs/sessions.md +12 -10
  18. data/docs/testing.md +37 -4
  19. data/lib/samagotchi/block_renderers.rb +3 -6
  20. data/lib/samagotchi/bridge/card_store.rb +2 -1
  21. data/lib/samagotchi/bridge/turn_accumulator.rb +7 -8
  22. data/lib/samagotchi/bridge.rb +45 -3
  23. data/lib/samagotchi/bundle_command/installed_check.rb +2 -1
  24. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  25. data/lib/samagotchi/chi_home.rb +44 -2
  26. data/lib/samagotchi/client_id.rb +34 -3
  27. data/lib/samagotchi/compat.rb +34 -0
  28. data/lib/samagotchi/context_command.rb +3 -0
  29. data/lib/samagotchi/context_providers.rb +5 -6
  30. data/lib/samagotchi/context_sources.rb +2 -2
  31. data/lib/samagotchi/continue_intent.rb +50 -5
  32. data/lib/samagotchi/events.rb +4 -4
  33. data/lib/samagotchi/extension_load.rb +2 -1
  34. data/lib/samagotchi/guardrails/approvals.rb +36 -9
  35. data/lib/samagotchi/guardrails/child_boundary.rb +7 -27
  36. data/lib/samagotchi/guardrails/rules.rb +11 -9
  37. data/lib/samagotchi/guardrails/targets.rb +3 -4
  38. data/lib/samagotchi/inline_widgets.rb +16 -1
  39. data/lib/samagotchi/memory_bundle/provenance.rb +46 -4
  40. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  41. data/lib/samagotchi/memory_command.rb +3 -0
  42. data/lib/samagotchi/memory_orphans.rb +4 -7
  43. data/lib/samagotchi/memory_paths.rb +64 -7
  44. data/lib/samagotchi/memory_usage.rb +1 -1
  45. data/lib/samagotchi/plugin/sessions.rb +8 -3
  46. data/lib/samagotchi/project_command.rb +4 -1
  47. data/lib/samagotchi/project_id_clash.rb +37 -26
  48. data/lib/samagotchi/project_init.rb +24 -7
  49. data/lib/samagotchi/reply_wait/poll.rb +4 -14
  50. data/lib/samagotchi/reply_wait.rb +0 -23
  51. data/lib/samagotchi/run_options.rb +1 -1
  52. data/lib/samagotchi/schedules.rb +124 -106
  53. data/lib/samagotchi/send_command.rb +71 -18
  54. data/lib/samagotchi/session.rb +3 -2
  55. data/lib/samagotchi/session_access/local.rb +19 -2
  56. data/lib/samagotchi/session_access/remote.rb +13 -17
  57. data/lib/samagotchi/session_chain/links.rb +109 -0
  58. data/lib/samagotchi/session_chain.rb +7 -19
  59. data/lib/samagotchi/session_continue.rb +138 -54
  60. data/lib/samagotchi/session_inbox.rb +1 -1
  61. data/lib/samagotchi/session_inbox_delivery.rb +57 -38
  62. data/lib/samagotchi/session_manager/delivery.rb +104 -18
  63. data/lib/samagotchi/session_manager/removal.rb +13 -7
  64. data/lib/samagotchi/session_manager.rb +1 -0
  65. data/lib/samagotchi/session_retention.rb +20 -10
  66. data/lib/samagotchi/session_setup.rb +31 -1
  67. data/lib/samagotchi/state_format.rb +12 -8
  68. data/lib/samagotchi/terminal_ui/attach_launcher.rb +6 -7
  69. data/lib/samagotchi/terminal_ui.rb +20 -9
  70. data/lib/samagotchi/tools/delegate.rb +2 -3
  71. data/lib/samagotchi/verify_fresh.rb +4 -1
  72. data/lib/samagotchi/version.rb +1 -1
  73. data/lib/samagotchi/web/public/activity.js +2 -2
  74. data/lib/samagotchi/web/public/app.js +28 -21
  75. data/lib/samagotchi/web/public/auth_lost.js +3 -1
  76. data/lib/samagotchi/web/public/bar_fold.js +293 -0
  77. data/lib/samagotchi/web/public/card.js +1 -1
  78. data/lib/samagotchi/web/public/chip_popover.js +5 -1
  79. data/lib/samagotchi/web/public/composer_mode.js +5 -7
  80. data/lib/samagotchi/web/public/delivery_line.js +19 -4
  81. data/lib/samagotchi/web/public/index.html +242 -94
  82. data/lib/samagotchi/web/public/info_bar.js +28 -16
  83. data/lib/samagotchi/web/public/info_bar_model.js +76 -2
  84. data/lib/samagotchi/web/public/live_timing.js +3 -0
  85. data/lib/samagotchi/web/public/more_sheet.js +98 -40
  86. data/lib/samagotchi/web/public/resync_reach.js +59 -0
  87. data/lib/samagotchi/web/public/session_fields.js +1 -0
  88. data/lib/samagotchi/web/public/session_state.js +5 -0
  89. data/lib/samagotchi/web/public/stage_frame.js +4 -2
  90. data/lib/samagotchi/web/public/stage_stall.js +134 -0
  91. data/lib/samagotchi/web/public/stage_view.js +78 -7
  92. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  93. data/lib/samagotchi/web/public/turn_events.js +0 -122
  94. data/lib/samagotchi/web/public/turn_model.js +1 -1
  95. data/lib/samagotchi/web/public/widget_picks.js +18 -3
  96. data/lib/samagotchi/web/session_control.rb +15 -2
  97. data/lib/samagotchi/web/session_create.rb +4 -2
  98. data/lib/samagotchi/web/token.rb +2 -2
  99. data/lib/samagotchi/web/update_check.rb +27 -8
  100. metadata +5 -1
@@ -173,6 +173,20 @@ module Samagotchi
173
173
  end
174
174
  end
175
175
 
176
+ # The setup a new one-shot session starts with (a resumed one keeps
177
+ # its own; #run lays --llm-context* and --thinking over it). It is made
178
+ # with Session.new_session, not spawn_session, so config's default
179
+ # toolkit is filled in here.
180
+ # @return [SessionSetup]
181
+ def new_session_setup
182
+ llm_context = LLMContextOverride.update(nil, @llm_context_words) unless @llm_context_words.empty?
183
+ setup = SessionSetup.from_request(memories: @requested_memories, muted: @muted_memory_names,
184
+ llm_context: llm_context, thinking: @thinking_word,
185
+ appended_prompt_files: @appended_prompt_files, toolkit: @toolkit,
186
+ settings: @session_settings, parent_answers: @parent_answers)
187
+ @toolkit ? setup : setup.with(toolkit: Toolkit.configured, toolkit_origin: "default")
188
+ end
189
+
176
190
  # Run the -p prompt as one turn (a session command as that command),
177
191
  # then return; with no prompt, nothing (no session is made).
178
192
  # @return [Symbol, nil] :turn_failed when the turn failed or the command
@@ -192,18 +206,15 @@ module Samagotchi
192
206
  model_name: @effective_model_name,
193
207
  working_directory: Dir.pwd,
194
208
  scratch: @scratch,
195
- setup: SessionSetup.new(appended_prompt_files: @appended_prompt_files, toolkit: @toolkit || Toolkit.configured,
196
- toolkit_origin: @toolkit ? "chosen" : "default", settings: @session_settings,
197
- parent_answers: @parent_answers, preloaded_memory_names: @requested_memories,
198
- muted_memory_names: @muted_memory_names)
209
+ setup: new_session_setup
199
210
  ))
200
- # --llm-context*: the session's own values, over a resumed one's.
201
- # Saved at once on a resumed one: leaving before a turn keeps them.
202
- # --thinking: the session's own level, saved at once on a resumed one.
203
- unless @llm_context_words.empty? && @thinking_word.nil?
211
+ # --llm-context* and --thinking on a resumed one: the session's own
212
+ # values, over its own (a new one's are in its setup). Saved at once:
213
+ # leaving before a turn keeps them.
214
+ if @resume_session && !(@llm_context_words.empty? && @thinking_word.nil?)
204
215
  session.llm_context = LLMContextOverride.update(session.llm_context, @llm_context_words) unless @llm_context_words.empty?
205
216
  session.thinking = Thinking.session_level(@thinking_word) if @thinking_word
206
- session.save if @resume_session
217
+ session.save
207
218
  end
208
219
  warn_toolkit_flags_ignored(session) if @resume_session
209
220
  claim_session!(session.id) unless @owner_lock
@@ -397,9 +397,8 @@ module Samagotchi
397
397
  # whether it runs as a turn of its own (the child idle, or its
398
398
  # running turn ended before taking it) or a running turn's drain
399
399
  # merges it (that turn's end is its answer: the drain's merge record,
400
- # or ReplyWait's inference for a 0.156 child, ReplyWait::Poll#
401
- # follow_merge). Only from a worker that names turn_ids; nil
402
- # otherwise: the wait takes the next reply.
400
+ # ReplyWait::Poll#follow_merge). Only from a worker that names
401
+ # turn_ids; nil otherwise: the wait takes the next reply.
403
402
  # @return [String, nil]
404
403
  def self.follow_up_turn(id, enqueued_id, state_dir:)
405
404
  ReplyWait.turn_ids?(Session.session_dir(id, state_dir: state_dir)) ? enqueued_id : nil
@@ -86,9 +86,12 @@ module Samagotchi
86
86
  locked(dir) do
87
87
  refuse_busy!(parent.id, of, author, state_dir)
88
88
 
89
+ # The parent's own parent_answers, as the delegate tool's child
90
+ # takes it: the child's answers are held at least as tight.
89
91
  child = spawn.call(prompt: prompt_for(anchor.quote), working_directory: parent.working_directory,
90
92
  model_name: parent.model_name,
91
- setup: SessionSetup.new(preloaded_memory_names: [Session::DELEGATE_MEMORY]),
93
+ setup: SessionSetup.new(preloaded_memory_names: [Session::DELEGATE_MEMORY],
94
+ parent_answers: parent.parent_answers),
92
95
  parent_id: parent.id, delegate: true, verify_fresh: origin, state_dir: state_dir,
93
96
  client_id: ClientId.delegate(parent.id))
94
97
  append_ledger(dir, { "child_id" => child.id, "of" => of, "author" => author, "at" => Time.now.utc.iso8601(3) })
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Samagotchi
4
- VERSION = "0.164.0"
4
+ VERSION = "0.166.0"
5
5
  # Sent as the User-Agent of every HTTP request chi makes.
6
6
  USER_AGENT = "chi/#{VERSION}"
7
7
  end
@@ -32,8 +32,8 @@ export function newActivity() {
32
32
 
33
33
  // A row's fields beyond its params, as the server's ToolRowFields lists
34
34
  // them; each list is copied in one place per path (addStarted, addCompleted's
35
- // synthesized row, turn_events.js snapshotEvents), so a new field is added
36
- // here. ACTIVITY_FIELDS: top-level on tool_call_started, inside `activity`
35
+ // synthesized row; a join's replay is the server's, TurnAccumulator), so a
36
+ // new field is added here. ACTIVITY_FIELDS: top-level on tool_call_started, inside `activity`
37
37
  // on tool_call_completed. EVENT_FIELDS: top-level on both.
38
38
  // title: what the call did in a few words (the server's tool title: a
39
39
  // project-relative path, a command without its "cd … &&"); rows show
@@ -38,7 +38,8 @@ import { createParticipantsControl } from "./participants_panel.js";
38
38
  import { createSettingsControl } from "./settings_chip.js";
39
39
  import { renderInfoBar } from "./info_bar.js";
40
40
  import { createMoreSheet } from "./more_sheet.js";
41
- import { sessionBar } from "./info_bar_model.js";
41
+ import { createBarFold } from "./bar_fold.js";
42
+ import { barItemKeys, sessionBar } from "./info_bar_model.js";
42
43
  import { createShownTexts } from "./shown_texts.js";
43
44
  import { emptySessionState, sessionStateFrom } from "./session_state.js";
44
45
  import { sessionFieldsFrom } from "./session_payload.js";
@@ -104,7 +105,8 @@ import { answerRefsOf, applyFinalAnswer, pairAnswerRefs, setAnswerRefs } from ".
104
105
  import { installRefClicks } from "./refs.js";
105
106
  import { linkRefs, touchedFiles } from "./ref_scan.js";
106
107
  import { DONE_MS, applyInitEvent, dropDone, fadeDone, initRowTemplate, newInitTasks, seedInitTasks } from "./init_row.js";
107
- import { newClientId, resyncRetry, snapshotEvents, streamDropEnd } from "./turn_events.js";
108
+ import { newClientId, resyncRetry, streamDropEnd } from "./turn_events.js";
109
+ import { createResyncReach } from "./resync_reach.js";
108
110
  import { applyConfirm, keptCommandBubbles, restoreCommandBubbles } from "./commands.js";
109
111
  import { createComposerCommands } from "./composer.js";
110
112
  import { createStreamHandlers } from "./stream_handlers.js";
@@ -172,8 +174,11 @@ const settingsControl = createSettingsControl({
172
174
  running: () => liveTurn.running,
173
175
  run: (line) => runSessionCommand(line),
174
176
  });
175
- // A phone's ⋯ on the info bar, and its sheet: the chips and buttons the row has no room for.
177
+ // ⋯ on the info bar, and its menu: the chips and buttons the row has no room for.
176
178
  const moreSheet = createMoreSheet({ el: $("#infoBar"), button: $("#infoMoreBtn"), session: () => store.selected, hash: sessionHash });
179
+ // The bar's fold (bar_fold.js): one row, what doesn't fit folded into ⋯. A
180
+ // resize, the fonts or a zoom refolds it by itself: ⋯ follows on the redraw.
181
+ const barFold = createBarFold({ barEl: $("#infoBar"), keysFor: barItemKeys, onChange: () => store.touch("infoBar") });
177
182
  // The open session's participants chip in the info bar, and its panel
178
183
  // (Invite, revoke, caps, the participant view).
179
184
  const participantsControl = createParticipantsControl({
@@ -310,6 +315,8 @@ let eventsControl = null;
310
315
  // session while one ran (its bridge_up event): the tail runs once more.
311
316
  let resyncsInFlight = 0;
312
317
  let resyncAgain = false;
318
+ // A failed re-read keeps the drawn history and says so in the bar (resync_reach.js).
319
+ const resyncReach = createResyncReach({ store, historyEl, errorHint: (message) => hintEl(`Error: ${message}`) });
313
320
  // The running turn's texts on the page (the turn output dedupe).
314
321
  const shownTexts = createShownTexts();
315
322
  const markdownPlace = createMarkdownPlace({
@@ -358,6 +365,8 @@ const turnDom = createStageView({
358
365
  // Stop turn in its status row (disabled until the request settles).
359
366
  onCancel: () => handleCancel(),
360
367
  onHandedOff: (handed) => reloadCheck.handedOff(handed),
368
+ // The quiet signal (stage_stall.js): the stream, what the turn waits on, a joiner's step clock.
369
+ streamLive: () => !!streamControl?.live, timingNote: () => liveTurn.timing.note, serverGen: () => liveTurn.serverGen,
361
370
  });
362
371
  // The opt-in reload check (web.reload_check): a handed-off turn against a
363
372
  // reload of it, the counts to chi web (reload_check.js).
@@ -402,7 +411,8 @@ const liveTurn = createLiveTurn({
402
411
  (stageHost || historyEl).appendChild(el);
403
412
  return !!stageHost;
404
413
  },
405
- onTick: () => store.touch("infoBar"),
414
+ // The stage's quiet signal and tool clock tick with it (?.: a stage_view.js an open tab loaded before).
415
+ onTick: () => { store.touch("infoBar"); turnDom.tick?.(); },
406
416
  });
407
417
 
408
418
  // The composer's delivery line while the open session's turn runs
@@ -591,7 +601,7 @@ function followSelectedSession(sess) {
591
601
  store.update({ current: fieldsFromCard(sess) });
592
602
  store.setStatus(sess.status, "hub", { streaming });
593
603
  });
594
- if (!sess.bridge_up || streaming) return;
604
+ if (streaming || !(sess.bridge_up || resyncReach.needsReread())) return;
595
605
  if (resyncsInFlight > 0) resyncAgain = true;
596
606
  else resync();
597
607
  }
@@ -786,7 +796,7 @@ window.addEventListener("hashchange", () => {
786
796
  const composerMode = createComposerMode({
787
797
  els: { body: document.body, prompt: promptEl, hint: composeHintEl, button: actionBtn, attach: attachBtn, empty: emptyEl,
788
798
  history: historyEl },
789
- store, liveTurn, startPage, deliveryControl, moreSheet, fitPrompt, placeToast,
799
+ store, liveTurn, startPage, deliveryControl, fitPrompt, placeToast,
790
800
  });
791
801
 
792
802
  function setTurnRunning(running) {
@@ -905,6 +915,7 @@ async function select(id) {
905
915
  store.update({ selected: id });
906
916
  setSessionHash(id);
907
917
  historyEl.replaceChildren(hintEl("Loading…"));
918
+ resyncReach.loading();
908
919
  emptyEl.classList.add("hidden");
909
920
  resyncAttempts = 0; // this session has its own re-read budget
910
921
  forgetSession({ keepVerify: same });
@@ -934,15 +945,17 @@ function resetTurnView() {
934
945
  const RESYNC_RETRIES = 3;
935
946
  let resyncAttempts = 0;
936
947
 
948
+ // @return whether another try is scheduled
937
949
  function retryResync(id, { endText = null } = {}) {
938
- if (id !== store.selected) return;
950
+ if (id !== store.selected) return false;
939
951
  const { attempt, delayMs } = resyncRetry({ attempts: resyncAttempts, max: RESYNC_RETRIES, baseMs: STREAM_RETRY_MS });
940
- if (delayMs === null) return;
952
+ if (delayMs === null) return false;
941
953
  resyncAttempts = attempt;
942
954
  setTimeout(() => {
943
955
  if (id !== store.selected || (streamControl && streamControl.live)) return;
944
956
  resync({ endText });
945
957
  }, delayMs);
958
+ return true;
946
959
  }
947
960
 
948
961
  // (Re)render the selected session from the server and stream on from the
@@ -964,10 +977,7 @@ async function resync({ endText = null } = {}) {
964
977
  data = await getSession(id);
965
978
  } catch (e) {
966
979
  if (e.status === 404) return leaveGoneSession(id, "not_found");
967
- if (id === store.selected) {
968
- historyEl.replaceChildren(hintEl(`Error: ${e.message}`));
969
- retryResync(id, { endText });
970
- }
980
+ if (id === store.selected) resyncReach.failed(id, e.message, { retrying: retryResync(id, { endText }) });
971
981
  return;
972
982
  }
973
983
  resyncAttempts = 0;
@@ -978,6 +988,7 @@ async function resync({ endText = null } = {}) {
978
988
  const kept = keptCommandBubbles(historyEl, id);
979
989
  resetTurnView();
980
990
  renderSessionView(data, { kept });
991
+ resyncReach.drawn(id);
981
992
  ownerClaim.showPending();
982
993
  // Preview is read-only: a worker is woken only by POST /turn, so attach
983
994
  // only when a live bridge exists.
@@ -1044,14 +1055,9 @@ function renderSessionView(data, { kept = [] } = {}) {
1044
1055
  const saved = data.saved_recap;
1045
1056
  if (saved) showRecap(saved.text, saved.turns_since, saved.created_at || null, saved.opening_id || null);
1046
1057
  else showRecap(data.recap);
1047
- // chi web's unfold of the join (TurnAccumulator.join_events); the page's
1048
- // own only for a mixed cache (an older chi web's payload has none).
1049
- const replay = data.replay ?? snapshotEvents({
1050
- current_turn: data.current_turn,
1051
- queued: data.queued,
1052
- queued_commands: data.queued_commands,
1053
- started_at: store.current.timing.activeTurn?.started_at,
1054
- });
1058
+ // chi web's unfold of the join (TurnAccumulator.join_events): the turn in
1059
+ // progress and the queue behind it as the live events that draw them.
1060
+ const replay = data.replay ?? [];
1055
1061
  // Marked replayed: a call's duration isn't timed from the replay's clock.
1056
1062
  replay.forEach((event) => streamHandlers[event.type]?.({ ...event, replayed: true }));
1057
1063
  // A join mid-generation: the worker's word on it clocks the delivery line.
@@ -1318,7 +1324,8 @@ function updateInfoBar() {
1318
1324
  // lit writes its text alone, the bar's other nodes (a tooltip, a button
1319
1325
  // mid-press) stay.
1320
1326
  renderInfoBar(infoTextEl, bar);
1321
- moreSheet.update({ bar, buttons });
1327
+ const { folded } = barFold.update({ bar, buttons });
1328
+ moreSheet.update({ bar, buttons, folded });
1322
1329
  updateSessionTitle();
1323
1330
  // A fresh link's picker follows what the bar follows: its model, its
1324
1331
  // owner, a next link continued from elsewhere.
@@ -61,7 +61,9 @@ export function createAuthLost({
61
61
  const bar = doc.createElement("div");
62
62
  bar.id = "authLost";
63
63
  bar.setAttribute("role", "alert");
64
- bar.style.cssText = "position:fixed;top:0;left:0;right:0;z-index:10000;padding:8px 16px;font-size:14px;"
64
+ // Its top padding clears a phone's status bar (both pages run under it: viewport-fit=cover).
65
+ bar.style.cssText = "position:fixed;top:0;left:0;right:0;z-index:10000;padding:8px 16px;"
66
+ + "padding-top:calc(8px + env(safe-area-inset-top, 0px));font-size:14px;"
65
67
  + "color:var(--warn-text);background:var(--warn-bg);border-bottom:1px solid var(--warn-border);"
66
68
  + "display:flex;gap:12px;align-items:center;justify-content:center";
67
69
  const text = doc.createElement("span");
@@ -0,0 +1,293 @@
1
+ // The session bar's fold (#infoBar): the bar is one row at every width, and
2
+ // what doesn't fit folds into ⋯ (more_sheet.js), the lowest rank first
3
+ // (info_bar_model.js BAR_ITEMS). foldPlan is the rule, pure, over measured
4
+ // widths; createBarFold is its watcher on the page: it measures, caches the
5
+ // widths, recomputes only when an input changes and writes the plan as three
6
+ // attributes on #infoBar that index.html's CSS hides by:
7
+ // data-folded="notes toolkit dir" (the folded keys: display:none, still in
8
+ // the DOM, so a click from ⋯ reaches them)
9
+ // data-compact="settings" (⚙ as its icon, the dot when own)
10
+ // data-empty-groups="relations" (a group with nothing on the row, and
11
+ // the hairline before it)
12
+ // lit renders into #infoText, inside #infoBar, so the attributes survive its
13
+ // redraws. docs/internals/web-frontend.md ("The session bar: one row").
14
+
15
+ import { BAR_ITEMS } from "./info_bar_model.js";
16
+ import { chipModel as settingsChipModel } from "./settings_chip.js";
17
+
18
+ // The page's phone width (index.html's 600 px cut): only phone: "row" items
19
+ // are row candidates there.
20
+ export const PHONE_QUERY = "(max-width: 600px)";
21
+
22
+ // The .meta's groups, left to right (info_bar.js infoBarHtml); the actions
23
+ // (#infoActions and ⋯) follow them.
24
+ export const META_GROUPS = Object.freeze(["identity", "setup", "relations", "trail"]);
25
+
26
+ // The chips a running turn rewrites: their text changes every tick, so they
27
+ // are left out of the signature and kept within a width budget instead.
28
+ export const LIVE_KEYS = Object.freeze(["ctx", "speed", "time"]);
29
+
30
+ // Items that are always in ⋯ and so don't count on it (more_sheet.js moreCount).
31
+ const UNCOUNTED = new Set(["archive", "delete", "more"]);
32
+
33
+ const pinned = (item) => item.rank === "pinned";
34
+ const rankOf = (item) => (pinned(item) ? Infinity : item.rank);
35
+
36
+ // The row's width with +row+ (items) on it, +compact+ (keys) in their compact
37
+ // form. +spacing+: {item: the gap between two chips of a group, group: from
38
+ // one group's last chip to the next's first (its hairline and gaps), bar:
39
+ // #infoBar's gap (between .info, #infoActions and ⋯), actions: the gap
40
+ // between two buttons}. +countWidth+: what the count on ⋯ adds, when any.
41
+ export function rowWidth(row, { widths, compact = new Set(), spacing, countWidth = 0, counted = false }) {
42
+ const w = (item) => {
43
+ const m = widths[item.key] || { full: 0 };
44
+ return compact.has(item.key) && m.compact !== undefined ? m.compact : m.full;
45
+ };
46
+ let meta = 0;
47
+ let drawn = 0;
48
+ for (const group of META_GROUPS) {
49
+ const its = row.filter((item) => item.group === group);
50
+ if (!its.length) continue;
51
+ meta += (drawn ? spacing.group : 0) + its.reduce((sum, item) => sum + w(item), 0) + spacing.item * (its.length - 1);
52
+ drawn += 1;
53
+ }
54
+ const buttons = row.filter((item) => item.group === "actions" && item.key !== "more");
55
+ const acts = buttons.reduce((sum, item) => sum + w(item), 0) + spacing.actions * Math.max(0, buttons.length - 1);
56
+ const more = row.find((item) => item.key === "more");
57
+ return meta + spacing.bar + acts + (more ? spacing.bar + w(more) + (counted ? countWidth : 0) : 0);
58
+ }
59
+
60
+ // The fold for +items+ (the BAR_ITEMS the session's bar has), +widths+
61
+ // ({key: {full, compact?}}, px), +available+ (the bar's content width, px)
62
+ // and +profile+ ("desktop" | "phone"):
63
+ // 1. every row candidate at its full form (on the phone only phone: "row"
64
+ // ones, ⚙ there compact from the start; "menu" items never);
65
+ // 2. while the row is wider than +available+: the lowest rank still on it
66
+ // (all of that rank together) goes compact when it has a compact form
67
+ // not yet used, else it folds;
68
+ // 3. pinned items never fold: with only those left the row clips.
69
+ // @return {folded: Set, compact: Set, emptyGroups: [group]} (emptyGroups: the
70
+ // META_GROUPS with no item on the row, in their order)
71
+ export function foldPlan({ items, widths, available, profile = "desktop", spacing, countWidth = 0 }) {
72
+ const phone = profile === "phone";
73
+ const candidate = (item) => item.rank !== "menu" && (!phone || item.phone === "row");
74
+ const folded = new Set(items.filter((item) => !candidate(item)).map((item) => item.key));
75
+ const compact = new Set(phone ? items.filter((item) => candidate(item) && item.compact).map((item) => item.key) : []);
76
+ const onRow = () => items.filter((item) => !folded.has(item.key));
77
+ const counted = () => [...folded].some((key) => !UNCOUNTED.has(key));
78
+ const fits = () => rowWidth(onRow(), { widths, compact, spacing, countWidth, counted: counted() }) <= available;
79
+ while (!fits()) {
80
+ const foldable = onRow().filter((item) => !pinned(item));
81
+ if (!foldable.length) break;
82
+ const low = Math.min(...foldable.map(rankOf));
83
+ const its = foldable.filter((item) => rankOf(item) === low);
84
+ const shrink = its.filter((item) => item.compact && !compact.has(item.key));
85
+ if (shrink.length) shrink.forEach((item) => compact.add(item.key));
86
+ else its.forEach((item) => { folded.add(item.key); compact.delete(item.key); });
87
+ }
88
+ const row = onRow();
89
+ const emptyGroups = META_GROUPS.filter((group) => !row.some((item) => item.group === group));
90
+ return { folded, compact, emptyGroups };
91
+ }
92
+
93
+ // What, besides the bar's width, changes the fold: the items present and the
94
+ // text of each one that isn't live (a status, "set 9" → "set 10", a delegate
95
+ // starting to wait, the model's name), as one string. +bar+, +buttons+:
96
+ // info_bar_model.js sessionBar's.
97
+ export function foldSignature(bar, buttons) {
98
+ if (!bar) return "";
99
+ const gear = bar.settings ? settingsChipModel(bar.settings) : null;
100
+ return JSON.stringify([
101
+ bar.id, bar.status, bar.statusText, bar.model?.text, bar.model?.mismatch, gear?.text, gear?.own,
102
+ bar.toolkit?.summary?.name, bar.toolkit?.summary?.label, bar.toolkit?.defaultKit, bar.notes?.text,
103
+ bar.workingSet ? [bar.workingSet.chip?.n] : (bar.memories || []).join(","),
104
+ bar.participants?.text, bar.participants?.count,
105
+ bar.chain?.prev?.date, bar.chain?.prev?.id, bar.chain?.next?.date, bar.chain?.next?.id, bar.chain?.pruned,
106
+ bar.parent?.id, bar.kids?.text, bar.kids?.waitingText, bar.dir, !!bar.speed,
107
+ bar.worker?.badge?.text, bar.worker?.badge?.restart, bar.worker?.busy,
108
+ buttons?.continue?.shown, buttons?.continue?.text, buttons?.stop?.shown,
109
+ buttons?.archive?.shown, buttons?.delete?.shown,
110
+ ]);
111
+ }
112
+
113
+ const px = (value) => parseFloat(value) || 0;
114
+
115
+ // The watcher. +barEl+: #infoBar; +win+: the window (matchMedia,
116
+ // ResizeObserver, getComputedStyle; a fake in the tests); +keysFor(bar,
117
+ // buttons)+: the BAR_ITEMS keys present (info_bar_model.js barItemKeys).
118
+ // update({bar, buttons}) after each render (app.js updateInfoBar, in the
119
+ // same task, before paint) → {folded, compact} (Sets); it recomputes only
120
+ // when the signature, the profile or the bar's width changed, or a live chip
121
+ // outgrew its budget. +onChange()+: a recompute the watcher started by itself
122
+ // (a resize, the fonts, a zoom), so the page can redraw ⋯ from the new fold.
123
+ // @return {update, recompute, folded(), compact()}
124
+ export function createBarFold({ barEl, keysFor, win = globalThis, doc = win.document, onChange = () => {} }) {
125
+ const phoneQuery = win.matchMedia(PHONE_QUERY);
126
+ // Natural widths per key + text (+ form); the live chips' budgets per key.
127
+ const cache = new Map();
128
+ const budgets = new Map();
129
+ let last = { bar: null, buttons: null };
130
+ let signature = null;
131
+ let profile = null;
132
+ let width = null;
133
+ let plan = { folded: new Set(), compact: new Set(), emptyGroups: [] };
134
+
135
+ const elOf = (item) => barEl.querySelector(item.selector);
136
+ const textOf = (el) => `${el.className}|${el.textContent}`;
137
+ const live = (item) => LIVE_KEYS.includes(item.key);
138
+ // ⋯'s own width is read with its count blank (the count is countWidth).
139
+ const cacheKey = (item, el, form) => (live(item) || item.key === "more" ? `${item.key}|${form}` : `${item.key}|${form}|${textOf(el)}`);
140
+ const boxWidth = (el) => (el.getClientRects().length ? el.getBoundingClientRect().width : 0);
141
+ const contentWidth = () => {
142
+ const style = win.getComputedStyle(barEl);
143
+ return barEl.clientWidth - px(style.paddingLeft) - px(style.paddingRight);
144
+ };
145
+
146
+ function setAttr(name, values) {
147
+ const text = [...values].join(" ");
148
+ if (text) barEl.setAttribute(name, text);
149
+ else barEl.removeAttribute(name);
150
+ }
151
+
152
+ function apply(next) {
153
+ plan = next;
154
+ setAttr("data-folded", next.folded);
155
+ setAttr("data-compact", next.compact);
156
+ setAttr("data-empty-groups", next.emptyGroups);
157
+ }
158
+
159
+ // The spacing the row's CSS has now (a phone's groups are display:contents
160
+ // with no hairline; a desktop's are flex boxes with one).
161
+ function spacing() {
162
+ const meta = barEl.querySelector(".meta");
163
+ const group = barEl.querySelector(".meta .bar-group");
164
+ const sep = barEl.querySelector(".meta .bar-sep");
165
+ const metaGap = meta ? px(win.getComputedStyle(meta).columnGap) : 0;
166
+ const groupStyle = group ? win.getComputedStyle(group) : null;
167
+ const item = groupStyle && groupStyle.display !== "contents" ? px(groupStyle.columnGap) : metaGap;
168
+ const sepWidth = sep && win.getComputedStyle(sep).display !== "none" ? boxWidth(sep) : 0;
169
+ const actions = barEl.querySelector("#infoActions");
170
+ return {
171
+ item,
172
+ group: sepWidth ? sepWidth + 2 * metaGap : metaGap,
173
+ bar: px(win.getComputedStyle(barEl).columnGap),
174
+ actions: actions ? px(win.getComputedStyle(actions).columnGap) : 0,
175
+ };
176
+ }
177
+
178
+ // Every candidate's width, measured where none is cached: with the fold's
179
+ // attributes off (a folded item has no box to read), and the row's children are
180
+ // flex:none (index.html), so a width is its natural one. Synchronous: no
181
+ // paint sees the unfolded row. The count on ⋯ is measured with two digits.
182
+ function measure(items) {
183
+ const forms = items.flatMap((item) => [["full", item], ...(item.compact ? [["compact", item]] : [])]);
184
+ const need = () => forms.some(([form, item]) => { const el = elOf(item); return el && !cache.has(cacheKey(item, el, form)); })
185
+ || !cache.has("more|count");
186
+ if (need()) {
187
+ const saved = ["data-folded", "data-compact", "data-empty-groups"].map((name) => [name, barEl.getAttribute(name)]);
188
+ saved.forEach(([name]) => barEl.removeAttribute(name));
189
+ const read = (form) => forms.filter(([f]) => f === form).forEach(([, item]) => {
190
+ const el = elOf(item);
191
+ if (el) cache.set(cacheKey(item, el, form), boxWidth(el));
192
+ });
193
+ const more = barEl.querySelector("#infoMoreBtn");
194
+ const count = more?.querySelector(".more-count");
195
+ const before = count ? count.textContent : "";
196
+ if (count) count.textContent = "";
197
+ read("full");
198
+ if (count) {
199
+ const bare = boxWidth(more);
200
+ count.textContent = "88";
201
+ cache.set("more|count", Math.max(0, boxWidth(more) - bare));
202
+ count.textContent = before;
203
+ } else {
204
+ cache.set("more|count", 0);
205
+ }
206
+ barEl.setAttribute("data-compact", items.filter((item) => item.compact).map((item) => item.key).join(" "));
207
+ read("compact");
208
+ saved.forEach(([name, value]) => (value === null ? barEl.removeAttribute(name) : barEl.setAttribute(name, value)));
209
+ }
210
+ const widths = {};
211
+ for (const item of items) {
212
+ const el = elOf(item);
213
+ if (!el) continue;
214
+ const full = cache.get(cacheKey(item, el, "full")) || 0;
215
+ const entry = { full: live(item) ? Math.max(full, budgets.get(item.key) || 0) : full };
216
+ if (item.compact) entry.compact = cache.get(cacheKey(item, el, "compact")) || 0;
217
+ if (live(item)) budgets.set(item.key, entry.full);
218
+ widths[item.key] = entry;
219
+ }
220
+ return widths;
221
+ }
222
+
223
+ function recompute() {
224
+ const { bar, buttons } = last;
225
+ if (!bar) {
226
+ apply({ folded: new Set(), compact: new Set(), emptyGroups: [] });
227
+ return plan;
228
+ }
229
+ const available = contentWidth();
230
+ width = barEl.clientWidth;
231
+ // A bar with no box (the start page, a hidden view): nothing to measure;
232
+ // the resize that gives it one recomputes.
233
+ if (!width) return plan;
234
+ const keys = new Set(keysFor(bar, buttons));
235
+ const items = BAR_ITEMS.filter((item) => keys.has(item.key));
236
+ const phone = profile === "phone";
237
+ const candidates = items.filter((item) => item.rank !== "menu" && (!phone || item.phone === "row"));
238
+ const widths = measure(candidates);
239
+ apply(foldPlan({ items, widths, available: available - 1, profile, spacing: spacing(),
240
+ countWidth: phone ? 0 : cache.get("more|count") || 0 }));
241
+ return plan;
242
+ }
243
+
244
+ // A live chip on the row wider than its budget (a 3-digit speed, ctx ~100%).
245
+ function outgrown() {
246
+ return LIVE_KEYS.some((key) => {
247
+ const item = BAR_ITEMS.find((i) => i.key === key);
248
+ if (plan.folded.has(key)) return false;
249
+ const el = elOf(item);
250
+ if (!el || !el.getClientRects().length) return false;
251
+ const w = boxWidth(el);
252
+ if (w <= (budgets.get(key) || 0) + 0.5) return false;
253
+ budgets.set(key, w);
254
+ return true;
255
+ });
256
+ }
257
+
258
+ function update({ bar, buttons }) {
259
+ last = { bar, buttons };
260
+ const sig = foldSignature(bar, buttons);
261
+ const prof = phoneQuery.matches ? "phone" : "desktop";
262
+ if (sig !== signature || prof !== profile || barEl.clientWidth !== width || (bar && outgrown())) {
263
+ // The phone's CSS sizes every chip anew.
264
+ if (prof !== profile) { cache.clear(); budgets.clear(); }
265
+ signature = sig;
266
+ profile = prof;
267
+ recompute();
268
+ }
269
+ return { folded: plan.folded, compact: plan.compact };
270
+ }
271
+
272
+ // Inputs the page's redraws don't carry: the bar's width, the profile, the
273
+ // fonts (a webfont swapped in) and the zoom (both change every width).
274
+ const again = ({ clear = false } = {}) => {
275
+ const prof = phoneQuery.matches ? "phone" : "desktop";
276
+ if (clear || prof !== profile) { cache.clear(); budgets.clear(); }
277
+ profile = prof;
278
+ recompute();
279
+ onChange();
280
+ };
281
+ if (win.ResizeObserver) {
282
+ new win.ResizeObserver(() => { if (barEl.clientWidth !== width) again(); }).observe(barEl);
283
+ }
284
+ phoneQuery.addEventListener?.("change", () => again());
285
+ doc?.fonts?.ready?.then?.(() => again({ clear: true }));
286
+ const watchZoom = () => {
287
+ const query = win.matchMedia(`(resolution: ${win.devicePixelRatio || 1}dppx)`);
288
+ query.addEventListener?.("change", () => { again({ clear: true }); watchZoom(); }, { once: true });
289
+ };
290
+ watchZoom();
291
+
292
+ return { update, recompute, folded: () => plan.folded, compact: () => plan.compact };
293
+ }
@@ -151,7 +151,7 @@ export function shownElsewhere(notice, capabilities) {
151
151
  // came during the running turn but aren't its own (an anytime command's,
152
152
  // such as /btw: after the running turn once it is drawn, as they came).
153
153
  // The running turn's own rows (a hook's notice, a retry) are left out:
154
- // they come with the turn's parts (snapshotEvents). So is a notice the
154
+ // they come with the turn's parts (the join's replay). So is a notice the
155
155
  // page shows elsewhere (shownElsewhere).
156
156
  export function splitSnapshotCards(cards, capabilities = null) {
157
157
  const list = (Array.isArray(cards) ? cards : []).filter((c) => !shownElsewhere(c, capabilities));
@@ -110,7 +110,11 @@ export function createChipPopover({ id, className, width: widest, el, anchor: an
110
110
  pop.style.width = `${at.width}px`;
111
111
  pop.style.left = `${at.left}px`;
112
112
  pop.style.top = "";
113
- pop.style.bottom = `${at.bottom}px`;
113
+ // On the window's bottom: clear of a phone's home indicator too
114
+ // (index.html --safe-b; 0 where unset). On a keyboard: its offset,
115
+ // already above the indicator, alone. (Not max(): the specs' DOM
116
+ // drops it.)
117
+ pop.style.bottom = at.bottom > SHEET_EDGE ? `${at.bottom}px` : `calc(${SHEET_EDGE}px + var(--safe-b, 0px))`;
114
118
  pop.style.maxHeight = `${at.maxHeight}px`;
115
119
  return;
116
120
  }
@@ -67,10 +67,10 @@ export function composerMode({ selected, owner, running, narrow }) {
67
67
  // page's session store (selected, current.owner; read only). +liveTurn+:
68
68
  // live_turn.js's (running). +startPage+: start_page.js's (restoreStartPick,
69
69
  // syncModelPick, dropChoices). +deliveryControl+: delivery_line.js's.
70
- // +moreSheet+: more_sheet.js's (⋯ is a phone's alone). +fitPrompt()+,
70
+ // +fitPrompt()+,
71
71
  // +placeToast()+: the page's. +win+: the window (matchMedia).
72
72
  export function createComposerMode({
73
- els, store, liveTurn, startPage, deliveryControl, moreSheet, fitPrompt, placeToast, win = globalThis,
73
+ els, store, liveTurn, startPage, deliveryControl, fitPrompt, placeToast, win = globalThis,
74
74
  }) {
75
75
  const narrowScreen = win.matchMedia(NARROW_QUERY);
76
76
  let hadSession = false;
@@ -100,11 +100,9 @@ export function createComposerMode({
100
100
  if (mode.clearHistory) els.history.replaceChildren();
101
101
  }
102
102
 
103
- narrowScreen.addEventListener("change", () => {
104
- update();
105
- // ⋯ is a phone's alone: a window grown past it takes its sheet along.
106
- if (!narrowScreen.matches && moreSheet.isOpen()) moreSheet.close();
107
- });
103
+ // ⋯'s menu stays open across the width: chip_popover.js turns its sheet
104
+ // into a popover (and back) on the resize.
105
+ narrowScreen.addEventListener("change", () => update());
108
106
 
109
107
  return { update };
110
108
  }