samagotchi 0.190.1 → 0.192.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 (106) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +61 -1
  3. data/docs/architecture.md +13 -11
  4. data/docs/bundles.md +1 -1
  5. data/docs/cli.md +17 -6
  6. data/docs/configuration.md +6 -1
  7. data/docs/context.md +8 -1
  8. data/docs/internals/attached-context.md +3 -1
  9. data/docs/internals/inline-widgets.md +2 -1
  10. data/docs/internals/participants.md +1 -5
  11. data/docs/internals/peers.md +15 -3
  12. data/docs/internals/remote-sessions.md +5 -2
  13. data/docs/internals/session-lifecycle.md +233 -18
  14. data/docs/internals/web-frontend.md +107 -9
  15. data/docs/peers.md +3 -1
  16. data/docs/plugins.md +2 -1
  17. data/docs/scheduling.md +31 -7
  18. data/docs/sessions.md +12 -12
  19. data/docs/sub-agent.md +1 -1
  20. data/docs/testing.md +1 -2
  21. data/docs/thin-clients.md +98 -12
  22. data/lib/samagotchi/bridge.rb +3 -4
  23. data/lib/samagotchi/bundles/mcp/manifest.yml +4 -2
  24. data/lib/samagotchi/bundles/mcp/plugin.rb +7 -398
  25. data/lib/samagotchi/bundles/mcp/server_config.rb +158 -0
  26. data/lib/samagotchi/bundles/mcp/sign_in.rb +261 -0
  27. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  28. data/lib/samagotchi/client_id.rb +2 -19
  29. data/lib/samagotchi/compat.rb +1 -7
  30. data/lib/samagotchi/config.rb +3 -0
  31. data/lib/samagotchi/context_command.rb +5 -1
  32. data/lib/samagotchi/context_sources.rb +28 -0
  33. data/lib/samagotchi/continue_intent.rb +23 -43
  34. data/lib/samagotchi/delivery.rb +1 -5
  35. data/lib/samagotchi/hold_stop.rb +5 -2
  36. data/lib/samagotchi/participants.rb +13 -5
  37. data/lib/samagotchi/peer_say.rb +29 -14
  38. data/lib/samagotchi/plugin/sessions.rb +9 -5
  39. data/lib/samagotchi/schedule_command.rb +6 -1
  40. data/lib/samagotchi/schedules/prune_part.rb +162 -41
  41. data/lib/samagotchi/schedules.rb +32 -15
  42. data/lib/samagotchi/send_command.rb +6 -6
  43. data/lib/samagotchi/session.rb +7 -0
  44. data/lib/samagotchi/session_access/ask.rb +9 -3
  45. data/lib/samagotchi/session_access/exchange.rb +6 -2
  46. data/lib/samagotchi/session_access/local.rb +103 -32
  47. data/lib/samagotchi/session_access/remote.rb +10 -9
  48. data/lib/samagotchi/session_access/remote_peers.rb +2 -2
  49. data/lib/samagotchi/session_access.rb +17 -7
  50. data/lib/samagotchi/session_chain/delete.rb +100 -47
  51. data/lib/samagotchi/session_chain/delete_preview.rb +9 -5
  52. data/lib/samagotchi/session_chain/successor.rb +78 -0
  53. data/lib/samagotchi/session_continue.rb +112 -42
  54. data/lib/samagotchi/session_inbox.rb +1 -1
  55. data/lib/samagotchi/session_inbox_delivery.rb +111 -25
  56. data/lib/samagotchi/session_lifecycle/allowed.rb +20 -1
  57. data/lib/samagotchi/session_lifecycle/reading.rb +9 -3
  58. data/lib/samagotchi/session_lifecycle.rb +17 -2
  59. data/lib/samagotchi/session_manager/delivery.rb +61 -29
  60. data/lib/samagotchi/session_manager/emptiness.rb +5 -2
  61. data/lib/samagotchi/session_manager/lifecycle.rb +68 -19
  62. data/lib/samagotchi/session_manager/listing.rb +2 -1
  63. data/lib/samagotchi/session_manager/removal.rb +67 -13
  64. data/lib/samagotchi/session_manager/spawn.rb +16 -9
  65. data/lib/samagotchi/session_manager.rb +4 -0
  66. data/lib/samagotchi/session_retention.rb +28 -7
  67. data/lib/samagotchi/session_row.rb +2 -0
  68. data/lib/samagotchi/session_transition.rb +361 -0
  69. data/lib/samagotchi/sessions_command.rb +1 -1
  70. data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +2 -0
  71. data/lib/samagotchi/tools/cancel_schedule.rb +10 -6
  72. data/lib/samagotchi/version.rb +1 -1
  73. data/lib/samagotchi/web/app.rb +13 -3
  74. data/lib/samagotchi/web/ask_create.rb +138 -0
  75. data/lib/samagotchi/web/ask_routes.rb +56 -9
  76. data/lib/samagotchi/web/last_ask.rb +78 -0
  77. data/lib/samagotchi/web/peer_routes.rb +5 -2
  78. data/lib/samagotchi/web/public/answer_refs.js +3 -9
  79. data/lib/samagotchi/web/public/answer_write.js +28 -0
  80. data/lib/samagotchi/web/public/app.js +72 -96
  81. data/lib/samagotchi/web/public/block_fix.js +30 -12
  82. data/lib/samagotchi/web/public/chains.js +3 -1
  83. data/lib/samagotchi/web/public/command_list.js +5 -3
  84. data/lib/samagotchi/web/public/composer.js +9 -6
  85. data/lib/samagotchi/web/public/composer_mount.js +18 -11
  86. data/lib/samagotchi/web/public/draft_keys.js +10 -0
  87. data/lib/samagotchi/web/public/drafts.js +278 -0
  88. data/lib/samagotchi/web/public/owner_claim.js +7 -12
  89. data/lib/samagotchi/web/public/prompt_history.js +6 -0
  90. data/lib/samagotchi/web/public/send_turn.js +51 -20
  91. data/lib/samagotchi/web/public/session_actions.js +80 -16
  92. data/lib/samagotchi/web/public/session_prefs.js +9 -3
  93. data/lib/samagotchi/web/public/session_view.js +7 -2
  94. data/lib/samagotchi/web/public/turn_events.js +0 -2
  95. data/lib/samagotchi/web/public/unqueue.js +22 -9
  96. data/lib/samagotchi/web/public/viewer_self.js +1 -6
  97. data/lib/samagotchi/web/public/views.js +12 -1
  98. data/lib/samagotchi/web/session_access_routes.rb +11 -5
  99. data/lib/samagotchi/web/session_control.rb +8 -1
  100. data/lib/samagotchi/web/session_create.rb +51 -34
  101. data/lib/samagotchi/web/session_hub.rb +52 -36
  102. data/lib/samagotchi/web/session_summary.rb +45 -7
  103. data/lib/samagotchi/web/start_dir.rb +6 -4
  104. data/lib/samagotchi/worker_boot.rb +28 -6
  105. data/lib/samagotchi/worker_presence.rb +22 -6
  106. metadata +10 -1
