samagotchi 0.165.0 → 0.167.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 +99 -1
  3. data/docs/architecture.md +1 -0
  4. data/docs/cli.md +16 -7
  5. data/docs/configuration.md +4 -1
  6. data/docs/guardrails.md +8 -3
  7. data/docs/hooks.md +4 -6
  8. data/docs/internals/bridge.md +6 -0
  9. data/docs/internals/bundles.md +2 -4
  10. data/docs/internals/engine.md +4 -5
  11. data/docs/internals/objectives.md +141 -9
  12. data/docs/internals/remote-sessions.md +6 -7
  13. data/docs/internals/web-frontend.md +62 -24
  14. data/docs/memory.md +1 -2
  15. data/docs/releasing.md +12 -3
  16. data/docs/sessions.md +24 -6
  17. data/docs/testing.md +14 -4
  18. data/lib/samagotchi/bridge.rb +1 -1
  19. data/lib/samagotchi/bundle_command/installed_check.rb +2 -14
  20. data/lib/samagotchi/bundle_command.rb +19 -11
  21. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  22. data/lib/samagotchi/cli/command.rb +10 -0
  23. data/lib/samagotchi/compat.rb +4 -14
  24. data/lib/samagotchi/config.rb +3 -0
  25. data/lib/samagotchi/context_command.rb +2 -1
  26. data/lib/samagotchi/engine/objectives.rb +20 -1
  27. data/lib/samagotchi/engine/side_requests.rb +3 -2
  28. data/lib/samagotchi/engine/turn_end.rb +4 -1
  29. data/lib/samagotchi/engine.rb +3 -0
  30. data/lib/samagotchi/extension_load.rb +2 -26
  31. data/lib/samagotchi/guardrails/approvals.rb +59 -9
  32. data/lib/samagotchi/jsonl_store.rb +61 -0
  33. data/lib/samagotchi/memory_bundle/status.rb +3 -15
  34. data/lib/samagotchi/memory_bundle/system_bundle.rb +16 -10
  35. data/lib/samagotchi/memory_command.rb +4 -2
  36. data/lib/samagotchi/objectives.rb +43 -14
  37. data/lib/samagotchi/objectives_backing.rb +124 -0
  38. data/lib/samagotchi/objectives_check.rb +19 -126
  39. data/lib/samagotchi/objectives_command.rb +14 -7
  40. data/lib/samagotchi/objectives_record.rb +104 -0
  41. data/lib/samagotchi/objectives_track.rb +353 -0
  42. data/lib/samagotchi/plugin/sessions.rb +4 -1
  43. data/lib/samagotchi/push_command.rb +2 -1
  44. data/lib/samagotchi/remote_command.rb +2 -1
  45. data/lib/samagotchi/reply_wait/poll.rb +10 -21
  46. data/lib/samagotchi/reply_wait.rb +4 -47
  47. data/lib/samagotchi/run_options.rb +1 -1
  48. data/lib/samagotchi/schedule_command.rb +6 -0
  49. data/lib/samagotchi/schedules.rb +1 -1
  50. data/lib/samagotchi/session_access/remote.rb +7 -24
  51. data/lib/samagotchi/session_commands.rb +1 -1
  52. data/lib/samagotchi/session_inbox.rb +1 -1
  53. data/lib/samagotchi/sessions_command.rb +12 -6
  54. data/lib/samagotchi/share_command.rb +2 -1
  55. data/lib/samagotchi/tool_activity.rb +11 -1
  56. data/lib/samagotchi/tool_declarations.rb +5 -1
  57. data/lib/samagotchi/tools/delegate.rb +2 -4
  58. data/lib/samagotchi/tools/objectives_tool.rb +19 -2
  59. data/lib/samagotchi/turn_stages/objectives.rb +46 -3
  60. data/lib/samagotchi/version.rb +1 -1
  61. data/lib/samagotchi/web/participant_access.rb +1 -1
  62. data/lib/samagotchi/web/public/app.js +55 -420
  63. data/lib/samagotchi/web/public/auth_lost.js +3 -1
  64. data/lib/samagotchi/web/public/bar_fold.js +1 -1
  65. data/lib/samagotchi/web/public/chip_popover.js +5 -1
  66. data/lib/samagotchi/web/public/copy.js +2 -1
  67. data/lib/samagotchi/web/public/delivery_line.js +19 -4
  68. data/lib/samagotchi/web/public/index.html +156 -49
  69. data/lib/samagotchi/web/public/info_bar.js +1 -1
  70. data/lib/samagotchi/web/public/info_bar_model.js +8 -1
  71. data/lib/samagotchi/web/public/live_timing.js +3 -0
  72. data/lib/samagotchi/web/public/no_contact_fill.js +29 -0
  73. data/lib/samagotchi/web/public/objectives.css +14 -0
  74. data/lib/samagotchi/web/public/objectives_moves.js +82 -9
  75. data/lib/samagotchi/web/public/objectives_state.js +42 -0
  76. data/lib/samagotchi/web/public/objectives_strip.js +33 -9
  77. data/lib/samagotchi/web/public/objectives_track.js +52 -0
  78. data/lib/samagotchi/web/public/objectives_wiring.js +16 -1
  79. data/lib/samagotchi/web/public/participant.html +1 -1
  80. data/lib/samagotchi/web/public/participants_panel.js +14 -7
  81. data/lib/samagotchi/web/public/question_cards.js +7 -12
  82. data/lib/samagotchi/web/public/resync_reach.js +63 -0
  83. data/lib/samagotchi/web/public/scope.js +3 -3
  84. data/lib/samagotchi/web/public/session_fields.js +1 -0
  85. data/lib/samagotchi/web/public/session_rename.js +6 -2
  86. data/lib/samagotchi/web/public/session_state.js +6 -1
  87. data/lib/samagotchi/web/public/session_sync.js +249 -0
  88. data/lib/samagotchi/web/public/session_view.js +279 -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 +75 -6
  92. data/lib/samagotchi/web/public/stream_handlers.js +1 -1
  93. data/lib/samagotchi/web/public/tokens.css +2 -2
  94. data/lib/samagotchi/web/public/turn_block.js +8 -0
  95. data/lib/samagotchi/web/public/turn_html.js +1 -1
  96. data/lib/samagotchi/web/public/widget_picks.js +3 -0
  97. data/lib/samagotchi/web/public/working_set_view.js +1 -1
  98. data/lib/samagotchi/web/session_access_routes.rb +4 -15
  99. data/lib/samagotchi/web/token.rb +2 -2
  100. metadata +12 -1
