pi-pocket 0.25.0 → 0.26.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 (85) hide show
  1. package/AGENTS.md +2 -0
  2. package/README.md +5 -3
  3. package/docs/architecture.md +21 -0
  4. package/docs/design/design-mode.md +108 -0
  5. package/docs/design/notes-a.md +106 -0
  6. package/docs/design/notes-b.md +123 -0
  7. package/docs/design/notes-c.md +92 -0
  8. package/docs/design/notes-d.md +78 -0
  9. package/docs/design/release-notes-design.md +46 -0
  10. package/docs/extensions/browser-modules.md +2 -0
  11. package/docs/extensions/policies/api-stability.md +2 -0
  12. package/docs/extensions/reference/api-versions.md +1 -0
  13. package/docs/extensions/reference/host.md +1 -1
  14. package/docs/extensions/reference/limits.md +4 -0
  15. package/docs/extensions/reference/names.md +2 -2
  16. package/docs/extensions/reference/pocket.md +38 -0
  17. package/docs/features.md +19 -5
  18. package/docs/map.md +75 -54
  19. package/docs/release-notes.md +1 -1
  20. package/docs/self-editing.md +1 -1
  21. package/docs/systemd.md +1 -1
  22. package/npm-shrinkwrap.json +2 -2
  23. package/package.json +1 -1
  24. package/src/launcher/main.ts +20 -9
  25. package/src/server/app.ts +113 -4
  26. package/src/server/background.ts +3 -3
  27. package/src/server/cache-keeper.ts +605 -0
  28. package/src/server/compaction.ts +68 -15
  29. package/src/server/design/bundle.ts +65 -0
  30. package/src/server/design/export.ts +118 -0
  31. package/src/server/design/files.ts +49 -0
  32. package/src/server/design/guide.ts +56 -0
  33. package/src/server/design/index.ts +232 -0
  34. package/src/server/design/pptx.ts +304 -0
  35. package/src/server/design/render.ts +593 -0
  36. package/src/server/design/system.ts +248 -0
  37. package/src/server/docs.ts +55 -0
  38. package/src/server/extensions/artifacts.ts +202 -18
  39. package/src/server/extensions/design/canvas.js +304 -0
  40. package/src/server/extensions/design/comments.js +15 -0
  41. package/src/server/extensions/design/data.js +263 -0
  42. package/src/server/extensions/design/devices.js +70 -0
  43. package/src/server/extensions/design/docks.js +647 -0
  44. package/src/server/extensions/design/edits.js +37 -0
  45. package/src/server/extensions/design/index.js +326 -0
  46. package/src/server/extensions/design/messages.js +92 -0
  47. package/src/server/extensions/design/parts.js +160 -0
  48. package/src/server/extensions/design/state.js +146 -0
  49. package/src/server/extensions/design/style.css +1332 -0
  50. package/src/server/extensions/design/tweaks.js +161 -0
  51. package/src/server/extensions/design/views.js +375 -0
  52. package/src/server/extensions/design/workspace.js +723 -0
  53. package/src/server/extensions/design.ts +620 -0
  54. package/src/server/extensions/plan.ts +11 -9
  55. package/src/server/extensions/prompt.ts +11 -3
  56. package/src/server/extensions/subagents.ts +7 -1
  57. package/src/server/extensions/updates/index.js +16 -6
  58. package/src/server/extensions/updates.ts +2 -2
  59. package/src/server/http/artifact-assets.ts +216 -0
  60. package/src/server/http/artifact-inspect.ts +1281 -0
  61. package/src/server/http/artifacts.ts +89 -14
  62. package/src/server/http/conversation-routes.ts +46 -1
  63. package/src/server/http.ts +12 -4
  64. package/src/server/main.ts +4 -0
  65. package/src/server/npm-install.ts +82 -0
  66. package/src/server/npm-update.ts +100 -0
  67. package/src/server/reload.ts +5 -0
  68. package/src/server/room.ts +2 -0
  69. package/src/server/spend.ts +73 -9
  70. package/src/server/update-state.ts +257 -8
  71. package/src/server/updates.ts +268 -33
  72. package/src/server/zip.ts +163 -0
  73. package/types/pocket.d.ts +32 -0
  74. package/web/activity-fold.js +28 -0
  75. package/web/artifact-bridge.js +506 -82
  76. package/web/extension-ui.js +21 -1
  77. package/web/pip.js +46 -9
  78. package/web/sessions.js +1 -1
  79. package/web/sheets/appearance.js +10 -0
  80. package/web/sheets/viewers.js +26 -1
  81. package/web/style.css +11 -0
  82. package/web/taps.js +26 -0
  83. package/web/theme.js +6 -0
  84. package/web/transcript.js +19 -10
  85. package/src/server/http/public.ts +0 -30
