@botiverse/porthole 0.12.0 → 0.13.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 (47) hide show
  1. package/dist/bridge/bridge.d.ts +8 -1
  2. package/dist/bridge/bridge.js +7 -0
  3. package/dist/bridge/unseen.d.ts +8 -0
  4. package/dist/bridge/unseen.js +17 -0
  5. package/dist/check/files.js +14 -10
  6. package/dist/check/lint.js +1 -1
  7. package/dist/check/page-source.js +1 -1
  8. package/dist/check/scroll.d.ts +29 -13
  9. package/dist/check/scroll.js +74 -18
  10. package/dist/config/capabilities.d.ts +16 -3
  11. package/dist/config/capabilities.js +1 -0
  12. package/dist/conformance/harness-source.js +1 -1
  13. package/dist/guide/runtime.js +1 -1
  14. package/dist/host/create-host.js +27 -0
  15. package/dist/host/types.d.ts +15 -0
  16. package/dist/index.d.ts +1 -0
  17. package/dist/index.js +1 -0
  18. package/dist/platform/focus-guard.d.ts +143 -0
  19. package/dist/platform/focus-guard.js +445 -0
  20. package/dist/platform/types.d.ts +18 -0
  21. package/dist/platform/web.js +22 -0
  22. package/dist/react/frame.d.ts +8 -0
  23. package/dist/react/frame.js +4 -0
  24. package/dist/runtime/requests.js +34 -12
  25. package/dist/runtime/types.generated.js +1 -1
  26. package/docs/ADOPTING.md +85 -6
  27. package/docs/DECISIONS.md +355 -5
  28. package/docs/DESIGN.md +9 -2
  29. package/docs/THREAT_MODEL.md +121 -29
  30. package/package.json +1 -1
  31. package/src/bridge/bridge.ts +17 -1
  32. package/src/bridge/unseen.ts +24 -0
  33. package/src/check/files.ts +14 -10
  34. package/src/check/lint.ts +1 -1
  35. package/src/check/scroll.ts +106 -38
  36. package/src/config/capabilities.ts +16 -3
  37. package/src/guide/runtime.ts +1 -1
  38. package/src/host/create-host.ts +29 -0
  39. package/src/host/types.ts +13 -0
  40. package/src/index.ts +1 -0
  41. package/src/platform/focus-guard.ts +572 -0
  42. package/src/platform/types.ts +17 -0
  43. package/src/platform/web.ts +22 -0
  44. package/src/react/frame.tsx +10 -0
  45. package/src/runtime/requests.ts +36 -14
  46. package/src/runtime/types.generated.ts +1 -1
  47. package/types/runtime/v1/comments.d.ts +8 -4