@@ -41,24 +41,22 @@ import { createMoreSheet } from "./more_sheet.js";
41
41
  import { createBarFold } from "./bar_fold.js";
42
42
  import { barItemKeys, sessionBar } from "./info_bar_model.js";
43
43
  import { createShownTexts } from "./shown_texts.js";
44
- import { emptySessionState, sessionStateFrom } from "./session_state.js";
44
+ import { emptySessionState } from "./session_state.js";
45
45
  import { sessionFieldsFrom } from "./session_payload.js";
46
- import { fieldsFromCard } from "./session_fields.js";
47
46
  import { createSessionStore } from "./session_store.js";
48
47
  import { createFeatureGates } from "./feature_gates.js";
49
48
  import { stillOn } from "./latest.js";
50
- import { thumbsTemplate } from "./images.js";
51
- import { normalize, failedTurnText, cantText, withoutWorker } from "./format.js";
49
+ import { normalize, cantText } from "./format.js";
52
50
  import { turnHistoryNodes } from "./turn_block.js";
53
- import { elementOf, emptyAnswerTemplate } from "./turn_html.js";
54
- import { createBubbles, hintEl, outputBubbleTemplate } from "./bubbles.js";
51
+ import { elementOf } from "./turn_html.js";
52
+ import { createBubbles } from "./bubbles.js";
55
53
  import { createCardsPlace } from "./cards_place.js";
56
54
  import { createStageView } from "./stage_view.js";
57
55
  import { createReloadCheck } from "./reload_check.js";
58
- import { createWorkingSet, groupItems } from "./working_set_view.js";
56
+ import { createWorkingSet } from "./working_set_view.js";
59
57
  import { createObjectives } from "./objectives_wiring.js";
60
- import { turnGroups } from "./timing.js";
61
- import { createGapClock, lastActivity } from "./time_gaps.js";
58
+ import { trackWorkerUnavailable } from "./objectives_track.js";
59
+ import { createGapClock } from "./time_gaps.js";
62
60
  import { createMarkdownPlace } from "./markdown_place.js";
63
61
  import { openerFill, openTitle, restoredComposer } from "./chains.js";
64
62
  import { createTaskStopper } from "./task_stop.js";
@@ -79,7 +77,6 @@ import { installAnswerFold, sweepAnswerFolds } from "./answer_fold.js";
79
77
  import { installDetailsMotion } from "./details_motion.js";
80
78
  import { answerLabel, installReviseStacks, reviseChipTemplate, reviseWorkerUnavailable } from "./revise_stack.js";
81
79
  import { createQuestionCards } from "./question_cards.js";
82
- import { splitSnapshotCards } from "./card.js";
83
80
  import { PROMPT_LINE_PX, PROMPT_MIN_PX } from "./composer_size.js";
84
81
  import { mountComposer } from "./composer_mount.js";
85
82
  import { createCommandList } from "./command_list.js";
@@ -104,9 +101,9 @@ import { createLiveTurn } from "./live_turn.js";
104
101
  import { answerRefsOf, applyFinalAnswer, pairAnswerRefs, setAnswerRefs } from "./answer_refs.js";
105
102
  import { installRefClicks } from "./refs.js";
106
103
  import { linkRefs, touchedFiles } from "./ref_scan.js";
107
- import { DONE_MS, applyInitEvent, dropDone, fadeDone, initRowTemplate, newInitTasks, seedInitTasks } from "./init_row.js";
108
- import { newClientId, resyncRetry, streamDropEnd } from "./turn_events.js";
109
- import { applyConfirm, keptCommandBubbles, restoreCommandBubbles } from "./commands.js";
104
+ import { DONE_MS, applyInitEvent, dropDone, fadeDone, initRowTemplate, newInitTasks } from "./init_row.js";
105
+ import { newClientId } from "./turn_events.js";
106
+ import { applyConfirm } from "./commands.js";
110
107
  import { createComposerCommands } from "./composer.js";
111
108
  import { createStreamHandlers } from "./stream_handlers.js";
112
109
  import { createListsView } from "./lists_view.js";
@@ -124,6 +121,8 @@ import { createStopSheet } from "./stop_sheet.js";
124
121
  import { createVersionNotices } from "./version_notices.js";
125
122
  import { createRename } from "./session_rename.js";
126
123
  import { createSendTurn } from "./send_turn.js";
