samagotchi 0.180.0 → 0.182.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 (123) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +71 -1
  3. data/bin/chi +11 -0
  4. data/docs/architecture.md +2 -2
  5. data/docs/bundles.md +7 -2
  6. data/docs/cli.md +46 -13
  7. data/docs/configuration.md +25 -4
  8. data/docs/internals/anthropic.md +4 -3
  9. data/docs/internals/background-tasks.md +2 -0
  10. data/docs/internals/block-renderers.md +123 -6
  11. data/docs/internals/bridge.md +10 -0
  12. data/docs/internals/engine.md +11 -0
  13. data/docs/internals/inline-widgets.md +3 -1
  14. data/docs/internals/objectives.md +9 -4
  15. data/docs/internals/prompt-caching.md +9 -1
  16. data/docs/internals/remote-sessions.md +14 -2
  17. data/docs/internals/web-frontend.md +100 -10
  18. data/docs/internals/working-set.md +24 -5
  19. data/docs/memory.md +3 -0
  20. data/docs/plugins.md +11 -4
  21. data/docs/sessions.md +8 -5
  22. data/docs/testing.md +1 -1
  23. data/lib/samagotchi/answer_display.rb +3 -2
  24. data/lib/samagotchi/block_fix/stamp.rb +49 -0
  25. data/lib/samagotchi/block_fix.rb +220 -0
  26. data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
  27. data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
  28. data/lib/samagotchi/bridge.rb +11 -2
  29. data/lib/samagotchi/bridge_client.rb +9 -0
  30. data/lib/samagotchi/bundle_command.rb +4 -1
  31. data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
  32. data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
  33. data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
  34. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  35. data/lib/samagotchi/client.rb +8 -1
  36. data/lib/samagotchi/config.rb +9 -1
  37. data/lib/samagotchi/continue_intent.rb +8 -0
  38. data/lib/samagotchi/core_notice.rb +44 -0
  39. data/lib/samagotchi/engine/block_fix.rb +332 -0
  40. data/lib/samagotchi/engine/side_requests.rb +7 -5
  41. data/lib/samagotchi/engine.rb +4 -0
  42. data/lib/samagotchi/events.rb +1 -0
  43. data/lib/samagotchi/host_address.rb +7 -0
  44. data/lib/samagotchi/host_config.rb +8 -5
  45. data/lib/samagotchi/host_registry.rb +26 -8
  46. data/lib/samagotchi/idle_client.rb +10 -6
  47. data/lib/samagotchi/inline_widgets.rb +12 -0
  48. data/lib/samagotchi/kernel_loop.rb +10 -7
  49. data/lib/samagotchi/llm/adapter_common.rb +3 -2
  50. data/lib/samagotchi/llm/adapters.rb +2 -1
  51. data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
  52. data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
  53. data/lib/samagotchi/llm/chat_loop.rb +8 -5
  54. data/lib/samagotchi/llm/errors.rb +41 -3
  55. data/lib/samagotchi/llm/http.rb +85 -22
  56. data/lib/samagotchi/llm/openai_chat.rb +20 -3
  57. data/lib/samagotchi/markdown_parser.rb +28 -0
  58. data/lib/samagotchi/memory_bundle/status.rb +2 -1
  59. data/lib/samagotchi/objectives.rb +7 -2
  60. data/lib/samagotchi/owner_lock.rb +2 -0
  61. data/lib/samagotchi/plugin/api.rb +4 -1
  62. data/lib/samagotchi/plugin/context.rb +9 -0
  63. data/lib/samagotchi/plugin/peer.rb +32 -15
  64. data/lib/samagotchi/plugin/tool_spec.rb +13 -2
  65. data/lib/samagotchi/row_refs.rb +14 -3
  66. data/lib/samagotchi/session_access/contract.rb +3 -0
  67. data/lib/samagotchi/session_access/delete_plan.rb +77 -0
  68. data/lib/samagotchi/session_access/local.rb +13 -0
  69. data/lib/samagotchi/session_access/remote.rb +19 -1
  70. data/lib/samagotchi/session_access.rb +1 -0
  71. data/lib/samagotchi/session_chain/delete.rb +45 -87
  72. data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
  73. data/lib/samagotchi/session_delete_command.rb +129 -3
  74. data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
  75. data/lib/samagotchi/session_manager/listing.rb +4 -4
  76. data/lib/samagotchi/session_manager/removal.rb +40 -14
  77. data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
  78. data/lib/samagotchi/session_manager.rb +1 -0
  79. data/lib/samagotchi/tool_ids.rb +19 -0
  80. data/lib/samagotchi/tool_runner.rb +8 -4
  81. data/lib/samagotchi/tools/registry.rb +3 -2
  82. data/lib/samagotchi/tools/task_runtime.rb +34 -0
  83. data/lib/samagotchi/turn_stages/objectives.rb +10 -5
  84. data/lib/samagotchi/version.rb +1 -1
  85. data/lib/samagotchi/web/app.rb +13 -1
  86. data/lib/samagotchi/web/block_fix_routes.rb +39 -0
  87. data/lib/samagotchi/web/markdown_renderer.rb +24 -9
  88. data/lib/samagotchi/web/message_display.rb +6 -1
  89. data/lib/samagotchi/web/participant_view.rb +1 -1
  90. data/lib/samagotchi/web/public/app.js +15 -19
  91. data/lib/samagotchi/web/public/block_fix.js +270 -0
  92. data/lib/samagotchi/web/public/block_fix_note.js +104 -0
  93. data/lib/samagotchi/web/public/block_frame.js +6 -3
  94. data/lib/samagotchi/web/public/block_host.js +21 -21
  95. data/lib/samagotchi/web/public/block_renderers.css +17 -5
  96. data/lib/samagotchi/web/public/block_watch.js +16 -2
  97. data/lib/samagotchi/web/public/context_chips.js +3 -4
  98. data/lib/samagotchi/web/public/images.js +1 -1
  99. data/lib/samagotchi/web/public/index.html +24 -5
  100. data/lib/samagotchi/web/public/inline_widgets.js +1 -1
  101. data/lib/samagotchi/web/public/objectives_strip.js +16 -6
  102. data/lib/samagotchi/web/public/pan_zoom.js +121 -0
  103. data/lib/samagotchi/web/public/peer_chip.js +3 -3
  104. data/lib/samagotchi/web/public/peer_data.js +27 -15
  105. data/lib/samagotchi/web/public/picture_viewer.js +304 -0
  106. data/lib/samagotchi/web/public/popover_modal.js +3 -2
  107. data/lib/samagotchi/web/public/session_view.js +4 -0
  108. data/lib/samagotchi/web/public/stream_handlers.js +5 -1
  109. data/lib/samagotchi/web/public/turn_block.js +5 -2
  110. data/lib/samagotchi/web/public/working_set.js +9 -3
  111. data/lib/samagotchi/web/public/working_set_view.js +28 -11
  112. data/lib/samagotchi/web/public/ws_cards.js +36 -10
  113. data/lib/samagotchi/web/public/ws_markdown.js +129 -0
  114. data/lib/samagotchi/web/public/ws_order.js +48 -0
  115. data/lib/samagotchi/web/public/ws_peek.js +22 -5
  116. data/lib/samagotchi/web/public/ws_preview.css +41 -1
  117. data/lib/samagotchi/web/public/ws_reader.js +35 -6
  118. data/lib/samagotchi/web/public/ws_sections.js +24 -15
  119. data/lib/samagotchi/web/server.rb +6 -4
  120. data/lib/samagotchi/web/session_control.rb +53 -21
  121. data/lib/samagotchi/worker/block_fixes.rb +22 -0
  122. data/lib/samagotchi/worker.rb +10 -3
  123. metadata +17 -1
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../block_fix"
4
+ require_relative "request_body"
5
+
6
+ module Samagotchi
7
+ module Web
8
+ # POST /api/sessions/:id/blocks/fix {turn_id, lang, source, reason},
9
+ # mixed into App: the owner's page asks again, once, for a block it
10
+ # couldn't draw in the newest answer, relayed to the worker's Bridge
11
+ # (Bridge::BlockFixRoute; docs/internals/block-renderers.md, A failed
12
+ # block is asked for again). With web.block_fix off it answers 404, as
13
+ # an unknown route.
14
+ module BlockFixRoutes
15
+ # The worker's answers passed through as they are; any other is 502.
16
+ PASSED = [200, 202].freeze
17
+ REFUSED = [400, 409, 413, 429].freeze
18
+
19
+ private
20
+
21
+ def handle_block_fix(req, id)
22
+ return not_found(path: req.path) unless @block_fix == "auto"
23
+
24
+ body = parse_json(request_body(req, RequestBody::SMALL_BODY_LIMIT))
25
+ return error_response(400, "invalid_json", "invalid JSON body") unless body.is_a?(Hash)
26
+
27
+ fields = body.slice("turn_id", "lang", "source", "reason").transform_keys(&:to_sym)
28
+ request = ->(client) { client.fix_block(turn_id: nil, lang: nil, source: nil, reason: nil, **fields) }
29
+ relay(id, bridge_client(id), request, what: "the fix was not asked for", cant: "fix blocks") do |reply|
30
+ if PASSED.include?(reply.status)
31
+ json_response(reply.status, reply.json || {})
32
+ elsif REFUSED.include?(reply.status)
33
+ error_response(reply.status, reply.json&.dig("error") || "refused", reply_detail(reply, "the fix was refused"))
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
@@ -2,8 +2,10 @@
2
2
 
