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