@@ -2,7 +2,13 @@
2
2
  // box, for them to review and send (#88); and load or save a small JSON value of its own, for that person (#89). The
3
3
  // page keeps its sandbox: it never gets the app, its cookies, or a way to make Pi act. Only the frame's first page is
4
4
  // heard (over a channel it opens as it starts), only while its session shows, and the app's rights decide, not the page.
5
- import { useLayoutEffect } from "preact/hooks";
5
+ //
6
+ // Design mode (`docs/design/design-mode.md`) adds a line the other way, for the workspace: `send` puts the app's
7
+ // messages to a frame (inspect, text edit, tweaks, pins, goto), and `onMessage` hears what the frame's inspector says
8
+ // (a pick, a text edit, the tweaks manifest, a deck's slides). The page's own script cannot send those four: they come
9
+ // from the inspector (`src/server/http/artifact-inspect.ts`) down the line, and the app checks their shape and length
10
+ // (`checkPageMessage`) before it hands them on as data.
11
+ import { useLayoutEffect, useRef } from "preact/hooks";
6
12
  import { api, canSteer, insertIntoComposer, notify, store } from "./store.js";
7
13
 
8
14
  /** The most a follow-up's text and its selection (as JSON) may take, and how often a frame may send one. */
@@ -72,13 +78,337 @@ addEventListener(
72
78
  true,
73
79
  );
74
80
 
75
- /** The pages using the bridge now: `{ ref, handle(frame, data) }`. */
81
+ /** The pages using the bridge now: `{ ref, handle(frame, data), ready(frame) }`. */
76
82
  const hooks = new Set();
77
83
  /** The line to each frame's first page: a `MessagePort` that page gave us when it started. */
78
84
  const ports = new WeakMap();
85
+ /** What the app said to a frame before its page opened the line: the newest of each kind, sent once it does. */
86
+ const waiting = new WeakMap();
79
87
 
80
88
  const hookOf = (frame) => [...hooks].find((hook) => hook.ref.current === frame);
81
89
 
