samagotchi 0.181.0 → 0.183.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +93 -1
- data/bin/chi +4 -1
- data/docs/architecture.md +17 -7
- data/docs/bundle-authoring.md +1 -1
- data/docs/bundles.md +103 -4
- data/docs/cli.md +58 -10
- data/docs/configuration.md +3 -1
- data/docs/guardrails.md +16 -1
- data/docs/internals/block-renderers.md +172 -3
- data/docs/internals/bridge.md +23 -5
- data/docs/internals/bundles.md +21 -4
- data/docs/internals/engine.md +29 -8
- data/docs/internals/inline-widgets.md +3 -1
- data/docs/internals/prompt-caching.md +9 -1
- data/docs/internals/remote-sessions.md +38 -7
- data/docs/internals/web-frontend.md +116 -26
- data/docs/internals/working-set.md +1 -1
- data/docs/mcp-server.md +80 -0
- data/docs/plugins.md +308 -21
- data/docs/sessions.md +7 -4
- data/docs/sub-agent.md +9 -0
- data/docs/testing.md +3 -1
- data/docs/thin-clients.md +146 -0
- data/lib/samagotchi/answer_display.rb +3 -2
- data/lib/samagotchi/block_fix/stamp.rb +49 -0
- data/lib/samagotchi/block_fix.rb +220 -0
- data/lib/samagotchi/bridge/block_fix_route.rb +30 -0
- data/lib/samagotchi/bridge/pending_card.rb +4 -3
- data/lib/samagotchi/bridge/sse_writer.rb +16 -15
- data/lib/samagotchi/bridge/turn_drawings.rb +19 -0
- data/lib/samagotchi/bridge.rb +69 -69
- data/lib/samagotchi/bridge_client.rb +9 -0
- data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
- data/lib/samagotchi/bundle_command/check.rb +36 -19
- data/lib/samagotchi/bundle_command.rb +50 -21
- data/lib/samagotchi/bundle_manifest.rb +101 -4
- data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
- data/lib/samagotchi/bundles/mcp/client.rb +260 -0
- data/lib/samagotchi/bundles/mcp/content.rb +107 -0
- data/lib/samagotchi/bundles/mcp/http_client.rb +407 -0
- data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
- data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
- data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
- data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
- data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
- data/lib/samagotchi/bundles/system/manifest.yml +2 -2
- data/lib/samagotchi/cli/parent_wait.rb +5 -3
- data/lib/samagotchi/command_intake.rb +7 -0
- data/lib/samagotchi/commands/registry.rb +8 -3
- data/lib/samagotchi/config.rb +3 -0
- data/lib/samagotchi/continue_intent.rb +8 -0
- data/lib/samagotchi/continue_offer.rb +24 -15
- data/lib/samagotchi/engine/block_fix.rb +332 -0
- data/lib/samagotchi/engine/cards.rb +14 -5
- data/lib/samagotchi/engine/events.rb +10 -15
- data/lib/samagotchi/engine/models.rb +1 -1
- data/lib/samagotchi/engine/plugins.rb +3 -0
- data/lib/samagotchi/engine/recap.rb +1 -1
- data/lib/samagotchi/engine/side_requests.rb +8 -6
- data/lib/samagotchi/engine/sign_in.rb +142 -0
- data/lib/samagotchi/engine/turn_end.rb +3 -3
- data/lib/samagotchi/engine.rb +47 -27
- data/lib/samagotchi/engine_snapshots.rb +1 -1
- data/lib/samagotchi/events.rb +1 -0
- data/lib/samagotchi/guardrail_wiring.rb +3 -1
- data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
- data/lib/samagotchi/guardrails/verdict.rb +3 -2
- data/lib/samagotchi/hold_stop.rb +4 -4
- data/lib/samagotchi/idle_client.rb +10 -6
- data/lib/samagotchi/idle_recap.rb +19 -11
- data/lib/samagotchi/idle_reminders.rb +7 -5
- data/lib/samagotchi/idle_scheduler.rb +7 -10
- data/lib/samagotchi/inline_widgets.rb +12 -0
- data/lib/samagotchi/installed_bundles/dir.rb +37 -0
- data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
- data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
- data/lib/samagotchi/installed_bundles/record.rb +3 -2
- data/lib/samagotchi/installed_bundles/standing.rb +3 -1
- data/lib/samagotchi/kernel_loop.rb +7 -5
- data/lib/samagotchi/llm/chat_loop.rb +2 -0
- data/lib/samagotchi/llm/http.rb +96 -5
- data/lib/samagotchi/markdown_parser.rb +28 -0
- data/lib/samagotchi/mcp_command.rb +110 -0
- data/lib/samagotchi/mcp_server/http.rb +112 -0
- data/lib/samagotchi/mcp_server/protocol.rb +244 -0
- data/lib/samagotchi/mcp_server/stdio.rb +92 -0
- data/lib/samagotchi/mcp_server/text.rb +155 -0
- data/lib/samagotchi/mcp_server/tools.rb +245 -0
- data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
- data/lib/samagotchi/memory_bundle/builder.rb +20 -2
- data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
- data/lib/samagotchi/memory_bundle/installer.rb +16 -3
- data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
- data/lib/samagotchi/memory_bundle/shas.rb +6 -4
- data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
- data/lib/samagotchi/memory_bundle/status.rb +15 -6
- data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
- data/lib/samagotchi/plugin/api.rb +6 -1
- data/lib/samagotchi/plugin/card.rb +36 -11
- data/lib/samagotchi/plugin/context.rb +63 -6
- data/lib/samagotchi/plugin/http.rb +40 -15
- data/lib/samagotchi/plugin/http_errors.rb +15 -0
- data/lib/samagotchi/plugin/http_stream.rb +86 -0
- data/lib/samagotchi/plugin/http_transport.rb +58 -16
- data/lib/samagotchi/plugin/loader.rb +18 -11
- data/lib/samagotchi/plugin/secrets.rb +266 -0
- data/lib/samagotchi/plugin/sign_in.rb +392 -0
- data/lib/samagotchi/plugin/sse_reader.rb +103 -0
- data/lib/samagotchi/queued_command.rb +28 -4
- data/lib/samagotchi/recap_setup.rb +13 -4
- data/lib/samagotchi/ref.rb +3 -2
- data/lib/samagotchi/relay_verifier.rb +8 -7
- data/lib/samagotchi/relay_watcher.rb +4 -4
- data/lib/samagotchi/run_options.rb +2 -1
- data/lib/samagotchi/send_command.rb +54 -41
- data/lib/samagotchi/session_access/ask.rb +244 -0
- data/lib/samagotchi/session_access/contract.rb +8 -0
- data/lib/samagotchi/session_access/delete_plan.rb +77 -0
- data/lib/samagotchi/session_access/exchange/token.rb +101 -0
- data/lib/samagotchi/session_access/exchange.rb +173 -0
- data/lib/samagotchi/session_access/local.rb +38 -6
- data/lib/samagotchi/session_access/remote.rb +23 -2
- data/lib/samagotchi/session_access.rb +1 -0
- data/lib/samagotchi/session_chain/delete.rb +39 -81
- data/lib/samagotchi/session_chain/delete_preview.rb +55 -19
- data/lib/samagotchi/session_command_catalog.rb +10 -0
- data/lib/samagotchi/session_commands.rb +17 -0
- data/lib/samagotchi/session_config.rb +4 -4
- data/lib/samagotchi/session_delete_command.rb +129 -3
- data/lib/samagotchi/session_manager/delegate_rule.rb +86 -0
- data/lib/samagotchi/session_manager/listing.rb +4 -4
- data/lib/samagotchi/session_manager/removal.rb +38 -12
- data/lib/samagotchi/session_manager/running_tasks.rb +50 -23
- data/lib/samagotchi/session_manager.rb +1 -0
- data/lib/samagotchi/session_observer.rb +27 -0
- data/lib/samagotchi/steer_cut.rb +4 -3
- data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
- data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
- data/lib/samagotchi/testing/boundary.rb +4 -0
- data/lib/samagotchi/testing/bundle.rb +48 -2
- data/lib/samagotchi/testing/fake_http.rb +60 -15
- data/lib/samagotchi/testing/host.rb +4 -1
- data/lib/samagotchi/testing/recorder.rb +45 -5
- data/lib/samagotchi/tools/tool_index.rb +14 -3
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +20 -6
- data/lib/samagotchi/web/ask_routes.rb +292 -0
- data/lib/samagotchi/web/block_fix_routes.rb +39 -0
- data/lib/samagotchi/web/markdown_renderer.rb +24 -9
- data/lib/samagotchi/web/mcp_route.rb +88 -0
- data/lib/samagotchi/web/message_display.rb +6 -1
- data/lib/samagotchi/web/participant_view.rb +1 -1
- data/lib/samagotchi/web/public/app.js +7 -8
- data/lib/samagotchi/web/public/block_fix.js +270 -0
- data/lib/samagotchi/web/public/block_fix_note.js +104 -0
- data/lib/samagotchi/web/public/block_frame.js +77 -13
- data/lib/samagotchi/web/public/block_host.js +45 -9
- data/lib/samagotchi/web/public/block_regions.js +126 -0
- data/lib/samagotchi/web/public/block_renderers.css +12 -0
- data/lib/samagotchi/web/public/block_watch.js +16 -2
- data/lib/samagotchi/web/public/card.js +22 -9
- data/lib/samagotchi/web/public/card_actions.js +21 -0
- data/lib/samagotchi/web/public/card_kinds.js +1 -1
- data/lib/samagotchi/web/public/card_registry.js +3 -2
- data/lib/samagotchi/web/public/data.js +15 -12
- data/lib/samagotchi/web/public/delete_sheet.js +222 -162
- data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
- data/lib/samagotchi/web/public/format.js +3 -0
- data/lib/samagotchi/web/public/index.html +52 -7
- data/lib/samagotchi/web/public/inline_widgets.js +1 -1
- data/lib/samagotchi/web/public/more_sheet.js +6 -4
- data/lib/samagotchi/web/public/picture_regions.js +243 -0
- data/lib/samagotchi/web/public/picture_viewer.js +113 -12
- data/lib/samagotchi/web/public/refs.js +5 -3
- data/lib/samagotchi/web/public/region_hit.js +144 -0
- data/lib/samagotchi/web/public/removal_sheet_model.js +275 -0
- data/lib/samagotchi/web/public/running_tasks.js +6 -4
- data/lib/samagotchi/web/public/session_actions.js +105 -100
- data/lib/samagotchi/web/public/stream_handlers.js +5 -1
- data/lib/samagotchi/web/public/turn_block.js +5 -2
- data/lib/samagotchi/web/server.rb +6 -4
- data/lib/samagotchi/web/session_access_routes.rb +14 -11
- data/lib/samagotchi/web/session_control.rb +84 -30
- data/lib/samagotchi/web/session_create.rb +2 -2
- data/lib/samagotchi/worker/block_fixes.rb +22 -0
- data/lib/samagotchi/worker/child_side.rb +3 -2
- data/lib/samagotchi/worker/command_queue.rb +13 -13
- data/lib/samagotchi/worker/leave.rb +3 -3
- data/lib/samagotchi/worker/scratch.rb +6 -6
- data/lib/samagotchi/worker/signal_grace.rb +6 -5
- data/lib/samagotchi/worker/startup.rb +3 -3
- data/lib/samagotchi/worker/wake_turns.rb +4 -4
- data/lib/samagotchi/worker.rb +42 -24
- data/lib/samagotchi/worker_exit_claim.rb +1 -1
- data/lib/samagotchi/worker_idle_exit.rb +18 -9
- data/lib/samagotchi/worker_inbound.rb +12 -7
- data/lib/samagotchi/worker_participant_gate.rb +9 -7
- data/lib/samagotchi/worker_task_wakes.rb +7 -5
- metadata +42 -1
|
@@ -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
|
+
}
|
|
@@ -9,19 +9,36 @@
|
|
|
9
9
|
// the frame's error event). The protocol, the handshake first:
|
|
10
10
|
//
|
|
11
11
|
// frame → loaded, page → code {files}, frame → ready | failed {message}
|
|
12
|
-
// page → render {id, source, theme}, frame → done {id, svg} | error {id, message}
|
|
12
|
+
// page → render {id, source, theme}, frame → done {id, svg, regions?} | error {id, message, bundle?}
|
|
13
13
|
//
|
|
14
|
+
// A renderer's render returns the SVG, or {svg, regions} when the page says it
|
|
15
|
+
// takes regions (chi.features.regions; an older chi's bootstrap refuses anything
|
|
16
|
+
// but a string, so a bundle checks). Regions are capped here and copied bounded,
|
|
17
|
+
// before any of them is cloned to the page (block_regions.js cleans them there). An object without a
|
|
18
|
+
// string svg is the bundle's bug, error {bundle: true}: not the model's, so no fix
|
|
19
|
+
// is asked (block_fix.js). No object at all (undefined, null, a number) is as an
|
|
20
|
+
// older chi took it: a failed render, the model's like a throw (so fixable): a
|
|
21
|
+
// renderer may return nothing for a source it can't draw. draw resolves {svg, regions} (regions raw, or null);
|
|
22
|
+
// render is its SVG.
|
|
14
23
|
// One render at a time. A timer can't fire while the renderer hangs (the frame
|
|
15
24
|
// shares the page's thread): block_host.js's mark is for that.
|
|
16
25
|
//
|
|
17
26
|
// A module of its own: static JS is cached at unversioned URLs.
|
|
18
27
|
|
|
28
|
+
import { MAX_REGIONS } from "./block_regions.js";
|
|
29
|
+
|
|
19
30
|
// Same words as the spike that tested them; the page's frame-src 'none' covers
|
|
20
31
|
// what this doesn't (navigation).
|
|
21
32
|
export const FRAME_CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; form-action 'none'";
|
|
22
33
|
export const FRAME_TIMEOUT_MS = 15000;
|
|
23
34
|
// An SVG this size isn't a diagram anyone reads, and it would sit in the DOM.
|
|
24
35
|
export const MAX_SVG_CHARS = 8 * 1024 * 1024;
|
|
36
|
+
// The error a bundle's bug gets: its render returned an object without a string svg.
|
|
37
|
+
const NO_SVG = "the renderer returned no SVG";
|
|
38
|
+
// The frame's copy of a region keeps a string this long at most, and this many
|
|
39
|
+
// points (the page cuts to 80 / 120 characters and 16 points).
|
|
40
|
+
const FRAME_TEXT_CHARS = 200;
|
|
41
|
+
const FRAME_POINTS = 16;
|
|
25
42
|
|
|
26
43
|
// Runs in the frame, before any bundle code. CSP doesn't stop WebRTC, so its
|
|
27
44
|
// constructors go (a nested srcdoc frame gets a fresh one: the residual risk,
|
|
@@ -33,7 +50,7 @@ const BOOTSTRAP = `(() => {
|
|
|
33
50
|
const words = (e) => String((e && e.message) || e).split("\\n")[0].slice(0, 300);
|
|
34
51
|
let renderer = null;
|
|
35
52
|
let loadError = null;
|
|
36
|
-
window.chi = { defineRenderer(r) { renderer = r; } };
|
|
53
|
+
window.chi = { defineRenderer(r) { renderer = r; }, features: { regions: true } };
|
|
37
54
|
addEventListener("error", (e) => { loadError = loadError || words(e.message || e.error); });
|
|
38
55
|
async function load(files) {
|
|
39
56
|
for (const code of files) {
|
|
@@ -47,14 +64,54 @@ const BOOTSTRAP = `(() => {
|
|
|
47
64
|
try { await (renderer.init && renderer.init()); } catch (e) { return send({ type: "failed", message: words(e) }); }
|
|
48
65
|
send({ type: "ready" });
|
|
49
66
|
}
|
|
67
|
+
// Regions only as an array of at most ${MAX_REGIONS}, each posted as a bounded copy
|
|
68
|
+
// of its known keys (strings cut to ${FRAME_TEXT_CHARS}, a box of 4 and up to ${FRAME_POINTS} points):
|
|
69
|
+
// so nothing vast is ever cloned on the page's thread (600 one-megabyte labels
|
|
70
|
+
// crashed a Chromium tab), and nothing uncloneable. Else none. The page cleans
|
|
71
|
+
// the copy again (block_regions.js).
|
|
72
|
+
const cut = (v) => (typeof v === "string" ? v.slice(0, ${FRAME_TEXT_CHARS}) : "");
|
|
73
|
+
const num = (v) => (typeof v === "number" ? v : NaN);
|
|
74
|
+
function copyRegion(r) {
|
|
75
|
+
if (!r || typeof r !== "object") return null;
|
|
76
|
+
const c = { kind: cut(r.kind), id: cut(r.id), label: cut(r.label), from: cut(r.from), to: cut(r.to) };
|
|
77
|
+
const box = r.box;
|
|
78
|
+
if (Array.isArray(box) && box.length === 4) c.box = [num(box[0]), num(box[1]), num(box[2]), num(box[3])];
|
|
79
|
+
const points = r.points;
|
|
80
|
+
if (Array.isArray(points) && points.length <= ${FRAME_POINTS}) {
|
|
81
|
+
c.points = [];
|
|
82
|
+
for (let i = 0; i < points.length; i++) {
|
|
83
|
+
const p = points[i];
|
|
84
|
+
c.points.push(Array.isArray(p) && p.length === 2 ? [num(p[0]), num(p[1])] : null);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return c;
|
|
88
|
+
}
|
|
89
|
+
function regionsOf(out) {
|
|
90
|
+
try {
|
|
91
|
+
const r = out.regions;
|
|
92
|
+
if (!Array.isArray(r) || r.length > ${MAX_REGIONS}) return null;
|
|
93
|
+
const copy = [];
|
|
94
|
+
for (let i = 0; i < r.length; i++) copy.push(copyRegion(r[i]));
|
|
95
|
+
return copy;
|
|
96
|
+
} catch (_) { return null; }
|
|
97
|
+
}
|
|
50
98
|
async function render(m) {
|
|
99
|
+
let out;
|
|
51
100
|
try {
|
|
52
|
-
|
|
53
|
-
if (typeof svg !== "string") throw new Error("the renderer returned no SVG");
|
|
54
|
-
send({ type: "done", id: m.id, svg });
|
|
101
|
+
out = await renderer.render(m.source, m.theme);
|
|
55
102
|
} catch (e) {
|
|
56
|
-
send({ type: "error", id: m.id, message: words(e) });
|
|
103
|
+
return send({ type: "error", id: m.id, message: words(e) });
|
|
104
|
+
}
|
|
105
|
+
if (typeof out === "string") return send({ type: "done", id: m.id, svg: out });
|
|
106
|
+
if (!out || typeof out !== "object") return send({ type: "error", id: m.id, message: ${JSON.stringify(NO_SVG)} });
|
|
107
|
+
let svg;
|
|
108
|
+
try { svg = out.svg; } catch (_) { svg = null; }
|
|
109
|
+
if (typeof svg !== "string") return send({ type: "error", id: m.id, message: ${JSON.stringify(NO_SVG)}, bundle: true });
|
|
110
|
+
const regions = regionsOf(out);
|
|
111
|
+
if (regions) {
|
|
112
|
+
try { return send({ type: "done", id: m.id, svg, regions }); } catch (_) { /* uncloneable: sent without them */ }
|
|
57
113
|
}
|
|
114
|
+
send({ type: "done", id: m.id, svg });
|
|
58
115
|
}
|
|
59
116
|
addEventListener("message", (e) => {
|
|
60
117
|
if (e.source !== parent) return;
|
|
@@ -82,19 +139,23 @@ export function frameMessage(event, frameWindow) {
|
|
|
82
139
|
|
|
83
140
|
// A reason a render or load failed. +timedOut+: the page's timer fired, so the
|
|
84
141
|
// block is suspect (block_host.js keeps its mark); +dropped+: the page let the
|
|
85
|
-
// frame go, which says nothing of the block
|
|
142
|
+
// frame go, which says nothing of the block; +renderer+: the renderer itself
|
|
143
|
+
// refused the source (the frame's error {id, message}), the model's input
|
|
144
|
+
// being wrong: the one failure a fix may help (block_fix.js).
|
|
86
145
|
export class FrameError extends Error {
|
|
87
|
-
constructor(message, { timedOut = false, dropped = false, load = false } = {}) {
|
|
146
|
+
constructor(message, { timedOut = false, dropped = false, load = false, renderer = false } = {}) {
|
|
88
147
|
super(message);
|
|
89
148
|
this.timedOut = timedOut;
|
|
90
149
|
this.dropped = dropped;
|
|
91
150
|
this.load = load;
|
|
151
|
+
this.renderer = renderer;
|
|
92
152
|
}
|
|
93
153
|
}
|
|
94
154
|
|
|
95
155
|
// @param files the renderer's file names, in load order
|
|
96
156
|
// @param fetchFile (file) => a promise of its text (block_host.js fetchRendererFile)
|
|
97
|
-
// @return {
|
|
157
|
+
// @return {draw(source, theme, {onStart}) → Promise<{svg, regions}> (regions raw: block_regions.js cleans them),
|
|
158
|
+
// render(...) → Promise<svg> (draw's SVG alone), drop(), dead()}
|
|
98
159
|
export function createBlockFrame({ files, fetchFile, doc = document, win = window, timeoutMs = FRAME_TIMEOUT_MS }) {
|
|
99
160
|
const iframe = doc.createElement("iframe");
|
|
100
161
|
iframe.setAttribute("sandbox", "allow-scripts");
|
|
@@ -144,9 +205,11 @@ export function createBlockFrame({ files, fetchFile, doc = document, win = windo
|
|
|
144
205
|
settle((w) => w.reject(new FrameError(String(m.message ?? "load failed"), { load: true })));
|
|
145
206
|
} else if (m.type === "done" && m.id === waiting.id) {
|
|
146
207
|
if (typeof m.svg !== "string" || m.svg.length > MAX_SVG_CHARS) settle((w) => w.reject(new FrameError("the renderer's SVG is too large or not text")));
|
|
147
|
-
else settle((w) => w.resolve(m.svg));
|
|
208
|
+
else settle((w) => w.resolve({ svg: m.svg, regions: m.regions ?? null }));
|
|
148
209
|
} else if (m.type === "error" && m.id === waiting.id) {
|
|
149
|
-
|
|
210
|
+
// A bundle's bug (its render's object had no svg) isn't the model's: no fix.
|
|
211
|
+
const renderer = m.bundle !== true;
|
|
212
|
+
settle((w) => w.reject(new FrameError(String(m.message ?? "render failed"), { renderer })));
|
|
150
213
|
}
|
|
151
214
|
}
|
|
152
215
|
|
|
@@ -181,7 +244,7 @@ export function createBlockFrame({ files, fetchFile, doc = document, win = windo
|
|
|
181
244
|
// One render at a time, whatever the last one came to.
|
|
182
245
|
let queue = ready.catch(() => {});
|
|
183
246
|
|
|
184
|
-
function
|
|
247
|
+
function draw(source, theme, { onStart = () => {} } = {}) {
|
|
185
248
|
const run = async () => {
|
|
186
249
|
await ready;
|
|
187
250
|
if (dead) throw new FrameError("the frame is gone", { dropped: true });
|
|
@@ -199,7 +262,8 @@ export function createBlockFrame({ files, fetchFile, doc = document, win = windo
|
|
|
199
262
|
|
|
200
263
|
return {
|
|
201
264
|
ready,
|
|
202
|
-
|
|
265
|
+
draw,
|
|
266
|
+
render: (source, theme, opts) => draw(source, theme, opts).then((r) => r.svg),
|
|
203
267
|
dead: () => dead,
|
|
204
268
|
drop: () => die(new FrameError("dropped", { dropped: true })),
|
|
205
269
|
};
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
|
|
14
14
|
import { html, render as litRender } from "./vendor/lit-html.js";
|
|
15
15
|
import { createBlockFrame, FRAME_TIMEOUT_MS } from "./block_frame.js";
|
|
16
|
+
import { cleanRegions } from "./block_regions.js";
|
|
16
17
|
import { DRAWN, figureOf, setSourceShown } from "./block_source.js";
|
|
17
18
|
import { createBlockWatch, failBlock, holdingView } from "./block_watch.js";
|
|
18
19
|
import { copyText } from "./copy.js";
|
|
@@ -155,6 +156,8 @@ export function createFrameDrawer({
|
|
|
155
156
|
// render has its blocks wait for that one, and each draws into whichever is connected.
|
|
156
157
|
const coming = new Map();
|
|
157
158
|
const retries = new WeakMap();
|
|
159
|
+
// The languages whose regions were cleaned away whole once: said once each.
|
|
160
|
+
const regionsDropped = new Set();
|
|
158
161
|
// What needsDraw checked, so draw draws that: pre => {lang, source, renderer}.
|
|
159
162
|
const checked = new WeakMap();
|
|
160
163
|
let list = null;
|
|
@@ -294,7 +297,12 @@ export function createFrameDrawer({
|
|
|
294
297
|
async function rendered(key, lang, source, renderer, now) {
|
|
295
298
|
const mark = markKey(lang, source);
|
|
296
299
|
try {
|
|
297
|
-
const
|
|
300
|
+
const frame = frameFor(lang, renderer);
|
|
301
|
+
const onStart = () => setMark(mark);
|
|
302
|
+
// draw: {svg, regions}; an older cached block_frame.js has render alone.
|
|
303
|
+
const out = frame.draw ? await frame.draw(source, now, { onStart }) : { svg: await frame.render(source, now, { onStart }) };
|
|
304
|
+
const svg = out.svg;
|
|
305
|
+
const regions = keptRegions(lang, out.regions);
|
|
298
306
|
const started = inFlight.get(mark);
|
|
299
307
|
const picture = pictureOf(svg, win);
|
|
300
308
|
const tooLarge = oversize(picture.width, picture.height);
|
|
@@ -305,7 +313,9 @@ export function createFrameDrawer({
|
|
|
305
313
|
if (tooLargeShown) throw new Error(tooLargeShown);
|
|
306
314
|
if (Date.now() - started > SLOW_RENDER_MS) inFlight.delete(mark);
|
|
307
315
|
else clearMark(mark);
|
|
308
|
-
const
|
|
316
|
+
const sized = picture.width ? picture : { ...picture, width: natural.width, height: natural.height };
|
|
317
|
+
// Only when there are some: a picture without regions has no such field.
|
|
318
|
+
const shown = regions ? { ...sized, regions } : sized;
|
|
309
319
|
remember(key, shown);
|
|
310
320
|
return shown;
|
|
311
321
|
} catch (e) {
|
|
@@ -316,6 +326,19 @@ export function createFrameDrawer({
|
|
|
316
326
|
}
|
|
317
327
|
}
|
|
318
328
|
|
|
329
|
+
// The renderer's regions, cleaned (block_regions.js), or null; a list cleaned
|
|
330
|
+
// away whole is said once per language, with its count and no model text.
|
|
331
|
+
function keptRegions(lang, raw) {
|
|
332
|
+
if (raw == null) return null;
|
|
333
|
+
const regions = cleanRegions(raw);
|
|
334
|
+
if (regions?.length) return regions;
|
|
335
|
+
if (!regions && !regionsDropped.has(lang)) {
|
|
336
|
+
regionsDropped.add(lang);
|
|
337
|
+
console.warn(`chi: the ${lang} renderer's regions were dropped (${Array.isArray(raw) ? raw.length : typeof raw} reported, over the caps or not a list)`);
|
|
338
|
+
}
|
|
339
|
+
return null;
|
|
340
|
+
}
|
|
341
|
+
|
|
319
342
|
// A claimed language has a renderer: the list is loaded by then.
|
|
320
343
|
function needsDraw(pre, figure) {
|
|
321
344
|
const lang = langOf(pre);
|
|
@@ -345,7 +368,7 @@ export function createFrameDrawer({
|
|
|
345
368
|
place(pre, await pictureFor(key, lang, source, renderer, now), now.name, lang);
|
|
346
369
|
} catch (e) {
|
|
347
370
|
// A redraw that failed keeps the picture it has.
|
|
348
|
-
if (!e?.dropped && !figureOf(pre)) failBlock(pre, lang, e?.message);
|
|
371
|
+
if (!e?.dropped && !figureOf(pre)) failBlock(pre, lang, e?.message, { fixable: !!e?.renderer });
|
|
349
372
|
retry = !!e?.dropped;
|
|
350
373
|
}
|
|
351
374
|
// Queued behind a frame that died (another block's timeout): a new frame's
|
|
@@ -359,19 +382,32 @@ export function createFrameDrawer({
|
|
|
359
382
|
else failBlock(pre, lang, "its renderer keeps stopping");
|
|
360
383
|
}
|
|
361
384
|
|
|
385
|
+
// A figure's picture for the viewer: its <img>'s URL, size from the viewBox
|
|
386
|
+
// (showPicture's attributes) and alt, plus what else the cache holds for that
|
|
387
|
+
// URL (a data: URL reads back from img.src as it was set; a Revise clone has
|
|
388
|
+
// the same). An evicted entry, or a figure an older page drew: the picture alone.
|
|
389
|
+
// At most CACHE_SIZE compares, on a click only.
|
|
390
|
+
function pictureOfFigure(figure) {
|
|
391
|
+
const img = figure?.querySelector(".block-img");
|
|
392
|
+
if (!img) return null;
|
|
393
|
+
const size = (name) => Number(img.getAttribute(name)) || null;
|
|
394
|
+
const picture = { url: img.src, width: size("width"), height: size("height"), alt: img.alt };
|
|
395
|
+
const held = [...cache.values()].find((p) => p.url === picture.url);
|
|
396
|
+
for (const [key, value] of Object.entries(held || {})) if (!(key in picture)) picture[key] = value;
|
|
397
|
+
return picture;
|
|
398
|
+
}
|
|
399
|
+
|
|
362
400
|
for (const root of roots) {
|
|
363
401
|
root.addEventListener("mousedown", (e) => {
|
|
364
402
|
if (e.target.closest?.(".block-zoom")) e.preventDefault();
|
|
365
403
|
});
|
|
366
|
-
// Delegated, so a Revise clone's work too: the picture in the viewer,
|
|
367
|
-
//
|
|
404
|
+
// Delegated, so a Revise clone's work too: the picture in the viewer, the
|
|
405
|
+
// focus back on the button.
|
|
368
406
|
root.addEventListener("click", (e) => {
|
|
369
407
|
if (!openPicture || !e.target.closest?.(".block-zoom, .block-img")) return;
|
|
370
408
|
const figure = e.target.closest(`.${DRAWN}`);
|
|
371
|
-
const
|
|
372
|
-
if (
|
|
373
|
-
const size = (name) => Number(img.getAttribute(name)) || null;
|
|
374
|
-
openPicture({ url: img.src, width: size("width"), height: size("height"), alt: img.alt }, { opener: figure.querySelector(":scope > .block-zoom") });
|
|
409
|
+
const picture = pictureOfFigure(figure);
|
|
410
|
+
if (picture) openPicture(picture, { opener: figure.querySelector(":scope > .block-zoom") });
|
|
375
411
|
});
|
|
376
412
|
}
|
|
377
413
|
|