@@ -57,7 +57,7 @@ import { createObjectives } from "./objectives_wiring.js";
57
57
  import { trackWorkerUnavailable } from "./objectives_track.js";
58
58
  import { createGapClock } from "./time_gaps.js";
59
59
  import { createMarkdownPlace } from "./markdown_place.js";
60
- import { openerFill, openTitle, restoredComposer } from "./chains.js";
60
+ import { openerText, openTitle } from "./chains.js";
61
61
  import { createTaskStopper } from "./task_stop.js";
62
62
  import { createSystemOneWrongAction } from "./system_one_wrong.js";
63
63
  import { appendQuote } from "./annotations.js";
@@ -80,6 +80,7 @@ import { answerLabel, installReviseStacks, reviseChipTemplate, reviseWorkerUnava
80
80
  import { createQuestionCards } from "./question_cards.js";
81
81
  import { PROMPT_LINE_PX, PROMPT_MIN_PX } from "./composer_size.js";
82
82
  import { mountComposer } from "./composer_mount.js";
83
+ import { createDrafts } from "./drafts.js";
83
84
  import { hasHistory, historyLoader } from "./participant_history.js";
84
85
  import { createCommandList } from "./command_list.js";
85
86
  import { sessionHash } from "./route.js";
@@ -293,6 +294,8 @@ const featureGates = createFeatureGates([
293
294
  featureGates.prime(store.current);
294
295
  // The open session's id, for the stale-answer guards (latest.js stillOn).
295
296
  const openId = () => store.selected;
297
+ // The draft on view: the open session's, "" the start page's (drafts.js).
298
+ const shownDraft = () => store.selected ?? "";
296
299
  // The composer's armed Revise ({turn_id, label}: the answer the next
297
300
  // message rewrites), shown as its chip; Verify's lifecycle (an emptied
298
301
  // composer, another session, the send's ack let go of it). Set only
@@ -324,15 +327,6 @@ function restoreRevise(anchor) {
324
327
  setReviseAnchor({ turn_id: anchor.turn_id, label: answerLabel(answer) });
325
328
  }
326
329
  let annotateBar = null;
327
- // The session the composer's text was last written in ("" the start page,
328
- // undefined unknown): the composer is one for every session, and continue →
329
- // keeps only a draft of its own (fillOpener).
330
- let draftFrom;
331
- // Record that the composer's text was written now, in session +id+ (default
332
- // the open one). Every write of text into the composer comes through here.
333
- function noteDraft(id) {
334
- draftFrom = id ?? store.selected ?? "";
335
- }
336
330
  // The session list's stream (GET /api/events); null while the page falls
337
331
  // back to fetching (a chi web without a hub).
338
332
  let eventsControl = null;
@@ -476,7 +470,7 @@ const deliveryControl = createDeliveryControl({
476
470
  participantTurn: !!liveTurn.participantTurn, viewerTurn: participant?.deliveryTurn() ?? null,
477
471
  };
478
472
  },
479
- composerEmpty: () => !composer.hasDraft(),
473
+ composerEmpty: () => !drafts.has(shownDraft()),
480
474
  history: hasHistory(viewer),
481
475
  send: (delivery) => handleSendTurn({ delivery }),
482
476
  });
@@ -558,6 +552,7 @@ const sessionView = createSessionView({
558
552
  later: {
559
553
  handlers: () => streamHandlers, composer: () => composer, ownerVerify: () => ownerVerify,
560
554
  commandList: () => commandList, initTasks: () => initTasks, resetTurnView: () => sessionSync.resetTurnView(),
555
+ drafts: () => drafts,
561
556
  },
562
557
  });
563
558
  const { forgetSession, readTurnEnd, endTurnView } = sessionView;
@@ -745,8 +740,18 @@ const sessionActions = createSessionActions({
745
740
  showNotice,
746
741
  toast: showToast,
747
742
  addCreatedSession,
748
- fillOpener,
749
- restoreDraft,
743
+ // Continue →: the session's draft to the new link (else its opener), then shown once it opens.
744
+ handOverDraft: (from, to, created) => drafts.handOver(from, to, created ? openerText(created) : null),
745
+ revealDraft,
746
+ // Kept for an older cached session_actions.js (it calls them after its select), until after the next release.
747
+ fillOpener: (created, continuedId) => {
748
+ drafts.handOver(continuedId, created.id, openerText(created));
749
+ revealDraft();
750
+ return null;
751
+ },
752
+ restoreDraft: () => {},
753
+ moveDraft: (from, to) => drafts.move(from, to),
754
+ dropDraft: (id) => drafts.drop(id),
750
755
  closeLiveStream: () => sessionSync.closeLive(),
751
756
  workerGone,
752
757
  stopSheet,
@@ -788,12 +793,12 @@ const views = createViews({
788
793
  select, clearSelection, ownerClaim: () => ownerClaim, pages: pagesUi?.pageView ?? null, pagesList: pagesUi?.pagesList ?? null,
789
794
  allViewOpened: () => pagesUi?.allViewOpened(),
790
795
  });
791
- const { allViewOpen, openAllView, closeAllView, leaveAllView, setSessionHash, selectFromHash, applyView, pageOpen, pagesAreaOpen } = views;
796
+ const { allViewOpen, openAllView, closeAllView, leaveAllView, setSessionHash, keepSessionHash, selectFromHash, applyView, pageOpen } = views;
792
797
  // The page's claim links (owner_claim.js): one opened here, once drawn, and
793
798
  // annotate's Copy link.
794
799
  const ownerClaim = createOwnerClaim({
795
800
  historyEl, store, claimTarget: () => participantsControl?.claimTarget() ?? null,
796
- toast: (...args) => showToast(...args), copyText, allViewOpen, pagesAreaOpen,
801
+ toast: (...args) => showToast(...args), copyText, keepSessionHash,
797
802
  home: document.body.dataset.home || "",
798
803
  });
799
804
 
@@ -875,7 +880,7 @@ function clearNotice() {
875
880
  noticeEl.textContent = "";
876
881
  }
877
882
  promptEl.addEventListener("input", clearNotice);
878
- promptEl.addEventListener("input", () => noteDraft());
883
+ promptEl.addEventListener("input", () => drafts.syncFromView());
879
884
  // An emptied composer lets go of its Verify claim and its Revise.
880
885
  promptEl.addEventListener("input", () => {
881
886
  if (promptEl.value.trim()) return;
@@ -1134,15 +1139,11 @@ const streamHandlers = observeCards(cardRegistry, (participant ? participant.wra
1134
1139
  restart: () => sessionSync.restart(),
1135
1140
  },
1136
1141
  composer: {
1137
- empty: () => !composer.hasDraft(),
1138
- refill: (text) => {
1139
- // A failed turn's line back: seen, so the composer opens (this visit).
1140
- openForVisit();
1141
- promptEl.value = text;
1142
- noteDraft();
1143
- fitPrompt();
1144
- },
1145
- setChips,
1142
+ empty: () => !drafts.has(shownDraft()),
1143
+ // A failed turn's line back: seen, so the composer opens (this visit).
1144
+ refill: (text) => drafts.setText(shownDraft(), text, { reveal: true }),
1145
+ // One list, the open session's (a property: an older cached stream_handlers.js calls it so too).
1146
+ setChips: (list) => drafts.putChips(shownDraft(), list),
1146
1147
  },
1147
1148
  getSession,
1148
1149
  // The page's hooks, passed as they are: function declarations (hoisted)
@@ -1199,8 +1200,8 @@ const composerCommands = viewer.can("session_controls") ? createComposerCommands
1199
1200
  },
1200
1201
  composer: {
1201
1202
  busy: () => { actionBtn.disabled = true; },
1202
- text: () => promptEl.value,
1203
- clear: () => clearComposer(),
1203
+ text: (id) => drafts.text(id ?? shownDraft()),
1204
+ clear: (id) => drafts.clear(id ?? shownDraft()),
1204
1205
  done: () => {
1205
1206
  actionBtn.disabled = store.current.owner === "tui";
1206
1207
  // A chip's command (the info bar) leaves a folded composer folded.
@@ -1229,16 +1230,21 @@ const sendTurnControl = createSendTurn({
1229
1230
  dir: scope.dir,
1230
1231
  startPage,
1231
1232
  takeDelivery: () => deliveryControl.take(),
1233
+ // The drafts by key (drafts.js); el, setChips and the key-less calls for an older cached send_turn.js.
1232
1234
  composer: {
1235
+ text: (key) => drafts.text(key), setText: (key, text) => drafts.setText(key, text),
1236
+ putChips: (key, list) => drafts.putChips(key, list), move: (from, to) => drafts.move(from, to),
1237
+ sending: (key, line) => drafts.sending(key, line), settle: (key, line) => drafts.settle(key, line),
1233
1238
  el: promptEl,
1234
1239
  button: actionBtn,
1235
- chips: () => composer.chips(),
1236
- setChips,
1240
+ chips: (key) => drafts.chips(key ?? shownDraft()),
1241
+ setChips: (list) => drafts.putChips(shownDraft(), list),
1237
1242
  fit: fitPrompt,
1238
- clear: clearComposer,
1243
+ clear: (key) => drafts.clear(key ?? shownDraft()),
1239
1244
  openForVisit: () => openForVisit(),
1240
1245
  focus: () => focusPrompt(),
1241
- noteDraft,
1246
+ // An older cached send_turn.js wrote the box itself, then called it.
1247
+ noteDraft: () => drafts.syncFromView(),
1242
1248
  },
1243
1249
  historyEl,
1244
1250
  turnDom,
@@ -1246,7 +1252,11 @@ const sendTurnControl = createSendTurn({
1246
1252
  bubbleById,
1247
1253
  addCommandBubble,
1248
1254
  addCreatedSession,
1249
- select,
1255
+ // A create's select: the start page's draft goes with it (an older cached send_turn.js doesn't move it).
1256
+ select: (id) => {
1257
+ if (!store.selected) drafts.move("", id);
1258
+ return select(id);
1259
+ },
1250
1260
  showNotice,
1251
1261
  followWokenWorker,
1252
1262
  refreshHistory,
@@ -1265,17 +1275,12 @@ function runSessionCommand(line) {
1265
1275
  return composerCommands?.run(line);
1266
1276
  }
1267
1277
 
1268
- function clearComposer() {
1269
- promptEl.value = "";
1270
- fitPrompt();
1271
- }
1272
-
1273
1278
  // A queue (Alt+Enter) to a worker that can't queue (it would steer): not
1274
1279
  // sent, the text kept, a note says why.
1275
1280
  function queueRefused(altKey) {
1276
1281
  if (!store.selected || !liveTurn.running || store.current.workerFeatures.includes("delivery")) return false;
1277
1282
  if (!altKey) return false;
1278
- addCommandBubble({ label: null, line: promptEl.value.trim(), text: QUEUE_NEEDS_WORKER, failed: true });
1283
+ addCommandBubble({ label: null, line: drafts.text(shownDraft()).trim(), text: QUEUE_NEEDS_WORKER, failed: true });
1279
1284
  return true;
1280
1285
  }
1281
1286
 
@@ -1287,8 +1292,8 @@ async function handleCancel() {
1287
1292
 
1288
1293
  // The chi logo: back to the empty start, where the composer makes a new
1289
1294
  // session (from all sessions too).
1290
- // The typed draft stays in the composer: paste in a session, then + new session
1291
- // starts from it (with the model picker). clearSelection leaves #prompt alone.
1295
+ // The start page has its own draft (drafts.js): clearSelection's
1296
+ // forgetSession shows it, and the session left keeps its own.
1292
1297
  viewer.control($("#newBtn"), "sessions")?.addEventListener("click", () => {
1293
1298
  if (allViewOpen() || pageOpen() || views.listOpen?.()) leaveAllView("");
1294
1299
  clearSelection();
@@ -1303,7 +1308,7 @@ function promptMinPx() {
1303
1308
 
1304
1309
  // The composer (composer_mount.js): the box, its height, image chips, grip
1305
1310
  // and fold, ↑/↓ history and keys. The owner's parts come in as hooks: the
1306
- // draft's origin (noteDraft), the / list's keys, the delivery line's Esc and
1311
+ // recalled entry's write (drafts.js), the / list's keys, the delivery line's Esc and
1307
1312
  // queue, the info bar's drop while folded, typing anywhere.
1308
1313
  const composer = mountComposer({
1309
1314
  els: {
@@ -1312,7 +1317,9 @@ const composer = mountComposer({
1312
1317
  },
1313
1318
  minPx: promptMinPx,
1314
1319
  toast: (text) => showToast(text),
1315
- onWrite: () => noteDraft(),
1320
+ // A recalled ↑/↓ entry (an older cached mount writes it itself, then calls onWrite).
1321
+ setText: (text) => drafts.setText(shownDraft(), text),
1322
+ onWrite: () => drafts.syncFromView(),
1316
1323
  // ↑/↓: the owner's prompt history shared with the TUI; a participant's own messages here.
1317
1324
  loadHistory: historyLoader(viewer, { fetchHistory, selected: () => store.selected }),
1318
1325
  imagesOff: viewer.can("images") ? null : IMAGES_NOT_HERE,
@@ -1335,33 +1342,30 @@ const composer = mountComposer({
1335
1342
  });
1336
1343
  // Bound here, not hoisted: no top-level code above this line may call them.
1337
1344
  const { openForVisit, focusPrompt, drawFoldControls } = composer;
1345
+ // The drafts (drafts.js): the one writer of #prompt and the chips (the mount's, handed over).
1346
+ const drafts = createDrafts({
1347
+ promptEl, view: composer, fit: () => composer.fit(), shownKey: shownDraft,
1348
+ reveal: { openForVisit: () => openForVisit(), focusPrompt: () => focusPrompt() },
1349
+ });
1338
1350
  // Hoisted, for the hooks above that name them (called once the page runs).
1339
1351
  function fitPrompt() {
1340
1352
  composer.fit();
1341
1353
  }
1342
- function setChips(list) {
1343
- composer.setChips(list);
1344
- }
1345
1354
  function refreshHistory() {
1346
1355
  composer.refreshHistory();
1347
1356
  }
1348
1357
 
1358
+ // Edit: the removed text back into session id's draft when it is empty (never over a draft), open or not.
1359
+ const putBackTo = (text, id) => drafts.putBack(id, text);
1349
1360
  // The × on a message queued for after the turn takes it back (unqueue.js).
1350
1361
  const unqueue = createUnqueue({
1351
1362
  sessionId: () => store.selected,
1352
1363
  clientId,
1353
1364
  toast: (text, action, options) => showToast(text, action, options),
1354
1365
  copy: (text) => copyText(text),
1355
- // Edit: the removed text back into an empty composer (never over a draft).
1356
- putBack: (text) => {
1357
- if (composer.hasDraft()) return false;
1358
- openForVisit();
1359
- promptEl.value = text;
1360
- noteDraft();
1361
- fitPrompt();
1362
- promptEl.focus();
1363
- return true;
1364
- },
1366
+ putBackTo,
1367
+ // An older cached unqueue.js's: the open session's.
1368
+ putBack: (text) => !!putBackTo(text, shownDraft()),
1365
1369
  });
1366
1370
  turnRoots().forEach((root) => root.addEventListener("click", (e) => {
1367
1371
  unqueue.onClick(e);
@@ -1375,10 +1379,8 @@ const commandList = createCommandList({
1375
1379
  list: $("#commandList"),
1376
1380
  prompt: promptEl,
1377
1381
  commands: () => (viewer.can("session_controls") && store.selected && store.current.owner !== "tui" ? store.current.commands : []),
1378
- afterPick: () => {
1379
- noteDraft();
1380
- fitPrompt();
1381
- },
1382
+ // The pick's text (an older cached command_list.js wrote it itself and passes none).
1383
+ afterPick: (text) => (text === undefined ? drafts.syncFromView() : drafts.setText(shownDraft(), text)),
1382
1384
  });
1383
1385
 
1384
1386
  stopBtn?.addEventListener("click", () => sessionActions.stopSelected());
@@ -1388,32 +1390,9 @@ deleteBtn?.addEventListener("click", () => {
1388
1390
  continueBtn?.addEventListener("click", () => continueSelected());
1389
1391
  archiveBtn?.addEventListener("click", () => sessionActions.toggleArchiveSelected());
1390
1392
 
1391
- // The new link's composer: the opener (openerText: the previous link's own,
1392
- // else the constant). A draft written in this session (or the new link, or
1393
- // of unknown origin) stays instead; one carried over from another session or
1394
- // the start page gives way to the opener and is returned, for the toast's
1395
- // Restore draft (chains.js openerFill). +created+: the continue's 201;
1396
- // +continuedId+: the session continued.
1397
- // @return the displaced draft's text, or null
1398
- function fillOpener(created, continuedId) {
1399
- const { value, displaced } = openerFill({
1400
- text: promptEl.value, hasChips: composer.chips().length > 0, draftFrom, continuedId, linkId: created.id, created,
1401
- });
1402
- if (value === null) return null;
1403
- openForVisit();
1404
- promptEl.value = value;
1405
- noteDraft(created.id);
1406
- fitPrompt();
1407
- focusPrompt();
1408
- promptEl.setSelectionRange(promptEl.value.length, promptEl.value.length);
1409
- return displaced;
1410
- }
1411
-
1412
- // Restore draft (the continue toast's): +draft+ back into the composer,
1413
- // over the untouched +opener+ or an empty one, else after what is there
1414
- // (chains.js restoredComposer); in whatever session is open now.
1415
- function restoreDraft(draft, opener) {
1416
- fillComposer(restoredComposer({ current: promptEl.value, opener, draft }));
1393
+ // The open session's draft seen (a continue's new link): the composer opens, the box takes the focus, the caret at the end.
1394
+ function revealDraft() {
1395
+ drafts.setText(shownDraft(), drafts.text(shownDraft()), { reveal: true, focus: true, caretEnd: true });
1417
1396
  }
1418
1397
 
1419
1398
  const toasts = createToasts({ el: $("#toast"), onChange: placeToast });
@@ -1435,14 +1414,9 @@ function showToast(text, action = null, options = {}) { toasts.show(text, action
1435
1414
  // command line and the quote, or send it at once, and Copy link in a turn
1436
1415
  // (owner_claim.js linkFor).
1437
1416
  function fillComposer(text) {
1438
- openForVisit();
1439
- promptEl.value = text;
1440
- noteDraft();
1441
- fitPrompt();
1442
- focusPrompt();
1443
- promptEl.setSelectionRange(promptEl.value.length, promptEl.value.length);
1444
- promptEl.scrollTop = promptEl.scrollHeight;
1417
+ drafts.setText(shownDraft(), text, { reveal: true, focus: true, caretEnd: true });
1445
1418
  }
1419
+ const composerText = () => drafts.text(shownDraft());
1446
1420
 
1447
1421
  annotateBar = createAnnotateBar({
1448
1422
  presets: withVerify(parsePresets(document.body.dataset.annotatePresets)),
@@ -1452,14 +1426,14 @@ annotateBar = createAnnotateBar({
1452
1426
  canAnnotate: () => !!store.selected && store.current.owner !== "tui",
1453
1427
  roots: turnRoots,
1454
1428
  isLive: (root) => liveTurn.running && turnDom.containsLive(root),
1455
- onQuote: (text) => fillComposer(appendQuote(promptEl.value, text)),
1429
+ onQuote: (text) => fillComposer(appendQuote(composerText(), text)),
1456
1430
  onPreset: (preset, fields) => ownerVerify.set(preset === VERIFY_PRESET ? ownerVerify.anchorFor(fields) : null),
1457
1431
  actions: () => annotationActions(store.current.commands),
1458
1432
  running: () => liveTurn.running,
1459
1433
  onAction: (action, fields) => {
1460
1434
  const line = actionLine(action, fields);
1461
1435
  if (action.send) runSessionCommand(line);
1462
- else fillComposer(composerWithAction(promptEl.value, action, line));
1436
+ else fillComposer(composerWithAction(composerText(), action, line));
1463
1437
  },
1464
1438
  link: ownerClaim.linkFor,
1465
1439
  onLink: ownerClaim.copyLink,
@@ -1477,9 +1451,9 @@ turnDom.scrollEl.addEventListener("scroll", annotateBar.schedule, true);
1477
1451
  turnRoots().forEach((root) => installCopy(root));
1478
1452
  // chi-ui blocks (inline_widgets.js) are a core drawer, ahead of the bundles'
1479
1453
  // renderers; a picks' Fill reply only fills the composer.
1480
- const widgets = createWidgetDrawer({ roots: turnRoots(), composerText: () => promptEl.value, fillComposer });
1454
+ const widgets = createWidgetDrawer({ roots: turnRoots(), composerText, fillComposer });
1481
1455
  wireDiagrams({ roots: turnRoots(), sessionId: () => store.selected, drawers: [widgets], renderers: viewer.can("block_renderers"), pictures });
1482
- const blockFix = wireBlockFix({ viewer, roots: turnRoots(), store, getSession, composerText: () => promptEl.value, fillComposer, linkTextRefs: markdownPlace.linkTextRefs });
1456
+ const blockFix = wireBlockFix({ viewer, roots: turnRoots(), store, getSession, composerText, fillComposer, linkTextRefs: markdownPlace.linkTextRefs });
1483
1457
  // A steps block, a thinking block and the recap open and close by hand
1484
1458
  // with their height animated (details_motion.js), in the history and on
1485
1459
  // the stage.
@@ -1568,4 +1542,6 @@ if (viewer.can("models")) startPage.loadModels();
1568
1542
  // The list: the hub's stream when the browser has EventSource, else fetched.
1569
1543
  if (typeof globalThis.EventSource === "function") openSessionEvents();
1570
1544
  else refresh();
1545
+ // The draft on view from the start (over a value the browser may have put back), before the hash opens a session.
1546
+ drafts.show(store.selected ?? "");
1571
1547
  selectFromHash();
@@ -25,8 +25,10 @@
25
25
  // export on an old module would blank the page.
26
26
 
27
27
  import { api } from "./data.js";
28
- import { codeText, copySource } from "./copy.js";
28
+ import { codeText, showsAnswer } from "./copy.js";
29
+ import { writeAnswer } from "./answer_write.js";
29
30
  import { setAnswerRefs } from "./answer_refs.js";
31
+ import { normalize } from "./format.js";
30
32
  import { askText, markFixed, noteOf, setFixNote } from "./block_fix_note.js";
31
33
  import { stillOn } from "./latest.js";
32
34
  import { TEXTS } from "./text_roots.js";
@@ -130,7 +132,7 @@ export function createBlockFix({ roots, sessionId, features, bridgeUp = () => tr
130
132
  if (status !== 202) delete pre.dataset.blockFixAsked;
131
133
  if (status === 200 && body.state === "fixed") {
132
134
  // Drawn again and failed again after a redraw: no second one.
133
- if (redrawOnce(turnId, source)) refresh(id, turnId);
135
+ if (redrawOnce(turnId, source)) refresh(id, turnId, [pre]);
134
136
  else setFixNote(pre, "nohelp");
135
137
  return;
136
138
  }
@@ -166,27 +168,43 @@ export function createBlockFix({ roots, sessionId, features, bridgeUp = () => tr
166
168
  return bubble ? [...bubble.querySelectorAll(`${FAILED}[data-block-fix-asked]`)] : [];
167
169
  }
168
170
 
169
- // The fixed answer, read again and written as applyFinalAnswer writes it
170
- // (answer_refs.js), which can't find the bubble by its old text.
171
- async function refresh(id, turnId) {
171
+ // The blocks a redraw that can't be drawn settles: their note says so
172
+ // ("older": today's words and Ask in chat), and never a note already set
173
+ // to nohelp.
174
+ function settlePre(pres) {
175
+ for (const pre of pres) {
176
+ if (!pre.isConnected || !asking(pre)) continue;
177
+ setFixNote(pre, "older");
178
+ }
179
+ }
180
+
181
+ // The fixed answer, read again and written by answer_refs.js's writeAnswer
182
+ // (which, unlike applyFinalAnswer, can't find the bubble by its old text).
183
+ // +pres+: the blocks this redraw settles when it can't (the session
184
+ // left behind mid-read is not one: leave that page alone).
185
+ async function refresh(id, turnId, pres = []) {
172
186
  const still = stillOn(sessionId, id);
173
187
  let data;
174
188
  try {
175
189
  data = await getSession(id, { tail: true, turnId });
176
190
  } catch (_) {
191
+ if (still()) settlePre(pres);
177
192
  return;
178
193
  }
179
194
  if (!still()) return;
180
195
  const message = [...(data?.messages || [])].reverse().find((m) => m?.role === "assistant" && typeof m.html === "string");
181
196
  const bubble = bubbleOf(turnId);
182
- if (!message || !bubble) return;
197
+ if (!message || !bubble) {
198
+ settlePre(pres);
199
+ return;
200
+ }
183
201
  // A turn no prompt names (a reminder's) is read as the newest answer: only
184
202
  // that bubble may take it; another waits for the next full read.
185
- if (bubble !== newestAnswer() && bubble.getAttribute("data-copy-source") !== message.content) return;
186
- bubble.classList.add("markdown");
187
- bubble.setAttribute("data-copy-source", copySource(message));
188
- bubble.toggleAttribute("data-answer-display", typeof message.display === "string");
189
- bubble.innerHTML = message.html;
203
+ if (bubble !== newestAnswer() && !showsAnswer(bubble, message, normalize)) {
204
+ settlePre(pres);
205
+ return;
206
+ }
207
+ writeAnswer(bubble, message);
190
208
  setAnswerRefs(bubble, message.display_refs);
191
209
  linkTextRefs();
192
210
  }
@@ -206,7 +224,7 @@ export function createBlockFix({ roots, sessionId, features, bridgeUp = () => tr
206
224
  }
207
225
  if (data.state === "fixed") {
208
226
  for (const pre of relevant) redrawOnce(turnId, codeText(pre));
209
- refresh(sessionId(), turnId);
227
+ refresh(sessionId(), turnId, relevant);
210
228
  return;
211
229
  }
212
230
  for (const pre of relevant) setFixNote(pre, "nohelp");
@@ -25,7 +25,9 @@ export function openerText(created) {
25
25
  return typeof own === "string" && own.trim() ? own : CONTINUE_OPENER;
26
26
  }
27
27
 
28
- // What continue → does with the composer as the new link opens (app.js
28
+ // Kept for an older cached app.js until after the next release (this app.js hands the
29
+ // draft over instead: drafts.js handOver), with restoredComposer below.
30
+ // What continue → did with the composer as the new link opens (app.js
29
31
  // fillOpener): +text+ / +hasChips+ the composer now; +draftFrom+ the session
30
32
  // the text was last written in ("" the start page, undefined unknown);
31
33
  // +continuedId+ the session continued, +linkId+ the new link. An empty
@@ -19,7 +19,10 @@ function optionTemplate(command, i, active) {
19
19
  // @param list the list element (#commandList)
20
20
  // @param prompt the composer's textarea
21
21
  // @param commands () => the open session's commands ([] when it takes none)
22
- // @param afterPick () runs after a pick changed the composer's text (fit it)
22
+ // @param afterPick (text) writes a pick's text into the composer (the page's
23
+ // drafts, drafts.js: the list never writes the box; the caret goes after
24
+ // it). An older cached app.js's takes none: the pick does nothing until a
25
+ // reload.
23
26
  // @return {update(), close(), handleKey(e)}; handleKey returns whether the
24
27
  // open list took the key
25
28
  export function createCommandList({ list, prompt, commands, afterPick = () => {} }) {
@@ -61,9 +64,8 @@ export function createCommandList({ list, prompt, commands, afterPick = () => {}
61
64
  const pick = pickCommand(command.name, prompt.value, { enter });
62
65
  close();
63
66
  if (pick.send) return false;
64
- prompt.value = pick.text;
67
+ afterPick(pick.text);
65
68
  prompt.setSelectionRange(pick.text.length, pick.text.length);
66
- afterPick();
67
69
  prompt.focus();
68
70
  return true;
69
71
  }
@@ -62,8 +62,10 @@ export function routeSessionLine(prompt, { commands = [], images = 0, delivery =
62
62
  // failed(line, text) a failed command's bubble
63
63
  // failedElsewhere(line, text, id) a command to session id, no longer open, failed
64
64
  // ownedByTui() a plain terminal holds the session
65
- // composer: {busy(), text(), clear(), done()} the composer's send button
66
- // and text (text(): what it holds now)
65
+ // composer: {busy(), text(id), clear(id), done()} the composer's send
66
+ // button and the drafts (drafts.js) by the session's
67
+ // id (text(id): what that draft holds now; an older
68
+ // cached app.js's take no id: the one box)
67
69
  export function createComposerCommands(deps) {
68
70
  const { session, clientId, sendCommand, followWokenWorker, refreshHistory, failed, failedElsewhere, ownedByTui,
69
71
  composer } = deps;
@@ -73,13 +75,14 @@ export function createComposerCommands(deps) {
73
75
  // worker, owner and history are left alone then.
74
76
  async function send(line) {
75
77
  const id = session();
76
- // The composer is shared: a draft typed in a session opened meanwhile
77
- // stays when the answer comes; only the text sent goes.
78
- const sent = composer.text();
78
+ // The draft it went from: cleared when the answer comes, unless
79
+ // something was typed into it since; a draft of a session opened
80
+ // meanwhile is never touched.
81
+ const sent = composer.text(id);
79
82
  composer.busy();
80
83
  try {
81
84
  await sendCommand(id, line, { clientId });
82
- if (composer.text() === sent) composer.clear();
85
+ if (composer.text(id) === sent) composer.clear(id);
83
86
  refreshHistory();
84
87
  if (session() === id) followWokenWorker();
85
88
  } catch (e) {
@@ -16,8 +16,11 @@ import { COMPOSER_FLOOR, read as readPref } from "./session_prefs.js";
16
16
  // button (Send/Start), chips (the chips' row), attachBtn, attachInput (the
17
17
  // hidden file picker; both null: no image button, viewer.js), grip}.
18
18
  // Hooks: +minPx()+ the empty box's height; +toast(text)+ why images stayed
19
- // out; +onWrite()+ the composer wrote the text itself (a recalled entry);
20
- // +loadHistory()+ a promise of the ↑/↓ entries (oldest first; none: no
19
+ // out; +setText(text)+ writes a recalled entry (the page's drafts, drafts.js:
20
+ // the mount never writes the box itself; none, an older cached app.js: ↑/↓
21
+ // recall nothing and stay the browser's); +onWrite+ is an older cached
22
+ // mount's (it wrote a recalled entry itself, then called it), never called
23
+ // here; +loadHistory()+ a promise of the ↑/↓ entries (oldest first; none: no
21
24
  // history); +send({queue})+ Enter (+queue+: with Alt/Option) or the button;
22
25
  // +keyFirst(e)+ a key the page takes before the history's (true: taken);
23
26
  // +escape()+ Esc, true when it let go of something. +imagesOff+: why this
@@ -25,11 +28,12 @@ import { COMPOSER_FLOOR, read as readPref } from "./session_prefs.js";
25
28
  // paste, drop or pick of one toasts it and adds no chip; null takes them.
26
29
  // +fold+: createComposerGrip's page hooks (session, waiting, allViewOpen,
27
30
  // lightboxOpen, infoBarEl, typeAnywhere).
28
- // @return {el, button, chips(), setChips(list), addImageFiles(files), fit(),
29
- // hasDraft(), refreshHistory(), applyPrefs(), and the grip's isComposerFolded,
30
- // openForVisit, focusPrompt, drawFoldControls, newVisit, decideVisit}
31
+ // @return {el, button, chips(), setChips(list, {revoke}), addImageFiles(files), fit(),
32
+ // hasDraft(), refreshHistory(), resetHistory(), applyPrefs(), and the grip's
33
+ // isComposerFolded, openForVisit, focusPrompt, drawFoldControls, newVisit,
34
+ // decideVisit}
31
35
  export function mountComposer({
32
- els, minPx, toast, onWrite = () => {}, loadHistory = null, send, keyFirst = () => false, escape = () => false,
36
+ els, minPx, toast, setText = null, loadHistory = null, send, keyFirst = () => false, escape = () => false,
33
37
  imagesOff = null, fold, win = globalThis.window, createObjectURL = (f) => URL.createObjectURL(f),
34
38
  revokeObjectURL = (src) => URL.revokeObjectURL(src),
35
39
  }) {
@@ -47,8 +51,10 @@ export function mountComposer({
47
51
  }
48
52
 
49
53
  // A chip that goes frees its preview; one kept in +list+ keeps it.
50
- function setChips(list) {
51
- for (const c of chips) if (c.file && c.src && !list.includes(c)) revokeObjectURL(c.src);
54
+ // +revoke+ false: none is freed (a draft's chips swapped out, drafts.js
55
+ // show: they come back with it).
56
+ function setChips(list, { revoke = true } = {}) {
57
+ if (revoke) for (const c of chips) if (c.file && c.src && !list.includes(c)) revokeObjectURL(c.src);
52
58
  chips = list;
53
59
  renderChips();
54
60
  }
@@ -152,13 +158,12 @@ export function mountComposer({
152
158
  }
153
159
  promptEl.addEventListener("focus", refreshHistory);
154
160
  function historyKey(e) {
155
- if (e.isComposing || e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) return false;
161
+ if (!setText || e.isComposing || e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) return false;
156
162
  const step = e.key === "ArrowUp" ? promptHistory.up : e.key === "ArrowDown" ? promptHistory.down : null;
157
163
  const recalled = step?.({ value: promptEl.value, start: promptEl.selectionStart, end: promptEl.selectionEnd });
158
164
  if (!recalled) return false;
159
165
  e.preventDefault();
160
- promptEl.value = recalled.value;
161
- onWrite();
166
+ setText(recalled.value);
162
167
  promptEl.setSelectionRange(recalled.caret, recalled.caret);
163
168
  fit();
164
169
  return true;
@@ -196,6 +201,8 @@ export function mountComposer({
196
201
  fit,
197
202
  hasDraft,
198
203
  refreshHistory,
204
+ // Browsing ↑/↓ ends (another draft on view: drafts.js show).
205
+ resetHistory: () => promptHistory.reset(),
199
206
  applyPrefs,
200
207
  isComposerFolded: composerGrip.isComposerFolded,
201
208
  openForVisit: composerGrip.openForVisit,
@@ -0,0 +1,10 @@
1
+ // The composer drafts' storage keys (drafts.js): a leaf module, so
2
+ // session_prefs.js can sweep the drafts with the view settings without a new
3
+ // export of its own (a new export on an old module would blank a page holding
4
+ // it cached: docs/internals/web-frontend.md).
5
+ //
6
+ // COMPOSER_DRAFT: a session's draft text, as `<key>:<session>`
7
+ // (session_prefs.js, swept with the session list). START_DRAFT: the start
8
+ // page's, one per browser, outside that sweep.
9
+ export const COMPOSER_DRAFT = "chi_composer_draft";
10
+ export const START_DRAFT = "chi_start_draft";