The Chrome extension, moved here from iterate/private: source, build and releases
Jonas Templestein, 2026-11-27 22:46 UTC · 8d04a3a46c48a61e12b3cb56f989001eaf232db1 · the first commit
43 files changed
- A .gitignore
- A README.md
- A extension-key.txt
- A oauth.js
- A package.json
- A pnpm-lock.yaml
- A pnpm-workspace.yaml
- A public/address.js
- A public/background.js
- A public/icon-128.png
- A public/icon-16.png
- A public/icon-32.png
- A public/icon-48.png
- A public/index.html
- A public/indicator.js
- A public/instructions.js
- A public/lend.js
- A public/manifest.json
- A public/offscreen-client.js
- A public/offscreen.html
- A public/offscreen.js
- A public/panel.js
- A public/profile.js
- A public/rpc-transport.js
- A public/socket-worker.js
- A releases/index.json
- A releases/iterate-chrome-extension-0.8.3.zip
- A scripts/build.ts
- A scripts/release.ts
- A src/extension.test.ts
- A src/lending.test.ts
- A src/locator-runtime.ts
- A src/page.test.ts
- A src/page.ts
- A test/address.test.ts
- A test/oauth.test.ts
- A test/offscreen.test.ts
- A test/panel-ui.test.ts
- A test/panel.test.ts
- A test/profile.test.ts
- A test/worker.test.ts
- A tsconfig.json
- A vitest.config.ts
A .gitignore
@@ -0,0 +1,2 @@ +node_modules/ +dist/
A README.md
@@ -0,0 +1,335 @@ +# Iterate browser extension + +A Chrome extension that lends this Chrome to an iterate mind, at the mind's own address +(`iterate.<address>`). The files in `public/` run as written, and `pnpm build` writes `dist/`, the +unpacked extension: `public/` plus capnweb's browser bundle as `capnweb.js`, `oauth.js` and the two +bundles of `src/`. `pnpm release` zips `dist/` into `releases/`, and +[chrome.iterate.com](https://chrome.iterate.com/) serves that ZIP from this repo (below, +**Release**). + +**This repo is the extension's home since 27 Nov 2026.** Before, it was +`packages/browser-extension` of iterate/private (archived that day; its last commit there is +40c2590b2, version 0.8.3), and the static Worker of `packages/spa` built and served the ZIP. The +code was moved as it was: `oauth.js` is a copy of `packages/spa/public/oauth.js`, the versions in +`package.json` are those that iterate/private's lockfile had, and a build of this repo gives the +22 files of the 0.8.3 ZIP that the old Worker served, byte for byte. It may still need a little +fiddling in its new home. + +The service worker owns sharing state and browser access. An offscreen document hosts a dedicated +worker with the authenticated WebSocket and capnweb session. The panel is a view; closing it leaves +sharing on. Chrome restart or extension reload leaves sharing off. + +- `public/manifest.json` — MV3; `debugger`, `declarativeNetRequestWithHostAccess`, `identity`, + `alarms`, `offscreen`, `sidePanel`, `storage`, `tabGroups`. Not `tabs`: URLs and titles come from the debugger's target + list. No host permission at install: at sign-in the panel asks for the mind's + host (`https://iterate.<address>/*` and its `wss:` twin), from `optional_host_permissions`. +- `public/background.js` — the service worker owns one lending controller and its UI ports. + `SHARE_ON_BROWSER_START = false` is the single startup-sharing policy setting. +- `public/lend.js` — sign-in, bounded recovery, live group checks, CDP and the API proxy. + `chrome.storage.session` holds sharing intent, retry budget/deadline and owned debugger IDs + across worker termination. Chrome clears this state on browser restart or extension reload. +- `public/offscreen-client.js` — one validated runtime port, serialized document creation/cleanup + and an API proxy. A fresh document URL nonce rejects old or unrelated ports. +- `public/offscreen.html` and `public/offscreen.js` — the hidden document uses only Chrome's runtime + API and hosts `public/socket-worker.js`, which owns the socket and external capnweb session. + `public/rpc-transport.js` carries capnweb strings across the port; it does not queue browser actions + for recovery. The `WORKERS` offscreen reason matches the dedicated worker it creates. +- `public/address.js` — the mind's address from what a person typed, by the rule of + `iterate/mind-api`, applied once; and its issuer. +- `public/profile.js` — the mind's name and logo, read from its website's public profile + (below, **How a mind is shown**). +- `public/instructions.js` — agent instructions prepared by the worker; the panel copies the text. +- `public/icon-{16,32,48,128}.png` — the iterate logo, as + PNGs (Chrome takes no SVG icons). Flat in `public/`: the release's zip packs only top-level files. +- `public/index.html` — the panel page (its styles inline). +- `public/indicator.js` — the frame and label the person sees on a tab the mind is attached to + (below, **What the person sees**). `lend.js` reads it and runs it in the page through CDP. +- `public/panel.js` — a control view of the worker. It cannot lend a second socket. + It requests sign-in through Chrome's identity window and shows the worker's live lending state. + The worker registers a public client at each sign-in and keeps its session in `chrome.storage.local`. + The service worker controls one offscreen transport to `wss://iterate.<address>/api` and the + lend: `itx.provide("itx.chrome.<person>.<browser>", new ChromeBrowser())` on the mind's root + context (below, **The name**) — an + `RpcTarget` with `tabs()` (the tabs in the mind's tab group: id, URL, title), + `openPage({ url })` (a new tab in the group, answered once loaded), `cdp(tabId, method, params)` (one raw Chrome DevTools Protocol command; of CDP's events only + `Runtime.bindingCalled` comes back, as a page report, below; `Runtime.evaluate`, `Page.captureScreenshot`, `Accessibility.getFullAXTree`, `Page.navigate`, + `Input.dispatchMouseEvent` cover most of what an agent wants) and `detach(tabId)`. +- `dist/oauth.js` — the OAuth client, `oauth.js` of this repo, copied by the build. It began as a + copy of the static SPA's client (`packages/spa/public/oauth.js` of iterate/private); nothing + keeps the two in step. +- `dist/capnweb.js` — capnweb's browser bundle, copied from `node_modules` by the build: the + version that `package.json` pins, the one a mind speaks. Chrome loads no remote code from an + extension, so the extension carries it. + +**Closing the panel.** Sharing continues with no panel open. Turn sharing off or sign out to end +the lend. Taking tabs out of the mind's group revokes those tabs. Chrome startup sharing is off; +a stopped worker within the same Chrome run uses the bounded recovery below. + +**Which tabs.** The mind drives the tabs in its tab group: every Chrome tab group whose title is +exactly the mind's address (`iterate.com`), in any window. Membership is the permission. The worker +reads it live from Chrome on every call, and stores no group id. So a Chrome restart, a group moved +to another window and one group per window all work. A renamed group loses its tabs; a group named +back gets them back. + +A tab joins when the person drags it into the group or clicks **Add this tab** in the panel, and +when the mind opens it with `openPage`. A page that a grouped tab opens joins too, by Chrome's +opener rule. A tab leaves when the person drags it out, clicks **Remove** in the panel's list, or +closes it. `cdp` on a tab outside the group is refused, also while the debugger is still attached. +The worker makes a group with a fixed color per mind, and never changes a group after that. + +The debugger attaches on the first `cdp` (Chrome shows its "is debugging this browser" bar on the +tab). It lets go on `detach`, when the tab leaves the group, and on sign-out. **Cancel** on +Chrome's debugging bar detaches every tab: the worker then takes every tab out of the group, so the +mind cannot attach again. Sign-out, or a switch to another mind, keeps the group: with no lend, or +a lend to a mind with another address, no tab is drivable. + +**What the person sees.** While the mind's debugger is attached to a tab, besides Chrome's +debugging bar: + +- A frame on the edge of the tab's page, in one iterate color, and a small label at the top + center: the mind (below, **How a mind is shown**) and what it does ("is using this tab", "is + clicking"), with a **Stop** button. The frame glows stronger and pulses for 3 s after each + command (no pulse with reduced motion). The words come from the command's method: clicking, + typing, opening a page, looking (a screenshot), reading the page (`Runtime.*`, `DOM.*`, + `Accessibility.*`, `CSS.*`), working. +- `indicator.js` runs in an isolated world, `iterate-indicator`, of the top frame only, on the page + that shows at attach and on every page the tab loads after; its elements sit in a closed shadow + root, so the page's scripts and CSS cannot reach inside. It goes before the worker detaches; after + a detach Chrome does by itself (Cancel on the bar, a stopped worker), the page cannot tell + (a binding outlives its session): the worker writes a heartbeat every 4 s, and the indicator + removes itself after 12 s without one. +- **Stop** calls a CDP binding that only that world has: the tab leaves the group and the + debugger lets go, as if the person had dragged it out. It never reaches the stream as a page + report. +- The toolbar button shows "on" on that tab, in a stronger color while the mind acts. The panel's + tab list shows the word while the mind acts, "in use" otherwise. +- A mind's `Page.captureScreenshot` leaves the frame and label out: the worker hides them, waits + two frames, takes the screenshot and shows them again. +- Closing a panel leaves the worker and its lend active. Worker termination ends that socket; + the next wake releases recorded debugger targets before it makes a fresh lend. The group stays. +- The worker keeps the Page and Runtime domains on (the indicator, navigation facts and page + reports need them): `cdp` answers `Page.disable` and `Runtime.disable` with `{}` and does not + send them. + +**How a mind is shown.** Everywhere the extension names a mind (the panel's header once signed +in, the label on a tab), it shows the mind's logo on the left, then its name over its address, or +the address alone for a mind with no name. The address is always there: it is what the person +signed in to and the title of the tab group. + +- The name and the logo are the mind's profile, `https://<address>/.well-known/iterate-profile` + (`profile.ts` of the mind's config). Its website answers it to anyone with + `access-control-allow-origin: *`, so the worker reads it with no host permission and no + credential: when a session shows, at sign-in and at each connect. A read with no answer keeps + what an earlier read of the same mind got. +- The profile is the owner's own words, unsigned, and proves nothing. `profile.js` takes two + fields from it and drops the rest. The name is one line of at most 80 characters, with no + control character and none that reorders text, and is only ever written as text. The profile's + default name is the hostname, which counts as no name. The logo must be an `https:` address on + the mind's website or a host under it, and is only ever an `<img>`, asked for with no referrer. +- A mind with no logo, and a logo that does not load, show iterate's mark in the panel and the + plain dot in the label. A page whose content policy refuses the image gets the dot too. +- No lend, group or permission depends on the profile. + +**What reaches the stream.** The CDP wire stays a wire, but the browser's facts go to the mind's +root stream, each with the `lendName`: + +- `events.iterate.com/chrome/tab-added { tabId, url }` and `chrome/tab-removed { tabId }` are + durable: a tab joined or left the group. Each lend announces every member again. +- `chrome/binding-called { tabId, name, payload }` is durable: a page report. The mind adds a CDP + binding (`Runtime.addBinding`, best in an isolated world from `Page.createIsolatedWorld`), and + each call of it from a tab in the group appends its string. To keep the script on every page + the tab loads, the mind also sends `Page.addScriptToEvaluateOnNewDocument` with + `{ source, worldName }` (a mind whose stack is older than this refuses the `source` argument: + then the script lives in the current page only). A payload over 8,192 characters is dropped. + The event type is always the extension's own: the worker appends as the person. +- `chrome/attached { tabId, url }`, `chrome/navigated { tabId, url }` (main-frame navigations of + attached tabs) and `chrome/detached { tabId, reason }` are ephemeral: live subscribers see them, + and `readEvents` with `includeEphemeral` reads the recent ones. + +**The socket.** The API accepts a bearer on its WebSocket upgrade. The service worker adds one +`declarativeNetRequest` session rule for this extension's own `websocket` request to that exact URL. +The next connection replaces the rule; sign-out removes it. Chrome drops session rules when it quits. +A service-worker WebSocket bypasses DNR in Chromium 155. The dedicated worker hosted by the +[offscreen document](https://developer.chrome.com/docs/extensions/reference/api/offscreen) uses +that existing header path. No core authentication route or stack change is needed. + +The API has no other transport than the socket, and checks the bearer inside the session: the +socket's worker calls `authenticate()` with no token, which reads the bearer of the upgrade, and +takes the session's `mind`. A bearer that the mind refuses fails the first call with the code +`UNAUTHENTICATED`, which ends recovery and waits for the person. The socket closes with 1008 and +the reason "the sign-in for this session ended: authenticate again" at the token's end, which +renews the token, and with 1012 when the mind behind the session restarted, which reconnects. + +The worker creates the offscreen document when it connects. Closing the panel does not touch it. +Document loss ends that transport; the worker's bounded recovery creates a fresh document. Losing +the worker's runtime port terminates the document's socket worker. Chrome alarms restore the +service-worker controller after suspension. Only the controller chooses whether and when to lend; +the offscreen document has no retry policy, tab access or stored credentials. + +Transient overloaded/unavailable answers and deploy disconnects retry for 30 minutes from the +first failure. Exponential backoff uses jitter; after reaching its 60-second cap, waits use narrow +54–60-second jitter until that original deadline. Overload waits at least 10 seconds. A valid longer +server cooldown is respected. No attempt starts after +the recovery deadline. The panel shows **Reconnecting, try N**, then **Lend again** when the window +ends. Successful probes must demonstrate 60 seconds of continuous health before resetting the window +and count. A reply gap beyond the 20-second cadence plus its 15-second deadline restarts that +health interval. Time asleep is not credited; a restarted worker starts fresh health evidence. +The deadline and count survive worker loss; restarting the worker does not extend the window. +Turning sharing off, signing out or a displaced lend stops recovery. Authentication refusals and +interrupted token refreshes still need a person. A handshake has 20 seconds to answer; the live +connection checks a read-only `tabs()` round trip through its own lent name every 20 seconds, with +a 15-second deadline. This detects a failed internal pager even while the API socket stays alive. This sends traffic within +Chrome's 30-second worker idle window: one setup `whoami()` and lend probe, then at most three +read-only heartbeat probes per minute. Resolved offline notices also start recovery; an explicit +return or replacement still waits for the person. +Opening a panel adds no mind calls. A local Chrome alarm wakes recovery at 30-second intervals; +it makes no mind call while the existing connection is healthy. Retry deadlines and counts survive +worker termination. The OAuth client awaits a durable refresh-intent callback at its actual rotating refresh +boundary. Worker loss there waits for a person; a cached-token read remains recoverable. Repeated worker losses share the same 30-minute deadline. + +During a disconnect, the worker clears the local lend and releases its debuggers. The tab groups +stay in Chrome. Recovery makes a fresh lend and reads membership again. It never repeats browser +actions or queued page reports from an old connection. Old browser/page handles are refused; +get the current lend and make fresh handles after recovery. Teardown has separate bounded waits; +a native attach or detach that has not answered must settle before that tab can attach again. +Sign-out cancels retries. A lend displaced +by another install still waits for **Lend again**. Retry and give-up records go to the service-worker console +as `browser-extension.platform-failure-retry` and `browser-extension.platform-failure-gave-up`. + +**The name.** Every lent Chrome has its own name, `itx.chrome.<person>.<browser>`, so two people +in one mind, or one person's two Chrome profiles, never take each other's. `chrome` comes first +because a lent name never starts with a name of the platform's (core's `lendRefusal`), and a +person's segment could be one (`email`, `run`). `<person>` is the +signed-in address before its `@` (`jonas`); `<browser>` is made at the first connect from the +platform and a random suffix (`mac3f9a`), kept in the install's storage, and the panel's **Rename +this browser** changes it (letters and digits). The newest lend of a name wins: when another panel +takes this one's name, the mind ends this lend and the panel stops with **Lend again**, so two +panels never trade a name back and forth. An agent finds every lent Chrome in its capability tree, +or with `(await itx.rewriteRules.list()).filter((rule) => /^itx\.chrome\./.test(rule.match))`. +A 0.4.0 panel lent itself as plain `itx.chrome`; the longer rule wins, so it never takes a call +meant for a named Chrome. + +The lend is a rewrite rule of the mind's root context, `/`: anything calling +`itx.chrome.jonas.mac3f9a.openPage(...)` there runs it in the worker while sharing is on; from another context of the mind (an agent's script runs in its own) the spelling is +`itx.cd('/').chrome.jonas.mac3f9a.openPage(...)`. The panel's **Copy instructions for an agent** +button copies that spelling, the methods, how a page reports to the mind and the tabs in +the group right now, for a person to paste to an agent. + +## Playwright-shaped controls (prototype) + +`page(tabId)` returns an RPC handle for one tab. Agents can pipeline locator calls: + +```js +const chrome = itx.cd("/").chrome.jonas.mybrowser; +const { tabId } = await chrome.openPage({ url: "https://example.com/form" }); +const page = chrome.page(tabId); +await page.getByLabel("Email", { exact: true }).fill("agent@example.com"); +await page.getByRole("button", { name: "Save", exact: true }).click({ timeout: 5000 }); +``` + +Use a browser name from the capability tree. `page` does not navigate or authorize tabs. +All of its CDP calls pass through the existing `cdp` method, including calls from retained +handles. The mind's tab group remains the grant. Raw `cdp` and `detach` remain available. + +Supported methods: + +- `page.getByRole(role, { name, exact, disabled, includeHidden, checked, expanded, level, +pressed, selected })`, `getByText(text, { exact })`, `getByLabel(text, { exact })`, + and `locator(selector)`. These can also chain from a locator. +- `locator.first()`, `nth(index)` (nonnegative), `count()`, and `textContent({ timeout })`. +- `locator.click({ timeout })`, `fill(text, { timeout })`, and `press(key, { timeout })`. + Keys: `Enter`, `Tab`, `Backspace`, `Escape`, `ArrowLeft`, `ArrowRight`. + +Matchers are strings. Matching defaults to substring matching; use `exact: true` where needed. +[`ivya` 1.8.2](https://github.com/vitest-dev/ivya) supplies selector, role, label and accessible-name +semantics. [Vitest's locator API](https://vitest.dev/api/browser/locators) uses the same engine. +We bundle it at build time; there is no runtime CDN dependency or copied selector engine. +The preview provider uses synthetic user events; this prototype uses CDP for trusted mouse, +text and keyboard input. Focus and text selection happen in an isolated world in the target tab. + +Actions resolve the locator again on every poll. They wait for visibility, enabled state, +a stable bounding box, and a center point that receives input. Fill also requires an editable +text input or textarea. Duplicate matches fail immediately with sample HTML. A timeout includes +the locator and the last unmet condition. Calls on one tab run in order. Queue wait counts toward +the deadline: default 5,000 ms, allowed range 1–30,000 ms. Mouse/key release has a separate bounded +cleanup allowance of 1,000 ms, including on failure. A stalled CDP command cannot hold the caller +forever, but a command already sent to Chrome cannot be cancelled. + +This is a small subset, not Playwright compatibility. It supports the main frame and open shadow +roots. Frames, regular expressions over RPC, modifiers, contenteditable, numeric/date/select/file +inputs, assertions, screenshots and navigation methods are outside this facade. Use raw CDP where +needed. A locator retained across a completed navigation resolves in the new document. A navigation +that destroys a context or changes the document before input fails the action. Actions do not wait +for navigation and never replay dispatched input. DOM and navigation changes can still race the +separate CDP commands; this does not give atomic or exactly-once interaction guarantees. Raw CDP +input can also race the facade's queue. + +### Development checks and release + +`pnpm test` builds the extension and runs real Chromium +fixture tests, including the packaged facade through `chrome.debugger` in a fresh headless +extension profile. It also runs the panel connection tests in a VM with controlled Chrome, RPC +and clock fixtures. Install the test browser with +`pnpm exec playwright install chromium` first. `pnpm check` runs the type check and the tests: +nothing runs them for you. `test/address.test.ts` compares the panel's address rule with the +platform's, from a checkout of `/repos/kernel` in the folder beside this repo, and is skipped +without one. +Tests use local HTTP/TLS fixtures only. The signed-in lifecycle test uses fixture-only session +values and a local WebSocket mind API with the unmodified extension. It covers group removal and +restoration, group rename, detach and reattach, sign-out, switching minds, continued lending after +panel closure, and alarm recovery after forced service-worker termination. VM tests cover the +persistent retry budget, heartbeat rate, interrupted refresh and startup sharing policy. No real +account, credential, browser profile or user tab is imported. It exercises the lending and group +policy; it does not automate a member's passkey login and consent. + +### Release + +A release is one file of this repo, on `main`: `releases/iterate-chrome-extension-<version>.zip`, +with its row in `releases/index.json` (`file`, `sha256`, `bytes`). `current` there is the version +that the install page offers. The mind's host `chrome.iterate.com` reads both from this repo's +main at a request (`apps/chrome/` of `/repos/config`), and serves a ZIP only when its bytes have +the sha256 of its row. So **the push to main is the publication**: no deploy, and no commit to the +mind's config. `await itx.config.chromeExtension()` answers what is served. + +1. Review the subset and input races, and run `pnpm check`. +2. Raise `version` in `public/manifest.json` and in `package.json` (the same value), and the + version that **Install** below names. +3. `pnpm release`: it builds `dist/` with iterate's key (`extension-key.txt`: the public half, + which every released `manifest.json` holds; it fixes the extension's id, and so each install's + OAuth redirect), writes the ZIP and its row, and makes it `current`. Every entry of the ZIP + has one fixed time, so the same commit gives the same bytes. +4. Commit the source and `releases/` together, and push to `main` (a clone and a push need the + repo's token: AGENTS.md of `/repos/config`, "Where the code lives"). Then tag that commit + `v<version>` (the skill `cut-release` of the mind). +5. Read `https://chrome.iterate.com/`: it offers the new version within a minute. Then reload + each unpacked install: a source change alone does not update an installed extension. + +A released version is never changed: `pnpm release` stops when its build differs from the kept +ZIP of the same version, and `node scripts/release.ts --verify` compares the two and writes +nothing. To go back to an older version, set `current` in `releases/index.json` to it and push: +its ZIP stays in the repo. + +## Install + +Download the current ZIP from [chrome.iterate.com](https://chrome.iterate.com/) and unzip it, or +build `dist/` from this repo (`pnpm install && pnpm build`). `public/manifest.json`'s `key` is a +placeholder: `scripts/release.ts` puts iterate's key in a release's ZIP, so existing installs +retain their extension ID and OAuth redirect URI, and `pnpm build` leaves it out of a `dist/` you +build, so Chrome derives the ID from its folder. The panel heading shows the version. + +Chrome 123 or newer (the styles use `light-dark()`). Open `chrome://extensions`, enable **Developer mode**, **Load unpacked**, select +the unzipped folder or this repo's `dist`. Pin it from the toolbar's extensions menu and +click its button to open the panel. Enter the mind's address (`iterate.com`, or +`iterate.iterate.com`) and click **Sign in with Iterate**: Chrome asks for access to the mind's +host, then the mind's own sign-in and consent pages open in a Chrome identity window. Click +**Share this browser**. Closing the panel keeps sharing on. **Turn sharing off** or **Sign out** +ends it. The panel shows **Connected · sharing on** only after the mind accepts the current lend. + +To update an existing install to 0.8.3: replace the files in the installed folder, click **Reload** +on its extension card, then close and reopen the panel. Confirm **v0.8.3** and click +**Share this browser**. After Chrome restarts, sharing is off even if sign-in was remembered. +Open the panel and turn sharing on again. Automatic sharing on browser startup is not enabled; +the policy is the one `SHARE_ON_BROWSER_START` setting in `public/background.js`. + +After editing a file, build again and click **Reload** on the extension's card. +Unpacked extensions do not update automatically: the install page says how to update one.
A extension-key.txt
@@ -0,0 +1,1 @@ +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAspgSUwSfiXguZe3WByjp613X57nr6/xazInTLwa7flo9sR1XREgiLCG1ZcrWR8LoottD2Hbs9ESpRLbIapj6rDAZwc/o3Q9HNVqNaS1AyInNG3WFHs8EFM/zS5UWZ5FxV5hHwQv5/soV24FDkcfvjJ81GwwizSsBxG0YTap+2WRQZkyipnQLQLgpf7Ei+MfIhUchxb4TBjgs9dKCD6ObRkHunEg3NUENGoVoKAs3+CctotvenoxgTsjLByC3tJBRwF7NLorAockPz7l6THWwi1F7J25LpvUpB0TdYrU8U2ygNUefU7+dWgkN13av5iAll2/sFNPJEsnwGpfVNagJZwIDAQAB
A oauth.js
@@ -0,0 +1,161 @@ +// oauth.js — THE OAUTH CLIENT of a page with no server of its own, one file for the static SPA +// (which serves it as written) and the Chrome extension (whose build copies it into its dist/): +// discovery, a public-client registration at each sign-in (RFC 7591), PKCE (S256), the callback, +// and refresh through the rotating refresh token, for the scope `iterate` and the resource +// `<issuer>/api`. The client id lives in the sign-in in flight and then in the session, nowhere +// else. Its host says where things are kept and how the browser gets to the issuer and back: +// - `sessions` keeps the sign-in in flight and the session (the SPA: this tab's sessionStorage; +// the extension: chrome.storage.local, until sign-out); +// - `redirectUri` is where the issuer sends the browser back, and `launch(url)` opens the +// issuer's authorization URL and resolves with the URL it came back to (Chrome's identity +// window). A page that navigates to the issuer never resolves: it is loaded again at +// `redirectUri` and hands that URL to `finishSignIn` itself. +// The access token is short-lived (the issuer renews an interactive grant's token hourly), so a +// leak is bounded. + +const PENDING = "oauth:pending"; +const SESSION = "oauth:session"; + +/** A Web Storage area (localStorage, sessionStorage) as a store: JSON values by key. */ +export const webStore = (storage) => ({ + get: async (key) => JSON.parse(storage.getItem(key) || "null"), + set: async (key, value) => storage.setItem(key, JSON.stringify(value)), + remove: async (key) => storage.removeItem(key), +}); + +const base64url = (bytes) => + btoa(String.fromCharCode(...bytes)) + .replaceAll("+", "-") + .replaceAll("/", "_") + .replace(/=+$/, ""); +const random = () => base64url(crypto.getRandomValues(new Uint8Array(32))); + +async function discover(issuer) { + const response = await fetch(`${issuer}/.well-known/oauth-authorization-server`); + if (!response.ok) throw new Error(`${issuer} is not an OAuth issuer (${response.status})`); + return response.json(); +} + +async function tokenRequest(endpoint, params) { + const response = await fetch(endpoint, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams(params), + }); + if (!response.ok) + throw new Error(`The token endpoint answered ${response.status}: ${await response.text()}`); + return response.json(); +} + +/** The client: `registration` is what the issuer's consent page shows of it (`client_name`, + * `client_uri`, `logo_uri`). */ +export function oauthClient({ sessions, redirectUri, launch, registration, beforeRefresh }) { + /** A public client (no secret), registered for this sign-in. */ + async function register(metadata) { + const response = await fetch(metadata.registration_endpoint, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + ...registration, + redirect_uris: [redirectUri], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + }), + }); + if (!response.ok) throw new Error(`Client registration failed (${response.status})`); + const { client_id } = await response.json(); + return client_id; + } + + async function store(issuer, clientId, tokens, previousRefreshToken) { + const session = { + issuer, + clientId, + accessToken: tokens.access_token, + // Refresh tokens rotate: the newest one wins, the previous one stands in when none came. + refreshToken: tokens.refresh_token || previousRefreshToken, + expiresAt: Date.now() + tokens.expires_in * 1000, + }; + await sessions.set(SESSION, session); + return session; + } + + /** The callback half: the URL the issuer sent the browser back to, `?code=&state=` or + * `?error=`. Resolves with the stored session. */ + async function finishSignIn(callback) { + const pending = await sessions.get(PENDING); + await sessions.remove(PENDING); + const params = new URL(callback).searchParams; + const oauthError = params.get("error"); + if (oauthError) throw new Error(params.get("error_description") || oauthError); + if (!pending || params.get("state") !== pending.state) + throw new Error("The OAuth state did not match — start the sign-in again."); + const code = params.get("code"); + if (!code) throw new Error("The issuer sent the browser back without an authorization code."); + const metadata = await discover(pending.issuer); + const tokens = await tokenRequest(metadata.token_endpoint, { + grant_type: "authorization_code", + code, + redirect_uri: redirectUri, + client_id: pending.clientId, + code_verifier: pending.verifier, + resource: `${pending.issuer}/api`, + }); + return store(pending.issuer, pending.clientId, tokens); + } + + return { + /** Sign in at `issuer`: its own login and consent pages, through `launch`. Resolves with the + * stored session once `launch` does. */ + async signIn(issuer) { + const metadata = await discover(issuer); + const clientId = await register(metadata); + const verifier = random(); + const state = random(); + await sessions.set(PENDING, { issuer, clientId, verifier, state }); + const url = new URL(metadata.authorization_endpoint); + url.search = new URLSearchParams({ + response_type: "code", + client_id: clientId, + redirect_uri: redirectUri, + code_challenge: base64url( + new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier))), + ), + code_challenge_method: "S256", + scope: "iterate", + state, + resource: `${issuer}/api`, + }).toString(); + // A closed identity window leaves no verifier behind. + const callback = await launch(url.href).catch(async (error) => { + await sessions.remove(PENDING); + throw error; + }); + return finishSignIn(callback); + }, + finishSignIn, + /** The stored session, or null — read fresh each time: a refresh rotates the token in it. */ + session: async () => (await sessions.get(SESSION)) || null, + /** The access token, refreshed through the refresh token when it is about to expire. */ + async freshAccessToken() { + const session = await sessions.get(SESSION); + if (!session) throw new Error("Not signed in."); + if (Date.now() < session.expiresAt - 30_000) return session.accessToken; + if (!session.refreshToken) + throw new Error("The access token expired and the grant cannot refresh. Sign in again."); + // The host can persist refresh intent before the rotating request can consume its token. + await beforeRefresh?.(); + const metadata = await discover(session.issuer); + const tokens = await tokenRequest(metadata.token_endpoint, { + grant_type: "refresh_token", + refresh_token: session.refreshToken, + client_id: session.clientId, + resource: `${session.issuer}/api`, + }); + return (await store(session.issuer, session.clientId, tokens, session.refreshToken)) + .accessToken; + }, + signOut: () => sessions.remove(SESSION), + }; +}
A package.json
@@ -0,0 +1,28 @@ +{ + "name": "@iterate-com/chrome-extension", + "version": "0.8.3", + "private": true, + "type": "module", + "packageManager": "pnpm@12.18.0", + "scripts": { + "build": "node scripts/build.ts", + "release": "node scripts/release.ts", + "typecheck": "tsc --noEmit", + "test": "node scripts/build.ts && vitest run src && node --experimental-vm-modules --test --test-isolation=none test/*.test.ts", + "check": "pnpm typecheck && pnpm test" + }, + "devDependencies": { + "@playwright/test": "1.63.0", + "@types/node": "26.6.6", + "@types/ws": "8.18.1", + "capnweb": "npm:@iterate-com/capnweb@0.13.0", + "esbuild": "0.28.2", + "fflate": "0.8.3", + "typescript": "7.0.2", + "vitest": "4.1.11", + "ws": "8.21.3" + }, + "dependencies": { + "ivya": "1.8.2" + } +}
A pnpm-lock.yaml
@@ -0,0 +1,1459 @@ +--- +lockfileVersion: '9.0' + +importers: + + .: + configDependencies: {} + packageManagerDependencies: + pnpm: + specifier: 12.18.0 + version: 12.18.0 + +packages: + + '@pnpm/exe.android-arm64@12.18.0': + resolution: {integrity: sha512-fOF6IwgvnUKEmVedGqiAsNPfN2Ry8GvaqzSQOiF3RJFbpBfPKO/6YT54s1GjToyYinRxw9preHHPe4y2N3SzhA==} + cpu: [arm64] + os: [android] + + '@pnpm/exe.android-x64@12.18.0': + resolution: {integrity: sha512-6OiolnaCsB3/GcJ9XNrenbUH3zFHRJ+5QynrMUUEyThbgnnCzWxa199hpQlOmxN4rAXuYQ0IYgWFNUZxyzg31Q==} + cpu: [x64] + os: [android] + + '@pnpm/exe.darwin-arm64@12.18.0': + resolution: {integrity: sha512-zkq+4YzVIX39ETYLyC3W7LY7MpHEU/J3nRhHl4i2yPld2Cf2+rEKRh3ejJ4AmaQ77HHJLCktY4Z3jq0fpcxFXg==} + cpu: [arm64] + os: [darwin] + + '@pnpm/exe.darwin-x64@12.18.0': + resolution: {integrity: sha512-qMsL9qx92unOTa6hgkfiTJv8ceZaTx0IQg7InhYDVX2ZrTECujaVEEVypnJK5m3eGUsP1KD7Y4qIgleCwfRsYw==} + cpu: [x64] + os: [darwin] + + '@pnpm/exe.freebsd-x64@12.18.0': + resolution: {integrity: sha512-/9vy/4ms52cU4MjZ5NhHd6N2d9L9W0kARf5/ff2tweAHu0VeUzs/0qp/7ZHFuddm2Wa/m0AKQoPum9AVUCqKsw==} + cpu: [x64] + os: [freebsd] + + '@pnpm/exe.linux-arm64-musl@12.18.0': + resolution: {integrity: sha512-Vp+TIMPPyackVCXkOdEKH/RmAn/r07EcIyrgZYQK7VrkksqZOie0GnWIx+85mPqeFEYCRtXIZAFJ9L4ceTndDg==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@pnpm/exe.linux-arm64@12.18.0': + resolution: {integrity: sha512-2dpyVBCHT+FfpuQh9i+7MXAqNWYLCvD5vYr5p6Eimxoga8USLnjbUgyj72AOrO0hjc5ri3TEFP3jiyBHjkSZpQ==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-ppc64@12.18.0': + resolution: {integrity: sha512-BBOOOfNJ2QwIIya3eKqOjiN4WNTszfRz7HCvw9XggcT7+ftMjNP8XJ/GfW+ltCBeUFR9d8WBVsr2m/NLjX2CZQ==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-riscv64@12.18.0': + resolution: {integrity: sha512-7kMN77xSOYJX8GPSH5RbNAc5oM61LMmcSUukDDUwllnZPXm8GRPskCNsTWy8SCw01Kr1FB+5SwGNMiTdiziLNQ==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-s390x@12.18.0': + resolution: {integrity: sha512-htuSCpEcmDzhKoJqXbPkvfr176dBHU0QIF5mWcRiqxRXAB/1JoYiMYotfjWpk+ztgpB9qlx4XnWlLFAf7gzc6g==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-x64-musl@12.18.0': + resolution: {integrity: sha512-Uj+vzfIQ62kDP10x36yHZIXVs5ohdNtiPYwn5FhCLlNScHPo0OAI+ShGDtLofiBXKE7umu71Jmjm7N8a8zVcDw==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@pnpm/exe.linux-x64@12.18.0': + resolution: {integrity: sha512-OJ+X2wcraldCwj75pCIerWARQSRpdfj0eBTs/2ODyhfeW46ylOnjTIE/GKra6Mn6E72/gBmXS8igrUioa+F9fQ==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.win32-arm64@12.18.0': + resolution: {integrity: sha512-wEY6jiACGcbhhi5yD59doHqNTndS7AaujaPmtWAu1DKkHru2hy5fJ9yUGecW72Ypaw2/I3BEprfMOopap2NQtw==} + cpu: [arm64] + os: [win32] + + '@pnpm/exe.win32-x64@12.18.0': + resolution: {integrity: sha512-5FJkghO7RLRkQpWxeVEygW9XsmnNuxzPfXbgwFWCHsFyFhpDn/vOdL88ToQEM0Kt5igdW5s6U0/IDH8Dvkt3pg==} + cpu: [x64] + os: [win32] + + pnpm@12.18.0: + resolution: {integrity: sha512-nXiC1dyCFH7PxOBiqjSDTgrQKWcQoYN6ERWuASEn02txCeMhrBWYod0KZVl2gbHpmRfhLtDXSerpEYeUM2O+sw==} + engines: {node: '>=18'} + hasBin: true + +snapshots: + + '@pnpm/exe.android-arm64@12.18.0': + optional: true + + '@pnpm/exe.android-x64@12.18.0': + optional: true + + '@pnpm/exe.darwin-arm64@12.18.0': + optional: true + + '@pnpm/exe.darwin-x64@12.18.0': + optional: true + + '@pnpm/exe.freebsd-x64@12.18.0': + optional: true + + '@pnpm/exe.linux-arm64-musl@12.18.0': + optional: true + + '@pnpm/exe.linux-arm64@12.18.0': + optional: true + + '@pnpm/exe.linux-ppc64@12.18.0': + optional: true + + '@pnpm/exe.linux-riscv64@12.18.0': + optional: true + + '@pnpm/exe.linux-s390x@12.18.0': + optional: true + + '@pnpm/exe.linux-x64-musl@12.18.0': + optional: true + + '@pnpm/exe.linux-x64@12.18.0': + optional: true + + '@pnpm/exe.win32-arm64@12.18.0': + optional: true + + '@pnpm/exe.win32-x64@12.18.0': + optional: true + + pnpm@12.18.0: + optionalDependencies: + '@pnpm/exe.android-arm64': 12.18.0 + '@pnpm/exe.android-x64': 12.18.0 + '@pnpm/exe.darwin-arm64': 12.18.0 + '@pnpm/exe.darwin-x64': 12.18.0 + '@pnpm/exe.freebsd-x64': 12.18.0 + '@pnpm/exe.linux-arm64': 12.18.0 + '@pnpm/exe.linux-arm64-musl': 12.18.0 + '@pnpm/exe.linux-ppc64': 12.18.0 + '@pnpm/exe.linux-riscv64': 12.18.0 + '@pnpm/exe.linux-s390x': 12.18.0 + '@pnpm/exe.linux-x64': 12.18.0 + '@pnpm/exe.linux-x64-musl': 12.18.0 + '@pnpm/exe.win32-arm64': 12.18.0 + '@pnpm/exe.win32-x64': 12.18.0 + +--- +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + ivya: + specifier: 1.8.2 + version: 1.8.2 + devDependencies: + '@playwright/test': + specifier: 1.63.0 + version: 1.63.0 + '@types/node': + specifier: 26.6.6 + version: 26.6.6 + '@types/ws': + specifier: 8.18.1 + version: 8.18.1 + capnweb: + specifier: npm:@iterate-com/capnweb@0.13.0 + version: '@iterate-com/capnweb@0.13.0' + esbuild: + specifier: 0.28.2 + version: 0.28.2 + fflate: + specifier: 0.8.3 + version: 0.8.3 + typescript: + specifier: 7.0.2 + version: 7.0.2 + vitest: + specifier: 4.1.11 + version: 4.1.11(@types/node@26.6.6)(vite@8.4.0(@types/node@26.6.6)(esbuild@0.28.2)) + ws: + specifier: 8.21.3 + version: 8.21.3 + +packages: + + '@esbuild/aix-ppc64@0.28.2': + resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.28.2': + resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.28.2': + resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.28.2': + resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.28.2': + resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.28.2': + resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.28.2': + resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.28.2': + resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.28.2': + resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.28.2': + resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.28.2': + resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.28.2': + resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.28.2': + resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.28.2': + resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.28.2': + resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.28.2': + resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.28.2': + resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.28.2': + resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.28.2': + resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.28.2': + resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.28.2': + resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.28.2': + resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.28.2': + resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.28.2': + resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.28.2': + resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.28.2': + resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@iterate-com/capnweb@0.13.0': + resolution: {integrity: sha512-/4x1zX6nE6K+LTdiYRTBiCXVy5LPfq6fsS49eR0DZbxTpJuScMn0ZlusrmmQ5salwvEDIN3TA7LVvIB00LX3Tw==} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@oxc-project/types@0.160.0': + resolution: {integrity: sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA==} + + '@playwright/test@1.63.0': + resolution: {integrity: sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==} + engines: {node: '>=20'} + hasBin: true + + '@rolldown/binding-android-arm-eabi@1.3.4': + resolution: {integrity: sha512-xCW8CkL/ualx/SbYqeG9iK87lJCZGDQ0soE+kaORJ0Bd+pHALyE4qK7BStmEAyYWLEzZ3/biSIpA6/7GDFvzIg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.3.4': + resolution: {integrity: sha512-5lifIO+b/prcM9sx/bkPN4w6UEToEfQ3gjhx0+0neuL+dkYskI792CfAq03T51jc8JFcaYXs2hi3l8RjiH/VWQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.3.4': + resolution: {integrity: sha512-RCgxTI4AJQxhVF//BI3ImQOsXTHrF4Eg+f99jBy8WoETA2kSEGFxpnrVmW0leQq/2aBR4R5AC6csmy3rc66e3Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.3.4': + resolution: {integrity: sha512-zNPJVVPUaDEj+L0lImoK3rFv2b+Z5gNijI6DWu/fcD3/1TfmRXKb9ZyxbSN+2AhlctqjbNzUvCsMa+EBhnEM4Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.3.4': + resolution: {integrity: sha512-upP6g7ZIRy5by1RDQ/EphHIdJ5xK0eUD7sUgfZFWJ49s4XdbYsIvIlAPtrFpayR70Hhf9J22lb4Pm8/9FhrZmg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.3.4': + resolution: {integrity: sha512-SAX5C5+poMLCxu8dkPF6h5yst40rkzs+9Y3cbPn2OFSydmHjAEprrGi64zGgnYyPIVZfdGUFqJ2fJbfbnHI+mA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.3.4': + resolution: {integrity: sha512-nwHqdlRZS6GWBef3dG5/pMY6RNTBBUjj7s0Da+m6xsFpe7jx6IC46SLZcCu8f46JOfCovZmwnrz51EzGE+7Fyw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.3.4': + resolution: {integrity: sha512-Gr78X2ur/AgLCkmZgHffk/FerIX8S5zb/eII4bCcvJo0ANzeXhTShahdNbpnY6bpiszIAgIfiuKS9ziziWsamw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.3.4': + resolution: {integrity: sha512-o9Wcn8nWrsQasaBRYM4d//FwhlBsTJYWkPVlhlt6FwzpwEoovY4IopRZjk5Fq3+ntRuSDORJjF/nA8sFeF2q6w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.3.4': + resolution: {integrity: sha512-UDWu4jkVcx2kiBKm3Ec//4lVCbeTWj8gmJ9SyLWCdLWtTlyq7fQVeVV/14nXvRtSLErvJ2+yA/Ux5taS31Y17Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.3.4': + resolution: {integrity: sha512-W9mGtTa0w4fWh8RLMNPyaEhhcuqUfO07Q4I1bBc4PDMNg7gQSw0yPQNQ3D0qwbkXwxbyL4YrIzc8n6k1vuFExQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.3.4': + resolution: {integrity: sha512-8B+ofyQZ7/aCmkqnyMonPr5zKLqMVNczhRGFNtdIuItiwNn8iQWJawMq2E58r7bxD1XEbtRRsULY/eCWwZQ01Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.3.4': + resolution: {integrity: sha512-TlD0FSZaC7o2B4NCe9V5N11ugTnhzTM9ksj4sgRLvrKosDzjEkvlsTX3ehkw4ZlPv8AADimZZTvJGEa16pfXug==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-wasm32-wasi@1.3.4': + resolution: {integrity: sha512-jwO8P3o53ygo7b5061B7BeaJ1BGv3BKZ6jroFdw/01qWry7Z+qNBlDvulzbTle5s/A0Fc1FRgsTxrke9DvsSbA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} + cpu: [wasm32] + + '@rolldown/binding-win32-arm64-msvc@1.3.4': + resolution: {integrity: sha512-8adGMrNtrdzi2WD1ozhYapER59gD8Q/DV6SCKJlyG2HqULPdeQUBvMa33lTsiEYwIqTZUaIU2MmvPp5f1wbtXA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.3.4': + resolution: {integrity: sha512-rIMjtESdXJCIoOiUTroQ1Y1rjVDZkuUVRUxs3APX2vNv175D7TDWvzdELiIhzGq9cUNUFat+co+PTmPHPqSREg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.1.1': + resolution: {integrity: sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==} + + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.11': + resolution: {integrity: sha512-YBdNe5JcjYR0sPhJW1QIeRCmI11YhYvaRuGCs9+WCeTTb+Yhb2BE2XMe5/wAqF10FK5g3+q1PDhQABfT7aX0gg==} + + '@types/node@26.6.6': + resolution: {integrity: sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==} + + '@types/ws@8.18.1': + resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==} + + '@typescript/typescript-aix-ppc64@7.0.2': + resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [aix] + + '@typescript/typescript-darwin-arm64@7.0.2': + resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [darwin] + + '@typescript/typescript-darwin-x64@7.0.2': + resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [darwin] + + '@typescript/typescript-freebsd-arm64@7.0.2': + resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [freebsd] + + '@typescript/typescript-freebsd-x64@7.0.2': + resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [freebsd] + + '@typescript/typescript-linux-arm64@7.0.2': + resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [linux] + + '@typescript/typescript-linux-arm@7.0.2': + resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} + engines: {node: '>=16.20.0'} + cpu: [arm] + os: [linux] + + '@typescript/typescript-linux-loong64@7.0.2': + resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} + engines: {node: '>=16.20.0'} + cpu: [loong64] + os: [linux] + + '@typescript/typescript-linux-mips64el@7.0.2': + resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} + engines: {node: '>=16.20.0'} + cpu: [mips64el] + os: [linux] + + '@typescript/typescript-linux-ppc64@7.0.2': + resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [linux] + + '@typescript/typescript-linux-riscv64@7.0.2': + resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} + engines: {node: '>=16.20.0'} + cpu: [riscv64] + os: [linux] + + '@typescript/typescript-linux-s390x@7.0.2': + resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} + engines: {node: '>=16.20.0'} + cpu: [s390x] + os: [linux] + + '@typescript/typescript-linux-x64@7.0.2': + resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [linux] + + '@typescript/typescript-netbsd-arm64@7.0.2': + resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [netbsd] + + '@typescript/typescript-netbsd-x64@7.0.2': + resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [netbsd] + + '@typescript/typescript-openbsd-arm64@7.0.2': + resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [openbsd] + + '@typescript/typescript-openbsd-x64@7.0.2': + resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [openbsd] + + '@typescript/typescript-sunos-x64@7.0.2': + resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [sunos] + + '@typescript/typescript-win32-arm64@7.0.2': + resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [win32] + + '@typescript/typescript-win32-x64@7.0.2': + resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] + + '@vitest/expect@4.1.11': + resolution: {integrity: sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==} + + '@vitest/mocker@4.1.11': + resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==} + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@4.1.11': + resolution: {integrity: sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==} + + '@vitest/runner@4.1.11': + resolution: {integrity: sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==} + + '@vitest/snapshot@4.1.11': + resolution: {integrity: sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==} + + '@vitest/spy@4.1.11': + resolution: {integrity: sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==} + + '@vitest/utils@4.1.11': + resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + chai@6.3.0: + resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} + engines: {node: '>=18'} + + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + + esbuild@0.28.2: + resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} + engines: {node: '>=18'} + hasBin: true + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fflate@0.8.3: + resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + ivya@1.8.2: + resolution: {integrity: sha512-9pGI1dtJbK2U+fpUoV95SL9slfrF2EM4p0Sf6EddYJwmMttBKijGOxCXibSCg8UKhmVwMx5CaDZ2PXinrcGfbA==} + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + napi-windows-process-start-time@0.1.0: + resolution: {integrity: sha512-zHxhzKsIFu3elch3eFw69WEUGc79DFhbc3nD/WEOzWL/pFFLZRW13EHnuO0c+0YjncE5uCaS9ICHxOBXkb6vPw==} + engines: {node: '>=20'} + cpu: [x64, arm64] + os: [win32] + + obug@2.2.1: + resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} + engines: {node: '>=12.20.0'} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + playwright-core@1.63.0: + resolution: {integrity: sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.63.0: + resolution: {integrity: sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==} + engines: {node: '>=20'} + hasBin: true + + postcss@8.5.33: + resolution: {integrity: sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==} + engines: {node: ^10 || ^12 || >=14} + + rolldown@1.3.4: + resolution: {integrity: sha512-p2rq4bfBmF0M6yaR8+A89fbkBQynZI2fxUW4G07eq9kpctAkpo7q5BZ4X4Mo4XZ7HHROu33cX9PeopUFN6u+2Q==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + source-map-js@1.2.4: + resolution: {integrity: sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==} + engines: {node: '>=6.0.0'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@4.3.0: + resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@1.4.0: + resolution: {integrity: sha512-PV6lIcJQh57aFeJDwx16JNHmgFRh5xguzallrDW1qe8nAghYgr5MKz2K5k7wEyV/ygZhdnIAP8+HZSarHPBCsg==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tinyrainbow@3.2.0: + resolution: {integrity: sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==} + engines: {node: '>=14.0.0'} + + typescript@7.0.2: + resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} + engines: {node: '>=16.20.0'} + hasBin: true + + undici-types@8.9.0: + resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} + + vite@8.4.0: + resolution: {integrity: sha512-X2nUJg+9cutlz3hzqyO6p+WTwk9H257DjwAEf9EQYUFrQbDItmetadi9gYmb+l7VDy4r3VXLUnmLTwuPmzejDw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@4.1.11: + resolution: {integrity: sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==} + engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 4.1.11 + '@vitest/browser-preview': 4.1.11 + '@vitest/browser-webdriverio': 4.1.11 + '@vitest/coverage-istanbul': 4.1.11 + '@vitest/coverage-v8': 4.1.11 + '@vitest/ui': 4.1.11 + happy-dom: '*' + jsdom: '*' + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + ws@8.21.3: + resolution: {integrity: sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + +snapshots: + + '@esbuild/aix-ppc64@0.28.2': + optional: true + + '@esbuild/android-arm64@0.28.2': + optional: true + + '@esbuild/android-arm@0.28.2': + optional: true + + '@esbuild/android-x64@0.28.2': + optional: true + + '@esbuild/darwin-arm64@0.28.2': + optional: true + + '@esbuild/darwin-x64@0.28.2': + optional: true + + '@esbuild/freebsd-arm64@0.28.2': + optional: true + + '@esbuild/freebsd-x64@0.28.2': + optional: true + + '@esbuild/linux-arm64@0.28.2': + optional: true + + '@esbuild/linux-arm@0.28.2': + optional: true + + '@esbuild/linux-ia32@0.28.2': + optional: true + + '@esbuild/linux-loong64@0.28.2': + optional: true + + '@esbuild/linux-mips64el@0.28.2': + optional: true + + '@esbuild/linux-ppc64@0.28.2': + optional: true + + '@esbuild/linux-riscv64@0.28.2': + optional: true + + '@esbuild/linux-s390x@0.28.2': + optional: true + + '@esbuild/linux-x64@0.28.2': + optional: true + + '@esbuild/netbsd-arm64@0.28.2': + optional: true + + '@esbuild/netbsd-x64@0.28.2': + optional: true + + '@esbuild/openbsd-arm64@0.28.2': + optional: true + + '@esbuild/openbsd-x64@0.28.2': + optional: true + + '@esbuild/openharmony-arm64@0.28.2': + optional: true + + '@esbuild/sunos-x64@0.28.2': + optional: true + + '@esbuild/win32-arm64@0.28.2': + optional: true + + '@esbuild/win32-ia32@0.28.2': + optional: true + + '@esbuild/win32-x64@0.28.2': + optional: true + + '@iterate-com/capnweb@0.13.0': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@oxc-project/types@0.160.0': {} + + '@playwright/test@1.63.0': + dependencies: + playwright: 1.63.0 + + '@rolldown/binding-android-arm-eabi@1.3.4': + optional: true + + '@rolldown/binding-android-arm64@1.3.4': + optional: true + + '@rolldown/binding-darwin-arm64@1.3.4': + optional: true + + '@rolldown/binding-darwin-x64@1.3.4': + optional: true + + '@rolldown/binding-freebsd-x64@1.3.4': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.3.4': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.3.4': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.3.4': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.3.4': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.3.4': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.3.4': + optional: true + + '@rolldown/binding-linux-x64-musl@1.3.4': + optional: true + + '@rolldown/binding-openharmony-arm64@1.3.4': + optional: true + + '@rolldown/binding-wasm32-wasi@1.3.4': + dependencies: + '@oxc-project/types': 0.160.0 + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.3.4': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.3.4': + optional: true + + '@rolldown/pluginutils@1.1.1': {} + + '@standard-schema/spec@1.1.0': {} + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.11': {} + + '@types/node@26.6.6': + dependencies: + undici-types: 8.9.0 + + '@types/ws@8.18.1': + dependencies: + '@types/node': 26.6.6 + + '@typescript/typescript-aix-ppc64@7.0.2': + optional: true + + '@typescript/typescript-darwin-arm64@7.0.2': + optional: true + + '@typescript/typescript-darwin-x64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-x64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm@7.0.2': + optional: true + + '@typescript/typescript-linux-loong64@7.0.2': + optional: true + + '@typescript/typescript-linux-mips64el@7.0.2': + optional: true + + '@typescript/typescript-linux-ppc64@7.0.2': + optional: true + + '@typescript/typescript-linux-riscv64@7.0.2': + optional: true + + '@typescript/typescript-linux-s390x@7.0.2': + optional: true + + '@typescript/typescript-linux-x64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-sunos-x64@7.0.2': + optional: true + + '@typescript/typescript-win32-arm64@7.0.2': + optional: true + + '@typescript/typescript-win32-x64@7.0.2': + optional: true + + '@vitest/expect@4.1.11': + dependencies: + '@standard-schema/spec': 1.1.0 + '@types/chai': 5.2.3 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 + chai: 6.3.0 + tinyrainbow: 3.2.0 + + '@vitest/mocker@4.1.11(vite@8.4.0(@types/node@26.6.6)(esbuild@0.28.2))': + dependencies: + '@vitest/spy': 4.1.11 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 8.4.0(@types/node@26.6.6)(esbuild@0.28.2) + + '@vitest/pretty-format@4.1.11': + dependencies: + tinyrainbow: 3.2.0 + + '@vitest/runner@4.1.11': + dependencies: + '@vitest/utils': 4.1.11 + pathe: 2.0.3 + + '@vitest/snapshot@4.1.11': + dependencies: + '@vitest/pretty-format': 4.1.11 + '@vitest/utils': 4.1.11 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@4.1.11': {} + + '@vitest/utils@4.1.11': + dependencies: + '@vitest/pretty-format': 4.1.11 + convert-source-map: 2.0.0 + tinyrainbow: 3.2.0 + + assertion-error@2.0.1: {} + + chai@6.3.0: {} + + convert-source-map@2.0.0: {} + + detect-libc@2.1.2: {} + + es-module-lexer@2.3.2: {} + + esbuild@0.28.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.2 + '@esbuild/android-arm': 0.28.2 + '@esbuild/android-arm64': 0.28.2 + '@esbuild/android-x64': 0.28.2 + '@esbuild/darwin-arm64': 0.28.2 + '@esbuild/darwin-x64': 0.28.2 + '@esbuild/freebsd-arm64': 0.28.2 + '@esbuild/freebsd-x64': 0.28.2 + '@esbuild/linux-arm': 0.28.2 + '@esbuild/linux-arm64': 0.28.2 + '@esbuild/linux-ia32': 0.28.2 + '@esbuild/linux-loong64': 0.28.2 + '@esbuild/linux-mips64el': 0.28.2 + '@esbuild/linux-ppc64': 0.28.2 + '@esbuild/linux-riscv64': 0.28.2 + '@esbuild/linux-s390x': 0.28.2 + '@esbuild/linux-x64': 0.28.2 + '@esbuild/netbsd-arm64': 0.28.2 + '@esbuild/netbsd-x64': 0.28.2 + '@esbuild/openbsd-arm64': 0.28.2 + '@esbuild/openbsd-x64': 0.28.2 + '@esbuild/openharmony-arm64': 0.28.2 + '@esbuild/sunos-x64': 0.28.2 + '@esbuild/win32-arm64': 0.28.2 + '@esbuild/win32-ia32': 0.28.2 + '@esbuild/win32-x64': 0.28.2 + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.11 + + expect-type@1.4.0: {} + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fflate@0.8.3: {} + + fsevents@2.3.3: + optional: true + + ivya@1.8.2: {} + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + nanoid@3.3.20: {} + + napi-windows-process-start-time@0.1.0: + optional: true + + obug@2.2.1: {} + + pathe@2.0.3: {} + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + playwright-core@1.63.0: {} + + playwright@1.63.0: + dependencies: + playwright-core: 1.63.0 + + postcss@8.5.33: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.4 + + rolldown@1.3.4: + dependencies: + '@oxc-project/types': 0.160.0 + '@rolldown/pluginutils': 1.1.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.3.4 + '@rolldown/binding-android-arm64': 1.3.4 + '@rolldown/binding-darwin-arm64': 1.3.4 + '@rolldown/binding-darwin-x64': 1.3.4 + '@rolldown/binding-freebsd-x64': 1.3.4 + '@rolldown/binding-linux-arm-gnueabihf': 1.3.4 + '@rolldown/binding-linux-arm64-gnu': 1.3.4 + '@rolldown/binding-linux-arm64-musl': 1.3.4 + '@rolldown/binding-linux-ppc64-gnu': 1.3.4 + '@rolldown/binding-linux-s390x-gnu': 1.3.4 + '@rolldown/binding-linux-x64-gnu': 1.3.4 + '@rolldown/binding-linux-x64-musl': 1.3.4 + '@rolldown/binding-openharmony-arm64': 1.3.4 + '@rolldown/binding-wasm32-wasi': 1.3.4 + '@rolldown/binding-win32-arm64-msvc': 1.3.4 + '@rolldown/binding-win32-x64-msvc': 1.3.4 + + siginfo@2.0.0: {} + + source-map-js@1.2.4: {} + + stackback@0.0.2: {} + + std-env@4.3.0: {} + + tinybench@2.9.0: {} + + tinyexec@1.4.0: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + tinyrainbow@3.2.0: {} + + typescript@7.0.2: + optionalDependencies: + '@typescript/typescript-aix-ppc64': 7.0.2 + '@typescript/typescript-darwin-arm64': 7.0.2 + '@typescript/typescript-darwin-x64': 7.0.2 + '@typescript/typescript-freebsd-arm64': 7.0.2 + '@typescript/typescript-freebsd-x64': 7.0.2 + '@typescript/typescript-linux-arm': 7.0.2 + '@typescript/typescript-linux-arm64': 7.0.2 + '@typescript/typescript-linux-loong64': 7.0.2 + '@typescript/typescript-linux-mips64el': 7.0.2 + '@typescript/typescript-linux-ppc64': 7.0.2 + '@typescript/typescript-linux-riscv64': 7.0.2 + '@typescript/typescript-linux-s390x': 7.0.2 + '@typescript/typescript-linux-x64': 7.0.2 + '@typescript/typescript-netbsd-arm64': 7.0.2 + '@typescript/typescript-netbsd-x64': 7.0.2 + '@typescript/typescript-openbsd-arm64': 7.0.2 + '@typescript/typescript-openbsd-x64': 7.0.2 + '@typescript/typescript-sunos-x64': 7.0.2 + '@typescript/typescript-win32-arm64': 7.0.2 + '@typescript/typescript-win32-x64': 7.0.2 + + undici-types@8.9.0: {} + + vite@8.4.0(@types/node@26.6.6)(esbuild@0.28.2): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.33 + rolldown: 1.3.4 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 26.6.6 + esbuild: 0.28.2 + fsevents: 2.3.3 + napi-windows-process-start-time: 0.1.0 + + vitest@4.1.11(@types/node@26.6.6)(vite@8.4.0(@types/node@26.6.6)(esbuild@0.28.2)): + dependencies: + '@vitest/expect': 4.1.11 + '@vitest/mocker': 4.1.11(vite@8.4.0(@types/node@26.6.6)(esbuild@0.28.2)) + '@vitest/pretty-format': 4.1.11 + '@vitest/runner': 4.1.11 + '@vitest/snapshot': 4.1.11 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 0.30.21 + obug: 2.2.1 + pathe: 2.0.3 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 2.9.0 + tinyexec: 1.4.0 + tinyglobby: 0.2.17 + tinyrainbow: 3.2.0 + vite: 8.4.0(@types/node@26.6.6)(esbuild@0.28.2) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 26.6.6 + transitivePeerDependencies: + - msw + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + ws@8.21.3: {}
A pnpm-workspace.yaml
@@ -0,0 +1,5 @@ +# One package. The versions are exact: a release's files are the same for the same commit. +packages: + - . +allowBuilds: + esbuild: true
A public/address.js
@@ -0,0 +1,38 @@ +// address.js — THE MIND'S ADDRESS, from what a person typed in the panel's field, and the mind's +// issuer, which is the origin at that address. The rule is iterate/mind-api's `mindAddressOf`, +// written again here because the extension carries its own code (README.md); +// test/address.test.ts holds the two to the same answers. +// +// The rule is applied ONCE, to what was typed. The issuer it answers is kept in the session and +// used as it is from then on: the bearer goes to that origin and to no other. + +/** A hostname is taken as typed, lowercased, with a scheme, a path and a trailing dot dropped. + * The one shorthand is for a bare `something.tld` with nothing else typed, which means + * `iterate.something.tld`. A URL keeps its hostname: `https://example.com/` is the mind whose + * control plane is `example.com`. */ +export function mindIssuerOf(typed) { + const text = typed.trim().toLowerCase(); + if (!text) throw new Error("Enter the mind's address, like iterate.example.com."); + let hostname; + try { + ({ hostname } = new URL(/^[a-z][a-z0-9+.-]*:\/\//.test(text) ? text : `https://${text}`)); + } catch { + throw new Error("Enter the mind's address, like iterate.example.com."); + } + hostname = hostname.replace(/\.$/, ""); + if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(hostname) || hostname.startsWith("[")) + throw new Error("A mind's address is a hostname, not an IP address."); + if (!hostname.includes(".")) + throw new Error("Enter the mind's whole address, like iterate.example.com."); + const address = /^[a-z0-9-]+\.[a-z0-9-]+\.?$/.test(text) ? `iterate.${hostname}` : hostname; + if (!/^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(address)) + throw new Error("That is no hostname. Enter the mind's address, like iterate.example.com."); + return `https://${address}`; +} + +/** `issuer`, once it answers as an OAuth issuer. */ +export async function answeringIssuer(issuer) { + const answer = await fetch(`${issuer}/.well-known/oauth-authorization-server`).catch(() => null); + if (!answer?.ok) throw new Error(`No mind signs in at ${issuer}.`); + return issuer; +}
A public/background.js
@@ -0,0 +1,50 @@ +import { createLending } from "./lend.js"; +import { acceptOffscreenPort } from "./offscreen-client.js"; + +// Startup sharing needs a separate user decision. Session storage survives worker suspension, +// but Chrome clears it on a browser restart or extension reload. +const SHARE_ON_BROWSER_START = false; +const lending = createLending(SHARE_ON_BROWSER_START); + +chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }).catch(console.error); +chrome.alarms.onAlarm.addListener((alarm) => { + if (alarm.name === "iterate-lending") void lending.wake().catch(console.error); +}); +chrome.runtime.onStartup.addListener(() => void lending.ready.catch(console.error)); +chrome.runtime.onInstalled.addListener(() => void lending.ready.catch(console.error)); +chrome.runtime.onConnect.addListener((port) => { + if (port.name === "offscreen-transport") { + acceptOffscreenPort(port); + return; + } + // No web page or other extension can use the panel's control channel. + if ( + port.name !== "panel" || + port.sender?.id !== chrome.runtime.id || + port.sender?.url !== chrome.runtime.getURL("index.html") + ) { + port.disconnect(); + return; + } + const send = (message) => { + try { + port.postMessage(message); + } catch { + /* The panel closed. */ + } + }; + const unsubscribe = lending.subscribe((state) => send({ state })); + port.onDisconnect.addListener(unsubscribe); + void lending.ready.then( + () => send({ state: lending.snapshot() }), + (error) => send({ error: error.message }), + ); + port.onMessage.addListener((message) => { + if (!Number.isSafeInteger(message?.id) || message.id < 1) return; + void lending.command(message).then( + (state) => send({ id: message.id, state }), + (error) => send({ id: message.id, error: error.message }), + ); + }); +}); +void lending.ready.catch(console.error);
A public/icon-128.png
Not text, so no diff is shown.
A public/icon-16.png
Not text, so no diff is shown.
A public/icon-32.png
Not text, so no diff is shown.
A public/icon-48.png
Not text, so no diff is shown.
A public/index.html
@@ -0,0 +1,339 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1.0" /> + <title>Iterate</title> + <style> + /* shadcn's neutral theme, the values of the mind apps' theme.css + (core/configs/default/apps/theme.css), following the system's light or dark mode. */ + :root { + color-scheme: light dark; + --radius: 0.625rem; + --background: light-dark(oklch(1 0 0), oklch(0.145 0 0)); + --foreground: light-dark(oklch(0.145 0 0), oklch(0.985 0 0)); + --card: light-dark(oklch(1 0 0), oklch(0.205 0 0)); + --primary: light-dark(oklch(0.205 0 0), oklch(0.922 0 0)); + --primary-foreground: light-dark(oklch(0.985 0 0), oklch(0.205 0 0)); + --muted: light-dark(oklch(0.97 0 0), oklch(0.269 0 0)); + --muted-foreground: light-dark(oklch(0.556 0 0), oklch(0.708 0 0)); + --accent: light-dark(oklch(0.97 0 0), oklch(0.269 0 0)); + --destructive: light-dark(oklch(0.577 0.245 27.325), oklch(0.704 0.191 22.216)); + --success: light-dark(oklch(0.627 0.194 149.214), oklch(0.723 0.219 149.579)); + --warning: light-dark(oklch(0.666 0.179 58.318), oklch(0.769 0.188 70.08)); + --border: light-dark(oklch(0.922 0 0), oklch(1 0 0 / 10%)); + --input: light-dark(oklch(0.922 0 0), oklch(1 0 0 / 15%)); + --ring: light-dark(oklch(0.708 0 0), oklch(0.556 0 0)); + --mono: ui-monospace, SFMono-Regular, Menlo, monospace; + font: + 14px/1.5 Inter, + ui-sans-serif, + system-ui, + sans-serif; + color: var(--foreground); + background: var(--background); + } + * { + box-sizing: border-box; + } + body { + margin: 0; + min-width: 280px; + /* Chrome's own style sheet for extension pages sets body to 75% */ + font: inherit; + } + /* minmax(0, 1fr): a long URL truncates instead of widening the panel */ + main, + .stack, + .card, + .tabs { + grid-template-columns: minmax(0, 1fr); + } + main { + display: grid; + gap: 12px; + padding: 16px; + align-content: start; + } + h1, + h2, + p, + ul, + dl, + dd { + margin: 0; + } + .header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + } + .brand { + display: flex; + align-items: center; + gap: 8px; + font-size: 16px; + font-weight: 600; + } + .brand img { + width: 20px; + height: 20px; + border-radius: 4px; + } + /* the mind: its logo, then its name over its address, or the address alone */ + .mind { + display: flex; + align-items: center; + gap: 10px; + flex: 1; + min-width: 0; + } + .mind-logo { + width: 32px; + height: 32px; + flex: none; + border-radius: 8px; + object-fit: cover; + } + .mind-name, + .mind-address:only-child { + font-size: 14px; + font-weight: 600; + line-height: 1.3; + } + .mind-name { + unicode-bidi: isolate; + } + .mind-name + .mind-address { + color: var(--muted-foreground); + font-size: 12px; + line-height: 1.3; + } + .stack { + display: grid; + gap: 12px; + } + .card { + display: grid; + gap: 12px; + padding: 16px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--card); + box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); + } + .card-head { + display: grid; + gap: 2px; + } + h2 { + font-size: 14px; + font-weight: 600; + } + .muted { + color: var(--muted-foreground); + font-size: 13px; + } + .row { + display: flex; + align-items: center; + gap: 8px; + } + .grow { + flex: 1; + min-width: 0; + } + .actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + } + .btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + height: 36px; + padding: 0 14px; + border: 1px solid transparent; + border-radius: calc(var(--radius) - 2px); + font: inherit; + font-weight: 500; + white-space: nowrap; + cursor: pointer; + transition: + background-color 0.15s, + opacity 0.15s; + } + .btn:focus-visible, + .input:focus-visible { + outline: none; + box-shadow: 0 0 0 3px color-mix(in oklch, var(--ring) 50%, transparent); + border-color: var(--ring); + } + .btn:disabled { + opacity: 0.5; + pointer-events: none; + } + .btn-primary { + color: var(--primary-foreground); + background: var(--primary); + } + .btn-primary:hover { + background: color-mix(in oklch, var(--primary) 90%, transparent); + } + .btn-outline { + color: var(--foreground); + background: var(--background); + border-color: var(--border); + box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); + } + .btn-outline:hover, + .btn-ghost:hover { + background: var(--accent); + } + .btn-ghost { + color: var(--foreground); + background: transparent; + } + .btn-sm { + height: 32px; + padding: 0 10px; + font-size: 13px; + } + .btn-block { + width: 100%; + } + .field { + display: grid; + gap: 6px; + font-size: 13px; + font-weight: 500; + } + .input { + height: 36px; + width: 100%; + padding: 0 12px; + border: 1px solid var(--input); + border-radius: calc(var(--radius) - 2px); + font: inherit; + color: var(--foreground); + background: transparent; + box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05); + } + .badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 2px 8px; + border: 1px solid var(--border); + border-radius: calc(var(--radius) - 4px); + font-size: 12px; + font-weight: 500; + color: var(--muted-foreground); + } + code, + .mono { + font-family: var(--mono); + font-size: 12px; + } + code { + padding: 1px 4px; + border-radius: 4px; + background: var(--muted); + overflow-wrap: anywhere; + } + .dot { + width: 8px; + height: 8px; + flex: none; + border-radius: 50%; + background: var(--muted-foreground); + } + .dot.ok { + background: var(--success); + box-shadow: 0 0 0 3px color-mix(in oklch, var(--success) 20%, transparent); + } + .dot.wait { + background: var(--warning); + } + .dot.bad { + background: var(--destructive); + } + .facts { + display: grid; + grid-template-columns: auto 1fr; + gap: 4px 12px; + font-size: 13px; + } + .facts dt { + color: var(--muted-foreground); + } + .facts dd { + min-width: 0; + overflow-wrap: anywhere; + } + .tabs { + display: grid; + padding: 0; + list-style: none; + border: 1px solid var(--border); + border-radius: calc(var(--radius) - 2px); + } + .tabs li { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 8px 8px 12px; + } + .tabs li + li { + border-top: 1px solid var(--border); + } + .tabs .empty { + color: var(--muted-foreground); + font-size: 13px; + padding: 12px; + } + .truncate { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .title { + font-size: 13px; + font-weight: 500; + } + .rename { + margin-top: 8px; + } + details summary { + cursor: pointer; + font-size: 13px; + color: var(--muted-foreground); + } + pre { + margin: 8px 0 0; + padding: 10px 12px; + max-height: 260px; + overflow: auto; + border-radius: calc(var(--radius) - 2px); + background: var(--muted); + font-family: var(--mono); + font-size: 11.5px; + line-height: 1.5; + white-space: pre-wrap; + user-select: text; + } + .error { + color: var(--destructive); + font-size: 13px; + overflow-wrap: anywhere; + } + </style> + </head> + <body> + <main id="app"></main> + <script type="module" src="panel.js"></script> + </body> +</html>
A public/indicator.js
@@ -0,0 +1,262 @@ +// indicator.js — what the person sees on a tab while the mind's debugger is attached to it: a frame +// on the viewport's edge and a label, top center, with the mind, what it does and a Stop button. +// lend.js runs this function as `(<this file>)({ address, name, icon })` in the isolated world +// "iterate-indicator" of the top frame: on each page the tab loads while the debugger is attached, +// and on the page that shows when it attaches. The page's own scripts do not see that world, and the +// shadow root is closed, so the page's CSS cannot reach inside it. +// +// THE MIND IS SHOWN AS THE PANEL SHOWS IT: its logo on the left, then its name over its address, or +// the address alone for a mind with no name. The name and the logo are the owner's own words +// (profile.js) and prove nothing, so the address is always there. The logo is an image and no +// more: a mind with none, a logo that does not load and a page whose policy refuses the image all +// show the plain dot. The image is asked for with no referrer, so the logo's host does not learn +// which page the tab shows. +// +// The host element is the only thing the panel and this script share: the panel writes its +// attributes from a world of its own. `data-activity="<word> <time>"` means the mind acts now (the +// time makes a repeat of the same word a change); `data-hidden` hides everything while the mind +// takes a screenshot. Stop calls `iterateIndicatorStop`, a CDP binding only this world has. +// `data-alive="<time>"` is the panel's heartbeat, every 4 s: a binding outlives its debugger +// session, so the page cannot tell that the debugger went, and without a heartbeat for 12 s the +// indicator removes itself. +// oxlint-disable-next-line no-unused-vars -- panel.js calls it, by its source text +function iterateIndicator({ address, name, icon }) { + if (window !== window.top) return; + /** How long the label says what the mind does, after its last command. */ + const ACTING_MS = 3_000; + /** The highest z-index: above everything the page draws. */ + const TOP = 2 ** 31 - 1; + /** How long the indicator stays without a heartbeat (`data-alive` or `data-activity`). */ + const ALIVE_MS = 12_000; + + const css = ` + .root { + all: initial; + --iterate: 99 102 241; + } + .frame { + position: fixed; + inset: 0; + pointer-events: none; + z-index: ${TOP}; + box-shadow: + inset 0 0 0 3px rgb(var(--iterate) / 0.5), + inset 0 0 10px rgb(var(--iterate) / 0.25); + transition: box-shadow 0.4s; + } + .acting .frame { + box-shadow: + inset 0 0 0 5px rgb(var(--iterate)), + inset 0 0 36px rgb(var(--iterate) / 0.7); + animation: pulse 1.2s ease-in-out infinite; + } + @keyframes pulse { + 50% { + box-shadow: + inset 0 0 0 4px rgb(var(--iterate) / 0.9), + inset 0 0 20px rgb(var(--iterate) / 0.5); + } + } + .label { + position: fixed; + top: 8px; + left: 50%; + transform: translateX(-50%); + z-index: ${TOP}; + pointer-events: none; + box-sizing: border-box; + min-height: 28px; + max-width: calc(100vw - 16px); + display: flex; + align-items: center; + gap: 8px; + padding: 4px 4px 4px 10px; + border-radius: 18px; + background: #18181b; + color: #fafafa; + font: 500 12px/1 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + white-space: nowrap; + box-shadow: + 0 2px 10px rgb(0 0 0 / 0.35), + 0 0 0 1px rgb(255 255 255 / 0.14); + } + .acting .label { + box-shadow: + 0 2px 10px rgb(0 0 0 / 0.35), + 0 0 0 2px rgb(var(--iterate)); + } + .dot { + flex: none; + width: 8px; + height: 8px; + border-radius: 50%; + background: rgb(var(--iterate)); + } + .acting .dot { + animation: blink 1s ease-in-out infinite; + } + @keyframes blink { + 50% { + opacity: 0.35; + } + } + .logo { + flex: none; + width: 20px; + height: 20px; + margin-left: -4px; + border-radius: 5px; + object-fit: cover; + } + .who { + flex: 0 1 auto; + min-width: 0; + display: flex; + flex-direction: column; + gap: 3px; + } + .name, + .address, + .text { + overflow: hidden; + text-overflow: ellipsis; + } + .name { + font-weight: 600; + unicode-bidi: isolate; + } + /* under a name the address is the smaller line; alone it is the label's first words */ + .name + .address { + font-size: 10px; + opacity: 0.7; + } + .text { + flex: 0 4 auto; + min-width: 0; + } + button { + all: unset; + pointer-events: auto; + flex: none; + height: 20px; + padding: 0 9px; + border-radius: 10px; + background: rgb(255 255 255 / 0.15); + color: inherit; + font: inherit; + cursor: pointer; + } + button:hover { + background: rgb(255 255 255 / 0.25); + } + button:focus-visible { + outline: 2px solid rgb(var(--iterate)); + } + button:disabled { + cursor: default; + opacity: 0.6; + } + .hidden .frame, + .hidden .label { + display: none; + } + @media (prefers-reduced-motion: reduce) { + .frame { + transition: none; + } + .acting .frame, + .acting .dot { + animation: none; + } + }`; + + const install = () => { + const page = document.documentElement; + if (!page || page.querySelector(":scope > iterate-indicator")) return; + const host = document.createElement("iterate-indicator"); + const shadow = host.attachShadow({ mode: "closed" }); + // A constructed sheet, not a <style> element: a page's CSP does not apply to it. + const sheet = new CSSStyleSheet(); + sheet.replaceSync(css); + shadow.adoptedStyleSheets = [sheet]; + // Elements, not innerHTML: a page that enforces Trusted Types refuses an HTML string. + const make = (tag, className) => { + const made = document.createElement(tag); + if (className) made.className = className; + return made; + }; + const root = make("div", "root"); + const label = make("div", "label"); + label.setAttribute("role", "status"); + const who = make("span", "who"); + if (name) who.append(Object.assign(make("span", "name"), { textContent: name })); + who.append(Object.assign(make("span", "address"), { textContent: address })); + let mark = make("span", "dot"); + if (icon) { + const dot = mark; + mark = make("img", "logo"); + mark.alt = ""; + mark.referrerPolicy = "no-referrer"; + mark.addEventListener("error", () => mark.replaceWith(dot), { once: true }); + mark.src = icon; + } + const text = make("span", "text"); + const stop = make("button"); + stop.type = "button"; + stop.textContent = "Stop"; + stop.title = `${address} lets go of this tab, and the tab leaves its group`; + label.append(mark, who, text, stop); + root.append(make("div", "frame"), label); + shadow.append(root); + + const idle = "is using this tab"; + text.textContent = idle; + let settle; + const update = () => { + root.classList.toggle("hidden", host.hasAttribute("data-hidden")); + const word = (host.getAttribute("data-activity") || "").replace(/ \d+$/, ""); + clearTimeout(settle); + if (!word) return; + root.classList.add("acting"); + text.textContent = `is ${word}`; + settle = setTimeout(() => { + root.classList.remove("acting"); + text.textContent = idle; + }, ACTING_MS); + }; + // A new page gets its indicator before any heartbeat: the 12 s start at install. + let alive; + const live = () => { + clearTimeout(alive); + alive = setTimeout(() => { + watcher.disconnect(); + clearTimeout(settle); + host.remove(); + }, ALIVE_MS); + }; + const watcher = new MutationObserver((changes) => { + const changed = new Set(changes.map((change) => change.attributeName)); + if (changed.has("data-alive") || changed.has("data-activity")) live(); + // `data-hidden` alone must not restart the 3 s of the last action. + if (changed.has("data-activity")) update(); + else root.classList.toggle("hidden", host.hasAttribute("data-hidden")); + }); + watcher.observe(host, { + attributes: true, + attributeFilter: ["data-activity", "data-alive", "data-hidden"], + }); + live(); + + stop.addEventListener("click", () => { + stop.disabled = true; + text.textContent = "is letting go…"; + globalThis.iterateIndicatorStop?.("stop"); + }); + page.append(host); + }; + + // A script for a new page runs before the page has elements. + if (document.readyState === "loading" || !document.documentElement) + document.addEventListener("DOMContentLoaded", install, { once: true }); + else install(); +}
A public/instructions.js
@@ -0,0 +1,21 @@ +export function agentInstructions(address, name, members) { + const spelled = `itx.cd("/").${name.replace(/^itx\./, "")}`; + const call = `\`await ${spelled}`; + return [ + `My Chrome is lent to the mind ${address} as \`${name}\` on its root context, while sharing is on; closing my Iterate side panel does not end the lend. You drive the tabs in the "${address}" tab group of this Chrome. From an agent's script, spell it \`${spelled}\`:`, + "", + `- ${call}.tabs()\`: the tabs in the group, as [{ tabId, url, title, attached }]. If this call fails, sharing or the connection may have ended: tell me.`, + `- ${call}.openPage({ url })\`: opens an http(s) page in a new tab in the group and answers { tabId, url } once it has loaded.`, + `- ${call}.cdp(tabId, method, params)\`: one Chrome DevTools Protocol command on a tab in the group, for example \`"Runtime.evaluate", { expression: "document.title", returnByValue: true }\`, \`"Page.navigate", { url }\`, \`"Page.captureScreenshot", {}\` or \`"Accessibility.getFullAXTree", {}\`.`, + `- ${call}.detach(tabId)\`: removes Chrome's debugging bar; the tab stays drivable.`, + `- ${call}.page(tabId)\`: prototype Playwright-shaped handle. ${call}.page(tabId).getByRole("button", { name: "Save", exact: true }).click()\`. Locators also support getByText/getByLabel/locator, nth/first, count/textContent, fill(text), press("Enter" | "Tab" | "Backspace" | "Escape" | "ArrowLeft" | "ArrowRight"). Actions take { timeout: 5000 } (1–30000 ms). Main frame only; string matchers only. No navigation wait or automatic action replay.`, + `- While you are attached to a tab, I see a frame around it and a label on top with what you do and a Stop button (Stop takes the tab out of the group). Screenshots leave them out. \`detach(tabId)\` when you are done removes them. \`Page.disable\` and \`Runtime.disable\` do nothing: the extension keeps both domains on.`, + `- A page can report to the mind: \`cdp(tabId, "Runtime.enable", {})\` and \`cdp(tabId, "Runtime.addBinding", { name, executionContextName: "iterate" })\`; then \`cdp(tabId, "Page.getFrameTree", {})\` for the main frame's id, \`cdp(tabId, "Page.createIsolatedWorld", { frameId, worldName: "iterate" })\` for its \`executionContextId\`, and \`cdp(tabId, "Runtime.evaluate", { expression, contextId: executionContextId })\` with a script that calls \`window[name](string)\`. The page's own scripts cannot see that world. Each call appends \`events.iterate.com/chrome/binding-called { lendName, tabId, name, payload }\` to the mind's root stream. To keep the script on every page the tab loads, also send \`cdp(tabId, "Page.addScriptToEvaluateOnNewDocument", { source: expression, worldName: "iterate" })\` (a mind whose stack is older than this refuses the \`source\` argument: then the script lives in the current page only).`, + + "", + "Run openPage and cdp in separate scripts, so a failed cdp does not lose the tabId. You can drive only the tabs in the group: I add a tab by dragging it into the group, and take it back by dragging it out.", + "", + members.length ? "Tabs in the group right now:" : "No tabs are in the group right now.", + ...members.map((tab) => `- ${tab.tabId}: ${tab.title || "(no title)"} (${tab.url})`), + ].join("\n"); +}
A public/lend.js
@@ -0,0 +1,1584 @@ +// One controller per service worker. UI ports never own the socket or a browser grant. +import { RpcTarget } from "./capnweb.js"; +import { ChromePage } from "./page.js"; +import { locatorSource } from "./locator-source.js"; +import { oauthClient } from "./oauth.js"; +import { agentInstructions } from "./instructions.js"; +import { answeringIssuer, mindIssuerOf } from "./address.js"; +import { mindAddressOf, readMindProfile } from "./profile.js"; +import { openOffscreenApi, disconnectOffscreen } from "./offscreen-client.js"; + +// Root overload lasted about 12 minutes (measured 2026-11-16), so five retries are too short. +// Keep a 30-minute window; capped jitter stays near one attempt/minute, below healthy heartbeats. +const LENDING_TIMING = Object.freeze({ + recoveryWindowMs: 30 * 60_000, + retryInitialMs: 2_000, + overloadedInitialMs: 20_000, + retryFloorMs: 1_000, + overloadedFloorMs: 10_000, + retryCapMs: 60_000, + retryJitter: 0.5, + cappedRetryJitter: 0.1, + setupDeadlineMs: 20_000, + heartbeatIntervalMs: 20_000, + heartbeatDeadlineMs: 15_000, + healthyResetMs: 60_000, + alarmPeriodMinutes: 0.5, +}); + +export function createLending(shareOnBrowserStart) { + // ── Signing in: the SPA's oauth.js, through Chrome's identity window, everything kept in + // chrome.storage.local until sign-out. + + /** chrome.storage.local as oauth.js's store. */ + let allowSessionWrites = true; + const chromeStore = { + get: async (key) => (await chrome.storage.local.get(key))[key], + set: (key, value) => { + if (!allowSessionWrites) throw new Error("Sharing ended before the token request ended."); + return chrome.storage.local.set({ [key]: value }); + }, + remove: (key) => chrome.storage.local.remove(key), + }; + + const oauth = oauthClient({ + sessions: chromeStore, + // `https://<extension id>.chromiumapp.org/`: the published zip's manifest `key` keeps the id, and so + // this URL, the same on every install (scripts/build.ts replaces manifest.json's placeholder). + redirectUri: chrome.identity.getRedirectURL(), + // the issuer's own login and consent pages, which share the profile's cookies + launch: async (url) => { + const callback = await chrome.identity.launchWebAuthFlow({ interactive: true, url }); + if (!callback) + throw new Error("The sign-in window closed before the issuer sent Chrome back."); + return callback; + }, + beforeRefresh: async () => { + const mine = tokenGeneration; + if (mine !== generation || !state.sharing) throw new Error("This connection ended."); + refreshInFlight = true; + publish({ phase: "refreshing" }); + await persist(); + if (mine !== generation || !state.sharing) throw new Error("This connection ended."); + }, + registration: { + client_name: "iterate Chrome extension", + client_uri: "https://iterate.com", + }, + }); + + let tokenRequest = null; + let signInRequest = null; + let tokenGeneration; + let refreshInFlight = false; + async function freshAccessToken() { + if (!tokenRequest) { + tokenGeneration = generation; + tokenRequest = oauth.freshAccessToken().finally(() => { + tokenRequest = null; + refreshInFlight = false; + }); + } + const pending = tokenRequest; + if (refreshInFlight) { + // Joining an older in-flight refresh must keep its interruption fence durable. + publish({ phase: "refreshing" }); + await persist(); + } + return pending; + } + + // ── What this Chrome lends: an RpcTarget (capnweb passes it by reference, so a call on the mind's + // root context runs HERE). The mind drives the tabs in its tab group, over raw CDP, commands only: + // the wire stays a wire. The browser's facts go to the root stream: who joined and left the group + // (durable, per lend), and a tab attached, navigated, detached (ephemeral). + + /** The mind's tab group: every Chrome tab group, in any window, whose title is exactly this. No + * group id is kept: membership is read live from Chrome on every call, so a Chrome restart, a + * group moved to another window and one group per window all just work. */ + const groupTitle = () => lend?.title ?? ""; + const GROUP_COLORS = ["blue", "red", "yellow", "green", "pink", "purple", "cyan", "orange"]; + /** A fixed color per mind, set only when the extension makes a group: the person may change it. */ + function groupColorOf(title) { + let hash = 0; + for (const char of title) hash = (hash * 31 + char.charCodeAt(0)) % (2 ** 31 - 1); + return GROUP_COLORS[hash % GROUP_COLORS.length]; + } + + /** The mind's groups. `tabGroups.query({ title })` matches titles as globs, so compare here. */ + async function mindGroups() { + const title = groupTitle(); + if (!title) return []; + return (await chrome.tabGroups.query({})).filter((group) => group.title === title); + } + + /** The ids of the tabs in the mind's groups. `tabs.query({ groupId })` needs no `tabs` permission + * (the tabs it answers carry no URL or title). */ + async function memberIds() { + const lists = await Promise.all( + (await mindGroups()).map((group) => chrome.tabs.query({ groupId: group.id })), + ); + return lists.flat().map((tab) => tab.id); + } + + /** Whether a tab is in the mind's group right now; a closed tab is `tabGone`. */ + async function isMember(tabId) { + const title = groupTitle(); + if (!title) return false; + const tab = await chrome.tabs.get(tabId).catch(() => { + throw tabGone(tabId); + }); + if (tab.groupId === chrome.tabGroups.TAB_GROUP_ID_NONE) return false; + const group = await chrome.tabGroups.get(tab.groupId).catch(() => null); + return group?.title === title; + } + + /** Chrome refuses tab and group edits while the person drags a tab: try again, 10 times at most, + * 200 ms apart. */ + async function whileNotDragging(edit) { + for (let retries = 0; ; retries += 1) { + try { + return await edit(); + } catch (error) { + if (retries === 10 || !/user may be dragging a tab/.test(error?.message)) throw error; + await new Promise((resolve) => setTimeout(resolve, 200)); + } + } + } + + /** Put a tab in the mind's group of its window, or in a new group there. */ + async function addToGroup(tabId, windowId) { + const title = groupTitle(); + if (!title) throw new Error("This Chrome is not lent to a mind."); + const existing = (await mindGroups()).find((group) => group.windowId === windowId); + if (existing) { + await whileNotDragging(() => chrome.tabs.group({ groupId: existing.id, tabIds: [tabId] })); + return; + } + const groupId = await whileNotDragging(() => + chrome.tabs.group({ tabIds: [tabId], createProperties: { windowId } }), + ); + await whileNotDragging(() => + chrome.tabGroups.update(groupId, { title, color: groupColorOf(title), collapsed: false }), + ); + } + + /** The debugger's state per tab: whether it is attached and, while it is being attached or + * released, that promise (so overlapping calls share one). Not a grant: the group is the grant. + * The rest is what the person sees (below): what the mind does now (`activity`, a word, null once + * it settles), and the indicator's world on the page that shows (`indicatorWorld`, a promise of + * its execution context id). */ + const debuggees = new Map(); + const owned = new Set(); + let ownedWrites = Promise.resolve(); + function saveOwned() { + const ids = [...owned]; + ownedWrites = ownedWrites.then(() => chrome.storage.session.set({ debuggeeIds: ids })); + return ownedWrites; + } + + /** Track the native detach separately from its caller's deadline. Only the state that owns the + * tab may detach it; a retired initializer must never detach its replacement. */ + function detachDebugger(tabId, state) { + if (debuggees.get(tabId) !== state || state.detached) return Promise.resolve(); + state.detaching ??= chrome.debugger + .detach({ tabId }) + .catch((error) => { + if (!/Debugger is not attached|No tab with given id/.test(error?.message)) throw error; + }) + .then(() => { + state.detached = true; + state.attached = false; + if (debuggees.get(tabId) === state) { + forgetActivity(tabId); + owned.delete(tabId); + return saveOwned(); + } + }) + .finally(() => { + state.detaching = null; + }); + return state.detaching; + } + + /** Cancel attachment initialization before teardown. A page dialog can hold a CDP initializer + * open: wait at most one second, then detach anyway. A late initializer checks its cancellation + * before it can issue another command. Indicator removal and detach have separate deadlines. */ + async function release(tabId) { + const state = debuggees.get(tabId); + if (!state) return; + if (state.releasing) return state.releasing; + if (state.detached || (!state.attached && !state.attaching && !state.detaching)) return; + state.attachCancelled = true; + state.releasing ??= (async () => { + await within(1_000, state.attaching).catch((error) => { + if (/No answer in/.test(error?.message)) + console.warn({ + event: "browser-extension.platform-failure-release", + tabId, + message: error.message, + }); + }); + if (state.detached || (!state.attached && !state.attaching && !state.detaching)) return; + if (state.attached) + await within(1_000, inIndicator(tabId, REMOVE_INDICATOR)).catch(console.warn); + await within(1_000, detachDebugger(tabId, state)).catch(console.error); + })().finally(() => { + state.releasing = null; + }); + await state.releasing; + } + /** Release tabs independently: a blocked tab cannot delay teardown of another. Their groups stay + * in Chrome; the groups belong to the person. */ + async function releaseTabs() { + await Promise.all([...debuggees.keys()].map((tabId) => release(tabId))); + } + + /** This Chrome's lend, set by `connect`: its name, the group's title, where its events go, and the + * tabs it announced as added. A new lend announces every member again: the facts belong to a lend. */ + let lend = null; + const fact = (type, payload) => + lend?.append({ type, ephemeral: true, payload: { ...payload, lendName: lend.name } }); + const record = (type, payload) => + lend?.append({ type, payload: { ...payload, lendName: lend.name } }); + /** Redraws the extension's list of tabs, and writes a line in its tab card (`connect` sets both). */ + let showTabs = () => {}; + let tellTabCard = () => {}; + + /** Brings the announced members and the debugger in step with the group: a tab that joined is + * `chrome/tab-added`; a tab that left (or closed) loses the debugger and is `chrome/tab-removed`. */ + async function reconcile() { + const current = lend; + const members = new Set(await memberIds()); + if (lend !== current) return; + const announced = current?.announced ?? new Set(); + const attached = [...debuggees].filter(([, state]) => state.attached || state.attaching); + const left = new Set( + [...announced, ...attached.map(([tabId]) => tabId)].filter((tabId) => !members.has(tabId)), + ); + for (const tabId of left) { + await release(tabId); + if (announced.delete(tabId) && lend === current) + record("events.iterate.com/chrome/tab-removed", { tabId }); + } + const joined = [...members].filter((tabId) => !announced.has(tabId)); + if (joined.length && current && lend === current) { + const targets = await chrome.debugger.getTargets(); + if (lend !== current) return; + for (const tabId of joined) { + announced.add(tabId); + const url = targets.find((target) => target.tabId === tabId)?.url; + record("events.iterate.com/chrome/tab-added", { tabId, url }); + } + } + showTabs(); + } + + // One reconcile at a time, and a request while one runs makes exactly one more. Requests wait + // 500 ms for quiet: Chrome sends short-lived `groupId = -1` updates while a group is dragged or + // moved to another window. + let reconcileTimer; + let reconciling = false; + let reconcileAgain = false; + async function reconcileNow() { + if (reconciling) { + reconcileAgain = true; + return; + } + reconciling = true; + try { + await reconcile(); + } catch (error) { + console.error(error); + } finally { + reconciling = false; + if (reconcileAgain) { + reconcileAgain = false; + void reconcileNow(); + } + } + } + function reconcileSoon() { + clearTimeout(reconcileTimer); + reconcileTimer = setTimeout(reconcileNow, 500); + } + + chrome.tabs.onUpdated.addListener((_tabId, change) => { + // `status` too: Chrome opens a grouped tab's child inside the group and sends no groupId change. + if ("groupId" in change || change.status) reconcileSoon(); + }); + chrome.tabs.onRemoved.addListener((tabId) => { + if (lend) ChromeBrowser.evictPage(lend.browser, tabId); + debuggees.delete(tabId); + if (owned.delete(tabId)) void saveOwned(); + reconcileSoon(); + }); + // A tab Chrome replaces (a prerendered page swapped in) is a new debuggee: the debugger stayed with + // the old page, so the next `cdp` attaches again. + chrome.tabs.onReplaced.addListener((_addedTabId, removedTabId) => { + if (lend) ChromeBrowser.evictPage(lend.browser, removedTabId); + debuggees.delete(removedTabId); + if (owned.delete(removedTabId)) void saveOwned(); + reconcileSoon(); + }); + chrome.tabGroups.onCreated.addListener(reconcileSoon); + chrome.tabGroups.onUpdated.addListener(reconcileSoon); + chrome.tabGroups.onRemoved.addListener(reconcileSoon); + + /** Chrome's "No tab with given id", in words an agent can act on. */ + function tabGone(tabId) { + return new Error( + `Tab ${tabId} is gone: it was closed, or Chrome replaced it. Call tabs() for the tabs you may drive.`, + ); + } + + /** Refuse a tab that is not in the mind's group right now, attached or not. */ + async function requireMember(tabId) { + if (await isMember(tabId)) return; + const title = groupTitle(); + throw new Error( + `Tab ${tabId} is not in the "${title}" tab group: the mind drives only the tabs in that group. Call tabs() for them.`, + ); + } + + /** Attach the debugger to a tab in the mind's group (once; Chrome shows its bar on the tab). The + * membership check runs on every call, so every `cdp` command makes it. */ + async function attach(tabId, requireConnection) { + let state = debuggees.get(tabId); + await state?.releasing?.catch(() => undefined); + requireConnection(); + await state?.detaching?.catch(() => undefined); + requireConnection(); + if (state?.attachCancelled) { + // A native attach can still arrive after teardown. Let that request answer before releasing + // it again; a stalled CDP initializer, in contrast, can be retired once detach has answered. + await state.attachRequest?.catch(() => undefined); + requireConnection(); + await release(tabId); + requireConnection(); + await state.detaching?.catch(() => undefined); + requireConnection(); + if (!state.detached) throw new Error(`Tab ${tabId}'s debugger teardown has not completed.`); + if (debuggees.get(tabId) === state) debuggees.delete(tabId); + } + await requireMember(tabId); + requireConnection(); + state = + debuggees.get(tabId) ?? debuggees.set(tabId, { attached: false, attaching: null }).get(tabId); + if (state.attached) return; + state.attaching ??= (async () => { + state.attachCancelled = false; + state.detached = false; + const requireAttachment = () => { + requireConnection(); + if (state.attachCancelled || debuggees.get(tabId) !== state) + throw new Error(`Tab ${tabId}'s debugger was released during attachment.`); + }; + try { + owned.add(tabId); + await saveOwned(); + requireAttachment(); + state.attachRequest = chrome.debugger.attach({ tabId }, "1.3").then(() => { + state.detached = false; + }); + await state.attachRequest.catch(async (error) => { + if (/No tab with given id/.test(error?.message)) throw tabGone(tabId); + // A stopped worker can leave this extension's session attached. Chrome accepts its CDP + // commands, but refuses commands through a debugger owned by DevTools or another extension. + if (!/Another debugger is already attached/.test(error?.message)) throw error; + state.detached = false; + requireAttachment(); + await chrome.debugger + .sendCommand({ tabId }, "Runtime.evaluate", { expression: "0" }) + .catch(() => { + throw error; + }); + }); + requireAttachment(); + // Page and Runtime carry navigation, the indicator and page reports. + await chrome.debugger.sendCommand({ tabId }, "Page.enable"); + requireAttachment(); + await chrome.debugger.sendCommand({ tabId }, "Runtime.enable"); + requireAttachment(); + const { result } = await chrome.debugger.sendCommand({ tabId }, "Runtime.evaluate", { + expression: "location.href", + returnByValue: true, + }); + requireAttachment(); + state.attached = true; + fact("events.iterate.com/chrome/attached", { tabId, url: result.value }); + await showIndicator(tabId); + requireAttachment(); + showTabs(); + } catch (error) { + await within(1_000, detachDebugger(tabId, state)).catch(console.warn); + throw error; + } + })().finally(() => { + state.attaching = null; + }); + await state.attaching; + } + + // ── What the person sees while the mind's debugger is attached to a tab: indicator.js on the page + // (a frame and a label with Stop), the toolbar button's badge on that tab, and a word in the + // panel's list. A tab is "acting" for 3 s after each `cdp` command. None of it may fail or slow the + // mind's command: its errors go to console.warn. + + /** The isolated world indicator.js runs in, and the binding its Stop button calls. Only contexts + * of that name get the binding: the page's own scripts cannot call Stop. */ + const INDICATOR_WORLD = "iterate-indicator"; + const STOP_BINDING = "iterateIndicatorStop"; + /** At most one write of the indicator's `data-activity` per tab in this time. */ + const INDICATOR_WRITE_MS = 200; + /** The longest wait for an indicator call: a page with an open dialog answers no evaluate. */ + const INDICATOR_TIMEOUT_MS = 1_000; + + /** The words for what the mind does, from the CDP method of its latest command. */ + const ACTIVITY_WORDS = new Map([ + ["Input.dispatchMouseEvent", "clicking"], + ["Input.dispatchTouchEvent", "clicking"], + ["Input.dispatchKeyEvent", "typing"], + ["Input.insertText", "typing"], + ["Page.navigate", "opening a page"], + ["Page.reload", "opening a page"], + ["Page.navigateToHistoryEntry", "opening a page"], + ["Page.captureScreenshot", "looking"], + ]); + const activityOf = (method) => + ACTIVITY_WORDS.get(method) ?? + (/^(Runtime|DOM|Accessibility|CSS)\./.test(method) ? "reading the page" : "working"); + + /** indicator.js's text, read once. */ + let indicatorSource; + async function indicatorScript() { + indicatorSource ??= fetch(chrome.runtime.getURL("indicator.js")).then((answer) => { + if (!answer.ok) throw new Error(`indicator.js answered ${answer.status}.`); + return answer.text(); + }); + // a failed read is tried again next time + return indicatorSource.catch((error) => { + indicatorSource = undefined; + throw error; + }); + } + /** The label names the mind as the panel does: its address, with the name and logo of its + * profile when it has them (./profile.js). */ + const indicatorExpression = async () => + `(${await indicatorScript()})(${JSON.stringify({ address: groupTitle(), ...shownProfile() })});`; + + /** The indicator's host element, as an expression for its world. */ + const HOST = `document.documentElement?.querySelector(":scope > iterate-indicator")`; + const REMOVE_INDICATOR = `${HOST}?.remove()`; + const SHOW_INDICATOR = `${HOST}?.removeAttribute("data-hidden")`; + // Two frames, so a screenshot taken after it has no indicator; a tab in the background draws no + // frames, so 100 ms at most. + const HIDE_INDICATOR = `(async () => { + ${HOST}?.setAttribute("data-hidden", ""); + await Promise.race([ + new Promise((drawn) => requestAnimationFrame(() => requestAnimationFrame(drawn))), + new Promise((waited) => setTimeout(waited, 100)), + ]); +})()`; + + /** A promise that rejects after `ms`, unless `promise` settles first. */ + function within(ms, promise) { + let timer; + const late = new Promise((_settled, failed) => { + timer = setTimeout(() => failed(new Error(`No answer in ${ms} ms.`)), ms); + }); + return Promise.race([promise, late]).finally(() => clearTimeout(timer)); + } + + // The heartbeat indicator.js waits for (its header says why). One interval writes `data-alive` on + // every attached tab every 4 s; the write at attach and each `data-activity` write count too. + let heartbeats = null; + + /** On attach: the indicator on every page the tab loads from now on (Chrome runs the script while + * the Page domain is on in this session, and forgets it at detach), and on the page that shows. A + * failure leaves the tab without an indicator, never the mind without the tab. */ + async function showIndicator(tabId) { + const state = debuggees.get(tabId); + const current = () => + debuggees.get(tabId) === state && state?.attached && !state.attachCancelled; + if (!current()) return; + try { + await chrome.debugger.sendCommand({ tabId }, "Runtime.addBinding", { + name: STOP_BINDING, + executionContextName: INDICATOR_WORLD, + }); + const source = await indicatorExpression(); + if (!current()) return; + await chrome.debugger.sendCommand({ tabId }, "Page.addScriptToEvaluateOnNewDocument", { + source, + worldName: INDICATOR_WORLD, + }); + } catch (error) { + console.warn(error); + return; + } + if (!current()) return; + showBadge(tabId); + heartbeat(tabId); + heartbeats ??= setInterval(() => { + const attached = [...debuggees].filter(([, state]) => state.attached); + if (!attached.length) { + clearInterval(heartbeats); + heartbeats = null; + } + for (const [attachedId] of attached) heartbeat(attachedId); + }, 4_000); + } + + /** One heartbeat on a tab's indicator, never two in flight. An indicator that is gone (it saw no + * heartbeat in time, or the page removed it) comes back at the next one, in a new world. */ + function heartbeat(tabId) { + const state = debuggees.get(tabId); + if (!state?.attached || state.heartbeating || state.attachCancelled) return; + state.heartbeating = true; + const expression = `(() => { + const host = ${HOST}; + host?.setAttribute("data-alive", "${Date.now()}"); + return Boolean(host); + })()`; + inIndicator(tabId, expression, { returnByValue: true }) + .then((found) => { + if (found?.value === false) state.indicatorWorld = null; + }) + .catch(console.warn) + .finally(() => { + state.heartbeating = false; + }); + } + + function requireIndicatorState(tabId, state) { + if (debuggees.get(tabId) !== state || !state.attached) + throw new Error(`Tab ${tabId}'s indicator session ended.`); + } + + /** The indicator's world on the page that shows: an isolated world of the top frame, with the + * indicator in it (indicator.js adds none where the page has one). */ + async function indicatorWorldOf(tabId, state) { + requireIndicatorState(tabId, state); + const { frameTree } = await chrome.debugger.sendCommand({ tabId }, "Page.getFrameTree"); + requireIndicatorState(tabId, state); + const { executionContextId } = await chrome.debugger.sendCommand( + { tabId }, + "Page.createIsolatedWorld", + { frameId: frameTree.frame.id, worldName: INDICATOR_WORLD }, + ); + const expression = await indicatorExpression(); + requireIndicatorState(tabId, state); + await chrome.debugger.sendCommand({ tabId }, "Runtime.evaluate", { + expression, + contextId: executionContextId, + }); + return executionContextId; + } + + /** Evaluate an expression in the indicator's world of an attached tab. The world is made on first + * use; a main-frame navigation drops it, and so does any failure here, so the next call makes a + * new one. A "Cannot find context" (the page went) is tried once more, in a new world. */ + async function inIndicator(tabId, expression, options = {}) { + const state = debuggees.get(tabId); + if (!state?.attached) return undefined; + for (let retried = false; ; retried = true) { + const world = (state.indicatorWorld ??= indicatorWorldOf(tabId, state)); + try { + return await within( + INDICATOR_TIMEOUT_MS, + world.then(async (contextId) => { + requireIndicatorState(tabId, state); + const { result, exceptionDetails } = await chrome.debugger.sendCommand( + { tabId }, + "Runtime.evaluate", + { expression, contextId, ...options }, + ); + if (exceptionDetails) + throw new Error(exceptionDetails.exception?.description ?? exceptionDetails.text); + return result; + }), + ); + } catch (error) { + if (state.indicatorWorld === world) state.indicatorWorld = null; + if (retried || !/Cannot find context/.test(error?.message)) throw error; + } + } + } + + /** The toolbar button's badge on a tab: "on" while attached, in the stronger color while the mind + * acts. A closed tab refuses it, and needs none. */ + function showBadge(tabId) { + const state = debuggees.get(tabId); + const text = state?.attached ? "on" : ""; + chrome.action.setBadgeText({ tabId, text }).catch(() => {}); + if (text) + chrome.action + .setBadgeBackgroundColor({ tabId, color: state.activity ? "#6366f1" : "#71717a" }) + .catch(() => {}); + } + + /** A `cdp` command on an attached tab: the word for it, now, on the badge, in the extension's list (on + * a change of word) and on the page (one write per 200 ms at most); it settles after 3 s. */ + function noteActivity(tabId, method) { + const state = debuggees.get(tabId); + if (!state?.attached) return; + const word = activityOf(method); + const changed = word !== state.activity; + state.activity = word; + state.actedAt = Date.now(); + clearTimeout(state.settleTimer); + state.settleTimer = setTimeout(() => { + state.activity = null; + showBadge(tabId); + showTabs(); + }, 3_000); + if (changed) { + showBadge(tabId); + showTabs(); + } + // The word and its time: a repeat of the same word restarts the indicator's 3 s too. + state.indicatorWrite ??= setTimeout( + () => { + state.indicatorWrite = null; + state.indicatorWrittenAt = Date.now(); + if (!state.activity) return; + const value = JSON.stringify(`${state.activity} ${state.actedAt}`); + inIndicator(tabId, `${HOST}?.setAttribute("data-activity", ${value})`).catch(console.warn); + }, + Math.max(0, (state.indicatorWrittenAt ?? 0) + INDICATOR_WRITE_MS - Date.now()), + ); + } + + /** After a detach: no activity, no world, no badge. */ + function forgetActivity(tabId) { + const state = debuggees.get(tabId); + if (state) { + clearTimeout(state.settleTimer); + clearTimeout(state.indicatorWrite); + state.indicatorWrite = null; + state.activity = null; + state.indicatorWorld = null; + } + showBadge(tabId); + } + + /** Stop on a tab's indicator: the person means "the mind lets go of this tab". It leaves the + * group, so the mind cannot attach again. */ + async function stopFromPage(tabId) { + try { + const target = (await chrome.debugger.getTargets()).find((each) => each.tabId === tabId); + await whileNotDragging(() => chrome.tabs.ungroup(tabId)); + await release(tabId); + tellTabCard(`You clicked Stop on ${target?.title || `tab ${tabId}`}: it left the group.`); + } catch (error) { + console.error(error); + } + } + + /** The longest page report the extension appends. */ + const BINDING_PAYLOAD_LIMIT = 8_192; + /** Page reports in the order the pages made them: the membership check is async. */ + let bindingReports = Promise.resolve(); + + chrome.debugger.onEvent.addListener(({ tabId }, method, params) => { + if (method === "Page.frameNavigated" && !params.frame.parentId) { + fact("events.iterate.com/chrome/navigated", { tabId, url: params.frame.url }); + // The new page has its indicator from the new-document script, but not the extension's world. + const state = debuggees.get(tabId); + if (state) state.indicatorWorld = null; + showBadge(tabId); + } + if (method !== "Runtime.bindingCalled") return; + const { name, payload } = params; + // The indicator's Stop is the extension's own, never a page report. + if (name === STOP_BINDING) { + void stopFromPage(tabId); + return; + } + if (payload.length > BINDING_PAYLOAD_LIMIT) { + console.warn(`Dropped a ${payload.length}-character ${name} report from tab ${tabId}.`); + return; + } + // The type is always the extension's own: the extension appends as the signed-in person, and some mind + // code trusts only a person's own append, so a type the page chose would let it act as them. + const current = lend; + bindingReports = bindingReports.then(async () => { + if ( + current && + lend === current && + (await isMember(tabId).catch(() => false)) && + lend === current + ) + record("events.iterate.com/chrome/binding-called", { tabId, name, payload }); + }); + }); + chrome.debugger.onDetach.addListener(({ tabId }, reason) => { + const state = debuggees.get(tabId); + if (state) { + state.attached = false; + state.detached = true; + state.attachCancelled = true; + } + // The page keeps an indicator the extension did not remove (no CDP after a detach) until it loads + // the next page, which gets none: no session, no new-document script. + if (owned.delete(tabId)) void saveOwned(); + forgetActivity(tabId); + fact("events.iterate.com/chrome/detached", { tabId, reason }); + // Cancel on Chrome's debugging bar detaches every tab, and the person meant "stop": the tabs + // leave the group, so the mind cannot attach again. Any other reason leaves the group alone: an + // injected iframe's stray `target_closed` must not take a tab away. + if (reason === "canceled_by_user") void ungroupMembers(); + showTabs(); + }); + + async function ungroupMembers() { + try { + const ids = await memberIds(); + if (ids.length) await whileNotDragging(() => chrome.tabs.ungroup(ids)); + tellTabCard("You clicked Cancel on Chrome's debugging bar: the tabs left the group."); + } catch (error) { + console.error(error); + } + } + + /** The tabs in the mind's group, still open. URLs and titles come from the debugger's target list, + * which carries them without the `tabs` permission. */ + async function memberTabs() { + const [ids, targets] = await Promise.all([memberIds(), chrome.debugger.getTargets()]); + return ids.map((tabId) => { + const target = targets.find((candidate) => candidate.tabId === tabId); + return { + tabId, + url: target?.url, + title: target?.title, + attached: debuggees.get(tabId)?.attached ?? false, + activity: debuggees.get(tabId)?.activity ?? null, + }; + }); + } + + class ChromeBrowser extends RpcTarget { + #current; + + constructor(current) { + super(); + this.#current = current; + } + + #requireConnection() { + if (!this.#current()) + throw new Error( + "This browser connection ended. Find the current lend before sending another action.", + ); + } + + #pages = new Map(); + + static evictPage(browser, tabId) { + browser.#pages.delete(tabId); + } + + /** A retained handle still checks live group membership on every CDP command. */ + async page(tabId) { + this.#requireConnection(); + if (!Number.isInteger(tabId) || tabId < 0) throw new Error("page() requires a tab id"); + await requireMember(tabId); + this.#requireConnection(); + if (!this.#pages.has(tabId)) + this.#pages.set( + tabId, + new ChromePage((method, params) => this.cdp(tabId, method, params), locatorSource), + ); + return this.#pages.get(tabId); + } + + /** The tabs in the mind's group: how an agent finds a tab the person added. */ + async tabs() { + this.#requireConnection(); + const members = await memberTabs(); + this.#requireConnection(); + return members; + } + + /** Open an http(s) page in a new active tab in the mind's group; answers once the page has + * loaded (or after ten seconds) with the tab's id and URL. A tab Chrome replaces while it loads + * answers with its new id; a tab closed while it loads is an error. */ + async openPage(input) { + this.#requireConnection(); + if (!input || typeof input.url !== "string") throw new Error("openPage() takes { url }."); + const target = new URL(input.url); + if (target.protocol !== "http:" && target.protocol !== "https:") + throw new Error("openPage() only accepts http and https URLs."); + // A service worker has no panel window. Prefer the current group's window, then any + // existing group, then a normal browser window. Never require the panel to be open. + const [currentWindow, groups] = await Promise.all([ + chrome.windows.getCurrent().catch(() => null), + mindGroups(), + ]); + const group = + groups.find((candidate) => candidate.windowId === currentWindow?.id) ?? groups[0]; + let windowId = group?.windowId ?? currentWindow?.id; + if (!Number.isInteger(windowId)) { + const windows = await chrome.windows.getAll({ windowTypes: ["normal"] }); + windowId = windows.find((window) => Number.isInteger(window.id))?.id; + } + this.#requireConnection(); + if (!Number.isInteger(windowId)) + throw new Error("Open a Chrome window before asking the mind to open a page."); + const tab = await chrome.tabs.create({ active: true, url: target.href, windowId }); + try { + this.#requireConnection(); + await addToGroup(tab.id, windowId); + } catch (error) { + await chrome.tabs.remove(tab.id).catch(() => {}); + throw error; + } + let tabId = tab.id; + await new Promise((loaded, failed) => { + const done = (settle) => { + chrome.tabs.onUpdated.removeListener(onUpdated); + chrome.tabs.onReplaced.removeListener(onReplaced); + chrome.tabs.onRemoved.removeListener(onRemoved); + clearTimeout(timer); + settle(); + }; + const onUpdated = (id, change) => { + if (id === tabId && change.status === "complete") done(loaded); + }; + const onReplaced = (added, removed) => { + if (removed === tabId) tabId = added; + }; + const onRemoved = (id) => { + if (id === tabId) done(() => failed(new Error(`Tab ${id} was closed before it loaded.`))); + }; + chrome.tabs.onUpdated.addListener(onUpdated); + chrome.tabs.onReplaced.addListener(onReplaced); + chrome.tabs.onRemoved.addListener(onRemoved); + const timer = setTimeout(() => done(loaded), 10_000); + // Listeners first, then the current status: a page that was already complete fires nothing. + void chrome.tabs.get(tabId).then( + (current) => onUpdated(tabId, { status: current.status }), + () => onRemoved(tabId), + ); + }); + return { tabId, url: target.href }; + } + + /** One CDP command on a tab in the mind's group (attached on first use): the command's result, + * e.g. `cdp(tabId, "Runtime.evaluate", { expression: "document.title", returnByValue: true })`. + * `Page.disable` and `Runtime.disable` answer `{}` and are not sent: the extension keeps both + * domains on, for the indicator, the navigation facts and page reports. A screenshot leaves the + * indicator out. */ + async cdp(tabId, method, params) { + this.#requireConnection(); + await attach(tabId, () => this.#requireConnection()); + this.#requireConnection(); + if (method === "Page.disable" || method === "Runtime.disable") return {}; + noteActivity(tabId, method); + const send = async () => { + this.#requireConnection(); + await requireMember(tabId); + this.#requireConnection(); + return chrome.debugger.sendCommand({ tabId }, method, params).catch((error) => { + throw /No tab with given id/.test(error?.message) ? tabGone(tabId) : error; + }); + }; + if (method !== "Page.captureScreenshot") return send(); + // Shown again when the last of overlapping screenshots is taken. One it cannot hide is taken + // anyway. + const state = debuggees.get(tabId); + state.screenshots = (state.screenshots ?? 0) + 1; + await inIndicator(tabId, HIDE_INDICATOR, { awaitPromise: true }).catch(console.warn); + try { + return await send(); + } finally { + state.screenshots -= 1; + if (!state.screenshots) inIndicator(tabId, SHOW_INDICATOR).catch(console.warn); + } + } + + /** Let go of a tab: the debugger bar goes; the tab stays in the group and stays drivable. */ + async detach(tabId) { + this.#requireConnection(); + await release(tabId); + } + } + + // ── The lend's name. Every lent Chrome has its own: `itx.chrome.<person>.<browser>`, so two people, + // or one person's two Chrome profiles, never take each other's. `chrome` comes first: a lent name + // never starts with a name of the platform's (core's `lendRefusal`), and a person's segment could be + // one (`email`, `run`). A name is letters and digits, each segment starting with a letter + // (`iterate provide`'s rule). + const SEGMENT = /^[a-zA-Z][a-zA-Z0-9]*$/; + const isLendSegment = (value) => + SEGMENT.test(value) && !["constructor", "prototype"].includes(value); + + /** The person's segment: the signed-in address before its `@`, letters and digits only. */ + function personSegmentOf(principal) { + const local = (principal?.email || "") + .split("@")[0] + .toLowerCase() + .replace(/[^a-z0-9]/g, ""); + return isLendSegment(local) ? local : "member"; + } + + /** This Chrome's segment: a name the person gave it, or one made at its first connect from the + * platform and a random suffix (`mac3f9a`), kept in this install's storage. */ + async function browserSegment() { + const { browserName } = await chrome.storage.local.get("browserName"); + if (browserName && isLendSegment(browserName)) return browserName; + const platform = (navigator.userAgentData?.platform || navigator.platform || "chrome") + .toLowerCase() + .replace(/^macos$|^macintel$/, "mac") + .replace(/^win.*/, "windows") + .replace(/[^a-z0-9]/g, ""); + const suffix = crypto.getRandomValues(new Uint16Array(1))[0].toString(16).padStart(4, "0"); + const made = `${isLendSegment(platform) ? platform : "chrome"}${suffix}`; + await chrome.storage.local.set({ browserName: made }); + return made; + } + + // ── The socket. A mind's API takes its bearer on the upgrade request, a header a page cannot set + // on a WebSocket: one session rule sets it, for this extension's own socket to that one URL. Each + // connect replaces the rule with its own token and sign-out removes it; the rule is never removed + // on a handshake, so a superseded socket cannot take the rule from the connect that replaced it. + // Every write to the rule waits in one queue, and a connect's write runs only while its generation + // is current: sign-out bumps the generation before it queues the removal, so a connect still in + // flight cannot put the token back after it. + const BEARER_RULE = 1; + let bearerRuleWrites = Promise.resolve(); + const writeBearerRule = (write) => (bearerRuleWrites = bearerRuleWrites.then(write, write)); + + /** The API proxy, or null when a newer connect or a sign-out came first. The mind's API is a + * WebSocket alone, and it checks the bearer inside the session: a bearer that it refuses fails + * the first call on the proxy with the code UNAUTHENTICATED, which ends the lend for good + * (`reconnectKind` retries no coded refusal). */ + async function openApiConnection({ issuer, token, current, onFailure }) { + const url = new URL("/api", issuer); + url.protocol = "wss:"; + const addRules = [ + { + id: BEARER_RULE, + action: { + type: "modifyHeaders", + requestHeaders: [{ header: "authorization", operation: "set", value: `Bearer ${token}` }], + }, + condition: { + urlFilter: `|${url.href}|`, + // never a web page's socket to the same URL + initiatorDomains: [chrome.runtime.id], + resourceTypes: ["websocket"], + }, + }, + ]; + await writeBearerRule(async () => { + if (!current()) return; + await chrome.declarativeNetRequest.updateSessionRules({ + removeRuleIds: [BEARER_RULE], + addRules, + }); + }); + return current() ? openOffscreenApi(url.href, current, onFailure) : null; + } + + // A view or a connection that is no longer current stops acting: every async step compares its + // generation to this counter before touching the page or the socket. + let generation = 0; + let live = null; + let retryTimer; + let beatTimer; + let drawTimer; + let retries = 0; + let recoveryUntil = null; + let cancelPending = () => {}; + + function disconnect() { + generation += 1; + void disconnectOffscreen().catch(console.error); + clearTimeout(retryTimer); + clearTimeout(beatTimer); + clearTimeout(drawTimer); + drawTimer = null; + cancelPending(); + cancelPending = () => {}; + lend = null; + + const previous = live; + live = null; + previous?.[Symbol.dispose](); + return generation; + } + + async function connectionAnswer(mine, ms, promise) { + const cancelled = new Promise((_resolve, reject) => { + cancelPending = () => reject(new Error("This connection ended.")); + }); + const deadline = Date.now() + ms; + try { + const answer = await within(ms, Promise.race([promise, cancelled])); + // After sleep, queued replies can run before an already-expired timer callback. + if (Date.now() >= deadline) throw new Error(`No answer in ${ms} ms.`); + return answer; + } finally { + if (mine === generation) cancelPending = () => {}; + } + } + + function reconnectKind(error) { + if (error?.code === "TOKEN_EXPIRED") return "token-expired"; + if (error?.code === "UNAVAILABLE") { + if (["overloaded", "disconnected", "deploy-reset"].includes(error.data?.kind)) + return error.data.kind; + return "unavailable"; + } + if (error?.code === "RPC_STUB_OFFLINE") return "disconnected"; + if (error?.code === "OVERLOADED" || error?.overloaded === true) return "overloaded"; + if (error?.code) return null; + if ( + error?.overloaded || + /is overloaded|queued for too long|No answer in \d+ ms/i.test(error?.message) + ) + return "overloaded"; + if ( + error?.retryable || + /WebSocket|disconnected|connection.*closed|network|Failed to fetch|reset because its code was updated/i.test( + error?.message, + ) + ) + return "disconnected"; + return null; + } + + const ALARM = "iterate-lending"; + const listeners = new Set(); + let session = null; + let state = { + phase: "initializing", + sharing: false, + retries: 0, + retryAt: null, + error: "", + members: [], + }; + let writes = Promise.resolve(); + // A mind's issuer is the origin at its address, which may be any hostname (./address.js). + const isMindSession = (value) => + typeof value?.issuer === "string" && value.issuer.startsWith("https://"); + + // What the mind says of itself (./profile.js), read when a session shows and at each connect. It + // is display data alone: no lend, group or permission depends on it. A read that got no answer + // keeps the profile that an earlier read of the same mind got. + let profile = null; + const shownProfile = () => + profile && profile.issuer === session?.issuer + ? { name: profile.name, icon: profile.icon } + : { name: "", icon: null }; + function readProfile() { + const issuer = session?.issuer; + if (!issuer) return; + void readMindProfile(issuer).then((read) => { + if (!read || session?.issuer !== issuer) return; + profile = { issuer, ...read }; + publish({}); + }); + } + + function snapshot() { + return { + ...state, + // a signed-in panel names its mind in every phase, not only while connected + address: isMindSession(session) ? mindAddressOf(session.issuer) : state.address, + profile: shownProfile(), + recoveryUntil, + instructions: + state.phase === "connected" + ? agentInstructions(state.address, state.name, state.members) + : "", + signedIn: !!session, + issuer: session?.issuer, + version: chrome.runtime.getManifest().version, + }; + } + function publish(patch) { + state = { ...state, ...patch, retries }; + for (const listener of listeners) listener(snapshot()); + } + function persist() { + const saved = { + issuer: session?.issuer, + sharing: state.sharing, + phase: state.phase, + retries, + recoveryUntil, + retryAt: state.retryAt, + }; + writes = writes.then(async () => { + await chrome.storage.session.set({ lending: saved }); + await chrome.storage.local.set({ sharingRequested: saved.sharing }); + }); + return writes; + } + async function watch() { + if (state.sharing && !["failed", "displaced", "exhausted"].includes(state.phase)) + await chrome.alarms.create(ALARM, { periodInMinutes: LENDING_TIMING.alarmPeriodMinutes }); + else await chrome.alarms.clear(ALARM); + } + showTabs = () => { + drawTimer ??= setTimeout(async () => { + drawTimer = null; + const mine = generation; + const members = await memberTabs().catch(() => []); + if (mine === generation) publish({ members }); + }, 100); + }; + tellTabCard = (notice) => publish({ notice }); + + async function connectionFailed(currentSession, mine, error, canReconnect) { + if (mine !== generation) return; + const stopped = disconnect(); + void releaseTabs(); + const kind = canReconnect && reconnectKind(error); + if (kind) recoveryUntil ??= Date.now() + LENDING_TIMING.recoveryWindowMs; + const expired = kind && Date.now() >= recoveryUntil; + const suggested = error?.data?.retryAfterMs; + const floor = Math.max( + kind === "overloaded" ? LENDING_TIMING.overloadedFloorMs : LENDING_TIMING.retryFloorMs, + Number.isFinite(suggested) && suggested > 0 ? suggested : 0, + ); + if (state.sharing && kind && !expired) { + const initial = + kind === "overloaded" ? LENDING_TIMING.overloadedInitialMs : LENDING_TIMING.retryInitialMs; + const backoff = Math.min(LENDING_TIMING.retryCapMs, initial * 2 ** retries); + const ceiling = Math.max(floor, backoff); + const jitter = + backoff === LENDING_TIMING.retryCapMs + ? LENDING_TIMING.cappedRetryJitter + : LENDING_TIMING.retryJitter; + const minimum = Math.max(floor, ceiling * (1 - jitter)); + const delay = Math.min( + Math.round(minimum + Math.random() * (ceiling - minimum)), + recoveryUntil - Date.now(), + ); + retries += 1; + publish({ phase: "waiting", retryAt: Date.now() + delay, error: error.message, members: [] }); + const renewal = kind === "token-expired"; + const log = renewal ? console.info : console.warn; + log({ + event: renewal + ? "browser-extension.session-renewal" + : "browser-extension.platform-failure-retry", + kind, + attempt: retries, + retryInMs: Date.now() + delay < recoveryUntil ? delay : null, + nextCheckInMs: delay, + recoveryUntil, + message: error.message, + }); + await persist(); + if (stopped !== generation) return; + await watch(); + if (stopped !== generation) return; + retryTimer = setTimeout(() => { + if (stopped === generation) void connect(currentSession, true); + }, delay); + } else { + publish({ + phase: expired ? "exhausted" : "failed", + retryAt: null, + members: [], + error: expired + ? `Automatic lending recovery ended after ${LENDING_TIMING.recoveryWindowMs / 60_000} minutes. Choose Lend again to start a new recovery window.` + : error.message, + }); + console.warn({ + event: "browser-extension.platform-failure-gave-up", + kind, + scheduledRetries: retries, + recoveryUntil, + reason: expired ? "recovery-window-ended" : "not-retryable", + message: error.message, + }); + await persist(); + await watch(); + } + } + + async function connect(currentSession, automatic = false) { + if (!state.sharing || session?.issuer !== currentSession.issuer) return; + if (automatic && state.phase !== "waiting") return; + if (automatic && recoveryUntil !== null && Date.now() >= recoveryUntil) { + await connectionFailed( + currentSession, + generation, + Object.assign(new Error("The connection recovery window ended."), { code: "UNAVAILABLE" }), + true, + ); + return; + } + if (!automatic) { + retries = 0; + recoveryUntil = null; + } + const mine = disconnect(); + const setupDeadline = Date.now() + LENDING_TIMING.setupDeadlineMs; + const setupCurrent = () => mine === generation && Date.now() < setupDeadline; + publish({ phase: "connecting", retryAt: null, error: "", members: [] }); + readProfile(); + let itx; + let checkLend; + let canReconnect = false; + try { + const setup = await connectionAnswer( + mine, + LENDING_TIMING.setupDeadlineMs, + (async () => { + await watch(); + if (!setupCurrent()) return null; + await persist(); + if (!setupCurrent()) return null; + await releaseTabs(); + if (!setupCurrent()) return null; + const token = await freshAccessToken(); + if (!setupCurrent()) return null; + canReconnect = true; + publish({ phase: "connecting" }); + await persist(); + if (!setupCurrent()) return null; + itx = await openApiConnection({ + issuer: currentSession.issuer, + token, + current: setupCurrent, + onFailure: (error) => connectionFailed(currentSession, mine, error, true), + }); + if (!itx) return null; + live = itx; + const browser = new ChromeBrowser(() => mine === generation && state.sharing); + const [whoami, browserName] = await Promise.all([itx.whoami(), browserSegment()]); + if (!setupCurrent()) return null; + const person = personSegmentOf(whoami.principal); + const name = `itx.chrome.${person}.${browserName}`; + checkLend = () => itx.invoke([...name.split("."), ["tabs"]]); + const provided = await itx.provide(name, browser, { + description: `${person}'s Chrome (${browserName}), while sharing is on (the side panel may be closed): tabs(), openPage({ url }), page(tabId) (prototype: Playwright-shaped getByRole/getByText/getByLabel/locator, click/fill/press), cdp(tabId, method, params), detach(tabId).`, + }); + if (!setupCurrent()) return null; + lend = { + browser, + name, + title: mindAddressOf(currentSession.issuer), + append: (event) => itx.append(event).catch(console.error), + announced: new Set(), + }; + // A pager can exist while registering its stub failed. Verify the usable lend, not + // only the outer API socket. This call reads membership and never dispatches input. + await checkLend(); + if (!setupCurrent()) return null; + return { browser, whoami, browserName, name, provided }; + })(), + ); + if (!setup || mine !== generation) return; + const { whoami, browserName, name, provided } = setup; + let lastHealthyAt = Date.now(); + let healthySince = lastHealthyAt; + publish({ + phase: "connected", + name, + browserName, + person: whoami.principal?.email || whoami.principal?.actor, + mindName: whoami.mindSlug || lend.title, + address: lend.title, + }); + await persist(); + if (mine !== generation) return; + await watch(); + void reconcileNow(); + void Promise.resolve(provided.lendEnded()).then( + async (reason) => { + if (mine !== generation) return; + // Core reports a lost pager as a resolved offline reason. A replaced/returned lend + // stays manual, so two profiles never take the same name back from each other. + const offline = typeof reason === "string" && /^went offline\b/i.test(reason); + const failure = Object.assign(new Error(String(reason)), { retryable: offline }); + if (offline || reconnectKind(failure)) { + await connectionFailed(currentSession, mine, failure, true); + return; + } + disconnect(); + void releaseTabs(); + publish({ + phase: "displaced", + retryAt: null, + members: [], + error: `The mind ended this lend: ${reason}. Choose Lend again to take it back.`, + }); + await persist(); + await watch(); + }, + (error) => void connectionFailed(currentSession, mine, error, true), + ); + // A read-only call through the lend detects a broken internal pager and supplies the + // WebSocket traffic Chrome needs inside its 30-second worker idle window. + const beat = async () => { + if (mine !== generation) return; + try { + await connectionAnswer(mine, LENDING_TIMING.heartbeatDeadlineMs, checkLend()); + if (mine !== generation) return; + const answeredAt = Date.now(); + // Continuous health needs successful replies, not a timer that can elapse asleep. + if ( + answeredAt - lastHealthyAt > + LENDING_TIMING.heartbeatIntervalMs + LENDING_TIMING.heartbeatDeadlineMs + ) + healthySince = answeredAt; + lastHealthyAt = answeredAt; + if ( + recoveryUntil !== null && + answeredAt - healthySince >= LENDING_TIMING.healthyResetMs + ) { + retries = 0; + recoveryUntil = null; + publish({}); + void persist(); + } + beatTimer = setTimeout(beat, LENDING_TIMING.heartbeatIntervalMs); + } catch (error) { + await connectionFailed(currentSession, mine, error, true); + } + }; + beatTimer = setTimeout(beat, LENDING_TIMING.heartbeatIntervalMs); + } catch (error) { + await connectionFailed(currentSession, mine, error, canReconnect); + } + } + + async function stopSharing() { + disconnect(); + retries = 0; + recoveryUntil = null; + publish({ sharing: false, phase: "off", members: [], retryAt: null, error: "" }); + const released = releaseTabs(); + await persist(); + await watch(); + await writeBearerRule(() => + chrome.declarativeNetRequest.updateSessionRules({ removeRuleIds: [BEARER_RULE] }), + ); + await released; + } + + const ready = (async () => { + await disconnectOffscreen(); + const stored = await chrome.storage.session.get(["lending", "debuggeeIds"]); + for (const tabId of stored.debuggeeIds || []) { + owned.add(tabId); + debuggees.set(tabId, { attached: true, attaching: null }); + } + await releaseTabs(); + session = await oauth.session(); + if (session && !isMindSession(session)) { + await oauth.signOut(); + session = null; + } + const previous = stored.lending; + const local = await chrome.storage.local.get(["sharingRequested", "mind"]); + publish({ phase: "off", mind: local.mind || "" }); + if (!session) { + await watch(); + return; + } + readProfile(); + if (previous?.sharing && previous.issuer === session.issuer) { + retries = + Number.isSafeInteger(previous.retries) && previous.retries >= 0 ? previous.retries : 0; + recoveryUntil = Number.isFinite(previous.recoveryUntil) + ? Math.min(previous.recoveryUntil, Date.now() + LENDING_TIMING.recoveryWindowMs) + : null; + publish({ sharing: true }); + if (["failed", "displaced", "refreshing", "exhausted"].includes(previous.phase)) { + publish({ + phase: previous.phase === "refreshing" ? "failed" : previous.phase, + error: + previous.phase === "exhausted" + ? `Automatic lending recovery ended after ${LENDING_TIMING.recoveryWindowMs / 60_000} minutes. Choose Lend again.` + : "Sharing stopped before the worker restarted. Choose Lend again, or sign in again if a token refresh was interrupted.", + }); + await persist(); + await watch(); + } else if (previous.phase === "waiting" && Number.isFinite(previous.retryAt)) { + recoveryUntil ??= Date.now() + LENDING_TIMING.recoveryWindowMs; + publish({ + phase: "waiting", + retryAt: Math.min(previous.retryAt, recoveryUntil), + error: "Restoring the bounded connection retry.", + }); + await persist(); + if (Date.now() >= recoveryUntil) await connect(session, true); + else { + await watch(); + retryTimer = setTimeout( + () => void connect(session, true), + Math.max(0, state.retryAt - Date.now()), + ); + } + } else + await connectionFailed( + session, + generation, + new Error("The worker connection closed."), + true, + ); + } else if (shareOnBrowserStart && local.sharingRequested) { + publish({ sharing: true }); + await connect(session); + } else { + await persist(); + await watch(); + } + })(); + + async function command(message) { + await ready; + if (!message || typeof message.action !== "string") throw new Error("Invalid panel command."); + switch (message.action) { + case "state": { + // Re-read only local state. Opening another panel never starts another socket. + const mine = generation; + const storedSession = await oauth.session(); + if (!state.sharing && mine === generation) + session = isMindSession(storedSession) ? storedSession : null; + return snapshot(); + } + case "login": { + if (state.sharing || tokenRequest || signInRequest) + throw new Error("Turn sharing off and wait for the current sign-in or token request."); + const mine = generation; + allowSessionWrites = true; + const issuer = mindIssuerOf(message.mind); + signInRequest = (async () => { + await chrome.storage.local.set({ mind: message.mind.trim() }); + if (mine !== generation) throw new Error("This sign-in ended."); + return oauth.signIn(await answeringIssuer(issuer)); + })(); + try { + const signedIn = await signInRequest; + if (mine !== generation) throw new Error("This sign-in ended."); + session = signedIn; + publish({ mind: message.mind.trim() }); + readProfile(); + return snapshot(); + } finally { + signInRequest = null; + } + } + case "logout": { + allowSessionWrites = false; + const stopped = stopSharing(); + session = null; + publish({}); + await oauth.signOut(); + await stopped; + return snapshot(); + } + case "share": { + const mine = generation; + const storedSession = await oauth.session(); + if (mine !== generation) throw new Error("Sharing changed before this request completed."); + session = storedSession; + if (!isMindSession(session)) throw new Error("Sign in to a mind first."); + if ( + state.phase === "connected" || + state.phase === "connecting" || + state.phase === "refreshing" + ) + return snapshot(); + allowSessionWrites = true; + publish({ sharing: true }); + await connect(session); + return snapshot(); + } + case "stop": + await stopSharing(); + return snapshot(); + case "rename": { + const mine = generation; + const chosen = typeof message.name === "string" ? message.name.trim() : ""; + if (!isLendSegment(chosen)) + throw new Error( + "Use letters and digits, starting with a letter. Constructor and prototype names are reserved.", + ); + await chrome.storage.local.set({ browserName: chosen }); + if (mine === generation && state.sharing) await connect(session); + return snapshot(); + } + case "prove": { + if (!lend || !live) throw new Error("This Chrome is not lent."); + const mine = generation; + const itx = live; + const path = lend.name.split("."); + const opened = await within( + 20_000, + itx.invoke([ + ...path, + [ + "openPage", + { + url: `https://example.com/?iterate-chrome-proof=${encodeURIComponent(state.mindName)}`, + }, + ], + ]), + ); + if (mine !== generation) + throw new Error("The connection ended. The test was not replayed."); + const evaluated = await within( + 20_000, + itx.invoke([ + ...path, + [ + "cdp", + opened.tabId, + "Runtime.evaluate", + { expression: "document.title", returnByValue: true }, + ], + ]), + ); + if (mine !== generation) throw new Error("The connection ended."); + publish({ + notice: `The mind opened tab ${opened.tabId} and read its title: ${JSON.stringify(evaluated.result.value)}.`, + }); + return snapshot(); + } + case "add": { + if (!lend) throw new Error("This Chrome is not lent."); + const mine = generation; + const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true }); + if (mine !== generation) throw new Error("Sharing ended."); + if (tab?.id && !(await isMember(tab.id))) await addToGroup(tab.id, tab.windowId); + showTabs(); + return snapshot(); + } + case "remove": { + if (!lend || !Number.isInteger(message.tabId) || !(await isMember(message.tabId))) + throw new Error("This tab is not lent."); + await whileNotDragging(() => chrome.tabs.ungroup(message.tabId)); + await reconcileNow(); + return snapshot(); + } + default: + throw new Error("Unsupported panel command."); + } + } + return { + ready, + command, + snapshot, + subscribe(listener) { + listeners.add(listener); + return () => listeners.delete(listener); + }, + async wake() { + await ready; + if (state.sharing && state.phase === "waiting" && Date.now() >= state.retryAt) + await connect(session, true); + }, + }; +}
A public/manifest.json
@@ -0,0 +1,26 @@ +{ + "manifest_version": 3, + "name": "Iterate", + "description": "Lend this Chrome to an iterate mind: its agents drive the tabs in the mind's tab group.", + "version": "0.8.3", + "minimum_chrome_version": "123", + "key": "<CHROME_EXTENSION_KEY: scripts/build.ts sets it, or leaves the key out>", + "icons": { "16": "icon-16.png", "32": "icon-32.png", "48": "icon-48.png", "128": "icon-128.png" }, + "action": { + "default_title": "Open Iterate", + "default_icon": { "16": "icon-16.png", "32": "icon-32.png" } + }, + "background": { "service_worker": "background.js", "type": "module" }, + "side_panel": { "default_path": "index.html" }, + "permissions": [ + "alarms", + "offscreen", + "debugger", + "declarativeNetRequestWithHostAccess", + "identity", + "sidePanel", + "storage", + "tabGroups" + ], + "optional_host_permissions": ["https://*/*", "wss://*/*"] +}
A public/offscreen-client.js
@@ -0,0 +1,110 @@ +import { RpcSession } from "./capnweb.js"; +import { messageTransport } from "./rpc-transport.js"; + +let active; +let jobs = Promise.resolve(); +const serialize = (job) => (jobs = jobs.then(job, job)); +const documentBase = () => chrome.runtime.getURL("offscreen.html"); +async function closeDocument(url) { + const contexts = await chrome.runtime.getContexts({ contextTypes: ["OFFSCREEN_DOCUMENT"] }); + if ( + contexts.some((context) => + url ? context.documentUrl === url : context.documentUrl?.split("?")[0] === documentBase(), + ) + ) + await chrome.offscreen.closeDocument(); +} +export function disconnectOffscreen() { + const previous = active; + active = null; + previous?.reject(new Error("The extension transport ended.")); + previous?.wire?.close(new Error("The extension transport ended.")); + previous?.remote?.[Symbol.dispose](); + previous?.port?.disconnect(); + return serialize(() => closeDocument(previous?.url)); +} +export async function openOffscreenApi(url, current, onFailure) { + if (active) throw new Error("An extension transport is already active."); + let resolve; + let reject; + const ready = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + // A cancelled creation can settle before createDocument() returns. + void ready.catch(() => {}); + const entry = { + url: `${documentBase()}?transport=${crypto.randomUUID()}`, + current, + onFailure, + resolve, + reject, + failed: false, + }; + active = entry; + return serialize(async () => { + if (active !== entry || !current()) return null; + await closeDocument(); + if (active !== entry || !current()) return null; + await chrome.offscreen.createDocument({ + url: entry.url, + reasons: ["WORKERS"], + justification: + "A dedicated worker in an extension document holds the authenticated lending socket while the service worker owns its state.", + }); + if (active !== entry || !current()) { + await closeDocument(entry.url); + return null; + } + const remote = await ready; + if (active !== entry || !current()) return null; + return remote.open(url); + }); +} +export function acceptOffscreenPort(port) { + const entry = active; + if ( + !entry || + !entry.current() || + entry.port || + port.sender?.id !== chrome.runtime.id || + port.sender?.url !== entry.url + ) { + port.disconnect(); + return; + } + entry.port = port; + const fail = (policyRefused = false, tokenExpired = false) => { + if (active !== entry || entry.failed) return; + entry.failed = true; + const error = + policyRefused === true + ? Object.assign(new Error("The mind ended this browser's authorization. Sign in again."), { + code: "UNAUTHORIZED", + }) + : tokenExpired === true + ? Object.assign(new Error("The API token expired. Refreshing the connection."), { + code: "TOKEN_EXPIRED", + }) + : new Error("The extension WebSocket transport disconnected."); + entry.reject(error); + entry.wire.close(error); + entry.onFailure(error); + }; + entry.wire = messageTransport( + (message) => port.postMessage(message), + () => { + port.disconnect(); + fail(); + }, + ); + port.onMessage.addListener((message) => { + if (message?.type === "socket-ended") + fail(message.policyRefused === true, message.tokenExpired === true); + else entry.wire.accept(message); + }); + port.onDisconnect.addListener(() => fail()); + const session = new RpcSession(entry.wire); + entry.remote = session.getRemoteMain(); + entry.resolve(entry.remote); +}
A public/offscreen.html
@@ -0,0 +1,4 @@ +<!doctype html> +<meta charset="utf-8" /> +<title>Iterate lending transport</title> +<script type="module" src="offscreen.js"></script>
A public/offscreen.js
@@ -0,0 +1,26 @@ +// Only this document uses runtime; its dedicated worker owns the socket and capnweb session. +const worker = new Worker("socket-worker.js", { type: "module" }); +let port; +let ended = false; +function stop() { + if (ended) return; + ended = true; + worker.terminate(); + port?.disconnect(); +} +worker.onmessage = ({ data }) => { + if (ended) return; + if (data?.type === "ready" && !port) { + port = chrome.runtime.connect({ name: "offscreen-transport" }); + port.onMessage.addListener((message) => worker.postMessage(message)); + port.onDisconnect.addListener(stop); + } else { + try { + port?.postMessage(data); + } catch { + stop(); + } + } +}; +worker.onerror = stop; +window.addEventListener("pagehide", stop);
A public/panel.js
@@ -0,0 +1,175 @@ +import { mindIssuerOf } from "./address.js"; +const app = document.getElementById("app"); +const escape = (value) => + String(value ?? "") + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll('"', """); +// THE MIND, AS EVERY PLACE OF THE EXTENSION SHOWS IT: its logo on the left, then its name over its +// address, or the address alone for a mind with no name. The name and the logo come from the mind's +// profile (profile.js): the owner's own words, so the name is escaped text, the logo is an image +// and no more, and the address is always there. A mind with no logo, and a logo that does not +// load, show iterate's mark. +const OWN_MARK = "icon-32.png"; +const brokenLogos = new Set(); +function mindMark(state) { + const { name, icon } = state.profile || {}; + const logo = icon && !brokenLogos.has(icon) ? icon : OWN_MARK; + return `<div class="mind"><img class="mind-logo" src="${escape(logo)}" alt="" referrerpolicy="no-referrer" /><div class="grow">${name ? `<div class="mind-name truncate">${escape(name)}</div>` : ""}<div class="mind-address truncate">${escape(state.address)}</div></div></div>`; +} +// An image's error does not bubble, so it is caught on its way down. render() writes the page +// again at each state, which a listener on the image itself would not outlive. +app.addEventListener( + "error", + ({ target }) => { + const src = target.getAttribute?.("src"); + if (!target.classList?.contains("mind-logo") || src === OWN_MARK) return; + brokenLogos.add(src); + target.src = OWN_MARK; + }, + true, +); +let port; +let serial = 0; +let reconnectTimer; +let reconnects = 0; +const pending = new Map(); +let latest; +function connect() { + port = chrome.runtime.connect({ name: "panel" }); + port.onMessage.addListener((message) => { + if (message.state && typeof message.state.phase === "string") { + reconnects = 0; + latest = message.state; + render(latest); + } + if (message.id) { + const call = pending.get(message.id); + pending.delete(message.id); + if (message.error) call?.reject(new Error(message.error)); + else call?.resolve(message.state); + } + }); + port.onDisconnect.addListener(() => { + for (const call of pending.values()) + call.reject(new Error("The worker connection ended. The command was not replayed.")); + pending.clear(); + app.innerHTML = + '<section class="card"><h2>Checking sharing status…</h2><p>The worker connection ended. Waiting for its current state.</p></section>'; + if (reconnects < 5) { + reconnects += 1; + reconnectTimer = setTimeout(connect, Math.min(30_000, 1_000 * 2 ** (reconnects - 1))); + } else { + app.innerHTML = + '<section class="card"><h2>Sharing status unavailable</h2><p>Close and reopen this panel to check the worker again.</p></section>'; + } + }); + void request({ action: "state" }).catch(showError); +} +function request(command) { + return new Promise((resolve, reject) => { + const id = ++serial; + pending.set(id, { resolve, reject }); + try { + port.postMessage({ id, ...command }); + } catch (error) { + pending.delete(id); + reject(error); + } + }); +} +function showError(error) { + const alert = document.createElement("p"); + alert.setAttribute("role", "alert"); + alert.className = "error"; + alert.textContent = error.message; + app.append(alert); +} +function action(id, command) { + document + .getElementById(id) + ?.addEventListener("click", () => void request(command).catch(showError)); +} +function render(state) { + const focus = document.activeElement; + // Tab events may update the state while the person types a browser name. + if (focus?.id === "browser-name" && latest?.phase === "connected") return; + app.innerHTML = `<header class="header">${state.signedIn ? mindMark(state) : '<div class="brand"><img src="icon-32.png" alt="" />Iterate</div>'}<div class="row"><span class="badge">v${escape(state.version)}</span>${state.signedIn ? '<button id="logout" class="btn btn-ghost btn-sm">Sign out</button>' : ""}</div></header>`; + if (!state.signedIn) { + app.innerHTML += `<section class="card"><h2>Sign in to a mind</h2><p class="muted">Then turn sharing on. The mind can drive only tabs in its tab group.</p><label class="field">Mind<input id="mind" class="input" value="${escape(state.mind)}" placeholder="example.com" /></label><button id="login" class="btn btn-primary">Sign in with Iterate</button></section>`; + document.getElementById("login").onclick = async () => { + try { + const mind = document.getElementById("mind").value; + const issuer = mindIssuerOf(mind); + const granted = await chrome.permissions.request({ + origins: [`${issuer}/*`, `${issuer.replace(/^https/, "wss")}/*`], + }); + if (!granted) throw new Error("Allow access to the mind's host to sign in."); + await request({ action: "login", mind }); + } catch (error) { + showError(error); + } + }; + return; + } + const connected = state.phase === "connected"; + const title = connected + ? "Connected · sharing on" + : state.phase === "off" + ? "Sharing off" + : state.phase === "waiting" + ? `Reconnecting, try ${state.retries}` + : state.phase === "displaced" + ? "No longer lent" + : state.phase === "exhausted" + ? "Not lent · Lend again" + : state.phase === "failed" + ? "Not connected" + : state.retries + ? `Reconnecting, try ${state.retries}` + : "Connecting…"; + app.innerHTML += `<section id="connection" class="card"><div class="row"><span class="dot ${connected ? "ok" : ["failed", "displaced", "exhausted"].includes(state.phase) ? "bad" : state.sharing ? "wait" : ""}"></span><h2 class="grow">${title}</h2></div><p class="muted">${connected ? "Sharing stays on when you close this panel." : "This Chrome is not lent while disconnected."} After a Chrome restart, open this panel and turn sharing on again.</p>${state.error ? `<p class="error">${escape(state.error)}</p>` : ""}${state.retryAt ? `<p class="muted">Try ${state.retries}, next check ${escape(new Date(state.retryAt).toLocaleTimeString())}.</p>` : ""}<div class="actions">${state.sharing ? '<button id="stop" class="btn btn-outline">Turn sharing off</button>' : '<button id="share" class="btn btn-primary">Share this browser</button>'}${["failed", "displaced", "exhausted"].includes(state.phase) ? `<button id="share" class="btn btn-primary">${["displaced", "exhausted"].includes(state.phase) ? "Lend again" : "Retry"}</button>` : ""}</div></section>`; + const controls = () => { + action("logout", { action: "logout" }); + action("share", { action: "share" }); + action("stop", { action: "stop" }); + }; + if (!connected) { + controls(); + return; + } + const members = state.members || []; + app.innerHTML += `<section class="card"><dl class="facts"><dt>Signed in as</dt><dd>${escape(state.person)}</dd><dt>Lent as</dt><dd><code>${escape(state.name)}</code></dd></dl><details><summary>Rename this browser</summary><form id="rename-form" class="row rename"><input id="browser-name" class="input grow" value="${escape(state.browserName)}" aria-label="Browser name" /><button class="btn btn-outline">Save</button></form></details></section><section class="card"><h2>Tab group <code>${escape(state.address)}</code></h2><p class="muted">Drag a tab into this group to lend it. Drag it out or click Remove to take it back.</p><ul id="tabs" class="tabs">${members.length ? members.map((tab) => `<li><div class="grow"><div class="title truncate">${escape(tab.title || tab.url)}</div><div class="muted mono truncate">${escape(tab.url)}</div></div>${tab.attached ? `<span class="badge">${escape(tab.activity || "in use")}</span>` : ""}<button class="btn btn-ghost btn-sm" data-remove="${tab.tabId}">Remove</button></li>`).join("") : '<li class="empty">No tabs in the group yet.</li>'}</ul><div class="actions"><button id="add" class="btn btn-primary">Add this tab</button><button id="prove" class="btn btn-outline">Test: open a page</button></div><p id="proof-result" class="muted">${escape(state.notice)}</p></section><section class="card"><h2>Tell an agent</h2><button id="copy" class="btn btn-outline">Copy instructions for an agent</button><details><summary>Show the instructions</summary><pre id="instructions"></pre></details></section>`; + controls(); + document.getElementById("instructions").textContent = state.instructions; + document.getElementById("copy").onclick = () => + void copyText(state.instructions).catch(showError); + document.getElementById("rename-form").onsubmit = (event) => { + event.preventDefault(); + void request({ action: "rename", name: document.getElementById("browser-name").value }).catch( + showError, + ); + }; + action("add", { action: "add" }); + action("prove", { action: "prove" }); + document.getElementById("tabs").onclick = (event) => { + const button = event.target.closest("[data-remove]"); + if (button) + void request({ action: "remove", tabId: Number(button.dataset.remove) }).catch(showError); + }; +} +window.addEventListener("pagehide", () => clearTimeout(reconnectTimer)); +connect(); + +async function copyText(text) { + try { + await navigator.clipboard.writeText(text); + } catch { + const area = document.createElement("textarea"); + area.value = text; + document.body.append(area); + area.select(); + document.execCommand("copy"); + area.remove(); + } +}
A public/profile.js
@@ -0,0 +1,84 @@ +// profile.js — WHAT A MIND SAYS OF ITSELF: its name and its logo, for the panel's header and the +// label on a tab. The mind's website answers them to anyone at `/.well-known/iterate-profile` +// (`{ name, description, icon }`, with `access-control-allow-origin: *`), so the read needs no host +// permission and carries no credential. +// +// THE PROFILE IS THE OWNER'S OWN WORDS, UNSIGNED: it proves nothing about who the mind is. So the +// address is always shown beside it, the name is text of bounded length, and the logo is an +// `https:` address on the mind's own hosts that is only ever shown as an image (`<img src>`). +// Anything else in the answer is dropped. + +/** Where the mind's website answers its profile. */ +const PROFILE_PATH = "/.well-known/iterate-profile"; +/** A profile's answer is small: a larger one is not read as a profile. */ +const ANSWER_MAX_LENGTH = 16 * 1024; +/** Control characters, and the characters that change the direction of the text after them. */ +const UNSAFE_IN_A_NAME = /[\p{Cc}\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu; + +/** The mind's address, as the panel and the tab group show it: the issuer's hostname without its + * `iterate.` label. */ +export const mindAddressOf = (issuer) => new URL(issuer).hostname.replace(/^iterate\./, ""); + +/** The origin of the mind's website: the issuer's without its `iterate.` label. */ +function websiteOf(issuer) { + const url = new URL(issuer); + url.hostname = mindAddressOf(issuer); + return url.origin; +} + +/** `{ name, icon }` from a profile's answer, for the mind whose issuer is `issuer`. `name` is "" + * for a mind that gave itself none (the profile then answers the hostname, which the address + * already says); `icon` is null for a mind with no logo that may be shown. */ +export function mindProfileOf(answer, issuer) { + const address = mindAddressOf(issuer); + const said = + typeof answer?.name === "string" + ? answer.name + .replace(UNSAFE_IN_A_NAME, " ") + .replace(/\s+/g, " ") + .trim() + // the profile's own bound for a name (core/configs/default/profile.ts) + .slice(0, 80) + .trim() + : ""; + const name = [address, `iterate.${address}`].includes(said.toLowerCase()) ? "" : said; + return { name, icon: iconOf(answer?.icon, issuer) }; +} + +/** The logo's address, when it is an `https:` address on the mind's website or a host under it. */ +function iconOf(icon, issuer) { + if (typeof icon !== "string" || icon.length > 2048) return null; + let url; + try { + url = new URL(icon); + } catch { + return null; + } + const website = new URL(websiteOf(issuer)); + if (url.protocol !== "https:" || url.username || url.password || url.port !== website.port) + return null; + if (url.hostname !== website.hostname && !url.hostname.endsWith(`.${website.hostname}`)) + return null; + return url.href; +} + +/** The profile of the mind whose issuer is `issuer`, or null when its website answered none + * (no such route, no network, an answer that is not a profile). */ +export async function readMindProfile(issuer) { + try { + const answer = await fetch(`${websiteOf(issuer)}${PROFILE_PATH}`, { + credentials: "omit", + redirect: "error", + referrerPolicy: "no-referrer", + signal: AbortSignal.timeout(5_000), + }); + if (!answer.ok) return null; + const text = await answer.text(); + if (text.length > ANSWER_MAX_LENGTH) return null; + const json = JSON.parse(text); + if (!json || typeof json !== "object" || Array.isArray(json)) return null; + return mindProfileOf(json, issuer); + } catch { + return null; + } +}
A public/rpc-transport.js
@@ -0,0 +1,44 @@ +// The same capnweb wire crosses a runtime port and an offscreen dedicated-worker channel. +export function messageTransport(send, abort) { + const queue = []; + let waiting; + let ended; + const close = (error) => { + if (ended) return; + ended = error; + queue.length = 0; + waiting?.reject(error); + waiting = null; + }; + return { + send(message) { + if (ended) throw ended; + send({ type: "rpc", message }); + }, + receive() { + if (ended) return Promise.reject(ended); + if (queue.length) return Promise.resolve(queue.shift()); + return new Promise((resolve, reject) => { + waiting = { resolve, reject }; + }); + }, + accept(message) { + if (ended) return; + if (message?.type !== "rpc" || typeof message.message !== "string") { + const error = new Error("Invalid extension transport frame."); + close(error); + abort(error); + return; + } + if (waiting) { + waiting.resolve(message.message); + waiting = null; + } else queue.push(message.message); + }, + close, + abort(error) { + close(error); + abort(error); + }, + }; +}
A public/socket-worker.js
@@ -0,0 +1,60 @@ +import { RpcSession, RpcTarget, newWebSocketRpcSession } from "./capnweb.js"; +import { messageTransport } from "./rpc-transport.js"; + +let socket; +let api; +let ended = false; +let disposed = false; +let owner; +function dispose() { + if (disposed) return; + disposed = true; + api?.[Symbol.dispose](); + api = null; + socket?.close(); + owner?.[Symbol.dispose](); + close(); +} +function failed(event) { + if (ended) return; + ended = true; + // This API close reason marks the access token's normal lifetime, not a refused refresh. + const tokenExpired = + event?.code === 1008 && + event.reason === "the sign-in for this session ended: authenticate again"; + postMessage({ + type: "socket-ended", + tokenExpired, + policyRefused: event?.code === 1008 && !tokenExpired, + }); +} +class SocketController extends RpcTarget { + open(address) { + const url = new URL(address); + if (socket || url.protocol !== "wss:" || url.pathname !== "/api" || url.search || url.hash) + throw new Error("Invalid or duplicate lending socket."); + socket = new WebSocket(url); + socket.addEventListener("close", failed); + socket.addEventListener("error", failed); + api = newWebSocketRpcSession(socket); + // The root of a session at a mind's /api answers a session to `authenticate()`, and the + // session's `mind` is the mind (iterate/api `ControlPlaneApi`). With no token in the call, + // the credential is the bearer on this socket's own request (lend.js sets it). Nothing is + // awaited: capnweb sends the first calls with it, and a bearer that the mind refuses fails + // the first call with the code UNAUTHENTICATED. `dup()` makes a stub of the pipelined mind, + // and the session's promise is let go, so that the stub is the one hold on the mind. + // Returning a stub transfers it; the socket session's root stays owned here. + const session = api.authenticate(); + try { + return session.mind.dup(); + } finally { + session[Symbol.dispose](); + } + } +} +const transport = messageTransport((message) => postMessage(message), dispose); +const session = new RpcSession(transport, new SocketController()); +// Hold the bridge's root stub until its owner ends the runtime port. +owner = session.getRemoteMain(); +self.onmessage = ({ data }) => transport.accept(data); +postMessage({ type: "ready" });
A releases/index.json
@@ -0,0 +1,10 @@ +{ + "current": "0.8.3", + "releases": { + "0.8.3": { + "file": "iterate-chrome-extension-0.8.3.zip", + "sha256": "fb8513924e1f0828d25b9366fe8ff737c4222f1dd8ddf2dcd95c66f5ee58b398", + "bytes": 99588 + } + } +}
A releases/iterate-chrome-extension-0.8.3.zip
Not text, so no diff is shown.
A scripts/build.ts
@@ -0,0 +1,44 @@ +// dist/ is the unpacked extension (what Load unpacked takes, and what scripts/release.ts zips): +// public/, capnweb's browser bundle from node_modules (the version that package.json pins, the one +// the platform speaks) and oauth.js, the OAuth client. README.md says why the extension carries +// its code itself. +import { cpSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { build } from "esbuild"; + +const dist = new URL("../dist/", import.meta.url); +rmSync(dist, { recursive: true, force: true }); +cpSync(new URL("../public/", import.meta.url), dist, { recursive: true }); +cpSync(new URL(import.meta.resolve("capnweb")), new URL("capnweb.js", dist)); +cpSync(new URL("../oauth.js", import.meta.url), new URL("oauth.js", dist)); + +// public/manifest.json's `key` is a placeholder, which Chrome would refuse. A real key fixes the +// extension's id, and so its sign-in redirect (`https://<id>.chromiumapp.org/`), on every install: +// a release has iterate's (scripts/release.ts sets CHROME_EXTENSION_KEY from extension-key.txt). +// Without one the key is removed and Chrome derives the id from the unpacked folder's path; +// sign-in still works, as the worker registers its redirect with the issuer. +const manifestPath = new URL("manifest.json", dist); +const manifest = JSON.parse(readFileSync(manifestPath, "utf8")); +manifest.key = process.env.CHROME_EXTENSION_KEY || undefined; +writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + "\n"); + +const runtime = await build({ + entryPoints: [new URL("../src/locator-runtime.ts", import.meta.url).pathname], + bundle: true, + write: false, + format: "iife", + globalName: "globalThis.__iterateControls", + minify: true, + legalComments: "inline", +}); +writeFileSync( + new URL("locator-source.js", dist), + `export const locatorSource = ${JSON.stringify(runtime.outputFiles[0].text)};\n`, +); +await build({ + entryPoints: [new URL("../src/page.ts", import.meta.url).pathname], + bundle: true, + format: "esm", + outfile: new URL("page.js", dist).pathname, + external: ["./capnweb.js"], + alias: { capnweb: "./capnweb.js" }, +});
A scripts/release.ts
@@ -0,0 +1,64 @@ +// A release is one file of this repo: releases/iterate-chrome-extension-<version>.zip, with its row +// in releases/index.json. This script builds dist/ with iterate's key and writes both. The mind +// serves them from this repo's main (README.md, "Release"): the push is the publication. +// +// node scripts/release.ts build, write the ZIP and its row, make it the current one +// node scripts/release.ts --verify build, and compare with the ZIP that the repo holds +// +// A released version is never changed: when the build's files differ from the kept ZIP of that +// version, the script stops. Raise `version` in public/manifest.json and package.json first. +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; +import { unzipSync, zipSync } from "fflate"; + +const root = new URL("../", import.meta.url); +const verify = process.argv.includes("--verify"); + +// The key is the public half: every released manifest.json holds it. It fixes the extension's id. +process.env.CHROME_EXTENSION_KEY = readFileSync(new URL("extension-key.txt", root), "utf8").trim(); +await import("./build.ts"); + +const dist = new URL("dist/", root); +const { version } = JSON.parse(readFileSync(new URL("manifest.json", dist), "utf8")) as { version: string }; +if (!/^\d+(\.\d+){0,3}$/.test(version)) throw new Error(`manifest.json: "${version}" is no version`); +const declared = (JSON.parse(readFileSync(new URL("package.json", root), "utf8")) as { version: string }).version; +if (declared !== version) throw new Error(`package.json says ${declared}, public/manifest.json says ${version}`); + +// Top-level files alone, A to Z: dist/ is flat (README.md). One fixed time for every entry, so the +// same commit gives the same bytes. +const built: Record<string, Uint8Array> = {}; +for (const name of readdirSync(dist).sort()) built[name] = readFileSync(new URL(name, dist)); +const sha256 = (data: Uint8Array) => createHash("sha256").update(data).digest("hex"); + +const file = `iterate-chrome-extension-${version}.zip`; +const zipPath = new URL(`releases/${file}`, root); +const indexPath = new URL("releases/index.json", root); +type Index = { current: string; releases: Record<string, { file: string; sha256: string; bytes: number }> }; +const index: Index = existsSync(indexPath) ? JSON.parse(readFileSync(indexPath, "utf8")) : { current: "", releases: {} }; + +if (existsSync(zipPath)) { + const kept = unzipSync(readFileSync(zipPath)); + const names = [...new Set([...Object.keys(kept), ...Object.keys(built)])].sort(); + const differ = names.filter((name) => !kept[name] || !built[name] || sha256(kept[name]) !== sha256(built[name])); + if (differ.length) { + console.error(`${file} is released, and this build differs in: ${differ.join(", ")}`); + console.error("A released version is never changed. Raise the version, or build the release's own commit."); + process.exit(1); + } + console.log(`${file}: this build's ${names.length} files are the released ones.`); +} else if (verify) { + console.error(`${file} is not in releases/: nothing to compare with.`); + process.exit(1); +} else { + mkdirSync(new URL("releases/", root), { recursive: true }); + writeFileSync(zipPath, zipSync(built, { mtime: new Date(1980, 0, 1) })); + console.log(`wrote releases/${file}`); +} + +if (!verify) { + const data = readFileSync(zipPath); + index.releases[version] = { file, sha256: sha256(data), bytes: data.byteLength }; + index.current = version; + writeFileSync(indexPath, JSON.stringify(index, null, 2) + "\n"); + console.log(`releases/index.json: current is ${version}, sha256 ${index.releases[version].sha256}`); +}
A src/extension.test.ts
@@ -0,0 +1,76 @@ +// The packaged facade through chrome.debugger in a fresh headless extension profile. +import { cp, mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { chromium } from "@playwright/test"; +import { expect, test } from "vitest"; + +test("the packaged extension renders valid calls, sends trusted input and obeys revocation", async () => { + const directory = await mkdtemp(join(tmpdir(), "iterate-extension-fixture-")); + const extension = join(directory, "extension"); + await cp(new URL("../dist/", import.meta.url), extension, { recursive: true }); + const server = createServer((_, response) => { + response.setHeader("Content-Type", "text/html"); + response.end( + '<label>Message<input></label><button onclick="document.body.dataset.trusted=event.isTrusted">Send</button>', + ); + }); + await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Fixture server has no TCP port"); + const context = await chromium.launchPersistentContext(join(directory, "profile"), { + channel: "chromium", + headless: true, + args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`], + }); + try { + const worker = context.serviceWorkers()[0] || (await context.waitForEvent("serviceworker")); + const controller = await context.newPage(); + await controller.goto(`chrome-extension://${new URL(worker.url()).host}/index.html`); + const instructions = await controller.evaluate<string>( + `import('./instructions.js').then(({agentInstructions}) => agentInstructions('fixture.test','itx.chrome.fixture.browser',[]))`, + ); + expect(instructions).toContain( + '`await itx.cd("/").chrome.fixture.browser.page(tabId).getByRole("button", { name: "Save", exact: true }).click()`', + ); + expect(instructions).toContain('- `await itx.cd("/").chrome.fixture.browser.page(tabId)`:'); + expect(instructions).not.toContain("``"); + // This fixture grants its own local tab only. It does not sign in or lend a Chrome to a mind. + const tabId = await controller.evaluate<number>(`(async () => { + const { ChromePage } = await import('./page.js'); + const { locatorSource } = await import('./locator-source.js'); + const tab = await chrome.tabs.create({url: 'http://127.0.0.1:${address.port}', active: false}); + await new Promise(resolve => { + const listener = (id, change) => { if(id === tab.id && change.status === 'complete') { chrome.tabs.onUpdated.removeListener(listener); resolve(); } }; + chrome.tabs.onUpdated.addListener(listener); + chrome.tabs.get(tab.id).then(current => listener(tab.id, {status: current.status})); + }); + await chrome.debugger.attach({tabId:tab.id}, '1.3'); + globalThis.fixtureGranted = true; + globalThis.fixturePage = new ChromePage((method, params) => { + if (!globalThis.fixtureGranted) throw new Error('fixture tab revoked'); + return chrome.debugger.sendCommand({tabId:tab.id},method,params); + }, locatorSource); + return tab.id; + })()`); + await controller.evaluate(`fixturePage.getByLabel('Message').fill('from extension')`); + await controller.evaluate(`fixturePage.getByRole('button', {name:'Send'}).click()`); + const result = await controller.evaluate<{ + result: { value: { value: string; trusted: string } }; + }>( + `chrome.debugger.sendCommand({tabId:${tabId}},'Runtime.evaluate',{expression:'({value:document.querySelector("input").value,trusted:document.body.dataset.trusted})',returnByValue:true})`, + ); + expect(result).toMatchObject({ + result: { value: { value: "from extension", trusted: "true" } }, + }); + await controller.evaluate("globalThis.fixtureGranted = false"); + await expect( + controller.evaluate(`fixturePage.getByLabel('Message').fill('revoked')`), + ).rejects.toThrow(/fixture tab revoked/); + } finally { + await context.close(); + await new Promise<void>((resolve) => server.close(() => resolve())); + await rm(directory, { recursive: true, force: true }); + } +});
A src/lending.test.ts
@@ -0,0 +1,563 @@ +// Real offscreen sockets and Chrome grants, using only an isolated profile and local TLS API. +import { execFileSync } from "node:child_process"; +import { cpSync, readFileSync, writeFileSync } from "node:fs"; +import { createServer as createTlsServer } from "node:https"; +import { mkdtemp, rm } from "node:fs/promises"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { chromium } from "@playwright/test"; +import { RpcSession, RpcTarget, type RpcStub } from "capnweb"; +import { expect, test } from "vitest"; +import { WebSocketServer } from "ws"; +import type { ChromePage } from "./page.ts"; + +test("signed-in lends recover a dropped connection and enforce group changes, sign-out and mind switching", async () => { + const directory = await mkdtemp(join(tmpdir(), "iterate-lending-fixture-")); + const extension = join(directory, "extension"); + cpSync(new URL("../dist/", import.meta.url), extension, { recursive: true }); + const manifest = JSON.parse(readFileSync(join(extension, "manifest.json"), "utf8")); + expect(manifest.host_permissions).toBeUndefined(); + // The fixture starts after sign-in: grant only its two local hosts, without a headless prompt. + manifest.host_permissions = [ + "https://iterate.first.test/*", + "wss://iterate.first.test/*", + "https://iterate.second.test/*", + "wss://iterate.second.test/*", + ]; + writeFileSync(join(extension, "manifest.json"), JSON.stringify(manifest)); + const server = createServer((_, response) => { + response.setHeader("Content-Type", "text/html"); + response.end( + '<button id="top" style="position:fixed;top:8px;left:50%;transform:translateX(-80px);width:60px;height:28px" onclick="document.body.dataset.top=event.isTrusted">Top action</button><main style="padding:100px"><label>Message<input></label><button onclick="document.body.dataset.trusted=event.isTrusted">Send</button></main>', + ); + }); + await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Fixture server has no TCP port"); + execFileSync( + "openssl", + [ + "req", + "-x509", + "-newkey", + "ec", + "-pkeyopt", + "ec_paramgen_curve:P-256", + "-nodes", + "-keyout", + join(directory, "key.pem"), + "-out", + join(directory, "cert.pem"), + "-subj", + "/CN=iterate.first.test", + "-days", + "1", + ], + { stdio: "ignore" }, + ); + const authorization = "Bearer fixture-only-grant"; + let authorizedChecks = 0; + let refusedChecks = 0; + const tls = createTlsServer( + { + key: readFileSync(join(directory, "key.pem")), + cert: readFileSync(join(directory, "cert.pem")), + }, + // The mind's API is a WebSocket alone. Its website (the address without `iterate.`) answers + // its profile: the first mind has a name and a logo, the second has no name (the profile's + // default is the hostname) and a logo that does not load. + (request, response) => { + const host = (request.headers.host || "").replace(/:\d+$/, ""); + const website = `https://${request.headers.host}`; + if (request.url === "/.well-known/iterate-profile" && !host.startsWith("iterate.")) { + response.writeHead(200, { + "content-type": "application/json", + "access-control-allow-origin": "*", + }); + response.end( + JSON.stringify( + host === "first.test" + ? { name: "First <b>mind</b>", description: "", icon: `${website}/favicon.svg` } + : { name: host, description: "", icon: `${website}/missing.svg` }, + ), + ); + } else if (request.url === "/favicon.svg" && host === "first.test") { + response.writeHead(200, { "content-type": "image/svg+xml" }); + response.end( + '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8"><rect width="8" height="8" fill="#0a0"/></svg>', + ); + } else { + response.writeHead(request.url === "/missing.svg" ? 404 : 426); + response.end(); + } + }, + ); + // Every socket opens: the bearer on its request is checked inside the session, at + // `authenticate()`, as the mind's API checks it. + const webSockets = new WebSocketServer({ server: tls }); + await new Promise<void>((resolve) => tls.listen(0, "127.0.0.1", resolve)); + const tlsAddress = tls.address(); + if (!tlsAddress || typeof tlsAddress === "string") throw new Error("TLS fixture has no port"); + const launch = () => + chromium.launchPersistentContext(join(directory, "profile"), { + channel: "chromium", + headless: true, + args: [ + `--disable-extensions-except=${extension}`, + `--load-extension=${extension}`, + "--ignore-certificate-errors", + "--host-resolver-rules=MAP iterate.first.test 127.0.0.1,MAP first.test 127.0.0.1,MAP iterate.second.test 127.0.0.1,MAP second.test 127.0.0.1", + ], + }); + let context = await launch(); + const lends: { host: string; browser: RpcStub<LentChrome> }[] = []; + const stubs: { [Symbol.dispose](): void }[] = []; + const sockets: { close(code?: number, reason?: string): void; terminate(): void }[] = []; + let failNextProvide = false; + let refusedProvides = 0; + try { + webSockets.on("connection", (socket, request) => { + const valid = request.headers.authorization === authorization; + const host = new URL(`https://${request.headers.host}`).hostname; + sockets.push(socket); + const queue: string[] = []; + let waiting: { resolve(value: string): void; reject(reason: Error): void } | undefined; + let closed = false; + socket.on("message", (message) => { + const text = typeof message === "string" ? message : message.toString(); + if (waiting) { + const current = waiting; + waiting = undefined; + current.resolve(text); + } else queue.push(text); + }); + socket.on("close", () => { + closed = true; + waiting?.reject(new Error("Fixture socket closed")); + }); + let providedBrowser: RpcStub<LentChrome> | undefined; + let ready = false; + // The `mind` of the session that the root of a mind's /api answers to `authenticate()` + // (iterate/api `ControlPlaneApi`), as far as the extension calls it. + class FixtureMind extends RpcTarget { + async whoami() { + return { mindSlug: host, principal: { email: "fixture@example.test" } }; + } + async provide(_name: string, browser: RpcStub<LentChrome>) { + if (failNextProvide) { + failNextProvide = false; + refusedProvides += 1; + throw new Error("Durable Object is overloaded. Requests queued for too long."); + } + providedBrowser = browser.dup(); + return new FixtureLend(); + } + async append() { + return {}; + } + async invoke(steps: unknown[]) { + const terminal = steps.at(-1); + if (!providedBrowser || !Array.isArray(terminal) || terminal[0] !== "tabs") + throw new Error("Unexpected fixture probe"); + const tabs = await providedBrowser.tabs(); + // The setup probe runs after the controller assigns this lend's group title. + if (!ready) { + ready = true; + lends.push({ host, browser: providedBrowser }); + } + return tabs; + } + } + const mind = new FixtureMind(); + const session = new RpcSession( + { + send: (message: string) => socket.send(message), + receive: () => { + const message = queue.shift(); + if (message) return Promise.resolve(message); + if (closed) return Promise.reject(new Error("Fixture socket closed")); + return new Promise<string>((resolve, reject) => { + waiting = { resolve, reject }; + }); + }, + abort: () => socket.close(), + }, + { + authenticate: () => { + if (!valid) { + refusedChecks += 1; + throw Object.assign(new Error("no live credential of this mind: sign in again"), { + code: "UNAUTHENTICATED", + }); + } + authorizedChecks += 1; + return { mind }; + }, + }, + ); + stubs.push(session.getRemoteMain()); + }); + const worker = context.serviceWorkers()[0] || (await context.waitForEvent("serviceworker")); + let controller = await context.newPage(); + await controller.goto(`chrome-extension://${new URL(worker.url()).host}/index.html`); + // Test-only grants are created here. No real session, cookie, profile or token is imported. + const signIn = async (mind: string) => { + await controller.evaluate(`chrome.storage.local.set({ + mind: "${mind}.test", browserName: "fixture", + "oauth:session": { issuer: "https://iterate.${mind}.test:${tlsAddress.port}", clientId: "fixture-client", accessToken: "fixture-only-grant", expiresAt: Date.now() + 3_600_000 }, + })`); + await controller.reload(); + await controller.getByRole("button", { name: "Share this browser", exact: true }).click(); + await expect + .poll( + async () => ({ + lends: lends.filter((lend) => lend.host === `iterate.${mind}.test`).length, + panel: await controller.locator("#connection").innerText(), + }), + { timeout: 5_000 }, + ) + .toMatchObject({ lends: 1 }); + await expect.poll(() => controller.locator("#copy").count()).toBe(1); + const lend = lends.find((lend) => lend.host === `iterate.${mind}.test`); + if (!lend) throw new Error("Fixture was not lent"); + return lend.browser; + }; + /** What the label on an attached tab shows: the closed shadow root, read through CDP. */ + const labelOf = (id: number) => + controller.evaluate<{ + name: string | null; + address: string | null; + text: string | null; + logo: string | null; + dot: boolean; + } | null>(`(async () => { + const send = (method, params) => chrome.debugger.sendCommand({tabId:${id}}, method, params); + const {root} = await send('DOM.getDocument', {depth:-1,pierce:true}); + function find(node, test) { + if (test(node)) return node; + for (const child of [...(node.children || []), ...(node.shadowRoots || [])]) { const found=find(child, test); if(found) return found; } + } + const classOf = (node) => { const all = node.attributes || []; const at = all.indexOf('class'); return at < 0 ? '' : all[at + 1]; }; + const host = find(root, node => node.nodeName === 'ITERATE-INDICATOR'); + if (!host) return null; + const part = (name) => find(host, node => classOf(node) === name); + const text = (name) => { const node = part(name); return node ? (node.children || []).map(child => child.nodeValue || '').join('') : null; }; + let logo = null; + if (part('logo')) { + const {object} = await send('DOM.resolveNode', {nodeId:part('logo').nodeId}); + const {result} = await send('Runtime.callFunctionOn', {objectId:object.objectId, functionDeclaration:'function(){return this.complete && this.naturalWidth > 0 ? this.src : "";}', returnByValue:true}); + logo = result.value; + } + return {name:text('name'), address:text('address'), text:text('text'), logo, dot:Boolean(part('dot'))}; + })()`); + let first = await signIn("first"); + // The panel names the mind by its profile: the logo, then the name over the address. + await expect + .poll(() => + controller.evaluate(() => { + const logo = window.document.querySelector<HTMLImageElement>(".mind-logo"); + return { + name: window.document.querySelector(".mind-name")?.textContent, + address: window.document.querySelector(".mind-address")?.textContent, + markup: window.document.querySelectorAll(".mind b").length, + logo: logo?.complete && logo.naturalWidth > 0 ? logo.src : "", + }; + }), + ) + .toEqual({ + name: "First <b>mind</b>", + address: "first.test", + markup: 0, + logo: `https://first.test:${tlsAddress.port}/favicon.svg`, + }); + const screenshots = process.env.ITERATE_EXTENSION_SCREENSHOTS_DIR; + if (screenshots) + await controller.screenshot({ path: join(screenshots, "chrome-083-sharing-on.png") }); + await controller.close(); + expect(await first.tabs()).toEqual([]); + controller = await context.newPage(); + await controller.goto(`chrome-extension://${new URL(worker.url()).host}/index.html`); + await expect.poll(() => controller.locator("#copy").count()).toBe(1); + expect(lends).toHaveLength(1); + const { tabId } = await first.openPage({ url: `http://127.0.0.1:${address.port}/form` }); + await first.openPage({ url: `http://127.0.0.1:${address.port}/anchor` }); + let page = first.page(tabId); + await page.getByLabel("Message").fill("signed-in panel"); + await expect + .poll(() => labelOf(tabId)) + .toEqual({ + name: "First <b>mind</b>", + address: "first.test", + text: expect.stringMatching(/^is /), + logo: `https://first.test:${tlsAddress.port}/favicon.svg`, + dot: false, + }); + if (screenshots) + await context + .pages() + .find((tab) => tab.url().endsWith("/form")) + ?.screenshot({ path: join(screenshots, "chrome-083-label.png") }); + await first.cdp(tabId, "Input.insertText", { text: " activity proof " }); + await expect + .poll(() => controller.locator("#tabs .badge").allTextContents()) + .toContain("typing"); + expect(await controller.locator("#instructions").textContent()).toContain( + "while sharing is on", + ); + await page.getByRole("button", { name: "Top action", exact: true }).click(); + await page.getByRole("button", { name: "Send" }).click(); + expect( + await first.cdp(tabId, "Runtime.evaluate", { + expression: "document.body.dataset.trusted", + returnByValue: true, + }), + ).toMatchObject({ result: { value: "true" } }); + const waiting = first + .page(tabId) + .getByRole("button", { name: "Not present" }) + .click({ timeout: 500 }); + const queued = first.page(tabId).getByLabel("Message").fill("queued", { timeout: 100 }); + await expect(queued).rejects.toThrow(/Timed out in page queue/); + await expect(waiting).rejects.toThrow(/Timed out/); + const transient = await first.openPage({ url: `http://127.0.0.1:${address.port}/transient` }); + const closedPage = first.page(transient.tabId); + await closedPage.getByLabel("Message").fill("temporary"); + await controller.evaluate(`chrome.tabs.remove(${transient.tabId})`); + await expect(closedPage.getByLabel("Message").fill("closed tab")).rejects.toThrow(); + await page.getByLabel("Message").fill("other tab still works"); + const stopPointerEvents = await controller.evaluate<string>(`(async () => { + const {root} = await chrome.debugger.sendCommand({tabId:${tabId}}, 'DOM.getDocument', {depth:-1,pierce:true}); + function stop(node) { + if (node.nodeName === 'BUTTON' && node.children?.some(child => child.nodeValue === 'Stop')) return node; + for (const child of [...(node.children || []), ...(node.shadowRoots || [])]) { const found=stop(child); if(found) return found; } + } + const button=stop(root); if(!button) throw new Error('Missing indicator Stop'); + const {object}=await chrome.debugger.sendCommand({tabId:${tabId}}, 'DOM.resolveNode', {nodeId:button.nodeId}); + const {result,exceptionDetails}=await chrome.debugger.sendCommand({tabId:${tabId}}, 'Runtime.callFunctionOn', { + objectId:object.objectId, functionDeclaration:'function(){const pointer=getComputedStyle(this).pointerEvents;this.click();return pointer;}',returnByValue:true + }); + if(exceptionDetails) throw new Error(exceptionDetails.text); + return result.value; + })()`); + expect(stopPointerEvents).toBe("auto"); + await expect + .poll(() => first.tabs()) + .not.toEqual(expect.arrayContaining([expect.objectContaining({ tabId })])); + await expect(page.getByLabel("Message").fill("stopped")).rejects.toThrow(/not in.*tab group/); + const anchorGroup = await controller.evaluate<number>( + `chrome.tabs.query({}).then(tabs=>tabs.find(tab=>tab.groupId !== -1).groupId)`, + ); + await controller.evaluate(`chrome.tabs.group({groupId:${anchorGroup},tabIds:[${tabId}]})`); + await page.getByLabel("Message").fill("returned after Stop"); + await first.detach(tabId); + expect(await first.tabs()).toEqual( + expect.arrayContaining([expect.objectContaining({ tabId, attached: false })]), + ); + await page.getByLabel("Message").fill("reattached"); + const groupId = await controller.evaluate<number>( + `chrome.tabs.get(${tabId}).then(tab => tab.groupId)`, + ); + await controller.evaluate(`chrome.tabs.ungroup(${tabId})`); + await expect(page.getByLabel("Message").fill("refused")).rejects.toThrow(/not in.*tab group/); + await expect(first.cdp(tabId, "Runtime.evaluate", { expression: "1" })).rejects.toThrow( + /not in.*tab group/, + ); + await controller.evaluate(`chrome.tabs.group({groupId:${groupId},tabIds:[${tabId}]})`); + await page.getByLabel("Message").fill("group restored"); + await controller.evaluate(`chrome.tabGroups.update(${groupId},{title:"not-the-mind"})`); + await expect(page.getByLabel("Message").fill("refused")).rejects.toThrow(/not in.*tab group/); + await controller.evaluate(`chrome.tabGroups.update(${groupId},{title:"first.test"})`); + await page.getByLabel("Message").fill("title restored"); + const stalePage = page; + sockets[0].terminate(); // Abnormal1006, as in the deploy incident. + await expect + .poll(() => lends.filter((lend) => lend.host === "iterate.first.test").length, { + timeout: 5_000, + }) + .toBe(2); + await expect.poll(() => controller.locator("#copy").count()).toBe(1); + await expect(stalePage.getByLabel("Message").fill("stale connection")).rejects.toThrow(); + first = lends[1].browser; + // The redial succeeds, then its pager is cut and the following lend is refused. + failNextProvide = true; + sockets[1].terminate(); + await expect.poll(() => refusedProvides, { timeout: 5_000 }).toBe(1); + await expect + .poll(() => controller.getByRole("heading", { name: /Reconnecting, try/ }).count()) + .toBe(1); + await controller.close(); + await expect + .poll(() => lends.filter((lend) => lend.host === "iterate.first.test").length, { + timeout: 65_000, + }) + .toBe(3); + first = lends[2].browser; + controller = await context.newPage(); + await controller.goto(`chrome-extension://${new URL(worker.url()).host}/index.html`); + await expect.poll(() => controller.locator("#copy").count()).toBe(1); + page = first.page(tabId); + await page.getByLabel("Message").fill("recovered connection"); + await page.getByRole("button", { name: "Send" }).click(); + expect( + await first.cdp(tabId, "Runtime.evaluate", { + expression: + "({value:document.querySelector('input').value,trusted:document.body.dataset.trusted})", + returnByValue: true, + }), + ).toMatchObject({ result: { value: { value: "recovered connection", trusted: "true" } } }); + await controller.getByRole("button", { name: "Sign out", exact: true }).click(); + await expect.poll(() => controller.locator("#logout").count()).toBe(0); + await expect(page.getByLabel("Message").fill("signed out")).rejects.toThrow(); + const beforeRefusal = lends.length; + await controller.evaluate(`chrome.storage.local.set({ + mind: "second.test", "oauth:session": { issuer: "https://iterate.second.test:${tlsAddress.port}", + clientId: "fixture-client", accessToken: "revoked-fixture-grant", expiresAt: Date.now() + 3_600_000 } + })`); + await controller.reload(); + await controller.getByRole("button", { name: "Share this browser", exact: true }).click(); + await expect + .poll(() => controller.getByRole("heading", { name: "Not connected", exact: true }).count()) + .toBe(1); + expect(refusedChecks).toBe(1); + expect(lends.length).toBe(beforeRefusal); + const refusedCdp = await context.browser()!.newBrowserCDPSession(); + const refusedWorker = (await refusedCdp.send("Target.getTargets")).targetInfos.find( + (target) => target.type === "service_worker" && target.url === worker.url(), + ); + if (!refusedWorker) throw new Error("Missing refused worker"); + await refusedCdp.send("Target.closeTarget", { targetId: refusedWorker.targetId }); + await controller.reload(); + await expect + .poll(() => controller.getByRole("heading", { name: "Not connected", exact: true }).count()) + .toBe(1); + expect(refusedChecks).toBe(1); + expect(lends.length).toBe(beforeRefusal); + await controller.getByRole("button", { name: "Sign out", exact: true }).click(); + await refusedCdp.detach(); + const second = await signIn("second"); + expect(await second.tabs()).toHaveLength(0); + await expect(second.page(tabId).getByLabel("Message").fill("other mind")).rejects.toThrow( + /not in.*tab group/, + ); + const other = await second.openPage({ url: `http://127.0.0.1:${address.port}/second` }); + await second.page(other.tabId).getByLabel("Message").fill("second mind"); + // A mind with no name and a logo that does not load: the address stays, with the plain marks. + await expect + .poll(() => labelOf(other.tabId)) + .toEqual({ + name: null, + address: "second.test", + text: expect.stringMatching(/^is /), + logo: null, + dot: true, + }); + await expect + .poll(() => + controller.evaluate(() => ({ + name: window.document.querySelector(".mind-name")?.textContent ?? null, + address: window.document.querySelector(".mind-address")?.textContent, + logo: window.document.querySelector(".mind-logo")?.getAttribute("src"), + })), + ) + .toEqual({ name: null, address: "second.test", logo: "icon-32.png" }); + await controller.close(); + await second.page(other.tabId).getByLabel("Message").fill("closed panel still lent"); + const cdp = await context.browser()!.newBrowserCDPSession(); + const beforeDocumentLoss = lends.filter((lend) => lend.host === "iterate.second.test").length; + const { targetInfos: documents } = await cdp.send("Target.getTargets"); + const document = documents.find((target) => target.url.includes("/offscreen.html?transport=")); + if (!document) throw new Error("Missing offscreen transport document"); + await cdp.send("Target.closeTarget", { targetId: document.targetId }); + await expect + .poll(() => lends.filter((lend) => lend.host === "iterate.second.test").length, { + timeout: 5_000, + }) + .toBe(beforeDocumentLoss + 1); + await lends + .at(-1)! + .browser.page(other.tabId) + .getByLabel("Message") + .fill("offscreen document restored"); + const { targetInfos } = await cdp.send("Target.getTargets"); + const target = targetInfos.find( + (target) => target.type === "service_worker" && target.url === worker.url(), + ); + if (!target) throw new Error("Missing extension service worker target"); + await cdp.send("Target.closeTarget", { targetId: target.targetId }); + await expect + .poll(() => lends.filter((lend) => lend.host === "iterate.second.test").length, { + timeout: 65_000, + }) + .toBe(beforeDocumentLoss + 2); + const restored = lends.at(-1)!.browser; + await restored.page(other.tabId).getByLabel("Message").fill("worker restored"); + await expect( + second.page(other.tabId).getByLabel("Message").fill("retired worker"), + ).rejects.toThrow(); + controller = await context.newPage(); + await controller.goto(`chrome-extension://${new URL(worker.url()).host}/index.html`); + await expect.poll(() => controller.locator("#copy").count()).toBe(1); + await controller.getByRole("button", { name: "Turn sharing off", exact: true }).click(); + await expect.poll(() => controller.locator("#share").count()).toBe(1); + await expect(restored.tabs()).rejects.toThrow(); + await cdp.detach(); + await controller.getByRole("button", { name: "Share this browser", exact: true }).click(); + await expect.poll(() => controller.locator("#copy").count()).toBe(1); + const prior = lends.length; + await context.close(); + context = await launch(); + const restartedWorker = + context.serviceWorkers()[0] || (await context.waitForEvent("serviceworker")); + controller = await context.newPage(); + await controller.goto(`chrome-extension://${new URL(restartedWorker.url()).host}/index.html`); + await expect + .poll(() => controller.getByRole("heading", { name: "Sharing off", exact: true }).isVisible()) + .toBe(true); + await expect + .poll(() => + controller.getByRole("button", { name: "Share this browser", exact: true }).isVisible(), + ) + .toBe(true); + expect(lends).toHaveLength(prior); + expect(authorizedChecks).toBeGreaterThanOrEqual(lends.length); + await controller.getByRole("button", { name: "Share this browser", exact: true }).click(); + await expect.poll(() => controller.locator("#copy").count()).toBe(1); + const tokenTab = await lends + .at(-1)! + .browser.openPage({ url: `http://127.0.0.1:${address.port}/token-renewal` }); + const beforeTokenExpiry = lends.length; + sockets.at(-1)!.close(1008, "the sign-in for this session ended: authenticate again"); + await expect.poll(() => lends.length, { timeout: 5_000 }).toBe(beforeTokenExpiry + 1); + await expect.poll(() => controller.locator("#copy").count()).toBe(1); + expect(await lends.at(-1)!.browser.tabs()).toEqual( + expect.arrayContaining([expect.objectContaining({ tabId: tokenTab.tabId })]), + ); + await lends.at(-1)!.browser.page(tokenTab.tabId).getByLabel("Message").fill("token renewed"); + if (screenshots) + await controller.screenshot({ path: join(screenshots, "chrome-083-sharing-off.png") }); + } finally { + for (const lend of lends) lend.browser[Symbol.dispose](); + for (const stub of stubs) stub[Symbol.dispose](); + await context.close(); + for (const socket of webSockets.clients) socket.terminate(); + await new Promise<void>((resolve) => webSockets.close(() => resolve())); + await new Promise<void>((resolve) => tls.close(() => resolve())); + await new Promise<void>((resolve) => server.close(() => resolve())); + await rm(directory, { recursive: true, force: true }); + } +}, 180_000); + +class FixtureLend extends RpcTarget { + lendEnded() { + return new Promise<string>(() => {}); + } +} + +type LentChrome = { + openPage(input: { url: string }): Promise<{ tabId: number }>; + page(tabId: number): Promise<ChromePage>; + tabs(): Promise<{ tabId: number; attached: boolean }[]>; + cdp(tabId: number, method: string, params: Record<string, unknown>): Promise<unknown>; + detach(tabId: number): Promise<void>; +};
A src/locator-runtime.ts
@@ -0,0 +1,111 @@ +import { Ivya, getByLabelSelector, getByRoleSelector, getByTextSelector } from "ivya"; +import { getAriaDisabled, isElementVisible } from "ivya/utils"; +import type { Probe, Step } from "./page.ts"; + +const engine = Ivya.create({ browser: "chromium", testIdAttribute: "data-testid" }); +const identities = new WeakMap<Element, number>(); +let nextIdentity = 0; + +export function probe(steps: Step[], action: string, commitId?: number): Probe { + const selector = steps + .map((step) => { + switch (step.kind) { + case "css": + return step.selector; + case "role": + return getByRoleSelector(step.role, { exact: false, ...step.options }); + case "text": + return getByTextSelector(step.text, { exact: false, ...step.options }); + case "label": + return getByLabelSelector(step.text, { exact: false, ...step.options }); + case "nth": + return `nth=${step.index}`; + } + }) + .join(" >> "); + let matches: Element[]; + try { + matches = engine.queryLocatorSelectorAll(selector, document.documentElement); + } catch (error) { + return { status: "fatal", detail: String(error) }; + } + if (action === "count") return { status: "value", value: matches.length }; + if (matches.length > 1) + return { + status: "fatal", + detail: `strict mode violation: ${matches.length} matches for ${selector}: ${matches + .slice(0, 5) + .map((el) => el.outerHTML.slice(0, 180)) + .join("\n")}`, + }; + const el = matches[0]; + if (!el) return { status: "wait", detail: `no match for ${selector}` }; + if (action === "textContent") return { status: "value", value: el.textContent }; + if (el instanceof HTMLIFrameElement) + return { status: "fatal", detail: "Frame controls are unsupported; use raw CDP." }; + if (!isElementVisible(el)) return { status: "wait", detail: "element is hidden" }; + if (getAriaDisabled(el) || el.matches(":disabled") || inert(el)) + return { status: "wait", detail: "element is disabled or inert" }; + if (action === "fill") { + if (!(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)) + return { status: "fatal", detail: "fill supports text inputs and textareas only" }; + if ( + el instanceof HTMLInputElement && + !["text", "search", "email", "tel", "url", "password"].includes(el.type) + ) + return { status: "fatal", detail: `fill does not support input type ${el.type}` }; + if (el.readOnly || el.getAttribute("aria-readonly") === "true") + return { status: "wait", detail: "element is read-only" }; + } + el.scrollIntoView({ block: "center", inline: "center", behavior: "instant" }); + const rect = el.getBoundingClientRect(); + const x = (Math.max(0, rect.left) + Math.min(innerWidth, rect.right)) / 2; + const y = (Math.max(0, rect.top) + Math.min(innerHeight, rect.bottom)) / 2; + if (x < 0 || y < 0 || x >= innerWidth || y >= innerHeight) + return { status: "wait", detail: "element is outside the viewport" }; + let hit = document.elementFromPoint(x, y); + while (hit?.shadowRoot) { + const inner = hit.shadowRoot.elementFromPoint(x, y); + if (!inner || inner === hit) break; + hit = inner; + } + if (!contains(el, hit)) + return { status: "wait", detail: `element is covered by ${hit?.tagName || "the viewport"}` }; + const id = identities.get(el) ?? ++nextIdentity; + identities.set(el, id); + if (commitId !== undefined) { + if (id !== commitId) return { status: "wait", detail: "element was replaced" }; + if (action === "fill" || action === "press") { + if (!(el instanceof HTMLElement)) + return { status: "fatal", detail: "element cannot receive keyboard input" }; + el.focus({ preventScroll: true }); + let active = document.activeElement; + while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement; + if (active !== el) return { status: "wait", detail: "element did not receive focus" }; + if ( + action === "fill" && + (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) + ) + el.select(); + } + } + return { status: "ready", id, box: [x, y, rect.width, rect.height] }; +} + +function contains(outer: Element, node: Node | null): boolean { + for (let current = node; current; current = renderedParent(current)) + if (current === outer) return true; + return false; +} + +function inert(el: Element): boolean { + for (let current: Node | null = el; current; current = renderedParent(current)) { + if (current instanceof Element && current.hasAttribute("inert")) return true; + } + return false; +} + +function renderedParent(node: Node): Node | null { + const slot = node instanceof Element || node instanceof Text ? node.assignedSlot : null; + return slot || node.parentNode || (node instanceof ShadowRoot ? node.host : null); +}
A src/page.test.ts
@@ -0,0 +1,355 @@ +// Real Chromium DOM and trusted CDP input on local fixtures. No user browser or network sites. +import { createServer } from "node:http"; +import { chromium, type Page } from "@playwright/test"; +import { build } from "esbuild"; +import { newMessagePortRpcSession } from "capnweb"; +import { test, expect } from "vitest"; +import { ChromePage, type Cdp } from "./page.ts"; + +const runtime = await build({ + entryPoints: [new URL("./locator-runtime.ts", import.meta.url).pathname], + bundle: true, + write: false, + format: "iife", + globalName: "globalThis.__iterateControls", +}); +const source = runtime.outputFiles[0].text; + +test("role, accessible name, labels, text and strict RPC chains use Ivya semantics", async () => { + await fixture(async ({ page, controls }) => { + await page.setContent( + `<span id="name">Publish report</span><button aria-labelledby="name">Icon</button><label for="email">Email address</label><input id="email"><p> A message </p><div id="shadow"></div>`, + ); + await page.evaluate(() => { + document + .querySelector("#shadow") + ?.attachShadow({ mode: "open" }) + .append(Object.assign(document.createElement("button"), { textContent: "Shadow action" })); + }); + const channel = new MessageChannel(); + using _server = newMessagePortRpcSession(channel.port1, controls); + using remote = newMessagePortRpcSession<ChromePage>(channel.port2); + await remote.getByLabel("Email address", { exact: true }).fill("a@example.test"); + await remote.getByRole("button", { name: "Publish report", exact: true }).click(); + expect(await remote.getByText("A message", { exact: true }).textContent()).toBe( + " A message ", + ); + expect(await remote.getByRole("button", { name: "Shadow action" }).count()).toBe(1); + expect(await page.inputValue("#email")).toBe("a@example.test"); + }); +}); + +test("click, fill, clearing and keyboard actions produce trusted browser events", async () => { + await fixture(async ({ page, controls }) => { + await page.setContent( + `<button>Send</button><label>Message<input value="before"></label><script>window.events=[]; for(const t of ['click','input','keydown','keyup']) document.addEventListener(t,e=>events.push({type:e.type,trusted:e.isTrusted,key:e.key}));</script>`, + ); + await controls.getByRole("button", { name: "Send" }).click(); + await controls.getByLabel("Message").fill("hello"); + await controls.getByLabel("Message").press("ArrowLeft"); + await controls.getByLabel("Message").press("Backspace"); + expect(await page.inputValue("input")).toBe("helo"); + await controls.getByLabel("Message").fill(""); + await controls.getByLabel("Message").press("Enter"); + expect(await page.inputValue("input")).toBe(""); + const events = + await page.evaluate<Array<{ type: string; trusted: boolean; key?: string }>>("events"); + expect(events).toEqual( + expect.arrayContaining([ + { type: "click", trusted: true }, + { type: "input", trusted: true }, + { type: "keydown", trusted: true, key: "Enter" }, + { type: "keyup", trusted: true, key: "Enter" }, + ]), + ); + expect(events.filter((e: { trusted: boolean }) => !e.trusted)).toHaveLength(0); + }); +}); + +test("textarea replacement and Enter submit use native editing behavior", async () => { + await fixture(async ({ page, controls }) => { + await page.setContent( + '<label>Notes<textarea>before</textarea></label><form onsubmit="event.preventDefault();document.body.dataset.submitted=\'true\'"><label>Email<input type="email"></label></form>', + ); + await controls.getByLabel("Notes").fill("two\nlines"); + expect(await page.inputValue("textarea")).toBe("two\nlines"); + await controls.locator("form").getByLabel("Email").fill("agent@example.test"); + await controls.getByLabel("Email").press("Enter"); + expect(await page.getAttribute("body", "data-submitted")).toBe("true"); + }); +}); + +test("locators wait for delayed DOM and re-resolve replaced nodes", async () => { + await fixture(async ({ page, controls }) => { + const field = controls.getByLabel("Later"); + await page.evaluate(() => { + setTimeout(() => { + document.body.innerHTML = "<label>Later<input></label>"; + }, 120); + }); + await field.fill("first"); + await page.evaluate(() => { + const input = document.querySelector("input"); + input?.replaceWith(input.cloneNode()); + }); + await field.fill("second"); + expect(await page.inputValue("input")).toBe("second"); + }); +}); + +test("duplicates fail strictly while first and nth select deliberately", async () => { + await fixture(async ({ page, controls }) => { + await page.setContent(`<button>Same</button><button>Same</button>`); + await expect(controls.getByRole("button", { name: "Same" }).click()).rejects.toThrow( + /strict mode violation: 2 matches/, + ); + expect(await controls.getByRole("button").count()).toBe(2); + await controls.getByRole("button").first().click(); + await controls.getByRole("button").nth(1).click(); + }); +}); + +test("missing elements time out with the locator and no input", async () => { + await fixture(async ({ controls, commands }) => { + await expect( + controls.getByRole("button", { name: "Absent" }).click({ timeout: 1000 }), + ).rejects.toThrow(/Timed out: click.*Absent.*no match/s); + expect(commands.filter((method) => method.startsWith("Input."))).toHaveLength(0); + }); +}); + +test.for([ + { + name: "hidden", + html: '<button style="visibility:hidden">Act</button>', + release: 'document.querySelector("button").style.visibility="visible"', + reason: "hidden", + }, + { + name: "disabled fieldset", + html: "<fieldset disabled><button>Act</button></fieldset>", + release: 'document.querySelector("fieldset").disabled=false', + reason: "disabled", + }, + { + name: "ARIA disabled", + html: '<div role="group" aria-disabled="true"><button>Act</button></div>', + release: 'document.querySelector("div").removeAttribute("aria-disabled")', + reason: "disabled", + }, + { + name: "inert", + html: "<div inert><button>Act</button></div>", + release: 'document.querySelector("div").inert=false', + reason: "disabled or inert", + }, + { + name: "covered", + html: '<button>Act</button><div id="cover" style="position:fixed;inset:0;background:red"></div>', + release: 'document.querySelector("#cover").remove()', + reason: "covered", + }, +])("$name controls wait without input and recover", async ({ html, release, reason }) => { + await fixture(async ({ page, controls, commands }) => { + await page.setContent(html); + await expect(controls.locator("button").click({ timeout: 1000 })).rejects.toThrow( + new RegExp(reason), + ); + expect(commands.filter((method) => method.startsWith("Input."))).toHaveLength(0); + await page.evaluate(`setTimeout(() => { ${release} }, 120)`); + await controls.locator("button").click(); + }); +}); + +test("read-only fill waits and unsupported controls fail before input", async () => { + await fixture(async ({ page, controls, commands }) => { + await page.setContent( + '<input aria-label="Read only" readonly><input type="number" aria-label="Number"><div contenteditable aria-label="Editor"></div>', + ); + await expect(controls.getByLabel("Read only").fill("x", { timeout: 1000 })).rejects.toThrow( + /read-only/, + ); + await expect(controls.getByLabel("Number").fill("1")).rejects.toThrow(/input type number/); + await expect(controls.getByLabel("Editor").fill("x")).rejects.toThrow( + /text inputs and textareas only/, + ); + await expect(controls.getByLabel("Read only").press("Control+A")).rejects.toThrow( + /Unsupported key/, + ); + expect(commands.filter((method) => method.startsWith("Input."))).toHaveLength(0); + }); +}); + +test("moving targets settle before click and replaced targets are re-resolved", async () => { + await fixture(async ({ page, controls }) => { + await page.setContent( + '<button style="position:absolute;left:0">Move</button><script>let n=0; const t=setInterval(()=>{const b=document.querySelector("button");b.style.left=(++n*10)+"px"; if(n===8) {clearInterval(t);b.replaceWith(b.cloneNode(true));}},20);</script>', + ); + await controls.getByRole("button", { name: "Move" }).click(); + expect(await page.locator("button").evaluate((el) => el.getBoundingClientRect().left)).toBe(80); + }); +}); + +test("retained locators resolve in a new document and actions do not wait for navigation", async () => { + await fixture(async ({ page, controls, url }) => { + const button = controls.getByRole("button", { name: "Fixture" }); + await button.click(); + await page.goto(`${url}/next`); + await button.click(); + expect(await page.evaluate("window.clicked")).toBe(1); + await page.setContent(`<a href="${url}/next">Navigate</a>`); + await controls.getByRole("link", { name: "Navigate" }).click(); + await page.waitForURL(`${url}/next`); + await button.click(); + expect(await page.evaluate("window.clicked")).toBe(1); + }); +}); + +test("navigation between readiness and input fails without replay", async () => { + await fixture(async ({ page, controls, commands, intercept, url }) => { + let frames = 0; + intercept.current = async (method) => { + if (method === "Page.getFrameTree" && ++frames === 3) await page.goto(`${url}/next`); + }; + await expect(controls.getByRole("button", { name: "Fixture" }).click()).rejects.toThrow( + /Navigation changed the document/, + ); + expect(commands.filter((method) => method.startsWith("Input."))).toEqual([ + "Input.dispatchMouseEvent", + ]); + }); +}); + +test("frames are explicit limits and cross-frame contents are not selected", async () => { + await fixture(async ({ page, controls }) => { + await page.setContent('<iframe srcdoc="<button>Inside</button>"></iframe>'); + await expect(controls.locator("iframe").click()).rejects.toThrow( + /Frame controls are unsupported/, + ); + expect(await controls.getByRole("button", { name: "Inside" }).count()).toBe(0); + }); +}); + +test("transport revocation fails immediately and retained handles cannot bypass it", async () => { + await fixture(async ({ controls, intercept, commands }) => { + const retained = controls.getByRole("button", { name: "Fixture" }); + await retained.click(); + const count = commands.length; + intercept.current = async () => { + throw new Error("Tab is not in the mind's tab group"); + }; + await expect(retained.click()).rejects.toThrow(/not in the mind's tab group/); + expect(commands.slice(count)).toEqual(["Page.getFrameTree"]); + }); +}); + +test("a stalled CDP command is bounded and a key press always attempts release", async () => { + await fixture(async ({ controls, intercept, commands }) => { + intercept.current = async (method, params) => { + if (method === "Input.dispatchKeyEvent" && params.type === "keyDown") + throw new Error("transport failed"); + }; + await expect(controls.getByRole("button", { name: "Fixture" }).press("Enter")).rejects.toThrow( + /transport failed/, + ); + expect(commands.slice(-2)).toEqual(["Input.dispatchKeyEvent", "Input.dispatchKeyEvent"]); + intercept.current = async () => { + await new Promise(() => {}); + }; + await expect(controls.locator("button").click({ timeout: 100 })).rejects.toThrow( + /exceeded action deadline/, + ); + }); +}); + +test("queued actions have their own bounded deadline and never run after expiry", async () => { + await fixture(async ({ controls, intercept, commands }) => { + intercept.current = async () => { + await new Promise(() => {}); + }; + const first = controls.locator("button").click({ timeout: 300 }); + const second = controls.locator("button").click({ timeout: 80 }); + await expect(second).rejects.toThrow(/Timed out in page queue/); + await expect(first).rejects.toThrow(/exceeded action deadline/); + expect(commands).toEqual(["Page.getFrameTree"]); + }); +}); + +test("hover replacement is checked again before the mouse goes down", async () => { + await fixture(async ({ page, controls }) => { + await page.setContent("<button>Save</button>"); + await page.evaluate(() => { + document.querySelector("button")?.addEventListener( + "mouseenter", + (event) => { + const button = document.createElement("button"); + button.textContent = "Save"; + button.addEventListener("click", () => { + document.body.dataset.saved = "true"; + }); + if (event.target instanceof Element) event.target.replaceWith(button); + }, + { once: true }, + ); + }); + await controls.getByRole("button", { name: "Save" }).click(); + expect(await page.getAttribute("body", "data-saved")).toBe("true"); + }); +}); + +test("shadow buttons accept hits on assigned slot content", async () => { + await fixture(async ({ page, controls }) => { + await page.setContent("<x-save><span>Save</span></x-save>"); + await page.evaluate(() => { + const host = document.querySelector("x-save"); + if (!host) throw new Error("Missing component"); + const button = document.createElement("button"); + button.append(document.createElement("slot")); + button.addEventListener("click", () => { + document.body.dataset.saved = "true"; + }); + host.attachShadow({ mode: "open" }).append(button); + }); + await controls.getByRole("button", { name: "Save", exact: true }).click(); + expect(await page.getAttribute("body", "data-saved")).toBe("true"); + }); +}); + +async function fixture( + run: (fixture: { + page: Page; + controls: ChromePage; + commands: string[]; + url: string; + intercept: { current?: (method: string, params: Record<string, unknown>) => Promise<void> }; + }) => Promise<void>, +) { + const server = createServer((_, response) => { + response.setHeader("Content-Type", "text/html"); + response.end('<button onclick="window.clicked=(window.clicked||0)+1">Fixture</button>'); + }); + await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Fixture server has no TCP port"); + const browser = await chromium.launch({ headless: true }); + try { + const page = await browser.newPage(); + const url = `http://127.0.0.1:${address.port}`; + await page.goto(url); + const session = await page.context().newCDPSession(page); + const commands: string[] = []; + const intercept: { + current?: (method: string, params: Record<string, unknown>) => Promise<void>; + } = {}; + const cdp: Cdp = async (method, params) => { + commands.push(method); + await intercept.current?.(method, params); + // The browser session accepts the same CDP method/params pairs as chrome.debugger.sendCommand. + return session.send(method as Parameters<typeof session.send>[0], params) as ReturnType<Cdp>; + }; + await run({ page, controls: new ChromePage(cdp, source), commands, url, intercept }); + } finally { + await browser.close(); + await new Promise<void>((resolve) => server.close(() => resolve())); + } +}
A src/page.ts
@@ -0,0 +1,318 @@ +import { RpcTarget } from "capnweb"; + +type MatchOptions = { exact?: boolean }; +type RoleOptions = MatchOptions & { + name?: string; + disabled?: boolean; + includeHidden?: boolean; + checked?: boolean; + expanded?: boolean; + level?: number; + pressed?: boolean; + selected?: boolean; +}; +export type Step = + | { kind: "css"; selector: string } + | { kind: "role"; role: string; options: RoleOptions } + | { kind: "text" | "label"; text: string; options: MatchOptions } + | { kind: "nth"; index: number }; +export type Probe = + | { status: "ready"; id: number; box: number[] } + | { status: "wait" | "fatal"; detail: string } + | { status: "value"; value: number | string | null }; +type CdpReply = { + frameTree?: { frame: { id: string; loaderId: string } }; + executionContextId?: number; + result?: { value?: unknown }; + exceptionDetails?: { text: string; exception?: { description?: string } }; +}; +export type Cdp = (method: string, params: Record<string, unknown>) => Promise<CdpReply>; +type Options = { timeout?: number }; +class DeadlineError extends Error {} + +/** Each tab has one page handle and one input queue; queue wait counts toward its deadline. */ +export class ChromePage extends RpcTarget { + #cdp: Cdp; + #source: string; + #queue: Promise<unknown> = Promise.resolve(); + constructor(cdp: Cdp, source: string) { + super(); + this.#cdp = cdp; + this.#source = source; + } + locator(selector: string) { + return new ChromeLocator(this, [{ kind: "css", selector }]); + } + getByRole(role: string, options: RoleOptions = {}) { + return new ChromeLocator(this, [{ kind: "role", role, options }]); + } + getByText(text: string, options: MatchOptions = {}) { + return new ChromeLocator(this, [{ kind: "text", text, options }]); + } + getByLabel(text: string, options: MatchOptions = {}) { + return new ChromeLocator(this, [{ kind: "label", text, options }]); + } + + /** Internal calls stay off the RPC target's public method table. */ + static run(page: ChromePage, steps: Step[], action: string, value: string, options: Options) { + const timeout = options.timeout ?? 5_000; + if (!Number.isFinite(timeout) || timeout < 1 || timeout > 30_000) + throw new Error("timeout must be between 1 and 30000 ms"); + const deadline = performance.now() + timeout; + let timer: ReturnType<typeof setTimeout> | undefined; + const waiting = new Promise<never>((_, reject) => { + timer = setTimeout( + () => reject(new Error(`Timed out in page queue: ${action} ${JSON.stringify(steps)}`)), + timeout, + ); + }); + const task = page.#queue.then(() => { + clearTimeout(timer); + return page.#act(steps, action, value, deadline); + }); + page.#queue = task.catch(() => {}); + return Promise.race([task, waiting]); + } + + async #command( + method: string, + params: Record<string, unknown>, + deadline: number, + ): Promise<CdpReply> { + const remaining = deadline - performance.now(); + if (remaining <= 0) throw new DeadlineError("action deadline exceeded"); + let timer: ReturnType<typeof setTimeout> | undefined; + try { + return await Promise.race([ + this.#cdp(method, params), + new Promise<never>((_, reject) => { + timer = setTimeout( + () => reject(new DeadlineError(`CDP ${method} exceeded action deadline`)), + remaining, + ); + }), + ]); + } finally { + clearTimeout(timer); + } + } + + async #frame(deadline: number) { + const reply = await this.#command("Page.getFrameTree", {}, deadline); + if (!reply.frameTree) throw new Error("CDP did not return the main frame"); + return reply.frameTree.frame; + } + + async #probe( + contextId: number, + steps: Step[], + action: string, + deadline: number, + commitId?: number, + ) { + const reply = await this.#command( + "Runtime.evaluate", + { + contextId, + expression: `if (!globalThis.__iterateControls) { ${this.#source}\n }; globalThis.__iterateControls.probe(${JSON.stringify(steps)}, ${JSON.stringify(action)}, ${JSON.stringify(commitId)})`, + returnByValue: true, + }, + deadline, + ); + if (reply.exceptionDetails) + throw new Error( + `Locator evaluation failed (navigation may have replaced the document): ${reply.exceptionDetails.exception?.description || reply.exceptionDetails.text}`, + ); + const result = reply.result?.value; + if (!isLocatorProbeReply(result)) throw new Error("Invalid locator runtime reply"); + if (result.status === "fatal") throw new Error(result.detail); + return result; + } + + async #act(steps: Step[], action: string, value: string, deadline: number) { + if (action === "press" && !Object.hasOwn(keys, value)) + throw new Error(`Unsupported key ${value}; supported: ${Object.keys(keys).join(", ")}`); + let last = "no match"; + let previous = ""; + try { + for (;;) { + if (performance.now() >= deadline) + throw new Error(`Timed out: ${action} ${JSON.stringify(steps)}: ${last}`); + const frame = await this.#frame(deadline); + const world = await this.#command( + "Page.createIsolatedWorld", + { frameId: frame.id, worldName: "iterate-controls" }, + deadline, + ); + if (!world.executionContextId) throw new Error("CDP did not return an isolated world"); + const result = await this.#probe(world.executionContextId, steps, action, deadline); + if (result.status === "value") return result.value; + if (result.status === "ready") { + const signature = JSON.stringify([frame.loaderId, world.executionContextId, result]); + if (signature === previous) { + if (action === "click") + await this.#command( + "Input.dispatchMouseEvent", + { + type: "mouseMoved", + x: result.box[0], + y: result.box[1], + button: "none", + }, + deadline, + ); + const checked = await this.#probe( + world.executionContextId, + steps, + action, + deadline, + result.id, + ); + if (checked.status === "ready" && JSON.stringify(checked) === JSON.stringify(result)) { + const current = await this.#frame(deadline); + if (current.id !== frame.id || current.loaderId !== frame.loaderId) + throw new Error( + "Navigation changed the document before input; action was not retried", + ); + await this.#input(action, value, result.box, deadline); + return; + } + last = checked.status === "wait" ? checked.detail : "element changed before input"; + previous = ""; + } else { + previous = signature; + last = "waiting for a stable element"; + } + } else { + previous = ""; + last = result.detail; + } + await new Promise((resolve) => + setTimeout(resolve, Math.min(50, Math.max(0, deadline - performance.now()))), + ); + } + } catch (error) { + if (error instanceof DeadlineError) + throw new Error(`Timed out: ${action} ${JSON.stringify(steps)}: ${last}; ${error.message}`); + throw error; + } + } + + async #input(action: string, value: string, box: number[], deadline: number) { + if (action === "click") { + const params = { x: box[0], y: box[1], button: "left", clickCount: 1 }; + try { + await this.#command( + "Input.dispatchMouseEvent", + { ...params, type: "mousePressed", buttons: 1 }, + deadline, + ); + } finally { + await this.#command( + "Input.dispatchMouseEvent", + { ...params, type: "mouseReleased", buttons: 0 }, + performance.now() + 1_000, + ); + } + } else if (action === "fill" && value) { + await this.#command("Input.insertText", { text: value }, deadline); + } else { + const key = keys[action === "fill" ? "Backspace" : value]; + const { text: _text, ...released } = key; + try { + await this.#command("Input.dispatchKeyEvent", { type: "keyDown", ...key }, deadline); + } finally { + await this.#command( + "Input.dispatchKeyEvent", + { type: "keyUp", ...released }, + performance.now() + 1_000, + ); + } + } + } +} + +class ChromeLocator extends RpcTarget { + #page: ChromePage; + #steps: Step[]; + constructor(page: ChromePage, steps: Step[]) { + super(); + this.#page = page; + this.#steps = steps; + } + #chain(step: Step) { + return new ChromeLocator(this.#page, [...this.#steps, step]); + } + locator(selector: string) { + return this.#chain({ kind: "css", selector }); + } + getByRole(role: string, options: RoleOptions = {}) { + return this.#chain({ kind: "role", role, options }); + } + getByText(text: string, options: MatchOptions = {}) { + return this.#chain({ kind: "text", text, options }); + } + getByLabel(text: string, options: MatchOptions = {}) { + return this.#chain({ kind: "label", text, options }); + } + nth(index: number) { + if (!Number.isInteger(index) || index < 0) + throw new Error("nth requires a nonnegative integer"); + return this.#chain({ kind: "nth", index }); + } + first() { + return this.nth(0); + } + click(options: Options = {}) { + return ChromePage.run(this.#page, this.#steps, "click", "", options); + } + fill(value: string, options: Options = {}) { + // RPC callers can pass values that do not match the TypeScript signature. + // oxlint-disable-next-line iterate/simple-truthiness-check + if (typeof value !== "string") throw new Error("fill requires a string"); + return ChromePage.run(this.#page, this.#steps, "fill", value, options); + } + press(key: string, options: Options = {}) { + return ChromePage.run(this.#page, this.#steps, "press", key, options); + } + count() { + return ChromePage.run(this.#page, this.#steps, "count", "", {}); + } + textContent(options: Options = {}) { + return ChromePage.run(this.#page, this.#steps, "textContent", "", options); + } +} + +const keys: Record< + string, + { key: string; code: string; windowsVirtualKeyCode: number; text?: string } +> = { + Enter: { key: "Enter", code: "Enter", windowsVirtualKeyCode: 13, text: "\r" }, + Tab: { key: "Tab", code: "Tab", windowsVirtualKeyCode: 9 }, + Backspace: { key: "Backspace", code: "Backspace", windowsVirtualKeyCode: 8 }, + Escape: { key: "Escape", code: "Escape", windowsVirtualKeyCode: 27 }, + ArrowLeft: { key: "ArrowLeft", code: "ArrowLeft", windowsVirtualKeyCode: 37 }, + ArrowRight: { key: "ArrowRight", code: "ArrowRight", windowsVirtualKeyCode: 39 }, +}; + +// The Runtime.evaluate result crosses a CDP boundary; validate its discriminated payload. +// oxlint-disable iterate/simple-truthiness-check +function isLocatorProbeReply(value: unknown): value is Probe { + if (!value || typeof value !== "object" || !("status" in value)) return false; + if (value.status === "fatal" || value.status === "wait") + return "detail" in value && typeof value.detail === "string"; + if (value.status === "value") + return ( + "value" in value && + (value.value === null || typeof value.value === "string" || typeof value.value === "number") + ); + return ( + value.status === "ready" && + "id" in value && + typeof value.id === "number" && + "box" in value && + Array.isArray(value.box) && + value.box.length === 4 && + value.box.every((n) => typeof n === "number" && Number.isFinite(n)) + ); +}
A test/address.test.ts
@@ -0,0 +1,49 @@ +// The panel's address rule (public/address.js) against the rule that every other client uses +// (iterate/mind-api `mindAddressOf`): the extension carries its own copy, and the two answer alike. +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { test } from "node:test"; +import { mindIssuerOf } from "../public/address.js"; + +// The shared rule is the platform's, in the repo /repos/kernel. This repo has no copy of it: the +// two tests read it from a checkout of kernel in the folder beside this one, with its packages +// installed (`pnpm install` there), and are skipped without one. +type Rule = (typed: string) => { address: string } | { error: string }; +const kernel = new URL("../../kernel/core/lib/src/mind-api.ts", import.meta.url); +let mindAddressOf: Rule = () => ({ error: "skipped" }); +let skip: string | false = "no checkout of /repos/kernel beside this repo"; +if (existsSync(kernel)) { + try { + mindAddressOf = ((await import(kernel.href)) as { mindAddressOf: Rule }).mindAddressOf; + skip = false; + } catch (error) { + skip = `the checkout of /repos/kernel beside this repo does not load: ${(error as Error).message}`; + } +} + +void test("what a person typed names the same mind in the panel as in every other client", { skip }, () => { + for (const typed of [ + "example.com", + " Example.COM. ", + // a control plane at a zone's apex, and at a hostname of the person's choice + "https://example.com", + "example.com/", + "control.example.com", + "iterate.example.com", + "https://iterate.example.com/minds/x", + "example.co.uk", + ]) { + const shared = mindAddressOf(typed); + assert.ok("address" in shared, typed); + assert.equal(mindIssuerOf(typed), `https://${shared.address}`, typed); + } + assert.equal(mindIssuerOf("https://example.com"), "https://example.com"); + assert.equal(mindIssuerOf("control.example.com"), "https://control.example.com"); +}); + +void test("what is no address in the other clients is none in the panel", { skip }, () => { + for (const typed of ["", "example", "192.0.2.1", "https://[2001:db8::1]/", "foo_bar.com"]) { + assert.ok("error" in mindAddressOf(typed), typed); + assert.throws(() => mindIssuerOf(typed), typed); + } +});
A test/oauth.test.ts
@@ -0,0 +1,106 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; +import vm from "node:vm"; + +void test("OAuth waits for durable refresh intent after its asynchronous expiry check", async () => { + let now = 69_999; + let read; + let mark; + const reading = new Promise((resolve) => { + read = resolve; + }); + const marking = new Promise((resolve) => { + mark = resolve; + }); + const requests = []; + const context = vm.createContext({ + Date: class extends Date { + static now() { + return now; + } + }, + URLSearchParams, + fetch: async (url) => { + requests.push(url); + return { + ok: true, + json: async () => + url.endsWith("/token") + ? { access_token: "fixture-access", refresh_token: "fixture-next", expires_in: 3600 } + : { token_endpoint: "https://issuer.test/token" }, + }; + }, + }); + const module = new vm.SourceTextModule( + readFileSync(new URL("../oauth.js", import.meta.url), "utf8"), + { context }, + ); + await module.link(() => { + throw Error("Unexpected import"); + }); + await module.evaluate(); + let session = { + issuer: "https://issuer.test", + clientId: "fixture", + expiresAt: 100_000, + accessToken: "fixture-cached", + refreshToken: "fixture-refresh", + }; + let intents = 0; + const oauth = module.namespace.oauthClient({ + sessions: { + get: async () => { + await reading; + return session; + }, + set: async (_key, value) => { + session = value; + }, + }, + beforeRefresh: async () => { + intents += 1; + await marking; + }, + }); + const pending = oauth.freshAccessToken(); + now = 70_001; + read(); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(intents, 1); + assert.equal(requests.length, 0); + mark(); + assert.equal(await pending, "fixture-access"); + assert.equal(requests.length, 2); + assert.equal(await oauth.freshAccessToken(), "fixture-access"); + assert.equal(intents, 1); +}); +void test("a rejected refresh-intent write prevents the rotating request", async () => { + let requests = 0; + const context = vm.createContext({ + Date, + URLSearchParams, + fetch: async () => { + requests += 1; + throw Error("Must not fetch"); + }, + }); + const module = new vm.SourceTextModule( + readFileSync(new URL("../oauth.js", import.meta.url), "utf8"), + { context }, + ); + await module.link(() => { + throw Error("Unexpected import"); + }); + await module.evaluate(); + const oauth = module.namespace.oauthClient({ + sessions: { + get: async () => ({ issuer: "https://issuer.test", expiresAt: 0, refreshToken: "fixture" }), + }, + beforeRefresh: async () => { + throw Error("Intent not durable"); + }, + }); + await assert.rejects(oauth.freshAccessToken(), /Intent not durable/); + assert.equal(requests, 0); +});
A test/offscreen.test.ts
@@ -0,0 +1,264 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { RpcSession, RpcTarget } from "../dist/capnweb.js"; +import { messageTransport } from "../public/rpc-transport.js"; + +void test("message transport rejects queued and future calls when its port ends", async () => { + const sent = []; + const transport = messageTransport( + (message) => sent.push(message), + () => {}, + ); + transport.send("one"); + assert.deepEqual(sent, [{ type: "rpc", message: "one" }]); + transport.accept({ type: "rpc", message: "old reply" }); + transport.close(new Error("Worker ended")); + await assert.rejects(transport.receive(), /Worker ended/); + assert.throws(() => transport.send("late action"), /Worker ended/); +}); +void test("invalid local wire data ends the bridge instead of becoming an RPC call", async () => { + let aborts = 0; + const transport = messageTransport( + () => {}, + () => { + aborts += 1; + }, + ); + const waiting = transport.receive(); + transport.accept({ type: "rpc", message: { action: "click" } }); + await assert.rejects(waiting, /Invalid extension transport frame/); + assert.equal(aborts, 1); +}); +void test("only the current offscreen document can export the one API session", async () => { + const h = await harness(); + const gate = deferred(); + h.createGate = gate.promise; + const opening = h.api.openOffscreenApi( + "wss://iterate.fixture.test/api", + () => true, + () => {}, + ); + await flush(); + const url = h.documents[0].documentUrl; + for (const sender of [ + { id: "other", url }, + { id: "fixture", url: "https://web.test" }, + { id: "fixture", url: "chrome-extension://fixture/index.html" }, + { id: "fixture", url: url.replace(/transport=.*/, "transport=old-generation") }, + ]) { + const [port] = ports(sender); + h.api.acceptOffscreenPort(port); + assert.equal(port.closed, true); + } + gate.resolve(); + const api = await opening; + assert.equal(await api.echo("browser data"), "browser data"); + assert.deepEqual(h.opens, ["wss://iterate.fixture.test/api"]); + await assert.rejects( + h.api.openOffscreenApi( + "wss://iterate.fixture.test/api", + () => true, + () => {}, + ), + /already active/, + ); + const [duplicate] = ports({ id: "fixture", url }); + h.api.acceptOffscreenPort(duplicate); + assert.equal(duplicate.closed, true); + await h.api.disconnectOffscreen(); + await assert.rejects(Promise.resolve(api.echo("late action"))); + assert.deepEqual(h.calls, ["browser data"]); + assert.equal(h.documents.length, 0); +}); +void test("a late document creation after sharing off cannot open a socket", async () => { + const h = await harness(); + const gate = deferred(); + h.createGate = gate.promise; + let current = true; + const opening = h.api.openOffscreenApi( + "wss://iterate.fixture.test/api", + () => current, + () => {}, + ); + await flush(); + current = false; + const stopped = h.api.disconnectOffscreen(); + gate.resolve(); + assert.equal(await opening, null); + await stopped; + assert.deepEqual(h.opens, []); + assert.equal(h.documents.length, 0); +}); +void test("a socket failure and port loss report one failure and a new attempt uses a fresh document", async () => { + const h = await harness(); + let failures = 0; + const api = await h.api.openOffscreenApi( + "wss://iterate.fixture.test/api", + () => true, + () => { + failures += 1; + }, + ); + const url = h.documents[0].documentUrl; + h.peer.postMessage({ type: "socket-ended" }); + await flush(); + h.peer.disconnect(); + await flush(); + assert.equal(failures, 1); + await assert.rejects(Promise.resolve(api.echo("no replay"))); + await h.api.disconnectOffscreen(); + const replacement = await h.api.openOffscreenApi( + "wss://iterate.fixture.test/api", + () => true, + () => {}, + ); + assert.notEqual(h.documents[0].documentUrl, url); + assert.equal(await replacement.echo("fresh action"), "fresh action"); + assert.deepEqual(h.calls, ["fresh action"]); + await h.api.disconnectOffscreen(); +}); +void test("startup cleanup closes the orphaned offscreen document before any new API is opened", async () => { + const h = await harness(); + h.documents.push({ documentUrl: "chrome-extension://fixture/offscreen.html?transport=old" }); + await h.api.disconnectOffscreen(); + assert.equal(h.documents.length, 0); + assert.deepEqual(h.opens, []); +}); + +async function harness() { + const h = { + documents: [], + opens: [], + calls: [], + createGate: undefined, + peer: undefined, + api: undefined, + }; + class Api extends RpcTarget { + echo(value) { + h.calls.push(value); + return value; + } + } + class Controller extends RpcTarget { + open(url) { + h.opens.push(url); + return new Api(); + } + } + globalThis.chrome = { + runtime: { + id: "fixture", + getURL: (path) => `chrome-extension://fixture/${path}`, + getContexts: async () => [...h.documents], + }, + offscreen: { + createDocument: async ({ url }) => { + h.documents.push({ documentUrl: url }); + await h.createGate; + const [port, peer] = ports({ id: "fixture", url }); + h.peer = peer; + const wire = messageTransport( + (message) => peer.postMessage(message), + () => peer.disconnect(), + ); + peer.onMessage.addListener((message) => wire.accept(message)); + peer.onDisconnect.addListener(() => wire.close(new Error("Worker ended"))); + new RpcSession(wire, new Controller()).getRemoteMain(); + h.api.acceptOffscreenPort(port); + }, + closeDocument: async () => { + h.documents.length = 0; + }, + }, + }; + h.api = await import( + new URL(`../dist/offscreen-client.js?fixture=${crypto.randomUUID()}`, import.meta.url).href + ); + return h; +} +function ports(sender) { + const make = () => ({ + sender, + closed: false, + onMessage: event(), + onDisconnect: event(), + postMessage: undefined, + disconnect: undefined, + }); + const a = make(); + const b = make(); + for (const [local, peer] of [ + [a, b], + [b, a], + ]) { + local.postMessage = (message) => { + if (local.closed) throw new Error("Port ended"); + queueMicrotask(() => { + if (!peer.closed) peer.onMessage.emit(structuredClone(message)); + }); + }; + local.disconnect = () => { + if (local.closed) return; + local.closed = true; + peer.closed = true; + local.onDisconnect.emit(); + peer.onDisconnect.emit(); + }; + } + return [a, b]; +} +function event() { + const listeners = new Set(); + return { + addListener: (listener) => listeners.add(listener), + emit: (...args) => { + for (const listener of listeners) listener(...args); + }, + }; +} +function deferred() { + let resolve; + const promise = new Promise((yes) => { + resolve = yes; + }); + return { promise, resolve }; +} +function flush() { + return new Promise((resolve) => setImmediate(resolve)); +} + +void test("an explicit WebSocket policy close is a terminal authorization refusal", async () => { + const h = await harness(); + let refusal; + const api = await h.api.openOffscreenApi( + "wss://iterate.fixture.test/api", + () => true, + (error) => { + refusal = error; + }, + ); + h.peer.postMessage({ type: "socket-ended", policyRefused: true }); + await flush(); + assert.equal(refusal.code, "UNAUTHORIZED"); + await assert.rejects(Promise.resolve(api.echo("not replayed"))); + await h.api.disconnectOffscreen(); +}); + +void test("the normal token lifetime marker requests renewal and preserves real refusal precedence", async () => { + for (const policyRefused of [false, true]) { + const h = await harness(); + let failure; + await h.api.openOffscreenApi( + "wss://iterate.fixture.test/api", + () => true, + (error) => { + failure = error; + }, + ); + h.peer.postMessage({ type: "socket-ended", tokenExpired: true, policyRefused }); + await flush(); + assert.equal(failure.code, policyRefused ? "UNAUTHORIZED" : "TOKEN_EXPIRED"); + await h.api.disconnectOffscreen(); + } +});
A test/panel-ui.test.ts
@@ -0,0 +1,211 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; +import vm from "node:vm"; + +void test("successful panel reconnections reset the consecutive failure budget", async () => { + const ui = await panel(); + for (let i = 0; i < 8; i += 1) { + ui.ports.at(-1).onMessage.emit({ state: { phase: "off", signedIn: false, version: "0.8.2" } }); + assert.match(ui.app.innerHTML, /Sign in to a mind/); + ui.ports.at(-1).onDisconnect.emit(); + ui.tick(); + } + assert.equal(ui.ports.length, 9); + assert.equal(ui.timers.size, 0); + assert.equal(ui.ports.at(-1).messages[0].action, "state"); +}); +void test("failed panel reconnections stop after five attempts without replaying commands", async () => { + const ui = await panel(); + for (let i = 0; i < 6; i += 1) { + ui.ports.at(-1).onDisconnect.emit(); + ui.tick(); + await new Promise((resolve) => setImmediate(resolve)); + } + assert.equal(ui.ports.length, 6); + assert.equal(ui.timers.size, 0); + assert.match(ui.app.innerHTML, /Sharing status unavailable/); + assert.ok( + ui.ports.every((port) => port.messages.length === 1 && port.messages[0].action === "state"), + ); +}); +async function panel() { + const ports = []; + const timers = new Map(); + let serial = 0; + let imageError; + const app = { + innerHTML: "", + append() {}, + addEventListener(type, listener, capture) { + if (type === "error" && capture) imageError = (target) => listener({ target }); + }, + }; + const elements = new Map([ + ["app", app], + ["login", {}], + ]); + const context = vm.createContext({ + chrome: { + runtime: { + connect() { + const port = { + onMessage: event(), + onDisconnect: event(), + messages: [], + postMessage(message) { + this.messages.push(message); + }, + }; + ports.push(port); + return port; + }, + }, + }, + document: { + getElementById: (id) => elements.get(id), + activeElement: null, + createElement: () => ({ setAttribute() {} }), + }, + window: { addEventListener() {} }, + setTimeout: (callback) => { + timers.set(++serial, callback); + return serial; + }, + clearTimeout: (id) => timers.delete(id), + Date, + Error, + Map, + Set, + String, + Promise, + console, + }); + const module = new vm.SourceTextModule( + readFileSync(new URL("../public/panel.js", import.meta.url), "utf8"), + { context }, + ); + await module.link( + async () => + new vm.SourceTextModule( + readFileSync(new URL("../public/address.js", import.meta.url), "utf8"), + { context }, + ), + ); + await module.evaluate(); + return { + ports, + timers, + app, + imageError, + tick() { + const entry = timers.entries().next().value; + if (entry) { + timers.delete(entry[0]); + entry[1](); + } + }, + }; +} +function event() { + const listeners = new Set(); + return { + addListener: (listener) => listeners.add(listener), + emit: (...args) => { + for (const listener of listeners) listener(...args); + }, + }; +} + +void test("panel shows continued recovery try count then an explicit Lend again state", async () => { + const ui = await panel(); + ui.ports[0].onMessage.emit({ + state: { + phase: "waiting", + signedIn: true, + sharing: true, + version: "0.8.2", + retries: 23, + retryAt: 1_800_000, + }, + }); + assert.match(ui.app.innerHTML, /Reconnecting, try 23/); + assert.doesNotMatch(ui.app.innerHTML, /of 5/); + ui.ports[0].onMessage.emit({ + state: { + phase: "exhausted", + signedIn: true, + sharing: true, + version: "0.8.2", + retries: 40, + retryAt: null, + error: "Automatic lending recovery ended after 30 minutes.", + }, + }); + assert.match(ui.app.innerHTML, /Not lent · Lend again/); + assert.match(ui.app.innerHTML, />Lend again<\/button>/); +}); + +void test("a signed-in panel shows the mind's logo beside its name over its address", async () => { + const ui = await panel(); + ui.ports[0].onMessage.emit({ + state: { + phase: "off", + signedIn: true, + version: "0.8.3", + address: "example.com", + profile: { name: 'Ada\'s <b>"mind"</b>', icon: "https://example.com/favicon.svg" }, + }, + }); + assert.match( + ui.app.innerHTML, + /<img class="mind-logo" src="https:\/\/example\.com\/favicon\.svg" alt="" referrerpolicy="no-referrer" \/>/, + ); + assert.match( + ui.app.innerHTML, + /<div class="mind-name truncate">Ada's <b>"mind"<\/b><\/div><div class="mind-address truncate">example\.com<\/div>/, + ); + assert.doesNotMatch(ui.app.innerHTML, /class="brand"/); +}); + +void test("a mind with no name shows its address alone, and one with no logo shows iterate's mark", async () => { + const ui = await panel(); + ui.ports[0].onMessage.emit({ + state: { + phase: "off", + signedIn: true, + version: "0.8.3", + address: "example.com", + profile: { name: "", icon: null }, + }, + }); + assert.match(ui.app.innerHTML, /<img class="mind-logo" src="icon-32\.png"/); + assert.match( + ui.app.innerHTML, + /<div class="grow"><div class="mind-address truncate">example\.com<\/div><\/div>/, + ); + assert.doesNotMatch(ui.app.innerHTML, /mind-name/); +}); + +void test("a logo that does not load is replaced by iterate's mark and is not asked for again", async () => { + const ui = await panel(); + const state = { + phase: "off", + signedIn: true, + version: "0.8.3", + address: "example.com", + profile: { name: "Ada", icon: "https://example.com/favicon.svg" }, + }; + ui.ports[0].onMessage.emit({ state }); + const image = { + src: "https://example.com/favicon.svg", + classList: { contains: (name) => name === "mind-logo" }, + getAttribute: () => "https://example.com/favicon.svg", + }; + ui.imageError(image); + assert.equal(image.src, "icon-32.png"); + ui.ports[0].onMessage.emit({ state }); + assert.match(ui.app.innerHTML, /<img class="mind-logo" src="icon-32\.png"/); + assert.match(ui.app.innerHTML, /mind-name truncate">Ada</); + assert.match(ui.app.innerHTML, /mind-address truncate">example\.com</); +});
A test/panel.test.ts
@@ -0,0 +1,1459 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; +import vm from "node:vm"; + +const source = readFileSync(new URL("../public/lend.js", import.meta.url), "utf8"); + +void test("initial overload waits, disposes its socket, and recovers one lend", async () => { + const p = await panel(); + p.plans.push({ whoami: () => Promise.reject(overload()) }); + await p.signedIn(); + assert.equal(p.controller.snapshot().phase, "waiting"); + assert.notEqual(p.controller.snapshot().phase, "connected"); + assert.equal(p.sockets[0].disposed, true); + const wait = p.nextWait(); + assert.ok(wait >= 10_000 && wait <= 20_000, String(wait)); + await p.tick(wait - 1); + assert.equal(p.sockets.length, 1); + await p.tick(1); + assert.equal(p.controller.snapshot().phase, "connected"); + assert.equal(p.sockets.length, 2); + assert.equal(p.sockets[1].calls.provide, 1); + assert.equal(p.controller.snapshot().name, "itx.chrome.test.test"); +}); + +void test("a dropped live socket clears its lend and reconnects without replaying actions", async () => { + const p = await panel(); + await p.signedIn(); + await p.sockets[0].browser.cdp(7, "Input.insertText", { text: "one action" }); + await assert.rejects(p.controller.command({ action: "prove" }), /Action interrupted/); + assert.equal(p.sockets[0].calls.actions, 1); + await p.attachForTest(); + p.sockets[0].emit("close"); + await flush(); + assert.notEqual(p.controller.snapshot().phase, "connected"); + p.chrome.debugger.onEvent.emit({ tabId: 7 }, "Runtime.bindingCalled", { + name: "ignored", + payload: "ended", + }); + assert.ok(!p.appends.some((event) => event.type === "ignored")); + await p.tick(3_000); + assert.equal(p.sockets.length, 2); + assert.equal(p.sockets[1].calls.actions, 0); + assert.ok(p.commands.some(([, method]) => method === "detach")); + assert.equal(p.groups[0].title, "iterate.com"); +}); + +void test("sign-out cancels an overload retry and removes the bearer rule", async () => { + const p = await panel(); + p.plans.push({ whoami: () => Promise.reject(overload()) }); + await p.signedIn(); + await p.controller.command({ action: "logout" }); + await p.tick(600_000); + assert.equal(p.sockets.length, 1); + assert.equal(p.timers.size, 0); + assert.notEqual(p.controller.snapshot().phase, "connected"); + assert.equal(p.signOuts(), 1); + assert.deepEqual(JSON.parse(JSON.stringify(p.rules.at(-1))), { removeRuleIds: [1] }); +}); + +void test("a late token after sign-out cannot open a socket or restore a bearer", async () => { + const p = await panel(); + const token = deferred(); + p.token(() => token.promise); + const pending = p.signedIn(); + await flush(); + await p.controller.command({ action: "logout" }); + token.resolve("late-token"); + await pending; + await flush(); + assert.equal(p.sockets.length, 0); + assert.ok(p.rules.every((rule) => !rule.addRules)); + assert.equal(p.storage.refreshedSession, undefined); +}); + +void test("overloads keep retrying for 30 minutes then require Lend again", async () => { + const p = await panel(); + for (let i = 0; i < 100; i += 1) p.plans.push({ whoami: () => Promise.reject(overload()) }); + await p.signedIn(); + const deadline = p.controller.snapshot().recoveryUntil; + assert.equal(deadline, 30 * 60_000); + const waits = []; + while (p.controller.snapshot().phase === "waiting") { + const wait = p.nextWait(); + waits.push(wait); + assert.ok(wait > 0 && wait <= 60_000); + await p.tick(wait); + } + assert.equal(p.now(), deadline); + assert.ok(p.sockets.length > 5); + assert.equal(p.controller.snapshot().phase, "exhausted"); + assert.equal(p.timers.size, 0); + const attempts = p.sockets.length; + await p.tick(600_000); + await p.controller.wake(); + assert.equal(p.sockets.length, attempts); + await p.controller.command({ action: "share" }); + assert.equal(p.controller.snapshot().phase, "waiting"); + assert.equal(p.controller.snapshot().retries, 1); + assert.equal(p.controller.snapshot().recoveryUntil, p.now() + 30 * 60_000); +}); + +void test("close, error and heartbeat failure produce one reconnect", async () => { + const p = await panel(); + await p.signedIn(); + p.sockets[0].emit("error"); + p.sockets[0].emit("close"); + p.sockets[0].emit("close"); + await p.tick(3_000); + assert.equal(p.sockets.length, 2); + assert.equal(p.controller.snapshot().phase, "connected"); +}); + +void test("heartbeat rejection is a failure and an unanswered handshake has a deadline", async () => { + const p = await panel(); + p.plans.push({ + probe: (count) => (count === 1 ? Promise.resolve([]) : Promise.reject(overload())), + }); + await p.signedIn(); + await p.tick(20_000); + assert.notEqual(p.controller.snapshot().phase, "connected"); + assert.equal(p.controller.snapshot().phase, "waiting"); + + const q = await panel(); + q.plans.push({ whoami: () => new Promise(() => {}) }); + const pending = q.signedIn(); + await flush(); + await q.tick(20_000); + await pending; + assert.equal(q.sockets[0].disposed, true); + assert.equal(q.controller.snapshot().phase, "waiting"); +}); + +void test("a displaced lend stops until the person chooses Lend again", async () => { + const p = await panel(); + await p.signedIn(); + p.sockets[0].ended.resolve("replaced"); + await flush(); + assert.notEqual(p.controller.snapshot().phase, "connected"); + await p.tick(600_000); + assert.equal(p.sockets.length, 1); + assert.equal(p.timers.size, 0); + assert.equal(p.controller.snapshot().phase, "displaced"); +}); + +// The mind's API checks the bearer inside the session: a refused one fails the first call. +void test("a bearer that the mind refuses at authenticate waits for the person", async () => { + const p = await panel(); + p.plans.push({ + whoami: () => + Promise.reject( + Object.assign(new Error("no live credential of this mind: sign in again"), { + code: "UNAUTHENTICATED", + }), + ), + }); + await p.signedIn(); + await p.tick(600_000); + assert.equal(p.sockets.length, 1); + assert.equal(p.timers.size, 0); + assert.equal(p.controller.snapshot().phase, "failed"); +}); + +void test("old browser targets refuse actions after recovery and membership remains the grant", async () => { + const p = await panel(); + await p.signedIn(); + const old = p.sockets[0].browser; + p.sockets[0].emit("close"); + await p.tick(3_000); + await assert.rejects(old.tabs(), /connection ended/); + await assert.rejects(old.page(7), /connection ended/); + await assert.rejects(old.openPage({ url: "https://example.com" }), /connection ended/); + await assert.rejects(old.cdp(7, "Input.insertText", { text: "never sent" }), /connection ended/); + await assert.rejects(old.detach(7), /connection ended/); + const current = p.sockets[1].browser; + p.tabs[0].groupId = -1; + await assert.rejects(current.cdp(7, "Input.insertText", { text: "never sent" }), /not in the/); + assert.equal(p.commands.length, 0); +}); + +void test("flapping connections do not reset or prematurely exhaust the recovery window", async () => { + const p = await panel(); + await p.signedIn(); + let deadline; + for (let i = 0; i < 8; i += 1) { + p.sockets.at(-1).emit("close"); + await flush(); + deadline ??= p.controller.snapshot().recoveryUntil; + assert.equal(p.controller.snapshot().recoveryUntil, deadline); + await p.tick(p.nextWait()); + assert.equal(p.controller.snapshot().phase, "connected"); + } + assert.equal(p.sockets.length, 9); + await p.controller.command({ action: "stop" }); + assert.equal(p.timers.size, 0); +}); + +void test("a stable connection resets the retry budget and heartbeat timers do not accumulate", async () => { + const p = await panel(); + await p.signedIn(); + p.sockets[0].emit("close"); + await p.tick(3_000); + await p.tick(60_000); + assert.equal(p.sockets[0].calls.whoami, 1); + assert.equal(p.timers.size, 1); + p.sockets[1].emit("close"); + assert.ok(p.nextWait() <= 2_000); + await p.controller.command({ action: "logout" }); + assert.equal(p.timers.size, 0); +}); + +void test("jitter varies retry waits and honors the server cooldown", async () => { + const waits = []; + for (const random of [0, 0.99]) { + const p = await panel(); + p.random(random); + p.plans.push({ whoami: () => Promise.reject(overload()) }); + await p.signedIn(); + waits.push(p.nextWait()); + } + assert.ok(waits[1] > waits[0]); + const p = await panel(); + p.plans.push({ + whoami: () => + Promise.reject( + Object.assign(new Error("Busy"), { + code: "UNAVAILABLE", + data: { kind: "overloaded", retryAfterMs: 45_000 }, + }), + ), + }); + await p.signedIn(); + assert.equal(p.nextWait(), 45_000); +}); + +void test("a late handshake cannot provide or replace a newer lend", async () => { + const p = await panel(); + const whoami = deferred(); + p.plans.push({ whoami: () => whoami.promise }); + const pending = p.signedIn(); + await flush(); + await p.controller.command({ action: "stop" }); + await p.controller.command({ action: "share" }); + whoami.resolve({ principal: { email: "old@example.com" } }); + await pending; + assert.equal(p.sockets[0].calls.provide, 0); + assert.equal(p.sockets[0].disposed, true); + assert.equal(p.controller.snapshot().name, "itx.chrome.test.test"); +}); + +void test("a failed rotating refresh is not automatically replayed", async () => { + const p = await panel(); + let refreshes = 0; + p.token(() => { + refreshes += 1; + return Promise.reject(new Error("Failed to fetch")); + }); + await p.signedIn(); + await p.tick(600_000); + assert.equal(refreshes, 1); + assert.equal(p.sockets.length, 0); + assert.equal(p.timers.size, 0); +}); + +void test("a failed lend watcher recovers and stale page reports do not cross connections", async () => { + const p = await panel(); + await p.signedIn(); + p.chrome.debugger.onEvent.emit({ tabId: 7 }, "Runtime.bindingCalled", { + name: "report", + payload: "old connection", + }); + p.sockets[0].ended.reject(overload()); + await flush(); + assert.notEqual(p.controller.snapshot().phase, "connected"); + await p.tick(p.nextWait()); + assert.equal(p.sockets.length, 2); + assert.ok(!p.appends.some((event) => event.payload?.payload === "old connection")); +}); + +void test("sign-out during tab membership lookup cannot leave a late debugger attached", async () => { + const p = await panel(); + await p.signedIn(); + const member = deferred(); + p.chrome.tabs.get = () => member.promise; + const action = p.sockets[0].browser.cdp(7, "Input.insertText", { text: "never sent" }); + const refused = assert.rejects(action, /connection ended/); + await flush(); + await p.controller.command({ action: "logout" }); + member.resolve(p.tabs[0]); + await refused; + assert.equal(p.commands.length, 0); +}); + +void test("sign-out during domain setup sends no later CDP setup or input", async () => { + const p = await panel(); + await p.signedIn(); + const enabling = deferred(); + p.chrome.debugger.attach = async () => {}; + p.chrome.debugger.sendCommand = async ({ tabId }, method) => { + p.commands.push([tabId, method]); + if (method === "Page.enable") return enabling.promise; + if (method === "Runtime.evaluate") return { result: { value: "https://example.com" } }; + return {}; + }; + const action = p.sockets[0].browser.cdp(7, "Input.insertText", { text: "never sent" }); + const refused = assert.rejects(action, /connection ended/); + await flush(); + assert.deepEqual(p.commands, [[7, "Page.enable"]]); + const signingOut = p.controller.command({ action: "logout" }); + await flush(); + enabling.resolve({}); + await refused; + await signingOut; + assert.deepEqual(p.commands, [ + [7, "Page.enable"], + [7, "detach"], + ]); +}); + +void test("a rename still saving at sign-out cannot start another connection", async () => { + const p = await panel(); + await p.signedIn(); + const saving = deferred(); + const set = p.chrome.storage.local.set; + p.chrome.storage.local.set = async (values) => { + if (values.browserName) await saving.promise; + return set(values); + }; + const renaming = p.controller.command({ action: "rename", name: "renamed" }); + await flush(); + await p.controller.command({ action: "logout" }); + const connections = p.sockets.length; + saving.resolve(); + await renaming; + assert.equal(p.sockets.length, connections); + assert.notEqual(p.controller.snapshot().phase, "connected"); + assert.equal(p.sockets.length, 1); + assert.equal(p.timers.size, 0); +}); + +for (const stalled of ["Page.enable", "Runtime.addBinding"]) { + void test(`recovery replaces cancelled ${stalled} initialization before it answers`, async () => { + const p = await panel(); + await p.signedIn(); + const enabling = deferred(); + let blocked = false; + p.chrome.debugger.attach = async () => {}; + p.chrome.debugger.sendCommand = async ({ tabId }, method) => { + p.commands.push([tabId, method]); + if (method === stalled && !blocked) { + blocked = true; + return enabling.promise; + } + if (method === "Runtime.evaluate") return { result: { value: "https://example.com" } }; + return {}; + }; + const action = p.sockets[0].browser.cdp(7, "Input.insertText", { text: "never sent" }); + const refused = assert.rejects(action, /connection ended/); + await flush(); + p.sockets[0].emit("close"); + await p.tick(3_000); + assert.equal(p.sockets.length, 2); + assert.equal(p.controller.snapshot().phase, "connected"); + const current = p.sockets[1].browser.cdp(7, "Input.insertText", { text: "fresh connection" }); + current.catch(() => {}); + assert.equal(await Promise.race([current.then(() => true), flush().then(() => false)]), true); + const detached = p.commands.filter(([, method]) => method === "detach").length; + assert.ok(detached > 0); + enabling.resolve({}); + await refused; + assert.equal(p.commands.filter(([, method]) => method === "detach").length, detached); + assert.equal(p.commands.filter(([, method]) => method === "Input.insertText").length, 1); + }); +} + +void test("sign-out during takeover detaches a leftover extension session", async () => { + const p = await panel(); + await p.signedIn(); + const attaching = deferred(); + p.chrome.debugger.attach = () => attaching.promise; + const action = p.sockets[0].browser.cdp(7, "Input.insertText", { text: "never sent" }); + const refused = assert.rejects(action, /connection ended/); + await flush(); + const signingOut = p.controller.command({ action: "logout" }); + await flush(); + attaching.reject(new Error("Another debugger is already attached")); + await refused; + await signingOut; + assert.deepEqual(p.commands, [[7, "detach"]]); +}); + +void test("a teardown deadline cannot let a late detach remove a replacement attachment", async () => { + const p = await panel(); + await p.signedIn(); + await p.attachForTest(); + const detaching = deferred(); + let attaches = 0; + p.chrome.debugger.detach = () => detaching.promise; + p.chrome.debugger.attach = async () => { + attaches += 1; + }; + p.chrome.debugger.sendCommand = async () => ({ result: { value: "https://example.com" } }); + p.sockets[0].emit("close"); + await p.tick(4_000); + assert.equal(p.sockets.length, 2); + const action = p.sockets[1].browser.cdp(7, "Runtime.evaluate", { expression: "1" }); + await flush(); + assert.equal(attaches, 0); + detaching.resolve(); + await action; + assert.equal(attaches, 1); +}); + +void test("Chrome already detached is completed teardown, so recovery can attach again", async () => { + const p = await panel(); + await p.signedIn(); + await p.attachForTest(); + let attaches = 0; + p.chrome.debugger.detach = async () => { + throw new Error("Debugger is not attached to the tab with id: 7."); + }; + p.chrome.debugger.attach = async () => { + attaches += 1; + }; + p.chrome.debugger.sendCommand = async () => ({ result: { value: "https://example.com" } }); + p.sockets[0].emit("close"); + await p.tick(3_000); + await p.sockets[1].browser.cdp(7, "Input.insertText", { text: "fresh connection" }); + assert.equal(attaches, 1); +}); + +void test("retry after a live setup failure waits for its native detach", async () => { + const p = await panel(); + await p.signedIn(); + const detaching = deferred(); + let attaches = 0; + let failed = false; + p.chrome.debugger.attach = async () => { + attaches += 1; + }; + p.chrome.debugger.detach = () => detaching.promise; + p.chrome.debugger.sendCommand = async (_target, method) => { + if (method === "Page.enable" && !failed) { + failed = true; + throw new Error("Setup refused"); + } + return { result: { value: "https://example.com" } }; + }; + const first = assert.rejects( + p.sockets[0].browser.cdp(7, "Input.insertText", { text: "failed" }), + /Setup refused/, + ); + await flush(); + await p.tick(1_000); + await first; + const second = p.sockets[0].browser.cdp(7, "Input.insertText", { text: "explicit retry" }); + await flush(); + assert.equal(attaches, 1); + detaching.resolve(); + await second; + assert.equal(attaches, 2); +}); + +void test("Chrome's detach event completes cancelled teardown", async () => { + const p = await panel(); + await p.signedIn(); + await p.attachForTest(); + let attaches = 0; + p.chrome.debugger.attach = async () => { + attaches += 1; + }; + p.chrome.debugger.sendCommand = async () => ({ result: { value: "https://example.com" } }); + p.chrome.debugger.onDetach.emit({ tabId: 7 }, "target_closed"); + await p.sockets[0].browser.cdp(7, "Input.insertText", { text: "after Chrome detach" }); + assert.equal(attaches, 1); +}); + +function deferred() { + let resolve; + let reject; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} + +function event() { + const listeners = new Set(); + return { + addListener: (listener) => listeners.add(listener), + removeListener: (listener) => listeners.delete(listener), + emit: (...args) => listeners.forEach((listener) => listener(...args)), + }; +} + +function flush() { + return new Promise((resolve) => setImmediate(resolve)); +} +function overload() { + return new Error("Durable Object is overloaded. Requests queued for too long."); +} + +async function panel( + sharedSession = {}, + localStorage = undefined, + shareOnStart = false, + initialNow = 0, +) { + let now = initialNow; + let nextTimer = 0; + const timers = new Map(); + const later = (fn, ms, interval = false) => { + timers.set(++nextTimer, { fn, at: now + ms, ms, interval }); + return nextTimer; + }; + const plans = []; + const sockets = []; + const warnings = []; + const commands = []; + const appends = []; + const session = { issuer: "https://iterate.iterate.com", expiresAt: 3_600_000 }; + const storage = localStorage || { + browserName: "test", + mind: "iterate.com", + "oauth:session": session, + }; + let token = () => Promise.resolve("test-token"); + let signing = () => Promise.resolve(session); + let random = 0.5; + let signOuts = 0; + const rules = []; + const groups = [{ id: 4, windowId: 1, title: "iterate.com" }]; + const tabs = [{ id: 7, groupId: 4, windowId: 1 }]; + class Socket { + listeners = new Map(); + readyState = 0; + disposed = false; + calls = { whoami: 0, provide: 0, actions: 0, probes: 0 }; + plan = plans.shift() ?? {}; + ended = deferred(); + constructor() { + sockets.push(this); + } + addEventListener(type, listener) { + const listeners = this.listeners.get(type) ?? new Set(); + listeners.add(listener); + this.listeners.set(type, listeners); + } + removeEventListener(type, listener) { + this.listeners.get(type)?.delete(listener); + } + emit(type, fields = {}) { + if (type === "close") this.readyState = 3; + this.listeners.get(type)?.forEach((listener) => listener(fields)); + } + close() { + this.emit("close"); + } + } + const chrome = { + storage: { + session: { + get: async () => sharedSession, + set: async (values) => Object.assign(sharedSession, values), + }, + local: { + get: async () => storage, + set: async (values) => Object.assign(storage, values), + remove: async () => {}, + }, + }, + alarms: { create: async () => {}, clear: async () => {} }, + identity: { getRedirectURL: () => "https://test.chromiumapp.org/" }, + runtime: { id: "test", getManifest: () => ({ version: "0.7.0" }) }, + action: { + setBadgeText: async () => {}, + setBadgeBackgroundColor: async () => {}, + setTitle: async () => {}, + }, + declarativeNetRequest: { updateSessionRules: async (rule) => rules.push(rule) }, + tabs: { + onUpdated: event(), + onRemoved: event(), + onReplaced: event(), + get: async (id) => tabs.find((tab) => tab.id === id), + query: async () => tabs, + }, + tabGroups: { + TAB_GROUP_ID_NONE: -1, + query: async () => groups, + get: async (id) => groups.find((group) => group.id === id), + onCreated: event(), + onUpdated: event(), + onRemoved: event(), + }, + debugger: { + onEvent: event(), + onDetach: event(), + getTargets: async () => [{ tabId: 7, url: "https://example.com/", title: "Example" }], + attach: async () => {}, + detach: async ({ tabId }) => commands.push([tabId, "detach"]), + sendCommand: async ({ tabId }, method) => { + commands.push([tabId, method]); + return { result: { value: "https://example.com" } }; + }, + }, + }; + const context = vm.createContext({ + chrome, + fetch: async (url) => { + if (url.endsWith("/.well-known/oauth-authorization-server")) return { ok: true }; + throw new Error("Unexpected fixture fetch"); + }, + navigator: {}, + console: { error: () => {}, warn: (...args) => warnings.push(args), info: () => {} }, + WebSocket: Socket, + AbortController, + AbortSignal, + URL, + Error, + Symbol, + Math: Object.assign(Object.create(Math), { random: () => random }), + Date: class extends Date { + static now() { + return now; + } + }, + setTimeout: (fn, ms) => later(fn, ms), + clearTimeout: (id) => timers.delete(id), + setInterval: (fn, ms) => later(fn, ms, true), + clearInterval: (id) => timers.delete(id), + RpcTarget: class {}, + ChromePage: class {}, + locatorSource: "", + oauthClient: ({ sessions, beforeRefresh }) => ({ + session: async () => storage["oauth:session"], + signIn: async () => { + const next = await signing(); + await sessions.set("oauth:session", next); + return next; + }, + freshAccessToken: async () => { + const stored = await sessions.get("oauth:session"); + if (now >= stored.expiresAt - 30_000) await beforeRefresh?.(); + const accessToken = await token(); + await sessions.set("refreshedSession", accessToken); + return accessToken; + }, + signOut: async () => { + signOuts += 1; + delete storage["oauth:session"]; + }, + }), + newWebSocketRpcSession: (socket) => ({ + whoami: () => { + socket.calls.whoami += 1; + if (socket.plan.whoami) return socket.plan.whoami(socket.calls.whoami); + return Promise.resolve({ mindSlug: "iterate", principal: { email: "test@example.com" } }); + }, + provide: async (_name, browser) => { + socket.calls.provide += 1; + socket.browser = browser; + if (socket.plan.provide) await socket.plan.provide(); + return { lendEnded: () => socket.ended.promise }; + }, + append: async (value) => { + appends.push(value); + }, + invoke: async (steps) => { + if (steps.at(-1)?.[0] === "tabs") { + socket.calls.probes += 1; + if (socket.plan.probe) return socket.plan.probe(socket.calls.probes); + return socket.browser.tabs(); + } + socket.calls.actions += 1; + throw new Error("Action interrupted"); + }, + [Symbol.dispose]: () => { + socket.disposed = true; + socket.close(); + }, + }), + }); + context.disconnectOffscreen = async () => {}; + context.openOffscreenApi = async (_url, current, onFailure) => { + if (!current()) return null; + const socket = new Socket(); + socket.fail = onFailure; + socket.addEventListener("close", () => + onFailure(new Error("The WebSocket connection closed.")), + ); + socket.addEventListener("error", () => + onFailure(new Error("The WebSocket connection failed.")), + ); + return context.newWebSocketRpcSession(socket); + }; + const module = new vm.SourceTextModule(source, { context }); + await module.link(async (specifier) => { + if (specifier === "./instructions.js") + return new vm.SourceTextModule( + readFileSync(new URL("../public/instructions.js", import.meta.url), "utf8"), + { context }, + ); + if (specifier === "./address.js" || specifier === "./profile.js") + return new vm.SourceTextModule( + readFileSync(new URL(`../public/${specifier.slice(2)}`, import.meta.url), "utf8"), + { context }, + ); + const exports = + specifier === "./capnweb.js" + ? ["RpcTarget"] + : specifier === "./offscreen-client.js" + ? ["openOffscreenApi", "disconnectOffscreen"] + : specifier === "./page.js" + ? ["ChromePage"] + : specifier === "./locator-source.js" + ? ["locatorSource"] + : ["oauthClient"]; + return new vm.SyntheticModule( + exports, + function () { + for (const name of exports) this.setExport(name, context[name]); + }, + { context }, + ); + }); + await module.evaluate(); + const controller = module.namespace.createLending(shareOnStart); + await controller.ready; + return { + controller, + sharedSession, + attachForTest: async () => { + await sockets.at(-1).browser.cdp(7, "Runtime.evaluate", { expression: "0" }); + commands.length = 0; + }, + chrome, + storage, + session, + plans, + sockets, + timers, + rules, + groups, + tabs, + commands, + appends, + warnings, + signedIn: () => controller.command({ action: "share" }), + signOuts: () => signOuts, + signing: (get) => { + signing = get; + }, + token: (get) => { + token = get; + }, + random: (value) => { + random = value; + }, + now: () => now, + jump: (ms) => { + now += ms; + }, + nextWait: () => + controller.snapshot().retryAt !== null + ? Math.max(0, controller.snapshot().retryAt - now) + : Math.min(...[...timers.values()].map((timer) => timer.at - now)), + tick: async (ms) => { + await flush(); + const until = now + ms; + for (;;) { + const entry = [...timers] + .filter(([, timer]) => timer.at <= until) + .sort((a, b) => a[1].at - b[1].at)[0]; + if (!entry) break; + const [id, timer] = entry; + now = Math.max(now, timer.at); + if (timer.interval) timer.at += timer.ms; + else timers.delete(id); + timer.fn(); + await flush(); + } + now = until; + await flush(); + }, + }; +} +void test("worker restart preserves an overload deadline and its retry budget", async () => { + const p = await panel(); + p.plans.push({ whoami: () => Promise.reject(overload()) }); + await p.signedIn(); + const saved = structuredClone(p.sharedSession); + const q = await panel(saved, p.storage); + assert.equal(q.sockets.length, 0); + assert.equal(q.controller.snapshot().phase, "waiting"); + assert.equal(q.controller.snapshot().retries, 1); + await q.tick(q.nextWait() - 1); + assert.equal(q.sockets.length, 0); + await q.tick(1); + assert.equal(q.sockets.length, 1); + assert.equal(q.controller.snapshot().retries, 1); + assert.equal(q.sockets[0].calls.actions, 0); +}); + +void test("successive worker losses preserve the original 30-minute recovery deadline", async () => { + let p = await panel(); + await p.signedIn(); + let deadline; + for (let i = 1; i <= 8; i += 1) { + p = await panel(structuredClone(p.sharedSession), p.storage, false, p.now()); + assert.equal(p.controller.snapshot().phase, "waiting"); + assert.equal(p.controller.snapshot().retries, i); + deadline ??= p.controller.snapshot().recoveryUntil; + assert.equal(p.controller.snapshot().recoveryUntil, deadline); + await p.tick(p.nextWait()); + assert.equal(p.sockets.length, 1); + assert.equal(p.controller.snapshot().phase, "connected"); + } + const stopped = await panel(structuredClone(p.sharedSession), p.storage, false, deadline); + assert.equal(stopped.controller.snapshot().phase, "exhausted"); + await stopped.tick(600_000); + await stopped.controller.wake(); + assert.equal(stopped.sockets.length, 0); +}); + +void test("an alarm and timer due together create only one replacement socket", async () => { + const p = await panel(); + await p.signedIn(); + p.sockets[0].emit("close"); + await p.tick(p.nextWait()); + await Promise.all([ + p.controller.wake(), + p.controller.wake(), + p.controller.command({ action: "state" }), + ]); + assert.equal(p.sockets.length, 2); + assert.equal(p.sockets[1].calls.provide, 1); +}); + +void test("browser restart keeps authentication but sharing is off until an explicit request", async () => { + const p = await panel(); + await p.signedIn(); + assert.equal(p.storage.sharingRequested, true); + const restarted = await panel({}, p.storage); + assert.equal(restarted.controller.snapshot().signedIn, true); + assert.equal(restarted.controller.snapshot().sharing, false); + await restarted.tick(600_000); + await restarted.controller.wake(); + await restarted.controller.command({ action: "state" }); + assert.equal(restarted.sockets.length, 0); + await restarted.signedIn(); + assert.equal(restarted.sockets.length, 1); + const optedIn = await panel({}, p.storage, true); + assert.equal(optedIn.sockets.length, 1); +}); + +void test("sleep during rotating refresh cannot automatically replay a token request", async () => { + const p = await panel({ + lending: { + sharing: true, + issuer: "https://iterate.iterate.com", + phase: "refreshing", + retries: 2, + }, + }); + await p.tick(600_000); + await p.controller.wake(); + assert.equal(p.sockets.length, 0); + assert.equal(p.controller.snapshot().phase, "failed"); +}); + +void test("opening multiple panel views does not connect or call the mind", async () => { + const p = await panel(); + await p.signedIn(); + let observations = 0; + const stop = p.controller.subscribe(() => { + observations += 1; + }); + await Promise.all(Array.from({ length: 20 }, () => p.controller.command({ action: "state" }))); + await p.tick(60_000); + stop(); + assert.ok(observations > 0); + assert.equal(p.sockets.length, 1); + assert.equal(p.sockets[0].calls.whoami, 1); + assert.equal(p.sockets[0].calls.probes, 4); // setup, then every20seconds + assert.equal(p.sockets[0].calls.provide, 1); + assert.equal(p.sockets[0].calls.actions, 0); +}); + +void test("worker restart cleans up only recorded debugger targets before restoring a lend", async () => { + const p = await panel({ + debuggeeIds: [7], + lending: { + sharing: true, + issuer: "https://iterate.iterate.com", + phase: "connected", + retries: 0, + }, + }); + assert.deepEqual( + p.commands.filter(([, method]) => method === "detach"), + [[7, "detach"]], + ); + assert.equal(p.sharedSession.debuggeeIds.length, 0); + await p.tick(p.nextWait()); + assert.equal(p.sockets.length, 1); +}); + +void test("turning sharing off cancels recovery across worker wake and keeps tab groups", async () => { + const p = await panel(); + p.plans.push({ whoami: () => Promise.reject(overload()) }); + await p.signedIn(); + await p.controller.command({ action: "stop" }); + const q = await panel(structuredClone(p.sharedSession), p.storage); + await q.tick(600_000); + await q.controller.wake(); + assert.equal(q.controller.snapshot().phase, "off"); + assert.equal(q.sockets.length, 0); + assert.equal(q.groups[0].title, "iterate.com"); +}); + +void test("crossing the refresh cutoff during token acquisition cannot replay after worker loss", async () => { + const p = await panel({}, undefined, false, 3_569_999); + const token = deferred(); + let requests = 0; + p.token(() => { + requests += 1; + return token.promise; + }); + const reading = deferred(); + const get = p.chrome.storage.local.get; + p.chrome.storage.local.get = async (key) => { + if (key === "oauth:session") await reading.promise; + return get(key); + }; + const pending = p.signedIn(); + await flush(); + await p.tick(2); + reading.resolve(); + await flush(); + assert.equal(p.sharedSession.lending.phase, "refreshing"); + const saved = structuredClone(p.sharedSession); + await p.controller.command({ action: "stop" }); + token.resolve("late-token"); + await pending; + const q = await panel(saved, p.storage, false, 3_570_001); + await q.tick(600_000); + await q.controller.wake(); + assert.equal(requests, 1); + assert.equal(q.sockets.length, 0); + assert.equal(q.controller.snapshot().phase, "failed"); +}); + +void test("sign-out fences an unfinished sign-in and blocks a competing login until it settles", async () => { + const p = await panel(); + const signing = deferred(); + p.signing(() => signing.promise); + const pending = p.controller.command({ action: "login", mind: "iterate.com" }); + const refused = assert.rejects(pending, /Sharing ended|sign-in ended/); + await flush(); + await p.controller.command({ action: "logout" }); + await assert.rejects( + p.controller.command({ action: "login", mind: "iterate.com" }), + /current sign-in/, + ); + signing.resolve(p.session); + await refused; + assert.equal(p.storage["oauth:session"], undefined); + assert.equal(p.controller.snapshot().signedIn, false); + p.signing(() => Promise.resolve(p.session)); + await p.controller.command({ action: "login", mind: "iterate.com" }); + assert.equal(p.controller.snapshot().signedIn, true); + assert.equal(p.controller.snapshot().sharing, false); +}); + +void test("a stale in-memory expiry does not turn cached-token recovery into an interrupted refresh", async () => { + const p = await panel(); + await p.signedIn(); + const cached = deferred(); + p.token(() => cached.promise); + p.session.expiresAt = -1; + p.storage["oauth:session"] = { ...p.session, expiresAt: 3_600_000 }; + p.sockets[0].emit("close"); + await p.tick(3_000); + assert.equal(p.sharedSession.lending.phase, "connecting"); + const saved = structuredClone(p.sharedSession); + await p.controller.command({ action: "stop" }); + cached.resolve("cached-token"); + await flush(); + const q = await panel(saved, p.storage); + assert.equal(q.controller.snapshot().phase, "waiting"); + await q.tick(q.nextWait()); + assert.equal(q.controller.snapshot().phase, "connected"); +}); + +for (const grouped of [true, false]) + void test(`openPage uses an existing normal window without a current window (group=${grouped})`, async () => { + const p = await panel(); + await p.signedIn(); + if (!grouped) p.groups.length = 0; + p.chrome.windows = { + getCurrent: async () => { + throw new Error("No current window"); + }, + getAll: async () => [{ id: 1 }], + }; + let created; + p.chrome.tabs.create = async (options) => { + created = options; + const tab = { id: 8, windowId: options.windowId, groupId: -1, status: "complete" }; + p.tabs.push(tab); + return tab; + }; + p.chrome.tabs.group = async (options) => { + const id = options.groupId ?? 5; + if (!p.groups.some((group) => group.id === id)) + p.groups.push({ id, windowId: options.createProperties.windowId, title: "" }); + p.tabs.find((tab) => tab.id === 8).groupId = id; + return id; + }; + p.chrome.tabGroups.update = async (id, change) => + Object.assign( + p.groups.find((group) => group.id === id), + change, + ); + const opened = await p.sockets[0].browser.openPage({ url: "https://fixture.test/form" }); + assert.equal(opened.tabId, 8); + assert.equal(created.windowId, 1); + assert.equal( + p.groups.find((group) => group.id === p.tabs.find((tab) => tab.id === 8).groupId).title, + "iterate.com", + ); + }); +void test("openPage asks for a browser window when none exists without creating a tab", async () => { + const p = await panel(); + await p.signedIn(); + p.groups.length = 0; + p.chrome.windows = { + getCurrent: async () => { + throw new Error("No current window"); + }, + getAll: async () => [], + }; + let created = 0; + p.chrome.tabs.create = async () => { + created += 1; + }; + await assert.rejects( + p.sockets[0].browser.openPage({ url: "https://fixture.test/form" }), + /Open a Chrome window/, + ); + assert.equal(created, 0); +}); + +for (const failureAt of ["provide", "lendEnded"]) + void test(`deploy incident:1006,redial,pager cut,${failureAt} overload recovers after17minutes`, async () => { + const p = await panel(); + await p.signedIn(); + await p.sockets[0].browser.cdp(7, "Input.insertText", { text: "one authorized action" }); + p.sockets[0].emit("close", { code: 1006 }); + await p.tick(p.nextWait()); + assert.equal(p.sockets.length, 2); + assert.equal(p.sockets[1].calls.provide, 1); + const busy = () => + Object.assign(overload(), { code: "UNAVAILABLE", data: { kind: "overloaded" } }); + if (failureAt === "provide") p.plans.push({ provide: () => Promise.reject(busy()) }); + p.sockets[1].emit("close", { code: 1006, reason: "responseStreamDisconnected" }); + await p.tick(p.nextWait()); + if (failureAt === "lendEnded") { + p.sockets[2].ended.reject(busy()); + await flush(); + } + const deadline = p.controller.snapshot().recoveryUntil; + assert.equal(p.controller.snapshot().phase, "waiting"); + while (p.now() < 17 * 60_000) { + p.plans.push({ provide: () => Promise.reject(busy()) }); + await p.tick(p.nextWait()); + assert.equal(p.controller.snapshot().phase, "waiting"); + assert.equal(p.controller.snapshot().recoveryUntil, deadline); + } + assert.ok(p.sockets.length > 5); + await p.tick(p.nextWait()); + assert.equal(p.controller.snapshot().phase, "connected"); + assert.equal(p.sockets.at(-1).calls.provide, 1); + assert.equal(p.commands.filter(([, method]) => method === "Input.insertText").length, 1); + assert.ok(p.sockets.every((socket) => socket.calls.actions === 0)); + }); + +for (const data of [undefined, { kind: "not-yet-known" }]) + void test(`generic UNAVAILABLE keeps retrying (data=${JSON.stringify(data)})`, async () => { + const p = await panel(); + p.plans.push({ + provide: () => + Promise.reject( + Object.assign(new Error("Temporarily unavailable"), { code: "UNAVAILABLE", data }), + ), + }); + await p.signedIn(); + assert.equal(p.controller.snapshot().phase, "waiting"); + await p.tick(p.nextWait()); + assert.equal(p.controller.snapshot().phase, "connected"); + }); +void test("server cooldown longer than app backoff is respected within the recovery window", async () => { + const p = await panel(); + p.plans.push({ + provide: () => + Promise.reject( + Object.assign(overload(), { + code: "UNAVAILABLE", + data: { kind: "overloaded", retryAfterMs: 90_000 }, + }), + ), + }); + await p.signedIn(); + assert.equal(p.nextWait(), 90_000); + await p.tick(89_999); + assert.equal(p.sockets.length, 1); + await p.tick(1); + assert.equal(p.sockets.length, 2); + assert.equal(p.controller.snapshot().phase, "connected"); +}); +void test("an outage deadline restored during worker sleep ends recovery without another socket", async () => { + const p = await panel( + { + lending: { + sharing: true, + issuer: "https://iterate.iterate.com", + phase: "waiting", + retries: 40, + retryAt: 1_800_000, + recoveryUntil: 1_800_000, + }, + }, + undefined, + false, + 1_800_001, + ); + assert.equal(p.controller.snapshot().phase, "exhausted"); + assert.equal(p.sockets.length, 0); + assert.equal(p.timers.size, 0); +}); +void test("a minute of stable connection starts a fresh window for the next outage", async () => { + const p = await panel(); + await p.signedIn(); + p.sockets[0].emit("close"); + await p.tick(p.nextWait()); + const first = p.controller.snapshot().recoveryUntil; + await p.tick(60_000); + assert.equal(p.controller.snapshot().recoveryUntil, null); + p.sockets[1].emit("close"); + await flush(); + assert.equal(p.controller.snapshot().retries, 1); + assert.ok(p.controller.snapshot().recoveryUntil > first); +}); + +void test("a successful provide with an unavailable stub is not shown as connected", async () => { + const p = await panel(); + const phases = []; + p.controller.subscribe((state) => phases.push(state.phase)); + p.plans.push({ + probe: () => + Promise.reject(Object.assign(new Error("Stub offline"), { code: "RPC_STUB_OFFLINE" })), + }); + await p.signedIn(); + assert.equal(p.sockets[0].calls.provide, 1); + assert.equal(p.sockets[0].calls.probes, 1); + assert.equal(p.controller.snapshot().phase, "waiting"); + assert.ok(!phases.includes("connected")); + await p.tick(p.nextWait()); + assert.equal(p.controller.snapshot().phase, "connected"); +}); +void test("the lend heartbeat detects a failed pager while the outer API remains healthy", async () => { + const p = await panel(); + p.plans.push({ + probe: (count) => + count === 1 + ? Promise.resolve([]) + : Promise.reject( + Object.assign(overload(), { code: "UNAVAILABLE", data: { kind: "overloaded" } }), + ), + }); + await p.signedIn(); + await p.sockets[0].browser.cdp(7, "Input.insertText", { text: "once" }); + await p.tick(20_000); + assert.equal(p.sockets[0].calls.whoami, 1); + assert.equal(p.sockets[0].calls.probes, 2); + assert.equal(p.controller.snapshot().phase, "waiting"); + await p.tick(p.nextWait()); + assert.equal(p.controller.snapshot().phase, "connected"); + assert.equal(p.commands.filter(([, method]) => method === "Input.insertText").length, 1); +}); +void test("resolved offline pager notices recover without requiring a new API close", async () => { + const p = await panel(); + await p.signedIn(); + p.sockets[0].ended.resolve("went offline (its pager dropped and could not be re-dialed)"); + await flush(); + assert.equal(p.controller.snapshot().phase, "waiting"); + await p.tick(p.nextWait()); + assert.equal(p.sockets.length, 2); + assert.equal(p.controller.snapshot().phase, "connected"); +}); +for (const reason of ["was returned (its pager closed)", "was recalled by its lender"]) + void test(`explicit terminal lend stays manual: ${reason}`, async () => { + const p = await panel(); + await p.signedIn(); + p.sockets[0].ended.resolve(reason); + await flush(); + assert.equal(p.controller.snapshot().phase, "displaced"); + await p.tick(31 * 60_000); + assert.equal(p.sockets.length, 1); + assert.equal(p.timers.size, 0); + }); + +void test("a late restored retry callback cannot replace a healthy recovered lend", async () => { + const p = await panel({ + lending: { + sharing: true, + issuer: "https://iterate.iterate.com", + phase: "waiting", + retries: 12, + retryAt: 10_000, + recoveryUntil: 1_800_000, + }, + }); + const callback = [...p.timers.values()].find((timer) => timer.at === 10_000).fn; + await p.tick(10_000); + assert.equal(p.controller.snapshot().phase, "connected"); + callback(); + await flush(); + assert.equal(p.sockets.length, 1); + assert.equal(p.sockets[0].disposed, false); +}); +void test("a server cooldown past the recovery deadline ends with no premature retry", async () => { + const p = await panel(); + p.plans.push({ + provide: () => + Promise.reject( + Object.assign(overload(), { + code: "UNAVAILABLE", + data: { kind: "overloaded", retryAfterMs: 3_600_000 }, + }), + ), + }); + await p.signedIn(); + assert.equal(p.nextWait(), 30 * 60_000); + await p.tick(30 * 60_000); + assert.equal(p.controller.snapshot().phase, "exhausted"); + assert.equal(p.sockets.length, 1); + assert.equal(p.timers.size, 0); +}); + +void test("a sleeping worker cannot reset recovery with an overdue health timer", async () => { + const p = await panel(); + await p.signedIn(); + p.sockets[0].emit("close"); + await p.tick(p.nextWait()); + const deadline = p.controller.snapshot().recoveryUntil; + p.jump(120_000); + await p.tick(0); + assert.equal(p.sockets[1].calls.probes, 2); // one setup and one late check, no catch-up + assert.equal(p.controller.snapshot().retries, 1); + assert.equal(p.controller.snapshot().recoveryUntil, deadline); + await p.tick(40_000); + assert.equal(p.controller.snapshot().retries, 1); + await p.tick(20_000); + assert.equal(p.controller.snapshot().retries, 0); +}); +void test("one heartbeat stays in flight and schedules the next after its reply", async () => { + const p = await panel(); + const reply = deferred(); + p.plans.push({ probe: (count) => (count === 2 ? reply.promise : Promise.resolve([])) }); + await p.signedIn(); + await p.tick(20_000); + assert.equal(p.sockets[0].calls.probes, 2); + await p.tick(14_999); + assert.equal(p.sockets[0].calls.probes, 2); + reply.resolve([]); + await flush(); + await p.tick(19_999); + assert.equal(p.sockets[0].calls.probes, 2); + await p.tick(1); + assert.equal(p.sockets[0].calls.probes, 3); +}); +void test("a reply queued after sleep cannot beat an expired heartbeat deadline", async () => { + const p = await panel(); + const reply = deferred(); + p.plans.push({ probe: (count) => (count === 2 ? reply.promise : Promise.resolve([])) }); + await p.signedIn(); + await p.tick(20_000); + p.jump(15_001); + reply.resolve([]); + await flush(); + assert.equal(p.controller.snapshot().phase, "waiting"); + assert.equal(p.sockets[0].disposed, true); + const probes = p.sockets[0].calls.probes; + await p.tick(p.nextWait() - 1); + assert.equal(p.sockets[0].calls.probes, probes); +}); +void test("a late setup reply cannot provide after the whole setup deadline", async () => { + const p = await panel(); + const identity = deferred(); + p.plans.push({ whoami: () => identity.promise }); + const pending = p.signedIn(); + await flush(); + p.jump(20_001); + identity.resolve({ principal: { email: "late@example.test" } }); + await pending; + assert.equal(p.sockets[0].calls.provide, 0); + assert.equal(p.controller.snapshot().phase, "waiting"); +}); +void test("the setup bound includes the alarm prerequisite and fences its late completion", async () => { + const p = await panel(); + const alarm = deferred(); + p.chrome.alarms.create = () => alarm.promise; + const pending = p.signedIn(); + await flush(); + await p.tick(20_000); + await pending; + assert.equal(p.controller.snapshot().phase, "failed"); + assert.equal(p.sockets.length, 0); + alarm.resolve(); + await flush(); + assert.equal(p.sockets.length, 0); +}); + +for (const code of ["UNAUTHORIZED", "FORBIDDEN"]) + void test(`worker restart preserves terminal authentication refusal: ${code}`, async () => { + const p = await panel(); + p.plans.push({ + provide: () => Promise.reject(Object.assign(new Error("Grant refused"), { code })), + }); + await p.signedIn(); + const q = await panel(structuredClone(p.sharedSession), p.storage, false, p.now()); + await q.tick(31 * 60_000); + await q.controller.wake(); + assert.equal(q.controller.snapshot().phase, "failed"); + assert.equal(q.sockets.length, 0); + }); +void test("worker restart preserves an explicitly returned lend", async () => { + const p = await panel(); + await p.signedIn(); + p.sockets[0].ended.resolve("was returned (its pager closed)"); + await flush(); + const q = await panel(structuredClone(p.sharedSession), p.storage, false, p.now()); + await q.tick(31 * 60_000); + await q.controller.wake(); + assert.equal(q.controller.snapshot().phase, "displaced"); + assert.equal(q.sockets.length, 0); +}); +void test("late alarms, panel requests and restored timer callbacks share one in-flight setup", async () => { + const p = await panel({ + lending: { + sharing: true, + issuer: "https://iterate.iterate.com", + phase: "waiting", + retries: 12, + retryAt: 10_000, + recoveryUntil: 1_800_000, + }, + }); + const retry = [...p.timers.values()].find((timer) => timer.at === 10_000).fn; + const identity = deferred(); + p.plans.push({ whoami: () => identity.promise }); + p.jump(60_000); + const waking = p.controller.wake(); + await flush(); + retry(); + await Promise.all([ + p.controller.wake(), + p.controller.command({ action: "share" }), + p.controller.command({ action: "state" }), + ]); + assert.equal(p.sockets.length, 1); + assert.equal(p.sockets[0].calls.whoami, 1); + assert.equal(p.controller.snapshot().retries, 12); + identity.resolve({ principal: { email: "fixture@example.test" } }); + await waking; + await p.tick(0); + assert.equal(p.sockets.length, 1); + assert.equal(p.controller.snapshot().phase, "connected"); +}); + +void test("a bearer-rule write resolved after the setup deadline cannot open a socket", async () => { + const p = await panel(); + const write = deferred(); + p.chrome.declarativeNetRequest.updateSessionRules = async (rule) => { + p.rules.push(rule); + if (rule.addRules) await write.promise; + }; + const pending = p.signedIn(); + await flush(); + p.jump(20_001); + write.resolve(); + await pending; + assert.equal(p.sockets.length, 0); + assert.equal(p.controller.snapshot().phase, "waiting"); +}); + +for (const failure of ["overloaded", "disconnected"]) + for (const random of [0, 0.5, 0.999]) + void test(`capped ${failure} recovery stays near one attempt per minute across restart (jitter=${random})`, async () => { + const busy = () => + failure === "overloaded" ? overload() : new Error("The WebSocket disconnected."); + const p = await panel(); + p.random(random); + for (let i = 0; i < 8; i += 1) p.plans.push({ provide: () => Promise.reject(busy()) }); + await p.signedIn(); + while (p.controller.snapshot().retries < 7) await p.tick(p.nextWait()); + const deadline = p.controller.snapshot().recoveryUntil; + assert.ok(p.nextWait() >= 54_000 && p.nextWait() <= 60_000, String(p.nextWait())); + const saved = structuredClone(p.sharedSession); + const q = await panel(saved, p.storage, false, p.now()); + q.random(random); + q.plans.push({ provide: () => Promise.reject(busy()) }); + await q.controller.wake(); + await q.tick(q.nextWait() - 1); + assert.equal(q.sockets.length, 0); + await q.tick(1); + assert.equal(q.sockets.length, 1); + assert.equal(q.controller.snapshot().retries, 8); + assert.equal(q.controller.snapshot().recoveryUntil, deadline); + assert.ok(q.nextWait() >= 54_000 && q.nextWait() <= 60_000, String(q.nextWait())); + await q.controller.wake(); + assert.equal(q.sockets.length, 1); + }); + +for (const name of ["prototype", "constructor"]) + void test(`reserved principal ${name} uses a valid lend segment and cannot be chosen as browser name`, async () => { + const p = await panel(); + p.plans.push({ whoami: async () => ({ principal: { email: `${name}@example.test` } }) }); + await p.signedIn(); + assert.equal(p.controller.snapshot().name, "itx.chrome.member.test"); + await assert.rejects(p.controller.command({ action: "rename", name }), /reserved/); + assert.equal(p.sockets.length, 1); + }); + +void test("normal token expiry obtains a fresh token without replay or a platform-failure warning", async () => { + const p = await panel(); + await p.signedIn(); + await p.sockets[0].browser.cdp(7, "Input.insertText", { text: "once" }); + await p.tick(3_600_000); + let refreshed = 0; + p.token(async () => { + refreshed += 1; + return "fresh-fixture-token"; + }); + p.sockets[0].fail(Object.assign(new Error("The API token expired."), { code: "TOKEN_EXPIRED" })); + await p.tick(p.nextWait()); + assert.equal(refreshed, 1); + assert.equal(p.controller.snapshot().phase, "connected"); + assert.equal(p.sockets.length, 2); + assert.equal( + p.warnings.filter(([record]) => record?.event === "browser-extension.platform-failure-retry") + .length, + 0, + ); + assert.equal(p.commands.filter(([, method]) => method === "Input.insertText").length, 1); +});
A test/profile.test.ts
@@ -0,0 +1,96 @@ +// What the extension takes from a mind's profile (public/profile.js): a name and a logo to show +// beside the address, and nothing that the owner's own words could use against the person. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { mindAddressOf, mindProfileOf, readMindProfile } from "../public/profile.js"; + +const issuer = "https://iterate.example.com"; +/** What `readMindProfile` answers while the website answers `answer`, and what it asked. */ +async function readWith(answer: () => Response) { + const asked: { url: string; init: RequestInit }[] = []; + const realFetch = globalThis.fetch; + globalThis.fetch = async (url, init = {}) => { + asked.push({ url: String(url), init }); + return answer(); + }; + try { + return { profile: await readMindProfile(issuer), asked }; + } finally { + globalThis.fetch = realFetch; + } +} + +void test("the address is the issuer's hostname without its iterate label", () => { + assert.equal(mindAddressOf(issuer), "example.com"); + assert.equal(mindAddressOf("https://control.example.com:8443"), "control.example.com"); +}); + +void test("a named mind with a logo on its own website keeps both", () => { + assert.deepEqual( + mindProfileOf({ name: "Ada's mind", icon: "https://example.com/favicon.svg" }, issuer), + { name: "Ada's mind", icon: "https://example.com/favicon.svg" }, + ); + assert.equal( + mindProfileOf({ icon: "https://dash.example.com/icon.svg" }, issuer).icon, + "https://dash.example.com/icon.svg", + ); +}); + +void test("a mind that gave itself no name has none: the profile's default is its hostname", () => { + for (const name of ["example.com", "Example.COM", "iterate.example.com", "", " ", 7, null]) + assert.equal(mindProfileOf({ name }, issuer).name, "", String(name)); + assert.deepEqual(mindProfileOf(null, issuer), { name: "", icon: null }); +}); + +void test("a name is one bounded line with no character that reorders the text after it", () => { + assert.equal( + mindProfileOf({ name: " Ada\n\u202emoc.elgoog\u2066\t mind " }, issuer).name, + "Ada moc.elgoog mind", + ); + assert.equal(mindProfileOf({ name: "x".repeat(500) }, issuer).name.length, 80); + // markup stays text: the panel escapes it and the label writes it as textContent + assert.equal(mindProfileOf({ name: "<img src=x>" }, issuer).name, "<img src=x>"); +}); + +void test("a logo that is not an https address on the mind's own hosts is not shown", () => { + for (const icon of [ + "http://example.com/favicon.svg", + "https://evil.test/favicon.svg", + "https://notexample.com/favicon.svg", + "https://example.com.evil.test/favicon.svg", + "https://user:secret@example.com/favicon.svg", + "https://example.com:8443/favicon.svg", + "javascript:alert(1)", + "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'/>", + "/favicon.svg", + `https://example.com/${"x".repeat(3000)}`, + { href: "https://example.com/favicon.svg" }, + null, + ]) + assert.equal(mindProfileOf({ name: "Ada", icon }, issuer).icon, null, String(icon)); +}); + +void test("the profile is read from the mind's website, with no credential and no referrer", async () => { + const { profile, asked } = await readWith(() => + Response.json({ name: "Ada", description: "x", icon: "https://example.com/favicon.svg" }), + ); + assert.deepEqual(profile, { name: "Ada", icon: "https://example.com/favicon.svg" }); + assert.equal(asked.length, 1); + assert.equal(asked[0].url, "https://example.com/.well-known/iterate-profile"); + assert.equal(asked[0].init.credentials, "omit"); + assert.equal(asked[0].init.redirect, "error"); + assert.equal(asked[0].init.referrerPolicy, "no-referrer"); +}); + +void test("a website that answers no profile gives none", async () => { + for (const answer of [ + () => new Response("Not found\n", { status: 404 }), + () => new Response("<!doctype html>"), + () => Response.json(["Ada"]), + () => Response.json({ name: "Ada", description: "x".repeat(20_000) }), + () => { + throw new TypeError("Failed to fetch"); + }, + ]) + assert.equal((await readWith(answer)).profile, null); +});
A test/worker.test.ts
@@ -0,0 +1,133 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; +import vm from "node:vm"; + +void test("only the extension panel controls one worker-owned controller; closing it only unsubscribes", async () => { + const onConnect = event(); + const onStartup = event(); + const onInstalled = event(); + const onAlarm = event(); + const commands = []; + const transportPorts = []; + const settings = []; + const subscribers = new Set(); + let wakes = 0; + const context = vm.createContext({ + console, + chrome: { + runtime: { + id: "fixture", + getURL: (path) => `chrome-extension://fixture/${path}`, + onConnect, + onStartup, + onInstalled, + }, + alarms: { onAlarm }, + sidePanel: { setPanelBehavior: async () => {} }, + }, + }); + const controller = { + ready: Promise.resolve(), + snapshot: () => ({ phase: "off" }), + command: async (message) => { + commands.push(message); + return { phase: "off" }; + }, + subscribe: (listener) => { + subscribers.add(listener); + return () => subscribers.delete(listener); + }, + wake: async () => { + wakes += 1; + }, + }; + const module = new vm.SourceTextModule( + readFileSync(new URL("../public/background.js", import.meta.url), "utf8"), + { context }, + ); + await module.link(async (specifier) => + specifier === "./offscreen-client.js" + ? new vm.SyntheticModule( + ["acceptOffscreenPort"], + function () { + this.setExport("acceptOffscreenPort", (port) => transportPorts.push(port)); + }, + { context }, + ) + : new vm.SyntheticModule( + ["createLending"], + function () { + this.setExport("createLending", (setting) => { + settings.push(setting); + return controller; + }); + }, + { context }, + ), + ); + await module.evaluate(); + assert.deepEqual(settings, [false]); + const transport = port({ id: "fixture", url: "chrome-extension://fixture/offscreen.html" }); + transport.name = "offscreen-transport"; + onConnect.emit(transport); + assert.deepEqual(transportPorts, [transport]); + assert.equal(subscribers.size, 0); + for (const sender of [ + { id: "other", url: "chrome-extension://fixture/index.html" }, + { id: "fixture", url: "https://page.test" }, + { id: "fixture", url: "chrome-extension://fixture/other.html" }, + ]) { + const rejected = port(sender); + onConnect.emit(rejected); + assert.equal(rejected.disconnected, true); + } + const panel = port({ id: "fixture", url: "chrome-extension://fixture/index.html" }); + const other = port({ id: "fixture", url: "chrome-extension://fixture/index.html" }); + onConnect.emit(panel); + onConnect.emit(other); + assert.equal(subscribers.size, 2); + panel.onMessage.emit({ id: 1, action: "state" }); + panel.onMessage.emit({ id: "invalid", action: "share" }); + await new Promise((resolve) => setImmediate(resolve)); + assert.deepEqual(commands, [{ id: 1, action: "state" }]); + assert.equal(panel.messages[0].state.phase, "off"); + panel.disconnect(); + assert.equal(subscribers.size, 1); + assert.equal(commands.length, 1); + onStartup.emit(); + onInstalled.emit(); + onAlarm.emit({ name: "unrelated" }); + onAlarm.emit({ name: "iterate-lending" }); + assert.equal(wakes, 1); + assert.equal(settings.length, 1); + other.disconnect(); + assert.equal(subscribers.size, 0); +}); + +function event() { + const listeners = new Set(); + return { + addListener: (listener) => listeners.add(listener), + emit: (...args) => { + for (const listener of listeners) listener(...args); + }, + }; +} +function port(sender) { + return { + name: "panel", + sender, + onMessage: event(), + onDisconnect: event(), + disconnected: false, + messages: [], + postMessage(message) { + this.messages.push(message); + }, + disconnect() { + this.disconnected = true; + this.onDisconnect.emit(); + }, + }; +}
A tsconfig.json
@@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2024", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2024", "DOM"], + "types": ["node"], + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "erasableSyntaxOnly": true, + "noUncheckedSideEffectImports": true, + "allowImportingTsExtensions": true, + "resolveJsonModule": true + }, + "include": ["scripts", "src"] +}
A vitest.config.ts
@@ -0,0 +1,13 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + // Each file launches Chromium; keep browser load bounded within the parallel workspace job. + fileParallelism: false, + testTimeout: 20_000, + restoreMocks: true, + unstubGlobals: true, + unstubEnvs: true, + chaiConfig: { truncateThreshold: 0 }, + }, +});