90
+ // ─── Design mode: the messages, and their checks ─────────────────────────────────────────────────────────────────────
91
+
92
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
93
+ const isText = (value, max) => typeof value === "string" && value.length <= max;
94
+ const isCount = (value, max) => Number.isInteger(value) && value >= 0 && value <= max;
95
+ const isNumber = (value) =>
96
+ typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= 1e7;
97
+ const clip = (value, max) => (typeof value === "string" ? value.slice(0, max) : undefined);
98
+
99
+ /** The most a tweak, a pin, and the like may take, as the page side keeps to them (`artifact-inspect.ts`). */
100
+ export const LIMITS = {
101
+ selector: 500,
102
+ pid: 200,
103
+ text: 200,
104
+ html: 1000,
105
+ style: 200,
106
+ edit: 2000,
107
+ knobs: 40,
108
+ options: 50,
109
+ tweakValues: 100,
110
+ pins: 100,
111
+ slides: 1000,
112
+ };
113
+ const STYLE_KEYS = [
114
+ "color",
115
+ "background-color",
116
+ "font-family",
117
+ "font-size",
118
+ "font-weight",
119
+ "line-height",
120
+ "padding",
121
+ "margin",
122
+ "border-radius",
123
+ "gap",
124
+ ];
125
+ const KNOB_TYPES = ["range", "color", "select", "toggle", "text"];
126
+ const TAG = /^[a-z][a-z0-9-]{0,39}$/i;
127
+ const CSS_VARIABLE = /^--[A-Za-z0-9_-]{1,78}$/;
128
+
129
+ /**
130
+ * A page's `Target`, rebuilt from the fields it may have: `{ pid?, selector, tag, text, html, rect, styles }`. Text and
131
+ * html are cut to their limits; a selector that is too long or a field of the wrong kind makes it null.
132
+ */
133
+ export function checkTarget(raw) {
134
+ if (
135
+ !isRecord(raw) ||
136
+ typeof raw.selector !== "string" ||
137
+ raw.selector === "" ||
138
+ raw.selector.length > LIMITS.selector ||
139
+ typeof raw.tag !== "string" ||
140
+ !TAG.test(raw.tag) ||
141
+ typeof raw.text !== "string" ||
142
+ typeof raw.html !== "string" ||
143
+ !isRecord(raw.rect) ||
144
+ !["x", "y", "width", "height"].every((key) => isNumber(raw.rect[key]))
145
+ ) {
146
+ return null;
147
+ }
148
+
149
+ const styles = {};
150
+
151
+ for (const key of STYLE_KEYS) {
152
+ if (isRecord(raw.styles) && typeof raw.styles[key] === "string") {
153
+ styles[key] = clip(raw.styles[key], LIMITS.style);
154
+ }
155
+ }
156
+
157
+ const target = {
158
+ selector: raw.selector,
159
+ tag: raw.tag.toLowerCase(),
160
+ text: clip(raw.text, LIMITS.text),
161
+ html: clip(raw.html, LIMITS.html),
162
+ rect: { x: raw.rect.x, y: raw.rect.y, width: raw.rect.width, height: raw.rect.height },
163
+ styles,
164
+ };
165
+
166
+ if (typeof raw.pid === "string" && raw.pid !== "") {
167
+ target.pid = clip(raw.pid, LIMITS.pid);
168
+ }
169
+
170
+ return target;
171
+ }
172
+
173
+ /** A knob of the page's tweaks manifest, or null: `{ name, label?, type, value, min?, max?, step?, unit?, options? }`. */
174
+ function checkKnob(raw) {
175
+ if (
176
+ !isRecord(raw) ||
177
+ !isText(raw.name, 80) ||
178
+ raw.name === "" ||
179
+ !KNOB_TYPES.includes(raw.type) ||
180
+ !(isText(raw.value, LIMITS.style) || typeof raw.value === "boolean" || isNumber(raw.value))
181
+ ) {
182
+ return null;
183
+ }
184
+
185
+ const knob = { name: raw.name, type: raw.type, value: raw.value };
186
+
187
+ if (isText(raw.label, 80)) {
188
+ knob.label = raw.label;
189
+ }
190
+
191
+ for (const key of ["min", "max", "step"]) {
192
+ if (isNumber(raw[key])) {
193
+ knob[key] = raw[key];
194
+ }
195
+ }
196
+
197
+ if (isText(raw.unit, 10)) {
198
+ knob.unit = raw.unit;
199
+ }
200
+
201
+ if (Array.isArray(raw.options)) {
202
+ knob.options = raw.options.filter((option) => isText(option, 80)).slice(0, LIMITS.options);
203
+ }
204
+
205
+ return knob;
206
+ }
207
+
208
+ /**
209
+ * What the frame's inspector said, as clean data the app may use, or null when it is not one of the four messages or
210
+ * has the wrong shape. A new object is built from the known fields only, whatever else the message had.
211
+ */
212
+ export function checkPageMessage(data) {
213
+ if (!isRecord(data)) {
214
+ return null;
215
+ }
216
+
217
+ switch (data.type) {
218
+ case "pocket-picked": {
219
+ const target = checkTarget(data.target);
220
+
221
+ return target && { type: data.type, target };
222
+ }
223
+
224
+ case "pocket-text-edited": {
225
+ const target = checkTarget(data.target);
226
+
227
+ return target && isText(data.before, LIMITS.edit) && isText(data.after, LIMITS.edit)
228
+ ? { type: data.type, target, before: data.before, after: data.after }
229
+ : null;
230
+ }
231
+
232
+ case "pocket-tweaks": {
233
+ if (!Array.isArray(data.knobs)) {
234
+ return null;
235
+ }
236
+
237
+ const seen = new Set();
238
+ const knobs = data.knobs
239
+ .slice(0, LIMITS.knobs)
240
+ .map(checkKnob)
241
+ .filter((knob) => {
242
+ if (knob === null || seen.has(knob.name)) {
243
+ return false;
244
+ }
245
+
246
+ seen.add(knob.name);
247
+
248
+ return true;
249
+ });
250
+
251
+ return { type: data.type, knobs };
252
+ }
253
+
254
+ case "pocket-deck":
255
+ return isCount(data.slides, LIMITS.slides) &&
256
+ isCount(data.current, Math.max(data.slides - 1, 0))
257
+ ? { type: data.type, slides: data.slides, current: data.current }
258
+ : null;
259
+
260
+ default:
261
+ return null;
262
+ }
263
+ }
264
+
265
+ /** The one reason a message to a page is refused, or a clean copy of it: `{ message }` or `{ error }`. */
266
+ export function checkAppMessage(raw) {
267
+ if (!isRecord(raw)) {
268
+ return { error: "A message is an object" };
269
+ }
270
+
271
+ switch (raw.type) {
272
+ case "pocket-inspect":
273
+ case "pocket-edit-text":
274
+ return typeof raw.on === "boolean"
275
+ ? { message: { type: raw.type, on: raw.on } }
276
+ : { error: "`on` is true or false" };
277
+
278
+ case "pocket-tweak-set": {
279
+ if (!isRecord(raw.values)) {
280
+ return { error: "`values` is an object" };
281
+ }
282
+
283
+ const names = Object.keys(raw.values);
284
+
285
+ if (names.length > LIMITS.tweakValues) {
286
+ return { error: `At most ${LIMITS.tweakValues} values` };
287
+ }
288
+
289
+ const values = {};
290
+
291
+ for (const name of names) {
292
+ const value = raw.values[name];
293
+
294
+ if (
295
+ name === "" ||
296
+ name.length > 80 ||
297
+ (name.startsWith("--") && !CSS_VARIABLE.test(name)) ||
298
+ !(
299
+ value === null ||
300
+ isText(value, LIMITS.style) ||
301
+ typeof value === "boolean" ||
302
+ isNumber(value)
303
+ )
304
+ ) {
305
+ return { error: `Not a tweak value: ${name.slice(0, 40)}` };
306
+ }
307
+
308
+ values[name] = value;
309
+ }
310
+
311
+ return { message: { type: raw.type, values } };
312
+ }
313
+
314
+ case "pocket-highlight": {
315
+ if (!Array.isArray(raw.targets) || raw.targets.length > LIMITS.pins) {
316
+ return { error: `\`targets\` is a list of up to ${LIMITS.pins}` };
317
+ }
318
+
319
+ const targets = [];
320
+
321
+ for (const target of raw.targets) {
322
+ if (
323
+ !isRecord(target) ||
324
+ !isText(target.selector, LIMITS.selector) ||
325
+ (target.pid !== undefined && !isText(target.pid, LIMITS.pid)) ||
326
+ !(
327
+ target.label === undefined ||
328
+ isText(target.label, 8) ||
329
+ isCount(target.label, 99_999)
330
+ )
331
+ ) {
332
+ return { error: "A pin needs a selector (and a short label, if any)" };
333
+ }
334
+
335
+ const pin = { selector: target.selector };
336
+
337
+ if (target.pid !== undefined) {
338
+ pin.pid = target.pid;
339
+ }
340
+
341
+ if (target.label !== undefined) {
342
+ pin.label = target.label;
343
+ }
344
+
345
+ targets.push(pin);
346
+ }
347
+
348
+ return { message: { type: raw.type, targets } };
349
+ }
350
+
351
+ case "pocket-goto":
352
+ return isCount(raw.slide, LIMITS.slides)
353
+ ? { message: { type: raw.type, slide: raw.slide } }
354
+ : { error: "`slide` is a number from 0" };
355
+
356
+ default:
357
+ return { error: "Not a message for a page" };
358
+ }
359
+ }
360
+
361
+ /** A message to a page that waits for its line keeps only the newest of its kind; tweak values add up. */
362
+ function queue(frame, message) {
363
+ const held = waiting.get(frame) ?? new Map();
364
+ const before = held.get(message.type);
365
+
366
+ if (message.type === "pocket-tweak-set" && before) {
367
+ message = { ...message, values: { ...before.values, ...message.values } };
368
+ }
369
+
370
+ held.delete(message.type);
371
+ held.set(message.type, message);
372
+ waiting.set(frame, held);
373
+ }
374
+
375
+ /**
376
+ * Say `message` to the page in `frame` (a design message: `checkAppMessage`). True when it went down the line, or waits
377
+ * for the line to open (the frame has not loaded a page yet); false when it is refused or nobody can hear it.
378
+ */
379
+ export function sendToFrame(frame, message, { wait = true } = {}) {
380
+ const { message: clean } = checkAppMessage(message);
381
+ const hook = frame && hookOf(frame);
382
+
383
+ if (!clean || !hook) {
384
+ return false;
385
+ }
386
+
387
+ if (
388
+ (clean.type === "pocket-inspect" || clean.type === "pocket-edit-text") &&
389
+ clean.on &&
390
+ !canSteer()
391
+ ) {
392
+ return false;
393
+ }
394
+
395
+ const port = ports.get(frame);
396
+
397
+ if (port) {
398
+ port.postMessage(clean);
399
+
400
+ return true;
401
+ }
402
+
403
+ if (!wait || (loads.get(frame) ?? 0) > 0) {
404
+ return false;
405
+ }
406
+
407
+ queue(frame, clean);
408
+
409
+ return true;
410
+ }
411
+
82
412
  // The first page in a frame says hello as it starts (`ARTIFACT_BRIDGE` in `src/server/http/artifacts.ts`) and hands over