@@ -0,0 +1,445 @@
1
+ /**
2
+ * The focus guard (P109): a display's frame can move the keyboard into itself whenever it likes
3
+ * (`element.focus()` in its own realm; on Chromium and WebKit with no gesture at all), and what the
4
+ * person goes on typing into the host's composer or chat box then goes to the page. Porthole can't
5
+ * stop the call, which runs in the content's realm, but the host's page can undo it: when focus
6
+ * leaves one of its text fields for a display's frame and the person didn't move it there, focus
7
+ * goes back once the engine has finished moving it, the guard watches that it stays back, and the
8
+ * display hears `focusTaken`; a display whose frame keeps doing it is stopped (`createHost`).
9
+ *
10
+ * What the host's page can see of a move into a frame, measured on Chromium, WebKit and Firefox
11
+ * (P109): Chromium and WebKit blur the host's window as it happens, and a press on the frame (a
12
+ * click, a tap, held or not) leaves the frame element `:active` then; a Tab is the host's own
13
+ * keydown just before. Firefox doesn't blur the window and shows no `:active` (a focusout on the
14
+ * field was seen in one review's runs, not in another's): its `document.activeElement` changes,
15
+ * which the guard reads at each animation frame while a frame is guarded, and the pointer over the
16
+ * frame (`:hover`, `pointerover`) is all it can tell of a press. A page that takes focus back on
17
+ * its own blur (which a take-back fires) leaves Firefox's focus on nothing (`<body>`) or in the
18
+ * frame again (the review of the guard, GK-1): the guard keeps watching after each take-back and
19
+ * counts one that didn't hold. Every engine keeps a gesture's transient activation for 5 s
20
+ * (measured: 5.04 to 5.10 s).
21
+ */
22
+ /** How long the person's Tab counts as moving focus (the move follows its keydown at once). */
23
+ export const TAB_MS = 1_000;
24
+ /**
25
+ * How long transient activation lasts after a gesture (measured: 5 s on all three engines): a
26
+ * host page with activation and no gesture of its own for longer had one in a frame.
27
+ */
28
+ export const ACTIVATION_SPAN_MS = 5_000;
29
+ /** The person is typing: a key on the host's page within this long. */
30
+ export const TYPING_MS = 1_000;
31
+ /**
32
+ * After a take-back, the guard keeps watching (each animation frame) until focus has stayed in the
33
+ * text field this long: a page that takes it again at once (on its own blur, which the take-back
34
+ * fires) is caught as it does, on Firefox too (P109, after the review of the guard: GK-1).
35
+ */
36
+ export const HELD_MS = 300;
37
+ /** A take-back that hasn't put focus back in the field after this long failed: counted, and tried again. */
38
+ export const GIVE_BACK_MS = 50;
39
+ /**
40
+ * A frame that holds focus isn't the person's for this long after they press the host's page: the
41
+ * press gives the page activation before focus leaves the frame (on Firefox, a move between
42
+ * processes), and a call the frame sends in between would borrow it.
43
+ */
44
+ export const HOST_PRESS_MS = 1_000;
45
+ /**
46
+ * When a display is stopped for taking the keyboard (P109): focus given back can't stop its frame
47
+ * calling `focus()` again (nothing the host sets on the frame does, `inert` included: measured),
48
+ * and each try leaves it the keys typed until focus is back. So three undone moves within 10 s
49
+ * that came while the person typed on the page or that kept focus from going back (a take-back that
50
+ * failed: the keys then go to the frame, and the page sees no typing to count), or five at all
51
+ * within 2 s, stop it. A person's own move never fails a take-back.
52
+ */
53
+ export const TAKES = {
54
+ typing: { most: 3, withinMs: 10_000 },
55
+ any: { most: 5, withinMs: 2_000 },
56
+ };
57
+ /**
58
+ * Whether the person moved focus into the frame themselves:
59
+ * - the host did (`DisplayHandle.focus()`);
60
+ * - by the keyboard: their last key on the host's page was Tab (or Shift+Tab), just now;
61
+ * - by a press on the frame: where the engine tells the move as it happens (Chromium, WebKit),
62
+ * the frame element is `:active`; where it doesn't (Firefox), the pointer is over the frame and
63
+ * came over it after the text field got focus and after the person last typed in the host's page
64
+ * (a page can't move the pointer; a composer that opened beside the frame while the pointer
65
+ * rested over it, and a person typing with it there, keep their keys);
66
+ * - by a gesture the host's own events don't explain: the host's page has transient activation,
67
+ * and for longer than activation lasts it saw no gesture of its own and the text field has had
68
+ * focus, so the person pressed or activated something in a frame since (an assistive
69
+ * technology's activation, which moves no pointer and sends the host no key, is one). The
70
+ * gesture that opened a composer (a selection in the frame, `selected`) is older than the
71
+ * composer's focus, and doesn't count.
72
+ * Anything else is the page's: focus goes back.
73
+ */
74
+ export function personMoved(move) {
75
+ if (move.hostMoved) {
76
+ return true;
77
+ }
78
+ if (move.lastKey !== null && move.lastKey.key === "Tab" && move.now - move.lastKey.at <= TAB_MS) {
79
+ return true;
80
+ }
81
+ if (move.seen ? move.pressed : move.over && move.overSince > Math.max(move.typedAt, move.focusedAt)) {
82
+ return true;
83
+ }
84
+ return (move.activation === true &&
85
+ move.now - Math.max(move.gestureAt, move.focusedAt) > ACTIVATION_SPAN_MS);
86
+ }
87
+ /** Keys that type nothing on their own: they don't count as typing (a gesture still). */
88
+ const MODIFIERS = new Set(["Shift", "Control", "Alt", "Meta", "AltGraph", "CapsLock", "Fn"]);
89
+ /** The `<input>` types that take typed text (an unknown type is `text`). */
90
+ const TEXT_INPUTS = new Set(["text", "search", "url", "tel", "email", "password", "number"]);
91
+ /** Whether `element` takes the person's typed text: a text field, a text area, an editable region. */
92
+ export function takesText(element) {
93
+ if (element === null) {
94
+ return false;
95
+ }
96
+ switch (element.localName) {
97
+ case "textarea":
98
+ return true;
99
+ case "input":
100
+ return TEXT_INPUTS.has(element.type);
101
+ default:
102
+ return element.isContentEditable ?? false;
103
+ }
104
+ }
105
+ /** The element that has focus, inside open shadow roots too. */
106
+ function deepActive(document) {
107
+ let active = document.activeElement;
108
+ for (let inner = active?.shadowRoot?.activeElement; inner !== null && inner !== undefined; inner = active?.shadowRoot?.activeElement) {
109
+ active = inner;
110
+ }
111
+ return active;
112
+ }
113
+ const guards = new WeakMap();
114
+ /** The guard for `view`'s page, made on first use. */
115
+ export function focusGuard(view) {
116
+ const existing = guards.get(view);
117
+ if (existing !== undefined) {
118
+ return existing;
119
+ }
120
+ const document = view.document;
121
+ const frames = new Map();
122
+ const now = () => view.performance.now();
123
+ let known = deepActive(document);
124
+ let focusedAt = now();
125
+ let lastKey = null;
126
+ let typedAt = -Infinity;
127
+ let gestureAt = -Infinity;
128
+ let pressAt = -Infinity;
129
+ /** When focus last went into a guarded frame, and whether the person moved it there. */
130
+ let enteredAt = -Infinity;
131
+ let earned = false;
132
+ /** The text field the person last pressed, when, and what had focus as they pressed it. */
133
+ let pressed = null;
134
+ let hostMove = null;
135
+ let polling = 0;
136
+ /**
137
+ * A take-back in progress: the field focus goes back to, the frame it came from, when focus was
138
+ * last given back, and since when it has stayed in the field. Ends once it has stayed `HELD_MS`,
139
+ * the person moves focus somewhere of their own, or the field or frame is gone.
140
+ */
141
+ let contest = null;
142
+ const activation = () => {
143
+ try {
144
+ const state = view.navigator
145
+ .userActivation;
146
+ return state === undefined ? undefined : state.isActive;
147
+ }
148
+ catch {
149
+ return undefined;
150
+ }
151
+ };
152
+ /** What the person's move would need, read now: see `personMoved`. */
153
+ const judge = (frame, guarded, seen, at) => {
154
+ const moved = personMoved({
155
+ now: at,
156
+ seen,
157
+ pressed: frame.matches(":active"),
158
+ over: frame.matches(":hover"),
159
+ overSince: guarded.overSince,
160
+ lastKey,
161
+ typedAt,
162
+ focusedAt,
163
+ gestureAt,
164
+ activation: activation(),
165
+ hostMoved: hostMove !== null && hostMove.frame === frame && at - hostMove.at <= TAB_MS,
166
+ });
167
+ hostMove = null;
168
+ return moved;
169
+ };
170
+ /**
171
+ * Focus goes back to `field` once the engine has finished the move: given back inside its blur
172
+ * it stays with the frame on Chromium and WebKit, and Firefox takes it back only from a frame
173
+ * that was blurred first (measured). Unless the person has since put focus somewhere of their own.
174
+ */
175
+ const giveBack = (field, frame) => {
176
+ view.setTimeout(() => {
177
+ const current = deepActive(document);
178
+ if (field.isConnected &&
179
+ (current === frame || current === null || current === document.body)) {
180
+ frame.blur();
181
+ field.focus({ preventScroll: true });
182
+ }
183
+ }, 0);
184
+ };
185
+ /** A move the guard undoes: focus goes back, the display hears it, and the guard keeps watching. */
186
+ const takeBack = (field, frame, guarded, at, failed) => {
187
+ // Until it is back, the field counts as the page's focus, so a move that didn't take is seen.
188
+ known = field;
189
+ focusedAt = at;
190
+ contest = { field, frame, guarded, gaveAt: at, heldSince: null };
191
+ giveBack(field, frame);
192
+ schedule();
193
+ const take = { typing: at - typedAt <= TYPING_MS, failed };
194
+ for (const taken of guarded.taken) {
195
+ taken(take);
196
+ }
197
+ };
198
+ /**
199
+ * While a take-back is in progress: whether focus stayed in the field, or the frame has it again
200
+ * (or it landed on nothing), which is the page's doing unless the person moved it there.
201
+ */
202
+ const watch = (seen, active, at) => {
203
+ const watched = contest;
204
+ if (watched === null) {
205
+ return false;
206
+ }
207
+ const { field, frame, guarded } = watched;
208
+ if (!field.isConnected || pressAt > watched.gaveAt) {
209
+ // Gone, or the person pressed the page since: theirs to place focus now.
210
+ contest = null;
211
+ return false;
212
+ }
213
+ if (!frames.has(frame)) {
214
+ // The frame was removed mid-fight (its display stopped): Firefox may leave focus on nothing
215
+ // once the focused frame goes. Back into the field, for a moment after.
216
+ if ((active === null || active === document.body) && at - watched.gaveAt <= HELD_MS) {
217
+ field.focus({ preventScroll: true });
218
+ return true;
219
+ }
220
+ contest = null;
221
+ return false;
222
+ }
223
+ if (active === field) {
224
+ watched.heldSince ??= at;
225
+ if (at - watched.heldSince >= HELD_MS) {
226
+ contest = null;
227
+ }
228
+ known = field;
229
+ return true;
230
+ }
231
+ const lost = active === frame || active === null || active === document.body;
232
+ if (!lost) {
233
+ // Somewhere else of the person's (another field, a button, another frame): judged as any.
234
+ contest = null;
235
+ return false;
236
+ }
237
+ if (active === frame && judge(frame, guarded, seen, at)) {
238
+ contest = null;
239
+ known = frame;
240
+ enteredAt = at;
241
+ earned = true;
242
+ return true;
243
+ }
244
+ // Taken again once it was back (within `HELD_MS`), or not back yet after `GIVE_BACK_MS`: a
245
+ // take-back that failed, given again and counted.
246
+ if (watched.heldSince !== null || at - watched.gaveAt >= GIVE_BACK_MS) {
247
+ takeBack(field, frame, guarded, at, true);
248
+ }
249
+ return true;
250
+ };
251
+ /** Judges a change of focus since the last look: `seen` when the engine told it (a blur). */
252
+ const look = (seen) => {
253
+ const active = deepActive(document);
254
+ const at = now();
255
+ if (watch(seen, active, at)) {
256
+ return;
257
+ }
258
+ const was = known;
259
+ // The person pressed a text field and focus is on nothing: on Firefox, a page that takes focus
260
+ // as they press, or takes it back on its blur with a gesture of theirs, leaves it there
261
+ // (measured, on a slow machine too), and their keys are lost. Into the field, once: as a
262
+ // take-back the page failed if a frame had focus as they pressed, else simply.
263
+ const press = pressed;
264
+ if (press !== null &&
265
+ (active === null || active === document.body) &&
266
+ at - press.at <= HELD_MS &&
267
+ press.field.isConnected) {
268
+ pressed = null;
269
+ const from = press.from ?? was;
270
+ const blamed = from === null ? undefined : frames.get(from);
271
+ if (blamed === undefined) {
272
+ known = active;
273
+ press.field.focus({ preventScroll: true });
274
+ }
275
+ else {
276
+ takeBack(press.field, from, blamed, at, true);
277
+ }
278
+ return;
279
+ }
280
+ known = active;
281
+ if (active === was || active === null) {
282
+ return;
283
+ }
284
+ const entered = frames.get(active);
285
+ if (entered !== undefined) {
286
+ // From a text field it is judged below; from anything else it is let be, but only the
287
+ // person's own move makes the frame theirs for a gesture gate (`focused`).
288
+ enteredAt = at;
289
+ earned = takesText(was) || judge(active, entered, seen, at);
290
+ }
291
+ // Into a text field from a display's frame (the person pressed the composer while the frame
292
+ // had focus): watched as a take-back is, since a page that takes focus back on its own blur
293
+ // leaves it on nothing on Firefox (measured), where the keys are lost to the page's doing.
294
+ const left = was === null ? undefined : frames.get(was);
295
+ if (left !== undefined && takesText(active)) {
296
+ contest = {
297
+ field: active,
298
+ frame: was,
299
+ guarded: left,
300
+ gaveAt: at,
301
+ heldSince: at,
302
+ };
303
+ return;
304
+ }
305
+ const guarded = frames.get(active);
306
+ if (guarded === undefined || !takesText(was) || !was.isConnected) {
307
+ return;
308
+ }
309
+ const frame = active;
310
+ if (judge(frame, guarded, seen, at)) {
311
+ return;
312
+ }
313
+ takeBack(was, frame, guarded, at, false);
314
+ };
315
+ /**
316
+ * Firefox moves focus into a frame without a word to the host's page: while a frame is guarded,
317
+ * look at each animation frame (one read of the focused element), so the guard knows where focus
318
+ * is when it next leaves a text field, or comes into one from a frame.
319
+ */
320
+ const poll = () => {
321
+ polling = 0;
322
+ look(false);
323
+ schedule();
324
+ };
325
+ const schedule = () => {
326
+ if (polling === 0 && (frames.size > 0 || contest !== null)) {
327
+ polling = view.requestAnimationFrame(poll);
328
+ }
329
+ };
330
+ const gesture = () => {
331
+ gestureAt = now();
332
+ };
333
+ const press = (event) => {
334
+ pressAt = now();
335
+ gestureAt = pressAt;
336
+ const target = event.composedPath()[0];
337
+ pressed =
338
+ target instanceof Element && takesText(target)
339
+ ? { field: target, at: pressAt, from: deepActive(document) }
340
+ : null;
341
+ };
342
+ view.addEventListener("keydown", (event) => {
343
+ const at = now();
344
+ gestureAt = at;
345
+ lastKey = { key: event.key, at };
346
+ if (event.key !== "Tab" && !MODIFIERS.has(event.key)) {
347
+ typedAt = at;
348
+ }
349
+ }, true);
350
+ // A click too (an assistive technology's click on the host's own UI dispatches no press), and
351
+ // text that comes without a key (dictation, a paste, an input method): typing all the same.
352
+ for (const type of ["pointerup", "touchend", "click"]) {
353
+ view.addEventListener(type, gesture, true);
354
+ }
355
+ for (const type of ["pointerdown", "mousedown"]) {
356
+ view.addEventListener(type, press, true);
357
+ }
358
+ view.addEventListener("input", () => {
359
+ typedAt = now();
360
+ gestureAt = typedAt;
361
+ }, true);
362
+ // Focus moving within the page: what had it, for the next move out of a text field.
363
+ document.addEventListener("focusin", () => {
364
+ focusedAt = now();
365
+ look(false);
366
+ schedule();
367
+ }, true);
368
+ // Chromium and WebKit blur the window as focus goes into a frame. Firefox may send the field a
369
+ // focusout first (seen in one review's runs, not in another's): looked at once it's over.
370
+ view.addEventListener("blur", (event) => {
371
+ if (event.target === view) {
372
+ look(true);
373
+ }
374
+ });
375
+ document.addEventListener("focusout", () => {
376
+ view.setTimeout(() => look(false), 0);
377
+ }, true);
378
+ const guard = {
379
+ add(frame, taken) {
380
+ let guarded = frames.get(frame);
381
+ if (guarded === undefined) {
382
+ const entry = { taken: new Set(), overSince: -Infinity };
383
+ frame.addEventListener("pointerover", () => {
384
+ entry.overSince = now();
385
+ });
386
+ frames.set(frame, entry);
387
+ guarded = entry;
388
+ }
389
+ guarded.taken.add(taken);
390
+ schedule();
391
+ const own = guarded;
392
+ return () => {
393
+ own.taken.delete(taken);
394
+ if (own.taken.size === 0) {
395
+ frames.delete(frame);
396
+ }
397
+ };
398
+ },
399
+ focus(frame) {
400
+ hostMove = { frame, at: now() };
401
+ frame.focus();
402
+ look(true);
403
+ },
404
+ focused(frame) {
405
+ look(false);
406
+ // A press on the host's page since focus went into the frame, just now: the activation is
407
+ // that press's, and focus is about to leave (a call that lands in between doesn't count).
408
+ const pressedHost = pressAt > enteredAt && now() - pressAt < HOST_PRESS_MS;
409
+ return known === frame && document.activeElement === frame && earned && !pressedHost;
410
+ },
411
+ field(field) {
412
+ const holder = deepActive(document);
413
+ const guarded = holder === null ? undefined : frames.get(holder);
414
+ if (guarded === undefined) {
415
+ field.focus({ preventScroll: true });
416
+ return;
417
+ }
418
+ // Watched as a take-back: a frame that keeps focus fails it, and is counted.
419
+ const frame = holder;
420
+ frame.blur();
421
+ field.focus({ preventScroll: true });
422
+ known = field;
423
+ focusedAt = now();
424
+ contest = { field, frame, guarded, gaveAt: focusedAt, heldSince: null };
425
+ schedule();
426
+ },
427
+ };
428
+ guards.set(view, guard);
429
+ return guard;
430
+ }
431
+ /**
432
+ * Moves focus into one of the host page's text fields (a composer that opens beside a display,
433
+ * P109): `field.focus()` for a host to call instead. Firefox doesn't move focus from a frame that
434
+ * holds it with a gesture of the person's and takes it back on its own blur (measured: the keys
435
+ * then go to the frame); this blurs the frame first, and the focus guard watches that focus lands,
436
+ * counting a frame that keeps it toward stopping its display. Elsewhere it is `field.focus()`.
437
+ */
438
+ export function focusField(field) {
439
+ const view = field.ownerDocument.defaultView;
440
+ if (view === null) {
441
+ field.focus({ preventScroll: true });
442
+ return;
443
+ }
444
+ focusGuard(view).field(field);
445
+ }
@@ -46,6 +46,24 @@ export interface Surface {
46
46
  readonly width: number;
47
47
  readonly height: number;
48
48
  } | undefined;