3
3
  require "nokogiri"
4
4
  require "uri"
5
+ require_relative "../block_fix"
5
6
  require_relative "../block_renderers"
6
7
  require_relative "../inline_widgets"
8
+ require_relative "../markdown_parser"
7
9
 
8
10
  module Samagotchi
9
11
  module Web
@@ -57,7 +59,11 @@ module Samagotchi
57
59
  commonmarker_installed? ? TIP : TIP_GEM
58
60
  end
59
61
 
60
- def render(markdown)
62
+ # @param block_fixes [Array<Hash>, nil] the answer's block fix stamp
63
+ # (BlockFix.stamps): a block that is a fix gets data-block-fixed, one
64
+ # whose fix failed data-block-fix-failed. Only an answer's own render
65
+ # (MessageDisplay) passes it.
66
+ def render(markdown, block_fixes: nil)
61
67
  return nil unless available?
62
68
 
63
69
  html = Commonmarker.to_html(markdown.to_s, options: OPTIONS, plugins: {
@@ -68,7 +74,7 @@ module Samagotchi
68
74
  })
69
75
  return nil unless html
70
76
 
71
- sanitize(html, fences(markdown.to_s))
77
+ sanitize(html, fences(markdown.to_s), Array(block_fixes))
72
78
  end
73
79
 
74
80
  private
