samagotchi 0.181.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +26 -1
- data/bin/chi +1 -0
- data/docs/architecture.md +1 -1
- data/docs/cli.md +30 -4
- data/docs/configuration.md +1 -0
- data/docs/internals/block-renderers.md +114 -0
- data/docs/internals/bridge.md +10 -0
- data/docs/internals/engine.md +11 -0
- data/docs/internals/inline-widgets.md +3 -1
- data/docs/internals/prompt-caching.md +9 -1
- data/docs/internals/remote-sessions.md +14 -2
- data/docs/internals/web-frontend.md +33 -3
- data/docs/sessions.md +7 -4
- 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/turn_drawings.rb +19 -0
- data/lib/samagotchi/bridge.rb +11 -2
- data/lib/samagotchi/bridge_client.rb +9 -0
- data/lib/samagotchi/bundles/system/manifest.yml +1 -1
- data/lib/samagotchi/config.rb +3 -0
- data/lib/samagotchi/continue_intent.rb +8 -0
- data/lib/samagotchi/engine/block_fix.rb +332 -0
- data/lib/samagotchi/engine/side_requests.rb +7 -5
- data/lib/samagotchi/engine.rb +4 -0
- data/lib/samagotchi/events.rb +1 -0
- data/lib/samagotchi/idle_client.rb +10 -6
- data/lib/samagotchi/inline_widgets.rb +12 -0
- data/lib/samagotchi/kernel_loop.rb +7 -5
- data/lib/samagotchi/llm/chat_loop.rb +2 -0
- data/lib/samagotchi/markdown_parser.rb +28 -0
- data/lib/samagotchi/session_access/contract.rb +3 -0
- data/lib/samagotchi/session_access/delete_plan.rb +77 -0
- data/lib/samagotchi/session_access/local.rb +13 -0
- data/lib/samagotchi/session_access/remote.rb +19 -1
- 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_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/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +13 -1
- data/lib/samagotchi/web/block_fix_routes.rb +39 -0
- data/lib/samagotchi/web/markdown_renderer.rb +24 -9
- 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 +5 -5
- 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 +6 -3
- data/lib/samagotchi/web/public/block_host.js +1 -1
- 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/inline_widgets.js +1 -1
- 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_control.rb +53 -21
- data/lib/samagotchi/worker/block_fixes.rb +22 -0
- data/lib/samagotchi/worker.rb +10 -3
- metadata +12 -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
|
+
}
|
|
@@ -82,13 +82,16 @@ export function frameMessage(event, frameWindow) {
|
|
|
82
82
|
|
|
83
83
|
// A reason a render or load failed. +timedOut+: the page's timer fired, so the
|
|
84
84
|
// block is suspect (block_host.js keeps its mark); +dropped+: the page let the
|
|
85
|
-
// frame go, which says nothing of the block
|
|
85
|
+
// frame go, which says nothing of the block; +renderer+: the renderer itself
|
|
86
|
+
// refused the source (the frame's error {id, message}), the model's input
|
|
87
|
+
// being wrong: the one failure a fix may help (block_fix.js).
|
|
86
88
|
export class FrameError extends Error {
|
|
87
|
-
constructor(message, { timedOut = false, dropped = false, load = false } = {}) {
|
|
89
|
+
constructor(message, { timedOut = false, dropped = false, load = false, renderer = false } = {}) {
|
|
88
90
|
super(message);
|
|
89
91
|
this.timedOut = timedOut;
|
|
90
92
|
this.dropped = dropped;
|
|
91
93
|
this.load = load;
|
|
94
|
+
this.renderer = renderer;
|
|
92
95
|
}
|
|
93
96
|
}
|
|
94
97
|
|
|
@@ -146,7 +149,7 @@ export function createBlockFrame({ files, fetchFile, doc = document, win = windo
|
|
|
146
149
|
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
150
|
else settle((w) => w.resolve(m.svg));
|
|
148
151
|
} else if (m.type === "error" && m.id === waiting.id) {
|
|
149
|
-
settle((w) => w.reject(new FrameError(String(m.message ?? "render failed"))));
|
|
152
|
+
settle((w) => w.reject(new FrameError(String(m.message ?? "render failed"), { renderer: true })));
|
|
150
153
|
}
|
|
151
154
|
}
|
|
152
155
|
|
|
@@ -345,7 +345,7 @@ export function createFrameDrawer({
|
|
|
345
345
|
place(pre, await pictureFor(key, lang, source, renderer, now), now.name, lang);
|
|
346
346
|
} catch (e) {
|
|
347
347
|
// A redraw that failed keeps the picture it has.
|
|
348
|
-
if (!e?.dropped && !figureOf(pre)) failBlock(pre, lang, e?.message);
|
|
348
|
+
if (!e?.dropped && !figureOf(pre)) failBlock(pre, lang, e?.message, { fixable: !!e?.renderer });
|
|
349
349
|
retry = !!e?.dropped;
|
|
350
350
|
}
|
|
351
351
|
// Queued behind a frame that died (another block's timeout): a new frame's
|
|
@@ -24,3 +24,15 @@
|
|
|
24
24
|
.block-note{margin:4px 0 12px;font-size:12px;color:var(--text-3);white-space:normal}
|
|
25
25
|
.block-note{cursor:copy}
|
|
26
26
|
.block-note::before{content:attr(data-text)}
|
|
27
|
+
/* A failed block asked for again (block_fix_note.js): the line keeps one line's height while its words change, wraps only at a phone's width; "asking for a fix…" has a pulsing dot; Ask in chat is a pill whose label is CSS (data-label), so nothing of the page's own is in the bubble's text. */
|
|
28
|
+
.block-note[data-fix]{display:flex;flex-wrap:wrap;align-items:center;gap:2px 10px;min-height:28px}
|
|
29
|
+
.block-note[data-fix="asking"]::after{content:"";display:inline-block;flex:none;width:6px;height:6px;margin-left:-4px;border-radius:50%;background:var(--accent);animation:block-fix-pulse 1s steps(13) infinite}
|
|
30
|
+
@keyframes block-fix-pulse{50%{opacity:.25}}
|
|
31
|
+
@media (prefers-reduced-motion:reduce){.block-note[data-fix="asking"]::after{animation:none}}
|
|
32
|
+
.block-fix-ask{flex:none;font:inherit;font-size:12px;font-weight:500;line-height:1.5;color:var(--accent);background:none;border:1px solid var(--border-strong);border-radius:999px;padding:3px 10px;cursor:pointer}
|
|
33
|
+
.block-fix-ask::before{content:attr(data-label)}
|
|
34
|
+
.block-fix-ask:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
|
35
|
+
@media(hover:hover){.block-fix-ask:hover{border-color:var(--accent)}}
|
|
36
|
+
@media (pointer:coarse),(max-width:700px){.block-fix-ask{min-height:44px;padding:0 14px}}
|
|
37
|
+
/* "Drawn after a fix" under a fixed block that drew: muted, not a copy target. */
|
|
38
|
+
.block-note.fixed{margin-top:4px;cursor:default}
|
|
@@ -78,13 +78,23 @@ export function holdingView(pre, roots, mutate, bottomOf, win = window) {
|
|
|
78
78
|
return result;
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
+
// How much of a drawer's error a block keeps for a fix's request
|
|
82
|
+
// (BlockFix::MAX_REASON_CHARS): a Mermaid error's useful part is after its
|
|
83
|
+
// first line, which alone the line shows.
|
|
84
|
+
const MAX_REASON = 300;
|
|
85
|
+
|
|
81
86
|
// The <pre> stays as it is, under one muted line: never markup (the words are
|
|
82
87
|
// a drawer's, driven by the model's input), and shown by CSS, so a bubble's
|
|
83
88
|
// textContent, its dedupe and an annotation's text stay what they were (copy.js's
|
|
84
89
|
// rule for its buttons). A click on the line copies it (the watcher's listener).
|
|
85
|
-
|
|
90
|
+
// +fixable+: the failure is the model's (a refused chi-ui block, a renderer's
|
|
91
|
+
// own error), so a fix may be asked for (block_fix.js). Either way a bubbling
|
|
92
|
+
// "block-failed" event goes out from the <pre>.
|
|
93
|
+
export function failBlock(pre, lang, message, { fixable = false } = {}) {
|
|
86
94
|
if (!pre.isConnected) return;
|
|
87
95
|
pre.dataset.blockFailed = "1";
|
|
96
|
+
if (fixable) pre.dataset.blockFixable = "1";
|
|
97
|
+
pre.dataset.blockReason = String(message ?? "").trim().slice(0, MAX_REASON);
|
|
88
98
|
const note = pre.ownerDocument.createElement("div");
|
|
89
99
|
note.className = "block-note";
|
|
90
100
|
const first = String(message ?? "").split("\n")[0].trim();
|
|
@@ -94,6 +104,7 @@ export function failBlock(pre, lang, message) {
|
|
|
94
104
|
note.setAttribute("aria-label", words);
|
|
95
105
|
note.title = "Click to copy";
|
|
96
106
|
pre.after(note);
|
|
107
|
+
pre.dispatchEvent(new (pre.ownerDocument.defaultView?.CustomEvent || CustomEvent)("block-failed", { bubbles: true }));
|
|
97
108
|
}
|
|
98
109
|
|
|
99
110
|
// A copy.js wrap took the <pre> away from a figure placed first: back with it.
|
|
@@ -247,7 +258,10 @@ export function createBlockWatch({ roots, sessionId, drawers, watch = null, copy
|
|
|
247
258
|
setSourceShown(figure, figure.nextElementSibling, !figure.classList.contains("source"));
|
|
248
259
|
return;
|
|
249
260
|
}
|
|
250
|
-
|
|
261
|
+
// A button in the line (block_fix_note.js) is its own, not a copy, and
|
|
262
|
+
// "Drawn after a fix" (.block-note.fixed) has no error to copy.
|
|
263
|
+
if (e.target.closest?.(".block-note button")) return;
|
|
264
|
+
const note = e.target.closest?.(".block-note:not(.fixed)");
|
|
251
265
|
if (note) copy(note.dataset.text);
|
|
252
266
|
});
|
|
253
267
|
}
|
|
@@ -112,7 +112,7 @@ export function createWidgetDrawer({ roots, composerText, fillComposer, doc = do
|
|
|
112
112
|
function needsDraw(pre, figure) {
|
|
113
113
|
if (figure) return !hostOf(figure)?.shadowRoot;
|
|
114
114
|
if (pre.hasAttribute("data-widget-error")) {
|
|
115
|
-
failBlock(pre, LANG, pre.getAttribute("data-widget-error"));
|
|
115
|
+
failBlock(pre, LANG, pre.getAttribute("data-widget-error"), { fixable: true });
|
|
116
116
|
return false;
|
|
117
117
|
}
|
|
118
118
|
return pre.hasAttribute("data-widget");
|
|
@@ -46,6 +46,7 @@
|
|
|
46
46
|
// gapClock the page's last activity (time_gaps.js
|
|
47
47
|
// createGapClock; renderHistory seeds it)
|
|
48
48
|
// addTimeGap(text, {before}) a gap's divider (bubbles.js)
|
|
49
|
+
// blockFix(data) a block fix's word (block_fix.js onEvent); absent: none
|
|
49
50
|
|
|
50
51
|
import { routeChunk } from "./chunk_router.js";
|
|
51
52
|
import { extractCtxPct, generationTokens } from "./ctx.js";
|
|
@@ -75,7 +76,7 @@ export function createStreamHandlers(deps) {
|
|
|
75
76
|
appendChunk, readTurnEnd, applyFinalMarkdown, refreshTimingFromSession, makeUserBubble, addEndBubble,
|
|
76
77
|
commandBubble, addCommandBubble, addNoteBubble, findInTurnRoots, setUsedMemories, showRecap,
|
|
77
78
|
showGuardrailWarning, showHookNotice, onInitEvent, upsertCard, refreshCardBodies, syncModelPick,
|
|
78
|
-
gapClock = null, addTimeGap = () => null,
|
|
79
|
+
gapClock = null, addTimeGap = () => null, blockFix = null,
|
|
79
80
|
} = deps;
|
|
80
81
|
// Activity starts (a turn, a reminder, a note) at +time+ (the event's;
|
|
81
82
|
// none: now): a gap's divider above +before+ (else at the end) when a
|
|
@@ -440,6 +441,9 @@ export function createStreamHandlers(deps) {
|
|
|
440
441
|
question_cancelled: (data) => {
|
|
441
442
|
questionCards.resolveQuestion(data.id, { cancelled: true, reason: data.reason });
|
|
442
443
|
},
|
|
444
|
+
// The worker's word on a block fix it was asked for (block_fix.js): a
|
|
445
|
+
// fixed answer is read again and drawn; a failed or dropped one says so.
|
|
446
|
+
block_fix: (data) => blockFix?.(data),
|
|
443
447
|
// A side request (the recap, /btw, a plugin's ctx.ask_model) counted:
|
|
444
448
|
// the server's whole side block, for the ctx tooltip's line at once.
|
|
445
449
|
side_usage: (data) => {
|
|
@@ -969,10 +969,13 @@ function drawnTurnNodes(group, items, { thumbs, capabilities = {}, cards = null
|
|
|
969
969
|
|
|
970
970
|
// The live answer bubble as the reload draws it from its saved message
|
|
971
971
|
// (its markdown, refs, display: answerBubbleTemplate), when one of the
|
|
972
|
-
// turn's texts says what it says
|
|
972
|
+
// turn's texts says what it says, or the answer had a block fixed in its
|
|
973
|
+
// text since (block_fixed: what streamed is the block before the fix);
|
|
974
|
+
// else as live drew it.
|
|
973
975
|
function savedAnswer(el, group, items, kind) {
|
|
974
976
|
const text = el.textContent.trim();
|
|
975
|
-
const
|
|
977
|
+
const said = [group.answer, ...[...(group.texts || [])].reverse()].find((i) => i != null && String(items[i]?.content ?? "").trim() === text);
|
|
978
|
+
const at = said ?? (group.answer != null && items[group.answer]?.block_fixed ? group.answer : null);
|
|
976
979
|
if (at == null) return el;
|
|
977
980
|
const turnId = kind === "completed" ? group.drawing?.end?.turn_id || null : null;
|
|
978
981
|
return nodesOf(answerBubbleTemplate(items[at], { at, turnId })).firstElementChild;
|
|
@@ -172,6 +172,7 @@ module Samagotchi
|
|
|
172
172
|
working_set: Config::BY_KEY["web.working_set"].default, tunnel: nil, start_dir_from: :flag,
|
|
173
173
|
stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
|
|
174
174
|
reload_check: Config::BY_KEY["web.reload_check"].default,
|
|
175
|
+
block_fix: Config::BY_KEY["web.block_fix"].default,
|
|
175
176
|
restarted: false, restart_argv: ["web"], exec: nil)
|
|
176
177
|
handed_on = false # a :restart leaves Serve to the next process, a run turns it off itself
|
|
177
178
|
start_given = !start_dir.to_s.strip.empty?
|
|
@@ -231,8 +232,8 @@ module Samagotchi
|
|
|
231
232
|
Push.preflight!(public_url)
|
|
232
233
|
options = { port: port, host: host, url: url, open_browser: open_browser, markdown: markdown,
|
|
233
234
|
annotate_presets: annotate_presets, editor: editor, lan: lan, working_set: working_set,
|
|
234
|
-
stage_collapsed: stage_collapsed, reload_check: reload_check,
|
|
235
|
-
start_dir: start_dir }
|
|
235
|
+
stage_collapsed: stage_collapsed, reload_check: reload_check, block_fix: block_fix,
|
|
236
|
+
public_url: public_url, start_dir: start_dir }
|
|
236
237
|
started = if plan
|
|
237
238
|
with_tunnel(provider, plan) do |up|
|
|
238
239
|
start(**options, public_notes: provider.start_lines(plan, restarted: restarted), on_bound: up)
|
|
@@ -463,6 +464,7 @@ module Samagotchi
|
|
|
463
464
|
working_set: Config::BY_KEY["web.working_set"].default, public_url: nil, public_notes: [],
|
|
464
465
|
stage_collapsed: Config::BY_KEY["web.stage_collapsed"].default,
|
|
465
466
|
reload_check: Config::BY_KEY["web.reload_check"].default,
|
|
467
|
+
block_fix: Config::BY_KEY["web.block_fix"].default,
|
|
466
468
|
on_bound: nil, start_dir: Dir.pwd, update_check: nil, auto_update: nil)
|
|
467
469
|
config_restart_unsubscribe = ConfigFile.watch_restart_settings!(process: :web) do |message|
|
|
468
470
|
Samagotchi::Log.warn(:config, "restart_required", echo: "Warning: config: #{message}")
|
|
@@ -479,8 +481,8 @@ module Samagotchi
|
|
|
479
481
|
push = push_runtime(public_url, state_dir)
|
|
480
482
|
app = App.new(manager: manager, state_dir: state_dir, markdown: markdown,
|
|
481
483
|
annotate_presets: annotate_presets, editor: editor, hub: hub, lan: lan_option, working_set: working_set,
|
|
482
|
-
stage_collapsed: stage_collapsed, reload_check: reload_check,
|
|
483
|
-
public_token: public_token, push: push, start_dir: start_dir)
|
|
484
|
+
stage_collapsed: stage_collapsed, reload_check: reload_check, block_fix: block_fix,
|
|
485
|
+
public_url: public_url, public_token: public_token, push: push, start_dir: start_dir)
|
|
484
486
|
# update.auto: install; a stand-in app (a spec's) has no operations to run.
|
|
485
487
|
auto_update ||= AutoUpdate.new(hub: hub, ops: app.update_ops, check: update_check, preflight: method(:restart_preflight)) if app.respond_to?(:update_ops)
|
|
486
488
|
webrick = nil
|