49
+ /**
50
+ * Whether the embedding page's focus is in this frame now, once the platform's focus guard
51
+ * judged any move into it (P109); undefined, or absent, where the platform can't tell. A gesture
52
+ * gate that asks for the person in the calling frame (`comments`) reads it: false refuses.
53
+ */
54
+ focused?(): boolean | undefined;
55
+ /**
56
+ * Each time the content moved the keyboard into its frame from one of the embedding page's text
57
+ * fields without the person (no press on the frame, no Tab) and the platform gave focus back
58
+ * (P109): whether the person was typing then (a key within the last second), and whether focus
59
+ * failed to go back (the frame kept it or took it again). Absent where the platform has no guard.
60
+ */
61
+ onFocusTaken?(listener: (take: {
62
+ readonly typing: boolean;
63
+ readonly failed: boolean;
64
+ }) => void): () => void;
65
+ /** The host moves focus into the frame itself: the guard takes it as the person's (P109). */
66
+ focus?(): void;
49
67
  /**
50
68
  * The frame loaded a document other than the one it was given: the content navigated it. The
51
69
  * framework starts it again from its content and reports it.
@@ -1,5 +1,6 @@
1
1
  import { FRAME_STATUS_METHOD } from "../isolation/types.js";
2
2
  import { postMessageTransport } from "../transport/post-message.js";
3
+ import { focusGuard } from "./focus-guard.js";
3
4
  /** A frame-status message (`porthole/notifications/frame-status`), by its method alone. */