@@ -76,10 +82,7 @@ module Samagotchi
76
82
  def load_bundled_commonmarker!
77
83
  return @commonmarker_available unless @commonmarker_available.nil?
78
84
 
79
- require "commonmarker"
80
- @commonmarker_available = true
81
- rescue LoadError
82
- @commonmarker_available = false
85
+ @commonmarker_available = MarkdownParser.available?
83
86
  end
84
87
 
85
88
  def commonmarker_installed?
@@ -109,7 +112,7 @@ module Samagotchi
109
112
  # After the walk, which drops every attribute it doesn't know. Blocks and
110
113
  # fences pair by position; a count that differs says the two parses
111
114
  # disagree, and then no block gets one (it shows as source).
112
- def mark_languages(fragment, fences)
115
+ def mark_languages(fragment, fences, block_fixes = [])
113
116
  blocks = fragment.css("pre")
114
117
  return unless blocks.size == fences.size
115
118
 
@@ -118,6 +121,18 @@ module Samagotchi
118
121
 
119
122
  pre["data-lang"] = fence.language
120
123
  mark_widget(pre, fence.literal) if fence.language == InlineWidgets::LANG
124
+ mark_fix(pre, fence, block_fixes) unless block_fixes.empty?
125
+ end
126
+ end
127
+
128
+ # The stamp's word on this block: the fix of a failed one, or one
129
+ # whose fix didn't help. One SHA-256 per fenced block of a stamped answer.
130
+ def mark_fix(pre, fence, block_fixes)
131
+ key = BlockFix.key(fence.language, fence.literal)
132
+ if block_fixes.any? { |entry| entry[:fixed_key] == key }
133
+ pre["data-block-fixed"] = ""
134
+ elsif block_fixes.any? { |entry| entry[:key] == key && entry[:state] == "failed" }
135
+ pre["data-block-fix-failed"] = ""
121
136
  end
122
137
  end
123
138
 
@@ -134,7 +149,7 @@ module Samagotchi
134
149
  pre["data-widget-lenient"] = "" if widget.lenient?
135
150
  end
136
151
 
137
- def sanitize(html, fences)
152
+ def sanitize(html, fences, block_fixes = [])
138
153
  fragment = Nokogiri::HTML5.fragment(html)
139
154
  fragment.traverse do |node|
140
155
  next unless node.element?
@@ -147,7 +162,7 @@ module Samagotchi
147
162
  sanitize_attributes(node)
148
163
  end
149
164
  end
150
- mark_languages(fragment, fences)
165
+ mark_languages(fragment, fences, block_fixes)
151
166
  fragment.to_html
152
167
  end
153
168
 
@@ -3,6 +3,7 @@
3
3
  require_relative "../session"
4
4
  require_relative "../answer_refs"
5
5
  require_relative "../answer_tail"
6
+ require_relative "../block_fix/stamp"
6
7
  require_relative "../context_note"
7
8
  require_relative "../image_store"
8
9
  require_relative "../message_parts"
@@ -223,7 +224,11 @@ module Samagotchi
223
224
  shown = display.is_a?(String) ? Samagotchi::OutputFormatter.strip_markup(display) : ""
224
225
  message[:display] = shown unless shown.strip.empty?
225
226
  rendered = message[:display] || stripped
226
- message[:html] = @markdown_renderer.render(rendered) if markdown && !rendered.empty? && @markdown_renderer.available?
227
+ fixes = Samagotchi::BlockFix.stamps(m)
228
+ message[:html] = @markdown_renderer.render(rendered, block_fixes: fixes) if markdown && !rendered.empty? && @markdown_renderer.available?
229
+ # A block was fixed in it: a reload's drawn turn takes this answer
230
+ # even though what streamed differs (turn_block.js savedAnswer).
231
+ message[:block_fixed] = true if fixes.any? { |entry| entry[:state] == "fixed" }
227
232
  # The refs after_turn hooks attached (AnswerRefs), checked again:
228
233
  # a stored file is never trusted. Never raises.
229
234
  refs = Samagotchi::AnswerRefs.for_display(m[:display_refs] || m["display_refs"], cwd: cwd)
@@ -83,7 +83,7 @@ module Samagotchi
83
83
  # fails for a new one until it is decided here or in EVENTS. Not
84
84
  # named is dropped all the same.
