bom-pi 0.0.0-stage → 0.0.2

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 (131) hide show
  1. package/README.md +33 -2
  2. package/apps/README.md +7 -0
  3. package/apps/web/README.md +21 -0
  4. package/apps/web/pocket-adapter.mjs +323 -0
  5. package/apps/web/public/LICENSE.pocket +21 -0
  6. package/apps/web/public/activity-fold.js +28 -0
  7. package/apps/web/public/agent-now.js +37 -0
  8. package/apps/web/public/agent-tile.js +79 -0
  9. package/apps/web/public/app.js +975 -0
  10. package/apps/web/public/apple-touch-icon.png +0 -0
  11. package/apps/web/public/artifact-bridge.js +687 -0
  12. package/apps/web/public/avatar.js +87 -0
  13. package/apps/web/public/back.js +554 -0
  14. package/apps/web/public/box-keys.js +216 -0
  15. package/apps/web/public/browser-panel.js +1097 -0
  16. package/apps/web/public/browser.js +68 -0
  17. package/apps/web/public/calls.js +139 -0
  18. package/apps/web/public/chat.js +919 -0
  19. package/apps/web/public/clock.js +34 -0
  20. package/apps/web/public/commands.js +578 -0
  21. package/apps/web/public/composer.js +2068 -0
  22. package/apps/web/public/diff-parse.js +672 -0
  23. package/apps/web/public/diff.js +1646 -0
  24. package/apps/web/public/dock.js +299 -0
  25. package/apps/web/public/extension-ui.js +2734 -0
  26. package/apps/web/public/files-panel.js +775 -0
  27. package/apps/web/public/files.js +368 -0
  28. package/apps/web/public/fonts/FiraCode-VF.woff2 +0 -0
  29. package/apps/web/public/fonts/Geist.woff2 +0 -0
  30. package/apps/web/public/fonts/IBMPlexMono-Variable-Italic.woff2 +0 -0
  31. package/apps/web/public/fonts/IBMPlexMono-Variable.woff2 +0 -0
  32. package/apps/web/public/fonts/InterVariable-Italic.woff2 +0 -0
  33. package/apps/web/public/fonts/InterVariable.woff2 +0 -0
  34. package/apps/web/public/fonts/Iosevka-Bold.woff2 +0 -0
  35. package/apps/web/public/fonts/Iosevka-BoldItalic.woff2 +0 -0
  36. package/apps/web/public/fonts/Iosevka-Italic.woff2 +0 -0
  37. package/apps/web/public/fonts/Iosevka-Regular.woff2 +0 -0
  38. package/apps/web/public/fonts/Iosevka-SemiBold.woff2 +0 -0
  39. package/apps/web/public/fonts/Iosevka-SemiBoldItalic.woff2 +0 -0
  40. package/apps/web/public/fonts/JetBrainsMono-Italic.woff2 +0 -0
  41. package/apps/web/public/fonts/JetBrainsMono.woff2 +0 -0
  42. package/apps/web/public/fonts/NerdFontsSymbolsMono.woff2 +0 -0
  43. package/apps/web/public/fonts/SOURCES.md +69 -0
  44. package/apps/web/public/gestures.js +610 -0
  45. package/apps/web/public/highlight.js +480 -0
  46. package/apps/web/public/history.js +70 -0
  47. package/apps/web/public/home.js +169 -0
  48. package/apps/web/public/icon-192.png +0 -0
  49. package/apps/web/public/icon-512.png +0 -0
  50. package/apps/web/public/icon-maskable-512.png +0 -0
  51. package/apps/web/public/icon.svg +16 -0
  52. package/apps/web/public/index.html +71 -0
  53. package/apps/web/public/launcher.js +1293 -0
  54. package/apps/web/public/linked-sessions.js +55 -0
  55. package/apps/web/public/live.js +39 -0
  56. package/apps/web/public/manifest.webmanifest +32 -0
  57. package/apps/web/public/model-refresh.js +73 -0
  58. package/apps/web/public/notify.js +251 -0
  59. package/apps/web/public/peeks.js +920 -0
  60. package/apps/web/public/pip-attachments.js +182 -0
  61. package/apps/web/public/pip-window.js +141 -0
  62. package/apps/web/public/pip.js +1217 -0
  63. package/apps/web/public/quote-reply.js +109 -0
  64. package/apps/web/public/quote-text.js +31 -0
  65. package/apps/web/public/rich.js +403 -0
  66. package/apps/web/public/run-frame.js +106 -0
  67. package/apps/web/public/safe-mode.js +71 -0
  68. package/apps/web/public/seen.js +169 -0
  69. package/apps/web/public/session-tree.js +117 -0
  70. package/apps/web/public/sessions.js +2695 -0
  71. package/apps/web/public/share.js +126 -0
  72. package/apps/web/public/sheets/appearance.js +820 -0
  73. package/apps/web/public/sheets/branch.js +353 -0
  74. package/apps/web/public/sheets/extensions.js +818 -0
  75. package/apps/web/public/sheets/file.js +318 -0
  76. package/apps/web/public/sheets/find.js +250 -0
  77. package/apps/web/public/sheets/folder.js +680 -0
  78. package/apps/web/public/sheets/gallery.js +2340 -0
  79. package/apps/web/public/sheets/hooks.js +350 -0
  80. package/apps/web/public/sheets/memory.js +531 -0
  81. package/apps/web/public/sheets/menu.js +580 -0
  82. package/apps/web/public/sheets/message.js +220 -0
  83. package/apps/web/public/sheets/model.js +412 -0
  84. package/apps/web/public/sheets/people.js +414 -0
  85. package/apps/web/public/sheets/pi-sessions.js +264 -0
  86. package/apps/web/public/sheets/providers.js +525 -0
  87. package/apps/web/public/sheets/running.js +130 -0
  88. package/apps/web/public/sheets/schedules.js +71 -0
  89. package/apps/web/public/sheets/session.js +249 -0
  90. package/apps/web/public/sheets/shortcuts.js +101 -0
  91. package/apps/web/public/sheets/spend.js +150 -0
  92. package/apps/web/public/sheets/text.js +53 -0
  93. package/apps/web/public/sheets/viewers.js +363 -0
  94. package/apps/web/public/sheets/worktree.js +50 -0
  95. package/apps/web/public/sheets.js +410 -0
  96. package/apps/web/public/signin.js +57 -0
  97. package/apps/web/public/slots.js +208 -0
  98. package/apps/web/public/store.js +1760 -0
  99. package/apps/web/public/style.css +18625 -0
  100. package/apps/web/public/subagents-board.js +879 -0
  101. package/apps/web/public/subagents.js +273 -0
  102. package/apps/web/public/sw.js +169 -0
  103. package/apps/web/public/taps.js +26 -0
  104. package/apps/web/public/theme-surface.d.ts +4 -0
  105. package/apps/web/public/theme-surface.js +266 -0
  106. package/apps/web/public/theme.js +845 -0
  107. package/apps/web/public/themes/lantern/colors.toml +25 -0
  108. package/apps/web/public/themes/lantern/direction.css +60 -0
  109. package/apps/web/public/themes/lantern/frame.css +254 -0
  110. package/apps/web/public/themes/lantern/theme.css +10 -0
  111. package/apps/web/public/themes/lantern/theme.json +7 -0
  112. package/apps/web/public/themes/pocket/theme.css +189 -0
  113. package/apps/web/public/themes/pocket/theme.json +6 -0
  114. package/apps/web/public/themes.js +556 -0
  115. package/apps/web/public/transcript.js +3348 -0
  116. package/apps/web/public/trust.js +295 -0
  117. package/apps/web/public/turns.js +507 -0
  118. package/apps/web/public/ui.js +1910 -0
  119. package/apps/web/public/voice.js +345 -0
  120. package/apps/web/server.mjs +774 -0
  121. package/package.json +43 -4
  122. package/packages/cli/src/bom-pi.mjs +452 -0
  123. package/packages/cli/templates/blank.factory.json +7 -0
  124. package/packages/cli/templates/dev.factory.json +11 -0
  125. package/packages/cli/templates/docs.factory.json +12 -0
  126. package/packages/cli/templates/ops.factory.json +14 -0
  127. package/packages/cli/templates/triage.factory.json +10 -0
  128. package/packages/core/src/daemon.mjs +2047 -0
  129. package/packages/core/src/limit-gate.mjs +192 -0
  130. package/packages/core/src/rpc-client.mjs +66 -0
  131. package/systemd/README.md +11 -0
