samagotchi 0.179.0 → 0.181.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 (95) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +76 -1
  3. data/bin/chi +10 -0
  4. data/docs/architecture.md +1 -1
  5. data/docs/bundles.md +39 -3
  6. data/docs/cli.md +16 -9
  7. data/docs/configuration.md +25 -5
  8. data/docs/context.md +7 -0
  9. data/docs/internals/anthropic.md +4 -3
  10. data/docs/internals/background-tasks.md +4 -1
  11. data/docs/internals/block-renderers.md +11 -7
  12. data/docs/internals/bundles.md +12 -10
  13. data/docs/internals/objectives.md +9 -4
  14. data/docs/internals/web-frontend.md +127 -6
  15. data/docs/internals/working-set.md +24 -5
  16. data/docs/memory.md +3 -0
  17. data/docs/plugins.md +17 -6
  18. data/docs/sessions.md +1 -1
  19. data/docs/testing.md +5 -1
  20. data/lib/samagotchi/block_renderers.rb +22 -3
  21. data/lib/samagotchi/bundle_command.rb +9 -2
  22. data/lib/samagotchi/bundle_needs.rb +1 -1
  23. data/lib/samagotchi/bundle_settings_check.rb +5 -2
  24. data/lib/samagotchi/bundles/known-names/manifest.yml +2 -2
  25. data/lib/samagotchi/bundles/known-names/plugin.rb +4 -3
  26. data/lib/samagotchi/bundles/system/config_modification_protocol.md +3 -2
  27. data/lib/samagotchi/bundles/system/manifest.yml +2 -2
  28. data/lib/samagotchi/client.rb +8 -1
  29. data/lib/samagotchi/config.rb +6 -1
  30. data/lib/samagotchi/context_providers.rb +6 -8
  31. data/lib/samagotchi/core_notice.rb +44 -0
  32. data/lib/samagotchi/host_address.rb +7 -0
  33. data/lib/samagotchi/host_config.rb +8 -5
  34. data/lib/samagotchi/host_registry.rb +26 -8
  35. data/lib/samagotchi/installed_bundles/dir.rb +17 -55
  36. data/lib/samagotchi/installed_bundles/standing.rb +23 -3
  37. data/lib/samagotchi/installed_bundles.rb +26 -11
  38. data/lib/samagotchi/kernel_loop.rb +3 -2
  39. data/lib/samagotchi/llm/adapter_common.rb +3 -2
  40. data/lib/samagotchi/llm/adapters.rb +2 -1
  41. data/lib/samagotchi/llm/anthropic_assembly.rb +5 -0
  42. data/lib/samagotchi/llm/anthropic_messages.rb +6 -2
  43. data/lib/samagotchi/llm/chat_loop.rb +6 -5
  44. data/lib/samagotchi/llm/errors.rb +41 -3
  45. data/lib/samagotchi/llm/http.rb +85 -22
  46. data/lib/samagotchi/llm/openai_chat.rb +20 -3
  47. data/lib/samagotchi/memory_bundle/status.rb +10 -6
  48. data/lib/samagotchi/objectives.rb +7 -2
  49. data/lib/samagotchi/owner_lock.rb +2 -0
  50. data/lib/samagotchi/plugin/api.rb +4 -1
  51. data/lib/samagotchi/plugin/context.rb +9 -0
  52. data/lib/samagotchi/plugin/peer.rb +32 -15
  53. data/lib/samagotchi/plugin/tool_spec.rb +13 -2
  54. data/lib/samagotchi/row_refs.rb +14 -3
  55. data/lib/samagotchi/session_chain/delete.rb +6 -6
  56. data/lib/samagotchi/session_config.rb +15 -9
  57. data/lib/samagotchi/session_manager/removal.rb +2 -2
  58. data/lib/samagotchi/terminal_ui/attached_loop.rb +1 -1
  59. data/lib/samagotchi/terminal_ui/formatting.rb +13 -3
  60. data/lib/samagotchi/terminal_ui/join_replay.rb +1 -1
  61. data/lib/samagotchi/tool_ids.rb +19 -0
  62. data/lib/samagotchi/tool_runner.rb +8 -4
  63. data/lib/samagotchi/tools/registry.rb +3 -2
  64. data/lib/samagotchi/tools/task_runtime.rb +46 -3
  65. data/lib/samagotchi/turn_stages/objectives.rb +10 -5
  66. data/lib/samagotchi/version.rb +1 -1
  67. data/lib/samagotchi/web/public/app.js +22 -14
  68. data/lib/samagotchi/web/public/block_host.js +20 -20
  69. data/lib/samagotchi/web/public/block_renderers.css +5 -5
  70. data/lib/samagotchi/web/public/context_chips.js +183 -49
  71. data/lib/samagotchi/web/public/history_shape.js +5 -3
  72. data/lib/samagotchi/web/public/images.js +1 -1
  73. data/lib/samagotchi/web/public/index.html +90 -5
  74. data/lib/samagotchi/web/public/objectives_strip.js +16 -6
  75. data/lib/samagotchi/web/public/pan_zoom.js +121 -0
  76. data/lib/samagotchi/web/public/peer_chip.js +171 -0
  77. data/lib/samagotchi/web/public/peer_data.js +131 -0
  78. data/lib/samagotchi/web/public/peer_exchange.js +83 -0
  79. data/lib/samagotchi/web/public/peer_links.js +161 -0
  80. data/lib/samagotchi/web/public/peer_note.js +49 -0
  81. data/lib/samagotchi/web/public/picture_viewer.js +304 -0
  82. data/lib/samagotchi/web/public/popover_modal.js +3 -2
  83. data/lib/samagotchi/web/public/session_view.js +10 -1
  84. data/lib/samagotchi/web/public/stream_handlers.js +17 -4
  85. data/lib/samagotchi/web/public/turn_html.js +11 -2
  86. data/lib/samagotchi/web/public/working_set.js +9 -3
  87. data/lib/samagotchi/web/public/working_set_view.js +28 -11
  88. data/lib/samagotchi/web/public/ws_cards.js +36 -10
  89. data/lib/samagotchi/web/public/ws_markdown.js +129 -0
  90. data/lib/samagotchi/web/public/ws_order.js +48 -0
  91. data/lib/samagotchi/web/public/ws_peek.js +22 -5
  92. data/lib/samagotchi/web/public/ws_preview.css +41 -1
  93. data/lib/samagotchi/web/public/ws_reader.js +35 -6
  94. data/lib/samagotchi/web/public/ws_sections.js +24 -15
  95. metadata +11 -1