85
85
  DROPPED = %w[
86
- after_generation after_tool_call after_turn answer_display before_generation before_tool_call before_turn
86
+ after_generation after_tool_call after_turn answer_display before_generation before_tool_call before_turn block_fix
87
87
  card command_output command_queued command_ran context_added empty_answer_retry
88
88
  generation_cancelled generation_progress generation_started guardrail_warning hook_notice
89
89
  llm_context_edited merged_input objectives_updated part_settled participants_changed pending_input_merged plugin_init_finished
@@ -2,14 +2,11 @@ import {
2
2
  listSessions,
3
3
  getSession,
4
4
  sendTurn,
5
- stopTurn,
6
- stopSession,
5
+ stopTurn, stopSession,
7
6
  sessionHolds,
8
7
  stopSessionHolds,
9
8
  restartSession,
10
- deleteSession,
11
- deleteChain,
12
- deletePlan,
9
+ deleteSession, deleteChain, deletePlan,
13
10
  archiveSession,
14
11
  unarchiveSession,
15
12
  sendCommand,
@@ -72,6 +69,7 @@ import { createAnnotateBar } from "./annotate_bar.js";
72
69
  import { VERIFY_PRESET, VERIFY_UNAVAILABLE, verifyWorkerUnavailable, withVerify } from "./verify_preset.js";
73
70
  import { actionLine, annotationActions, composerWithAction } from "./annotate_actions.js";
74
71
  import { createBlockHost } from "./block_host.js";
72
+ import { wireBlockFix } from "./block_fix.js";
75
73
  import { createWidgetDrawer } from "./inline_widgets.js";
76
74
  import { copyText, installCopy } from "./copy.js";
77
75
  import { installAnswerFold, sweepAnswerFolds } from "./answer_fold.js";
@@ -131,6 +129,7 @@ import { createMarkdownTip } from "./markdown_tip.js";
131
129
  import { IMAGES_NOT_HERE } from "./images.js";
132
130
  import { withoutStaleParams } from "./stale_params.js";
133
131
  import { createViewer } from "./viewer.js";
132
+ import { createPictureViewer, thumbPicture } from "./picture_viewer.js";
134
133
  import { createParticipantMain } from "./participant_main.js";
135
134
  import { createPeers } from "./peer_data.js";
136
135
  import { peerStatusCommand } from "./peer_chip.js";
@@ -154,6 +153,7 @@ onAuthLost(authLost);
154
153
  const $ = (s) => document.querySelector(s);
155
154
  // Who looks and what they may do (viewer.js): every owner-only control and call asks it.
156
155
  const viewer = createViewer(document.body);
156
+ const pictures = createPictureViewer({ el: $("#lightbox") }); // a picture over the page (picture_viewer.js)
157
157
  const topStripEl = $("#topStrip");
158
158
  const allListEl = $("#allList");
159
159
  const historyEl = $("#history");
@@ -358,7 +358,7 @@ const { renderMarkdown, pairRefsIn, linkRefsIn, applyFinalMarkdown } = markdownP
358
358
  const wsLine = viewer.can("session_controls") ? (line) => (store.selected ? sendCommand(store.selected, line, { clientId }) : null) : null;
359
359
  // What chi has of an item (the owner's): the rows' peek and the reader over the stage (ws_reader.js).
360
360
  const wsPreview = document.body.dataset.workingSet === "1" && viewer.can("working_set_items")
361
- ? createWorkingSetPreview({ centerEl: $("#center"), session: () => store.selected, state: () => store.current, sendLine: wsLine }) : null;
361
+ ? createWorkingSetPreview({ centerEl: $("#center"), session: () => store.selected, state: () => store.current, sendLine: wsLine, renderMarkdown }) : null;
362
362
  const workingSet = document.body.dataset.workingSet === "1" && viewer.can("working_set")
363
363
  ? createWorkingSet({
364
364
  historyEl, stageRoot: () => turnDom.root, state: () => store.current, session: () => store.selected, infoEl: infoTextEl,
@@ -547,7 +547,7 @@ turnRoots().forEach((root) => root.addEventListener("click", cards.onCardAction)
547
547
  const sessionView = createSessionView({
548
548
  store, historyEl, getSession,
549
549
  liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet, wsPreview, gapClock,
550
- bubbles, cards, markdown: markdownPlace, cardRegistry, peerLinks,
550
+ bubbles, cards, markdown: markdownPlace, cardRegistry, peerLinks, pictures,
551
551
  capabilities: () => pageCapabilities,
552
552
  page: {
553
553
  setReviseAnchor, renderInitRow, setMarkdownWarning, setCapabilities, findInTurnRoots, appendToHistory,
@@ -847,7 +847,7 @@ function applyView() {
847
847
  // Its chip was in the list just hidden (the strip, or all sessions).
848
848
  lists.chainPop.close();
849
849
  if (open) {
850
- lists.familyPop.close(); // the strip is hidden in the all view
850
+ lists.familyPop.close(); pictures.close(); // the strip and #center (the picture viewer's parent) are hidden there
851
851
  // The list is live; only its order can lag (upserts keep cards in
852
852
  // place), so the all view opens in the server's order.
853
853
  // A new list: the lists' redraw draws the all view (lists.render).
@@ -1222,6 +1222,7 @@ const streamHandlers = observeCards(cardRegistry, (participant ? participant.wra
1222
1222
  syncModelPick: startPage.commandRan,
1223
1223
  objectivesUpdated: (data) => objectives.update(data),
1224
1224
  cardActionFailed: cards.actionFailed,
1225
+ blockFix: (data) => blockFix?.onEvent(data),
1225
1226
  })));
1226
1227
 
1227
1228
  async function refreshTimingFromSession() {
@@ -1358,7 +1359,6 @@ viewer.control($("#newBtn"), "sessions")?.addEventListener("click", () => {
1358
1359
  startPage.loadModels({ asked: true });
1359
1360
  });
1360
1361
 
1361
- const lightboxEl = $("#lightbox");
1362
1362
 
1363
1363
  // The empty box: one line in a session, three on the start page.
1364
1364
  function promptMinPx() {
@@ -1394,7 +1394,7 @@ const composer = mountComposer({
1394
1394
  session: () => store.selected,
1395
1395
  waiting: sessionWaits,
1396
1396
  allViewOpen,
1397
- lightboxOpen: () => !lightboxEl.hidden,
1397
+ lightboxOpen: () => pictures.isOpen(),
1398
1398
  },
1399
1399
  });
1400
1400
  // Bound here, not hoisted: no top-level code above this line may call them.
@@ -1427,17 +1427,11 @@ const unqueue = createUnqueue({
1427
1427
  return true;
1428
1428
  },
1429
1429
  });
1430
- turnRoots().forEach((root) => root.addEventListener("click", (e) => { unqueue.onClick(e); }));
1431
1430
  turnRoots().forEach((root) => root.addEventListener("click", (e) => {
1431
+ unqueue.onClick(e);
1432
1432
  const img = e.target.closest("img.thumb");
1433
- if (!img) return;
1434
- lightboxEl.querySelector("img").src = img.src;
1435
- lightboxEl.hidden = false;
1433
+ if (img) pictures.open(thumbPicture(img));
1436
1434
  }));
1437
- lightboxEl.addEventListener("click", () => { lightboxEl.hidden = true; });
1438
- document.addEventListener("keydown", (e) => {
1439
- if (e.key === "Escape" && !lightboxEl.hidden) lightboxEl.hidden = true;
1440
- });
1441
1435
 
1442
1436
  // The / autocomplete (command_list.js): the session's commands while the
1443
1437
  // composer holds one "/word".
@@ -1548,7 +1542,9 @@ turnRoots().forEach((root) => installCopy(root));
1548
1542
  // chi-ui blocks (inline_widgets.js) are a core drawer, ahead of the bundles'
1549
1543
  // renderers; a picks' Fill reply only fills the composer.
1550
1544
  const widgets = createWidgetDrawer({ roots: turnRoots(), composerText: () => promptEl.value, fillComposer });
1551
- createBlockHost({ roots: turnRoots(), sessionId: () => store.selected, drawers: [widgets], renderers: viewer.can("block_renderers") });
1545
+ createBlockHost({ roots: turnRoots(), sessionId: () => store.selected, drawers: [widgets], renderers: viewer.can("block_renderers"), openPicture: (p, o) => pictures.open(p, o) });
1546
+ const blockFix = wireBlockFix({ viewer, roots: turnRoots(), store, getSession, composerText: () => promptEl.value, fillComposer, linkTextRefs: markdownPlace.linkTextRefs });
1547
+ window.matchMedia?.("(prefers-color-scheme: dark)").addEventListener?.("change", () => pictures.close()); // a redrawn diagram's old picture
1552
1548
  // A steps block, a thinking block and the recap open and close by hand
1553
1549
  // with their height animated (details_motion.js), in the history and on
1554
1550
  // the stage.
@@ -0,0 +1,270 @@
1
+ // A block the owner's page couldn't draw in the newest answer, asked for again
2
+ // once (docs/internals/block-renderers.md, A failed block is asked for again):
3
+ // POST /api/sessions/:id/blocks/fix, then the worker's :block_fix says how it
4
+ // went, and a fixed answer is read again and drawn as any answer.
5
+ //
6
+ // Only the owner's page asks (a viewer with the bundles' renderers), and only
7
+ // with <body data-block-fix="auto"> (web.block_fix; a page served by an older
8
+ // chi web has none: off). What a block gets, from the DOM alone:
9
+ // - not marked fixable by its drawer (block_watch.js failBlock), or over
10
+ // 16 KB: today's line;
11
+ // - data-block-fixed (it is a fix, failing again): "also after a fix" and Ask in chat;
12
+ // - data-block-fix-failed (asked before, no help): "a fix didn't help" and Ask in chat;
13
+ // - not in the newest answer, or past the answer's 2 blocks: today's line and Ask in chat;
14
+ // - a live worker without the block_fix feature (worker_features.js
15
+ // workerPredates): "restart this session to fix"; a worker not up, or not
16
+ // reported yet, is asked (chi web answers 503 not_live: today's line);
17
+ // - else "asking for a fix…" and the POST.
18
+ // A Revise clone has no data-answer-turn, so it never asks. Nothing is kept
19
+ // across a re-render: a block that fails again is posted again and the worker
20
+ // says it is running (or how it went). Only the redraw is counted: an answer
21
+ // is read again at most once per block for the page's life, so no answer of
22
+ // the worker's (a "fixed" for a copy still failing) can make a loop.
23
+ //
24
+ // A module of its own: static JS is cached at unversioned URLs, and a new
25
+ // export on an old module would blank the page.
26
+
27
+ import { api } from "./data.js";
28
+ import { codeText, copySource } from "./copy.js";
29
+ import { setAnswerRefs } from "./answer_refs.js";
30
+ import { askText, markFixed, noteOf, setFixNote } from "./block_fix_note.js";
31
+ import { stillOn } from "./latest.js";
32
+ import { TEXTS } from "./text_roots.js";
33
+ import { withDraft } from "./widget_picks.js";
34
+ import { OWNER_FINAL } from "./verify_target.js";
35
+ import { workerPredates } from "./worker_features.js";
36
+
37
+ export const FEATURE = "block_fix";
38
+ // BlockFix::MAX_SOURCE_BYTES and its per-answer count (BlockFix::PER_ANSWER).
39
+ export const MAX_SOURCE_BYTES = 16 * 1024;
40
+ export const PER_ANSWER = 2;
41
+ // No :block_fix this long after a 202 (the worker died, a reset lost it): give up.
42
+ export const GIVE_UP_MS = 60_000;
43
+
44
+ const FAILED = "pre[data-block-failed]";
45
+ const ANSWER = `${OWNER_FINAL.answers}[data-answer-turn]`;
46
+
47
+ // @param roots the turn roots (app.js turnRoots())
48
+ // @param sessionId () => the open session's id
49
+ // @param features () => the open session's worker features
50
+ // @param bridgeUp () => whether the open session's worker is up (store.current.bridgeUp)
51
+ // @param post (id, body) => a Promise of {status, body} (the route's answer)
52
+ // @param getSession data.js getSession (the answer's tail read)
53
+ // @param composerText () => the composer's text; fillComposer(text) sets it
54
+ // @param linkTextRefs () => the answers' refs again (markdown_place.js)
55
+ // @param timers {setTimeout, clearTimeout}: a seam for the specs
56
+ export function createBlockFix({ roots, sessionId, features, bridgeUp = () => true, post, getSession, composerText,
57
+ fillComposer, linkTextRefs = () => {}, timers = globalThis, win = window }) {
58
+ // Per answer bubble: the sources it asked for (at most PER_ANSWER).
59
+ const asked = new WeakMap();
60
+ // Give-up timers of the open session, by its id.
61
+ let pending = new Map();
62
+ // The open session's "turn\0source" whose answer was read again for it.
63
+ let redrawn = new Set();
64
+ let session = sessionId();
65
+
66
+ function noticeSession() {
67
+ const now = sessionId();
68
+ if (now === session) return;
69
+ session = now;
70
+ for (const timer of pending.values()) timers.clearTimeout(timer);
71
+ pending = new Map();
72
+ redrawn = new Set();
73
+ }
74
+
75
+ // Whether the answer may be read again for +source+ (once), noting it.
76
+ function redrawOnce(turnId, source) {
77
+ const key = `${turnId}\0${source}`;
78
+ if (redrawn.has(key)) return false;
79
+ redrawn.add(key);
80
+ return true;
81
+ }
82
+
83
+ function newestAnswer() {
84
+ let newest = null;
85
+ for (const root of roots) {
86
+ const all = root.querySelectorAll(OWNER_FINAL.answers);
87
+ if (all.length) newest = all[all.length - 1];
88
+ }
89
+ return newest;
90
+ }
91
+
92
+ const tooLarge = (source) => new TextEncoder().encode(source).length > MAX_SOURCE_BYTES;
93
+
94
+ function decide(pre) {
95
+ if (!pre.isConnected || !pre.closest(TEXTS) || pre.dataset.blockFixSeen === "1") return;
96
+ pre.dataset.blockFixSeen = "1";
97
+ noticeSession();
98
+ const source = codeText(pre);
99
+ if (pre.dataset.blockFixable !== "1" || tooLarge(source)) return;
100
+ if (pre.hasAttribute("data-block-fixed")) { setFixNote(pre, "again"); return; }
101
+ if (pre.hasAttribute("data-block-fix-failed")) { setFixNote(pre, "nohelp"); return; }
102
+ const bubble = pre.closest(ANSWER);
103
+ const sources = bubble && (asked.get(bubble) || new Set());
104
+ if (!bubble || bubble !== newestAnswer() || (sources.size >= PER_ANSWER && !sources.has(source))) {
105
+ setFixNote(pre, "older");
106
+ return;
107
+ }
108
+ if (workerPredates(features(), bridgeUp(), FEATURE)) { setFixNote(pre, "restart"); return; }
109
+ sources.add(source);
110
+ asked.set(bubble, sources);
111
+ setFixNote(pre, "asking");
112
+ ask(pre, bubble.getAttribute("data-answer-turn"), source);
113
+ }
114
+
115
+ async function ask(pre, turnId, source) {
116
+ const id = sessionId();
117
+ const still = stillOn(sessionId, id);
118
+ const lang = pre.getAttribute("data-lang");
119
+ // Marked before the POST: the worker's word can come before its 202 (a
120
+ // quick side answer), and the event settles the blocks marked so.
121
+ pre.dataset.blockFixAsked = "1";
122
+ let answer;
123
+ try {
124
+ answer = await post(id, { turn_id: turnId, lang, source, reason: pre.dataset.blockReason || "" });
125
+ } catch (_) {
126
+ answer = { status: 0, body: {} };
127
+ }
128
+ if (!still() || !pre.isConnected) return;
129
+ const { status, body = {} } = answer;
130
+ if (status !== 202) delete pre.dataset.blockFixAsked;
131
+ if (status === 200 && body.state === "fixed") {
132
+ // Drawn again and failed again after a redraw: no second one.
133
+ if (redrawOnce(turnId, source)) refresh(id, turnId);
134
+ else setFixNote(pre, "nohelp");
135
+ return;
136
+ }
137
+ if (status === 200) { setFixNote(pre, "nohelp"); return; }
138
+ if (status === 202) {
139
+ // Running, unless the worker's word already came.
140
+ if (asking(pre)) giveUpLater(turnId);
141
+ return;
142
+ }
143
+ setFixNote(pre, status === 501 ? "restart" : "older");
144
+ }
145
+
146
+ function giveUpLater(turnId) {
147
+ if (pending.has(turnId)) timers.clearTimeout(pending.get(turnId));
148
+ pending.set(turnId, timers.setTimeout(() => {
149
+ pending.delete(turnId);
150
+ for (const pre of askedIn(turnId)) if (asking(pre)) setFixNote(pre, "older");
151
+ }, GIVE_UP_MS));
152
+ }
153
+
154
+ const asking = (pre) => noteOf(pre)?.dataset.fix === "asking";
155
+
156
+ function bubbleOf(turnId) {
157
+ for (const root of roots) {
158
+ for (const found of root.querySelectorAll(ANSWER)) if (found.getAttribute("data-answer-turn") === turnId) return found;
159
+ }
160
+ return null;
161
+ }
162
+
163
+ function askedIn(turnId) {
164
+ const bubble = bubbleOf(turnId);
165
+ return bubble ? [...bubble.querySelectorAll(`${FAILED}[data-block-fix-asked]`)] : [];
166
+ }
167
+
168
+ // The fixed answer, read again and written as applyFinalAnswer writes it
169
+ // (answer_refs.js), which can't find the bubble by its old text.
170
+ async function refresh(id, turnId) {
171
+ const still = stillOn(sessionId, id);
172
+ let data;
173
+ try {
174
+ data = await getSession(id, { tail: true, turnId });
175
+ } catch (_) {
176
+ return;
177
+ }
178
+ if (!still()) return;
179
+ const message = [...(data?.messages || [])].reverse().find((m) => m?.role === "assistant" && typeof m.html === "string");
180
+ const bubble = bubbleOf(turnId);
181
+ if (!message || !bubble) return;
182
+ // A turn no prompt names (a reminder's) is read as the newest answer: only
183
+ // that bubble may take it; another waits for the next full read.
184
+ if (bubble !== newestAnswer() && bubble.getAttribute("data-copy-source") !== message.content) return;
185
+ bubble.classList.add("markdown");
186
+ bubble.setAttribute("data-copy-source", copySource(message));
187
+ bubble.toggleAttribute("data-answer-display", typeof message.display === "string");
188
+ bubble.innerHTML = message.html;
189
+ setAnswerRefs(bubble, message.display_refs);
190
+ linkTextRefs();
191
+ }
192
+
193
+ // The worker's word on a fix it was asked for (stream_handlers.js).
194
+ function onEvent(data) {
195
+ noticeSession();
196
+ const turnId = data?.turn_id;
197
+ if (!turnId) return;
198
+ if (pending.has(turnId)) { timers.clearTimeout(pending.get(turnId)); pending.delete(turnId); }
199
+ if (data.state === "fixed") {
200
+ for (const pre of askedIn(turnId)) redrawOnce(turnId, codeText(pre));
201
+ refresh(sessionId(), turnId);
202
+ return;
203
+ }
204
+ for (const pre of askedIn(turnId)) setFixNote(pre, "nohelp");
205
+ }
206
+
207
+ function scan(el) {
208
+ if (el.matches?.(FAILED)) decide(el);
209
+ for (const pre of el.querySelectorAll?.(FAILED) || []) decide(pre);
210
+ if (el.matches?.("pre[data-block-fixed]")) markFixed(el);
211
+ for (const pre of el.querySelectorAll?.("pre[data-block-fixed]") || []) markFixed(pre);
212
+ }
213
+
214
+ for (const root of roots) {
215
+ root.addEventListener("block-failed", (e) => {
216
+ const pre = e.target;
217
+ if (pre?.matches?.("pre[data-block-fixed]")) markFixed(pre);
218
+ decide(pre);
219
+ });
220
+ // A Revise clone arrives failed; a figure placed is a drawn block (its
221
+ // "Drawn after a fix" line).
222
+ new win.MutationObserver((records) => {
223
+ for (const record of records) {
224
+ for (const node of record.addedNodes) {
225
+ if (node.nodeType !== 1) continue;
226
+ if (node.classList?.contains("block-drawn") && node.nextElementSibling?.matches?.("pre[data-block-fixed]")) {
227
+ markFixed(node.nextElementSibling);
228
+ } else scan(node);
229
+ }
230
+ }
231
+ }).observe(root, { childList: true, subtree: true });
232
+ // One delegated listener per root: a clone loses element listeners.
233
+ root.addEventListener("click", (e) => {
234
+ const button = e.target.closest?.(".block-note > .block-fix-ask");
235
+ if (!button) return;
236
+ e.preventDefault();
237
+ e.stopPropagation();
238
+ const pre = button.parentElement.previousElementSibling;
239
+ if (!pre?.matches?.("pre")) return;
240
+ fillComposer(withDraft(composerText(), askText(pre.getAttribute("data-lang"), pre.dataset.blockReason)));
241
+ });
242
+ scan(root);
243
+ }
244
+
245
+ return { onEvent, scan };
246
+ }
247
+
248
+ // The route's POST as {status, body}: 202 is the one answer that says
249
+ // "running"; a refusal's status is data.js api's error.status (0: no answer).
250
+ export async function postFix(id, body, { fetchImpl } = {}) {
251
+ try {
252
+ const answer = await api(`/api/sessions/${encodeURIComponent(id)}/blocks/fix`, {
253
+ method: "POST", body: JSON.stringify(body), ...(fetchImpl ? { fetchImpl } : {}),
254
+ });
255
+ return { status: answer?.state === "running" ? 202 : 200, body: answer || {} };
256
+ } catch (e) {
257
+ return { status: e?.status || 0, body: {} };
258
+ }
259
+ }
260
+
261
+ // app.js's wiring: the owner's page with web.block_fix auto, else null (the
262
+ // stream handler's dep stays null too).
263
+ export function wireBlockFix({ viewer, roots, store, getSession, composerText, fillComposer, linkTextRefs, doc = document }) {
264
+ if (!viewer.can("block_renderers") || doc.body?.dataset?.blockFix !== "auto") return null;
265
+ return createBlockFix({
266
+ roots, sessionId: () => store.selected, features: () => store.current.workerFeatures,
267
+ bridgeUp: () => store.current.bridgeUp, post: (id, body) => postFix(id, body),
268
+ getSession, composerText, fillComposer, linkTextRefs,
269
+ });
270
+ }
@@ -0,0 +1,104 @@
1
+ // The line under a block that failed to draw, as a fix is asked for or not
2
+ // (block_fix.js; docs/internals/block-renderers.md, A failed block is asked for
3
+ // again). DOM only. It is failBlock's own .block-note (block_watch.js): its words
4
+ // stay an attribute CSS shows, and a button in it has its label drawn by CSS from
5
+ // data-label with an aria-label, no text node, so nothing of the page's own gets
6
+ // into a bubble's textContent (copy.js's rule). A click on the words still copies
7
+ // them (the watcher's listener); a click on a button is the button's.
8
+ //
9
+ // The states (data-fix on the line):
10
+ // asking "… · asking for a fix…" and a pulsing dot
11
+ // nohelp "… · a fix didn't help", Ask in chat
12
+ // again "…, also after a fix: reason", Ask in chat (a fixed block failing again)
13
+ // older today's words, Ask in chat (an older answer, or past its 2 blocks)
14
+ // restart "… · restart this session to fix" (a worker without the feature)
15
+ // today today's words, no button (a failure that isn't the model's)
16
+ // A fixed block that draws gets its own line after it: "Drawn after a fix".
17
+ //
18
+ // A module of its own: static JS is cached at unversioned URLs, and a new
19
+ // export on an old module would blank the page.
20
+
21
+ import { figureOf } from "./block_source.js";
22
+
23
+ export const ASK_LABEL = "Ask in chat";
24
+ export const FIXED_TEXT = "Drawn after a fix";
25
+ const ASK = "block-fix-ask";
26
+ const FIXED = "fixed";
27
+
28
+ // The failed block's line (failBlock puts it right after the <pre>), or null.
29
+ export function noteOf(pre) {
30
+ const next = pre?.nextElementSibling;
31
+ return next?.classList?.contains("block-note") && !next.classList.contains(FIXED) ? next : null;
32
+ }
33
+
34
+ // What failBlock said: "Couldn't draw this <lang> block: <first line>".
35
+ function baseWords(lang, reason) {
36
+ const first = String(reason ?? "").split("\n")[0].trim();
37
+ return `Couldn't draw this ${lang} block${first ? `: ${first}` : ""}`;
38
+ }
39
+
40
+ function words(state, lang, reason) {
41
+ const base = baseWords(lang, reason);
42
+ switch (state) {
43
+ case "asking": return `${base} · asking for a fix…`;
44
+ case "nohelp": return `${base} · a fix didn't help`;
45
+ case "again": {
46
+ const first = String(reason ?? "").split("\n")[0].trim();
47
+ return `Couldn't draw this ${lang} block, also after a fix${first ? `: ${first}` : ""}`;
48
+ }
49
+ case "restart": return `${base} · restart this session to fix`;
50
+ default: return base;
51
+ }
52
+ }
53
+
54
+ const WITH_ASK = new Set(["nohelp", "again", "older"]);
55
+
56
+ // Sets the failed block's line to +state+. Returns the line, or null when the
57
+ // block has none (it drew, or left the page).
58
+ export function setFixNote(pre, state, { lang = pre?.getAttribute?.("data-lang") || "", reason = pre?.dataset?.blockReason } = {}) {
59
+ const note = noteOf(pre);
60
+ if (!note) return null;
61
+ const text = words(state, lang, reason);
62
+ note.dataset.text = text;
63
+ note.setAttribute("aria-label", text);
64
+ if (state === "today") delete note.dataset.fix;
65
+ else note.dataset.fix = state;
66
+ let button = note.querySelector(`:scope > .${ASK}`);
67
+ if (WITH_ASK.has(state) && !button) {
68
+ button = note.ownerDocument.createElement("button");
69
+ button.type = "button";
70
+ button.className = ASK;
71
+ button.dataset.label = ASK_LABEL;
72
+ button.setAttribute("aria-label", ASK_LABEL);
73
+ note.append(button);
74
+ } else if (!WITH_ASK.has(state) && button) {
75
+ button.remove();
76
+ }
77
+ return note;
78
+ }
79
+
80
+ // The sentence Ask in chat puts in the composer (never sent).
81
+ export function askText(lang, reason) {
82
+ const first = String(reason ?? "").split("\n")[0].trim().replace(/[.\s]+$/, "");
83
+ return `The ${lang} block in your answer didn't draw${first ? `: ${first}` : ""}. Please send it again, corrected.`;
84
+ }
85
+
86
+ // "Drawn after a fix" under a fixed block that drew (data-block-fixed and a
87
+ // figure), gone when it failed after all. Idempotent.
88
+ export function markFixed(pre) {
89
+ let mark = null;
90
+ for (let at = pre.nextElementSibling; at?.classList?.contains("block-note"); at = at.nextElementSibling) {
91
+ if (at.classList.contains(FIXED)) { mark = at; break; }
92
+ }
93
+ const wanted = pre.hasAttribute("data-block-fixed") && !!figureOf(pre) && !pre.dataset.blockFailed;
94
+ if (wanted && !mark) {
95
+ const line = pre.ownerDocument.createElement("div");
96
+ line.className = `block-note ${FIXED}`;
97
+ line.dataset.text = FIXED_TEXT;
98
+ line.setAttribute("role", "note");
99
+ line.setAttribute("aria-label", FIXED_TEXT);
100
+ pre.after(line);
101
+ } else if (!wanted && mark) {
102
+ mark.remove();
103
+ }
104
+ }