124
+ import { createSessionSync } from "./session_sync.js";
125
+ import { createSessionView } from "./session_view.js";
127
126
  import { createMarkdownTip } from "./markdown_tip.js";
128
127
  import { withoutStaleParams } from "./stale_params.js";
129
128
 
@@ -262,6 +261,8 @@ const featureGates = createFeatureGates([
262
261
  unavailable: (cur) => reviseWorkerUnavailable(cur.workerFeatures, cur.bridgeUp),
263
262
  redraw: () => redrawRevise(),
264
263
  },
264
+ // The objectives' Where are we? (objectives_track.js).
265
+ { name: "objectivesTrack", unavailable: (cur) => trackWorkerUnavailable(cur.workerFeatures, cur.bridgeUp), redraw: () => objectives.redraw() },
265
266
  ]);
266
267
  featureGates.prime(store.current);
267
268
  // The open session's id, for the stale-answer guards (latest.js stillOn).
@@ -306,14 +307,9 @@ let draftFrom;
306
307
  function noteDraft(id) {
307
308
  draftFrom = id ?? store.selected ?? "";
308
309
  }
309
- let streamControl = null;
310
310
  // The session list's stream (GET /api/events); null while the page falls
311
311
  // back to fetching (a chi web without a hub).
312
312
  let eventsControl = null;
313
- // resync() calls in flight, and whether a worker came up for the selected
314
- // session while one ran (its bridge_up event): the tail runs once more.
315
- let resyncsInFlight = 0;
316
- let resyncAgain = false;
317
313
  // The running turn's texts on the page (the turn output dedupe).
318
314
  const shownTexts = createShownTexts();
