@open-artifact/server-sdk 0.0.0-stage → 0.1.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.
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/bin/frame-host.d.ts +2 -0
- package/bin/frame-host.js +29 -0
- package/package.json +71 -4
- package/src/daemon.d.ts +65 -0
- package/src/daemon.js +157 -0
- package/src/frame/client/comments.css +1 -0
- package/src/frame/client/comments.js +57 -0
- package/src/frame/client/runtime.js +995 -0
- package/src/frame/client/shell.css +45 -0
- package/src/frame/client/shell.html +29 -0
- package/src/frame/client/shell.js +990 -0
- package/src/frame/comments.d.ts +87 -0
- package/src/frame/comments.js +228 -0
- package/src/frame/db.d.ts +149 -0
- package/src/frame/db.js +573 -0
- package/src/frame/declaration.d.ts +24 -0
- package/src/frame/declaration.js +65 -0
- package/src/frame/files.d.ts +107 -0
- package/src/frame/files.js +348 -0
- package/src/frame/index.d.ts +138 -0
- package/src/frame/index.js +1075 -0
- package/src/frame/wire.d.ts +182 -0
- package/src/frame/wire.js +21 -0
- package/src/index.d.ts +15 -0
- package/src/index.js +15 -0
- package/src/lan.d.ts +74 -0
- package/src/lan.js +201 -0
- package/src/serve.d.ts +360 -0
- package/src/serve.js +771 -0
- package/src/ws.d.ts +46 -0
- package/src/ws.js +182 -0
|
@@ -0,0 +1,990 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
(() => {
|
|
3
|
+
// packages/server-sdk/src/frame/client/shell.ts
|
|
4
|
+
(() => {
|
|
5
|
+
"use strict";
|
|
6
|
+
const $ = (id) => document.getElementById(id);
|
|
7
|
+
const params = new URLSearchParams(location.search);
|
|
8
|
+
const LOCAL_ORIGIN = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\]):\d{1,5}$/;
|
|
9
|
+
const outerOrigin = LOCAL_ORIGIN.test(params.get("open_artifact_shell") || "") ? params.get("open_artifact_shell") : null;
|
|
10
|
+
const outer = outerOrigin && window.parent !== window ? window.parent : null;
|
|
11
|
+
const client = randomId(16);
|
|
12
|
+
const api = (name) => new URL(`api/frame/${name}`, location.href).href;
|
|
13
|
+
const CHROME_PROTOCOL = 1;
|
|
14
|
+
const STALE_MESSAGE = "not run: the artifact was updated";
|
|
15
|
+
const UNDECLARED_MESSAGE = "the version this view runs does not declare it";
|
|
16
|
+
const DEFAULT_CAP_BUDGETS = { mcp: { callTool: 13e4 }, sample: { sample: 33e4 }, endpoints: { fetch: 13e4 }, assets: { upload: 27e4 } };
|
|
17
|
+
const ACKED = /* @__PURE__ */ new Set(["assets.upload", "comments.sendToAgent", "room.sendToAgentSession", "artifact.publish"]);
|
|
18
|
+
let session = null;
|
|
19
|
+
let frame = null;
|
|
20
|
+
let pageWin = null;
|
|
21
|
+
let contentOrigin = "";
|
|
22
|
+
let ver = "";
|
|
23
|
+
let gen = 1;
|
|
24
|
+
let ready = false;
|
|
25
|
+
let readyTimer = null;
|
|
26
|
+
let revealHeld = false;
|
|
27
|
+
let revealed = false;
|
|
28
|
+
let connected = false;
|
|
29
|
+
const subs = /* @__PURE__ */ new Map();
|
|
30
|
+
const rerun = /* @__PURE__ */ new Set();
|
|
31
|
+
let rerunTimer = null;
|
|
32
|
+
function randomId(n) {
|
|
33
|
+
const a = new Uint8Array(n);
|
|
34
|
+
crypto.getRandomValues(a);
|
|
35
|
+
return Array.from(a, (b) => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[b % 62]).join("");
|
|
36
|
+
}
|
|
37
|
+
async function post(name, body) {
|
|
38
|
+
const r = await fetch(api(name), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), credentials: "same-origin" });
|
|
39
|
+
const out = await r.json().catch(() => ({ error: { code: "upstream_error", message: `HTTP ${r.status}` } }));
|
|
40
|
+
if (!r.ok && !out.error) out.error = { code: "upstream_error", message: `HTTP ${r.status}` };
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
async function cap(capName, method, arg) {
|
|
44
|
+
const out = await post("cap", { cap: capName, method, args: [arg], client, brokerGen: gen });
|
|
45
|
+
if (out.error) throw out.error;
|
|
46
|
+
return out.result;
|
|
47
|
+
}
|
|
48
|
+
let backoff = 500;
|
|
49
|
+
function openStream() {
|
|
50
|
+
const u = new URL(api(`events?c=${client}`));
|
|
51
|
+
u.protocol = location.protocol === "https:" ? "wss:" : "ws:";
|
|
52
|
+
let ws;
|
|
53
|
+
try {
|
|
54
|
+
ws = new WebSocket(u.href, "baoyu-sse");
|
|
55
|
+
} catch {
|
|
56
|
+
setTimeout(openStream, backoff);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
ws.onmessage = (ev) => {
|
|
60
|
+
let m;
|
|
61
|
+
try {
|
|
62
|
+
m = JSON.parse(String(ev.data));
|
|
63
|
+
} catch {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
onEvent(m);
|
|
67
|
+
};
|
|
68
|
+
ws.onopen = () => {
|
|
69
|
+
backoff = 500;
|
|
70
|
+
};
|
|
71
|
+
ws.onclose = () => {
|
|
72
|
+
if (connected) {
|
|
73
|
+
connected = false;
|
|
74
|
+
toPage({ __frame_room_ev: true, kind: "connection", connected: false });
|
|
75
|
+
}
|
|
76
|
+
setTimeout(openStream, backoff);
|
|
77
|
+
backoff = Math.min(backoff * 2, 1e4);
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
function onEvent(m) {
|
|
81
|
+
if (m.t === "hello") {
|
|
82
|
+
connected = true;
|
|
83
|
+
toPage({ __frame_room_ev: true, kind: "connection", connected: true });
|
|
84
|
+
toPage({ __frame_room_ev: true, kind: "peers", peers: m.peers || [] });
|
|
85
|
+
for (const id of subs.keys()) rerun.add(id);
|
|
86
|
+
scheduleRerun();
|
|
87
|
+
void refreshThreads();
|
|
88
|
+
if (typeof m.brokerGen === "number" && m.brokerGen !== gen) void rewired({ t: "rewired", brokerGen: m.brokerGen, caps: session?.grants ?? [], reason: "type" });
|
|
89
|
+
else if (m.ver && ver && m.ver !== ver) reloadPage(m.ver);
|
|
90
|
+
} else if (m.t === "db") {
|
|
91
|
+
const paths = Array.isArray(m.paths) ? m.paths : [];
|
|
92
|
+
for (const [id, s] of subs) if (!paths.length || paths.some((p) => touches(s, p))) rerun.add(id);
|
|
93
|
+
scheduleRerun();
|
|
94
|
+
} else if (m.t === "room") {
|
|
95
|
+
toPage({ __frame_room_ev: true, kind: "msg", topic: m.topic, data: m.data, from: m.from, by: m.by });
|
|
96
|
+
} else if (m.t === "peers") {
|
|
97
|
+
toPage({ __frame_room_ev: true, kind: "peers", peers: m.peers || [] });
|
|
98
|
+
} else if (m.t === "files") {
|
|
99
|
+
if (m.from === client) {
|
|
100
|
+
ver = m.ver;
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
reloadPage(m.ver);
|
|
104
|
+
} else if (m.t === "comments") {
|
|
105
|
+
void refreshThreads();
|
|
106
|
+
} else if (m.t === "rewired") {
|
|
107
|
+
void rewired(m);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async function rewired(m) {
|
|
111
|
+
gen = m.brokerGen;
|
|
112
|
+
toPage({ __frame_cap_rewired: true, caps: m.caps.map((c) => c === "artifact" ? "self" : c).concat(m.caps.includes("artifact") ? ["artifact"] : []), brokerGen: gen });
|
|
113
|
+
try {
|
|
114
|
+
const r = await fetch(api("session"), { credentials: "same-origin" });
|
|
115
|
+
if (r.ok) session = await r.json();
|
|
116
|
+
} catch {
|
|
117
|
+
}
|
|
118
|
+
if (m.reason === "type") reloadPage(session?.ver ?? ver);
|
|
119
|
+
}
|
|
120
|
+
function touches(sub, docPath) {
|
|
121
|
+
if (sub.kind === "doc") return sub.path === docPath;
|
|
122
|
+
return docPath.split("/").slice(0, -1).join("/") === sub.path;
|
|
123
|
+
}
|
|
124
|
+
function scheduleRerun() {
|
|
125
|
+
if (rerunTimer) return;
|
|
126
|
+
rerunTimer = setTimeout(() => {
|
|
127
|
+
rerunTimer = null;
|
|
128
|
+
const ids = [...rerun];
|
|
129
|
+
rerun.clear();
|
|
130
|
+
for (const id of ids) void runSub(id);
|
|
131
|
+
}, 30);
|
|
132
|
+
}
|
|
133
|
+
async function runSub(id) {
|
|
134
|
+
const s = subs.get(id);
|
|
135
|
+
if (!s) return;
|
|
136
|
+
const n = ++s.gen;
|
|
137
|
+
try {
|
|
138
|
+
const msg = { __frame_db_ev: true, sub: id };
|
|
139
|
+
if (s.kind === "doc") {
|
|
140
|
+
const r = await cap("db", "get", { path: s.path });
|
|
141
|
+
msg.exists = !!r.exists;
|
|
142
|
+
if (r.exists) msg.data = r.data;
|
|
143
|
+
} else {
|
|
144
|
+
const r = await cap("db", "query", { path: s.path, spec: s.spec || {} });
|
|
145
|
+
msg.docs = r.docs;
|
|
146
|
+
}
|
|
147
|
+
if (subs.get(id) === s && n === s.gen) toPage(msg);
|
|
148
|
+
} catch (error) {
|
|
149
|
+
if (subs.get(id) === s) toPage({ __frame_db_ev: true, sub: id, error });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function toPage(msg) {
|
|
153
|
+
if (!pageWin || !contentOrigin) return;
|
|
154
|
+
try {
|
|
155
|
+
pageWin.postMessage(msg, contentOrigin);
|
|
156
|
+
} catch {
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const pageUrl = (v) => `${contentOrigin}/_f/${encodeURIComponent(v)}/${location.hash}`;
|
|
160
|
+
function mountPage() {
|
|
161
|
+
const f = document.createElement("iframe");
|
|
162
|
+
frame = f;
|
|
163
|
+
f.title = session?.title || "Artifact";
|
|
164
|
+
f.allow = "clipboard-read; clipboard-write; fullscreen; autoplay";
|
|
165
|
+
f.referrerPolicy = "origin";
|
|
166
|
+
f.src = pageUrl(ver);
|
|
167
|
+
f.addEventListener("load", () => {
|
|
168
|
+
pageWin = f.contentWindow;
|
|
169
|
+
chrome.answered = 0;
|
|
170
|
+
chrome.sent = 0;
|
|
171
|
+
});
|
|
172
|
+
$("stage").append(f);
|
|
173
|
+
armReadyTimer();
|
|
174
|
+
}
|
|
175
|
+
function reloadPage(nextVer) {
|
|
176
|
+
if (!frame) return;
|
|
177
|
+
ver = nextVer;
|
|
178
|
+
ready = false;
|
|
179
|
+
revealed = false;
|
|
180
|
+
revealHeld = false;
|
|
181
|
+
subs.clear();
|
|
182
|
+
closeCard();
|
|
183
|
+
comments.custom = false;
|
|
184
|
+
comments.customPins = false;
|
|
185
|
+
comments.movable = false;
|
|
186
|
+
comments.pageButton = false;
|
|
187
|
+
setPlaced({});
|
|
188
|
+
views?.setPageButton(false);
|
|
189
|
+
views?.setMovable(false);
|
|
190
|
+
chrome.snapshot = null;
|
|
191
|
+
lastSnapshotText = "";
|
|
192
|
+
chrome.pendingExport = null;
|
|
193
|
+
frame.src = pageUrl(nextVer);
|
|
194
|
+
armReadyTimer();
|
|
195
|
+
sendReport();
|
|
196
|
+
}
|
|
197
|
+
function armReadyTimer() {
|
|
198
|
+
if (readyTimer) clearTimeout(readyTimer);
|
|
199
|
+
const s = Math.max(5, Number(session?.readyTimeoutS) || 60);
|
|
200
|
+
readyTimer = setTimeout(() => {
|
|
201
|
+
if (!ready) showProblem("This page did not start", `It did not say it was ready within ${s} seconds.`);
|
|
202
|
+
}, s * 1e3);
|
|
203
|
+
}
|
|
204
|
+
function reveal() {
|
|
205
|
+
if (revealed) return;
|
|
206
|
+
revealed = true;
|
|
207
|
+
toPage({ __frame_revealed: true });
|
|
208
|
+
toPage({ __frame_size_poke: true });
|
|
209
|
+
}
|
|
210
|
+
const theme = () => matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
|
211
|
+
const hostVisible = () => document.visibilityState !== "hidden";
|
|
212
|
+
function initMessage() {
|
|
213
|
+
const s = session;
|
|
214
|
+
const capabilities = {};
|
|
215
|
+
for (const c of s.grants) capabilities[c] = { config: s.configs[c] ?? {} };
|
|
216
|
+
return {
|
|
217
|
+
__frame_init: {
|
|
218
|
+
contract: s.contract,
|
|
219
|
+
changes: [],
|
|
220
|
+
flags: s.flags,
|
|
221
|
+
capabilities,
|
|
222
|
+
usable: [...s.grants, ...Object.keys(s.stubs)],
|
|
223
|
+
theme: theme(),
|
|
224
|
+
hostVisible: hostVisible(),
|
|
225
|
+
hostOverlays: [],
|
|
226
|
+
hostSides: {},
|
|
227
|
+
// Here: no host keys (the outer Shell takes its own shortcuts in its own frame).
|
|
228
|
+
hostKeys: [],
|
|
229
|
+
hot: { gen: 0, phase: "final", from: null },
|
|
230
|
+
capBudgets: DEFAULT_CAP_BUDGETS,
|
|
231
|
+
capWants: true,
|
|
232
|
+
brokerGen: gen,
|
|
233
|
+
client
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
function viewportMessage() {
|
|
238
|
+
return {
|
|
239
|
+
__frame_viewport: true,
|
|
240
|
+
composer: { available: false, visible: false, unread: 0 },
|
|
241
|
+
safeAreaInsets: { top: 0, right: 0, bottom: 0, left: 0 },
|
|
242
|
+
bottomInset: 0,
|
|
243
|
+
topInset: 0
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
window.addEventListener("message", (ev) => {
|
|
247
|
+
const m = ev.data;
|
|
248
|
+
if (!m || typeof m !== "object") return;
|
|
249
|
+
if (frame && ev.source === frame.contentWindow && ev.origin === contentOrigin) {
|
|
250
|
+
pageWin = ev.source;
|
|
251
|
+
void fromPage(m);
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
if (outer && ev.source === outer && ev.origin === outerOrigin) fromOuter(m);
|
|
255
|
+
});
|
|
256
|
+
async function fromPage(m) {
|
|
257
|
+
if (m.__frame_connect === true) {
|
|
258
|
+
toPage(initMessage());
|
|
259
|
+
toPage(viewportMessage());
|
|
260
|
+
toPage({ __frame_host_visible: { visible: hostVisible() } });
|
|
261
|
+
sendCommentsState();
|
|
262
|
+
if (comments.on) toPage({ __open_artifact_comments: true, op: "mode", on: true });
|
|
263
|
+
void refreshThreads();
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
if (m.__frame_cap === true && typeof m.id === "string") return answerCap(m);
|
|
267
|
+
if (m.__frame_cap_want === true) return answerWant(m);
|
|
268
|
+
if (m.__frame_ready === true) {
|
|
269
|
+
if (!ready) {
|
|
270
|
+
ready = true;
|
|
271
|
+
if (readyTimer) clearTimeout(readyTimer);
|
|
272
|
+
hideProblem();
|
|
273
|
+
}
|
|
274
|
+
if (!revealHeld) reveal();
|
|
275
|
+
openAskedThread();
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
if (m.__frame_reveal_hold === true) {
|
|
279
|
+
revealHeld = true;
|
|
280
|
+
setTimeout(() => {
|
|
281
|
+
revealHeld = false;
|
|
282
|
+
if (ready) reveal();
|
|
283
|
+
}, 15e3);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
if (m.__frame_reveal_ready === true) {
|
|
287
|
+
revealHeld = false;
|
|
288
|
+
reveal();
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
if (m.__frame_flags_ask === true) return toPage({ __frame_flags: true, values: session?.flags ?? {} });
|
|
292
|
+
if (m.__frame_health === true) {
|
|
293
|
+
if (m.level === "error" || m.fatal) console.warn("[frame health]", m);
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (m.__frame_chrome_hello === true) return chromeHello();
|
|
297
|
+
if (m.__frame_chrome_report === true) return chromeReport(m.snapshot);
|
|
298
|
+
if (m.__frame_chrome_decline === true) return exportEnded(m.request, "declined");
|
|
299
|
+
if (m.__open_artifact_export_done === true) return exportEnded(m.request, "done");
|
|
300
|
+
if (m.__frame_title_from_content === true && typeof m.title === "string") {
|
|
301
|
+
const out = await post("title", { title: m.title, ifUnnamed: m.ifUnnamed !== false }).catch(() => null);
|
|
302
|
+
if (out && out.applied) document.title = out.title;
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
if (m.__frame_agent_activity_ask === true) {
|
|
306
|
+
if (activity.asks++ < 8) {
|
|
307
|
+
activity.asked = true;
|
|
308
|
+
void pollActivity();
|
|
309
|
+
}
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
if (m.__frame_comments_request === true) return commentsRequest(m);
|
|
313
|
+
if (m.__open_artifact_comments_placed === true) {
|
|
314
|
+
if (session?.grants.includes("comments")) onPlaced(m.map);
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
if (m.__frame_escape === true) return onEscape();
|
|
318
|
+
if (m.__frame_bare_keys_want === true) return toPage({ __frame_bare_keys: !views?.open() && !comments.listOpen });
|
|
319
|
+
if (m.__frame_anchor === true || m.type === "current_anchor") return onAnchor(m.fragment);
|
|
320
|
+
if (m.__open_artifact_console === true) {
|
|
321
|
+
(m.level === "warn" ? console.warn : console.error)("[page]", String(m.text || ""));
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (m.__open_artifact_comments_sent === true) {
|
|
325
|
+
const done = sendTickets.get(m.ticket);
|
|
326
|
+
if (m.pending === true) return done?.(m);
|
|
327
|
+
sendTickets.delete(m.ticket);
|
|
328
|
+
done?.(m);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
if (m.__open_artifact_comments_moved === true) return void onMoved(m);
|
|
332
|
+
}
|
|
333
|
+
async function answerCap(m) {
|
|
334
|
+
const reply = (body) => toPage({ __frame_cap_r: true, id: m.id, ...body });
|
|
335
|
+
const capName = m.cap === "self" ? "artifact" : String(m.cap);
|
|
336
|
+
const a = Array.isArray(m.args) && m.args[0] && typeof m.args[0] === "object" ? m.args[0] : {};
|
|
337
|
+
if (m.brokerGen !== void 0 && m.brokerGen !== gen) {
|
|
338
|
+
if (capName === "user") return reply({ result: null });
|
|
339
|
+
return reply({ error: { code: ["db", "downloads", "files", "paste", "reads"].includes(capName) ? "unavailable" : "upstream_error", message: STALE_MESSAGE } });
|
|
340
|
+
}
|
|
341
|
+
if (capName === "analytics") return reply({ result: null });
|
|
342
|
+
if (session && !session.grants.includes(capName) && !(capName in session.stubs)) {
|
|
343
|
+
return reply({ error: { code: "not_granted", message: `${capName}: ${UNDECLARED_MESSAGE}` } });
|
|
344
|
+
}
|
|
345
|
+
const key = `${capName}.${m.method}`;
|
|
346
|
+
if (ACKED.has(key)) toPage({ __frame_cap_ack: true, id: m.id });
|
|
347
|
+
try {
|
|
348
|
+
if (key === "db.subscribe") {
|
|
349
|
+
if (typeof a.sub !== "string") throw { code: "invalid_argument", message: "subscribe needs an id." };
|
|
350
|
+
subs.set(a.sub, { kind: a.kind === "doc" ? "doc" : "query", path: String(a.path), spec: a.spec || null, gen: 0 });
|
|
351
|
+
reply({ result: {} });
|
|
352
|
+
return void runSub(a.sub);
|
|
353
|
+
}
|
|
354
|
+
if (key === "db.unsubscribe") {
|
|
355
|
+
subs.delete(a.sub);
|
|
356
|
+
return reply({ result: {} });
|
|
357
|
+
}
|
|
358
|
+
if (key === "assets.upload") {
|
|
359
|
+
if (!(a.blob instanceof Blob)) throw { code: "invalid_request", message: "upload() takes a Blob." };
|
|
360
|
+
const type = String(a.type || a.blob.type || "");
|
|
361
|
+
const r = await fetch(api(`upload?type=${encodeURIComponent(type)}&gen=${gen}`), { method: "POST", body: a.blob, headers: { "Content-Type": "application/octet-stream" } });
|
|
362
|
+
const out = await r.json().catch(() => ({ error: { code: "upstream_error", message: `HTTP ${r.status}` } }));
|
|
363
|
+
if (out.error) throw out.error;
|
|
364
|
+
return reply({ result: out.result });
|
|
365
|
+
}
|
|
366
|
+
if (capName === "comments" && ["compose", "open", "placed", "custom", "mode"].includes(m.method)) return reply({ result: commentsUi(m.method, a) });
|
|
367
|
+
if (key === "comments.sendToAgent") return reply({ result: await sendToAgent(a) });
|
|
368
|
+
if (key === "room.sendToAgentSession" && a.deliver === "stage") {
|
|
369
|
+
const text = typeof a.data === "string" ? a.data : JSON.stringify(a.data);
|
|
370
|
+
await navigator.clipboard?.writeText(text).catch(() => {
|
|
371
|
+
});
|
|
372
|
+
toast("Copied for the agent session.");
|
|
373
|
+
return reply({ result: { to: "clipboard" } });
|
|
374
|
+
}
|
|
375
|
+
const result = await cap(capName, m.method, a);
|
|
376
|
+
if (capName === "comments" && ["create", "reply", "resolve", "delete", "move"].includes(m.method)) void refreshThreads();
|
|
377
|
+
reply({ result });
|
|
378
|
+
} catch (error) {
|
|
379
|
+
const e = error ?? {};
|
|
380
|
+
reply({ error: { ...e, code: e.code || "upstream_error", message: e.message || String(error) } });
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
function answerWant(m) {
|
|
384
|
+
const name = typeof m.cap === "string" && /^[a-z][a-z0-9]{0,23}$/.test(m.cap) ? m.cap : null;
|
|
385
|
+
if (!name || typeof m.ver !== "string" || m.ver.length < 1 || m.ver.length > 128) return;
|
|
386
|
+
const c = name === "self" ? "artifact" : name;
|
|
387
|
+
const granted = !!session && c !== "network" && session.grants.includes(c);
|
|
388
|
+
toPage({ __frame_cap_grant: true, cap: m.cap, ver: m.ver, ...granted ? { grant: { config: session.configs[c] ?? {} } } : {}, brokerGen: gen });
|
|
389
|
+
}
|
|
390
|
+
const chrome = {
|
|
391
|
+
snapshot: null,
|
|
392
|
+
/** Hellos answered and none/pokes sent for this load. */
|
|
393
|
+
answered: 0,
|
|
394
|
+
sent: 0,
|
|
395
|
+
lastExportAt: 0,
|
|
396
|
+
/** The export the page is running; `outer` when the outer Shell asked for it (it hears the outcome). */
|
|
397
|
+
pendingExport: null,
|
|
398
|
+
lastActionAt: 0,
|
|
399
|
+
/** What the outer Shell draws (`draws` of its last `chrome_hello`). */
|
|
400
|
+
outerDraws: /* @__PURE__ */ new Set()
|
|
401
|
+
};
|
|
402
|
+
function hostDrawsSave() {
|
|
403
|
+
return !!outer && chrome.outerDraws.has("saved");
|
|
404
|
+
}
|
|
405
|
+
function toPageCmd(cmd) {
|
|
406
|
+
toPage({ __frame_chrome_cmd: true, ...cmd, ...hostDrawsSave() ? {} : { rows: false } });
|
|
407
|
+
}
|
|
408
|
+
function chromeHello() {
|
|
409
|
+
if (chrome.answered >= 8) return;
|
|
410
|
+
chrome.answered++;
|
|
411
|
+
sendChromeAnswer();
|
|
412
|
+
}
|
|
413
|
+
function sendChromeAnswer() {
|
|
414
|
+
if (chrome.sent >= 8) return;
|
|
415
|
+
chrome.sent++;
|
|
416
|
+
if (hostDrawsSave()) toPage({ __frame_chrome_poke: true, words: ["readonly"] });
|
|
417
|
+
else toPage({ __frame_chrome_none: true });
|
|
418
|
+
}
|
|
419
|
+
const SAVED = ["saved", "saving", "unsaved", "reconnecting", "readonly"];
|
|
420
|
+
const WHY = ["older_version", "agent_working", "draft_open", "comments_on", "needs_chat", "unsaved", "other"];
|
|
421
|
+
const ACTION_ID = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
422
|
+
const FORMAT = /^[a-z0-9]{1,8}$/;
|
|
423
|
+
const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
424
|
+
const optBool = (v) => v === void 0 || typeof v === "boolean";
|
|
425
|
+
const clampN = (v) => Math.max(0, Math.min(9999, v));
|
|
426
|
+
function validateSnapshot(raw) {
|
|
427
|
+
if (!isObj(raw) || raw.v !== 1) return null;
|
|
428
|
+
const out = { v: 1 };
|
|
429
|
+
if (raw.saved !== void 0) {
|
|
430
|
+
if (!SAVED.includes(raw.saved)) return null;
|
|
431
|
+
out.saved = raw.saved;
|
|
432
|
+
}
|
|
433
|
+
if (raw.unresolved !== void 0) {
|
|
434
|
+
if (typeof raw.unresolved !== "number" || !Number.isFinite(raw.unresolved)) return null;
|
|
435
|
+
out.unresolved = clampN(Math.floor(raw.unresolved));
|
|
436
|
+
}
|
|
437
|
+
if (raw.leaveLosesWork !== void 0) {
|
|
438
|
+
if (raw.leaveLosesWork !== true) return null;
|
|
439
|
+
out.leaveLosesWork = true;
|
|
440
|
+
}
|
|
441
|
+
if (raw.actions !== void 0) {
|
|
442
|
+
if (!Array.isArray(raw.actions) || raw.actions.length > 18) return null;
|
|
443
|
+
const seen = /* @__PURE__ */ new Set();
|
|
444
|
+
out.actions = [];
|
|
445
|
+
for (const a of raw.actions) {
|
|
446
|
+
if (!isObj(a) || typeof a.id !== "string" || !ACTION_ID.test(a.id) || !optBool(a.disabled)) return null;
|
|
447
|
+
if (a.why !== void 0 && !WHY.includes(a.why)) return null;
|
|
448
|
+
if (seen.has(a.id)) continue;
|
|
449
|
+
seen.add(a.id);
|
|
450
|
+
out.actions.push({ id: a.id, ...a.disabled ? { disabled: true } : {}, ...a.why ? { why: a.why } : {} });
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
const formats = /* @__PURE__ */ new Set();
|
|
454
|
+
if (raw.exports !== void 0) {
|
|
455
|
+
if (!Array.isArray(raw.exports) || raw.exports.length > 8) return null;
|
|
456
|
+
out.exports = [];
|
|
457
|
+
for (const x of raw.exports) {
|
|
458
|
+
if (!isObj(x) || typeof x.format !== "string" || !FORMAT.test(x.format) || formats.has(x.format)) return null;
|
|
459
|
+
if (!optBool(x.disabled) || !optBool(x.interactive) || !optBool(x.bundle)) return null;
|
|
460
|
+
let variants;
|
|
461
|
+
if (x.variants !== void 0) {
|
|
462
|
+
if (!Array.isArray(x.variants) || x.variants.length > 8) return null;
|
|
463
|
+
variants = [];
|
|
464
|
+
for (const v of x.variants) {
|
|
465
|
+
if (!isObj(v) || typeof v.id !== "string" || !ACTION_ID.test(v.id) || !optBool(v.disabled)) return null;
|
|
466
|
+
variants.push({ id: v.id, ...v.disabled ? { disabled: true } : {} });
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
formats.add(x.format);
|
|
470
|
+
out.exports.push({ format: x.format, ...x.disabled ? { disabled: true } : {}, ...x.interactive ? { interactive: true } : {}, ...x.bundle ? { bundle: true } : {}, ...variants ? { variants } : {} });
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
if (raw.handoffs !== void 0) {
|
|
474
|
+
if (!Array.isArray(raw.handoffs)) return null;
|
|
475
|
+
out.handoffs = [];
|
|
476
|
+
for (const h of raw.handoffs) {
|
|
477
|
+
if (!isObj(h) || typeof h.format !== "string" || !FORMAT.test(h.format) || formats.has(h.format) || !optBool(h.disabled)) return null;
|
|
478
|
+
formats.add(h.format);
|
|
479
|
+
out.handoffs.push({ format: h.format, ...h.disabled ? { disabled: true } : {} });
|
|
480
|
+
}
|
|
481
|
+
if (formats.size > 8) return null;
|
|
482
|
+
}
|
|
483
|
+
if (raw.destinations !== void 0) {
|
|
484
|
+
if (!Array.isArray(raw.destinations) || raw.destinations.length > 8) return null;
|
|
485
|
+
out.destinations = [];
|
|
486
|
+
for (const d of raw.destinations) {
|
|
487
|
+
if (!isObj(d) || typeof d.id !== "string" || !optBool(d.disabled)) return null;
|
|
488
|
+
if (d.name !== void 0 && (typeof d.name !== "string" || [...d.name].length > 48 || /[\u0000-\u001f\u007f]/.test(d.name))) return null;
|
|
489
|
+
out.destinations.push({ id: d.id, ...d.name !== void 0 ? { name: d.name } : {}, ...d.disabled ? { disabled: true } : {} });
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
if (raw.shareNotice !== void 0) {
|
|
493
|
+
const n = raw.shareNotice;
|
|
494
|
+
if (!isObj(n) || typeof n.text !== "string" || n.text.length > 2e3 || n.tone !== "warning") return null;
|
|
495
|
+
out.shareNotice = { text: n.text, tone: "warning" };
|
|
496
|
+
}
|
|
497
|
+
if (raw.hasContent !== void 0) {
|
|
498
|
+
if (typeof raw.hasContent !== "boolean") return null;
|
|
499
|
+
out.hasContent = raw.hasContent;
|
|
500
|
+
}
|
|
501
|
+
if (raw.ownChat !== void 0) {
|
|
502
|
+
if (raw.ownChat !== true) return null;
|
|
503
|
+
out.ownChat = true;
|
|
504
|
+
}
|
|
505
|
+
if (raw.ground !== void 0) {
|
|
506
|
+
if (typeof raw.ground !== "string" || !/^#[0-9a-f]{6}$/i.test(raw.ground)) return null;
|
|
507
|
+
out.ground = raw.ground;
|
|
508
|
+
}
|
|
509
|
+
for (const k of ["footInset", "footSlotX", "footSlotY", "footSlotW"]) {
|
|
510
|
+
if (raw[k] === void 0) continue;
|
|
511
|
+
if (typeof raw[k] !== "number" || !Number.isFinite(raw[k])) return null;
|
|
512
|
+
out[k] = clampN(raw[k]);
|
|
513
|
+
}
|
|
514
|
+
return out;
|
|
515
|
+
}
|
|
516
|
+
let lastSnapshotText = "";
|
|
517
|
+
function chromeReport(raw) {
|
|
518
|
+
if (raw === null && chrome.snapshot) {
|
|
519
|
+
chrome.snapshot = null;
|
|
520
|
+
lastSnapshotText = "";
|
|
521
|
+
sendReport();
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
const snap = validateSnapshot(raw);
|
|
525
|
+
if (!snap) return;
|
|
526
|
+
const text = JSON.stringify(snap);
|
|
527
|
+
const first = chrome.snapshot === null;
|
|
528
|
+
chrome.snapshot = snap;
|
|
529
|
+
if (first && hostDrawsSave()) sendChromeAnswer();
|
|
530
|
+
if (text === lastSnapshotText) return;
|
|
531
|
+
lastSnapshotText = text;
|
|
532
|
+
sendReport();
|
|
533
|
+
}
|
|
534
|
+
function exportItems() {
|
|
535
|
+
const out = [];
|
|
536
|
+
for (const x of chrome.snapshot?.exports ?? []) {
|
|
537
|
+
if (x.disabled) continue;
|
|
538
|
+
const label = x.format.toUpperCase();
|
|
539
|
+
const live = (x.variants ?? []).filter((v) => !v.disabled);
|
|
540
|
+
if (live.length) for (const v of live) out.push({ item: { label: `${label} (${v.id})` }, format: x.format, variant: v.id, ...x.interactive ? { interactive: true } : {} });
|
|
541
|
+
else out.push({ item: { label, ...x.interactive ? { description: "Opens the page’s export options" } : {} }, format: x.format, ...x.interactive ? { interactive: true } : {} });
|
|
542
|
+
}
|
|
543
|
+
return out;
|
|
544
|
+
}
|
|
545
|
+
const REQUEST = /^[A-Za-z0-9_-]{16,64}$/;
|
|
546
|
+
function startExport(format, variant, request, fromOuter2) {
|
|
547
|
+
const x = chrome.snapshot?.exports?.find((e) => e.format === format);
|
|
548
|
+
if (!x || x.disabled) return "unsupported";
|
|
549
|
+
if (variant !== void 0 && !(x.variants ?? []).some((v) => v.id === variant && !v.disabled)) return "unsupported";
|
|
550
|
+
const now = Date.now();
|
|
551
|
+
if (now - chrome.lastExportAt < 250) return "busy";
|
|
552
|
+
if (chrome.pendingExport && now - chrome.pendingExport.at < 5e3) return "busy";
|
|
553
|
+
chrome.lastExportAt = now;
|
|
554
|
+
chrome.pendingExport = { request, at: now, outer: fromOuter2 };
|
|
555
|
+
toPageCmd({ cmd: "export", format, request, interactive: true, ...variant ? { variant } : {}, sender: "viewer" });
|
|
556
|
+
return "started";
|
|
557
|
+
}
|
|
558
|
+
function runExport(label) {
|
|
559
|
+
const hit = exportItems().find((x) => x.item.label === label);
|
|
560
|
+
if (hit) startExport(hit.format, hit.variant, randomId(24), false);
|
|
561
|
+
}
|
|
562
|
+
function runExportFormat(c) {
|
|
563
|
+
const request = typeof c.request === "string" ? c.request : "";
|
|
564
|
+
if (!REQUEST.test(request)) return;
|
|
565
|
+
const variant = typeof c.variant === "string" ? c.variant : void 0;
|
|
566
|
+
const state = typeof c.format === "string" ? startExport(c.format, variant, request, true) : "unsupported";
|
|
567
|
+
toOuter({ openArtifact: "chrome_export", request, state });
|
|
568
|
+
}
|
|
569
|
+
function exportEnded(request, state) {
|
|
570
|
+
const pending = chrome.pendingExport;
|
|
571
|
+
if (!pending || pending.request !== request) return;
|
|
572
|
+
chrome.pendingExport = null;
|
|
573
|
+
if (pending.outer) toOuter({ openArtifact: "chrome_export", request: pending.request, state });
|
|
574
|
+
}
|
|
575
|
+
function runAction(id) {
|
|
576
|
+
if (typeof id !== "string") return;
|
|
577
|
+
const action = chrome.snapshot?.actions?.find((a) => a.id === id);
|
|
578
|
+
if (!action || action.disabled) return;
|
|
579
|
+
const now = Date.now();
|
|
580
|
+
if (now - chrome.lastActionAt < 250) return;
|
|
581
|
+
chrome.lastActionAt = now;
|
|
582
|
+
toPageCmd({ cmd: "action", id });
|
|
583
|
+
}
|
|
584
|
+
const WHY_OUT = { needs_chat: "needs_agent" };
|
|
585
|
+
const whyOut = (why) => why ? WHY_OUT[why] ?? why : void 0;
|
|
586
|
+
function snapshotChrome(snap) {
|
|
587
|
+
if (!snap) return {};
|
|
588
|
+
const actions = snap.actions?.map((a) => {
|
|
589
|
+
const why = whyOut(a.why);
|
|
590
|
+
return { id: a.id, ...a.disabled ? { disabled: true } : {}, ...why ? { why } : {} };
|
|
591
|
+
});
|
|
592
|
+
const formats = snap.exports?.map((x) => ({
|
|
593
|
+
format: x.format,
|
|
594
|
+
...x.disabled ? { disabled: true } : {},
|
|
595
|
+
...x.interactive ? { interactive: true } : {},
|
|
596
|
+
...x.variants?.length ? { variants: x.variants.map((v) => ({ id: v.id, ...v.disabled ? { disabled: true } : {} })) } : {}
|
|
597
|
+
}));
|
|
598
|
+
return {
|
|
599
|
+
...snap.saved ? { saved: snap.saved } : {},
|
|
600
|
+
...snap.leaveLosesWork ? { leaveLosesWork: true } : {},
|
|
601
|
+
...actions ? { actions } : {},
|
|
602
|
+
...formats ? { formats } : {},
|
|
603
|
+
...snap.shareNotice ? { shareNotice: snap.shareNotice } : {},
|
|
604
|
+
...typeof snap.hasContent === "boolean" ? { hasContent: snap.hasContent } : {}
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
const activity = { asked: false, asks: 0, working: false, timer: null };
|
|
608
|
+
function toOuter(msg) {
|
|
609
|
+
if (!outer || !outerOrigin) return;
|
|
610
|
+
try {
|
|
611
|
+
outer.postMessage(msg, outerOrigin);
|
|
612
|
+
} catch {
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
function sendReport() {
|
|
616
|
+
const snap = chrome.snapshot;
|
|
617
|
+
const count = session?.comments?.available ? comments.count : snap?.unresolved ?? 0;
|
|
618
|
+
const report = {
|
|
619
|
+
comments: { available: !!session?.comments?.available, on: comments.on, open: comments.listOpen, count, pageButton: comments.pageButton },
|
|
620
|
+
agent: { available: !!session?.agent?.available, listening: false, busy: activity.working },
|
|
621
|
+
history: false,
|
|
622
|
+
share: false,
|
|
623
|
+
shareOn: false,
|
|
624
|
+
// Older Shells list these by label (`exports` / `export`); newer ones use `formats`.
|
|
625
|
+
exports: exportItems().length > 0,
|
|
626
|
+
...snapshotChrome(snap)
|
|
627
|
+
};
|
|
628
|
+
toOuter({ openArtifact: "chrome_report", protocol: CHROME_PROTOCOL, report });
|
|
629
|
+
}
|
|
630
|
+
function fromOuter(m) {
|
|
631
|
+
if (m.openArtifact === "chrome_hello") {
|
|
632
|
+
const draws = new Set(Array.isArray(m.draws) ? m.draws.filter((d) => typeof d === "string") : []);
|
|
633
|
+
const before = hostDrawsSave();
|
|
634
|
+
chrome.outerDraws = draws;
|
|
635
|
+
if (hostDrawsSave() !== before && chrome.snapshot) {
|
|
636
|
+
chrome.sent = Math.min(chrome.sent, 7);
|
|
637
|
+
sendChromeAnswer();
|
|
638
|
+
}
|
|
639
|
+
return sendReport();
|
|
640
|
+
}
|
|
641
|
+
if (m.openArtifact === "files_changed") return toOuter({ openArtifact: "files_changed_ok" });
|
|
642
|
+
if (m.openArtifact !== "chrome_cmd") return;
|
|
643
|
+
const c = m;
|
|
644
|
+
if (c.cmd === "comments_mode") setMode(c.on ?? !comments.on);
|
|
645
|
+
else if (c.cmd === "comments_list") setList(c.open ?? !comments.listOpen);
|
|
646
|
+
else if (c.cmd === "exports") toOuter({ openArtifact: "chrome_exports", id: c.id, items: exportItems().map((x) => x.item) });
|
|
647
|
+
else if (c.cmd === "export") runExport(c.label);
|
|
648
|
+
else if (c.cmd === "export_format") runExportFormat(c);
|
|
649
|
+
else if (c.cmd === "action") runAction(c.id);
|
|
650
|
+
}
|
|
651
|
+
async function pollActivity() {
|
|
652
|
+
if (activity.timer) clearTimeout(activity.timer);
|
|
653
|
+
const out = await post("activity", {}).catch(() => null);
|
|
654
|
+
const working = !!out?.working;
|
|
655
|
+
if (working !== activity.working || activity.asked) {
|
|
656
|
+
activity.asked = false;
|
|
657
|
+
activity.working = working;
|
|
658
|
+
toPage({ __frame_agent_activity: true, working });
|
|
659
|
+
sendReport();
|
|
660
|
+
}
|
|
661
|
+
if (session?.agent?.available) activity.timer = setTimeout(pollActivity, 1e4);
|
|
662
|
+
}
|
|
663
|
+
const RESERVED_FRAGMENT = /^(sidebar|settings|customize|upgrade|downloads)$/;
|
|
664
|
+
const validFragment = (f) => typeof f === "string" && /^[A-Za-z0-9._~-]{1,128}$/.test(f) && !f.startsWith("comment-") && !RESERVED_FRAGMENT.test(f) ? f : "";
|
|
665
|
+
let anchorTimer = null;
|
|
666
|
+
function onAnchor(fragment) {
|
|
667
|
+
const frag = validFragment(fragment);
|
|
668
|
+
if (anchorTimer) clearTimeout(anchorTimer);
|
|
669
|
+
anchorTimer = setTimeout(() => {
|
|
670
|
+
const current = location.hash.slice(1);
|
|
671
|
+
if (frag === current || !frag && current && !validFragment(current)) return;
|
|
672
|
+
history.replaceState(history.state, "", `${location.pathname}${location.search}${frag ? `#${frag}` : ""}`);
|
|
673
|
+
}, 250);
|
|
674
|
+
}
|
|
675
|
+
function onEscape() {
|
|
676
|
+
if (views?.open()) closeCard();
|
|
677
|
+
else if (comments.listOpen) setList(false);
|
|
678
|
+
else if (comments.on) setMode(false);
|
|
679
|
+
}
|
|
680
|
+
const LINK_RETRY_MS = 300;
|
|
681
|
+
const LINK_TRIES = 30;
|
|
682
|
+
const MAX_PLACED = 256;
|
|
683
|
+
const comments = {
|
|
684
|
+
on: false,
|
|
685
|
+
listOpen: false,
|
|
686
|
+
count: 0,
|
|
687
|
+
threads: [],
|
|
688
|
+
/** The threads were listed at least once. */
|
|
689
|
+
listed: false,
|
|
690
|
+
/** The page registered custom anchors (`customAnchors`). */
|
|
691
|
+
custom: false,
|
|
692
|
+
/** …and wants its pins drawn outside comment mode too (`pinsOutsideMode`). */
|
|
693
|
+
customPins: false,
|
|
694
|
+
/** …and can move a thread to where a pin is dropped (`move`). */
|
|
695
|
+
movable: false,
|
|
696
|
+
/** The page draws its own comments button (`__frame_comments_request {drawn}`). */
|
|
697
|
+
pageButton: false,
|
|
698
|
+
placed: {}
|
|
699
|
+
};
|
|
700
|
+
const sendTickets = /* @__PURE__ */ new Map();
|
|
701
|
+
let views;
|
|
702
|
+
function ui() {
|
|
703
|
+
if (views !== void 0) return views;
|
|
704
|
+
const bundle = window.__openArtifactFrameComments;
|
|
705
|
+
if (!bundle) return null;
|
|
706
|
+
views = bundle.mount(
|
|
707
|
+
$("comments-ui"),
|
|
708
|
+
{
|
|
709
|
+
cap: (method, arg) => cap("comments", method, arg),
|
|
710
|
+
sendToAgent,
|
|
711
|
+
refresh: refreshThreads,
|
|
712
|
+
agent: () => ({ available: !!session?.agent?.available, name: agentName() }),
|
|
713
|
+
activeChanged: () => pushThreads(),
|
|
714
|
+
listChanged: (open) => setList(open),
|
|
715
|
+
modeChanged: (on) => setMode(on),
|
|
716
|
+
composingChanged: (open) => toPage({ __open_artifact_comments: true, op: "composing", state: open }),
|
|
717
|
+
reveal: (id) => {
|
|
718
|
+
pushThreads();
|
|
719
|
+
toPage({ __open_artifact_comments: true, op: "reveal", id });
|
|
720
|
+
},
|
|
721
|
+
move: (id, at) => movePin(id, at),
|
|
722
|
+
toast
|
|
723
|
+
},
|
|
724
|
+
{ launcher: !outer }
|
|
725
|
+
);
|
|
726
|
+
views.setThreads(comments.threads);
|
|
727
|
+
views.setPlaced(comments.placed);
|
|
728
|
+
views.setMode(comments.on);
|
|
729
|
+
views.setPageButton(comments.pageButton);
|
|
730
|
+
views.setMovable(comments.movable);
|
|
731
|
+
return views;
|
|
732
|
+
}
|
|
733
|
+
function needUi() {
|
|
734
|
+
const out = ui();
|
|
735
|
+
if (!out) toast("Comments need the frame client built: node scripts/build.mjs --only frame");
|
|
736
|
+
return out;
|
|
737
|
+
}
|
|
738
|
+
function setCount(n) {
|
|
739
|
+
if (n === comments.count) return;
|
|
740
|
+
comments.count = n;
|
|
741
|
+
sendCommentsState();
|
|
742
|
+
sendReport();
|
|
743
|
+
}
|
|
744
|
+
function sendCommentsState() {
|
|
745
|
+
const available = !!session?.comments?.available;
|
|
746
|
+
toPage({ __frame_comments: true, offered: available, available, showsList: available, on: comments.on, listOpen: comments.listOpen, count: comments.count });
|
|
747
|
+
}
|
|
748
|
+
function setMode(on) {
|
|
749
|
+
if (!session?.comments?.available) return;
|
|
750
|
+
on = !!on;
|
|
751
|
+
if (on === comments.on) return;
|
|
752
|
+
comments.on = on;
|
|
753
|
+
if (!on) {
|
|
754
|
+
closeCard();
|
|
755
|
+
if (!comments.customPins) setPlaced({});
|
|
756
|
+
}
|
|
757
|
+
ui()?.setMode(on);
|
|
758
|
+
toPage({ __open_artifact_comments: true, op: "mode", on });
|
|
759
|
+
sendCommentsState();
|
|
760
|
+
sendReport();
|
|
761
|
+
}
|
|
762
|
+
function setList(open) {
|
|
763
|
+
if (comments.listOpen === !!open) return;
|
|
764
|
+
const views2 = open ? needUi() : ui();
|
|
765
|
+
if (open && !views2) return;
|
|
766
|
+
comments.listOpen = !!open;
|
|
767
|
+
views2?.setList(comments.listOpen);
|
|
768
|
+
sendCommentsState();
|
|
769
|
+
sendReport();
|
|
770
|
+
}
|
|
771
|
+
function commentsRequest(m) {
|
|
772
|
+
if (typeof m.drawn === "boolean" && m.drawn !== comments.pageButton) {
|
|
773
|
+
comments.pageButton = m.drawn;
|
|
774
|
+
ui()?.setPageButton(m.drawn);
|
|
775
|
+
sendReport();
|
|
776
|
+
}
|
|
777
|
+
if (typeof m.show === "boolean") setList(m.show);
|
|
778
|
+
}
|
|
779
|
+
function setPlaced(map) {
|
|
780
|
+
comments.placed = map;
|
|
781
|
+
views?.setPlaced(map);
|
|
782
|
+
}
|
|
783
|
+
function onPlaced(raw) {
|
|
784
|
+
if (!comments.on && !comments.customPins) return;
|
|
785
|
+
const out = {};
|
|
786
|
+
if (raw && typeof raw === "object") {
|
|
787
|
+
let n = 0;
|
|
788
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
789
|
+
if (n++ >= MAX_PLACED) break;
|
|
790
|
+
out[k] = v && typeof v === "object" && Number.isFinite(v.x) && Number.isFinite(v.y) ? { x: v.x, y: v.y } : null;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
setPlaced(out);
|
|
794
|
+
if (Object.keys(out).length) ui();
|
|
795
|
+
}
|
|
796
|
+
async function refreshThreads() {
|
|
797
|
+
if (!session?.comments?.available) return;
|
|
798
|
+
try {
|
|
799
|
+
const r = await cap("comments", "list", { all: true });
|
|
800
|
+
comments.threads = r.threads || [];
|
|
801
|
+
comments.listed = true;
|
|
802
|
+
} catch {
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
setCount(comments.threads.reduce((n, t) => t.resolved ? n : n + (t.messages?.length || 0), 0));
|
|
806
|
+
if (comments.threads.length) ui()?.setThreads(comments.threads);
|
|
807
|
+
else views?.setThreads(comments.threads);
|
|
808
|
+
pushThreads();
|
|
809
|
+
}
|
|
810
|
+
function pushThreads() {
|
|
811
|
+
const active = views?.active() ?? null;
|
|
812
|
+
toPage({ __open_artifact_comments: true, op: "threads", threads: comments.threads.map((t) => ({ id: t.id, anchor: t.anchor, resolved: t.resolved, active: t.id === active })) });
|
|
813
|
+
}
|
|
814
|
+
function commentsUi(method, a) {
|
|
815
|
+
if (method === "custom") {
|
|
816
|
+
comments.custom = !!a.on;
|
|
817
|
+
comments.customPins = !!a.on && !!a.pins;
|
|
818
|
+
comments.movable = !!a.on && !!a.move;
|
|
819
|
+
views?.setMovable(comments.movable);
|
|
820
|
+
if (!a.on) setPlaced({});
|
|
821
|
+
if (a.on && comments.on) toPage({ __open_artifact_comments: true, op: "mode", on: true });
|
|
822
|
+
if (a.on) pushThreads();
|
|
823
|
+
return {};
|
|
824
|
+
}
|
|
825
|
+
if (method === "mode") {
|
|
826
|
+
setMode(!!a.on);
|
|
827
|
+
return {};
|
|
828
|
+
}
|
|
829
|
+
if (method === "placed") {
|
|
830
|
+
onPlaced(a.map);
|
|
831
|
+
return {};
|
|
832
|
+
}
|
|
833
|
+
if (method === "compose") {
|
|
834
|
+
if (comments.custom && a.click && !comments.on) setMode(true);
|
|
835
|
+
const views2 = needUi();
|
|
836
|
+
if (!views2) return { opened: false };
|
|
837
|
+
const typed = views2.draftText();
|
|
838
|
+
if (typed !== null && typed.trim() && !a.area) return { opened: false };
|
|
839
|
+
if (a.click && !a.area && views2.open()) {
|
|
840
|
+
views2.close();
|
|
841
|
+
return { opened: false };
|
|
842
|
+
}
|
|
843
|
+
views2.compose(a.anchor, a.at, typeof a.label === "string" ? a.label : void 0, typeof a.detail === "string" ? a.detail : void 0);
|
|
844
|
+
return { opened: true };
|
|
845
|
+
}
|
|
846
|
+
if (method === "open") {
|
|
847
|
+
return { opened: !!needUi()?.openThread(String(a.id ?? ""), a.at || comments.placed[a.id]) };
|
|
848
|
+
}
|
|
849
|
+
return {};
|
|
850
|
+
}
|
|
851
|
+
function closeCard() {
|
|
852
|
+
views?.close();
|
|
853
|
+
}
|
|
854
|
+
window.addEventListener("blur", () => {
|
|
855
|
+
setTimeout(() => {
|
|
856
|
+
if (!comments.on && frame && document.activeElement === frame) views?.outsidePress();
|
|
857
|
+
});
|
|
858
|
+
});
|
|
859
|
+
let moveSeq = 0;
|
|
860
|
+
const moves = /* @__PURE__ */ new Map();
|
|
861
|
+
function movePin(id, at) {
|
|
862
|
+
if (!comments.movable) return;
|
|
863
|
+
const n = ++moveSeq;
|
|
864
|
+
moves.set(n, id);
|
|
865
|
+
setTimeout(() => moves.delete(n), 5e3);
|
|
866
|
+
toPage({ __open_artifact_comments: true, op: "move", n, id, x: at.x, y: at.y });
|
|
867
|
+
}
|
|
868
|
+
async function onMoved(m) {
|
|
869
|
+
const id = moves.get(m.n);
|
|
870
|
+
moves.delete(m.n);
|
|
871
|
+
if (!id || m.refused || m.anchor === void 0) return;
|
|
872
|
+
try {
|
|
873
|
+
await cap("comments", "move", { threadId: id, anchor: m.anchor, ...typeof m.label === "string" ? { label: m.label } : {}, ...typeof m.detail === "string" ? { detail: m.detail } : {} });
|
|
874
|
+
} catch (error) {
|
|
875
|
+
toast(error?.message || "Could not move the comment.");
|
|
876
|
+
}
|
|
877
|
+
void refreshThreads();
|
|
878
|
+
}
|
|
879
|
+
const agentName = () => session?.agent?.name || "the agent";
|
|
880
|
+
async function sendToAgent(a) {
|
|
881
|
+
const ticket = randomId(10);
|
|
882
|
+
const asked = new Promise((resolve) => {
|
|
883
|
+
let timer = setTimeout(() => {
|
|
884
|
+
if (sendTickets.delete(ticket)) resolve({ handled: false });
|
|
885
|
+
}, 1500);
|
|
886
|
+
sendTickets.set(ticket, (m) => {
|
|
887
|
+
if (m?.pending === true) {
|
|
888
|
+
clearTimeout(timer);
|
|
889
|
+
timer = setTimeout(() => {
|
|
890
|
+
if (sendTickets.delete(ticket)) resolve({ handled: false });
|
|
891
|
+
}, 12e4);
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
clearTimeout(timer);
|
|
895
|
+
resolve(m);
|
|
896
|
+
});
|
|
897
|
+
});
|
|
898
|
+
toPage({ __open_artifact_comments: true, op: "send", ticket, payload: a });
|
|
899
|
+
const r = await asked;
|
|
900
|
+
if (r?.handled) return { status: "handled", ...r.reply ? { reply: r.reply } : {} };
|
|
901
|
+
const out = await cap("comments", "sendToAgent", a);
|
|
902
|
+
void refreshThreads();
|
|
903
|
+
return out;
|
|
904
|
+
}
|
|
905
|
+
let askedThreadDone = false;
|
|
906
|
+
function openAskedThread() {
|
|
907
|
+
const id = params.get("comment");
|
|
908
|
+
if (!id || askedThreadDone) return;
|
|
909
|
+
askedThreadDone = true;
|
|
910
|
+
const url = new URL(location.href);
|
|
911
|
+
url.searchParams.delete("comment");
|
|
912
|
+
history.replaceState(history.state, "", url.href);
|
|
913
|
+
const start = (waits) => {
|
|
914
|
+
if (!comments.listed) {
|
|
915
|
+
if (waits > 0) setTimeout(() => start(waits - 1), LINK_RETRY_MS);
|
|
916
|
+
return;
|
|
917
|
+
}
|
|
918
|
+
const t = comments.threads.find((x) => x.id === id || x.id.startsWith(id));
|
|
919
|
+
if (!t) return;
|
|
920
|
+
const attempt = (n) => {
|
|
921
|
+
needUi()?.show(t.id);
|
|
922
|
+
if (comments.placed[t.id] || n <= 1) return;
|
|
923
|
+
setTimeout(() => attempt(n - 1), LINK_RETRY_MS);
|
|
924
|
+
};
|
|
925
|
+
attempt(LINK_TRIES);
|
|
926
|
+
};
|
|
927
|
+
start(LINK_TRIES);
|
|
928
|
+
}
|
|
929
|
+
function showProblem(title, text) {
|
|
930
|
+
$("problemTitle").textContent = title;
|
|
931
|
+
$("problemText").textContent = text;
|
|
932
|
+
$("problemAgent").hidden = !session?.agent?.available;
|
|
933
|
+
$("problemNote").textContent = "";
|
|
934
|
+
$("problem").hidden = false;
|
|
935
|
+
}
|
|
936
|
+
const hideProblem = () => void ($("problem").hidden = true);
|
|
937
|
+
let toastTimer = null;
|
|
938
|
+
function toast(text) {
|
|
939
|
+
const t = $("toast");
|
|
940
|
+
t.textContent = text;
|
|
941
|
+
t.hidden = false;
|
|
942
|
+
if (toastTimer) clearTimeout(toastTimer);
|
|
943
|
+
toastTimer = setTimeout(() => t.hidden = true, 3500);
|
|
944
|
+
}
|
|
945
|
+
$("problemReload").onclick = () => {
|
|
946
|
+
hideProblem();
|
|
947
|
+
reloadPage(ver);
|
|
948
|
+
};
|
|
949
|
+
$("problemAgent").onclick = async () => {
|
|
950
|
+
const b = $("problemAgent");
|
|
951
|
+
b.disabled = true;
|
|
952
|
+
const out = await post("agent", { text: `The ${session?.key} page of this artifact did not start within ${session?.readyTimeoutS} seconds. Please look at why.` }).catch((e) => ({ error: e }));
|
|
953
|
+
b.disabled = false;
|
|
954
|
+
$("problemNote").textContent = out?.error ? `Could not reach the agent: ${out.error.message || out.error}` : "The agent has been asked.";
|
|
955
|
+
};
|
|
956
|
+
document.addEventListener("keydown", (ev) => {
|
|
957
|
+
if (ev.key === "Escape") onEscape();
|
|
958
|
+
});
|
|
959
|
+
document.addEventListener("visibilitychange", () => toPage({ __frame_host_visible: { visible: hostVisible() } }));
|
|
960
|
+
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => toPage({ __frame_theme: { theme: theme() } }));
|
|
961
|
+
window.addEventListener("resize", () => toPage(viewportMessage()));
|
|
962
|
+
window.addEventListener("pageshow", () => {
|
|
963
|
+
chrome.sent = Math.min(chrome.sent, 7);
|
|
964
|
+
if (chrome.snapshot) sendChromeAnswer();
|
|
965
|
+
});
|
|
966
|
+
window.addEventListener("popstate", () => {
|
|
967
|
+
const frag = validFragment(location.hash.slice(1));
|
|
968
|
+
if (frag) toPage({ __frame_anchor_goto: { fragment: frag } });
|
|
969
|
+
});
|
|
970
|
+
void (async () => {
|
|
971
|
+
try {
|
|
972
|
+
const r = await fetch(api("session"), { credentials: "same-origin" });
|
|
973
|
+
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
974
|
+
session = await r.json();
|
|
975
|
+
} catch (error) {
|
|
976
|
+
showProblem("This artifact cannot open", `The type server did not answer (${error?.message || error}).`);
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
contentOrigin = session.contentOrigin;
|
|
980
|
+
ver = session.ver;
|
|
981
|
+
gen = session.brokerGen;
|
|
982
|
+
document.title = session.title || "Artifact";
|
|
983
|
+
comments.count = session.comments?.count || 0;
|
|
984
|
+
openStream();
|
|
985
|
+
mountPage();
|
|
986
|
+
if (!outer && session.comments?.available) ui();
|
|
987
|
+
sendReport();
|
|
988
|
+
})();
|
|
989
|
+
})();
|
|
990
|
+
})();
|