@@ -0,0 +1,83 @@
1
+ // A peer exchange as the conversation shows it (docs/internals/web-frontend.md,
2
+ // The peer exchange): a send row's peer ref, the exchange's state as words
3
+ // ("waiting 2m", "changes · answered after 6m") and the send row's pill. Pure:
4
+ // no fetch, no DOM; the state and the verdict come from the server
5
+ // (GET …/peers: PeerExchanges.joined), never joined or parsed here.
6
+ // Its own module: new exports go in new modules (web-frontend.md).
7
+
8
+ import { html, nothing } from "./vendor/lit-html.js";
9
+
10
+ // The ref of kind peer on a tool row (a peer tool's send: Plugin::Peer's
11
+ // refs, {kind: "peer", target: {id}}), or null.
12
+ export function peerRef(row) {
13
+ const refs = Array.isArray(row?.refs) ? row.refs : [];
14
+ return refs.find((ref) => ref?.kind === "peer" && typeof ref.target?.id === "string" && ref.target.id) || null;
15
+ }
16
+
17
+ // A stretch of time as the pill says it: "<1m", "6m", "2h", "3d".
18
+ export function spanText(ms) {
19
+ const s = Math.max(0, Math.floor(Number(ms) / 1000) || 0);
20
+ if (s < 60) return "<1m";
21
+ if (s < 3600) return `${Math.floor(s / 60)}m`;
22
+ if (s < 86400) return `${Math.floor(s / 3600)}h`;
23
+ return `${Math.floor(s / 86400)}d`;
24
+ }
25
+
26
+ const since = (from, to) => {
27
+ const a = Date.parse(from || "");
28
+ const b = typeof to === "number" ? to : Date.parse(to || "");
29
+ return Number.isNaN(a) || Number.isNaN(b) ? null : b - a;
30
+ };
31
+
32
+ // The verdict word of an answer (the server's, one of OK, CHANGES,
33
+ // UNSURE), lower case; "" for none.
34
+ export function verdictWord(verdict) {
35
+ return ["OK", "CHANGES", "UNSURE"].includes(verdict) ? verdict.toLowerCase() : "";
36
+ }
37
+
38
+ // The exchange's state in words. +ended+: the row's turn has ended (a row
39
+ // whose id has no exchange then reads "not sent": the send never went out);
40
+ // +short+: the phone's words. "" when there is nothing to say (a context
41
+ // send expects no answer; an exchange not read yet in a running turn).
42
+ export function stateText(exchange, { now = Date.now(), short = false, ended = false } = {}) {
43
+ if (!exchange) return ended ? "not sent" : "";
44
+ if (exchange.state === "failed") return "not sent";
45
+ if (exchange.state === "none_expected") return "";
46
+ if (exchange.state === "waiting") {
47
+ const age = since(exchange.at, now);
48
+ return age === null ? "waiting" : `waiting ${spanText(age)}`;
49
+ }
50
+ if (exchange.state !== "answered") return "";
51
+ const took = since(exchange.at, exchange.answer?.at);
52
+ const verdict = verdictWord(exchange.answer?.verdict);
53
+ const after = took === null ? "" : `after ${spanText(took)}`;
54
+ if (!verdict) return after ? `answered ${after}` : "answered";
55
+ if (short) return after ? `${verdict} · ${after}` : verdict;
56
+ return after ? `${verdict} · answered ${after}` : `${verdict} · answered`;
57
+ }
58
+
59
+ // The pill's tint: the verdict's for an answer, else the state's.
60
+ function pillKind(exchange, text) {
61
+ if (!exchange) return text ? "failed" : "";
62
+ if (exchange.state === "answered") return verdictWord(exchange.answer?.verdict) || "answered";
63
+ return exchange.state;
64
+ }
65
+
66
+ // The send row's pill: a button that jumps to the answer (↓) once answered,
67
+ // a span otherwise, nothing when stateText has no words. Its long and short
68
+ // words both drawn (CSS shows the phone's under 600 px). +title+: the row's
69
+ // output text (its output line is hidden on a send that went out).
70
+ export function pillTemplate(exchange, { now = Date.now(), ended = false, title = "" } = {}) {
71
+ const long = stateText(exchange, { now, ended });
72
+ if (!long) return nothing;
73
+ const short = stateText(exchange, { now, ended, short: true });
74
+ const cls = `peer-state ${pillKind(exchange, long)}`;
75
+ const words = short === long
76
+ ? html`<span class="peer-long">${long}</span>`
77
+ : html`<span class="peer-long">${long}</span><span class="peer-short">${short}</span>`;
78
+ if (exchange?.state === "answered") {
79
+ return html`<button type="button" class=${cls} data-peer-jump="answer" title=${title || nothing}
80
+ aria-label=${`${long}: go to the answer`}>${words}<span aria-hidden="true"> ↓</span></button>`;
81
+ }
82
+ return html`<span class=${cls} title=${title || nothing}>${words}</span>`;
83
+ }
@@ -0,0 +1,161 @@
1
+ // The peer exchange in the conversation: the controller that draws what the
2
+ // peers model (peer_data.js) knows into the slots the templates leave
3
+ // (turn_html.js: a send row's `.peer-slot`; peer_note.js: an answer's ↑ and
4
+ // "Read the full answer"), and the jumps between a send and its answer.
5
+ // Finished rows are never drawn again and a reload makes them anew, so the
6
+ // state that comes later is drawn here: after each history draw
7
+ // (session_view.js renderSessionView) and on the model's onChange.
8
+ // docs/internals/web-frontend.md, The peer exchange.
9
+ // Its own module: new exports go in new modules (web-frontend.md).
10
+
11
+ import { html, nothing, render } from "./vendor/lit-html.js";
12
+ import { pillTemplate } from "./peer_exchange.js";
13
+ import { EXCHANGES_CAP } from "./peer_data.js";
14
+ import { showRow } from "./refs.js";
15
+ import { revealInHistory } from "./history_reveal.js";
16
+
17
+ const SLOTS = ".peer-slot[data-peer-ref]";
18
+ const ANSWERS = ".bubble.note.peer-answer";
19
+
20
+ // +a+ comes before +b+ in the page.
21
+ const precedes = (a, b) => !!(a.compareDocumentPosition(b) & 4 /* DOCUMENT_POSITION_FOLLOWING */);
22
+
23
+ // The answer's ↑: back to the send it answers (kind · title), nothing for
24
+ // an answer no send claims (or one not read yet).
25
+ export function upTemplate(exchange) {
26
+ if (!exchange?.id) return nothing;
27
+ const what = [exchange.kind, exchange.title].filter(Boolean).join(" · ") || "the send";
28
+ return html`<button type="button" class="peer-up" data-peer-jump="send" data-peer-id=${exchange.id}
29
+ aria-label=${`${what}: go to the send`}>${what}<span aria-hidden="true"> ↑</span></button>`;
30
+ }
31
+
32
+ // "Read the full answer": the newest answer of a peer only (its outbox keeps
33
+ // one text).
34
+ export function fullTemplate(newest) {
35
+ return newest ? html`<button type="button" class="peer-full" data-peer-full="1">Read the full answer</button>` : nothing;
36
+ }
37
+
38
+ // +peers+ the model (peer_data.js); +roots+() the elements a turn's rows can
39
+ // be in (the history and the stage); +running+() whether a turn runs;
40
+ // +showText+(source) opens that context source's text (context_chips.js);
41
+ // +behavior+() the scroll's.
42
+ //
43
+ // @return {draw(), drawn(), hasPeer(), hasSend(id), showSend(id), reset()}
44
+ export function createPeerLinks({ peers, roots, running = () => false, showText = () => {}, behavior = smooth } = {}) {
45
+ const all = (selector) => roots().filter(Boolean).flatMap((root) => [...root.querySelectorAll(selector)]);
46
+
47
+ // A slot of the running turn (the stage's, or a turn opened in the history).
48
+ const live = (slot) => running() && !!slot.closest(".turn-stage, [data-opened-turn]");
49
+
50
+ // A send whose id the read doesn't have: did it not go out ("not sent"),
51
+ // or is it only not in the read (unknown: no pill)? Not sent when the row
52
+ // says it failed, or, once its turn has ended, when its peer's list is
53
+ // whole (under the server's cap) or holds a send drawn before this row
54
+ // (the list is the newest exchanges, so this row is among them). A peer
55
+ // the read doesn't name (detached, an older chi web) is unknown.
56
+ function notSent(slot, slots) {
57
+ const row = slot.closest(".activity-row");
58
+ if (/^Error:/.test(slot.getAttribute("title") || "") || row?.querySelector(":scope > .activity-status.error")) return true;
59
+ if (!peers.loaded() || live(slot)) return false;
60
+ const tool = row?.dataset.tool || "";
61
+ const peer = tool.endsWith("_send") ? peers.peer(tool.slice(0, -"_send".length)) : null;
62
+ if (!peer) return false;
63
+ const listed = (peer.exchanges || []).filter((ex) => ex?.id);
64
+ if ((peer.exchanges || []).length < EXCHANGES_CAP) return true;
65
+ const ids = new Set(listed.map((ex) => ex.id));
66
+ return slots.some((other) => other !== slot && ids.has(other.dataset.peerRef) && precedes(other, slot));
67
+ }
68
+
69
+ function draw() {
70
+ const now = Date.now();
71
+ const slots = all(SLOTS);
72
+ for (const slot of slots) {
73
+ const exchange = peers.exchange(slot.dataset.peerRef);
74
+ const ended = !exchange && notSent(slot, slots);
75
+ render(pillTemplate(exchange, { now, ended, title: slot.getAttribute("title") || "" }), slot);
76
+ }
77
+ const notes = all(ANSWERS);
78
+ const newest = new Map();
79
+ for (const note of notes) newest.set(note.dataset.peerSource || "", note);
80
+ for (const note of notes) {
81
+ const up = note.querySelector(":scope > .peer-head > .peer-up-slot");
82
+ if (up) render(upTemplate(answerOf(note)), up);
83
+ const full = note.querySelector(":scope > .peer-foot > .peer-full-slot");
84
+ if (full) render(fullTemplate(newest.get(note.dataset.peerSource || "") === note && !!note.dataset.peerSource), full);
85
+ }
86
+ }
87
+
88
+ function answerOf(note) {
89
+ const { peerName, peerSerial, peerRe } = note.dataset;
90
+ return peers.answer(peerName, peerSerial ?? null, peerRe || null);
91
+ }
92
+
93
+ // Focus lands on the jump's target (it isn't focusable by itself).
94
+ function land(el) {
95
+ if (!el.hasAttribute("tabindex")) el.setAttribute("tabindex", "-1");
96
+ el.focus?.({ preventScroll: true });
97
+ }
98
+
99
+ // ↓: the send's answer, the last bubble drawn for its serial.
100
+ function toAnswer(slot) {
101
+ const ex = peers.exchange(slot.dataset.peerRef);
102
+ const serial = ex?.answer?.serial;
103
+ if (serial === undefined || serial === null) return;
104
+ const note = all(ANSWERS).filter((n) => n.dataset.peerName === ex.peer && n.dataset.peerSerial === String(serial)).at(-1);
105
+ if (!note) return;
106
+ revealInHistory(note);
107
+ note.scrollIntoView?.({ block: "center", behavior: behavior() });
108
+ land(note);
109
+ }
110
+
111
+ // ↑: the send's row, the last one with its id before the answer (a resend
112
+ // has one id), else the last one.
113
+ function toSend(button) {
114
+ showSend(button.dataset.peerId, button.closest(ANSWERS));
115
+ }
116
+
117
+ // The row of send +id+ (the last before +before+, when given), shown and
118
+ // focused; false when none is drawn.
119
+ function showSend(id, before = null) {
120
+ const slots = all(SLOTS).filter((s) => s.dataset.peerRef === id);
121
+ const slot = (before && slots.filter((s) => precedes(s, before)).at(-1)) || slots.at(-1);
122
+ const row = slot?.closest(".activity-row");
123
+ if (!row) return false;
124
+ showRow(row, { behavior: behavior() });
125
+ land(row);
126
+ return true;
127
+ }
128
+
129
+ function onClick(e) {
130
+ const jump = e.target.closest?.("[data-peer-jump]");
131
+ if (jump?.dataset.peerJump === "answer") {
132
+ const slot = jump.closest(SLOTS);
133
+ if (slot) toAnswer(slot);
134
+ } else if (jump?.dataset.peerJump === "send") toSend(jump);
135
+ else if (e.target.closest?.("[data-peer-full]")) {
136
+ const source = e.target.closest(ANSWERS)?.dataset.peerSource;
137
+ if (source) showText(source);
138
+ }
139
+ }
140
+ for (const root of roots().filter(Boolean)) root.addEventListener("click", onClick);
141
+
142
+ return {
143
+ draw,
144
+ // A history drawn (a session's read): its slots filled with what is
145
+ // known, then read again.
146
+ drawn() {
147
+ draw();
148
+ return peers.refresh();
149
+ },
150
+ hasPeer: () => all(SLOTS).length > 0 || all(ANSWERS).length > 0,
151
+ // Whether send +id+'s row is drawn, and a jump to it (the peer chip's
152
+ // exchange list, peer_chip.js).
153
+ hasSend: (id) => all(SLOTS).some((s) => s.dataset.peerRef === id),
154
+ showSend: (id) => showSend(id),
155
+ reset: () => peers.clear(),
156
+ };
157
+ }
158
+
159
+ function smooth() {
160
+ return globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth";
161
+ }
@@ -0,0 +1,49 @@
1
+ // A peer's answer in the conversation (turn_html.js noteBubbleTemplate
2
+ // draws a note with `peer` here): a bubble from the peer, its verdict and
3
+ // summary, and chi's instruction to the model folded behind "what chi told
4
+ // the agent". It keeps what a note that opens a wake turn carries (the
5
+ // classes `bubble note` and `turn-start`, data-opening-id, the time title):
6
+ // TURN_PROMPT (bubbles.js), card_stamps.js, stage_handoff.js OPENING,
7
+ // reload_check.js and revise_stack.js (its `.note-text`, the summary) read
8
+ // it as any wake note. The ↑ to the send and "Read the full answer" are
9
+ // slots peer_links.js fills (data-peer-slot: history_shape.js leaves them
10
+ // out, so live and an offscreen reload read alike).
11
+ // Its own module: new exports go in new modules (web-frontend.md).
12
+
13
+ import { html, nothing } from "./vendor/lit-html.js";
14
+ import { fullTime } from "./format.js";
15
+
16
+ const VERDICT_CLASS = { OK: "ok", CHANGES: "changes", UNSURE: "unsure" };
17
+
18
+ // The answer's verdict pill (the note's peer.verdict, the server's word):
19
+ // "VERDICT OK" with "round closed" when the peer agreed, CHANGES, UNSURE;
20
+ // nothing for none. The phone shows the bare word (CSS).
21
+ export function verdictTemplate(peer) {
22
+ const kind = VERDICT_CLASS[peer?.verdict];
23
+ if (!kind) return nothing;
24
+ const closed = peer.agreed && peer.verdict === "OK"
25
+ ? html`<span class="peer-closed">round closed</span>` : nothing;
26
+ return html`<span class="peer-mark">${closed}<span class=${`peer-verdict ${kind}`}><span class="peer-long">VERDICT </span>${peer.verdict}</span></span>`;
27
+ }
28
+
29
+ // What the bubble says the peer answered: its summary, else the note's
30
+ // first line that says something (a quote's `> ` dropped), else "(no
31
+ // summary)". revise_stack.js labels a Revise version with it.
32
+ export function peerSummaryText(note) {
33
+ const summary = String(note?.peer?.summary ?? "").trim();
34
+ if (summary) return summary;
35
+ const line = String(note?.content ?? "").split("\n").map((l) => l.replace(/^\s*>\s?/, "").trim()).find(Boolean);
36
+ return line || "(no summary)";
37
+ }
38
+
39
+ // The bubble for +note+ (a context note with `peer`: {peer, label, re,
40
+ // summary, serial, verdict, agreed}).
41
+ export function peerNoteTemplate(note) {
42
+ const peer = note.peer || {};
43
+ const name = peer.label || peer.peer || "Your peer";
44
+ const cls = note.turn_start ? "bubble note turn-start peer-answer" : "bubble note peer-answer";
45
+ const opening = note.turn_start && note.turn_id ? String(note.turn_id) : nothing;
46
+ const source = note.context_source || (peer.peer ? `${peer.peer}-outbox` : "");
47
+ const attr = (value) => (value === null || value === undefined || value === "" ? nothing : String(value));
48
+ return html`<div class=${cls} title=${fullTime(note.at) || nothing} data-opening-id=${opening} data-peer-source=${attr(source)} data-peer-name=${attr(peer.peer)} data-peer-re=${attr(peer.re)} data-peer-serial=${attr(peer.serial)}><div class="peer-head"><span class="peer-who">${name} answered</span><span class="peer-up-slot" data-peer-slot="up"></span>${verdictTemplate(peer)}</div><div class="note-text">${peerSummaryText(note)}</div><div class="peer-foot"><span class="peer-full-slot" data-peer-slot="full"></span><details class="peer-told"><summary>what chi told the agent</summary><div class="peer-told-text">${note.content ?? ""}</div></details></div></div>`;
49
+ }
@@ -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
  }