83
413
  // one end of a channel. That channel is the only way in: a page the frame goes on to gets no line, so it is not heard,
84
414
  // and an answer goes down the line, so it reaches no page but the first. Only a frame that is still on its first load
@@ -108,125 +438,219 @@ addEventListener("message", (event) => {
108
438
  hookOf(frame)?.handle(frame, data);
109
439
  }
110
440
  };
441
+
442
+ // What was said before the line opened goes first; then the workspace may say the rest.
443
+ for (const held of waiting.get(frame)?.values() ?? []) {
444
+ port.postMessage(held);
445
+ }
446
+
447
+ waiting.delete(frame);
448
+ hook.ready(frame);
111
449
  });
112
450
 
451
+ /** How many messages from one page the app hears in a second: the inspector sends when a person acts, so this is plenty. */
452
+ const RATE = 60;
453
+
113
454
  /**
114
455
  * Hear the first page of the frame `ref`: follow-ups always, saved state only for an artifact (`artifact`, its id).
115
456
  * `source` names the page in the box ("the artifact “Plan”"). `enabled` is false for a page that has no bridge (SVG,
116
457
  * Markdown). The page asks with `parent.postMessage`, as a page does, but the frame page it starts with (`ARTIFACT_BRIDGE`)
117
458
  * takes the call, checks that a person tapped the page (a real tap, which the page cannot make), and sends it down the
118
459
  * line. A follow-up so reaches us only after a tap; a frame inside PiP's panel adds nothing to the session's box.
460
+ *
461
+ * Design mode (stream B) adds, in `settings` (read each time, so they may change):
462
+ * - `onMessage(message, frame)`: a checked `pocket-picked`, `pocket-text-edited`, `pocket-tweaks`, or `pocket-deck`
463
+ * (`checkPageMessage`). Not for a viewer's frame in PiP's panel, nor once the session is another.
464
+ * - `onReady(frame)`: the frame's page opened its line. Its page has just started: say the modes again.
465
+ *
466
+ * Returns `{ send(message), ready(), detach() }`. `send` is `sendToFrame` for this frame (see there); `ready` is true
467
+ * once the page opened its line. Use it in a component with `useArtifactBridge`.
119
468
  */
