@botiverse/porthole 0.14.8 → 0.14.9

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 (54) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/bridge/bridge.d.ts +6 -0
  3. package/dist/bridge/bridge.js +5 -0
  4. package/dist/check/page-source.js +1 -1
  5. package/dist/config/capabilities.d.ts +16 -2
  6. package/dist/config/capabilities.js +8 -0
  7. package/dist/conformance/harness-source.js +1 -1
  8. package/dist/find/types.d.ts +83 -0
  9. package/dist/find/types.js +29 -0
  10. package/dist/find/validate.d.ts +17 -0
  11. package/dist/find/validate.js +82 -0
  12. package/dist/guide/guide.js +2 -1
  13. package/dist/host/create-host.js +214 -0
  14. package/dist/host/pass-on.js +3 -2
  15. package/dist/host/types.d.ts +51 -0
  16. package/dist/index.d.ts +3 -1
  17. package/dist/index.js +3 -0
  18. package/dist/react/frame.d.ts +43 -0
  19. package/dist/react/frame.js +107 -3
  20. package/dist/react/view.js +2 -0
  21. package/dist/runtime/contract.d.ts +1 -1
  22. package/dist/runtime/contract.js +1 -1
  23. package/dist/shell/annotate.js +2 -95
  24. package/dist/shell/document.d.ts +3 -3
  25. package/dist/shell/document.js +5 -3
  26. package/dist/shell/find.d.ts +82 -0
  27. package/dist/shell/find.js +725 -0
  28. package/dist/shell/runtime.js +4 -1
  29. package/dist/shell/text.d.ts +17 -0
  30. package/dist/shell/text.js +140 -0
  31. package/docs/ADOPTING.md +83 -0
  32. package/docs/ARCHITECTURE.md +10 -3
  33. package/docs/DECISIONS.md +219 -1
  34. package/docs/DESIGN.md +33 -0
  35. package/docs/THREAT_MODEL.md +48 -4
  36. package/docs/insertion-entry-points.md +17 -0
  37. package/package.json +1 -1
  38. package/src/bridge/bridge.ts +7 -0
  39. package/src/config/capabilities.ts +13 -1
  40. package/src/find/types.ts +86 -0
  41. package/src/find/validate.ts +101 -0
  42. package/src/guide/guide.ts +3 -1
  43. package/src/host/create-host.ts +230 -0
  44. package/src/host/pass-on.ts +3 -2
  45. package/src/host/types.ts +52 -0
  46. package/src/index.ts +12 -0
  47. package/src/react/frame.tsx +160 -1
  48. package/src/react/view.tsx +3 -0
  49. package/src/runtime/contract.ts +1 -1
  50. package/src/shell/annotate.ts +3 -95
  51. package/src/shell/document.ts +5 -3
  52. package/src/shell/find.ts +731 -0
  53. package/src/shell/runtime.ts +4 -1
  54. package/src/shell/text.ts +140 -0