4
5
  const isFrameStatus = (data) => data !== null &&
5
6
  typeof data === "object" &&
@@ -56,6 +57,15 @@ export const webPlatform = {
56
57
  });
57
58
  container.append(frame);
58
59
  const view = container.ownerDocument.defaultView ?? window;
60
+ // The focus guard (P109): a move of the keyboard into this frame from one of the page's text
61
+ // fields that the person didn't make is undone.
62
+ const guard = focusGuard(view);
63
+ const taken = new Set();
64
+ const unguard = guard.add(frame, (take) => {
65
+ for (const listener of taken) {
66
+ listener(take);
67
+ }
68
+ });
59
69
  // A served frame may pass through the host's own pages (a redirect entry's, P068): what they
60
70
  // say of the frame's status is heard too, and nothing else from there.
61
71
  const own = view.origin;
@@ -85,6 +95,16 @@ export const webPlatform = {
85
95
  const activation = view.navigator.userActivation;
86
96
  return activation === undefined ? undefined : activation.isActive;
87
97
  },
98
+ focused() {
99
+ return guard.focused(frame);
100
+ },
101
+ onFocusTaken(listener) {
102
+ taken.add(listener);
103
+ return () => taken.delete(listener);
104
+ },
105
+ focus() {
106
+ guard.focus(frame);
107
+ },
88
108
  onLoad(listener) {
89
109
  loaded.add(listener);
90
110
  return () => loaded.delete(listener);
@@ -96,6 +116,8 @@ export const webPlatform = {
96
116
  destroy() {
97
117
  navigated.clear();
98
118
  loaded.clear();
119
+ taken.clear();
120
+ unguard();
99
121
  transport.close();
100
122
  frame.remove();
101
123
  },
@@ -229,6 +229,14 @@ export interface PortholeFrameProps {
229
229
  readonly onRefused?: (capability: CapabilityName, refusal: Refusal) => void;
230
230
  /** Too many declines: the display stops asking until it runs again. */
231
231
  readonly onMuted?: () => void;
232
+ /**
233
+ * The content moved the keyboard into its frame from one of the page's text fields without the
234
+ * person, and focus went back (P109); `typing`: the person was typing on the page. A display
235
+ * that keeps doing it is stopped (`onContentError` says so).
236
+ */
237
+ readonly onFocusTaken?: (taken: {
238
+ readonly typing: boolean;
239
+ }) => void;
232
240
  /**
233
241
  * How the frame's first document went: loaded, blocked (and why), or a timeout. A host shows its
234
242
  * own fallback (a url-mode app "Open in a new tab") on anything but loaded.
@@ -415,6 +415,9 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
415
415
  case "muted":
416
416
  frame.onMuted?.();
417
417
  return;
418
+ case "focusTaken":
419
+ frame.onFocusTaken?.(detail);
420
+ return;
418
421
  case "outcome":
419
422
  frame.onOutcome?.(detail);
420
423
  return;
@@ -532,6 +535,7 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
532
535
  "navigationBlocked",
533
536
  "refused",
534
537
  "muted",
538
+ "focusTaken",
535
539
  "outcome",
536
540
  "annotation",
537
541
  "contentError",
@@ -1,4 +1,4 @@
1
- import { unseen } from "../bridge/unseen.js";
1
+ import { unseenStrict, withoutUnseen } from "../bridge/unseen.js";
2
2
  import { fileLimits, filePathProblem } from "../files/paths.js";
3
3
  import { fileTypeOf } from "../files/types.js";
4
4
  const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -21,33 +21,55 @@ export function base64Bytes(value) {
21
21
  return (value.length / 4) * 3 - padding;
22
22
  }
23
23
  const encoder = new TextEncoder();
24
+ /** Characters that draw as a blank: spaces of every kind, tabs, new lines, the braille blank. */
25
+ const BLANK = /^[\p{White_Space}\u2800]*$/u;
26
+ /** More than 32 blanks in a row on a line, or more than two blank lines in a row (P109). */
27
+ const BLANK_RUN = /[\p{Zs}\t\u2800]{33}|\n(?:[\p{Zs}\t\u2800]*\n){3}/u;
28
+ /** Line and paragraph separators: a line break a person may see as nothing (Firefox, WebKit). */
29
+ const SEPARATORS = /[\u2028\u2029]/u;
24
30
  /**
25
- * A draft (P108): text the person will post in their own name, so all of it must be text they can
26
- * see: at most 2,000 characters, well-formed, not blank, and nothing `unseen` (P100: no zero-width
27
- * or bidi characters, no tags, no controls but a new line and a tab), which a host would show as
28
- * nothing and an agent would read as the person's words. Lines and tabs are fine: a checklist.
31
+ * A draft (P108, P109): text the person will post in their own name, so all of it must be text
32
+ * they can see: at most 2,000 characters, well-formed, and nothing invisible (`unseenStrict`: no
33
+ * zero-width characters, bidi or tag characters, controls but a new line and a tab; a joiner or
34
+ * non-joiner only between two letters or marks, a variation selector only after a pictograph), no line or paragraph
35
+ * separator, not blank-looking, at most 32 blanks in a row and two blank lines in a row (so that
36
+ * "whole" is something a host can show). Lines and tabs are fine: a checklist.
29
37
  */
30
38
  const draftText = (value) => typeof value === "string" &&
31
- value.trim() !== "" &&
32
39
  value.length <= 2_000 &&
33
40
  value.isWellFormed() &&
34
- !unseen(value);
41
+ !BLANK.test(value) &&
42
+ !unseenStrict(value) &&
43
+ !SEPARATORS.test(value) &&
44
+ !BLANK_RUN.test(value);
45
+ /**
46
+ * An anchor's label or quote, shown beside the draft (P109): the page's short text, without what a
47
+ * person can't see (P105's `withoutUnseen`, line and paragraph separators too), or null if nothing
48
+ * visible is left. Shown, never posted as the person's words, so cleaned rather than refused.
49
+ */
50
+ const shownText = (value, max) => {
51
+ if (!shortText(value, max)) {
52
+ return null;
53
+ }
54
+ const seen = withoutUnseen(value).replace(/[\u2028\u2029]/gu, "");
55
+ return BLANK.test(seen) ? null : seen;
56
+ };
35
57
  export function parseCommentRequest(args) {
36
58
  const anchor = isRecord(args) ? args.anchor : undefined;
37
59
  if (!isRecord(anchor) || !shortText(anchor.name, 256)) {
38
60
  return null;
39
61
  }
40
62
  const draft = isRecord(args) ? args.draft : undefined;
41
- if ((anchor.label !== undefined && !shortText(anchor.label, 200)) ||
42
- (anchor.quote !== undefined && !shortText(anchor.quote, 2_000)) ||
43
- (draft !== undefined && !draftText(draft))) {
63
+ const label = anchor.label === undefined ? undefined : shownText(anchor.label, 200);
64
+ const quote = anchor.quote === undefined ? undefined : shownText(anchor.quote, 2_000);
65
+ if (label === null || quote === null || (draft !== undefined && !draftText(draft))) {
44
66
  return null;
45
67
  }
46
68
  return {
47
69
  anchor: {
48
70
  name: anchor.name,
49
- ...(anchor.label === undefined ? {} : { label: anchor.label }),
50
- ...(anchor.quote === undefined ? {} : { quote: anchor.quote }),
71
+ ...(label === undefined ? {} : { label }),
72
+ ...(quote === undefined ? {} : { quote }),
51
73
  },
52
74
  ...(draft === undefined ? {} : { draft }),
53
75
  };
@@ -7,7 +7,7 @@ export const RUNTIME_TYPES = {
7
7
  "assets": "// Porthole capability runtime, contract 1: assets (the artifact's asset library). Declare it: { assets: {} }.\n// Assets live outside every version, at \"/_blob/<id>\" on the page's own origin: keep that url (or\n// the id) in your data, and show it with assets.url(id). Images, media and fonts load; scripts and\n// stylesheets only where the app lets only admins upload, and only those an admin added. Not for\n// files that version with the page: publish those with it.\n\ninterface PortholeAsset {\n /** 32 hex characters. */\n readonly id: string;\n /** \"/_blob/<id>\": use it as given. */\n readonly url: string;\n readonly name: string;\n /** Porthole's type for the name's extension. */\n readonly type: string;\n readonly size: number;\n}\n\ninterface PortholeAssets {\n /** The library, people's uploads through the page included. Level: view. */\n list(): Promise<readonly PortholeAsset[]>;\n /**\n * Adds a file (a File from an <input type=\"file\">, a Blob, bytes) under its name (a File's own,\n * or options.name): an image, media, a font, a PDF, text or data, never HTML; a script or a\n * stylesheet only where uploads are the admins'. The app may ask the person first. Level: admin,\n * unless the app lets people who interact upload.\n */\n upload(\n file: Blob | ArrayBuffer | ArrayBufferView,\n options?: { readonly name?: string },\n ): Promise<PortholeAsset>;\n /**\n * The address that loads an asset in this page now: put it in src or href when you show it.\n * Store the id (or \"/_blob/<id>\"), never this: it carries this page's access. A \"/_blob/<id>\"\n * written in the page loads too, except in some browsers' frames (Safari's); this always does.\n */\n url(id: string): string;\n /** Removes one, from a click; the app asks the person first. Level: admin. */\n delete(id: string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n assets: PortholeAssets;\n}\n",
8
8
  "chat": "// Porthole capability runtime, contract 1: chat. Declare it: { chat: {} }.\n\ninterface PortholeChat {\n /**\n * Sends text to the agent as the person's message (\"explain this point\"). Call it from a click.\n * Resolves true if it was sent. Level: interact.\n */\n send(text: string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n chat: PortholeChat;\n}\n",
9
9
  "clipboard": "// Porthole capability runtime, contract 1: clipboard. Built in: never declare it.\n\ninterface PortholeClipboard {\n /**\n * Copies text to the person's clipboard (at most 20,000 characters); the app shows them what\n * was copied. Nothing else in the page can write the clipboard. Call it from a click.\n * Resolves true if it was copied. Level: view.\n */\n copy(text: string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n clipboard: PortholeClipboard;\n}\n",
10
- "comments": "// Porthole capability runtime, contract 1: comments. Built in: never declare it.\n\n/** Where a comment goes, in the page's own words. */\ninterface PortholeCommentAnchor {\n /** A stable name the page chose: \"slide-3\", \"refs/a.md#L12\" (at most 256 characters). */\n readonly name: string;\n /** What the app shows for it (at most 200). */\n readonly label?: string;\n /** The text the comment is about (at most 2,000). */\n readonly quote?: string;\n}\n\n/** How the composer opens. */\ninterface PortholeCommentOptions {\n /**\n * Text the composer starts with (at most 2,000 characters): a draft the person edits, posts\n * or discards in the app. It is never posted without them. Visible text only: new lines and\n * tabs are fine; a draft with zero-width, bidi or tag characters is refused.\n */\n readonly draft?: string;\n}\n\ninterface PortholeComments {\n /**\n * Opens the app's comment composer at the anchor (a name alone is { name }), starting with\n * `options.draft` if given. The person writes and posts it in the app. Resolves true if the\n * composer opened. Write-only: a page never reads comments. Call it from a click. Level: view.\n */\n open(anchor: PortholeCommentAnchor | string, options?: PortholeCommentOptions): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n comments: PortholeComments;\n}\n",
10
+ "comments": "// Porthole capability runtime, contract 1: comments. Built in: never declare it.\n\n/** Where a comment goes, in the page's own words. */\ninterface PortholeCommentAnchor {\n /** A stable name the page chose: \"slide-3\", \"refs/a.md#L12\" (at most 256 characters). */\n readonly name: string;\n /** What the app shows for it (at most 200; what a person can't see is taken out). */\n readonly label?: string;\n /** The text the comment is about (at most 2,000; what a person can't see is taken out). */\n readonly quote?: string;\n}\n\n/** How the composer opens. */\ninterface PortholeCommentOptions {\n /**\n * Text the composer starts with (at most 2,000 characters): a draft the person edits, posts\n * or discards in the app. It is never posted without them. Visible text only: new lines and\n * tabs are fine (at most 32 blanks in a row, two blank lines in a row), and so are U+200C and\n * U+200D between two letters or marks (Persian, the Indic scripts); a draft with zero-width\n * characters, a joiner anywhere else (an emoji joined with U+200D too; ❤️ is fine), bidi or tag\n * characters, or a line or paragraph separator (U+2028, U+2029) is refused.\n */\n readonly draft?: string;\n}\n\ninterface PortholeComments {\n /**\n * Opens the app's comment composer at the anchor (a name alone is { name }), starting with\n * `options.draft` if given. The person writes and posts it in the app. Resolves true if the\n * composer opened, false if it didn't (the app may refuse while the person is writing).\n * Write-only: a page never reads comments. Call it from a click in the page. Level: view.\n */\n open(anchor: PortholeCommentAnchor | string, options?: PortholeCommentOptions): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n comments: PortholeComments;\n}\n",
11
11
  "context": "// Porthole capability runtime, contract 1: context. Declare it: { context: {} }.\n\ninterface PortholeContextUpdate {\n /**\n * MCP text blocks only: [{ type: \"text\", text: \"…\" }]. Visible characters only, here and in\n * structuredContent: no zero-width or bidi controls, variation selectors, tag or private-use\n * characters, or controls other than new lines and tabs (refused), but the selectors and\n * joiners inside real emoji (☀️, 👨‍👩‍👧, 1️⃣), and a joiner or non-joiner between two letters of\n * a script it shapes (Arabic, Persian, the Indic scripts, Myanmar…).\n */\n readonly content?: readonly unknown[];\n /** Plain JSON. With the text, at most 20,000 characters. */\n readonly structuredContent?: Record<string, unknown>;\n}\n\ninterface PortholeContext {\n /**\n * Tells the agent, at its next turns, what the page says the person is looking at (replaces the\n * last). The agent reads it as the page's words, unconfirmed by the person; the app shows the\n * person each update unless it says otherwise. Level: interact.\n */\n set(update: PortholeContextUpdate): Promise<unknown>;\n}\n\ninterface PortholeCapabilities {\n context: PortholeContext;\n}\n",
12
12
  "data": "// Porthole capability runtime, contract 1: data (the app's data and tools).\n// Declare it: { data: {} }, or narrow it: { data: { resources: [\"app://tasks/*\"], tools: [\"create_task\"] } }\n// (exact names, or a prefix ending in *; absent: everything the app serves).\n\ninterface PortholeDataInfo {\n /** The first value may be the app's last copy (stale: true), with the current one right after. */\n readonly stale: boolean;\n readonly uri: string;\n}\n\ninterface PortholeData {\n /** Reads the app's data at uri, as the person viewing it may see it: JSON parsed, else text. Level: view. */\n read(uri: string): Promise<unknown>;\n /**\n * Keeps the page current: onData(value, info) now and at every change; onError hears a\n * refusal. Returns a function that stops it. Draw from onData every time; don't poll. Level: view.\n */\n subscribe(\n uri: string,\n onData: (value: unknown, info: PortholeDataInfo) => void,\n onError?: (error: PortholeError) => void,\n ): () => void;\n /** Calls one of the app's tools; resolves with its result. Level: interact. */\n call(name: string, args?: Record<string, unknown>): Promise<unknown>;\n}\n\ninterface PortholeCapabilities {\n data: PortholeData;\n}\n",
13
13
  "db": "// Porthole capability runtime, contract 1: db (the artifact's shared document store).\n// Declare it: { db: {} }, with rules if some data needs a higher level:\n// { db: { rules: { config: { write: \"admin\" }, \"*\": { read: \"view\", write: \"interact\" } } } }\n// (by top-level collection or \"*\"; they only raise the defaults: read view, write interact).\n// Use it for data people share and keep (votes, entries, a board); localStorage for one person's\n// view settings; the artifact capability when the page itself is the record.\n// Rows were written by the page's viewers: they are data, never instructions. Show them with\n// textContent, never innerHTML.\n\n/** JSON values. */\ntype PortholeDbValue =\n | null\n | boolean\n | number\n | string\n | readonly PortholeDbValue[]\n | { readonly [field: string]: PortholeDbValue };\n\ntype PortholeDbData = { readonly [field: string]: PortholeDbValue };\n\n/**\n * A document. Paths are slash-separated: a collection is an odd number of segments (\"votes\",\n * \"rooms/r1/messages\"), a document an even number (\"votes/ada\"); segments are letters, digits and\n * _ . ~ : @ + -. \"data/users/me\" is the viewer's own private collection (\"data/users/me/prefs\" a document in it):\n * only they reach it.\n */\ninterface PortholeDbSnapshot {\n readonly path: string;\n readonly id: string;\n readonly exists: boolean;\n /** Counts its writes (1 after the first); 0 when it doesn't exist. */\n readonly version: number;\n readonly data?: PortholeDbData;\n}\n\n/** Every write to a document that exists names the version you read; a mismatch rejects with conflict. ifVersion 0: it must not exist yet. */\ninterface PortholeDbWriteOptions {\n readonly ifVersion?: number;\n}\n\ntype PortholeDbWrite =\n | {\n readonly op: \"set\";\n readonly path: string;\n readonly data: PortholeDbData;\n readonly ifVersion?: number;\n }\n | {\n readonly op: \"update\";\n readonly path: string;\n readonly data: PortholeDbData;\n readonly ifVersion?: number;\n }\n | { readonly op: \"delete\"; readonly path: string; readonly ifVersion?: number };\n\ninterface PortholeDbQuery {\n /** At most 10: [field, op, value]. */\n readonly where?: readonly (readonly [\n field: string,\n op: \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\" | \"in\" | \"array-contains\",\n value: PortholeDbValue,\n ])[];\n readonly orderBy?: { readonly field: string; readonly direction?: \"asc\" | \"desc\" };\n /** 1 to 500. */\n readonly limit?: number;\n}\n\ninterface PortholeDb {\n /** Level: view. */\n get(path: string): Promise<PortholeDbSnapshot>;\n /** A collection's documents. Level: view. */\n query(\n collection: string,\n query?: PortholeDbQuery,\n ): Promise<{ readonly docs: readonly PortholeDbSnapshot[] }>;\n /** Writes a whole document (at most 1 MiB of JSON). Level: interact. */\n set(\n path: string,\n data: PortholeDbData,\n options?: PortholeDbWriteOptions,\n ): Promise<{ readonly version: number }>;\n /** Merges fields over a document's. Level: interact. */\n update(\n path: string,\n data: PortholeDbData,\n options?: PortholeDbWriteOptions,\n ): Promise<{ readonly version: number }>;\n /** Level: interact. */\n delete(path: string, options?: PortholeDbWriteOptions): Promise<null>;\n /**\n * Up to 50 writes to different documents, all or none. Each write's new version (null for a\n * delete). Each write at its own level.\n */\n batch(\n writes: readonly PortholeDbWrite[],\n ): Promise<{ readonly versions: readonly (number | null)[] }>;\n /**\n * Follows a document (a snapshot) or a collection ({ docs }) now and at every change. Returns a\n * function that stops it. Draw from onData; don't poll. Level: view.\n */\n onSnapshot(\n path: string,\n onData: (state: PortholeDbSnapshot | { readonly docs: readonly PortholeDbSnapshot[] }) => void,\n onError?: (error: PortholeError) => void,\n ): () => void;\n}\n\ninterface PortholeCapabilities {\n db: PortholeDb;\n}\n",