120
- export function useArtifactBridge(ref, { artifact = null, source, enabled = true }) {
121
- useLayoutEffect(() => {
122
- if (!enabled) {
123
- return undefined;
469
+ export function attachBridge(ref, settings = {}) {
470
+ const { artifact = null, source = "the page" } = settings;
471
+ const conversationId = store.state.conversationId;
472
+ let lastFollowUp = 0;
473
+ let windowStart = 0;
474
+ let heard = 0;
475
+
476
+ const reply = (frame, fields) => ports.get(frame)?.postMessage(fields);
477
+
478
+ const followUp = (frame, data) => {
479
+ const answer = (fields) => reply(frame, { type: "pocket-follow-up", ...fields });
480
+ const problem = followUpProblem(data);
481
+ const now = Date.now();
482
+
483
+ if (problem !== null) {
484
+ return answer({ ok: false, error: problem });
124
485
  }
125
486
 
126
- const conversationId = store.state.conversationId;
127
- let lastFollowUp = 0;
487
+ if (store.state.conversationId !== conversationId || frame.closest(".pip-panel")) {
488
+ return answer({ ok: false, error: "Not in this session" });
489
+ }
128
490
 
129
- const reply = (frame, fields) => ports.get(frame)?.postMessage(fields);
491
+ if (now - lastFollowUp < FOLLOW_UP_MS) {
492
+ return answer({ ok: false, error: "Too soon" });
493
+ }
130
494
 
131
- const followUp = (frame, data) => {
132
- const answer = (fields) => reply(frame, { type: "pocket-follow-up", ...fields });
133
- const problem = followUpProblem(data);
134
- const now = Date.now();
495
+ lastFollowUp = now;
135
496
 
136
- if (problem !== null) {
137
- return answer({ ok: false, error: problem });
138
- }
497
+ if (!canSteer()) {
498
+ notify("info", `${capital(source)} offered a message, but you can only view here.`);
139
499
 
140
- if (store.state.conversationId !== conversationId || frame.closest(".pip-panel")) {
141
- return answer({ ok: false, error: "Not in this session" });
142
- }
500
+ return answer({ ok: false, error: "View only" });
501
+ }
502
+
503
+ insertIntoComposer(followUpText(data.text.trim(), data.selection, source));
504
+ notify("info", `${capital(source)} added a message to your box: read it, then send it.`);
505
+ answer({ ok: true });
506
+ };
507
+
508
+ const state = async (frame, data) => {
509
+ const requestId = data.requestId;
143
510
 
144
- if (now - lastFollowUp < FOLLOW_UP_MS) {
145
- return answer({ ok: false, error: "Too soon" });
511
+ const answer = (fields) => {
512
+ if (ref.current === frame) {
513
+ reply(frame, { type: "pocket-state", requestId, ...fields });
146
514
  }
515
+ };
516
+
517
+ if (!REQUEST_ID.test(String(requestId ?? ""))) {
518
+ return;
519
+ }
147
520
 
148
- lastFollowUp = now;
521
+ if (artifact === null) {
522
+ return answer({ ok: false, error: "Only a saved artifact keeps state" });
523
+ }
149
524
 
150
- if (!canSteer()) {
151
- notify("info", `${capital(source)} offered a message, but you can only view here.`);
525
+ if (store.state.conversationId !== conversationId) {
526
+ return answer({ ok: false, error: "Not in this session" });
527
+ }
152
528
 
153
- return answer({ ok: false, error: "View only" });
529
+ // The same for a get and a set: a schema is a string, or none.
530
+ if (data.schema !== undefined && data.schema !== null && typeof data.schema !== "string") {
531
+ return answer({ ok: false, error: "A schema is a string" });
532
+ }
533
+
534
+ const path = `c/${conversationId}/artifact-state/${encodeURIComponent(artifact)}`;
535
+
536
+ try {
537
+ if (data.type === "pocket-state-get") {
538
+ const query = data.schema ? `?schema=${encodeURIComponent(data.schema)}` : "";
539
+ const result = await api(`${path}${query}`);
540
+
541
+ answer({ ok: true, state: result.state, at: result.at });
542
+ } else {
543
+ const result = await api(path, {
544
+ state: data.state ?? null,
545
+ schema: data.schema ?? undefined,
546
+ });
547
+
548
+ answer({ ok: true, at: result.at });
154
549
  }
550
+ } catch (error) {
551
+ answer({ ok: false, error: error.message ?? String(error) });
552
+ }
553
+ };
155
554
 
156
- insertIntoComposer(followUpText(data.text.trim(), data.selection, source));
157
- notify(
158
- "info",
159
- `${capital(source)} added a message to your box: read it, then send it.`,
160
- );
161
- answer({ ok: true });
162
- };
555
+ const design = (frame, data) => {
556
+ const now = Date.now();
163
557
 
164
- const state = async (frame, data) => {
165
- const requestId = data.requestId;
558
+ if (now - windowStart > 1000) {
559
+ windowStart = now;
560
+ heard = 0;
561
+ }
166
562
 
167
- const answer = (fields) => {
168
- if (ref.current === frame) {
169
- reply(frame, { type: "pocket-state", requestId, ...fields });
170
- }
171
- };
563
+ heard += 1;
172
564
 
173
- if (!REQUEST_ID.test(String(requestId ?? ""))) {
174
- return;
175
- }
565
+ const message = heard <= RATE ? checkPageMessage(data) : null;
176
566
 
177
- if (artifact === null) {
178
- return answer({ ok: false, error: "Only a saved artifact keeps state" });
179
- }
567
+ if (
568
+ message &&
569
+ store.state.conversationId === conversationId &&
570
+ !frame.closest(".pip-panel")
571
+ ) {
572
+ settings.onMessage?.(message, frame);
573
+ }
574
+ };
180
575
 
181
- if (store.state.conversationId !== conversationId) {
182
- return answer({ ok: false, error: "Not in this session" });
576
+ const hook = {
577
+ ref,
578
+ handle: (frame, data) => {
579
+ if (data.type === "pocket-follow-up") {
580
+ followUp(frame, data);
581
+ } else if (data.type === "pocket-state-get" || data.type === "pocket-state-set") {
582
+ void state(frame, data);
583
+ } else {
584
+ design(frame, data);
183
585
  }
184
-
185
- // The same for a get and a set: a schema is a string, or none.
186
- if (
187
- data.schema !== undefined &&
188
- data.schema !== null &&
189
- typeof data.schema !== "string"
190
- ) {
191
- return answer({ ok: false, error: "A schema is a string" });
586
+ },
587
+ ready: (frame) => {
588
+ if (store.state.conversationId === conversationId) {
589
+ settings.onReady?.(frame);
192
590
  }
591
+ },
592
+ };
193
593
 
194
- const path = `c/${conversationId}/artifact-state/${encodeURIComponent(artifact)}`;
594
+ hooks.add(hook);
195
595
 
196
- try {
197
- if (data.type === "pocket-state-get") {
198
- const query = data.schema ? `?schema=${encodeURIComponent(data.schema)}` : "";
199
- const result = await api(`${path}${query}`);
596
+ return {
597
+ send: (message) => sendToFrame(ref.current, message),
598
+ ready: () => Boolean(ref.current && ports.has(ref.current)),
599
+ detach: () => hooks.delete(hook),
600
+ };
601
+ }
200
602
 
201
- answer({ ok: true, state: result.state, at: result.at });
202
- } else {
203
- const result = await api(path, {
204
- state: data.state ?? null,
205
- schema: data.schema ?? undefined,
206
- });
603
+ /**
604
+ * `attachBridge` for a component: `useArtifactBridge(ref, { artifact, source, enabled, onMessage, onReady })`. It
605
+ * returns one `{ send, ready }` that stays the same between renders; `send` says no (false) while `enabled` is false.
606
+ * The callbacks may change between renders; the bridge is made again only when `artifact`, `source`, or `enabled` do.
607
+ */
608
+ export function useArtifactBridge(ref, settings) {
609
+ const live = useRef({});
610
+ const control = useRef(null);
207
611
 
208
- answer({ ok: true, at: result.at });
209
- }
210
- } catch (error) {
211
- answer({ ok: false, error: error.message ?? String(error) });
212
- }
213
- };
612
+ Object.assign(live.current, settings);
214
613
 
215
- const hook = {
216
- ref,
217
- handle: (frame, data) => {
218
- if (data.type === "pocket-follow-up") {
219
- followUp(frame, data);
220
- } else if (data.type === "pocket-state-get" || data.type === "pocket-state-set") {
221
- void state(frame, data);
222
- }
614
+ if (control.current === null) {
615
+ const attached = { current: null };
616
+
617
+ control.current = {
618
+ attached,
619
+ api: {
620
+ send: (message) => attached.current?.send(message) ?? false,
621
+ ready: () => attached.current?.ready() ?? false,
223
622
  },
224
623
  };
624
+ }
625
+
626
+ const { artifact = null, source, enabled = true } = settings;
225
627
 
226
- hooks.add(hook);
628
+ useLayoutEffect(() => {
629
+ if (!enabled) {
630
+ return undefined;
631
+ }
632
+
633
+ // The settings are read live: a new callback needs no new line.
634
+ const bridge = attachBridge(ref, {
635
+ artifact,
636
+ source,
637
+ get onMessage() {
638
+ return live.current.onMessage;
639
+ },
640
+ get onReady() {
641
+ return live.current.onReady;
642
+ },
643
+ });
644
+
645
+ control.current.attached.current = bridge;
227
646
 
228
- return () => hooks.delete(hook);
647
+ return () => {
648
+ control.current.attached.current = null;
649
+ bridge.detach();
650
+ };
229
651
  }, [artifact, source, enabled]);
652
+
653
+ return control.current.api;
230
654
  }
231
655
 
232
656
  const capital = (text) => text.charAt(0).toUpperCase() + text.slice(1);