@@ -23,7 +23,10 @@
23
23
  // from a read before its replay, reset with the session; null: none
24
24
  // stageMissing the stage's running-with-no-turn check (stage_missing.js);
25
25
  // null: no check (the render then says nothing)
26
+ // peerLinks the peer exchange's slots (peer_links.js): filled after a
27
+ // read is drawn, reset with the session; null: none
26
28
  // markdown markdown_place.js (linkTextRefs, applyFinalMarkdown)
29
+ // pictures the picture viewer (picture_viewer.js), closed with the session; null: none
27
30
  // capabilities() the page's capabilities (card.js shownElsewhere, the history's cards)
28
31
  // page: {setReviseAnchor(anchor), renderInitRow(), setMarkdownWarning(warning),
29
32
  // setCapabilities(capabilities, editorUrl, viewer), findInTurnRoots(selector), appendToHistory(el),
@@ -56,7 +59,8 @@ export function createSessionView(deps) {
56
59
  const {
57
60
  store, historyEl, getSession,
58
61
  liveTurn, turnDom, questionCards, shownTexts, objectives, featureGates, markdownTip, workingSet = null, wsPreview = null, gapClock,
59
- bubbles, cards, markdown, capabilities, page, later, cardRegistry = null, stageMissing = null,
62
+ bubbles, cards, markdown, capabilities, page, later, cardRegistry = null, stageMissing = null, peerLinks = null,
63
+ pictures = null,
60
64
  } = deps;
61
65
  const { makeUserBubble, addEndBubble, showGuardrailWarning, showRecap } = bubbles;
62
66
  const { placeSnapshotCards, upsertCard } = cards;
@@ -98,6 +102,7 @@ export function createSessionView(deps) {
98
102
  later.commandList().close();
99
103
  later.resetTurnView();
100
104
  cardRegistry?.reset();
105
+ peerLinks?.reset();
101
106
  objectives.reset();
102
107
  seedInitTasks(later.initTasks(), []);
103
108
  renderInitRow();
@@ -108,6 +113,8 @@ export function createSessionView(deps) {
108
113
  // The reader and the peek are the session's: another one (or none, the
109
114
  // start page) never finds them over #center, the composer inert under it.
110
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();
111
118
  applyPrefs();
112
119
  }
113
120
 
@@ -213,6 +220,8 @@ export function createSessionView(deps) {
213
220
  stageMissing.note(data);
214
221
  stageMissing.check();
215
222
  }
223
+ // The peer sends and answers drawn: their state, then read again.
224
+ peerLinks?.drawn();
216
225
  // The same running turn as when the page left it: what was opened, back.
217
226
  applyView(viewMemory.take(store.selected, data.current_turn?.turn_id || null), { stage: turnDom, reader: wsPreview });
218
227
  // A whole view drawn: the composer and the bar once more (the working