@@ -1776,6 +1776,8 @@ export const SHELL_RUNTIME = String.raw `(() => {
1776
1776
 
1777
1777
  __ANNOTATE__
1778
1778
 
1779
+ __FIND__
1780
+
1779
1781
  if (plan.protocol !== "shell") {
1780
1782
  // A view that speaks for itself.
1781
1783
  if (typeof plan.document === "string") {
@@ -2209,7 +2211,8 @@ export const SHELL_RUNTIME = String.raw `(() => {
2209
2211
  }
2210
2212
  break;
2211
2213
  default:
2212
- if (data.id !== undefined) {
2214
+ // Find's own request is answered by the find runtime (P131), where the config declares it.
2215
+ if (data.id !== undefined && !(data.method === "porthole/find.query" && declared("find"))) {
2213
2216
  send({ id: data.id, error: { code: -32601, message: String(data.method) + " isn't offered here" } });
2214
2217
  }
2215
2218
  break;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The document's text as annotations (P053) and find in page (P131) read it, spliced into each of
3
+ * their runtimes (inside its own function, after it took `createTreeWalker` and `createRange` from
4
+ * the DOM before content ran): the body's text nodes in order, without scripts, styles, noscript
5
+ * and templates, as one string with each node's start (`textIndex()`); an offset into it as a
6
+ * boundary point (`pointAt`), a boundary point as an offset (`offsetOf`), a span as a range
7
+ * (`rangeAt`). One source, so a match find highlights and an anchor's `TextPositionSelector` count
8
+ * the same text. Plain ES2020, no template literals (it sits in one).
9
+ *
10
+ * Every built-in it calls is taken before content runs and called through the shell's `callOf`
11
+ * (P129): the walker's step, a node's type, name and text (the `nodeType`, `localName` and
12
+ * `nodeValue` getters), the body getter, a range's boundaries, and the map of nodes. Its
13
+ * lists are the shell's prototype-less ones (`listOf`, `pushTo`), and the names it skips a lookup
14
+ * with no prototype, so nothing content puts on `Array.prototype`, `Object.prototype`, `Map` or a
15
+ * DOM prototype takes part in what it reads.
16
+ */
17
+ export declare const TEXT_INDEX: string;
@@ -0,0 +1,140 @@
1
+ /**
2
+ * The document's text as annotations (P053) and find in page (P131) read it, spliced into each of
3
+ * their runtimes (inside its own function, after it took `createTreeWalker` and `createRange` from
4
+ * the DOM before content ran): the body's text nodes in order, without scripts, styles, noscript
5
+ * and templates, as one string with each node's start (`textIndex()`); an offset into it as a
6
+ * boundary point (`pointAt`), a boundary point as an offset (`offsetOf`), a span as a range
7
+ * (`rangeAt`). One source, so a match find highlights and an anchor's `TextPositionSelector` count
8
+ * the same text. Plain ES2020, no template literals (it sits in one).
9
+ *
10
+ * Every built-in it calls is taken before content runs and called through the shell's `callOf`
11
+ * (P129): the walker's step, a node's type, name and text (the `nodeType`, `localName` and
12
+ * `nodeValue` getters), the body getter, a range's boundaries, and the map of nodes. Its
13
+ * lists are the shell's prototype-less ones (`listOf`, `pushTo`), and the names it skips a lookup
14
+ * with no prototype, so nothing content puts on `Array.prototype`, `Object.prototype`, `Map` or a
15
+ * DOM prototype takes part in what it reads.
16
+ */
17
+ export const TEXT_INDEX = String.raw `// The document's text: the body's text nodes in order, without scripts, styles, templates.
18
+ const textNextNode = TreeWalker.prototype.nextNode;
19
+ const textTypeOf = getterOf(Node.prototype, "nodeType");
20
+ const textNameOf = getterOf(Element.prototype, "localName");
21
+ const textValueOf = getterOf(Node.prototype, "nodeValue");
22
+ const textBodyOf = getterOf(Document.prototype, "body");
23
+ const textSetStart = Range.prototype.setStart;
24
+ const textSetEnd = Range.prototype.setEnd;
25
+ const textCollapse = Range.prototype.collapse;
26
+ const textComparePoint = Range.prototype.comparePoint;
27
+ const TextMap = Map;
28
+ const textMapSet = Map.prototype.set;
29
+ const textMapGet = Map.prototype.get;
30
+ const textMapHas = Map.prototype.has;
31
+ const TEXT_SHOW = NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT;
32
+ const TEXT_ACCEPT = NodeFilter.FILTER_ACCEPT;
33
+ const TEXT_REJECT = NodeFilter.FILTER_REJECT;
34
+ const TEXT_SKIP = NodeFilter.FILTER_SKIP;
35
+ const SKIPPED = bare(null);
36
+ SKIPPED.script = 1;
37
+ SKIPPED.style = 1;
38
+ SKIPPED.noscript = 1;
39
+ SKIPPED.template = 1;
40
+ // A text node's text, read once through the kept getter; anything but a string is none.
41
+ const textOf = (node) => {
42
+ const value = textValueOf === null ? node.nodeValue : callOf(textValueOf, node, []);
43
+ return typeof value === "string" ? value : "";
44
+ };
45
+ const textKind = (node) => (textTypeOf === null ? node.nodeType : callOf(textTypeOf, node, []));
46
+ const textLesser = (a, b) => (a < b ? a : b);
47
+ const skippedElement = (node) => SKIPPED[textNameOf === null ? node.localName : callOf(textNameOf, node, [])] === 1;
48
+ const textIndex = () => {
49
+ const nodes = listOf();
50
+ const starts = listOf();
51
+ const at = new TextMap();
52
+ let text = "";
53
+ const body = textBodyOf === null ? document.body : callOf(textBodyOf, document, []);
54
+ if (body) {
55
+ const walker = callOf(createTreeWalker, document, [body, TEXT_SHOW, {
56
+ acceptNode: (node) => (textKind(node) === 1 ? (skippedElement(node) ? TEXT_REJECT : TEXT_SKIP) : TEXT_ACCEPT),
57
+ }]);
58
+ for (let node = callOf(textNextNode, walker, []); node !== null; node = callOf(textNextNode, walker, [])) {
59
+ callOf(textMapSet, at, [node, nodes.length]);
60
+ pushTo(nodes, node);
61
+ pushTo(starts, text.length);
62
+ text += textOf(node);
63
+ }
64
+ }
65
+ return { nodes, starts, at, text };
66
+ };
67
+ // A boundary point as an offset into the text: in a text node, where it is; elsewhere, the
68
+ // first text at or after it.
69
+ const offsetOf = (index, container, offset) => {
70
+ if (textKind(container) === 3 && callOf(textMapHas, index.at, [container])) {
71
+ return index.starts[callOf(textMapGet, index.at, [container])] + textLesser(offset, textOf(container).length);
72
+ }
73
+ const point = callOf(createRange, document, []);
74
+ try {
75
+ callOf(textSetStart, point, [container, offset]);
76
+ } catch (_) {
77
+ return index.text.length;
78
+ }
79
+ callOf(textCollapse, point, [true]);
80
+ let low = 0;
81
+ let high = index.nodes.length;
82
+ while (low < high) {
83
+ const middle = (low + high) >> 1;
84
+ if (callOf(textComparePoint, point, [index.nodes[middle], 0]) >= 0) {
85
+ high = middle;
86
+ } else {
87
+ low = middle + 1;
88
+ }
89
+ }
90
+ return low < index.nodes.length ? index.starts[low] : index.text.length;
91
+ };
92
+ const pointAt = (index, at, end) => {
93
+ let low = 0;
94
+ let high = index.nodes.length - 1;
95
+ let found = -1;
96
+ while (low <= high) {
97
+ const middle = (low + high) >> 1;
98
+ if (index.starts[middle] <= at) {
99
+ found = middle;
100
+ low = middle + 1;
101
+ } else {
102
+ high = middle - 1;
103
+ }
104
+ }
105
+ if (found === -1) {
106
+ return null;
107
+ }
108
+ let node = index.nodes[found];
109
+ let offset = at - index.starts[found];
110
+ if (end) {
111
+ // An end at a node's very start belongs to the text before it.
112
+ while (offset === 0 && found > 0) {
113
+ found -= 1;
114
+ node = index.nodes[found];
115
+ offset = textOf(node).length;
116
+ }
117
+ } else {
118
+ while (offset >= textOf(node).length && found + 1 < index.nodes.length) {
119
+ found += 1;
120
+ node = index.nodes[found];
121
+ offset = 0;
122
+ }
123
+ }
124
+ return { node, offset: textLesser(offset, textOf(node).length) };
125
+ };
126
+ const rangeAt = (index, start, end) => {
127
+ const from = pointAt(index, start, false);
128
+ const to = pointAt(index, end, true);
129
+ if (from === null || to === null) {
130
+ return null;
131
+ }
132
+ const range = callOf(createRange, document, []);
133
+ try {
134
+ callOf(textSetStart, range, [from.node, from.offset]);
135
+ callOf(textSetEnd, range, [to.node, to.offset]);
136
+ } catch (_) {
137
+ return null;
138
+ }
139
+ return range;
140
+ };`;
package/docs/ADOPTING.md CHANGED
@@ -389,6 +389,89 @@ composer.onClose(() => display.annotations.clearSelection());
389
389
  the person can't see; a quote (`exact`) keeps it, to be found again. Hand either to a model only
390
390
  as the page's words.
391
391
 
392
+ ### Find in page: the host's find bar
393
+
394
+ With `find` declared (`capabilities: { find: {} }`), your own find bar searches a display
395
+ ([P131](DECISIONS.md)): the shell finds the query in the page's text (case-insensitive by default,
396
+ any spacing), highlights every match it can see and the current one apart, brings the current one
397
+ into view (its scrolling box too), and answers where they stand. The page reads every query you
398
+ send (the search runs in the page's document): declare `find` only where the page may learn what
399
+ the person searches for (not a third-party app with egress, unless you accept that).
400
+
401
+ Send a query when the person pauses (a debounce of a few hundred ms) or presses Enter, not at
402
+ every key. Each query you send is posted into the page, so a bar that searches at every key shows
403
+ the page each prefix of what the person types and the rhythm of their typing; one that waits for
404
+ a pause shows it the words they settled on. It also spares a large page a search per key (the
405
+ shell searches only the latest of a burst, below).
406
+
407
+ ```js
408
+ display.find.takeShortcut(true); // Cmd+F / Ctrl+F in the frame opens your bar, not the browser's
409
+ display.on("findRequested", () => bar.open()); // the page's word too: open the bar, nothing more
410
+ // "unsupported", or `${active}/${total}` ("+" after the total where `capped`).
411
+ bar.showResult = (result) => bar.show(result === "unsupported" ? "Not available here" : result);
412
+ // Only the answer to the latest query is shown: an earlier one may come back "unsupported".
413
+ let asked = 0;
414
+ const ask = (query, options) => {
415
+ const mine = ++asked;
416
+ void display.find.query(query, options).then((result) => mine === asked && bar.showResult(result));
417
+ };
418
+ // A new query once the person pauses or presses Enter: the first match in view becomes current.
419
+ let pause;
420
+ bar.onInput((query) => {
421
+ clearTimeout(pause);
422
+ pause = setTimeout(() => ask(query), 300);
423
+ });
424
+ bar.onEnter((query) => (clearTimeout(pause), ask(query)));
425
+ bar.onNext(() => ask(bar.query, { direction: "next" }));
426
+ bar.onPrevious(() => ask(bar.query, { direction: "prev" }));
427
+ display.on("findUpdated", bar.showResult); // the page changed: new numbers
428
+ bar.onClose(() => display.find.clear()); // Escape in your bar: highlights gone
429
+ // The display forgot the query: its content navigated away (it runs again). Reset your bar here,
430
+ // and wherever you reload() it or give it other content.
431
+ display.on("navigated", () => bar.reset());
432
+ ```
433
+
434
+ - **`"unsupported"`**: the config doesn't declare `find`, the frame's shell is older than your
435
+ host (it answers that it doesn't know the request: upgrade the content server first), or no
436
+ answer came within `FIND_LIMITS.timeoutMs` (3 s) of the frame running. Also for a query that a
437
+ later one superseded before it ran (the shell searches only the latest of a burst; queries asked
438
+ before the frame ran: the latest is sent), and for one waiting when the content it was asked of
439
+ went (below): show the answer to your latest query only. A query asked before the frame ran
440
+ waits for it. An empty query clears and answers `{ total: 0, active: 0 }`; one longer than
441
+ `FIND_LIMITS.query` (256) rejects with a `TypeError`.
442
+ - **A query is for the content it was asked of.** A new run (`reload()`, a restart after the
443
+ content navigated its frame away, `navigated`) or other content (`setContent` with content that
444
+ doesn't continue what you gave: more of a streamed page keeps it) forgets the query: nothing is
445
+ highlighted or searched there until you call `find.query` again, so another page never sees the
446
+ last one's search. Clear your find bar's state (its query, "3/12") whenever the display shows
447
+ other content, then search again if the person asks. The shortcut (`takeShortcut`) is kept.
448
+ - **The numbers are the page's word**: at most 1,000 matches (`capped: true`: there may be
449
+ more), the current one from 1. `rect` is the current match's box in the frame's CSS px, clamped
450
+ to its viewport: a display that grows with its content (not `layout: "fill"`) doesn't scroll
451
+ itself, so scroll your page to the frame's position plus `rect`.
452
+ - **The shortcut** is yours only while you take it, and only where the page doesn't handle Cmd+F
453
+ or Ctrl+F itself. `findRequested` is taken only with the page's focus in the frame, so a page
454
+ can't open your bar while the person types in your composer. Your own page's Cmd+F (focus
455
+ outside every frame) is yours to handle as before. Escape and Cmd+G in the frame stay the page's:
456
+ close and move on from your bar.
457
+ - **Not found**: words in open shadow roots, in a page's own frames (P128), in form fields, in
458
+ images or a canvas, and words split across cells with no space between them.
459
+ - **React**: `onFindRequested` (given, the shortcut is yours) and `onFindUpdated` are props; the
460
+ handle holds `find(query, options)` and `clearFind()` beside `clearSelection()`. With no display
461
+ running, `find` answers `"unsupported"` and keeps the query for the content the frame shows: a
462
+ display made later for it (the frame nears the screen again) finds it again and tells
463
+ `onFindUpdated`. Other content forgets it: another `content` that doesn't continue it, a new
464
+ `generation`, `document`, `instance` (another artifact or version), `config`, `declaration` or
465
+ `viewer`. Reset your find bar when you change those. A refused query reaches `onHostError`,
466
+ kind `"find"`.
467
+
468
+ ```tsx
469
+ const frame = useRef<PortholeFrameHandle>(null);
470
+ <PortholeView ref={frame} display="page" instance={instance} displayId={id} title={title}
471
+ onFindRequested={() => setFinding(true)} onFindUpdated={setFound} />;
472
+ const result = await frame.current?.find(query, { direction: "next" });
473
+ ```
474
+
392
475
  ### The keyboard: what a display can take, and what you get
393
476
 
394
477
  Any display can move the keyboard into its frame (`element.focus()` in the page, with no gesture
@@ -278,9 +278,10 @@ several displays on one page are in [THREAT_MODEL.md](THREAT_MODEL.md).
278
278
  4. **Message boundary.** Every message crossing the frame is validated against a
279
279
  schema and checked for sender identity before use; the shell accepts messages
280
280
  only from its host, and the host only from its frame. What the frame says about
281
- itself (its size, its errors, an annotation's anchor and where it is) is the
282
- content's word even when the shell says it, since they share a realm: the host
283
- bounds it and uses it as a UI hint, never as a permission (P053).
281
+ itself (its size, its errors, an annotation's anchor and where it is, how many
282
+ matches find found) is the content's word even when the shell says it, since they
283
+ share a realm: the host bounds it and uses it as a UI hint, never as a permission
284
+ (P053, P131). What the host sends in (a mark, a find query) the content can read.
284
285
  A nested page (P111) is the one place they don't: the shell is a document of its
285
286
  own, the page's parent, on another origin than the page's (opaque), so the page
286
287
  reaches nothing of the shell's realm. Nor does any other content: the shell's
@@ -328,6 +329,12 @@ several displays on one page are in [THREAT_MODEL.md](THREAT_MODEL.md).
328
329
  comments (P053). A mark may carry a count, drawn as a clickable marker whose click
329
330
  the host hears and answers with its own UI outside the frame (P104), and may be a
330
331
  draft, its author's unposted comment, drawn apart with a hollow marker (P107).
332
+ - **Find in page** (`find`): the host draws its own find bar and asks the shell for
333
+ a query (`porthole/find.query`, a request: how many matches, which is current);
334
+ the shell finds it in the same text index annotations read, highlights it in a layer
335
+ of its own, and says when the person pressed Cmd+F or Ctrl+F in the frame, where the
336
+ host takes the shortcut (P131). An older shell answers "isn't offered here", and the
337
+ host calls find unsupported there.
331
338
  - **Served content.** A host plugs its own policy and infrastructure into `/server`:
332
339
  who may see what (`authorize`), where tickets live (`TicketStore`: memory, D1),
333
340
  how origins are named (`content.name`, other servers' `reserved` namespaces),
package/docs/DECISIONS.md CHANGED
@@ -6260,7 +6260,7 @@ Tested: `test/shell.test.ts` (`<`, `</`, `</di`, inside an attribute, and whole
6260
6260
  unchanged); `leak/react.spec.ts` "content streams through props…" (a draft cut after `</` and
6261
6261
  after `<` draws neither).
6262
6262
 
6263
- ## P118 · 2026-10-28 · React: `trackedAnnotation` and a handle with `clearSelection` · Accepted
6263
+ ## P118 · 2026-10-28 · React: `trackedAnnotation` and a handle with `clearSelection` · Accepted; amended by P131
6264
6264
 
6265
6265
  **Context.** Raft's web app (Kirby) shows displays through `PortholeFrame` and `PortholeView`,
6266
6266
  which hold the display handle inside: it could not follow a mark (`annotations.track`, P112) or
@@ -7313,3 +7313,221 @@ as the guard holding, and record it ("refused at creation"); with the refusal ta
7313
7313
  **Revisit when** an engine adds an insertion or parsing entry point (add it to the list, the
7314
7314
  runtime and the test), the default configuration is to allow frames, or the leak suite's probes
7315
7315
  cover each row.
7316
+
7317
+ ## P131 · 2026-11-04 · Find in page: the host's find bar, the shell's matches in a layer of its own (`find`) · Accepted
7318
+
7319
+ Raft's task: an Artifact viewer's find bar, like the thread panel's "search this thread": a query
7320
+ box, previous and next, a "3/12" count, highlights, Escape closes. The host can't read a display's
7321
+ text (its frame is another origin, opaque or the content's own), and the browser's own find gives
7322
+ it no count, no UI of its own and no say over Cmd+F. Only the shell, in the frame, can find the
7323
+ words and draw over them, so Porthole provides that part; the bar is the host's. Amends P118: the
7324
+ React handle holds `find` and `clearFind` beside `clearSelection`. Holds to P129 and P130: the find
7325
+ runtime calls only built-ins captured before content runs, and its layer's nodes go in only
7326
+ through the guarded insertion methods (**Drawing**, below).
7327
+
7328
+ **Decision.**
7329
+ - **A capability, `find`**, declared per config (`capabilities: { find: {} }`; in no preset by
7330
+ default; Raft opts in on its artifact kind). Served as an event, as `annotate` is; its default
7331
+ gate is a rate (120 a minute) on what the frame says unasked. The manual's entry tells the agent
7332
+ the person may search the page's words with the app's find bar (keep them as text) and that a
7333
+ page handling Cmd+F itself keeps the key (`test/agreement.test.ts` covers it). A url-mode app has
7334
+ no shell and declares no capability: find there is the browser's.
7335
+ - **The protocol** (own-prefixed, P002; `FIND_METHODS`):
7336
+ - `porthole/find.query`, host → frame, a **request**: `{ query, direction?: "next" | "prev" |
7337
+ "none", caseSensitive?: boolean }`, answered with `{ total, active, capped?: true, rect? }`:
7338
+ how many matches (at most `FIND_LIMITS.matches`, 1,000; `capped`: it stopped looking, there may
7339
+ be more), the current one from 1 (0 for none), and the current one's box in the frame's
7340
+ viewport once it was scrolled into view. A new query makes current the first match at or after
7341
+ the viewport's top (`prev`: the one before it); the same query with `next` or `prev` moves on
7342
+ from the current one by its place, wrapping; `none` keeps it. An empty query (or only spaces)
7343
+ clears and answers `{ total: 0, active: 0 }`. A query that a later query or a clear
7344
+ superseded before the shell ran it is answered with an error (`-32800`, "superseded by a later
7345
+ query"), which the host makes `"unsupported"` as it does any error (**Only the latest**,
7346
+ below).
7347
+ - `porthole/find.clear`, host → frame: highlights gone, query forgotten.
7348
+ - `porthole/find.handled { handled }`, host → frame: whether the host draws its own find bar.
7349
+ - `porthole/find.requested {}`, frame → host: the person pressed the shortcut (below).
7350
+ - `porthole/find.updated { total, active, capped? }`, frame → host: the matches changed while a
7351
+ query is shown (the content changed), at most once a second.
7352
+ - **Matching** (`FIND_MATCH`, one pure function spliced into the runtime, unit-tested): over
7353
+ annotations' text index (`TEXT_INDEX`, moved out of the annotation runtime and spliced into both:
7354
+ the body's text nodes, without scripts, styles, noscript and templates; the same text and
7355
+ offsets as before, now read through built-ins captured before content runs, P129).
7356
+ Case-insensitive unless asked (`RegExp` with `iu`: Unicode simple case folding, offsets kept),
7357
+ loose about spacing as annotations' `squash` is (trimmed; a run of white space in the query
7358
+ matches any run in the text), every other character literal (no pattern syntax reaches the
7359
+ expression). A match counts only if it has a box (text that is drawn: not `display: none`, not
7360
+ a closed `<details>`). At most 1,000 kept, 10,000 looked at, a query of at most 256 code units
7361
+ (the host refuses longer, the shell cuts).
7362
+ - **Drawing**: a layer of the shell's own, a closed shadow root over the content with the same
7363
+ forced inline style as annotations' layer (one constant, a test holds them equal), apart from
7364
+ it; a match is a light warm fill with a thin edge, the current one stronger with a ring (neither
7365
+ looks like a comment's yellow underline). Boxes from `Range.getClientRects`, only for matches in
7366
+ view, redrawn at each scroll and resize (an animation frame), and found again once a run of
7367
+ changes settles (150 ms quiet, at most a second late), the current match kept by its place. The
7368
+ current match is brought into view, centred, in its scrolling ancestors first (innermost first,
7369
+ `overflow` auto, scroll or overlay that overflows), then in the window; instantly. The selection
7370
+ is never touched (annotations would report it as the person's).
7371
+ - **Only the latest** (`FIND_LATEST`, one pure function spliced into the runtime, unit-tested). A
7372
+ search is synchronous, and on a large page long (measured: 150-730 ms on a page of 30,000
7373
+ spans), so a bar that asks at every key queued a search per key (50 queries at once took 14-22
7374
+ s). A query that comes while none waits, and not within 16 ms of the end of the last one run, is
7375
+ run at once, answered before any content's listener could answer it, as before. Otherwise it
7376
+ waits for the next task, after the messages already queued; a later query supersedes it, and a
7377
+ clear drops it, each answering it with the superseded error at once. A burst is so at most two
7378
+ searches: the one running and the latest. What a waiting query will search is read from the
7379
+ host's message when it comes (each field once, as an own property) and kept as those values,
7380
+ never read from the message again (P129). The host sends only the latest of the queries asked
7381
+ while a frame loads, and answers the others `"unsupported"`.
7382
+ - **Built-ins and insertion (P129, P130).** Every built-in the find runtime and the text index call
7383
+ once content may have run is captured before content runs and called only through `callOf`:
7384
+ `createRange`, `createTreeWalker` and the walker's `nextNode`, the `nodeType`, `localName`,
7385
+ `nodeValue`, `parentElement`, `body` and `documentElement` getters, `Range`'s `setStart`,
7386
+ `setEnd`, `collapse`, `comparePoint`, `startContainer` and boxes, `DOMRectList`'s and `DOMRect`'s
7387
+ getters, the sizes, `getComputedStyle` and `getPropertyValue`, `scrollBy`, the `style` getter and
7388
+ `cssText` accessors, the `className` and `nonce` setters, `Map`'s `set`/`get`/`has`, `RegExp` and
7389
+ its `exec`, the timers, `postMessage`, `MutationObserver.observe` and the `MutationRecord`
7390
+ getters, the `MessageEvent` `data`/`origin`/`source` getters, `KeyboardEvent`'s getters, and the
7391
+ platform's `preventDefault`. No live `.call`, `.apply` or `.bind`, no `Array`/`Object` prototype
7392
+ method (`map`, `concat`, `indexOf`, `push`, `for…of`, `Object.assign`) and no `Math` function:
7393
+ its lists are the shell's prototype-less ones (`listOf`, `pushTo`, also given to `FIND_MATCH`),
7394
+ its lookups and answers objects with no prototype. What it reads from the host's message (the
7395
+ event's fields, the request's own properties) is read once, and only a string, number or boolean
7396
+ is acted on; a box's numbers are read once and only numbers are used. The layer's nodes are made
7397
+ and inserted only through the shell's guarded methods, which step 3 wrapped before the find
7398
+ runtime runs (it is spliced after the guard and takes them then): `createElement` (A21 of
7399
+ [insertion-entry-points.md](insertion-entry-points.md)), `attachShadow` (A19), `appendChild`
7400
+ (A1), `replaceChildren` on an element and a shadow root (A2), and the `textContent` setter
7401
+ (A5). It inserts nothing into the content's own trees, and its inline styles go through CSSOM
7402
+ (`cssText`), not a `style` attribute.
7403
+ - **The shortcut**: Cmd+F on Apple's platforms (`navigator.platform`, read before content runs),
7404
+ Ctrl+F elsewhere, no Alt or Shift (`FIND_SHORTCUT`, unit-tested; on a layout whose letters aren't
7405
+ Latin, the key in F's place). Read in a listener on the window as the key bubbles, after the
7406
+ page's own: only while the host said `handled`, only a trusted key, and only one the page didn't
7407
+ take (`defaultPrevented`: a page with a find of its own keeps its key). Then the shell cancels
7408
+ the browser's find and says `requested`. Otherwise the key is left alone: a host without its own
7409
+ bar keeps the browser's.
7410
+ - **The host** (`display.find`): `query(query, { direction, caseSensitive })` resolves with the
7411
+ checked answer (its box clamped to the frame's viewport, P104) or `"unsupported"`: a config
7412
+ without `find`, an error (an older shell answers `-32601`, "isn't offered here"; the shell's own
7413
+ fallback now leaves `porthole/find.query` to the find runtime where it is declared), a malformed
7414
+ answer, or none within `FIND_LIMITS.timeoutMs` (3 s) of the frame running (asked before, the
7415
+ load's time too). A query too long, or options that aren't these, reject with a `TypeError`.
7416
+ `clear()`; `takeShortcut(take)` sends `handled`. The shortcut is kept and given to every frame
7417
+ the display runs. The query holds only for the content it was asked of: every new run (a
7418
+ `reload()`, a restart after the content navigated its frame away, so a new location) and other
7419
+ content (`setContent` with content that doesn't continue what was given; more of a streamed
7420
+ page does) forget it, answer what waits `"unsupported"` and, for other content, clear the frame
7421
+ running now. A new page is so never searched with the last one's query (not even unheard: the
7422
+ shell's scrolling and its layer would tell the page which of its words matched) unless the host
7423
+ asks again; the host clears its find bar then (ADOPTING).
7424
+ Events: `findRequested` (taken only while the host takes the shortcut and the platform says the
7425
+ page's focus is in the frame, or can't tell) and `findUpdated` (taken only while a query is
7426
+ shown); both checked (`parseFindReport`) and through the bridge's rate.
7427
+ - **React**: the handle (`PortholeFrameHandle`, P118) adds `find(query, options)` and
7428
+ `clearFind()`: with no display running, `"unsupported"`, and the query is kept, with what the
7429
+ frame showed when it was asked (`findScopeOf`: the config, instance with its version,
7430
+ declaration, viewer and generation by value, the document, the content). A display made later
7431
+ that shows the same (the frame neared the screen again; the content continued) finds it again
7432
+ and tells `onFindUpdated`; any other (`sameFindScope` false: another source, document, version
7433
+ or config, a new generation, content that doesn't continue it) forgets it. A refused query is `onHostError`
7434
+ (kind `"find"`) and `"unsupported"`, never a rejection. `onFindRequested`, given, makes the
7435
+ frame's shortcut the host's (`takeShortcut(true)`); `onFindUpdated` hears updates.
7436
+
7437
+ **Why a capability, gated per config** (THREAT_MODEL §7). Find gives content no power: nothing it
7438
+ can call, nothing of the host's it can read. But:
7439
+ 1. The query is the person's words, typed in the host's own UI, and it is posted into the content's
7440
+ realm, where the page can read it (each keystroke, for a bar that searches as the person
7441
+ types). A page with a way out (an MCP App's `connectDomains`, S5; egress a host opened; the
7442
+ runtime's `db` and other carriers, `mayPassOn`) can send what the person searched for to its
7443
+ author. A host opts in per config, knowing which displays may learn that.
7444
+ 2. The shell carries nothing the config doesn't declare (PRINCIPLE 4): a host that upgrades gets
7445
+ no new listener or message in its existing displays.
7446
+ 3. What the frame says unasked goes through the bridge, with a rate, as annotations' reports do.
7447
+
7448
+ **Accepted exposure.** The page can read every query the host sends it: the search runs in the
7449
+ page's document, so the query is in the page's realm (and, without reading the message, the
7450
+ shell's scrolling and its layer show the page which of its words matched). This was accepted by
7451
+ the product owner, with hosts sending queries on a pause or Enter rather than at every key, which
7452
+ limits what the page sees of the person's typing (ADOPTING).
7453
+ Accepted by xxchan (product owner, Raft #proj-workspace:e56d96e4, message 3d68e461, 2026-11-04):
7454
+ the page can read the queries sent to it; hosts send them on a pause or Enter, only while their
7455
+ find bar is open.
7456
+
7457
+ **Threat.** No wall moves: no CSP, sandbox, `allow`, egress or storage changes, nothing secret
7458
+ enters the frame, and annotations behave as before (the text index moved into a shared constant,
7459
+ spliced in the same place, and now reads through captured built-ins, P129). New on the message
7460
+ boundary:
7461
+ - *What content learns*: the query, whether it is case-sensitive, each move (next, previous), when
7462
+ the bar opens and closes, and whether the host draws its own bar.
7463
+ - *What content can say*: any count, any current match, any box inside its frame (clamped), and
7464
+ `updated` while a query is shown. All of it the content's word: a find bar's numbers, never a
7465
+ fact about the content. `requested` it can say at will, but the host takes it only with the
7466
+ page's focus in the frame (the web platform's focus guard: a press on the frame or a Tab put it
7467
+ there, P109). Without that rule a page could open the host's bar, which takes focus, while the
7468
+ person types in the host's composer, and their next keys would go into the bar, and so into the
7469
+ frame as queries. With the person already in the frame, the page has their keys anyway, and a bar
7470
+ opening moves the keyboard out of it. Negative control `find-requested-focus`.
7471
+ - *What content can always do*: hide, cover or move the layer, change its words so the count
7472
+ changes, keep the key from the shell (its own `preventDefault`, as intended; or stopping the
7473
+ event, which leaves the browser's find to open), patch built-ins to reach the closed shadow root
7474
+ (as annotations' layer, P105), or make the search dear by its size (linear in its text, bounded
7475
+ by the limits above; found again at most once a second while it changes; in an opaque frame that
7476
+ shares the host's process that time is the host's too, as annotations' is, §5); a burst of
7477
+ queries costs at most two searches (**Only the latest**).
7478
+
7479
+ **Rejected.**
7480
+ - The CSS Custom Highlight API (as P053 and P104 rejected it for marks): `CSS.highlights` is the
7481
+ content's registry, to read, clear or restyle; the shell's drawing must be its own.
7482
+ - `window.find()` or the browser's find: non-standard or out of reach, no count, and it moves the
7483
+ selection, which annotations report as the person's.
7484
+ - Always on, ungated: every display's page would get the person's search terms after an upgrade, a
7485
+ third-party MCP App's (S5) included.
7486
+ - A find bar drawn in the frame: the content could cover or fake it; the host's own UI is the
7487
+ point.
7488
+ - Taking Cmd+F wherever `find` is declared: a host without a bar of its own would lose the
7489
+ browser's find. And a notification only (no request): an older shell couldn't say it doesn't
7490
+ know it, and the host would wait out a timeout for every query.
7491
+ - The host searching text the page sends it: a new channel for the page's words into the host's
7492
+ UI, and its word of its own text anyway.
7493
+
7494
+ **Not covered** (each a gap a host may hear about): text in open shadow roots, in a page's own
7495
+ nested frames (P128) or in form fields' values, words in images or a canvas (the manual says to keep
7496
+ them as text), and words split across elements with no space between in the text (a table's
7497
+ cells: "foo bar" doesn't find `<td>foo</td><td>bar</td>`). Escape and Cmd+G in the frame are the
7498
+ page's: the host's bar closes and moves on from its own UI.
7499
+
7500
+ **Tested** (written 2026-11-04, not yet run: the authoring machine runs no tests; run `pnpm check`,
7501
+ `pnpm test:leak` on Chromium, WebKit and Firefox, and `pnpm --filter @botiverse/porthole
7502
+ test:controls find-requested-focus` before merging). Unit, `test/find.test.ts`: the matching
7503
+ (case, Unicode folding, spacing, literal syntax, no overlaps, the limits, `keep`, ten times the most
7504
+ looked at), the shortcut rule, the host's checks (`parseFindResult`, `parseFindReport`,
7505
+ `checkFindQuery`), only the latest query (`FIND_LATEST`: at once when nothing is queued, a burst
7506
+ of fifty as two searches with the rest answered superseded, a clear dropping what waits, its
7507
+ splice reading a request once), the shell (the runtime only where declared, beside annotations' with the text
7508
+ index in both, a plain script, the built-ins taken before the message listener, no live call or
7509
+ replaceable prototype method in the find runtime or the text index and the layer inserted through
7510
+ the guarded methods (P129, P130), the same layer style, no Highlight API, the fallback leaving the
7511
+ request alone), `createHost` over a stand-in
7512
+ platform (asked once the frame ran, its own id only, the box clamped; `-32601`, malformed and no
7513
+ answer are `"unsupported"`; nothing without `find`; an empty query clears; a query too long
7514
+ rejects; the shortcut sent to every frame, `requested` only while taken and with the page's focus;
7515
+ `updated` only while a query is shown; a reload, a restart after a navigation away and other
7516
+ content forget the query, content continued keeps it; a query cleared before the frame ran
7517
+ answers nothing; a query waiting when its frame stops is `"unsupported"` and never sent to the
7518
+ next frame; of the queries asked while the frame loads only the latest is sent; a superseded
7519
+ answer is `"unsupported"`; a destroyed display answers `"unsupported"`), the React handle's scope
7520
+ (`findScopeOf`, `sameFindScope`: the same content again or continued, by value, versus another
7521
+ generation, content, document, config, viewer, source or version), and the bridge (an event, a
7522
+ refusal, the rate). `test/agreement.test.ts`: a case
7523
+ with `find`, and Raft's shape with it. `test/react-ssr.test.ts`: the handle's and props' types.
7524
+ Browser, `leak/find.spec.ts` (three engines): highlights in the closed layer, next and previous into
7525
+ view (a scrolling box too), the box, case, clear; a change found again and told; a page's own query
7526
+ message ignored; the shortcut the browser's until taken, then the host's, a page's own find keeping
7527
+ it; and the hostile page's `requested` while the person types in the host's composer (the control's
7528
+ probe, with its positive control: taken with the person in the frame).
7529
+
7530
+ **Revisit when** a host needs matches in open shadow roots or a page's own frames, the person's
7531
+ Escape or Cmd+G in the frame should reach the host's bar, a host searches as the person types and
7532
+ wants the page not to see each keystroke (debounce in the host first), or engines give a frame a
7533
+ highlight registry content can't reach.
package/docs/DESIGN.md CHANGED
@@ -1181,6 +1181,38 @@ a selection away from a page that patched `Selection.prototype.removeAllRanges`,
1181
1181
  nothing back, leaves marks and drafts found, and the same words selected again are told
1182
1182
  (`clear-selection`).
1183
1183
 
1184
+ ### Find in page
1185
+
1186
+ A host's own find bar over a display (P131), where the config declares `find`:
1187
+
1188
+ - **Shell.** `FIND_RUNTIME` (`src/shell/find.ts`), spliced in as the annotation runtime is, before
1189
+ content runs. It finds a query (`porthole/find.query`, a request) in annotations' text index
1190
+ (`TEXT_INDEX`, `src/shell/text.ts`, shared), case-insensitive and loose about spacing
1191
+ (`FIND_MATCH`), only matches that are drawn, at most 1,000; draws them in a layer of its own (a
1192
+ closed shadow root, annotations' layer style), the current one apart, redrawn on scroll and
1193
+ resize and found again as the content changes (`porthole/find.updated`, at most once a second);
1194
+ brings the current one into view through its scrolling ancestors and the window; and, while the
1195
+ host says it draws its own bar (`porthole/find.handled`), cancels the browser's find on Cmd+F or
1196
+ Ctrl+F a page didn't take (`FIND_SHORTCUT`) and says `porthole/find.requested`. Like the guards
1197
+ (P129), it and the text index call only built-ins captured before content runs, through
1198
+ `callOf`; its layer goes in through the guarded insertion methods (P130,
1199
+ [insertion-entry-points.md](insertion-entry-points.md) § The shell's own layers).
1200
+ - **Host API.** `display.find.query(query, { direction, caseSensitive })` → `{ total, active,
1201
+ capped?, rect? }` or `"unsupported"` (no `find`, an older shell's `-32601`, a malformed answer, no
1202
+ answer in `FIND_LIMITS.timeoutMs`, a query superseded by a later one: the shell searches only the
1203
+ latest of a burst, `FIND_LATEST`), `clear()`, `takeShortcut(take)`; the query holds only for the
1204
+ content it was asked of (a new run or other content forgets it); events `findRequested`
1205
+ (only while taken, with the page's focus in the frame) and `findUpdated` (only while a query is
1206
+ shown), checked and rate-limited through the bridge. React: `onFindRequested`, `onFindUpdated`,
1207
+ and the handle's `find` and `clearFind`.
1208
+ - **Trust.** The page reads every query; what it says back is a find bar's numbers. Tests:
1209
+ `test/find.test.ts` (the matching and its limits, the shortcut rule, the checks, the shell's
1210
+ splice and built-ins, only the latest query, `createHost`'s requests, answers, forgetting and
1211
+ gates, the React handle's scope); `leak/find.spec.ts`
1212
+ on three engines (highlights, next and previous into view, a scrolling box, a change found again,
1213
+ the shortcut the host's only while taken and the page's own find keeping it, and a hostile page's
1214
+ `requested` while the person types in the host's composer dropped: `find-requested-focus`).
1215
+
1184
1216
  ## The shell runtime
1185
1217
 
1186
1218
  The runtime (`src/shell/runtime.ts`, plain ES2020, no build) runs first in every
@@ -1514,6 +1546,7 @@ control the tables above name to the registry):
1514
1546
  | `blob-trusted` | `served/runtime.spec.ts` | `a script asset runs as code only if an admin uploaded it where uploads are the admins'` | — | — |
1515
1547
  | `blob-script,blob-trusted` | `served/runtime.spec.ts` | `a script asset runs as code only if an admin uploaded it where uploads are the admins'`, `scripts load from /_blob/ only where uploads are the admins' (a tab, its session)` | — | — |
1516
1548
  | `blob-inert` | `served/runtime.spec.ts` | `an asset opened on its own runs nothing, on a tab with the artifact's session` | — | — |
1549
+ | `find-requested-focus` | `find.spec.ts` | `a hostile page says the find shortcut was pressed while the person types in the host's composer: the host's find bar stays shut (P131)` | — | — |
1517
1550
 
1518
1551
  ## Milestones
1519
1552