319
315
  const markdownPlace = createMarkdownPlace({
@@ -330,7 +326,7 @@ const markdownPlace = createMarkdownPlace({
330
326
  setAnswerRefs,
331
327
  answerRefsOf,
332
328
  });
333
- const { renderMarkdown, pairRefsIn, linkRefsIn, applyFinalMarkdown, linkTextRefs } = markdownPlace;
329
+ const { renderMarkdown, pairRefsIn, linkRefsIn, applyFinalMarkdown } = markdownPlace;
334
330
  // The stage view's working set (web.working_set, or ?working_set=1|0):
335
331
  // what each turn brought into context, in a rail in the stage, a footprint
336
332
  // under each finished turn and a "set N" chip in the mem chip's place
@@ -362,6 +358,8 @@ const turnDom = createStageView({
362
358
  // Stop turn in its status row (disabled until the request settles).
363
359
  onCancel: () => handleCancel(),
364
360
  onHandedOff: (handed) => reloadCheck.handedOff(handed),
361
+ // The quiet signal (stage_stall.js): the stream, what the turn waits on, a joiner's step clock.
362
+ streamLive: () => sessionSync.streamLive(), timingNote: () => liveTurn.timing.note, serverGen: () => liveTurn.serverGen,
365
363
  });
366
364
  // The opt-in reload check (web.reload_check): a handed-off turn against a
367
365
  // reload of it, the counts to chi web (reload_check.js).
@@ -406,7 +404,8 @@ const liveTurn = createLiveTurn({
406
404
  (stageHost || historyEl).appendChild(el);
407
405
  return !!stageHost;
408
406
  },
409
- onTick: () => store.touch("infoBar"),
407
+ // The stage's quiet signal and tool clock tick with it (?.: a stage_view.js an open tab loaded before).
408
+ onTick: () => { store.touch("infoBar"); turnDom.tick?.(); },
410
409
  });
411
410
 
412
411
  // The composer's delivery line while the open session's turn runs
@@ -439,6 +438,7 @@ const clientId = newClientId();
439
438
  const objectives = createObjectives({
440
439
  el: $("#objectivesStrip"), historyEl, session: () => store.selected, running: () => liveTurn.running, holding: () => turnDom.holds(), commands: () => store.current.commands,
441
440
  clientId, sendCommand, sendTurn, follow: () => followWokenWorker(), toast: (...args) => showToast(...args),
441
+ canTrack: () => !trackWorkerUnavailable(store.current.workerFeatures, store.current.bridgeUp),
442
442
  });
443
443
  // The question and continue cards in the history (question_cards.js).
444
444
  const questionCards = createQuestionCards({
@@ -486,8 +486,39 @@ const cards = createCardsPlace({
486
486
  bubbles,
487
487
  followWokenWorker: () => followWokenWorker(),
488
488
  });
489
- const { upsertCard, placeSnapshotCards, refreshCardBodies } = cards;
489
+ const { upsertCard, refreshCardBodies } = cards;
490
490
  turnRoots().forEach((root) => root.addEventListener("click", cards.onCardAction));
491
+ // The open session's view (session_view.js): a read drawn, a turn's end,
492
+ // the reset for another session; and its sync with the server
493
+ // (session_sync.js): select, resync and the stream. Made before the views that
494
+ // take their functions (the session actions, the send, the stream handlers);
495
+ // the ones made later come in as getters, and each reaches the other lazily.
496
+ const sessionView = createSessionView({
497
+ store, historyEl, getSession,
498
+ liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet, gapClock,
499
+ bubbles, cards, markdown: markdownPlace,
500
+ capabilities: () => pageCapabilities,
501
+ page: {
502
+ setReviseAnchor, renderInitRow, setMarkdownWarning, setCapabilities, findInTurnRoots, appendToHistory,
503
+ setTurnRunning, mergeTurnTiming, applySessionPayload, turnEndStatus, replaceSelectedCard,
504
+ },
505
+ later: {
506
+ handlers: () => streamHandlers, composer: () => composer, ownerVerify: () => ownerVerify,
507
+ commandList: () => commandList, initTasks: () => initTasks, resetTurnView: () => sessionSync.resetTurnView(),
508
+ },
509
+ });
510
+ const { forgetSession, historyOpts, readTurnEnd, endTurnView } = sessionView;
511
+ const sessionSync = createSessionSync({
512
+ store, historyEl, emptyEl, getSession, openStream,
513
+ liveTurn, turnDom, questionCards, contextChips, participantsControl,
514
+ view: sessionView,
515
+ page: { clearNotice, setSessionHash, setTurnRunning, setLiveStatus, replaceCard, addEndBubble },
516
+ later: {
517
+ handlers: () => streamHandlers, composer: () => composer, focusPrompt: (opts) => focusPrompt(opts),
518
+ sessionActions: () => sessionActions, ownerClaim: () => ownerClaim,
519
+ },
520
+ });
521
+ const { select, resync, followSelectedSession, followWokenWorker, workerGone } = sessionSync;
491
522
  // The enqueued_ids this page sent (from the /turn acks): only these come back
492
523
  // into the composer when their turn fails.
493
524
  const sentIds = new Set();
@@ -583,23 +614,6 @@ function openSessionEvents() {
583
614
 
584
615
  const EVENTS_REOPEN_MS = 3000;
585
616
 
586
- // The selected session's card changed: its owner and, without a live
587
- // stream, its status show in the info bar; a worker whose bridge is up
588
- // (a turn another client sent woke one, or a replacement after a kill)
589
- // gets the stream attached through one resync.
590
- function followSelectedSession(sess) {
591
- const streaming = !!(streamControl && streamControl.live);
592
- // A Verify gate that flips (a restart brought the feature) redraws the
593
- // cards' Verify fresh part: featureGates.
594
- store.batch(() => {
595
- store.update({ current: fieldsFromCard(sess) });
596
- store.setStatus(sess.status, "hub", { streaming });
597
- });
598
- if (!sess.bridge_up || streaming) return;
599
- if (resyncsInFlight > 0) resyncAgain = true;
600
- else resync();
601
- }
602
-
603
617
  // The header's scope chip: "<project> · all" in a project view (all links
604
618
  // to the same place without ?dir); "all projects" otherwise, with where a
605
619
  // new session starts on the start page.
@@ -670,7 +684,7 @@ const sessionActions = createSessionActions({
670
684
  addCreatedSession,
671
685
  fillOpener,
672
686
  restoreDraft,
673
- closeLiveStream: () => streamControl?.close(),
687
+ closeLiveStream: () => sessionSync.closeLive(),
674
688
  workerGone,
675
689
  stopSheet,
676
690
  });
@@ -841,32 +855,6 @@ function onInitEvent(type, data) {
841
855
  }, DONE_MS);
842
856
  }
843
857
 
844
- // Forget everything the page knew about the open session: its fields (the
845
- // info bar, composer, command list), the turn on view, its stream and
846
- // question cards, its init row, the payload's markdown warning and tip and
847
- // capabilities, and the composer's Verify claim and Revise (+keepVerify+:
848
- // the same session opened again keeps them). The one reset list select() and
849
- // clearSelection() share, so a field the previous session set (its
850
- // "delegated by" parent, its commands, its card actions) never shows for
851
- // the next one, also when the next one's read fails.
852
- function forgetSession({ keepVerify = false } = {}) {
853
- if (!keepVerify) ownerVerify.clear();
854
- if (!keepVerify) setReviseAnchor(null);
855
- store.batch(() => {
856
- store.replaceCurrent(emptySessionState());
857
- featureGates.prime(store.current);
858
- });
859
- commandList.close();
860
- resetTurnView();
861
- objectives.reset();
862
- seedInitTasks(initTasks, []);
863
- renderInitRow();
864
- setMarkdownWarning(null);
865
- markdownTip.show(null);
866
- setCapabilities(null, null);
867
- composer.newVisit();
868
- }
869
-
870
858
  function clearSelection() {
871
859
  store.batch(() => {
872
860
  store.update({ selected: null });
@@ -900,232 +888,6 @@ promptEl.addEventListener("input", () => {
900
888
  setReviseAnchor(null);
901
889
  });
902
890
 
903
- async function select(id) {
904
- clearNotice();
905
- const same = store.selected === id;
906
- // Its synchronous part in one batch: the active card, the composer and
907
- // the bar redraw once, at its end (never across the await).
908
- store.batch(() => {
909
- store.update({ selected: id });
910
- setSessionHash(id);
911
- historyEl.replaceChildren(hintEl("Loading…"));
912
- emptyEl.classList.add("hidden");
913
- resyncAttempts = 0; // this session has its own re-read budget
914
- forgetSession({ keepVerify: same });
915
- contextChips.load(id);
916
- participantsControl.load(id);
917
- });
918
- await resync();
919
- // A folded composer stays folded: typing on the page opens it.
920
- focusPrompt({ open: false });
921
- }
922
-
923
- // Clear everything that belongs to one turn's rendering.
924
- function resetTurnView() {
925
- closeStream();
926
- // workerGone and a re-render come through here: the answer_display wait
927
- // goes too.
928
- liveTurn.forget();
929
- questionCards.removeQuestion();
930
- questionCards.forgetContinue();
931
- setTurnRunning(false);
932
- }
933
-
934
- // A re-read that failed (the phone still offline, chi web a moment): try it
935
- // again, backing off, and stop when the tries run out. The running turn's DOM
936
- // is left alone meanwhile: a worker that still owns the turn keeps showing it running,
937
- // and the hub's next event for the session is the fallback once the tries end.
938
- const RESYNC_RETRIES = 3;
939
- let resyncAttempts = 0;
940
-
941
- function retryResync(id, { endText = null } = {}) {
942
- if (id !== store.selected) return;
943
- const { attempt, delayMs } = resyncRetry({ attempts: resyncAttempts, max: RESYNC_RETRIES, baseMs: STREAM_RETRY_MS });
944
- if (delayMs === null) return;
945
- resyncAttempts = attempt;
946
- setTimeout(() => {
947
- if (id !== store.selected || (streamControl && streamControl.live)) return;
948
- resync({ endText });
949
- }, delayMs);
950
- }
951
-
952
- // (Re)render the selected session from the server and stream on from the
953
- // event_seq that render covers. Used on select, when the stream resets
954
- // (its cursor could not be replayed) and when it dropped (workerGone).
955
- // Without a live bridge there is nothing to stream: the session's next
956
- // event with bridge_up (a worker another client woke) resyncs again
957
- // (followSelectedSession); a bridge_up that arrived while this ran is
958
- // taken by the tail. +endText+: what workerGone said about the turn the
959
- // worker left unfinished; shown again after the re-render when no worker
960
- // took over.
961
- async function resync({ endText = null } = {}) {
962
- const id = store.selected;
963
- if (!id) return;
964
- resyncsInFlight += 1;
965
- let data;
966
- try {
967
- try {
968
- data = await getSession(id);
969
- } catch (e) {
970
- if (e.status === 404) return leaveGoneSession(id, "not_found");
971
- if (id === store.selected) {
972
- historyEl.replaceChildren(hintEl(`Error: ${e.message}`));
973
- retryResync(id, { endText });
974
- }
975
- return;
976
- }
977
- resyncAttempts = 0;
978
- if (id !== store.selected) return;
979
- // An archived session opens folded: decided once per visit, from its
980
- // first answer (the list may not hold it yet, or ever under ?dir).
981
- composer.decideVisit(data.session?.archived);
982
- const kept = keptCommandBubbles(historyEl, id);
983
- resetTurnView();
984
- renderSessionView(data, { kept });
985
- ownerClaim.showPending();
986
- // Preview is read-only: a worker is woken only by POST /turn, so attach
987
- // only when a live bridge exists.
988
- store.update({ current: { streamSeq: typeof data.last_event_seq === "number" ? (data.last_event_id || data.last_event_seq) : null } });
989
- if (store.current.streamSeq !== null) startStream(id, store.current.streamSeq);
990
- else if (endText) addEndBubble(endText);
991
- } finally {
992
- resyncsInFlight -= 1;
993
- if (resyncsInFlight === 0 && resyncAgain) {
994
- resyncAgain = false;
995
- if (id === store.selected && !(streamControl && streamControl.live)) resync();
996
- }
997
- }
998
- }
999
-
1000
- // A session view: its messages, then the turn in progress and the queued
1001
- // prompts (a live worker's snapshot) replayed through the stream handlers,
1002
- // then a pending question.
1003
- function renderSessionView(data, { kept = [] } = {}) {
1004
- setMarkdownWarning(data.markdown_warning);
1005
- markdownTip.show(data.markdown_tip);
1006
- setCapabilities(data.capabilities, data.editor_url);
1007
- // The saved fill (when there is one) goes in here too, so a reloaded or
1008
- // stopped session shows it before its next turn (a running turn's replay
1009
- // below streams over it).
1010
- const { status, ...fields } = sessionStateFrom(data);
1011
- // The fields in one batch (their chips' popovers, the bar); the replay's
1012
- // own redraws below stay where they run.
1013
- store.batch(() => {
1014
- store.update({ current: fields });
1015
- store.setStatus(status, "payload");
1016
- featureGates.prime(store.current);
1017
- });
1018
- liveTurn.timing.ended = store.current.timing.turnRecords.length;
1019
- const activeTurnId = store.current.timing.activeTurn?.id || null;
1020
- if (data.messages && data.messages.length) renderHistory(data.messages, data);
1021
- else renderHistory(data.history || []);
1022
- seedWorkingSet(data);
1023
- objectives.seed(data.objectives);
1024
- restoreCommandBubbles(historyEl, kept);
1025
- // A failed turn's prompt went back to the user: shown after the
1026
- // conversation, marked failed, as it was live (prompt_restored).
1027
- const failedPrompt = data.failed_turn ? makeUserBubble(data.failed_turn.prompt, { state: "failed" }) : null;
1028
- if (failedPrompt) {
1029
- failedPrompt.dataset.failedTurn = "1";
1030
- addEndBubble(failedTurnText(data.failed_turn));
1031
- }
1032
- seedSeenFromDom();
1033
- seedInitTasks(initTasks, data.init_tasks);
1034
- renderInitRow();
1035
- // A guardrail file that failed to load, announced before this page
1036
- // joined: where it came (the snapshot's cards), else at the end.
1037
- const loadWarned = (label) => (data.cards || []).some((c) => c?.type === "guardrail_warning" && (c.label || "guardrails") === label);
1038
- if (!loadWarned("guardrails")) showGuardrailWarning(data.guardrail_warning);
1039
- if (!loadWarned("plugins")) showGuardrailWarning(data.plugin_warning, "plugins");
1040
- // A live worker's last cards and between-turns notices, where they
1041
- // arrived; the running turn's go into its step once it is drawn.
1042
- const snapshotCards = splitSnapshotCards(data.cards, pageCapabilities);
1043
- // Above a failed turn's prompt: it came after them, and it is no turn.
1044
- placeSnapshotCards(snapshotCards.placed, { before: failedPrompt });
1045
- // The recap saved with the session (also a stopped one's), else a live
1046
- // worker's from before saved_recap existed. After the cards: the last
1047
- // turn's check-in notice goes to the end, and the recap closes the page.
1048
- const saved = data.saved_recap;
1049
- if (saved) showRecap(saved.text, saved.turns_since, saved.created_at || null, saved.opening_id || null);
1050
- else showRecap(data.recap);
1051
- // chi web's unfold of the join (TurnAccumulator.join_events): the turn in
1052
- // progress and the queue behind it as the live events that draw them.
1053
- const replay = data.replay ?? [];
1054
- // Marked replayed: a call's duration isn't timed from the replay's clock.
1055
- replay.forEach((event) => streamHandlers[event.type]?.({ ...event, replayed: true }));
1056
- // A join mid-generation: the worker's word on it clocks the delivery line.
1057
- const gen = data.current_turn?.generation;
1058
- liveTurn.serverGen = gen ? { ...gen, at: Date.now() } : null;
1059
- if (!data.current_turn) {
1060
- setTurnRunning(store.current.status === "running");
1061
- // Running with no turn to draw: the stage's status row still holds Stop turn.
1062
- turnDom.runningWithoutTurn?.(liveTurn.running);
1063
- if (liveTurn.running && store.current.timing.activeTurn?.started_at) liveTurn.timing.start(store.current.timing.activeTurn.started_at, activeTurnId);
1064
- } else if (liveTurn.running) {
1065
- // The live line's turn: the running turn's record's (the replayed
1066
- // turn_started carries the same id, on both unfolds).
1067
- liveTurn.timing.turnId = activeTurnId;
1068
- }
1069
- turnDom.flush();
1070
- snapshotCards.current.forEach((card) => upsertCard(card));
1071
- snapshotCards.during.forEach((card) => upsertCard(card));
1072
- // A question the worker is blocked on (also after a reload).
1073
- if (data.pending_question && data.pending_question.id && data.pending_question.status === "pending") {
1074
- // Its refs on the asking step, as question_requested puts them.
1075
- if (data.pending_question.refs) turnDom.questionRefs(data.pending_question.refs);
1076
- questionCards.renderQuestion(data.pending_question);
1077
- // The turn's replay drew it as asked; the snapshot knows whether it is
1078
- // relayed to the parent now.
1079
- questionCards.markRelayed(data.pending_question.id, data.pending_question.relayed_to || null);
1080
- }
1081
- // A turn ran out of iterations and waits for a yes or no.
1082
- if (data.continue_offer) questionCards.renderContinue(data.continue_offer);
1083
- // A whole view drawn: the composer and the bar once more (the working
1084
- // set's seed may change the bar's chip).
1085
- store.batch(() => {
1086
- store.touch("composer");
1087
- store.touch("infoBar");
1088
- });
1089
- }
1090
-
1091
- // The working set's turns from a session's messages, as turnHistoryNodes
1092
- // numbers them: the drawn ones (the running turn, which the replay draws
1093
- // in the stage, has no drawing yet).
1094
- function seedWorkingSet(data) {
1095
- if (!workingSet) return;
1096
- const items = data.messages || [];
1097
- const groups = typeof items[0] === "object" && items[0]?.role ? turnGroups(items, store.current.timing, { drawings: data.turn_drawings }).filter((g) => g.kind === "turn") : [];
1098
- workingSet.seed(groups.map((g, i) => {
1099
- const text = String(items[g.user]?.content ?? "").replace(/\s+/g, " ").trim();
1100
- return { items: groupItems(g, i), prompt: text.length > 60 ? `${text.slice(0, 59)}\u2026` : text };
1101
- }));
1102
- }
1103
-
1104
- // turnHistoryNodes' options for a read's +data+: its turns' drawings
1105
- // (turn_drawing.js), cards (a drawn card's body) and the running turn's id
1106
- // (its prompt has no drawing yet: a plain row, no miss).
1107
- const historyOpts = (data = {}) => ({ thumbs: (images) => thumbsTemplate(store.selected, images), workingSet: !!workingSet,
1108
- drawings: data.turn_drawings || null, cards: data.cards || null, capabilities: pageCapabilities,
1109
- runningTurnId: data.current_turn?.turn_id || null });
1110
-
1111
- function renderHistory(items, data = {}) {
1112
- gapClock.seed(null);
1113
- if (!items.length) {
1114
- historyEl.replaceChildren(hintEl("No output yet. Send a message."));
1115
- return;
1116
- }
1117
- if (typeof items[0] === "object" && items[0].role) {
1118
- historyEl.replaceChildren(turnHistoryNodes(items, store.current.timing, historyOpts(data)));
1119
- ownerVerify.renderSaved();
1120
- // The live dividers count from the history's last activity.
1121
- gapClock.seed(lastActivity(turnGroups(items, store.current.timing, { drawings: data.turn_drawings }), items));
1122
- linkTextRefs();
1123
- } else {
1124
- historyEl.replaceChildren(...items.map((c) => elementOf(outputBubbleTemplate(c))));
1125
- }
1126
- historyEl.scrollTop = historyEl.scrollHeight;
1127
- }
1128
-
1129
891
  function setMarkdownWarning(warning) {
1130
892
  if (!warning) {
1131
893
  markdownWarningEl.hidden = true;
@@ -1154,43 +916,6 @@ installRefClicks(document.body, pageViewer, {
1154
916
  copy: async (text) => showToast((await copyText(text)) ? "Path copied" : "Couldn't copy the path"),
1155
917
  });
1156
918
 
1157
- async function readTurnEnd() {
1158
- if (!store.selected) return;
1159
- const id = store.selected;
1160
- // The line and the turn this read is for, before the await: a turn
1161
- // queued behind this one may start (a new live line) before it lands.
1162
- const line = liveTurn.timing.capture();
1163
- const still = stillOn(openId);
1164
- try {
1165
- const d = await getSession(id, { tail: true, recent: true, turnId: line.turnId });
1166
- if (!still()) return;
1167
- if (d.session) {
1168
- if (!(await mergeTurnTiming(id, d.timing))) return;
1169
- liveTurn.timing.finishLine(line);
1170
- // The rest in one batch: the bar and the lists redraw once, after the
1171
- // answer's markdown.
1172
- store.batch(() => {
1173
- // The notes chip: the first turn's build (or a /model) records them.
1174
- applySessionPayload(d, { fields: ["usedMemories", "promptNotes"] });
1175
- turnEndStatus(d);
1176
- setMarkdownWarning(d.markdown_warning);
1177
- markdownTip.show(d.markdown_tip);
1178
- setCapabilities(d.capabilities, d.editor_url);
1179
- if (Array.isArray(d.messages)) applyFinalMarkdown(d.messages);
1180
- // Its card, replaced (replaceSelectedCard).
1181
- replaceSelectedCard((sess) => ({ ...sess, used_memory_names: store.current.usedMemories.slice(), status: store.current.status }));
1182
- });
1183
- }
1184
- } catch (_) {
1185
- // A failed read (the server or worker gone a moment) leaves the answer
1186
- // as the stream drew it, plain text: the session's next load renders it.
1187
- }
1188
- }
1189
-
1190
- function seedSeenFromDom() {
1191
- shownTexts.seed(findInTurnRoots(".bubble").map((b) => normalize(b.textContent)));
1192
- }
1193
-
1194
919
  // Sticky-follow scroll: only auto-scroll to the bottom while the user is
1195
920
  // already near it; never yank them back down mid-read. Capture the decision
1196
921
  // BEFORE any DOM mutation that grows the content (new chunk / row / thinking
@@ -1205,29 +930,6 @@ function atHistoryEnd() {
1205
930
  return shouldFollowScroll({ scrollHeight, scrollTop, clientHeight });
1206
931
  }
1207
932
 
1208
- // Everything a turn's end (completed, canceled, failed) closes: then its
1209
- // end line (+endText+, the cancel or failed line), then the step cards that
1210
- // left the collapsed block (card.js leavesBlock), where a reload puts them.
1211
- function endTurnView(kind, endText = null, { emptyAnswer = null, stopped = false } = {}) {
1212
- setTurnRunning(false);
1213
- // Every ended turn has a record (completed, canceled, failed); a worker
1214
- // gone mid-turn is re-rendered (resync), which counts again.
1215
- if (kind !== "gone") liveTurn.timing.ended += 1;
1216
- // A completed turn with no answer: its notice where the answer goes
1217
- // (the turn block places it), else after the turn; before the timing.
1218
- const endNote = emptyAnswer ? elementOf(emptyAnswerTemplate(emptyAnswer)) : null;
1219
- const kept = turnDom.turnEnded({ kind, endNote, emptyAnswer: !!emptyAnswer, turnId: liveTurn.timing.turnId }) || [];
1220
- if (endNote && !endNote.isConnected) appendToHistory(endNote);
1221
- liveTurn.timing.finish({ canceled: kind === "canceled" });
1222
- if (endText) addEndBubble(endText, { stopped });
1223
- if (kept.length) {
1224
- kept.forEach((el) => appendToHistory(el));
1225
- if (!turnDom.holds()) historyEl.scrollTop = historyEl.scrollHeight;
1226
- }
1227
- // The question dies with its turn (the worker stopped waiting).
1228
- if (questionCards.pendingQuestion()) questionCards.resolveQuestion(questionCards.pendingQuestion().id, { cancelled: true, reason: "turn ended" });
1229
- }
1230
-
1231
933
  infoTextEl.addEventListener("click", (e) => {
1232
934
  if (e.target.closest(".worker-restart")) versionNotices.restart();
1233
935
  // Pushed as openAllView does, so the view's back returns here.
@@ -1289,7 +991,7 @@ function updateInfoBar() {
1289
991
  annotateBar?.refresh();
1290
992
  const { buttons, bar } = sessionBar({
1291
993
  id: store.selected, state: store.current, sessions: store.sessions, versions: versionNotices.versions(), cardTitle: (s) => lists.cardTitle(s),
1292
- continuing: sessionActions.continuing, restarting: versionNotices.restarting, streaming: !!streamControl, running: liveTurn.running, waiting: sessionWaits(),
994
+ continuing: sessionActions.continuing, restarting: versionNotices.restarting, streaming: sessionSync.hasStream(), running: liveTurn.running, waiting: sessionWaits(),
1293
995
  workingSet: workingSet ? workingSet.chip() : undefined, participants: participantsControl.chip(),
1294
996
  });
1295
997
  const stopBtn = document.getElementById("infoStopBtn");
@@ -1432,60 +1134,6 @@ function turnEndStatus(data) {
1432
1134
  if (status) store.setStatus(status, "turnEnd", { running: liveTurn.running });
1433
1135
  }
1434
1136
 
1435
- // A turn or command just woke the session's worker: follow its stream if
1436
- // none is open, from the render's cursor. A render with none (no worker
1437
- // then) streams from 0, the start of a new worker's events; should that
1438
- // worker have been up already, turn_started says so (replaysDrawnTurn).
1439
- function followWokenWorker() {
1440
- if (streamControl?.live) return;
1441
- startStream(store.selected, store.current.streamSeq ?? 0);
1442
- store.update({ current: { streamFromGuess: store.current.streamSeq === null } });
1443
- }
1444
-
1445
- function startStream(id, fromSeq) {
1446
- store.update({ current: { streamFromGuess: false } });
1447
- if (streamControl) {
1448
- streamControl.close();
1449
- streamControl = null;
1450
- }
1451
- streamControl = openStream(id, fromSeq, streamHandlers, {
1452
- // The stream dropped or never opened: the worker left (idle exit, stop,
1453
- // crash) or is starting. Its cursor means nothing to the next worker
1454
- // (event_seq starts over), so re-read the session once one is live.
1455
- onStreamClosed: () => workerGone(id),
1456
- onStreamError: () => workerGone(id, { opened: false }),
1457
- });
1458
- store.touch("infoBar"); // streaming
1459
- }
1460
-
1461
- // +opened+ false: the stream never delivered a frame (the proxy answered
1462
- // 503, or the bridge refused it), so a retry waits a moment rather than
1463
- // spinning through resync → stream → error.
1464
- const STREAM_RETRY_MS = 3000;
1465
- function workerGone(id, { opened = true } = {}) {
1466
- streamControl = null;
1467
- if (id !== store.selected) return;
1468
- // A turn that was running is over only when the worker really left: a
1469
- // stream that merely dropped (no stop, it was open) waits for the re-read.
1470
- const stopped = sessionActions.stoppingId() === id;
1471
- const { endNow, endText } = streamDropEnd({ turnRunning: liveTurn.running, stopped, opened });
1472
- if (endNow) endTurnView("gone", endText, { stopped });
1473
- store.batch(() => {
1474
- if (endNow && !stopped) setLiveStatus("idle");
1475
- store.update({ current: { ...(store.current.owner === "worker" ? { owner: null } : {}), bridgeUp: false } });
1476
- // Its card says "live" (the list's owner, or setLiveStatus's) until the
1477
- // hub's event says otherwise: the worker is gone now, as far as this
1478
- // tab can tell.
1479
- if (store.sessions.find((s) => s.id === id)?.owner === "worker") replaceCard(id, withoutWorker);
1480
- store.touch("infoBar"); // streaming
1481
- });
1482
- // Once: a worker still alive with a bridge (the stream dropped, not the
1483
- // worker: chi web restarted) reconnects right here. Otherwise the next
1484
- // worker's bridge_up event brings the stream back (followSelectedSession).
1485
- if (opened) resync({ endText });
1486
- else setTimeout(() => { if (id === store.selected && !(streamControl && streamControl.live)) resync({ endText }); }, STREAM_RETRY_MS);
1487
- }
1488
-
1489
1137
  // The stream's event handlers (stream_handlers.js); renderSessionView
1490
1138
  // replays a snapshot through them too.
1491
1139
  const streamHandlers = createStreamHandlers({
@@ -1513,11 +1161,7 @@ const streamHandlers = createStreamHandlers({
1513
1161
  store.update({ current: { streamFromGuess: false } });
1514
1162
  return guess;
1515
1163
  },
1516
- restart: () => {
1517
- streamControl?.close();
1518
- streamControl = null;
1519
- resync();
1520
- },
1164
+ restart: () => sessionSync.restart(),
1521
1165
  },
1522
1166
  composer: {
1523
1167
  empty: () => !composer.hasDraft(),
@@ -1560,15 +1204,6 @@ async function refreshTimingFromSession() {
1560
1204
  } catch (_) {}
1561
1205
  }
1562
1206
 
1563
-
1564
- function closeStream() {
1565
- turnDom.reset();
1566
- if (streamControl) {
1567
- streamControl.close();
1568
- streamControl = null;
1569
- }
1570
- }
1571
-
1572
1207
  // A session this tab just created: onto the list now, as the events would
1573
1208
  // put it (they follow, with its owner and bridge_up).
1574
1209
  function addCreatedSession(created) {
@@ -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");
@@ -98,7 +98,7 @@ export function foldSignature(bar, buttons) {
98
98
  if (!bar) return "";
99
99
  const gear = bar.settings ? settingsChipModel(bar.settings) : null;
100
100
  return JSON.stringify([
101
- bar.id, bar.status, bar.model?.text, bar.model?.mismatch, gear?.text, gear?.own,
101
+ bar.id, bar.status, bar.statusText, bar.model?.text, bar.model?.mismatch, gear?.text, gear?.own,
102
102
  bar.toolkit?.summary?.name, bar.toolkit?.summary?.label, bar.toolkit?.defaultKit, bar.notes?.text,
103
103
  bar.workingSet ? [bar.workingSet.chip?.n] : (bar.memories || []).join(","),
104
104
  bar.participants?.text, bar.participants?.count,
@@ -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
  }