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,304 @@
1
+ // The picture viewer (#lightbox): an attached image, or a drawn diagram
2
+ // (block_host.js), over the whole page, fitted at first, with zoom and pan.
3
+ // The maths is pan_zoom.js's; this is the DOM and the gestures
4
+ // (docs/internals/web-frontend.md, Picture viewer).
5
+ //
6
+ // - Zoom is the picture's layout size (its box's width and height in px) and a
7
+ // 2D translate its place: an SVG <img> is drawn again at its layout size, a
8
+ // scaled one can be a blurred bitmap. No will-change, no 3D transform, no
9
+ // animation: a composited layer at the largest size is hundreds of MB.
10
+ // - One pointer drags, two pinch; plain wheel moves, Ctrl/Cmd + wheel (a
11
+ // Chromium trackpad pinch) zooms at the cursor. Safari's gesture events are
12
+ // always prevented and applied only with no touch pointer down (a Mac
13
+ // trackpad): iOS fires them for a finger pinch too, beside the pointers.
14
+ // - A double tap or click goes close, or back to fit when already closer.
15
+ // - Closing is ✕ and Esc only; the keys are on the viewer's element.
16
+ //
17
+ // The picture and its place are one positioned box (.pv-pic), so a later
18
+ // overlay on the picture can share it.
19
+ //
20
+ // +picture+: {url, width, height, alt}; width and height may be absent.
21
+ // A module of its own: its exports are new (docs/internals/web-frontend.md,
22
+ // "New exports go in new modules").
23
+
24
+ import { html, render } from "./vendor/lit-html.js";
25
+ import { focusBack, modalDialog } from "./popover_modal.js";
26
+ import { BAR_ROOM, clampScale, clampView, fitScale, fitView, pinch, wheelStep, zoomAt } from "./pan_zoom.js";
27
+
28
+ const LABEL = "Picture viewer";
29
+ const STEP = 1.25;
30
+ const ARROW_PX = 60;
31
+ const TAP_MS = 300;
32
+ const TAP_SLOP = 4;
33
+ // A double tap goes this close to the fit, or to natural size if that is closer.
34
+ const CLOSE_FACTOR = 2.5;
35
+
36
+ const icon = (d) => html`<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d=${d} fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>`;
37
+
38
+ // A thumbnail's picture: its size once loaded, so most opens don't wait for
39
+ // a decode.
40
+ export function thumbPicture(img) {
41
+ const sized = img.complete && img.naturalWidth > 0;
42
+ return { url: img.src, alt: img.alt, width: sized ? img.naturalWidth : null, height: sized ? img.naturalHeight : null };
43
+ }
44
+
45
+ // The safe areas, as #lightbox's padding resolves them (index.html: --safe-*).
46
+ function paddingInsets(el, win) {
47
+ const s = win.getComputedStyle?.(el);
48
+ const px = (v) => parseFloat(v) || 0;
49
+ return s ? { t: px(s.paddingTop), r: px(s.paddingRight), b: px(s.paddingBottom), l: px(s.paddingLeft) } : { t: 0, r: 0, b: 0, l: 0 };
50
+ }
51
+
52
+ // @param el the #lightbox element (index.html keeps its <img> for an older
53
+ // cached app.js, which reads it; one is added when it is missing)
54
+ // The rest are seams for the specs: +measure+ the viewer's box, +insets+ its
55
+ // safe areas, +decode+ an image of unknown size, +now+ the clock of a double tap.
56
+ // Nothing here touches layout, PointerEvent or ResizeObserver until an open.
57
+ // @return {open(picture, {opener}), close(), isOpen()}
58
+ export function createPictureViewer({
59
+ el, doc = document, win = window, measure = () => el.getBoundingClientRect(), insets = () => paddingInsets(el, win),
60
+ decode = (img) => img.decode(), now = Date.now,
61
+ }) {
62
+ const img = el.querySelector("img") || el.appendChild(doc.createElement("img"));
63
+ img.draggable = false;
64
+ el.tabIndex = -1;
65
+ modalDialog(el, { label: LABEL, isOpen: () => isOpen(), doc });
66
+
67
+ let drawn = false;
68
+ let box = null;
69
+ let pct = null;
70
+ let picture = null;
71
+ let view = { scale: 1, x: 0, y: 0 };
72
+ let atFit = true;
73
+ let opener = null;
74
+ let opening = 0;
75
+ const pointers = new Map();
76
+ let pinchStart = null;
77
+ let gesture = null;
78
+ let down = null;
79
+ let lastTap = null;
80
+
81
+ const isOpen = () => !el.hidden;
82
+
83
+ function stage() {
84
+ const rect = measure();
85
+ return { width: rect.width, height: rect.height, insets: insets(), bar: BAR_ROOM };
86
+ }
87
+
88
+ const fit = () => fitScale(picture, stage());
89
+ const limit = (scale) => clampScale(scale, { fit: fit(), picture });
90
+
91
+ function paint() {
92
+ if (!picture) return;
93
+ view = clampView(view, picture, stage());
94
+ box.style.width = `${picture.width * view.scale}px`;
95
+ box.style.height = `${picture.height * view.scale}px`;
96
+ box.style.transform = `translate(${view.x}px, ${view.y}px)`;
97
+ pct.textContent = `${Math.round(view.scale * 100)}%`;
98
+ }
99
+
100
+ function toFit() {
101
+ if (!picture) return;
102
+ view = fitView(picture, stage());
103
+ atFit = true;
104
+ paint();
105
+ }
106
+
107
+ function zoomTo(scale, point) {
108
+ if (!picture) return;
109
+ view = zoomAt(view, limit(scale), point);
110
+ atFit = false;
111
+ paint();
112
+ }
113
+
114
+ function moveBy(dx, dy) {
115
+ if (!picture) return;
116
+ view = { ...view, x: view.x + dx, y: view.y + dy };
117
+ atFit = false;
118
+ paint();
119
+ }
120
+
121
+ function centre() {
122
+ const rect = measure();
123
+ return { x: rect.width / 2, y: rect.height / 2 };
124
+ }
125
+
126
+ function local(e) {
127
+ const rect = measure();
128
+ return { x: e.clientX - (rect.left || 0), y: e.clientY - (rect.top || 0) };
129
+ }
130
+
131
+ // A double tap at +point+: close in, or back to fit when already closer.
132
+ function toggleClose(point) {
133
+ const f = fit();
134
+ if (view.scale > f * 1.05) toFit();
135
+ else zoomTo(Math.max(f * CLOSE_FACTOR, 1), point);
136
+ }
137
+
138
+ function draw() {
139
+ if (drawn) return;
140
+ drawn = true;
141
+ render(html`<div class="pv-pic">${img}</div>
142
+ <button type="button" class="pv-btn pv-close" aria-label="Close" title="Close (Esc)" @click=${() => close()}>${icon("M4 4l8 8M12 4l-8 8")}</button>
143
+ <div class="pv-bar">
144
+ <button type="button" class="pv-btn pv-out" aria-label="Zoom out" title="Zoom out (-)" @click=${() => zoomTo(view.scale / STEP, centre())}>${icon("M3.5 8h9")}</button>
145
+ <span class="pv-pct" aria-live="polite"></span>
146
+ <button type="button" class="pv-btn pv-in" aria-label="Zoom in" title="Zoom in (+)" @click=${() => zoomTo(view.scale * STEP, centre())}>${icon("M3.5 8h9M8 3.5v9")}</button>
147
+ <span class="pv-sep" aria-hidden="true"></span>
148
+ <button type="button" class="pv-btn pv-fit" aria-label="Fit to the screen" title="Fit (0)" @click=${() => toFit()}>Fit</button>
149
+ </div>`, el);
150
+ box = el.querySelector(".pv-pic");
151
+ pct = el.querySelector(".pv-pct");
152
+ }
153
+
154
+ function onResize() {
155
+ if (atFit) toFit();
156
+ else paint();
157
+ }
158
+
159
+ async function open(next, { opener: from = null } = {}) {
160
+ draw();
161
+ const token = ++opening;
162
+ opener = from;
163
+ pointers.clear();
164
+ pinchStart = null;
165
+ gesture = null;
166
+ lastTap = null;
167
+ picture = null;
168
+ box.classList.add("waiting");
169
+ img.alt = next.alt || "";
170
+ img.src = next.url;
171
+ if (!isOpen()) {
172
+ el.hidden = false;
173
+ win.addEventListener?.("resize", onResize);
174
+ }
175
+ el.focus({ preventScroll: true });
176
+ let size = next.width > 0 && next.height > 0 ? { width: next.width, height: next.height } : null;
177
+ if (!size) {
178
+ try { await decode(img); } catch (_) { /* its natural size, if any, all the same */ }
179
+ if (token !== opening || !isOpen()) return;
180
+ size = { width: img.naturalWidth || 300, height: img.naturalHeight || 150 };
181
+ }
182
+ picture = size;
183
+ toFit();
184
+ // Placed already; shown once there is something to show (WebKit draws a
185
+ // broken-image box while even a cached URL loads).
186
+ if (!img.complete) {
187
+ try { await decode(img); } catch (_) { /* shown all the same */ }
188
+ if (token !== opening || !isOpen()) return;
189
+ }
190
+ box.classList.remove("waiting");
191
+ }
192
+
193
+ function close() {
194
+ if (!isOpen()) return;
195
+ opening++;
196
+ const back = focusBack(el, { doc, preventScroll: true });
197
+ el.hidden = true;
198
+ el.classList.remove("dragging");
199
+ win.removeEventListener?.("resize", onResize);
200
+ pointers.clear();
201
+ pinchStart = null;
202
+ gesture = null;
203
+ back(opener);
204
+ opener = null;
205
+ }
206
+
207
+ const onControls = (e) => e.target.closest?.(".pv-close, .pv-bar");
208
+ const touchDown = () => [...pointers.values()].some((p) => p.type === "touch");
209
+
210
+ el.addEventListener("pointerdown", (e) => {
211
+ if (onControls(e) || !picture) return;
212
+ if (e.pointerType === "mouse" && e.button !== 0) return;
213
+ try { el.setPointerCapture?.(e.pointerId); } catch (_) { /* a pointer already gone */ }
214
+ pointers.set(e.pointerId, { ...local(e), type: e.pointerType });
215
+ el.classList.add("dragging");
216
+ if (pointers.size === 1) down = { ...local(e), moved: false };
217
+ if (pointers.size === 2) {
218
+ const [a, b] = [...pointers.values()];
219
+ pinchStart = { a, b, view };
220
+ down.moved = true;
221
+ }
222
+ });
223
+
224
+ el.addEventListener("pointermove", (e) => {
225
+ const was = pointers.get(e.pointerId);
226
+ if (!was) return;
227
+ const at = { ...local(e), type: was.type };
228
+ pointers.set(e.pointerId, at);
229
+ if (pointers.size === 1) {
230
+ if (Math.abs(at.x - down.x) + Math.abs(at.y - down.y) > TAP_SLOP) down.moved = true;
231
+ moveBy(at.x - was.x, at.y - was.y);
232
+ } else if (pointers.size === 2 && pinchStart) {
233
+ const [a, b] = [...pointers.values()];
234
+ view = pinch(pinchStart, a, b, limit);
235
+ atFit = false;
236
+ paint();
237
+ }
238
+ });
239
+
240
+ function up(e) {
241
+ if (!pointers.delete(e.pointerId)) return;
242
+ if (pointers.size < 2) pinchStart = null;
243
+ if (pointers.size) return;
244
+ el.classList.remove("dragging");
245
+ if (e.type !== "pointerup" || down?.moved) { lastTap = null; return; }
246
+ const t = now();
247
+ const at = local(e);
248
+ if (lastTap && t - lastTap.t < TAP_MS && Math.abs(at.x - lastTap.x) + Math.abs(at.y - lastTap.y) < 30) {
249
+ lastTap = null;
250
+ toggleClose(at);
251
+ } else {
252
+ lastTap = { t, ...at };
253
+ }
254
+ }
255
+ el.addEventListener("pointerup", up);
256
+ el.addEventListener("pointercancel", up);
257
+ el.addEventListener("dragstart", (e) => e.preventDefault());
258
+
259
+ el.addEventListener("wheel", (e) => {
260
+ e.preventDefault();
261
+ if (!picture) return;
262
+ const step = wheelStep(e);
263
+ if (e.ctrlKey || e.metaKey) zoomTo(view.scale * step.zoom, local(e));
264
+ else moveBy(-step.dx, -step.dy);
265
+ }, { passive: false });
266
+
267
+ // Safari's gestures: always prevented (they would zoom the page), applied
268
+ // only for a Mac trackpad (no touch pointer down).
269
+ el.addEventListener("gesturestart", (e) => {
270
+ e.preventDefault();
271
+ gesture = picture && !touchDown() ? { view, point: local(e) } : null;
272
+ });
273
+ el.addEventListener("gesturechange", (e) => {
274
+ e.preventDefault();
275
+ if (!gesture || touchDown() || !picture) return;
276
+ view = zoomAt(gesture.view, limit(gesture.view.scale * e.scale), gesture.point);
277
+ atFit = false;
278
+ paint();
279
+ });
280
+ el.addEventListener("gestureend", (e) => {
281
+ e.preventDefault();
282
+ gesture = null;
283
+ });
284
+
285
+ el.addEventListener("keydown", (e) => {
286
+ const k = e.key;
287
+ const plain = !e.ctrlKey && !e.metaKey && !e.altKey;
288
+ let done = true;
289
+ if (k === "Escape") close();
290
+ else if (plain && (k === "+" || k === "=")) zoomTo(view.scale * STEP, centre());
291
+ else if (plain && (k === "-" || k === "_")) zoomTo(view.scale / STEP, centre());
292
+ else if (plain && k === "0") toFit();
293
+ else if (plain && k === "ArrowLeft") moveBy(ARROW_PX, 0);
294
+ else if (plain && k === "ArrowRight") moveBy(-ARROW_PX, 0);
295
+ else if (plain && k === "ArrowUp") moveBy(0, ARROW_PX);
296
+ else if (plain && k === "ArrowDown") moveBy(0, -ARROW_PX);
297
+ else done = false;
298
+ if (!done) return;
299
+ e.preventDefault();
300
+ e.stopPropagation();
301
+ });
302
+
303
+ return { open, close, isOpen };
304
+ }
@@ -50,8 +50,9 @@ export function modalDialog(pop, { label = null, isOpen, doc = document }) {
50
50
 
51
51
  // Called before +pop+ closes: whether the focus was in it (or +refocus+:
52
52
  // an Esc), and so goes back(to) its opener once it has closed.
53
+ // +preventScroll+: the opener takes the focus without scrolling to it.
53
54
  // @return (to) => focuses +to+ when it should and still can
54
- export function focusBack(pop, { refocus = false, doc = document } = {}) {
55
+ export function focusBack(pop, { refocus = false, doc = document, preventScroll = false } = {}) {
55
56
  const had = refocus || pop.contains(doc.activeElement);
56
- return (to) => { if (had && to?.isConnected) to.focus?.(); };
57
+ return (to) => { if (had && to?.isConnected) to.focus?.(preventScroll ? { preventScroll: true } : undefined); };
57
58
  }
@@ -26,6 +26,7 @@
26
26
  // peerLinks the peer exchange's slots (peer_links.js): filled after a
27
27
  // read is drawn, reset with the session; null: none
28
28
  // markdown markdown_place.js (linkTextRefs, applyFinalMarkdown)
29
+ // pictures the picture viewer (picture_viewer.js), closed with the session; null: none
29
30
  // capabilities() the page's capabilities (card.js shownElsewhere, the history's cards)
30
31
  // page: {setReviseAnchor(anchor), renderInitRow(), setMarkdownWarning(warning),
31
32
  // setCapabilities(capabilities, editorUrl, viewer), findInTurnRoots(selector), appendToHistory(el),
@@ -59,6 +60,7 @@ export function createSessionView(deps) {
59
60
  store, historyEl, getSession,
60
61
  liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet = null, wsPreview = null, gapClock,
61
62
  bubbles, cards, markdown, capabilities, page, later, cardRegistry = null, stageMissing = null, peerLinks = null,
63
+ pictures = null,
62
64
  } = deps;
63
65
  const { makeUserBubble, addEndBubble, showGuardrailWarning, showRecap } = bubbles;
64
66
  const { placeSnapshotCards, upsertCard } = cards;
@@ -111,6 +113,8 @@ export function createSessionView(deps) {
111
113
  // The reader and the peek are the session's: another one (or none, the
112
114
  // start page) never finds them over #center, the composer inert under it.
113
115
  if (!keepVerify) wsPreview?.reset();
116
+ // The picture viewer holds a picture of the session left; the same one again keeps it.
117
+ if (!keepVerify) pictures?.close();
114
118
  applyPrefs();
115
119
  }
116
120
 
@@ -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; else as live drew it.
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 at = [group.answer, ...[...(group.texts || [])].reverse()].find((i) => i != null && String(items[i]?.content ?? "").trim() === text);
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;
@@ -10,9 +10,11 @@
10
10
  // write: a write of a file is an edit), at the first row that brought it in
11
11
  // as ordinals ({turn, step, row}: the turn's place in the page's turns, the
12
12
  // generation's in the turn, the row's in the generation; never a row key,
13
- // which differs live and reloaded), count the rows that touched it, runs
13
+ // which differs live and reloaded), last the newest row that touched it
14
+ // (the same ordinals: the list's order and its session step tag,
15
+ // ws_order.js), count the rows that touched it, runs
14
16
  // each row's tool id with its at ([{id, at}], rows with an id only). A later
15
- // touch unions its ops and bumps its count, never its at: within a turn
17
+ // touch unions its ops, bumps its count and moves its last, never its at: within a turn
16
18
  // the set is append-only, which keeps the fold stable. state is "live" from
17
19
  // the rows; the server's projection (GET working_set, :working_set_updated:
18
20
  // WorkingSet) overlays its state (live, stale, forgotten, dropped) and
@@ -147,6 +149,8 @@ export function itemsOfTurn(turn, turnOrdinal) {
147
149
  byKey.set(id, item);
148
150
  items.push(item);
149
151
  }
152
+ // Its newest touch so far (the turn's last, once the walk ends).
153
+ item.last = at;
150
154
  // The row's tool id and place: the timeline's step tags and "go to
151
155
  // the call" (ws_timeline.js placeOf); a legacy row has none.
152
156
  if (row.tool_id) item.runs = [...(item.runs || []), { id: row.tool_id, at }];
@@ -157,7 +161,7 @@ export function itemsOfTurn(turn, turnOrdinal) {
157
161
  }
158
162
 
159
163
  // The session's set: every turn's items merged (the first entry's at kept,
160
- // ops unioned, counts summed), the preloaded memories first (tag
164
+ // the latest list's last, ops unioned, counts summed), the preloaded memories first (tag
161
165
  // "prompt"), the used memories no row explains (a turn without its saved
162
166
  // rows) after them; the muted memories listed apart, never counted.
163
167
  // @param turns the finished turns' item lists, in order
@@ -184,6 +188,8 @@ export function sessionItems({ turns = [], live = [], preloaded = [], notes = []
184
188
  found.count += it.count;
185
189
  if (it.runs) found.runs = [...(found.runs || []), ...it.runs];
186
190
  if (!found.at) found.at = it.at;
191
+ // Lists come in turn order, the live turn's last: the latest wins.
192
+ if (it.last) found.last = it.last;
187
193
  }
188
194
  }
189
195
  }
@@ -53,6 +53,7 @@ import {
53
53
  steerId, steerLine, stepRange, stepTag, tokensText, turnLens, undroppable,
54
54
  } from "./working_set.js";
55
55
  import { serverSig } from "./ws_item_sig.js";
56
+ import { heldOrder, recencyOrder } from "./ws_order.js";
56
57
 
57
58
  // The popover's files fold to this many lines (groups open in place, one at
58
59
  // a time), its memories past this many to one group.
@@ -177,6 +178,10 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
177
178
  // lit on the session's list), the group open in it.
178
179
  let lens = null;
179
180
  let openGroup = null;
181
+ // The list's order taken at the open (ws_order.js): the item keys, last
182
+ // touched first. Held while it is open (rows that come go on top, the
183
+ // others stay); every open takes it again (null: closed).
184
+ let openKeys = null;
180
185
  // What the drawn list shows of the context's tokens (tokenText): a chunk's
181
186
  // new count redraws it only when that text changes.
182
187
  let shownTokens = null;
@@ -224,11 +229,14 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
224
229
  session,
225
230
  // Opened: the server's set asked again (a file changed while the
226
231
  // session sat idle shows stale).
232
+ // The order is taken again at each open (a footprint or the rail while
233
+ // it is open too: they open it again).
227
234
  show: (_data, opening) => {
235
+ if (opening) openKeys = recencyOrder(sessionSet().items).map(itemKey);
228
236
  draw();
229
237
  if (opening) fetchServer();
230
238
  },
231
- onClose: () => { openGroup = null; peek?.close(); onChange(); },
239
+ onClose: () => { openGroup = null; openKeys = null; peek?.close(); onChange(); },
232
240
  // The foot's + add (the popover's submit): one KEY as typed (quoted
233
241
  // when it has spaces).
234
242
  onSubmit: (form) => {
@@ -298,11 +306,14 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
298
306
  // the words, the edited mark) and nothing else.
299
307
  const item = touched ? lensItem(row0, touched) : row0;
300
308
  const lensClass = touched && !row0.added ? (touched.has(itemKey(row0)) ? " lit" : " dim") : "";
301
- // A dimmed row's entry is the session's (its first, "t1·s1"); a lit row's the turn's.
309
+ // A dimmed row's tag is the session's last touch ("t3·s4"; an older
310
+ // page's item: its first entry); a lit row's the turn's entry ("s3").
311
+ // By the lens class: a lit row carries the session's `last` too.
302
312
  const whole = inSession || lensClass === " dim";
313
+ const place = whole ? row0.last || row0.at : item.at;
303
314
  const fresh = isFresh(seenAt(row0), now);
304
315
  // A lit preloaded memory the turn read shows the turn's step, not "prompt".
305
- const tag = stepTag(lensClass === " lit" && item.at ? { ...item, preloaded: false } : item, { session: whole });
316
+ const tag = stepTag(lensClass === " lit" && item.at ? { ...item, preloaded: false } : { ...item, at: place }, { session: whole });
306
317
  const note = start && touched ? heldTwiceNote(row0, touched.get(itemKey(row0))) : "";
307
318
  // An added row's words: what it is (a phone's tap on them opens its strip).
308
319
  const what = start ? [memoryPartWords(row0), row0.state && row0.state !== "live" ? row0.state : ""].filter(Boolean).join(" · ") : opsText(item);
@@ -323,9 +334,9 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
323
334
  if (start && inSession && heldTwice(row0)) tagEl = html`<span class="ws-twice" title="already in the prompt and read again: held twice">held twice</span>`;
324
335
  else if (tag === "prompt") tagEl = start ? nothing : html`<span class="ws-step p" title="in the system prompt">prompt</span>`;
325
336
  else if (tag) {
326
- const prompt = whole ? promptOf(item.at.turn) : "";
327
- const where = whole ? `turn ${item.at.turn + 1}${prompt ? ` (${prompt})` : ""}, step ${item.at.step + 1}` : `step ${item.at.step + 1}`;
328
- tagEl = html`<button type="button" class=${`ws-step${item.kind === "memory" ? " p" : ""}${note ? " twice" : ""}`} data-ws="jump" data-at=${atAttr(item.at)} title=${`entered at ${where}: go to the call`}>${tag}</button>`;
337
+ const prompt = whole ? promptOf(place.turn) : "";
338
+ const where = whole ? `turn ${place.turn + 1}${prompt ? ` (${prompt})` : ""}, step ${place.step + 1}` : `step ${place.step + 1}`;
339
+ tagEl = html`<button type="button" class=${`ws-step${item.kind === "memory" ? " p" : ""}${note ? " twice" : ""}`} data-ws="jump" data-at=${atAttr(place)} title=${`${whole ? "last touched" : "entered"} at ${where}: go to the call`}>${tag}</button>`;
329
340
  }
330
341
  const edited = item.kind === "file" && item.ops.includes("edit");
331
342
  const state = row0.state && row0.state !== "live" ? ` ${row0.state}` : "";
@@ -367,8 +378,9 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
367
378
  const startRow = (row, opts) => (row.kind === "memory" ? rowTemplate(row, { ...opts, start: true }) : partRowTemplate(row, opts));
368
379
  const isLit = (item, opts) => !!opts.touched && opts.touched.has(itemKey(item));
369
380
 
370
- // The head view's sections (ws_sections.js headSections): each header
371
- // folds (per session, session_prefs.js WS_SECTION_FOLD); folded, a section
381
+ // The head view's sections (ws_sections.js headSections), read · talk ·
382
+ // start: each header folds (per session, session_prefs.js WS_SECTION_FOLD;
383
+ // none stored: start folded); folded, a section
372
384
  // shows only the rows the lens lights. Conversation is one row, no header,
373
385
  // no fold (a stored fold naming it is ignored).
374
386
  function headTemplate(sections, opts, folded) {
@@ -376,7 +388,7 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
376
388
  if (section.key === "talk") return html`<div class="ws-sec talk">${talkTemplate(section, opts)}</div>`;
377
389
  const open = !folded.has(section.key);
378
390
  const tokens = tokensText(section.tokens);
379
- const head = html`<button type="button" class="ws-sec-head" data-ws="section" data-id=${section.key} aria-expanded=${String(open)}><span class="k">${open ? "▾" : "▸"}</span><span class="t">${section.title}</span>${section.meta ? html`<span class="n">${section.meta}</span>` : nothing}${tokens ? html`<span class="tk">${tokens}</span>` : nothing}</button>`;
391
+ const head = html`<button type="button" class="ws-sec-head" data-ws="section" data-id=${section.key} aria-expanded=${String(open)}><span class="k">${open ? "▾" : "▸"}</span><span class="t">${section.title}</span>${section.meta ? html`<span class="n">${section.meta}</span>` : nothing}${section.twice ? html`<span class="w" title="in the prompt and read again: held twice">· ${section.twice} held twice</span>` : nothing}${tokens ? html`<span class="tk">${tokens}</span>` : nothing}</button>`;
380
392
  let body;
381
393
  if (section.inner) {
382
394
  body = open
@@ -409,7 +421,8 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
409
421
  }
410
422
 
411
423
  // The session's folded sections, and a toggle of one.
412
- const foldedNow = () => foldedSections(readPref(WS_SECTION_FOLD, session(), "[]"));
424
+ // Nothing stored (null, told from a stored []) is the default fold.
425
+ const foldedNow = () => foldedSections(readPref(WS_SECTION_FOLD, session(), null));
413
426
  function toggleSection(key) {
414
427
  const folded = foldedNow();
415
428
  if (folded.has(key)) folded.delete(key);
@@ -442,10 +455,14 @@ export function createWorkingSet({ historyEl, stageRoot = () => null, state, ses
442
455
  // session and is kept: the turn coming back lights it again.
443
456
  const at = curLens();
444
457
  const inSession = at === null;
445
- const set = sessionSet();
458
+ const full = sessionSet();
446
459
  const pend = pending();
447
460
  const forget = forgetOn(st.llmContext);
448
461
  const last = lastTurn();
462
+ // The list's order: last touched first, held while it is open
463
+ // (ws_order.js). Only the list's: rowItem, steer and the rail read the
464
+ // set as it is.
465
+ const set = { ...full, items: heldOrder(full.items, openKeys) };
449
466
  // The head view (no parts: today's list); a turn's read of `system/x`
450
467
  // lights the start row of `x`, and a prompt memory is never new.
451
468
  const head = headSections(set, POP_BUDGET, { parts: st.promptParts, ctxTokens: st.ctxTokens, turns: last + 1, inTurn: !inSession });
@@ -3,10 +3,14 @@
3
3
  // read's lines draw as a read row's do (.read-line, numbered); an edit's
4
4
  // diff with diff_view.js, the same renderer as the tool row's and the
5
5
  // approval card's. A card chi no longer has is greyed, its text folded.
6
+ // A memory's text and a whole read of an .md file render as markdown once
7
+ // their HTML is there (ws_markdown.js; the +md+ option), with a
8
+ // "rendered | source" switch in the card's header.
6
9
 
7
10
  import { html, nothing } from "./vendor/lit-html.js";
8
11
  import { diffCounts, diffTemplate } from "./diff_view.js";
9
12
  import { eventTag, goneText, linesText, placeOf, SLICE_FOLD_LINES, tagsText } from "./ws_timeline.js";
13
+ import { markdownTemplate, renderable, sourceText } from "./ws_markdown.js";
10
14
 
11
15
  const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
12
16
 
@@ -34,23 +38,40 @@ export function callTemplate(event, item, label = "go to the call") {
34
38
  return html`<button type="button" class="wsr-call" data-ws="jump" data-at=${`${at.turn}.${at.step}.${at.row}`}>${label}</button>`;
35
39
  }
36
40
 
37
- function goneBody(card, rows, undrop) {
41
+ // The card's "rendered | source" switch (+view+ the one pressed).
42
+ function viewTemplate(view) {
43
+ const button = (name) => html`<button type="button" class=${view === name ? "on" : ""} aria-pressed=${String(view === name)} data-wsr="view" data-view=${name}>${name}</button>`;
44
+ return html`<span class="wsr-view" role="group" aria-label="Show as">${button("rendered")}${button("source")}</span>`;
45
+ }
46
+
47
+ // A text, rendered when +shown+ holds its markdown (else as sent).
48
+ const textOr = (text, shown) => shown ?? textTemplate(text);
49
+
50
+ function goneBody(card, rows, undrop, shown = null) {
38
51
  const words = goneText(card.state);
39
52
  const what = card.type === "slice" ? plural(rows.length, "line") : "its text";
40
53
  const offer = card.state === "dropped" && undrop !== nothing ? html` · ${undrop}` : nothing;
41
- return html`<div class="wsr-gone">${what} · ${words}${offer}</div><details class="wsr-had"><summary>what it was</summary>${card.type === "slice" ? linesTemplate(rows) : textTemplate(card.event.text)}</details>`;
54
+ const had = shown ?? (card.type === "slice" ? linesTemplate(rows) : textTemplate(card.event.text));
55
+ return html`<div class="wsr-gone">${what} · ${words}${offer}</div><details class="wsr-had"><summary>what it was</summary>${had}</details>`;
42
56
  }
43
57
 
44
- // A memory read's overlay part (ws_timeline: event.memory.overlay).
45
- function overlayTemplate(memory) {
58
+ // A memory read's overlay part (ws_timeline: event.memory.overlay),
59
+ // rendered with its card (+md+, +on+: the card shows rendered).
60
+ function overlayTemplate(memory, md = null, on = false) {
46
61
  if (!memory?.overlay) return nothing;
47
62
  const name = String(memory.overlay_path || "").split("/").pop();
48
- return html`<div class="wsr-overlay"><div class="wsr-overlay-h">+ overlay for this model${name ? ` · ${name}` : ""}</div>${textTemplate(memory.overlay)}</div>`;
63
+ // Asked with its card's text, so both come together.
64
+ const rendered = md ? markdownTemplate(memory.overlay, md) : null;
65
+ const shown = on ? rendered : null;
66
+ return html`<div class="wsr-overlay"><div class="wsr-overlay-h">+ overlay for this model${name ? ` · ${name}` : ""}</div>${textOr(memory.overlay, shown)}</div>`;
49
67
  }
50
68
 
51
69
  // One card. +item+: the open item (its runs: the step tags); +undrop+: the
52
- // greyed card's undrop button (a template), or nothing.
53
- export function cardTemplate(card, { item, undrop = nothing } = {}) {
70
+ // greyed card's undrop button (a template), or nothing; +md+ ({view,
71
+ // html(text)}: the reader's): a renderable card whose HTML is there gets
72
+ // the switch and, with +view+ "rendered", its markdown. Without it (an old
73
+ // reader), today's source.
74
+ export function cardTemplate(card, { item, undrop = nothing, md = null } = {}) {
54
75
  const gone = card.state && card.state !== "sent";
55
76
  const pill = gone ? html`<span class="wsr-pill gone">chi no longer has this</span>`
56
77
  : card.latest ? html`<span class="wsr-pill latest">latest</span>` : nothing;
@@ -58,10 +79,13 @@ export function cardTemplate(card, { item, undrop = nothing } = {}) {
58
79
  let meta = "";
59
80
  let body;
60
81
  let call;
82
+ const rendered = md && renderable(card, item) ? markdownTemplate(sourceText(card), md) : null;
83
+ const on = rendered !== null && md.view !== "source";
84
+ const shown = on ? rendered : null;
61
85
  if (card.type === "slice") {
62
86
  title = linesText(card);
63
87
  meta = `${plural(card.reads.length, "read")} · ${tagsText(card.reads, item)}`;
64
- body = gone ? goneBody(card, card.rows, undrop) : linesTemplate(card.rows);
88
+ body = gone ? goneBody(card, card.rows, undrop, shown) : shown ?? linesTemplate(card.rows);
65
89
  call = callTemplate(card.reads[0], item);
66
90
  } else {
67
91
  const { event } = card;
@@ -81,9 +105,11 @@ export function cardTemplate(card, { item, undrop = nothing } = {}) {
81
105
  title = `${words} · ${tag}`;
82
106
  const shared = event.shared_with?.length ? `read with ${event.shared_with.join(", ")}` : "";
83
107
  meta = shared;
84
- body = gone ? goneBody(card, [], undrop) : html`${textTemplate(event.text)}${card.type === "memory" ? overlayTemplate(event.memory) : nothing}`;
108
+ body = gone ? goneBody(card, [], undrop, shown) : html`${textOr(event.text, shown)}${card.type === "memory" ? overlayTemplate(event.memory, md, on) : nothing}`;
85
109
  }
86
110
  }
87
111
  const classes = `wsr-card ${card.type}${gone ? ` gone ${card.state}` : ""}${card.latest ? " latest" : ""}`;
88
- return html`<article class=${classes} data-newest=${card.newest}><header class="wsr-card-h"><span class="wsr-card-t">${title}</span>${meta ? html`<span class="wsr-card-m">${meta}</span>` : nothing}${pill}${call}</header>${body}</article>`;
112
+ const view = rendered !== null ? viewTemplate(on ? "rendered" : "source") : nothing;
113
+ const first = card.type === "slice" ? card.first : nothing;
114
+ return html`<article class=${classes} data-newest=${card.newest} data-first=${first}><header class="wsr-card-h"><span class="wsr-card-t">${title}</span>${meta ? html`<span class="wsr-card-m">${meta}</span>` : nothing}${pill}<span class="wsr-card-actions">${view}${call}</span></header>${body}</article>`;
89
115
  }