@@ -0,0 +1,109 @@
1
+ import { useEffect, useState } from "preact/hooks";
2
+ import { quoteReply } from "./store.js";
3
+ import { html, Icon } from "./ui.js";
4
+
5
+ const coarse = matchMedia("(pointer: coarse)").matches;
6
+ const WIDTH = 92;
7
+ const HEIGHT = 36;
8
+
9
+ function selected() {
10
+ const selection = getSelection();
11
+
12
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) {
13
+ return null;
14
+ }
15
+
16
+ const range = selection.getRangeAt(0);
17
+ const within = (node) => (node.nodeType === 1 ? node : node.parentElement)?.closest(".reply");
18
+ // A triple-click can end the range at the start of the next block: that end does not count.
19
+ const end =
20
+ range.endOffset === 0 && range.endContainer !== range.startContainer
21
+ ? range.commonAncestorContainer
22
+ : range.endContainer;
23
+ const from = within(range.startContainer);
24
+ const to = within(end) ?? (within(range.commonAncestorContainer) ? from : null);
25
+ const text = selection.toString().trim();
26
+
27
+ // Whoever cannot write to Pi has no message box to put the quote in.
28
+ if (
29
+ !from ||
30
+ from !== to ||
31
+ text === "" ||
32
+ !document.querySelector('[data-part="composer"] textarea')
33
+ ) {
34
+ return null;
35
+ }
36
+
37
+ const rects = [...range.getClientRects()].filter((rect) => rect.width > 0);
38
+
39
+ if (rects.length === 0) {
40
+ return null;
41
+ }
42
+
43
+ const first = rects[0];
44
+ const last = rects[rects.length - 1];
45
+ const below = coarse || first.top < HEIGHT + 12;
46
+ const top = below ? last.bottom + 10 : first.top - HEIGHT - 8;
47
+ const anchor = below ? last.right : first.left;
48
+ const left = Math.max(8, Math.min(anchor - (below ? WIDTH : 0), innerWidth - WIDTH - 8));
49
+
50
+ if (top < 0 || top > (visualViewport?.height ?? innerHeight) - HEIGHT) {
51
+ return null;
52
+ }
53
+
54
+ return { text, top, left };
55
+ }
56
+
57
+ export function QuoteReplyButton() {
58
+ const [at, setAt] = useState(null);
59
+
60
+ useEffect(() => {
61
+ let timer = 0;
62
+
63
+ const look = () => {
64
+ clearTimeout(timer);
65
+ // Dragging a handle changes the selection all the time: show the button once it holds still.
66
+ timer = setTimeout(() => setAt(selected()), 160);
67
+ };
68
+
69
+ document.addEventListener("selectionchange", look);
70
+ addEventListener("scroll", look, true);
71
+ addEventListener("resize", look);
72
+
73
+ return () => {
74
+ clearTimeout(timer);
75
+ document.removeEventListener("selectionchange", look);
76
+ removeEventListener("scroll", look, true);
77
+ removeEventListener("resize", look);
78
+ };
79
+ }, []);
80
+
81
+ if (!at) {
82
+ return null;
83
+ }
84
+
85
+ const reply = () => {
86
+ quoteReply(at.text);
87
+ getSelection()?.removeAllRanges();
88
+ setAt(null);
89
+
90
+ if (!coarse) {
91
+ requestAnimationFrame(() =>
92
+ document.querySelector('[data-part="composer"] textarea')?.focus(),
93
+ );
94
+ }
95
+ };
96
+
97
+ // Pressing the button must not take the selection away before the click reads it.
98
+ return html`<button
99
+ class="quote-reply-button"
100
+ data-part="quote-reply-button"
101
+ style=${`top:${at.top}px;left:${at.left}px`}
102
+ onPointerDown=${(event) => event.preventDefault()}
103
+ onMouseDown=${(event) => event.preventDefault()}
104
+ onClick=${reply}
105
+ >
106
+ <${Icon} name="reply" size=${14} stroke=${2} />
107
+ <span>Reply</span>
108
+ </button>`;
109
+ }
@@ -0,0 +1,31 @@
1
+ export const QUOTE_MAX = 1500;
2
+
3
+ function quoteLines(passage) {
4
+ const text = passage.trim().replace(/\r\n?/g, "\n");
5
+ const cut = text.length > QUOTE_MAX ? `${text.slice(0, QUOTE_MAX).trimEnd()}…` : text;
6
+
7
+ return cut
8
+ .split("\n")
9
+ .map((line) => (line === "" ? ">" : `> ${line}`))
10
+ .join("\n");
11
+ }
12
+
13
+ export function withQuote(passage, reply) {
14
+ return passage ? `${quoteLines(passage)}\n\n${reply}`.trimEnd() : reply;
15
+ }
16
+
17
+ export function splitQuote(text) {
18
+ const match = /^((?:>[^\n]*(?:\n|$))+)\n*([\s\S]*)$/.exec(text);
19
+
20
+ if (!match) {
21
+ return null;
22
+ }
23
+
24
+ const passage = match[1]
25
+ .replace(/\n$/, "")
26
+ .split("\n")
27
+ .map((line) => line.replace(/^> ?/, ""))
28
+ .join("\n");
29
+
30
+ return { passage, rest: match[2] };
31
+ }
@@ -0,0 +1,403 @@
1
+ // Code blocks in replies that show more than code: an HTML page previewed (and run, on a tap), an SVG image, a diff
2
+ // in the diff viewer. ui.js draws every code block as code; this module gives `Markdown` the component for these when
3
+ // it loads (`setRichBlock`), so ui.js does not import it.
4
+
5
+ import { useEffect, useMemo, useRef, useState } from "preact/hooks";
6
+ import { DiffBlock } from "./diff.js";
7
+ import { highlight, langOf } from "./highlight.js";
8
+ import { RunFrame, useFitHeight } from "./run-frame.js";
9
+ import { notify, openSheet } from "./store.js";
10
+ import { COLOR_LIMIT, copyText, html, setRichBlock } from "./ui.js";
11
+
12
+ // ─── A page, previewed ──────────────────────────────────────────────────────────────
13
+
14
+ /**
15
+ * What a preview may load: nothing from anywhere, only styles and images written into the page. The frame inherits the
16
+ * app's policy too; this narrows it further, so a page cannot even load the app's own addresses.
17
+ */
18
+ const PREVIEW_POLICY =
19
+ "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; media-src data:";
20
+ /** A fragment of HTML gets a plain page around it: readable type on white, as a browser would show it. */
21
+ const FRAGMENT_STYLE =
22
+ "body{margin:12px;font:15px/1.5 system-ui,-apple-system,'Segoe UI',sans-serif;color:#1f2328;background:#fff}";
23
+ const MIN_HEIGHT = 40;
24
+ const MAX_HEIGHT = 1200;
25
+
26
+ /**
27
+ * The page a preview shows, always in standards mode (a page written without a doctype would otherwise lay out in
28
+ * quirks mode). Parsed without running or loading anything, it loses what could run, reach out, or move it elsewhere
29
+ * before a tap: scripts and event handlers, frames and embeds, refreshes and other `http-equiv` meta, links
30
+ * (stylesheets, prefetches), and bases; then the preview's policy goes first in its head. The sandbox and the policy
31
+ * would stop them all as well. A fragment gets a plain page around it.
32
+ */
33
+ export function previewDocument(source) {
34
+ const fragment = !/<(?:!doctype|html|head|body)[\s>]/i.test(source);
35
+ const page = new DOMParser().parseFromString(source, "text/html");
36
+
37
+ for (const node of page.querySelectorAll(
38
+ "script, iframe, frame, object, embed, meta[http-equiv], link, base",
39
+ )) {
40
+ node.remove();
41
+ }
42
+
43
+ for (const element of page.querySelectorAll("*")) {
44
+ for (const { name } of [...element.attributes]) {
45
+ if (/^on/i.test(name)) {
46
+ element.removeAttribute(name);
47
+ }
48
+ }
49
+ }
50
+
51
+ const meta = (name, value) => {
52
+ const element = page.createElement("meta");
53
+
54
+ element.httpEquiv = name;
55
+ element.content = value;
56
+
57
+ return element;
58
+ };
59
+
60
+ const charset = page.createElement("meta");
61
+
62
+ charset.setAttribute("charset", "utf-8");
63
+ page.head.prepend(
64
+ charset,
65
+ meta("Content-Security-Policy", PREVIEW_POLICY),
66
+ meta("x-dns-prefetch-control", "off"),
67
+ );
68
+
69
+ if (fragment) {
70
+ const style = page.createElement("style");
71
+
72
+ style.textContent = FRAGMENT_STYLE;
73
+ page.head.append(style);
74
+ }
75
+
76
+ return `<!doctype html>${page.documentElement.outerHTML}`;
77
+ }
78
+
79
+ /**
80
+ * HTML drawn as a page, with its scripts off: a frame of its own, without `allow-scripts`, so nothing in it runs, and
81
+ * same-origin only so the app can measure it and fit the frame to it. Tap Run (`RunFrame`) for its scripts.
82
+ */
83
+ export function HtmlPreview({ source, title = "Preview" }) {
84
+ const ref = useRef(null);
85
+ const [height, fitHeight, resetFit] = useFitHeight(MIN_HEIGHT * 3, MIN_HEIGHT, MAX_HEIGHT);
86
+ const page = useMemo(() => previewDocument(source), [source]);
87
+
88
+ // The page's content (the bottom of its last box, which `100vh` alone does not push down), its body's padding and
89
+ // margin, and the frame's own border.
90
+ const fit = () => {
91
+ const frame = ref.current;
92
+ const body = frame?.contentDocument?.body;
93
+
94
+ if (!body) {
95
+ return;
96
+ }
97
+
98
+ const shown = frame.contentDocument;
99
+ const style = getComputedStyle(body);
100
+ // Everything in the body, text outside any element included, and each box (for those placed out of the flow).
101
+ const range = shown.createRange();
102
+
103
+ range.selectNodeContents(body);
104
+ const bottom = Math.max(
105
+ range.getBoundingClientRect().bottom,
106
+ ...[...body.children].map((each) => each.getBoundingClientRect().bottom),
107
+ );
108
+ const fills = body.getBoundingClientRect().height >= frame.clientHeight - 1;
109
+ const tail =
110
+ parseFloat(style.paddingBottom) +
111
+ parseFloat(style.borderBottomWidth) +
112
+ parseFloat(style.marginBottom);
113
+ // The body's own height counts too, unless it is only as tall as its frame: the line box under an inline image
114
+ // or SVG reaches a few pixels below the last box.
115
+ const content = Math.max(
116
+ bottom + shown.documentElement.scrollTop + tail,
117
+ fills
118
+ ? 0
119
+ : body.getBoundingClientRect().bottom +
120
+ shown.documentElement.scrollTop +
121
+ parseFloat(style.marginBottom),
122
+ );
123
+
124
+ fitHeight(content + (frame.offsetHeight - frame.clientHeight), fills);
125
+ };
126
+
127
+ // A narrower frame makes a taller page.
128
+ useEffect(() => {
129
+ const observer = new ResizeObserver(() => fit());
130
+
131
+ observer.observe(ref.current);
132
+
133
+ return () => observer.disconnect();
134
+ }, []);
135
+
136
+ return html`<iframe
137
+ class="html-preview"
138
+ ref=${ref}
139
+ sandbox="allow-same-origin"
140
+ srcdoc=${page}
141
+ title=${title}
142
+ style=${`height:${height}px`}
143
+ onLoad=${() => {
144
+ resetFit();
145
+ fit();
146
+ }}
147
+ ></iframe>`;
148
+ }
149
+
150
+ // ─── Blocks ───────────────────────────────────────────────────────────────────────
151
+
152
+ const VIEW_NAMES = { html: "Preview", svg: "Image", diff: "Diff" };
153
+
154
+ /** An SVG as an image: as an image, it runs no scripts and loads nothing. Tap it to see it full screen. */
155
+ function SvgImage({ source }) {
156
+ const [broken, setBroken] = useState(false);
157
+
158
+ if (broken) {
159
+ return html`<p class="muted small rich-note">This SVG could not be drawn.</p>`;
160
+ }
161
+
162
+ return html`<img
163
+ class="rich-svg"
164
+ alt="SVG image"
165
+ src=${`data:image/svg+xml;charset=utf-8,${encodeURIComponent(source)}`}
166
+ onError=${() => setBroken(true)}
167
+ />`;
168
+ }
169
+
170
+ /**
171
+ * A code block that shows more than code: what it draws (a page, an image, a diff) with its code a tab away. While
172
+ * the reply is still being written it shows the code, as the page or diff is not whole yet. A page's scripts run only
173
+ * on a tap of Run, in the artifacts' sandbox. `artifact` (`{ id, title, version }`) makes it an artifact's card in the
174
+ * reply (`InlineArtifact`): named by the artifact and its version, with a button for the viewer, and its page, once run,
175
+ * gets the artifact's saved state as the viewer gives it.
176
+ */
177
+ function RichBlock({ kind, lang, source, streaming, artifact = null }) {
178
+ const [view, setView] = useState("shown");
179
+ const [running, setRunning] = useState(false);
180
+ const code = streaming || view === "code";
181
+ const colored = useMemo(
182
+ () =>
183
+ code && source.length <= COLOR_LIMIT ? highlight(source, langOf(lang) ?? kind) : null,
184
+ [code, source, lang, kind],
185
+ );
186
+
187
+ // A new version of the page stops the old one running.
188
+ useEffect(() => setRunning(false), [source]);
189
+
190
+ const copy = () =>
191
+ copyText(source).then(
192
+ () => notify("info", "Copied."),
193
+ () => notify("error", "Could not copy."),
194
+ );
195
+
196
+ let body;
197
+
198
+ if (code) {
199
+ body =
200
+ colored === null
201
+ ? html`<pre><code>${source}</code></pre>`
202
+ : html`<pre><code dangerouslySetInnerHTML=${{ __html: colored }}></code></pre>`;
203
+ } else if (kind === "html") {
204
+ body = running
205
+ ? html`<${RunFrame}
206
+ source=${source}
207
+ artifact=${artifact?.id ?? null}
208
+ from=${artifact ? `the artifact “${artifact.title}”` : undefined}
209
+ />`
210
+ : html`<${HtmlPreview} source=${source} />`;
211
+ } else if (kind === "svg") {
212
+ body = html`<${SvgImage} source=${source} />`;
213
+ } else {
214
+ body = html`<${DiffBlock} text=${source} />`;
215
+ }
216
+
217
+ return html`<div class=${`code rich ${kind} ${artifact ? "inline-artifact" : ""}`}>
218
+ <div class="code-head">
219
+ <span class="code-lang">
220
+ ${artifact ? `${artifact.title} · v${artifact.version}` : lang || kind}
221
+ </span>
222
+ ${
223
+ !streaming &&
224
+ html`<span class="rich-tabs" role="tablist">
225
+ <button
226
+ type="button"
227
+ role="tab"
228
+ aria-selected=${view === "shown" ? "true" : "false"}
229
+ class=${view === "shown" ? "on" : ""}
230
+ onClick=${() => setView("shown")}
231
+ >
232
+ ${VIEW_NAMES[kind]}
233
+ </button>
234
+ <button
235
+ type="button"
236
+ role="tab"
237
+ aria-selected=${view === "code" ? "true" : "false"}
238
+ class=${view === "code" ? "on" : ""}
239
+ onClick=${() => setView("code")}
240
+ >
241
+ Code
242
+ </button>
243
+ </span>`
244
+ }
245
+ <span class="grow"></span>
246
+ ${
247
+ kind === "html" &&
248
+ !code &&
249
+ html`<button
250
+ type="button"
251
+ class=${`rich-run ${running ? "on" : ""}`}
252
+ title=${running ? "Stop its scripts" : "Run its scripts in a sandbox, as an artifact runs: it can reach the internet, not the app"}
253
+ onClick=${() => setRunning(!running)}
254
+ >
255
+ ${running ? "■ Stop" : "▶ Run"}
256
+ </button>`
257
+ }
258
+ ${
259
+ artifact &&
260
+ html`<button
261
+ type="button"
262
+ class="copy"
263
+ title="Open it in the artifact viewer, at this version"
264
+ onClick=${() => openSheet({ type: "viewer", id: artifact.id, version: artifact.version })}
265
+ >
266
+ Open
267
+ </button>`
268
+ }
269
+ <button type="button" class="copy" onClick=${copy}>Copy</button>
270
+ </div>
271
+ ${body}
272
+ </div>`;
273
+ }
274
+
275
+ setRichBlock(RichBlock);
276
+
277
+ // ─── An artifact in the reply ───────────────────────────────────────────────────────
278
+
279
+ /**
280
+ * The pages fetched for cards, by address: a version never changes, so one is fetched once. Least recently used first
281
+ * out, so a long session does not hold every page: each is `{ page, text }`, the text once it came.
282
+ */
283
+ const pages = new Map();
284
+ const PAGES_KEPT = 20;
285
+ const addressOf = (conversationId, id, version) =>
286
+ `/a/${conversationId}/${encodeURIComponent(id)}/${version}`;
287
+
288
+ /** The entry for an address, now the most recently used, or undefined. */
289
+ function recent(address) {
290
+ const entry = pages.get(address);
291
+
292
+ if (entry !== undefined) {
293
+ pages.delete(address);
294
+ pages.set(address, entry);
295
+ }
296
+
297
+ return entry;
298
+ }
299
+
300
+ function pageOf(conversationId, id, version) {
301
+ const address = addressOf(conversationId, id, version);
302
+ let entry = recent(address);
303
+
304
+ if (entry === undefined) {
305
+ entry = { page: null, text: null };
306
+ entry.page = fetch(address, { credentials: "same-origin" }).then((response) => {
307
+ if (!response.ok) {
308
+ throw new Error(`HTTP ${response.status}`);
309
+ }
310
+
311
+ return response.text();
312
+ });
313
+ pages.set(address, entry);
314
+
315
+ const mine = entry;
316
+
317
+ // Into the entry, which may be gone by then (evicted): nothing is put back in the map.
318
+ mine.page.then(
319
+ (text) => {
320
+ mine.text = text;
321
+ },
322
+ // A page that did not come may on the next try.
323
+ () => {
324
+ if (pages.get(address) === mine) {
325
+ pages.delete(address);
326
+ }
327
+ },
328
+ );
329
+
330
+ if (pages.size > PAGES_KEPT) {
331
+ pages.delete(pages.keys().next().value);
332
+ }
333
+ }
334
+
335
+ return entry.page;
336
+ }
337
+
338
+ /**
339
+ * What `artifact_inline` published, as a card in the reply: the version its call made, with Preview/Code, Run/Stop, and
340
+ * the viewer a tap away. The page comes from the artifact's own address, as the viewer's does, so whoever may see the
341
+ * session may see the card; later versions never change it. Until it comes the card says so.
342
+ */
343
+ export function InlineArtifact({ conversationId, id, title, version }) {
344
+ const [page, setPage] = useState({
345
+ source: recent(addressOf(conversationId, id, version))?.text ?? null,
346
+ failed: false,
347
+ });
348
+
349
+ useEffect(() => {
350
+ let current = true;
351
+
352
+ setPage({
353
+ source: recent(addressOf(conversationId, id, version))?.text ?? null,
354
+ failed: false,
355
+ });
356
+ pageOf(conversationId, id, version).then(
357
+ (source) => current && setPage({ source, failed: false }),
358
+ () => current && setPage({ source: null, failed: true }),
359
+ );
360
+
361
+ return () => {
362
+ current = false;
363
+ };
364
+ }, [conversationId, id, version]);
365
+
366
+ const artifact = { id, title, version };
367
+
368
+ if (page.source !== null) {
369
+ return html`<${RichBlock} kind="html" source=${page.source} artifact=${artifact} />`;
370
+ }
371
+
372
+ return html`<div class="code rich html inline-artifact">
373
+ <div class="code-head">
374
+ <span class="code-lang">${title} · v${version}</span>
375
+ <span class="grow"></span>
376
+ <button
377
+ type="button"
378
+ class="copy"
379
+ onClick=${() => openSheet({ type: "viewer", id, version })}
380
+ >
381
+ Open
382
+ </button>
383
+ </div>
384
+ <p class="muted small rich-note">
385
+ ${page.failed ? "This version could not be loaded." : "Loading…"}
386
+ </p>
387
+ </div>`;
388
+ }
389
+
390
+ // ─── Code elsewhere ────────────────────────────────────────────────────────────────────
391
+
392
+ /** Code with syntax colors for `lang` (a language, or a path to tell it by), as a `pre` with the class given. */
393
+ export function Highlighted({ text, lang, class: className = "" }) {
394
+ const language = langOf(lang ?? "");
395
+ const colored = useMemo(
396
+ () => (language && text.length <= COLOR_LIMIT ? highlight(text, language) : null),
397
+ [text, language],
398
+ );
399
+
400
+ return colored === null
401
+ ? html`<pre class=${className}>${text}</pre>`
402
+ : html`<pre class=${className} dangerouslySetInnerHTML=${{ __html: colored }}></pre>`;
403
+ }
@@ -0,0 +1,106 @@
1
+ // HTML from a reply, run: in the server's sandboxed frame page (`/a/frame`), only once someone taps Run. The frame has
2
+ // an opaque origin, as artifacts do: it can run scripts and reach the network, never the app or its cookies.
3
+ import { useLayoutEffect, useRef, useState } from "preact/hooks";
4
+ import { useArtifactBridge } from "./artifact-bridge.js";
5
+ import { html } from "./ui.js";
6
+
7
+ /**
8
+ * The sandbox's permissions: those of the artifact viewer's frame (`sheets/viewers.js`). A frame gets only what both this
9
+ * and its page's own policy allow, so without `allow-popups-to-escape-sandbox` here its popups stay sandboxed.
10
+ */
11
+ const SANDBOX =
12
+ "allow-scripts allow-forms allow-modals allow-popups allow-pointer-lock allow-downloads";
13
+ /** How tall a frame may grow to fit its page: past it, the page scrolls inside. */
14
+ const MAX_HEIGHT = 900;
15
+ const MIN_HEIGHT = 48;
16
+
17
+ /**
18
+ * The height that fits a page in a frame, from what it says it needs now. A page sized by its frame (`100vh`) asks
19
+ * for a little more each time it gets it: a second step up by the same amount is that, not the page, so it stays.
20
+ */
21
+ export function useFitHeight(initial, min, max) {
22
+ const [height, setHeight] = useState(initial);
23
+ const step = useRef(0);
24
+
25
+ const fit = (wanted, fills) =>
26
+ setHeight((current) => {
27
+ const next = Math.max(min, Math.min(max, Math.ceil(wanted)));
28
+ const grown = next - current;
29
+
30
+ // Only a page as tall as its frame grows with it: one that grows by equal steps otherwise (a list adding
31
+ // rows) is growing for real.
32
+ if (fills && grown > 0 && grown === step.current) {
33
+ return current;
34
+ }
35
+
36
+ step.current = Math.max(0, grown);
37
+
38
+ return next;
39
+ });
40
+
41
+ const reset = () => {
42
+ step.current = 0;
43
+ };
44
+
45
+ return [height, fit, reset];
46
+ }
47
+
48
+ /**
49
+ * A frame running `source`, as the artifact `artifact` when it is one. The frame page says when it is ready; then it
50
+ * gets the HTML and reports its height, and the frame fits it. Messages count only from this frame's own window, and a
51
+ * height only when it is a sane number.
52
+ */
53
+ export function RunFrame({
54
+ source,
55
+ title = "Preview",
56
+ from = "the page in Pi's reply",
57
+ artifact = null,
58
+ }) {
59
+ const ref = useRef(null);
60
+ const [height, fitHeight, resetFit] = useFitHeight(240, MIN_HEIGHT, MAX_HEIGHT);
61
+
62
+ // It may offer a follow-up for the message box, as an artifact may; `from` names it there. It keeps state only as
63
+ // an artifact (`artifact`, its id): a reply's HTML has none. Its frame page opens the line to the app, and the HTML
64
+ // it writes in keeps it (`ARTIFACT_BRIDGE`, `src/server/http/artifacts.ts`).
65
+ useArtifactBridge(ref, { artifact, source: from });
66
+
67
+ // Listening from the moment the frame is in the page, before it can load: it says it is ready only once.
68
+ useLayoutEffect(() => {
69
+ const onMessage = (event) => {
70
+ const frame = ref.current;
71
+ const data = event.data;
72
+
73
+ if (!frame || event.source !== frame.contentWindow || typeof data !== "object") {
74
+ return;
75
+ }
76
+
77
+ if (data?.type === "pocket-run-ready") {
78
+ resetFit();
79
+ // The frame's origin is opaque, so no address can be named: it is this frame's window either way.
80
+ frame.contentWindow.postMessage({ type: "pocket-run", html: source }, "*");
81
+ } else if (data?.type === "pocket-run-size" && Number.isFinite(data.height)) {
82
+ // The page's height, and the frame's own border around it.
83
+ fitHeight(
84
+ data.height + (frame.offsetHeight - frame.clientHeight),
85
+ data.fills === true,
86
+ );
87
+ }
88
+ };
89
+
90
+ addEventListener("message", onMessage);
91
+
92
+ return () => removeEventListener("message", onMessage);
93
+ }, [source]);
94
+
95
+ return html`<iframe
96
+ class="run-frame"
97
+ ref=${ref}
98
+ key=${source}
99
+ src="/a/frame"
100
+ sandbox=${SANDBOX}
101
+ allow="fullscreen; clipboard-write"
102
+ referrerpolicy="no-referrer"
103
+ title=${title}
104
+ style=${`height:${height}px`}
105
+ ></iframe>`;
106
+ }