packages/ui of iterate/private at 7efba8ca09e199e410984f2a081b45564de0d2a9
Jonas Templestein, 2026-11-26 12:56 UTC · 5ec5c8702eca7ec6e243f7a80b492059ff52aaba · the first commit
414 files changed
- A AGENTS.md
- A LICENSE
- A README.md
- A browser-entries.ts
- A components.json
- A doctor.config.mjs
- A examples/README.md
- A examples/agent-chat-page.ts
- A examples/any-website.html
- A examples/change-my-mind.html
- A examples/events-chart-page.ts
- A examples/mind-host-page.ts
- A package.json
- A registry.json
- A scripts/build-agent-kind-view-frame.ts
- A scripts/build-docs-tree.ts
- A scripts/build-iterate-css.ts
- A scripts/check-docs-editor-css.ts
- A scripts/component-tokens.test.ts
- A scripts/component-tokens.ts
- A scripts/iterate-look.test.ts
- A scripts/iterate-look.ts
- A scripts/stylesheet-order.test.ts
- A scripts/stylesheet-order.ts
- A src/agent-kind-view/bridge.test.ts
- A src/agent-kind-view/bridge.ts
- A src/agent-kind-view/call-presence.ts
- A src/agent-kind-view/dash-agent-calls.test.ts
- A src/agent-kind-view/dash-agent-calls.ts
- A src/agent-kind-view/dash-agents.test.tsx
- A src/agent-kind-view/dash-agents.tsx
- A src/agent-kind-view/dash-call.tsx
- A src/agent-kind-view/dash-share.tsx
- A src/agent-kind-view/default-kind.test.ts
- A src/agent-kind-view/default-kind.ts
- A src/agent-kind-view/frame-view.test.tsx
- A src/agent-kind-view/frame-view.tsx
- A src/agent-kind-view/frame.ts
- A src/agent-kind-view/host.test.ts
- A src/agent-kind-view/host.ts
- A src/agent-kind-view/kit.ts
- A src/agent-kind-view/load.test.ts
- A src/agent-kind-view/load.ts
- A src/agent-kind-view/types.ts
- A src/apps/base-path.ts
- A src/apps/document.test.tsx
- A src/apps/document.tsx
- A src/apps/head.ts
- A src/apps/providers.tsx
- A src/apps/router.tsx
- A src/apps/server.test.ts
- A src/apps/server.ts
- A src/asset-modules.d.ts
- A src/browser/agent-kind-view-frame.ts
- A src/browser/change-my-mind.test.ts
- A src/browser/change-my-mind.ts
- A src/browser/chunks.test.ts
- A src/browser/docs-editor-look.css
- A src/browser/docs-editor.css
- A src/browser/icons.ts
- A src/browser/iterate.css
- A src/browser/live.ts
- A src/browser/member-itx.test.tsx
- A src/browser/member-itx.ts
- A src/browser/page.ts
- A src/browser/query.ts
- A src/browser/react-compiler-runtime.ts
- A src/browser/react-dom-client.ts
- A src/browser/react-dom.ts
- A src/browser/react-jsx-runtime.ts
- A src/browser/react-modules.test.ts
- A src/browser/react.ts
- A src/browser/styles.css
- A src/browser/stylesheet.css
- A src/components/agent-chat/AGENTS.md
- A src/components/agent-chat/agent-chat-search.ts
- A src/components/agent-chat/agent-chat.test.tsx
- A src/components/agent-chat/agent-chat.tsx
- A src/components/agent-chat/agent-event-inspectors.tsx
- A src/components/agent-chat/agent-events.test.ts
- A src/components/agent-chat/agent-events.ts
- A src/components/agent-chat/agent-facts.test.ts
- A src/components/agent-chat/agent-facts.ts
- A src/components/agent-chat/agent-feed-list.tsx
- A src/components/agent-chat/agent-feed.tsx
- A src/components/agent-chat/agent-inspectors.tsx
- A src/components/agent-chat/agent-live-activity.test.tsx
- A src/components/agent-chat/agent-page-header.test.tsx
- A src/components/agent-chat/agent-page-header.tsx
- A src/components/agent-chat/agent-progress.test.ts
- A src/components/agent-chat/agent-progress.ts
- A src/components/agent-chat/agent-reading.tsx
- A src/components/agent-chat/agent-shell-contexts.ts
- A src/components/agent-chat/agent-shell.tsx
- A src/components/agent-chat/agent-strip.tsx
- A src/components/agent-chat/agent-traces.ts
- A src/components/agent-chat/agent-ui-reducer.test.ts
- A src/components/agent-chat/agent-ui-reducer.ts
- A src/components/agent-chat/authored-script.test.ts
- A src/components/agent-chat/chat-parts.tsx
- A src/components/agent-chat/choice-in-words.tsx
- A src/components/agent-chat/choice-syntax.ts
- A src/components/agent-chat/chunked-text.test.ts
- A src/components/agent-chat/chunked-text.ts
- A src/components/agent-chat/composer-attachments.tsx
- A src/components/agent-chat/composer-textarea.client.tsx
- A src/components/agent-chat/composer-textarea.tsx
- A src/components/agent-chat/composer.test.tsx
- A src/components/agent-chat/composer.tsx
- A src/components/agent-chat/full-text-snapshot.tsx
- A src/components/agent-chat/llm-request-trace-view.tsx
- A src/components/agent-chat/llm-request-trace.test.ts
- A src/components/agent-chat/llm-request-trace.ts
- A src/components/agent-chat/message.test.tsx
- A src/components/agent-chat/message.tsx
- A src/components/agent-chat/multiplayer.test.tsx
- A src/components/agent-chat/participant.tsx
- A src/components/agent-chat/presence-line.tsx
- A src/components/agent-chat/queued-messages.tsx
- A src/components/agent-chat/stream-event.ts
- A src/components/agent-chat/streaming-text.test.tsx
- A src/components/agent-chat/streaming-text.tsx
- A src/components/agent-chat/use-composer-attachments.ts
- A src/components/agent-chat/use-ticking-now-ms.ts
- A src/components/agent-context-rows.test.ts
- A src/components/agent-context-rows.ts
- A src/components/agent-context.test.tsx
- A src/components/agent-context.tsx
- A src/components/agent-look.ts
- A src/components/agents-home.test.tsx
- A src/components/agents-home.tsx
- A src/components/agents-nav.test.tsx
- A src/components/agents-nav.tsx
- A src/components/analytics-page.test.tsx
- A src/components/analytics-page.tsx
- A src/components/app-build.tsx
- A src/components/app-shell-palette-entries.test.ts
- A src/components/app-shell-palette-entries.ts
- A src/components/app-shell-palette.tsx
- A src/components/app-shell.test.tsx
- A src/components/app-shell.tsx
- A src/components/approvals-alert.tsx
- A src/components/call/calendar-invite.test.ts
- A src/components/call/calendar-invite.ts
- A src/components/call/call-bar.test.tsx
- A src/components/call/call-bar.tsx
- A src/components/call/call-controls.test.tsx
- A src/components/call/call-controls.tsx
- A src/components/call/call-lobby.test.tsx
- A src/components/call/call-lobby.tsx
- A src/components/call/call-pip.test.tsx
- A src/components/call/call-pip.tsx
- A src/components/call/call-share.tsx
- A src/components/call/call-tiles.test.tsx
- A src/components/call/call-tiles.tsx
- A src/components/call/caption-strip.test.tsx
- A src/components/call/caption-strip.tsx
- A src/components/call/face.tsx
- A src/components/call/spoken-lines.test.ts
- A src/components/call/spoken-lines.ts
- A src/components/call/transcript-history.test.tsx
- A src/components/call/transcript-history.tsx
- A src/components/call/transcript-rollup.test.tsx
- A src/components/call/transcript-rollup.tsx
- A src/components/change-my-mind-button.test.tsx
- A src/components/change-my-mind-button.tsx
- A src/components/checklist.tsx
- A src/components/cloudflare-button.tsx
- A src/components/code-block.client.tsx
- A src/components/code-block.tsx
- A src/components/code-editor.client.tsx
- A src/components/code-editor.tsx
- A src/components/connect-mind.tsx
- A src/components/connected-minds.ts
- A src/components/context-catalog/context-about.tsx
- A src/components/context-catalog/context-activity-stack-view.tsx
- A src/components/context-catalog/context-activity-stack.test.tsx
- A src/components/context-catalog/context-activity-stack.ts
- A src/components/context-catalog/context-catalog-list.test.tsx
- A src/components/context-catalog/context-catalog-list.tsx
- A src/components/context-catalog/context-catalog-rows.test.ts
- A src/components/context-catalog/context-catalog-rows.ts
- A src/components/context-catalog/context-catalog.ts
- A src/components/context-catalog/context-icon.tsx
- A src/components/context-catalog/context-palette-rows.test.ts
- A src/components/context-catalog/context-palette-rows.ts
- A src/components/context-catalog/context-palette.tsx
- A src/components/context-explorer/context-explorer.test.tsx
- A src/components/context-explorer/context-explorer.tsx
- A src/components/context-path-text.tsx
- A src/components/context-view/append-completions.test.ts
- A src/components/context-view/append-completions.ts
- A src/components/context-view/append-composer.tsx
- A src/components/context-view/append-events.test.ts
- A src/components/context-view/append-events.ts
- A src/components/context-view/awake-dot.tsx
- A src/components/context-view/context-path-links.ts
- A src/components/context-view/context-path.tsx
- A src/components/context-view/context-tree-rows.ts
- A src/components/context-view/context-tree.test.ts
- A src/components/context-view/context-tree.tsx
- A src/components/context-view/context-view-search.test.ts
- A src/components/context-view/context-view-search.ts
- A src/components/context-view/context-view.tsx
- A src/components/context-view/core-events.tsx
- A src/components/context-view/event-inspector-log.test.ts
- A src/components/context-view/event-inspector-log.ts
- A src/components/context-view/event-inspector.test.tsx
- A src/components/context-view/event-inspector.tsx
- A src/components/context-view/event-row-format.ts
- A src/components/context-view/event-row.test.tsx
- A src/components/context-view/event-row.tsx
- A src/components/context-view/feed-list.tsx
- A src/components/context-view/feed-rows.tsx
- A src/components/context-view/filter-row.tsx
- A src/components/context-view/filters.test.tsx
- A src/components/context-view/filters.tsx
- A src/components/context-view/folds.test.tsx
- A src/components/context-view/folds.tsx
- A src/components/context-view/live-state-value.tsx
- A src/components/context-view/payload-readers.ts
- A src/components/context-view/presence-strip.tsx
- A src/components/context-view/pretty-state.tsx
- A src/components/context-view/print-expression.ts
- A src/components/context-view/processors-panel.tsx
- A src/components/context-view/types.tsx
- A src/components/copy-text.tsx
- A src/components/dash/dash-agents-nav.tsx
- A src/components/dash/dash-href.test.ts
- A src/components/dash/dash-href.ts
- A src/components/dash/dash-pages.test.tsx
- A src/components/dash/dash-pages.tsx
- A src/components/dash/dash-paths.ts
- A src/components/dash/dash-routes.fixture.json
- A src/components/dash/dash.test.tsx
- A src/components/dash/dash.tsx
- A src/components/dash/serves.test.ts
- A src/components/dash/serves.ts
- A src/components/docs-editor/AGENTS.md
- A src/components/docs-editor/anchor.test.ts
- A src/components/docs-editor/anchor.ts
- A src/components/docs-editor/collab.ts
- A src/components/docs-editor/commands.ts
- A src/components/docs-editor/comment-marks.ts
- A src/components/docs-editor/comments-panel.tsx
- A src/components/docs-editor/comments.test.ts
- A src/components/docs-editor/comments.ts
- A src/components/docs-editor/create-doc.ts
- A src/components/docs-editor/doc-list-panel.tsx
- A src/components/docs-editor/doc-list.ts
- A src/components/docs-editor/doc-session.test.ts
- A src/components/docs-editor/doc-session.ts
- A src/components/docs-editor/doc-tree-element.test.ts
- A src/components/docs-editor/doc-tree-nav.tsx
- A src/components/docs-editor/doc-tree.test.ts
- A src/components/docs-editor/doc-tree.ts
- A src/components/docs-editor/docs-editor.tsx
- A src/components/docs-editor/extensions.ts
- A src/components/docs-editor/file-kind.ts
- A src/components/docs-editor/frames.test.ts
- A src/components/docs-editor/frames.ts
- A src/components/docs-editor/frontmatter.ts
- A src/components/docs-editor/icons.test.ts
- A src/components/docs-editor/install.test.ts
- A src/components/docs-editor/install.ts
- A src/components/environment-head-content.tsx
- A src/components/identifier.tsx
- A src/components/integrations-page-server.test.tsx
- A src/components/integrations-page.test.tsx
- A src/components/integrations-page.tsx
- A src/components/iterate-logo.svg
- A src/components/iterate-logo.tsx
- A src/components/last-mind-redirect.tsx
- A src/components/list-row-text.tsx
- A src/components/log-in-with-iterate.tsx
- A src/components/mcp-connect.test.tsx
- A src/components/mcp-connect.tsx
- A src/components/mind-app-shell.tsx
- A src/components/not-recorded.tsx
- A src/components/page-tools.test.tsx
- A src/components/page-tools.tsx
- A src/components/posthog-replay.test.tsx
- A src/components/posthog.tsx
- A src/components/reconnecting-mark.tsx
- A src/components/repo-ide/AGENTS.md
- A src/components/repo-ide/codemirror.ts
- A src/components/repo-ide/commit-diff-pane.tsx
- A src/components/repo-ide/commit-history-panel.tsx
- A src/components/repo-ide/file-chrome.tsx
- A src/components/repo-ide/git-panel.tsx
- A src/components/repo-ide/html-preview.tsx
- A src/components/repo-ide/markdown-preview.tsx
- A src/components/repo-ide/repo-client.test.tsx
- A src/components/repo-ide/repo-client.ts
- A src/components/repo-ide/repo-code-editor.tsx
- A src/components/repo-ide/repo-editor-pane.tsx
- A src/components/repo-ide/repo-file-discard.test.ts
- A src/components/repo-ide/repo-file-discard.ts
- A src/components/repo-ide/repo-file-kinds.ts
- A src/components/repo-ide/repo-file-tree-paths.test.ts
- A src/components/repo-ide/repo-file-tree-paths.ts
- A src/components/repo-ide/repo-file-tree.tsx
- A src/components/repo-ide/repo-ide-activity-strip.tsx
- A src/components/repo-ide/repo-ide-search.ts
- A src/components/repo-ide/repo-ide.tsx
- A src/components/repo-ide/staged-changes.test.ts
- A src/components/repo-ide/staged-changes.ts
- A src/components/repo-ide/use-repo-ide-actions.ts
- A src/components/route-defaults.test.tsx
- A src/components/route-defaults.tsx
- A src/components/secrets-page.tsx
- A src/components/setup-steps.tsx
- A src/components/source-code-block.client.tsx
- A src/components/standalone-page.tsx
- A src/components/step-row.test.tsx
- A src/components/step-row.tsx
- A src/components/stream-link.test.tsx
- A src/components/stream-link.tsx
- A src/components/time-chart.tsx
- A src/components/ui/AGENTS.md
- A src/components/ui/alert-dialog.tsx
- A src/components/ui/alert.tsx
- A src/components/ui/avatar.tsx
- A src/components/ui/badge.tsx
- A src/components/ui/breadcrumb.tsx
- A src/components/ui/button-group.tsx
- A src/components/ui/button.tsx
- A src/components/ui/card.tsx
- A src/components/ui/checkbox.tsx
- A src/components/ui/collapsible.tsx
- A src/components/ui/command.tsx
- A src/components/ui/dialog.tsx
- A src/components/ui/dropdown-menu.tsx
- A src/components/ui/empty.tsx
- A src/components/ui/field.tsx
- A src/components/ui/input-group.tsx
- A src/components/ui/input.tsx
- A src/components/ui/label.tsx
- A src/components/ui/native-select.tsx
- A src/components/ui/popover.tsx
- A src/components/ui/radio-group.tsx
- A src/components/ui/select.tsx
- A src/components/ui/separator.tsx
- A src/components/ui/sheet.tsx
- A src/components/ui/sidebar.tsx
- A src/components/ui/skeleton.tsx
- A src/components/ui/sonner.tsx
- A src/components/ui/spinner.tsx
- A src/components/ui/table.tsx
- A src/components/ui/tabs.tsx
- A src/components/ui/textarea.tsx
- A src/components/ui/tooltip.tsx
- A src/components/virtual-log/AGENTS.md
- A src/components/virtual-log/older-pages.ts
- A src/components/virtual-log/read-progress.test.tsx
- A src/components/virtual-log/read-progress.tsx
- A src/components/virtual-log/remembered.ts
- A src/components/virtual-log/use-reader.ts
- A src/components/virtual-log/virtual-log.tsx
- A src/components/widget/widget-frame.test.tsx
- A src/components/widget/widget-frame.tsx
- A src/components/widget/widget-mcp.test.ts
- A src/components/widget/widget-mcp.ts
- A src/components/widget/widget-row.tsx
- A src/components/widget/widget.test.ts
- A src/components/widget/widget.ts
- A src/hooks/use-context-explorer.ts
- A src/hooks/use-itx-session.ts
- A src/hooks/use-mobile.ts
- A src/lib/agent-summary.test.ts
- A src/lib/agent-summary.ts
- A src/lib/approvals.test.ts
- A src/lib/approvals.ts
- A src/lib/call-engine.test.ts
- A src/lib/call-engine.ts
- A src/lib/call-rules.test.ts
- A src/lib/call-rules.ts
- A src/lib/change-my-mind.test.ts
- A src/lib/change-my-mind.ts
- A src/lib/codemirror-theme.ts
- A src/lib/facet-view.ts
- A src/lib/format-script.test.ts
- A src/lib/format-script.ts
- A src/lib/held-acts.test.ts
- A src/lib/held-acts.ts
- A src/lib/itx-session.test.ts
- A src/lib/itx-session.ts
- A src/lib/page-tools.test.ts
- A src/lib/page-tools.ts
- A src/lib/page-url.test.ts
- A src/lib/page-url.ts
- A src/lib/plain-left-click.ts
- A src/lib/presence.test.ts
- A src/lib/presence.ts
- A src/lib/principal-label.ts
- A src/lib/px-per-rem.ts
- A src/lib/saved-context.test.tsx
- A src/lib/saved-context.ts
- A src/lib/saved-log-tail.test.ts
- A src/lib/saved-log-tail.ts
- A src/lib/secrets.ts
- A src/lib/source-editor.ts
- A src/lib/waiting-approvals-hook.test.tsx
- A src/lib/waiting-approvals.test.ts
- A src/lib/waiting-approvals.ts
- A src/styles/AGENTS.md
- A src/styles/globals.css
- A src/styles/iterate.css
- A src/styles/tokens.css
- A src/test-support/agent-log.ts
- A tsconfig.json
- A tsconfig.worker.json
- A tsdown.config.ts
- A vitest.config.ts
A AGENTS.md
@@ -0,0 +1,109 @@ +# packages/ui + +`@iterate-com/ui`, the UI kit that every client app in this repo imports as `@iterate-com/ui/*`. +The same files are also a shadcn registry for apps in other repos, and an npm package built for +no-build pages. [README.md](README.md) tells outside users which one to use. `packages/` is copied +to the public iterate/packages repo, so write nothing private here. + +## Layout and imports + +The package has the layout of an app after `shadcn add`, so the registry serves its files as they +are: + +- `src/components/ui/`: shadcn's components, vendored byte for byte. Do not edit them + ([src/components/ui/AGENTS.md](src/components/ui/AGENTS.md)). +- `src/components/` and `src/lib/`: our components and their plain helpers. Each file or folder is + one registry item. +- `src/apps/` (the shell that every app's `server.ts`, `router.tsx`, `document.tsx` and `head.ts` + call), `src/hooks/` and `src/agent-kind-view/`: not in the registry. Apps in this repo import them + through the workspace. +- Imports use the `#/*` subpath import, with extensions: `#/components/ui/button.tsx`. `shadcn add` + rewrites these to the installing app's aliases. The CLI identifies a shadcn component only by the + `ui/` in its path. Files of one item import each other relatively (`./filters.tsx`), because they + travel together. + +## The registry + +`registry.json` names each item, gives a one-line description and lists its files. +`node scripts/ci/shadcn-registry.ts update` calculates the rest (dependencies, registry +dependencies, the `theme` item, `publishConfig.exports`) and writes `registry.json` and +`package.json`. Run it after you add or move a file, or change an import, and commit both files. +Lint and Typecheck fails when they are stale. The script's header explains the registry. + +- `update` throws when an installing app would get an import it cannot resolve: a file in + `src/components/` or `src/lib/` that no item lists, a relative import of another item's file, a + `#/` import of a file outside the registry (`src/apps/`, `src/hooks/`), or an `@iterate-com/*` + import. +- Hooks and providers are not items. They belong in `iterate/react`. `use-context-explorer` stays + here until it moves. A hook that a registry item needs lives in its `src/lib/` file + (`lib/saved-context`, `lib/waiting-approvals`). +- The shadcn CLI drops a file's leading comment when it installs it (shadcn-ui/ui#9206). The copy + here keeps it. + +## The npm package + +`pnpm --dir packages/ui build` (tsdown, `tsdown.config.ts`) makes the package that a no-build page +imports from esm.sh. Main publishes it under the `main` dist-tag. + +- The build bundles every dependency, React included, so the runtime dependencies are + `devDependencies`. For this reason, do not `npm install` the package into an app: the app gets a + second React, and our hooks fail with "Invalid hook call". +- `browser-entries.ts` names the entries: one for each item and each vendored component, plus + `page`, `live`, React's own modules (`src/browser/`) and `styles.css`. esm.sh needs each entry + named, not a wildcard, to keep shared chunks shared. +- The default config's apps (`core/configs/default/apps/*/index.html`) import one pinned build + through their import maps, so a change here reaches them only when that pin moves. +- How a page uses the package and signs in: [examples/README.md](examples/README.md). + +## Quality bar + +- Colours are tokens and text sizes are steps (`lint/design-tokens.test.ts`). The tokens and the + look are in [src/styles/AGENTS.md](src/styles/AGENTS.md). +- The repo IDE, the virtual log, the context view and the agent chat score 100 on React Doctor. + Keep them there. The commands are in the folders' `AGENTS.md` files. +- The browser specs of this package (`test/playwright/ui/*.spec.ts`) left the repo with `core/os`. + `git show cbf560aa7:test/playwright/ui/<name>.spec.ts` shows what they held. + +## Topic notes + +- [src/components/virtual-log/AGENTS.md](src/components/virtual-log/AGENTS.md): the root of every + view of a log. +- [src/components/agent-chat/AGENTS.md](src/components/agent-chat/AGENTS.md): one agent's + conversation. +- [src/components/repo-ide/AGENTS.md](src/components/repo-ide/AGENTS.md): the IDE over one repo. +- `components/dash` is a mind's Dash, drawn from lists, for a no-build page: the shell takes + the pages and the groups of links, and each kit page (`DashRepo`, `DashSecrets`, …) takes the + member's `itx` and does its own reads. A page imports its larger part with `import()` of that + item's own entry file, never of a file that is no entry: on esm.sh only an entry stays one + module. Its URL is `lib/page-url`; the member's socket is `live`'s `memberItx`, whose `itx` is a + proxy that dials a new session when the socket closes. A stub or a subscription ends with its + session. The Dash keeps a page mounted over a new session only when its component says + `staysOverReconnect`; any other page is mounted anew, so a page on the SDK's hooks alone is + never stale. A page that stays opens again what it holds: the plain parts are `lib/itx-session` + (the session's epoch for a hook's deps, `kept`, `keptContext`), and the hooks over them + (`useHeldContext`, `useKeptContext`) are `src/hooks/use-itx-session.ts`, outside the registry + and exported by `live`. Only `ReconnectingMark`, once in the shell, says that the connection + is gone. THE FIRST PAINT IS THE PAGE'S HTML: the default config's Dash draws the shell's frame + from its `index.html` and `app.css` alone (the sidebar open or as a rail, an agent page's + header row, `DashPlaceholder`'s shapes), dials `/itx` in its head (`EARLY_ITX_SOCKET`, which + `memberItx` takes) and renders with no await: `Dash` asks `whoami()` itself, and a page gets + `principal` undefined until the answer. The frame's numbers are the shell's own (sidebar 16rem + or 3rem, header rows of 45, 53 and 42 px, the column of 48rem): when one changes here, change + `core/configs/default/apps/dash/public/app.css` with it. `data-frame` on `<html>` tells + `LogReading` that the wait began with the page. Two page ids mean + more: `agents` puts the agents in the sidebar and takes `/agents/<path>` (`/agents?contextPath=/` + for root), and `contexts` is the raw view. The Home and Agents pages (`DashHome`, `DashAgents`) + are in `agent-kind-view/dash-agents.tsx`, outside the registry, because they host a kind's frame. + THE DASH'S ADDRESSES ARE PATHS: `/`, `/secrets`, `/agents/agents/onboarding`, + `/contexts/repos/config` (`/contexts?contextPath=/` for root), `/repos/config/worker.ts`, and + `/<id>/<rest>` (the pure codec is `components/dash/dash-paths.ts`, registered by + `components/dash/dash-href.ts`). Every part reads `usePageParam` and builds `pageHref`, + `agentViewHref` or `rawViewHref`: never read `location` or write a `?page=` link by hand. +- `components/page-tools` lends the agent that a page shows tools that run in that page (a + banner, Playwright's locators). `lib/page-tools.ts` says how a call travels, who may call and + what each refusal is worth: read its header before you add a tool or loosen a rule. The Dash + turns it on with the Agents row's `pageTools`. +- The Agents app's parts (`components/agents-nav`, `components/agents-home`, `lib/agent-summary`) + serve the hosted app; the Dash takes `StatusDot` and `lib/agent-summary`. None imports a router. They take + `agentHref(path)` and `onOpen(path)`, so that a page with a client router can make a plain click + a route change.
A LICENSE
@@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License.
A README.md
@@ -0,0 +1,326 @@ +# @iterate-com/ui + +iterate's React components: the stream viewer (`ContextView`), the repo IDE, code views, and +shadcn's components on Base UI. Which way to use them depends on what you're building: + +| Building | Use | +| ------------------------------------------------------------------ | ------------------------------------------------------------- | +| An app with a build step, that you'll keep | The shadcn registry: `npx shadcn add iterate/packages/<item>` | +| A one-off page with no build (an agent's answer to a request, say) | This package from esm.sh, with an import map | + +`npm install @iterate-com/ui` into an app is not supported (below). + +## An app: the shadcn registry + +```sh +npx shadcn add iterate/packages/context-view +``` + +The component's source lands in your app, on your React and your dependencies, for you to change. +The items are in +[registry.json](https://github.com/iterate/packages/blob/main/packages/ui/registry.json); setup is +in [AGENTS.md](https://github.com/iterate/packages/blob/main/packages/ui/AGENTS.md#the-registry). + +## A one-off page: esm.sh + +A page an agent might write when asked what happened in an email thread: its worker answers +`./events` with the thread's context's events, and the page shows them in the stream viewer, +polling for new ones. + +```html +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <title>Re: Tomorrow's huddle</title> + <script type="importmap"> + { + "imports": { + "@iterate-com/ui/": "https://esm.iterate.com/@iterate-com/ui@<version>/", + "react": "https://esm.iterate.com/@iterate-com/ui@<version>/react", + "react/": "https://esm.iterate.com/@iterate-com/ui@<version>/react/", + "react-dom": "https://esm.iterate.com/@iterate-com/ui@<version>/react-dom", + "react-dom/": "https://esm.iterate.com/@iterate-com/ui@<version>/react-dom/", + "@tanstack/react-query": "https://esm.iterate.com/@tanstack/react-query@5?external=react,react-dom" + } + } + </script> + <link rel="stylesheet" href="https://esm.iterate.com/@iterate-com/ui@<version>/styles.css" /> + <!-- optional: iterate's look (Ubuntu, square corners) over the neutral one --> + <link rel="stylesheet" href="https://esm.iterate.com/@iterate-com/ui@<version>/iterate.css" /> + </head> + <body> + <script type="module"> + import { html, render, useState } from "@iterate-com/ui/page"; + import { ContextView } from "@iterate-com/ui/components/context-view/context-view"; + import { Badge } from "@iterate-com/ui/components/ui/badge"; + import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query"; + + function Thread() { + const events = useQuery({ + queryKey: ["events"], + queryFn: () => fetch("./events").then((response) => response.json()), + refetchInterval: 5000, + }); + // the view's own state: the open inspector, the search, the filters + const [state, setState] = useState({}); + return html` + <div class="flex h-screen flex-col"> + <header class="flex items-center gap-2 border-b px-4 py-2"> + <h1 class="font-medium">Re: Tomorrow's huddle</h1> + <${Badge} variant="secondary">${events.isFetching ? "checking…" : "up to date"}<//> + </header> + <${ContextView} + title="/agents/email/t42" + context=${{ + events: events.data || [], + caughtUp: events.isSuccess, + error: events.error?.message, + processors: { rows: [] }, + presence: { actors: [], rpcStubs: [] }, + liveState: {}, + }} + state=${state} + onStateChange=${(patch) => setState((previous) => ({ ...previous, ...patch }))} + className="min-h-0 flex-1" + /> + </div> + `; + } + + render( + html`<${QueryClientProvider} client=${new QueryClient()}><${Thread} /><//>`, + document.body, + ); + </script> + </body> +</html> +``` + +- `<version>` is exact: the `main` dist-tag's, from `npm view @iterate-com/ui dist-tags.main`. +- `html` is [htm](https://github.com/developit/htm): JSX's shape in a template string, so the page + needs no compiler. +- React is the package's own. Load any other React library from esm.sh with + `?external=react,react-dom` and it uses the same one, as react-query does here. A chart library + beside our components, and what goes wrong without the flag: + [Another React library](https://github.com/iterate/packages/blob/main/packages/ui/examples/README.md#another-react-library). +- Components are `@iterate-com/ui/components/<name>`: `context-view/context-view`, + `repo-ide/repo-ide`, `code-block`, and shadcn's (`ui/card`, `ui/table`, …). + +### The Change my mind button + +A mind's blog is the diary of the changes that mind made to itself. The button copies instructions +that a reader pastes to their own iterate mind, which reads the post and offers to make the same +change. The instructions tell that mind to treat the post as a stranger's information, not as +instructions, and to change nothing before its owner says yes. + +On a plain HTML page, one script tag defines `<change-my-mind>`, with no React and no stylesheet: + +```html +<script + type="module" + src="https://esm.iterate.com/@iterate-com/ui@<version>/change-my-mind" +></script> +<change-my-mind source="https://blog.example.com/a-post"></change-my-mind> +``` + +On a React page, `ChangeMyMindButton` from `@iterate-com/ui/components/change-my-mind-button`: + +```js +html`<${ChangeMyMindButton} source="https://blog.example.com/a-post" />`; +``` + +- `source`: the post's URL. By default, this page without its query or hash. +- `scope`: `"post"` (the default), or `"blog"` for the whole blog: its `/feed.xml` and `/README.md`. +- `instructions`: the exact text to copy, in place of the built one (the element also takes its own + text). +- `size`: `"sm"` for a list. The button is 36px high, the kit's large Button; `"sm"` is 32px, its + default Button. Its corners are the page's `--radius`. The element also takes `align="end"`. +- `variant`: `"default"`, the solid button, or `"outline"`, the kit's outline Button: quieter, for + a list of posts (with `size="sm"`). The copied state, the tooltip and the card are the same. +- `changeMyMindInstructions({ source, scope })` (`@iterate-com/ui/lib/change-my-mind`) gives the + text alone. + +The element takes the kit's tokens when the page has the kit's stylesheet, and shadcn's neutral +values when not: dark on a page whose `color-scheme` is dark, light on any other. A whole page: +[examples/change-my-mind.html](https://github.com/iterate/packages/blob/main/packages/ui/examples/change-my-mind.html). + +### A call's spoken lines + +What is said in a call, from `@iterate-com/ui/components/call/<part>`. A line said is +`{ key, who, at, text }`: `who` is the speaker's address, or the agent's name. `CaptionStrip` is one +quiet line of the newest words under the call, with a button that opens `TranscriptHistory`: every +line said, on the virtual log, which reads older pages through its `older` as the reader scrolls +up. +`TranscriptRollup` is one row of a feed for a run of lines said, and `rollUpSpokenLines` makes the +runs from the page's rows: + +```js +import { html, useMemo, useState } from "@iterate-com/ui/page"; +import { CaptionStrip } from "@iterate-com/ui/components/call/caption-strip"; +import { TranscriptRollup } from "@iterate-com/ui/components/call/transcript-rollup"; +import { rollUpSpokenLines } from "@iterate-com/ui/components/call/spoken-lines"; + +// rows: the page's feed, in log order; spoken ones are { key, offset, kind: "said", who, at, text } +const feed = useMemo(() => rollUpSpokenLines(rows), [rows]); +const [open, setOpen] = useState({}); +const renderRow = (row) => + row.kind === "rollup" + ? html`<${TranscriptRollup} + lines=${row.lines} + me=${myEmail} + expanded=${Boolean(open[row.key])} + onToggle=${() => setOpen((was) => ({ ...was, [row.key]: !was[row.key] }))} + />` + : html`<${MyRow} row=${row} />`; + +// under the feed: the newest words, and the viewer's own still being transcribed +html`<${CaptionStrip} + said=${said} + live=${{ captions, pending }} + me=${myEmail} + open=${shown} + onOpen=${toggle} +/>`; +``` + +A page that uses `AgentContext` (`@iterate-com/ui/components/agent-context`) passes the strip and +the open transcript through `captions`, over the composer. `spokenLine(event)` answers a line for +an event said in the call: `AgentContext` rolls up each run of them, and `me` marks "(you)". +`agentContext`, the agent's own log, adds its settled work as rows that open into the scripts and +traces. `activityRows={false}` hides those rows for a reader who must not see them. + +### An agent's tools in the page + +A page that shows an agent can lend that agent tools that run in the page, while a signed-in person +has it open: `PageTools` from `@iterate-com/ui/components/page-tools`, mounted beside the agent's +view. Without it nothing is lent. + +```js +html`<div data-page-tools="scope"> + <${AgentChat} path=${path} ... /> + <${PageTools} itx=${itx} path=${path} me=${principal} agent="Helper" /> + <aside data-page-tools="off">a part that never matches a locator</aside> +</div>`; +``` + +The agent then finds `itx.page.<person>.<tab>` in its capability tree and calls it from a script: + +```js +const page = itx.page.jonas.k3f9xq2mabcd; +await page.banner.show({ + title: "The build is done", + buttons: [{ label: "Open", open: "/agents" }], +}); +await page.getByLabel("Message this agent").fill("Looks good, ship it"); +await page.getByRole("tab", { name: "Events" }).highlight({ note: "The raw log is here" }); +``` + +- `banner.show({ title, body, buttons, seconds })` answers `{ pressed }`: the label, or `null` and + why (`"no answer"`, `"dismissed"`, `"off"`). One banner shows and three wait. The answer is what + a tab said: it is no member's approval, and any code of the mind could lend a name that answers + the same. +- `getByRole`, `getByText`, `getByLabel` and `locator(css)` find one element inside the `scope`, as + Playwright does (`first()`, `nth(i)`, chained); then `fill`, `click`, `press` (Enter, Escape, the + arrows), `focus`, `highlight`, `scrollIntoView`, `textContent` and `count`. The input is a + script's: no browser default follows a key, a frame is out of reach, and an act moves the focus. +- `open(path)` shows a path of the same app (`onOpen`, else the browser loads it). +- `help()` answers how each tool is called, the host's own among them. The capability tree's line + for the name holds only the names: a mind takes one line of at most 500 characters there. +- With no `scope` mark around `PageTools`, the agent gets the banner and `open` alone. +- The person sees the agent's path on every banner, a label while a call runs ("Helper is typing") + with Stop, and a ring on what was filled or highlighted. Stop ends the lend for the tab, and a + reload does not lend again. **No call runs while the tab is in the background**: the person + would not see it. +- One lend takes 30 calls in 10 seconds, and bounded texts. A call over a limit is refused in + words. + +**What it costs.** What the agent does in the tab, it does as the person: a message it sends from +the composer and a button it presses carry the PERSON's stamp in the log. The page also appends one +audit row for each call to the agent's context (`events.iterate.com/page/tool-called`: the tool, +the locator, the outcome, never a value). That row carries the person's stamp too, and names no +caller: it says that a tool ran in this person's tab, not which code of the mind called it. Any +unjailed code of the mind can call a lent name, so one member's agent can act in another member's +tab. + +| Tools | Worst case | What bounds it | +| ------------------------------ | --------------------------------------------------------------------------------- | --------------------------------------------------------- | +| The banner and `open` alone | A false notice in the person's tab; the page of the app that they look at changes | The agent's path on the banner; chat text can say as much | +| Locators in a `scope` | The agent presses buttons and sends messages as the person, inside the scope | The scope and what never matches; the visible tab; Stop | +| An `evaluate` tool of your own | The page's whole session, with no label or audit row that the code cannot remove | Nothing in the page | + +- **A jailed agent gets nothing.** The lender reads the agent's own rules + (`rewriteRules.list(0)`) before the lend and again before every call. It lends only where the + agent's scripts run in the agent's own context with the kernel's own `itx.run` and `itx.cd`: such + an agent holds the mind's whole reach already. An agent whose scripts a mind's config sends to a + jail fails that, and so does the jail. A host that calls `itx.provide` by itself skips this check + and must make it: for a jailed agent a function in a member's tab is a way out. +- **Never matched,** by any selector and by `count`: a password, one-time-code, card, hidden or + file field, a part marked `off`, and anything outside the `scope`. +- **Refused:** a click or a key on a link or a form that leaves the page's origin, or that leads to + a path of the platform's own (`/.auth/…`, `/.iterate/…`: sign-in and sign-out). So no tool signs + a person out, or sends them to the pages where a member signs with a passkey. The kit watches a + click or a key for 2 seconds for the link or the form that it sets off, also when the page's own + handler submits the form later. In those 2 seconds the person's own Sign out is held too: they + press it again. A handler that leaves the page by `location`, by `form.submit()` or by a request + of its own is the page's act, and the kit cannot see it. +- **What these rules do not do:** seal what the page holds. A CSS selector asks about every + attribute and every text of the document, and a patient caller learns from what matches. The + rules bound the agent's ACTS and what `textContent` answers. A host whose page holds what the + agent must not learn does not mount this. +- **In an app whose code the mind's agents cannot change**, the rules above are the wall for the + agent's acts. **On a mind's own Dash they are manners**: an unjailed agent can commit to the + mind's config repo, which is the Dash's code. There the walls are the jail and the passkey. +- A call is live only. The lent name holds the person and a part that is new at every lend, so a + call reaches one tab, nothing is stored, and a page opened later gets nothing old. + +**Tools of your own, and eval.** `tools` adds functions of the page under names of your own; the +kit shows the label and writes the audit row. The kit has no eval. An owner who wants one adds it +to their own page, here on the Agents row of a Dash's `app.js`, and pays the third row of the table: + +```js +pageTools: { + tools: { + evaluate: { + description: "evaluate(code) runs JavaScript in this page and answers what it returns.", + run: (code) => new Function(`return (async () => { ${code} })()`)(), + }, + }, +}, +``` + +### Your mind's data + +`@iterate-com/ui/live` reads a mind live, as the person viewing the page. On the mind's own +host (`<host>.<domain>`, served by its config worker) the page uses the host's session. On +any other website the page signs in with iterate itself: a page to copy does it, jsfiddle included. +Both, and how a Claude artifact reaches iterate instead: +[Signing in](https://github.com/iterate/packages/blob/main/packages/ui/examples/README.md#signing-in). + +## Not: `npm install` into an app + +The package bundles every dependency, React included, so a page has nothing left to resolve. In an +app with its own React, that makes two: our components, rendered in your app's tree, call a React +that isn't rendering, and fail with "Invalid hook call". It ships no type declarations either. Use +the registry. + +## Versions + +Every commit to iterate's main branch that changes the package publishes +`<version>-main.<commit date>-<commit>` under the `main` dist-tag. `latest` names the same version. + +## The source of a version + +The package ships built files only. The source is in `packages/ui/src` of +[iterate/packages](https://github.com/iterate/packages/tree/main/packages/ui/src): an import of +`@iterate-com/ui/components/dash/dash` is `src/components/dash/dash.tsx` there. + +`main` there is the newest build. To read the source of the version a page pins, find the commit it +names: each commit of that repository ends with `GitOrigin-RevId: <commit>`, and the version's last +part is the start of it. + +```sh +git clone https://github.com/iterate/packages && cd packages +git log -1 --format=%H --grep='GitOrigin-RevId: 2da5c60' # for 0.1.0-main.20261113T222359Z-2da5c60 +git show <that commit>:packages/ui/src/components/dash/dash-pages.tsx +```
A browser-entries.ts
@@ -0,0 +1,212 @@ +// THE MODULES A NO-BUILD PAGE IMPORTS FROM @iterate-com/ui, as the published package names them +// (tsdown.config.ts builds one file per entry; package.json's publishConfig.exports maps each name to +// it, and `node scripts/ci/shadcn-registry.ts update` writes that map). A page imports the same names the apps in this repo do (`@iterate-com/ui/components/…`), +// plus React's own modules, which its import map points `react`, `react/…` and `react-dom/…` at. +import { readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; + +const ui = import.meta.dirname; + +/** The items whose files a page imports one by one, as `components/<item>/<file>`: the call's + * parts (src/components/call/), which a page takes as it needs them. */ +const ITEMS_OF_PARTS: Record<string, string[]> = { + call: [ + "spoken-lines.ts", + "face.tsx", + "caption-strip.tsx", + "transcript-history.tsx", + "transcript-rollup.tsx", + "call-bar.tsx", + "call-controls.tsx", + "call-share.tsx", + "call-tiles.tsx", + "call-pip.tsx", + "call-lobby.tsx", + ], +}; + +/** Each entry's name, with the source tsdown builds it from: the modules in src/browser/, one + * per registry item of files (its file named after it, `context-view/context-view.tsx`; the theme + * item is a stylesheet's, iterate.css), and one per vendored shadcn component + * (`components/ui/button`). */ +export function browserEntries(): Record<string, string> { + const registry: { items: { name: string; files?: { path: string }[] }[] } = JSON.parse( + readFileSync(path.join(ui, "registry.json"), "utf8"), + ); + const items = registry.items.flatMap((item) => { + if (!item.files) return []; + // an item of parts with no file named after it: each part a page imports is an entry + const parts = ITEMS_OF_PARTS[item.name]; + if (parts) return parts.map((part) => `src/components/${item.name}/${part}`); + const file = item.files.find( + ({ path: file }) => path.basename(file, path.extname(file)) === item.name, + ); + if (!file) + throw new Error( + `registry item ${item.name} has no file named after it (${item.name}.tsx or ${item.name}.ts) for a page to import`, + ); + return [file.path]; + }); + const shadcn = readdirSync(path.join(ui, "src/components/ui")) + .filter((file) => file.endsWith(".tsx")) + .map((file) => `src/components/ui/${file}`); + return { + page: "src/browser/page.ts", + live: "src/browser/live.ts", + // the icons a page takes from this package, and not from lucide-react (src/browser/icons.ts) + icons: "src/browser/icons.ts", + // react-query for a page, from this package and not from an import-map line of its own + // (src/browser/query.ts) + query: "src/browser/query.ts", + react: "src/browser/react.ts", + "react/jsx-runtime": "src/browser/react-jsx-runtime.ts", + "react/compiler-runtime": "src/browser/react-compiler-runtime.ts", + "react-dom": "src/browser/react-dom.ts", + "react-dom/client": "src/browser/react-dom-client.ts", + // the page's side of a kind's own chat view (src/agent-kind-view/host.ts); the frame's side is + // one classic script beside these modules (`AGENT_KIND_VIEW_FRAME`) + "agent-kind-view/host": "src/agent-kind-view/host.ts", + // a mind's Dash's Home and Agents pages, which host kinds' frames (src/agent-kind-view/dash-agents.tsx) + "agent-kind-view/dash-agents": "src/agent-kind-view/dash-agents.tsx", + // `<change-my-mind>`, the button for a page with no React: one script tag defines it + "change-my-mind": "src/browser/change-my-mind.ts", + // the chat's parts for a page of its own (a call's log, a room's chat): `Feed`, `MessageBubble`, + // `Composer` and `Markdown`, and `AgentShell`'s Chat | Events strip. A kind's view gets the same + // parts as `ui` (src/agent-kind-view/kit.ts); a page imports them by these names. + "components/agent-chat/chat-parts": "src/components/agent-chat/chat-parts.tsx", + "components/agent-chat/agent-shell": "src/components/agent-chat/agent-shell.tsx", + // the agent page's one header row, which the Dash and Meet draw alike + "components/agent-chat/agent-page-header": "src/components/agent-chat/agent-page-header.tsx", + "lib/agent-progress": "src/components/agent-chat/agent-progress.ts", + ...Object.fromEntries( + [...items, ...shadcn] + .sort() + .map((file) => [file.slice("src/".length).replace(/\.tsx?$/, ""), file]), + ), + }; +} + +/** THE VENDOR CHUNKS of the build: one file per library, whichever components load it + * (tsdown.config.ts makes one chunk per group). Each is also an export of the published package + * (`publishExports`), and the export is what keeps it ONE file on esm.sh. esm.sh builds every + * lazily loaded chunk again, and copies into it each file that chunk imports, unless the file is + * an export or two exports import it directly. Only lazy chunks import CodeMirror. So without the + * export, a page with two of them (the repo IDE: its own wiring, and `code-editor`) got two + * CodeMirrors, and the editor refused the extensions the other one made. */ +/** The lucide icons that only src/components/docs-editor imports, by their file names. */ +export const docsEditorIcons = [ + "bold", + "code-xml", + "dot", + "heading-1", + "heading-2", + "heading-3", + "italic", + "link", + "list-checks", + "list-ordered", + "message-square-plus", + "pilcrow", + "redo", + "rotate-ccw", + "separator-horizontal", + "strikethrough", + "table", + "text-quote", + "undo", +]; + +export const vendorChunks = [ + { name: "vendor-react", test: /node_modules[\\/](react|react-dom|scheduler)[\\/]/ }, + // CodeMirror, without the languages only the docs editor loads: those are the next group's. A + // group also takes every module its modules import that no earlier group has taken (rolldown's + // `codeSplitting.groups`), so this one comes first and keeps the core + { + name: "vendor-codemirror", + test: /node_modules[\\/](?!@codemirror[\\/](?:lang-(?:cpp|go|java|php|python|rust|xml)|legacy-modes)[\\/]|@lezer[\\/](?:cpp|go|java|php|python|rust|xml)[\\/])(@codemirror|@lezer|codemirror|crelt|style-mod|w3c-keyname|@marijn)[\\/]/, + }, + // the languages of the docs editor's code blocks (Atomic's `code-languages`) that the repo IDE has + // none of: a chunk of their own, so the pages that load vendor-codemirror do not pay for them + { + name: "vendor-codemirror-more-languages", + test: /node_modules[\\/](@codemirror[\\/](lang-(cpp|go|java|php|python|rust|xml)|legacy-modes)|@lezer[\\/](cpp|go|java|php|python|rust|xml))[\\/]/, + }, + { name: "vendor-codemirror-themes", test: /node_modules[\\/]@fsegurai[\\/]/ }, + { name: "vendor-base-ui", test: /node_modules[\\/](@base-ui|@floating-ui)[\\/]/ }, + { name: "vendor-yaml", test: /node_modules[\\/]yaml[\\/]/ }, + { name: "vendor-zod", test: /node_modules[\\/]zod[\\/]/ }, + // react-query, which a page takes from the `query` entry: one client for the page and for + // this package's components + { name: "vendor-query", test: /node_modules[\\/]@tanstack[\\/](react-query|query-core)[\\/]/ }, + { name: "vendor-yjs", test: /node_modules[\\/](yjs|lib0|y-protocols|y-codemirror\.next)[\\/]/ }, + // Atomic's live preview holds CodeMirror state fields and facets: one copy, beside CodeMirror's + { name: "vendor-atomic", test: /node_modules[\\/]@atomic-editor[\\/]/ }, + { name: "vendor-posthog", test: /node_modules[\\/]posthog-js[\\/]/ }, + // Prettier's browser build, which prettifies a script in the Agents app's Script tab + // (lib/format-script.ts): only a page that shows a script loads it + { name: "vendor-prettier", test: /node_modules[\\/]prettier[\\/]/ }, + // FEWER FILES FOR A PAGE TO ASK FOR, AT NO COST IN BYTES. Without these three, each icon is a + // chunk of its own, and a page asks for each vendored shadcn component by its own file of two + // kilobytes. A group also takes what its files import and no earlier group holds, so the order + // here says who holds what: + // vendor-icons every icon that a component or src/browser/icons.ts uses + // ui-base what nearly every page with a component loads: the button and the text + // fields, with the class helpers under them. A public page of one button and one + // card loads this and no more, as before. + // ui-shell the components that only the app shell brings: a page with the shell loads + // what it loaded before, in one file, and a page without it loads none of it. + // `components/ui/<name>` stays an entry, which hands on what its file holds. + // every icon but the docs editor's own, and lucide's shared parts (the group after this one + // says why the order is this) + { + name: "vendor-icons", + test: new RegExp( + `node_modules[\\\\/]lucide-react[\\\\/](?!dist[\\\\/]esm[\\\\/]icons[\\\\/](?:${docsEditorIcons.join("|")})\\.m?js$)`, + ), + }, + { + name: "ui-base", + test: /[\\/]src[\\/]components[\\/]ui[\\/](button|input|label|textarea)\.tsx$/, + }, + { + name: "ui-shell", + test: /[\\/]src[\\/]components[\\/]ui[\\/](avatar|dialog|dropdown-menu|input-group|separator|sheet|skeleton|tooltip)\.tsx$/, + }, + // The icons that the docs editor alone draws: a page that shows no doc loads none of them. + // AFTER vendor-icons, whose test leaves them out: a group also takes what its files import, so + // ahead of it this one would hold lucide's shared parts, and every page would load it. + // src/components/docs-editor/icons.test.ts holds the list to what the sources import. + { + name: "docs-editor-icons", + test: new RegExp( + `node_modules[\\\\/]lucide-react[\\\\/]dist[\\\\/]esm[\\\\/]icons[\\\\/](?:${docsEditorIcons.join("|")})\\.m?js$`, + ), + }, +]; + +/** THE SCRIPT OF THE FRAME a kind's chat view runs in, as one classic script of the published + * package (scripts/build-agent-kind-view-frame.ts builds it from src/browser/agent-kind-view-frame.ts). + * The frame is sandboxed with an opaque origin: a module script would need CORS and an import + * map; a classic `<script src>` needs neither. A page names it by its URL at the build it pins. */ +export const AGENT_KIND_VIEW_FRAME = "agent-kind-view-frame.js"; + +/** package.json's publishConfig.exports for `entries`: each name at its built file, the + * stylesheet, and iterate's look over it with each font file its url()s name beside it + * (`fonts`, scripts/iterate-look.ts). esm.sh serves a file by a name only an export names, and a + * wildcard export does not count. */ +export function publishExports(entries: Record<string, string>, fonts: string[]) { + return { + ...Object.fromEntries(Object.keys(entries).map((name) => [`./${name}`, `./dist/${name}.mjs`])), + ...Object.fromEntries( + vendorChunks.map(({ name }) => [`./chunks/${name}`, `./dist/chunks/${name}.mjs`]), + ), + "./styles.css": "./dist/styles.css", + // the docs editor's file tree, its own build (scripts/build-docs-tree.ts) + "./components/docs-editor/doc-tree": "./dist/components/docs-editor/doc-tree.mjs", + // the docs editor's page's whole stylesheet (src/browser/docs-editor.css), in place of styles.css + "./docs-editor.css": "./dist/docs-editor.css", + [`./${AGENT_KIND_VIEW_FRAME}`]: `./dist/${AGENT_KIND_VIEW_FRAME}`, + "./iterate.css": "./dist/iterate.css", + ...Object.fromEntries(fonts.map((file) => [`./fonts/${file}`, `./dist/fonts/${file}`])), + }; +}
A components.json
@@ -0,0 +1,21 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "base-nova", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/styles/globals.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "iconLibrary": "lucide", + "aliases": { + "components": "#/components", + "utils": "cn", + "hooks": "#/hooks", + "lib": "#/lib", + "ui": "#/components/ui" + } +}
A doctor.config.mjs
@@ -0,0 +1,43 @@ +// React Doctor's settings for this package (`npx react-doctor@latest --yes .` here scores 100). +export default { + ignore: { + // The vendored shadcn components are upstream's, byte for byte (src/components/ui/AGENTS.md): + // the drift check refuses an edit, and a finding in them is fixed upstream or at a call site. + files: ["src/components/ui/**"], + overrides: [ + // A `*.client.tsx` module IS the lazy chunk: code-block.tsx and code-editor.tsx load it with + // import(), so that CodeMirror and its grammars stay out of every other page. + { + files: ["src/components/*.client.tsx"], + rules: ["react-doctor/prefer-dynamic-import"], + }, + // The docs editor IS the page that loads it: DocEditor mounts CodeMirror bound to the doc's + // Y.Text as the page opens, showing the text the page read, so a lazy import would only + // delay that first paint (src/components/docs-editor/AGENTS.md). The shared source setup is + // also loaded on demand by the repo IDE (src/components/repo-ide/codemirror.ts). + { + files: ["src/components/docs-editor/*.ts", "src/lib/source-editor.ts"], + rules: ["react-doctor/prefer-dynamic-import"], + }, + // AN ENTRY OF THE PUBLISHED PACKAGE hands a page its component AND the readers of that + // component's state in ONE module: a no-build page loads the entry with one import() and + // calls both (`kit.SecretsPage`, `kit.secretsPageStateOf(view)`). The rule keeps Fast Refresh + // whole in a dev server, which costs these four files a full reload when they are edited. + { + files: [ + "src/components/analytics-page.tsx", + "src/components/context-explorer/context-explorer.tsx", + "src/components/repo-ide/repo-ide.tsx", + "src/components/secrets-page.tsx", + ], + rules: ["react-doctor/only-export-components"], + }, + // An example page's inline script runs in a browser and nowhere else: it has no server render + // to guard a global from. + { + files: ["examples/*.html"], + rules: ["react-doctor/no-unguarded-browser-global-at-module-scope"], + }, + ], + }, +};
A examples/README.md
@@ -0,0 +1,75 @@ +# No-build pages + +Each file here is a whole page that imports `@iterate-com/ui` from esm.sh, to copy and change. The +package [README](../README.md) shows the import map and a first page. + +> [!WARNING] +> These pages were written against the old platform at `https://os.iterate.com` (`ISSUER` in +> `any-website.html`; `this.auth.require` and `this.getItx()` in the config-worker routes the `.ts` +> pages name). The browser specs that proved them left the repository with that platform. They are +> not yet proven against a mind stack. + +- **Pin a version.** `<version>` is exact, for example the `main` dist-tag of + `https://registry.npmjs.org/@iterate-com/ui` on the day you write the page. +- **Use path-shaped URLs only.** The browser cannot prefix-map a URL with a `?query`: it drops the + query when it resolves a subpath against it. + +## Another React library + +`events-chart-page.ts` charts a context's events with recharts, above the same context in +`ContextView`. A library loads from esm.sh with `?external=react,react-dom`, which leaves its React +imports to the page's import map, so it uses the React that this package bundles: + +```json +"recharts": "https://esm.iterate.com/recharts@3.10.1?external=react,react-dom" +``` + +- **Without the flag**, esm.sh gives the library its own React. The page is blank and the console + says "Cannot read properties of null (reading 'useContext')" (or `'useState'`). +- **`?external=react` alone** leaves a library that imports react-dom (recharts, Floating UI) with a + second react-dom. +- **React is 19**, and the package serves only `react`, `react/jsx-runtime`, + `react/compiler-runtime`, `react-dom` and `react-dom/client`. A library that imports another + module (`react-dom/server`) fails to load on a 404. +- **Only React is shared.** A library built on Base UI or CodeMirror brings its own copy. That works + while nothing of one copy goes to the other (a CodeMirror extension for our editor would not). +- **The library's styles are its own.** Give it the stylesheet's variables (`var(--border)`, + `var(--muted-foreground)`) and it matches our components. +- For telemetry over time, use our `components/time-chart`. + +## Signing in + +A page reads and changes a mind as the person who views it. How it signs them in depends on where +it is served: + +| Served from | Signs in with | Example | +| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | +| The mind's own host, by its worker | The host's session: `createIterateClient(...).authenticate(location.href)` from `live` | `mind-host-page.ts` | +| Any other website | Its own OAuth client, written in the page: it registers, sends the person to iterate with PKCE, and opens `/api` with the token | `any-website.html` | +| A Claude artifact | The viewer's iterate connector, through the artifact's `mcp` capability | None: it runs only on claude.ai | + +An agent that builds a page for its mind serves it from the mind's host: there is no sign-in UI, and +the worker can write what it knows into the page. + +- **On any website**, the sign-in is the page's own code (about a hundred lines in the example). + Nothing in `iterate` or this package does it. `live` gives the page only the socket, + `newWebSocketRpcSession`, from the copy of capnweb that the hooks use. +- **A page that is not framed** goes to iterate and comes back to its own address with the code. The + pending sign-in waits in `sessionStorage`. There is no popup. +- **A framed page** (jsfiddle's result pane) cannot show iterate's sign-in, and jsfiddle's + `Cross-Origin-Opener-Policy: same-origin` cuts it off from any window it opens. So its sign-in + ends on `https://callback.iterate.com/`, where a button copies the result for the person to paste + back into the page. +- **The token stays in memory**, and a reload signs in again. Hosts like jsfiddle share one origin + between all pages, so a stored token would belong to every page. The client id is stored, per + address. +- **A platform on localhost**: Chrome asks the person before a public page reaches it (Local Network + Access). +- **In a Claude artifact**, load the package from + `https://cdn.jsdelivr.net/npm/@iterate-com/ui@<version>/dist/` (the artifact's CSP allows that CDN, + not esm.sh; the files end in `.mjs`) with `styles.css` inlined. Declare + `{ "mcp": { "servers": [{ "server": "iterate", "tools": ["run"] }] } }`, then + `(await window.claude.use("mcp")).callTool("iterate", "run", { project, script }, { cache: false })` + runs `script` (`async (itx) => …`) as the viewer and answers `{ payload: { result } }`. The + connector's argument is still `project`: it is the old platform's MCP server. Nothing is live: the + page reads again to refresh.
A examples/agent-chat-page.ts
@@ -0,0 +1,139 @@ +// agent-chat-page.ts — A NO-BUILD PAGE WITH AN AGENT'S CHAT (packages/ui/src/components/agent-chat/AGENTS.md): the chat agents.iterate.com shows, `AgentChat`, on a mind's own host, for a signed-in +// member. The worker writes the mind's agents into the page. The page holds one agent's context +// with the host's session and hands `AgentChat` what `useIterateContext` reads of it. Under each +// thing a person said is a row of the page's own (`itemFooter`): here, a link that opens that +// event in the chat's Events tab. +// Copy this file into a mind's config repo beside worker.ts, and route a slug to it in `fetch`: +// +// if (routingSlug === "chat") { +// const denied = this.auth.require(request); +// if (denied) return denied; +// using itx = this.getItx(); +// return await agentChatPage(itx); // awaited: `using` releases itx when the function returns +// } +// +// It is then `chat--<mind>.iterate.app` (or `/minds/<mind>/chat/` where minds are +// paths). test/playwright/ui/agent-chat.spec.ts commits it to a fresh mind and opens it. A page +// you keep pins an exact version of @iterate-com/ui in place of `@main`. + +/** The page, with what only the worker knows written into it: which mind this host is, and its + * agents, for the path box. */ +export async function agentChatPage(scope: { + whoami(): Promise<{ mindId: string; mindSlug: string }>; +}) { + // The mind's init case installs the agents app (`installAgents(itx)`, as the default + // template's does), so its root has `itx.agents`, which a plain scope's type does not name. + const itx = scope as typeof scope & { agents: { list(): Promise<{ path: string }[]> } }; + const [{ mindId, mindSlug }, agents] = await Promise.all([itx.whoami(), itx.agents.list()]); + const mind = { id: mindId, slug: mindSlug, agents: agents.map((agent) => agent.path) }; + // JSON inside a script element, `<` escaped so no value can close the element + const data = JSON.stringify(mind).replaceAll("<", "\\u003c"); + return new Response( + `<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>Chat</title> + <script type="importmap"> + { "imports": { "@iterate-com/ui/": "https://esm.iterate.com/@iterate-com/ui@main/" } } + </script> + <link rel="stylesheet" href="https://esm.iterate.com/@iterate-com/ui@main/styles.css" /> + <script type="application/json" id="mind">${data}</script> + </head> + <body> + <div id="root"><p class="p-4 text-sm text-muted-foreground">Connecting…</p></div> + <script type="module"> + import { html, render, useCallback, useState } from "@iterate-com/ui/page"; + import { AgentChat } from "@iterate-com/ui/components/agent-chat/agent-chat"; + import { Button } from "@iterate-com/ui/components/ui/button"; + import { Input } from "@iterate-com/ui/components/ui/input"; + import { Toaster } from "@iterate-com/ui/components/ui/sonner"; + import { createIterateClient, useContextStub, useIterateContext } from "@iterate-com/ui/live"; + + // what the worker knows and the page doesn't: which mind this host is, and its agents + const mind = JSON.parse(document.getElementById("mind").textContent); + // the session this host's sign-in set (the worker only serves a signed-in member) + const { api, info } = await createIterateClient().authenticate(location.href); + + function Chat({ path }) { + // the chat's own state: the tab, the open trace, the Events tab's choices + const [state, setState] = useState({}); + const patch = (change) => setState((previous) => ({ ...previous, ...change })); + const root = useContextStub(() => api.minds.get(mind.id), []); + const agent = useContextStub(root.stub ? () => root.stub.cd(path) : null, [root.stub, path]); + // ONE live read of the agent's context, with the events and the history the chat asks for + const context = useIterateContext(agent.stub, AgentChat.contextOptions); + // one function while the mind's handle is the same: a new one would draw every row again + const signedUrl = useCallback(async (file) => { + // asked of the mind: only an iterate agent's context links to the root, where files is + if (!root.stub) throw new Error("not connected"); + return (await root.stub.files.get(file).url()).url; + }, [root.stub]); + return html\`<\${AgentChat} + path=\${path} + context=\${context} + error=\${root.error || agent.error} + state=\${state} + onStateChange=\${patch} + onMessage=\${async ({ message, files }) => { + // a handle of its own: a person can send before the chat's contexts have opened + const itx = await api.minds.get(mind.id); + try { + await itx.agents.get(path).message({ message, files }); + } finally { + itx[Symbol.dispose](); + } + }} + onAppend=\${agent.stub ? (events) => agent.stub.append(...events) : undefined} + signedUrl=\${signedUrl} + itemFooter=\${(item) => + item.kind === "user" && + html\`<div class="flex justify-end pb-1"> + <\${Button} variant="link" size="xs" className="text-muted-foreground" onClick=\${() => patch({ view: "events", event: item.offset })}> + event #\${item.offset} + <//> + </div>\`} + />\`; + } + + function App() { + const [path, setPath] = useState(new URLSearchParams(location.search).get("agent") || mind.agents[0] || ""); + const open = (event) => { + event.preventDefault(); + const next = String(new FormData(event.currentTarget).get("agent") || ""); + history.replaceState(null, "", "?agent=" + encodeURIComponent(next)); + setPath(next); + }; + // The chat fills a column of a set height. Its copy buttons answer with a toast, which + // needs @iterate-com/ui's Toaster on the page, once. + return html\`<div class="flex h-dvh flex-col"> + <header class="flex shrink-0 flex-wrap items-center gap-3 border-b px-4 py-2 text-sm"> + <span class="font-medium">\${mind.slug}</span> + <span class="text-muted-foreground">as \${info.principal.email || info.principal.actor}</span> + <form class="ml-auto flex items-center gap-2" onSubmit=\${open}> + <\${Input} name="agent" list="agents" defaultValue=\${path} aria-label="Agent" className="h-8 w-64 font-mono" /> + <datalist id="agents">\${mind.agents.map((option) => html\`<option key=\${option} value=\${option} />\`)}</datalist> + <\${Button} type="submit" size="sm">Open<//> + </form> + <form method="post" action="/.auth/logout"> + <\${Button} type="submit" variant="outline" size="sm">Sign out<//> + </form> + </header> + \${path + ? html\`<\${Chat} key=\${path} path=\${path} />\` + : html\`<p class="p-4 text-sm text-muted-foreground">This mind has no agents yet.</p>\`} + <\${Toaster} /> + </div>\`; + } + + render(html\`<\${App} />\`, document.getElementById("root")); + </script> + </body> +</html> +`, + { + headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }, + }, + ); +}
A examples/any-website.html
@@ -0,0 +1,305 @@ +<!-- + A no-build page on any website (GitHub Pages, jsfiddle, a file on S3) that signs in with iterate and + shows one of your mind's contexts live (packages/ui/examples/README.md "Signing in"). Everything it takes + is in this file: copy it and change it. The page is its own OAuth client of iterate's; the token it + gets opens iterate's API. In a frame (jsfiddle's result pane) the sign-in opens in a new window and + ends on callback.iterate.com, where the person copies it to paste back here. + test/playwright/ui/sign-in.spec.ts runs both ways. + A page you keep pins an exact version of @iterate-com/ui in place of `@main`. +--> +<script type="importmap"> + { "imports": { "@iterate-com/ui/": "https://esm.iterate.com/@iterate-com/ui@main/" } } +</script> +<link rel="stylesheet" href="https://esm.iterate.com/@iterate-com/ui@main/styles.css" /> +<div id="app" class="flex h-screen flex-col"></div> +<script type="module"> + import { html } from "@iterate-com/ui/page"; + import { createRoot } from "@iterate-com/ui/react-dom/client"; + import { ContextView } from "@iterate-com/ui/components/context-view/context-view"; + import { Button } from "@iterate-com/ui/components/ui/button"; + import { Input } from "@iterate-com/ui/components/ui/input"; + import { Spinner } from "@iterate-com/ui/components/ui/spinner"; + import { newWebSocketRpcSession, useContextStub, useIterateContext } from "@iterate-com/ui/live"; + + const ISSUER = "https://os.iterate.com"; + + // SIGNING IN. iterate sends the person back to an address with a one-time code in it, which the + // page trades for a token for iterate's API. A page that isn't framed is its own return address + // (without its query). A framed one has none: iterate's sign-in won't show inside a frame, the + // page can't follow the window it opens (jsfiddle cuts it off), and its own address answers a + // window with a 404 there. Its sign-in ends on callback.iterate.com, a page of iterate's with a + // button that copies the address for the person to bring back. + const framed = window.top !== window.self; + const redirectUri = framed + ? "https://callback.iterate.com/" + : location.origin + location.pathname; + const resource = ISSUER + "/api"; + + /** This page's client id at iterate, which registers any page (RFC 7591). Kept in this browser, + * one per page address: it is no secret. */ + async function clientId() { + const key = "iterate-client-id:" + ISSUER + " " + redirectUri; + const kept = read("localStorage", key); + if (kept) return kept; + const response = await fetch(ISSUER + "/oauth2/register", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + client_name: "Context viewer on " + location.host, // what iterate's consent page calls this page + redirect_uris: [redirectUri], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + scope: "iterate", + }), + }); + if (!response.ok) + throw new Error("iterate didn't register this page: " + (await response.text())); + const { client_id } = await response.json(); + write("localStorage", key, client_id); + return client_id; + } + + /** A sign-in to start: iterate's address for it, and what later proves its answer is this page's + * (`state`, and PKCE's `verifier`, RFC 7636). */ + async function newSignIn() { + const verifier = random(32); + const state = random(16); + const [digest, client] = await Promise.all([ + crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)), + clientId(), + ]); + const url = new URL("/oauth2/auth", ISSUER); + url.search = new URLSearchParams({ + response_type: "code", + client_id: client, + redirect_uri: redirectUri, + scope: "iterate", + state, + code_challenge: base64url(new Uint8Array(digest)), + code_challenge_method: "S256", + resource, + }); + return { url: url.href, state, verifier, client }; + } + + /** The token for the address a sign-in ended on, which carries iterate's code. */ + async function tokenFor(address, signIn) { + const answer = new URLSearchParams(URL.canParse(address) ? new URL(address).search : ""); + if (answer.get("error")) + throw new Error( + "iterate refused: " + (answer.get("error_description") || answer.get("error")), + ); + if (answer.get("state") !== signIn.state || answer.get("iss") !== ISSUER || !answer.get("code")) + throw new Error( + "That isn't this sign-in. Paste what you copied where it ended, or sign in again.", + ); + const response = await fetch(ISSUER + "/oauth2/token", { + method: "POST", + body: new URLSearchParams({ + grant_type: "authorization_code", + code: answer.get("code"), + redirect_uri: redirectUri, + client_id: signIn.client, + code_verifier: signIn.verifier, + resource, + }), + }); + if (!response.ok) throw new Error("iterate didn't issue a token: " + (await response.text())); + return (await response.json()).access_token; + } + + /** iterate's API as the person. A browser can't put a token on a WebSocket's request, so the + * socket opens bare and the token is its first call. The token stays in memory: a reload signs in + * again (jsfiddle serves every fiddle from one origin, so a stored token would be every fiddle's). */ + async function sessionWith(token) { + const socket = newWebSocketRpcSession(ISSUER.replace(/^http/, "ws") + "/api"); + const api = socket.authenticate({ type: "bearer", token }); + return { api, info: await api.info() }; + } + + // Storage is refused in some frames and private windows: the page then registers, or signs in, again. + function read(storage, key) { + try { + return window[storage].getItem(key); + } catch { + return null; + } + } + function write(storage, key, value) { + try { + if (value === null) window[storage].removeItem(key); + else window[storage].setItem(key, value); + } catch {} + } + const base64url = (bytes) => + btoa(String.fromCharCode(...bytes)) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); + const random = (length) => base64url(crypto.getRandomValues(new Uint8Array(length))); + + // THE PAGE + const root = createRoot(document.getElementById("app")); + const store = { + busy: false, + error: "", + signIn: null, + session: null, + minds: [], + mindId: "", + path: "/", + view: {}, + }; + const update = (patch) => { + Object.assign(store, patch); + root.render(html`<${App} ...${store} />`); + }; + + async function start() { + update({ busy: true, error: "" }); + try { + const signIn = await newSignIn(); + // The sign-in waits in the tab's own storage: this tab leaves for iterate and comes back, or + // (framed) a phone reloads it while the person is away in the sign-in's window. + write("sessionStorage", "iterate-sign-in", JSON.stringify(signIn)); + if (!framed) return location.assign(signIn.url); + // a browser may refuse a window this long after the click: the page links the address too + window.open(signIn.url, "_blank", "noopener"); + update({ busy: false, signIn }); + } catch (error) { + update({ busy: false, error: error.message }); + } + } + + async function finish(address, signIn) { + update({ busy: true, error: "" }); + try { + const session = await sessionWith(await tokenFor(address, signIn)); + write("sessionStorage", "iterate-sign-in", null); + const minds = await session.api.minds.list(); + update({ + busy: false, + signIn: null, + session, + minds, + mindId: minds.length ? minds[0].id : "", + }); + } catch (error) { + update({ busy: false, error: error.message }); + } + } + + function Start({ error }) { + return html`<div class="m-auto flex max-w-md flex-col gap-3 p-4 text-center text-sm"> + <strong>See one of your iterate minds, live</strong> + <${Button} onClick=${start}>Sign in with iterate<//> + ${error ? html`<p class="text-destructive" role="alert">${error}</p>` : null} + </div>`; + } + + // A framed page, while the person signs in in another window. + function Waiting({ signIn, error }) { + const paste = (event) => { + event.preventDefault(); + finish(String(new FormData(event.currentTarget).get("address")).trim(), signIn); + }; + const cancel = () => { + write("sessionStorage", "iterate-sign-in", null); + update({ signIn: null, error: "" }); + }; + return html`<div class="m-auto flex max-w-md flex-col gap-3 p-4 text-center text-sm"> + <strong>Signing in with iterate</strong> + <p class="text-muted-foreground"> + Sign in in the window that opened. If none did,${" "} + <a class="underline" href=${signIn.url} target="_blank">open iterate's sign-in</a>. + </p> + <p class="text-muted-foreground"> + It ends on a page with a Copy button. Copy your sign-in there, come back, and paste it: + </p> + <form class="flex gap-2" onSubmit=${paste}> + <${Input} name="address" aria-label="Your sign-in" className="h-9" /> + <${Button} type="submit">Continue<//> + </form> + ${error ? html`<p class="text-destructive" role="alert">${error}</p>` : null} + <${Button} variant="ghost" onClick=${cancel}>Cancel<//> + </div>`; + } + + function Viewer({ api, mindId, path, view }) { + const mind = useContextStub(() => api.minds.get(mindId), [api, mindId]); + const shown = useContextStub(mind.stub ? () => mind.stub.cd(path) : null, [mind.stub, path]); + const context = useIterateContext(shown.stub); + return html`<${ContextView} + title=${path} + context=${context} + error=${mind.error || shown.error} + state=${view} + onStateChange=${(patch) => update({ view: { ...store.view, ...patch } })} + onAppend=${shown.stub ? (events) => shown.stub.append(...events) : undefined} + className="min-h-0 flex-1" + />`; + } + + function App(s) { + if (s.busy) return html`<${Spinner} className="m-auto" />`; + if (s.signIn) return html`<${Waiting} signIn=${s.signIn} error=${s.error} />`; + if (!s.session) return html`<${Start} error=${s.error} />`; + const open = (event) => { + event.preventDefault(); + const form = new FormData(event.currentTarget); + update({ + mindId: String(form.get("mind")), + path: String(form.get("path") || "/").trim() || "/", + view: {}, + }); + }; + return html` + <form class="flex flex-wrap items-center gap-3 border-b px-4 py-2 text-sm" onSubmit=${open}> + <span class="mr-auto" + >${s.session.info.principal.email || s.session.info.principal.actor}</span + > + <select + name="mind" + aria-label="Mind" + defaultValue=${s.mindId} + class="h-8 rounded-lg border px-2" + > + ${s.minds.map((mind) => html`<option key=${mind.id} value=${mind.id}>${mind.slug}</option>`)} + </select> + <${Input} + name="path" + aria-label="Context" + defaultValue=${s.path} + className="h-8 w-64 font-mono" + /> + <${Button} type="submit" size="sm">Open<//> + </form> + ${ + s.mindId + ? html`<${Viewer} + key=${s.mindId + s.path} + api=${s.session.api} + mindId=${s.mindId} + path=${s.path} + view=${s.view} + />` + : html`<p class="m-auto text-sm text-muted-foreground">You have no minds yet.</p>` + } + `; + } + + // A sign-in this tab started and hasn't finished. Back from iterate with its answer in the + // address: finish it. Framed, the person is away signing in, or back with what they copied. + const kept = read("sessionStorage", "iterate-sign-in"); + const pending = kept ? JSON.parse(kept) : null; + if (!new URLSearchParams(location.search).has("state")) + update({ signIn: framed ? pending : null }); + else if (!pending) update({ error: "This tab didn't start that sign-in. Sign in again." }); + else { + const address = location.href; + write("sessionStorage", "iterate-sign-in", null); + history.replaceState(null, "", redirectUri); // the code works once: a reload shouldn't send it again + finish(address, pending); + } +</script>
A examples/change-my-mind.html
@@ -0,0 +1,61 @@ +<!-- + A blog post with the Change my mind button, both ways (README.md "The Change my mind button"): the + custom element, which needs no React and no stylesheet, and the React component beside the kit's + other components. A page needs only one of them. Replace <version> with an exact version. +--> +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>How I learned to answer the phone</title> + <script type="importmap"> + { + "imports": { + "@iterate-com/ui/": "https://esm.iterate.com/@iterate-com/ui@<version>/", + "react": "https://esm.iterate.com/@iterate-com/ui@<version>/react", + "react/": "https://esm.iterate.com/@iterate-com/ui@<version>/react/", + "react-dom": "https://esm.iterate.com/@iterate-com/ui@<version>/react-dom", + "react-dom/": "https://esm.iterate.com/@iterate-com/ui@<version>/react-dom/" + } + } + </script> + <!-- after the import map: a module script above it makes the browser refuse the map --> + <script + type="module" + src="https://esm.iterate.com/@iterate-com/ui@<version>/change-my-mind" + ></script> + <link rel="stylesheet" href="https://esm.iterate.com/@iterate-com/ui@<version>/styles.css" /> + </head> + <body class="mx-auto max-w-2xl p-8"> + <h1 class="text-2xl font-medium">How I learned to answer the phone</h1> + <p class="my-4">What this mind changed in itself, and why.</p> + + <!-- the element: the post is this page, without its query or hash --> + <change-my-mind></change-my-mind> + + <!-- a list of posts: each row has the quiet button, outline and small --> + <ul class="my-6 flex flex-col gap-2"> + <li class="flex items-center justify-between gap-4"> + <a href="https://blog.example.com/answer-the-phone">How I learned to answer the phone</a> + <change-my-mind + source="https://blog.example.com/answer-the-phone" + variant="outline" + size="sm" + ></change-my-mind> + </li> + </ul> + + <!-- the React component --> + <div id="react-button" class="mt-4"></div> + <script type="module"> + import { html, render } from "@iterate-com/ui/page"; + import { ChangeMyMindButton } from "@iterate-com/ui/components/change-my-mind-button"; + + render( + html`<${ChangeMyMindButton} variant="outline" size="sm" />`, + document.getElementById("react-button"), + ); + </script> + </body> +</html>
A examples/events-chart-page.ts
@@ -0,0 +1,214 @@ +// events-chart-page.ts — A NO-BUILD PAGE THAT MIXES SOMEONE ELSE'S REACT LIBRARY WITH ITERATE'S +// (packages/ui/examples/README.md "Another React library"): a context's events charted over time by recharts, +// above the same context in ContextView, iterate's own viewer. One live read feeds both, so an event +// appended in the viewer raises a bar. recharts comes from esm.sh with `?external=react,react-dom`, +// which leaves its `react` imports for the import map, so it uses the React @iterate-com/ui brings. +// Copy this file into a mind's config repo beside worker.ts, and route a slug to it in `fetch`: +// +// if (routingSlug === "activity") { +// const denied = this.auth.require(request); +// if (denied) return denied; +// using itx = this.getItx(); +// return await eventsChartPage(itx); // awaited: `using` releases itx when the function returns +// } +// +// It is then `activity--<mind>.iterate.app` (or `/minds/<mind>/activity/` where minds +// are paths). test/playwright/ui/third-party-library.spec.ts commits it to a fresh mind and opens +// it. A page you keep pins an exact version of @iterate-com/ui in place of `@main`. + +/** The page, with what only the worker knows written into it: which mind this host is, and its + * contexts (the `mind` facet's registry), for the path box. */ +export async function eventsChartPage(itx: { + whoami(): Promise<{ mindId: string; mindSlug: string }>; + facets: { get(name: "mind"): { snapshot(): Promise<{ state: { contexts?: object } }> } }; +}) { + const [{ mindId, mindSlug }, { state }] = await Promise.all([ + itx.whoami(), + itx.facets.get("mind").snapshot(), + ]); + const mind = { + id: mindId, + slug: mindSlug, + paths: ["/", ...Object.keys(state.contexts || {}).sort()], + }; + // JSON inside a script element, `<` escaped so no value can close the element + const data = JSON.stringify(mind).replaceAll("<", "\\u003c"); + return new Response( + `<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>Activity</title> + <script type="importmap"> + { + "imports": { + "@iterate-com/ui/": "https://esm.iterate.com/@iterate-com/ui@main/", + "react": "https://esm.iterate.com/@iterate-com/ui@main/react", + "react/": "https://esm.iterate.com/@iterate-com/ui@main/react/", + "react-dom": "https://esm.iterate.com/@iterate-com/ui@main/react-dom", + "react-dom/": "https://esm.iterate.com/@iterate-com/ui@main/react-dom/", + "recharts": "https://esm.iterate.com/recharts@3.10.1?external=react,react-dom" + } + } + </script> + <link rel="stylesheet" href="https://esm.iterate.com/@iterate-com/ui@main/styles.css" /> + <script type="application/json" id="mind">${data}</script> + </head> + <body> + <div id="root"><p class="p-4 text-sm text-muted-foreground">Connecting…</p></div> + <script type="module"> + import { html, render, useState } from "@iterate-com/ui/page"; + import { ContextView } from "@iterate-com/ui/components/context-view/context-view"; + import { Button } from "@iterate-com/ui/components/ui/button"; + import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@iterate-com/ui/components/ui/card"; + import { Input } from "@iterate-com/ui/components/ui/input"; + import { createIterateClient, useContextStub, useIterateContext } from "@iterate-com/ui/live"; + import { Bar, BarChart, CartesianGrid, Legend, Rectangle, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts"; + + // what the worker knows and the page doesn't: which mind this host is, and its contexts + const mind = JSON.parse(document.getElementById("mind").textContent); + // the session this host's sign-in set (the worker only serves a signed-in member) + const { api, info } = await createIterateClient().authenticate(location.href); + + // THE CHART'S SERIES: who wrote an event, in a fixed order with a colour each, so a colour + // means the same writer whichever of them a context has. + const WRITERS = [ + { name: "People and apps", colour: "#2a78d6", wrote: (source) => !source.processor && !source.platform && Boolean(source.principal) }, + { name: "Processors", colour: "#eb6834", wrote: (source) => Boolean(source.processor) }, + { name: "The platform", colour: "#1baf7a", wrote: () => true }, + ]; + // A bar's span of time: the shortest that shows the events in no more than 48 bars. + const SPANS = [ + { ms: 60_000, unit: "a minute", label: { hour: "numeric", minute: "2-digit" } }, + { ms: 3_600_000, unit: "an hour", label: { weekday: "short", hour: "numeric" } }, + { ms: 86_400_000, unit: "a day", label: { month: "short", day: "numeric" } }, + ]; + + /** A bar for each span of time from the first event to the last, counting each writer's. */ + function barsOf(events) { + const times = events.map((event) => Date.parse(event.createdAt)); + const span = SPANS.find(({ ms }) => (times.at(-1) - times[0]) / ms < 48) || SPANS.at(-1); + const bars = new Map(); + for (let time = Math.floor(times[0] / span.ms) * span.ms; time <= times.at(-1); time += span.ms) + bars.set(time, { time }); + events.forEach((event, index) => { + const bar = bars.get(Math.floor(times[index] / span.ms) * span.ms); + const { name } = WRITERS.find((writer) => writer.wrote(event.source)); + bar[name] = (bar[name] || 0) + 1; + }); + // the series on top of each bar, whose end is rounded; a span with no events has none + for (const bar of bars.values()) bar.top = WRITERS.findLast(({ name }) => bar[name] > 0)?.name; + return { span, bars: [...bars.values()] }; + } + + const swatch = (colour) => html\`<span class="inline-block" style=\${{ width: 10, height: 10, borderRadius: 2, background: colour }} />\`; + + function BarTooltip({ active, payload, label, format }) { + if (!active || !payload || !payload.length) return null; + return html\`<div class="rounded-lg border bg-background p-2 text-xs shadow-md"> + <div class="font-medium">\${format(label)}</div> + \${payload.toReversed().map((item) => html\`<div key=\${item.dataKey} class="flex items-center gap-2"> + \${swatch(item.color)}<span class="text-muted-foreground">\${item.dataKey}</span> + <span class="tabular-nums" style=\${{ marginLeft: "auto" }}>\${item.value}</span> + </div>\`)} + </div>\`; + } + + // recharts, with nothing of iterate's in it but the colours of the stylesheet + function Activity({ path, events }) { + if (!events.length) return null; + const { span, bars } = barsOf(events); + const format = (time) => new Intl.DateTimeFormat(undefined, span.label).format(new Date(time)); + const axis = { fill: "var(--muted-foreground)", fontSize: 12 }; + return html\`<\${Card}> + <\${CardHeader}> + <\${CardTitle}>Activity<//> + <\${CardDescription}>\${events.length} events of \${path}, a bar \${span.unit}, by who wrote them.<//> + <//> + <\${CardContent}> + <div style=\${{ height: 220 }}> + <\${ResponsiveContainer} width="100%" height="100%"> + <\${BarChart} data=\${bars} margin=\${{ top: 4, right: 4, bottom: 0, left: 0 }} barCategoryGap=\${1} maxBarSize=\${48}> + <\${CartesianGrid} vertical=\${false} stroke="var(--border)" /> + <\${XAxis} dataKey="time" tickFormatter=\${format} minTickGap=\${24} tickLine=\${false} axisLine=\${false} tick=\${axis} /> + <\${YAxis} allowDecimals=\${false} width=\${40} tickLine=\${false} axisLine=\${false} tick=\${axis} /> + <\${Tooltip} cursor=\${{ fill: "var(--muted)" }} content=\${(props) => html\`<\${BarTooltip} ...\${props} format=\${format} />\`} /> + <\${Legend} iconType="square" iconSize=\${10} itemSorter=\${null} formatter=\${(name) => html\`<span class="text-sm text-foreground">\${name}</span>\`} /> + \${WRITERS.map(({ name, colour }) => html\`<\${Bar} + key=\${name} + dataKey=\${name} + stackId="events" + fill=\${colour} + stroke="var(--background)" + strokeWidth=\${1} + isAnimationActive=\${false} + shape=\${(bar) => html\`<\${Rectangle} ...\${bar} radius=\${bar.payload.top === name ? [3, 3, 0, 0] : 0} />\`} + />\`)} + <//> + <//> + </div> + <//> + <//>\`; + } + + function Context({ path }) { + // the view's own state: the open inspector, the search, the filters + const [state, setState] = useState({}); + const root = useContextStub(() => api.minds.get(mind.id), []); + const shown = useContextStub(root.stub ? () => root.stub.cd(path) : null, [root.stub, path]); + // ONE live read of the context, for recharts' chart and for iterate's viewer + const context = useIterateContext(shown.stub); + return html\`<div class="flex flex-col gap-4"> + <\${Activity} path=\${path} events=\${context.events} /> + <div class="flex flex-col overflow-hidden rounded-lg border" style=\${{ height: 480 }}> + <\${ContextView} + title=\${path} + context=\${context} + error=\${root.error || shown.error} + state=\${state} + onStateChange=\${(patch) => setState((previous) => ({ ...previous, ...patch }))} + onAppend=\${shown.stub ? (events) => shown.stub.append(...events) : undefined} + className="min-h-0 flex-1" + /> + </div> + </div>\`; + } + + function App() { + const [path, setPath] = useState(new URLSearchParams(location.search).get("path") || "/"); + const open = (event) => { + event.preventDefault(); + const next = String(new FormData(event.currentTarget).get("path") || "/"); + history.replaceState(null, "", "?path=" + encodeURIComponent(next)); + setPath(next); + }; + // Sign out is the host's: it ends the session on a POST to /.auth/logout and sends the + // browser back here, to sign in again. + return html\`<main class="mx-auto flex max-w-4xl flex-col gap-4 p-4"> + <header class="flex flex-wrap items-center gap-3 text-sm"> + <span class="font-medium">\${mind.slug}</span> + <span class="text-muted-foreground">as \${info.principal.email || info.principal.actor}</span> + <form class="ml-auto flex items-center gap-2" onSubmit=\${open}> + <\${Input} name="path" list="paths" defaultValue=\${path} aria-label="Context" className="h-8 w-64 font-mono" /> + <datalist id="paths">\${mind.paths.map((option) => html\`<option key=\${option} value=\${option} />\`)}</datalist> + <\${Button} type="submit" size="sm">Open<//> + </form> + <form method="post" action="/.auth/logout"> + <\${Button} type="submit" variant="outline" size="sm">Sign out<//> + </form> + </header> + <\${Context} key=\${path} path=\${path} /> + </main>\`; + } + + render(html\`<\${App} />\`, document.getElementById("root")); + </script> + </body> +</html> +`, + { + headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }, + }, + ); +}
A examples/mind-host-page.ts
@@ -0,0 +1,108 @@ +// mind-host-page.ts — A NO-BUILD PAGE ON A MIND'S OWN HOST (packages/ui/examples/README.md "Signing in"): +// the mind's config worker serves it to a signed-in member, and it reads one of the mind's +// contexts live, with the host's own session (`createIterateClient`) and @iterate-com/ui from esm.sh. +// Copy this file into a mind's config repo beside worker.ts, and route a slug to it in `fetch`: +// +// if (routingSlug === "contexts") { +// const denied = this.auth.require(request); +// if (denied) return denied; +// using itx = this.getItx(); +// return await mindHostPage(itx); // awaited: `using` releases itx when the function returns +// } +// +// It is then `contexts--<mind>.iterate.app` (or `/minds/<mind>/contexts/` where minds +// are paths). test/playwright/ui/sign-in.spec.ts commits it to a fresh mind and opens it. A page +// you keep pins an exact version of @iterate-com/ui in place of `@main`. + +/** The page, with what only the worker knows written into it: which mind this host is, and its + * contexts (the `mind` facet's registry), for the path box. */ +export async function mindHostPage(itx: { + whoami(): Promise<{ mindId: string; mindSlug: string }>; + facets: { get(name: "mind"): { snapshot(): Promise<{ state: { contexts?: object } }> } }; +}) { + const [{ mindId, mindSlug }, { state }] = await Promise.all([ + itx.whoami(), + itx.facets.get("mind").snapshot(), + ]); + const mind = { + id: mindId, + slug: mindSlug, + paths: ["/", ...Object.keys(state.contexts || {}).sort()], + }; + // JSON inside a script element, `<` escaped so no value can close the element + const data = JSON.stringify(mind).replaceAll("<", "\\u003c"); + return new Response( + `<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>Contexts</title> + <script type="importmap"> + { "imports": { "@iterate-com/ui/": "https://esm.iterate.com/@iterate-com/ui@main/" } } + </script> + <link rel="stylesheet" href="https://esm.iterate.com/@iterate-com/ui@main/styles.css" /> + <script type="application/json" id="mind">${data}</script> + </head> + <body> + <div id="root" class="flex h-screen flex-col"> + <p class="p-4 text-sm text-muted-foreground">Connecting…</p> + </div> + <script type="module"> + import { html, render, useState } from "@iterate-com/ui/page"; + import { ContextView } from "@iterate-com/ui/components/context-view/context-view"; + import { Button } from "@iterate-com/ui/components/ui/button"; + import { Input } from "@iterate-com/ui/components/ui/input"; + import { createIterateClient, useContextStub, useIterateContext } from "@iterate-com/ui/live"; + + // what the worker knows and the page doesn't: which mind this host is, and its contexts + const mind = JSON.parse(document.getElementById("mind").textContent); + // the session this host's sign-in set (the worker only serves a signed-in member) + const { api, info } = await createIterateClient().authenticate(location.href); + + function App() { + const [path, setPath] = useState(new URLSearchParams(location.search).get("path") || "/"); + // the view's own state: the open inspector, the search, the filters + const [state, setState] = useState({}); + const root = useContextStub(() => api.minds.get(mind.id), []); + const shown = useContextStub(root.stub ? () => root.stub.cd(path) : null, [root.stub, path]); + const context = useIterateContext(shown.stub); + const open = (event) => { + event.preventDefault(); + const next = String(new FormData(event.currentTarget).get("path") || "/"); + history.replaceState(null, "", "?path=" + encodeURIComponent(next)); + setState({}); + setPath(next); + }; + return html\` + <header class="flex flex-wrap items-center gap-3 border-b px-4 py-2 text-sm"> + <span class="font-medium">\${mind.slug}</span> + <span class="text-muted-foreground">as \${info.principal.email || info.principal.actor}</span> + <form class="ml-auto flex items-center gap-2" onSubmit=\${open}> + <\${Input} name="path" list="paths" defaultValue=\${path} aria-label="Context" className="h-8 w-80 font-mono" /> + <datalist id="paths">\${mind.paths.map((option) => html\`<option value=\${option} />\`)}</datalist> + <\${Button} type="submit" size="sm">Open<//> + </form> + </header> + <\${ContextView} + title=\${path} + context=\${context} + error=\${root.error || shown.error} + state=\${state} + onStateChange=\${(patch) => setState((previous) => ({ ...previous, ...patch }))} + onAppend=\${shown.stub ? (events) => shown.stub.append(...events) : undefined} + className="min-h-0 flex-1" + /> + \`; + } + + render(html\`<\${App} />\`, document.getElementById("root")); + </script> + </body> +</html> +`, + { + headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }, + }, + ); +}
A package.json
@@ -0,0 +1,290 @@ +{ + "name": "@iterate-com/ui", + "version": "0.1.0", + "description": "iterate's React components, built to import from a URL in a no-build page", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/iterate/packages.git", + "directory": "packages/ui" + }, + "type": "module", + "imports": { + "#/*": "./src/*" + }, + "exports": { + "./apps/base-path": "./src/apps/base-path.ts", + "./apps/document": "./src/apps/document.tsx", + "./apps/head": "./src/apps/head.ts", + "./apps/router": "./src/apps/router.tsx", + "./apps/server": "./src/apps/server.ts", + "./globals.css": "./src/styles/globals.css", + "./iterate.css": "./src/styles/iterate.css", + "./components/agent-chat/agent-chat-search": "./src/components/agent-chat/agent-chat-search.ts", + "./components/agent-chat/use-composer-attachments": "./src/components/agent-chat/use-composer-attachments.ts", + "./components/agent-chat/*": "./src/components/agent-chat/*.tsx", + "./components/context-explorer/*": "./src/components/context-explorer/*.tsx", + "./components/context-view/*": "./src/components/context-view/*.tsx", + "./components/context-catalog/context-catalog": "./src/components/context-catalog/context-catalog.ts", + "./components/context-view/context-view-search": "./src/components/context-view/context-view-search.ts", + "./components/repo-ide/repo-ide-search": "./src/components/repo-ide/repo-ide-search.ts", + "./components/repo-ide/repo-client": "./src/components/repo-ide/repo-client.ts", + "./components/repo-ide/*": "./src/components/repo-ide/*.tsx", + "./components/call/spoken-lines": "./src/components/call/spoken-lines.ts", + "./components/*": "./src/components/*.tsx", + "./hooks/*": "./src/hooks/*.ts", + "./lib/*": "./src/lib/*.ts", + "./agent-kind-view": "./src/agent-kind-view/types.ts", + "./agent-kind-view/bridge": "./src/agent-kind-view/bridge.ts", + "./agent-kind-view/frame": "./src/agent-kind-view/frame.ts", + "./agent-kind-view/host": "./src/agent-kind-view/host.ts", + "./agent-kind-view/load": "./src/agent-kind-view/load.ts", + "./lib/agent-progress": "./src/components/agent-chat/agent-progress.ts" + }, + "files": [ + "dist" + ], + "publishConfig": { + "access": "public", + "imports": {}, + "exports": { + "./page": "./dist/page.mjs", + "./live": "./dist/live.mjs", + "./icons": "./dist/icons.mjs", + "./query": "./dist/query.mjs", + "./react": "./dist/react.mjs", + "./react/jsx-runtime": "./dist/react/jsx-runtime.mjs", + "./react/compiler-runtime": "./dist/react/compiler-runtime.mjs", + "./react-dom": "./dist/react-dom.mjs", + "./react-dom/client": "./dist/react-dom/client.mjs", + "./agent-kind-view/host": "./dist/agent-kind-view/host.mjs", + "./agent-kind-view/dash-agents": "./dist/agent-kind-view/dash-agents.mjs", + "./change-my-mind": "./dist/change-my-mind.mjs", + "./components/agent-chat/chat-parts": "./dist/components/agent-chat/chat-parts.mjs", + "./components/agent-chat/agent-shell": "./dist/components/agent-chat/agent-shell.mjs", + "./components/agent-chat/agent-page-header": "./dist/components/agent-chat/agent-page-header.mjs", + "./lib/agent-progress": "./dist/lib/agent-progress.mjs", + "./components/agent-chat/agent-chat": "./dist/components/agent-chat/agent-chat.mjs", + "./components/agent-context": "./dist/components/agent-context.mjs", + "./components/agents-home": "./dist/components/agents-home.mjs", + "./components/agents-nav": "./dist/components/agents-nav.mjs", + "./components/analytics-page": "./dist/components/analytics-page.mjs", + "./components/app-build": "./dist/components/app-build.mjs", + "./components/app-shell": "./dist/components/app-shell.mjs", + "./components/approvals-alert": "./dist/components/approvals-alert.mjs", + "./components/call/call-bar": "./dist/components/call/call-bar.mjs", + "./components/call/call-controls": "./dist/components/call/call-controls.mjs", + "./components/call/call-lobby": "./dist/components/call/call-lobby.mjs", + "./components/call/call-pip": "./dist/components/call/call-pip.mjs", + "./components/call/call-share": "./dist/components/call/call-share.mjs", + "./components/call/call-tiles": "./dist/components/call/call-tiles.mjs", + "./components/call/caption-strip": "./dist/components/call/caption-strip.mjs", + "./components/call/face": "./dist/components/call/face.mjs", + "./components/call/spoken-lines": "./dist/components/call/spoken-lines.mjs", + "./components/call/transcript-history": "./dist/components/call/transcript-history.mjs", + "./components/call/transcript-rollup": "./dist/components/call/transcript-rollup.mjs", + "./components/change-my-mind-button": "./dist/components/change-my-mind-button.mjs", + "./components/checklist": "./dist/components/checklist.mjs", + "./components/cloudflare-button": "./dist/components/cloudflare-button.mjs", + "./components/code-block": "./dist/components/code-block.mjs", + "./components/code-editor": "./dist/components/code-editor.mjs", + "./components/connect-mind": "./dist/components/connect-mind.mjs", + "./components/context-catalog/context-catalog": "./dist/components/context-catalog/context-catalog.mjs", + "./components/context-explorer/context-explorer": "./dist/components/context-explorer/context-explorer.mjs", + "./components/context-path-text": "./dist/components/context-path-text.mjs", + "./components/context-view/context-view": "./dist/components/context-view/context-view.mjs", + "./components/copy-text": "./dist/components/copy-text.mjs", + "./components/dash/dash-paths": "./dist/components/dash/dash-paths.mjs", + "./components/dash/dash": "./dist/components/dash/dash.mjs", + "./components/docs-editor/docs-editor": "./dist/components/docs-editor/docs-editor.mjs", + "./components/environment-head-content": "./dist/components/environment-head-content.mjs", + "./components/identifier": "./dist/components/identifier.mjs", + "./components/integrations-page": "./dist/components/integrations-page.mjs", + "./components/iterate-logo": "./dist/components/iterate-logo.mjs", + "./components/last-mind-redirect": "./dist/components/last-mind-redirect.mjs", + "./components/list-row-text": "./dist/components/list-row-text.mjs", + "./components/log-in-with-iterate": "./dist/components/log-in-with-iterate.mjs", + "./components/mcp-connect": "./dist/components/mcp-connect.mjs", + "./components/mind-app-shell": "./dist/components/mind-app-shell.mjs", + "./components/not-recorded": "./dist/components/not-recorded.mjs", + "./components/page-tools": "./dist/components/page-tools.mjs", + "./components/posthog": "./dist/components/posthog.mjs", + "./components/reconnecting-mark": "./dist/components/reconnecting-mark.mjs", + "./components/repo-ide/repo-ide": "./dist/components/repo-ide/repo-ide.mjs", + "./components/route-defaults": "./dist/components/route-defaults.mjs", + "./components/secrets-page": "./dist/components/secrets-page.mjs", + "./components/setup-steps": "./dist/components/setup-steps.mjs", + "./components/standalone-page": "./dist/components/standalone-page.mjs", + "./components/step-row": "./dist/components/step-row.mjs", + "./components/stream-link": "./dist/components/stream-link.mjs", + "./components/time-chart": "./dist/components/time-chart.mjs", + "./components/ui/alert-dialog": "./dist/components/ui/alert-dialog.mjs", + "./components/ui/alert": "./dist/components/ui/alert.mjs", + "./components/ui/avatar": "./dist/components/ui/avatar.mjs", + "./components/ui/badge": "./dist/components/ui/badge.mjs", + "./components/ui/breadcrumb": "./dist/components/ui/breadcrumb.mjs", + "./components/ui/button-group": "./dist/components/ui/button-group.mjs", + "./components/ui/button": "./dist/components/ui/button.mjs", + "./components/ui/card": "./dist/components/ui/card.mjs", + "./components/ui/checkbox": "./dist/components/ui/checkbox.mjs", + "./components/ui/collapsible": "./dist/components/ui/collapsible.mjs", + "./components/ui/command": "./dist/components/ui/command.mjs", + "./components/ui/dialog": "./dist/components/ui/dialog.mjs", + "./components/ui/dropdown-menu": "./dist/components/ui/dropdown-menu.mjs", + "./components/ui/empty": "./dist/components/ui/empty.mjs", + "./components/ui/field": "./dist/components/ui/field.mjs", + "./components/ui/input-group": "./dist/components/ui/input-group.mjs", + "./components/ui/input": "./dist/components/ui/input.mjs", + "./components/ui/label": "./dist/components/ui/label.mjs", + "./components/ui/native-select": "./dist/components/ui/native-select.mjs", + "./components/ui/popover": "./dist/components/ui/popover.mjs", + "./components/ui/radio-group": "./dist/components/ui/radio-group.mjs", + "./components/ui/select": "./dist/components/ui/select.mjs", + "./components/ui/separator": "./dist/components/ui/separator.mjs", + "./components/ui/sheet": "./dist/components/ui/sheet.mjs", + "./components/ui/sidebar": "./dist/components/ui/sidebar.mjs", + "./components/ui/skeleton": "./dist/components/ui/skeleton.mjs", + "./components/ui/sonner": "./dist/components/ui/sonner.mjs", + "./components/ui/spinner": "./dist/components/ui/spinner.mjs", + "./components/ui/table": "./dist/components/ui/table.mjs", + "./components/ui/tabs": "./dist/components/ui/tabs.mjs", + "./components/ui/textarea": "./dist/components/ui/textarea.mjs", + "./components/ui/tooltip": "./dist/components/ui/tooltip.mjs", + "./components/virtual-log/virtual-log": "./dist/components/virtual-log/virtual-log.mjs", + "./components/widget/widget": "./dist/components/widget/widget.mjs", + "./lib/agent-summary": "./dist/lib/agent-summary.mjs", + "./lib/call-engine": "./dist/lib/call-engine.mjs", + "./lib/call-rules": "./dist/lib/call-rules.mjs", + "./lib/change-my-mind": "./dist/lib/change-my-mind.mjs", + "./lib/codemirror-theme": "./dist/lib/codemirror-theme.mjs", + "./lib/itx-session": "./dist/lib/itx-session.mjs", + "./lib/page-url": "./dist/lib/page-url.mjs", + "./lib/plain-left-click": "./dist/lib/plain-left-click.mjs", + "./lib/presence": "./dist/lib/presence.mjs", + "./lib/px-per-rem": "./dist/lib/px-per-rem.mjs", + "./lib/saved-context": "./dist/lib/saved-context.mjs", + "./lib/saved-log-tail": "./dist/lib/saved-log-tail.mjs", + "./lib/source-editor": "./dist/lib/source-editor.mjs", + "./lib/waiting-approvals": "./dist/lib/waiting-approvals.mjs", + "./chunks/vendor-react": "./dist/chunks/vendor-react.mjs", + "./chunks/vendor-codemirror": "./dist/chunks/vendor-codemirror.mjs", + "./chunks/vendor-codemirror-more-languages": "./dist/chunks/vendor-codemirror-more-languages.mjs", + "./chunks/vendor-codemirror-themes": "./dist/chunks/vendor-codemirror-themes.mjs", + "./chunks/vendor-base-ui": "./dist/chunks/vendor-base-ui.mjs", + "./chunks/vendor-yaml": "./dist/chunks/vendor-yaml.mjs", + "./chunks/vendor-zod": "./dist/chunks/vendor-zod.mjs", + "./chunks/vendor-query": "./dist/chunks/vendor-query.mjs", + "./chunks/vendor-yjs": "./dist/chunks/vendor-yjs.mjs", + "./chunks/vendor-atomic": "./dist/chunks/vendor-atomic.mjs", + "./chunks/vendor-posthog": "./dist/chunks/vendor-posthog.mjs", + "./chunks/vendor-prettier": "./dist/chunks/vendor-prettier.mjs", + "./chunks/vendor-icons": "./dist/chunks/vendor-icons.mjs", + "./chunks/ui-base": "./dist/chunks/ui-base.mjs", + "./chunks/ui-shell": "./dist/chunks/ui-shell.mjs", + "./chunks/docs-editor-icons": "./dist/chunks/docs-editor-icons.mjs", + "./styles.css": "./dist/styles.css", + "./components/docs-editor/doc-tree": "./dist/components/docs-editor/doc-tree.mjs", + "./docs-editor.css": "./dist/docs-editor.css", + "./agent-kind-view-frame.js": "./dist/agent-kind-view-frame.js", + "./iterate.css": "./dist/iterate.css", + "./fonts/ubuntu-cyrillic-400-normal.woff2": "./dist/fonts/ubuntu-cyrillic-400-normal.woff2", + "./fonts/ubuntu-cyrillic-500-normal.woff2": "./dist/fonts/ubuntu-cyrillic-500-normal.woff2", + "./fonts/ubuntu-cyrillic-700-normal.woff2": "./dist/fonts/ubuntu-cyrillic-700-normal.woff2", + "./fonts/ubuntu-cyrillic-ext-400-normal.woff2": "./dist/fonts/ubuntu-cyrillic-ext-400-normal.woff2", + "./fonts/ubuntu-cyrillic-ext-500-normal.woff2": "./dist/fonts/ubuntu-cyrillic-ext-500-normal.woff2", + "./fonts/ubuntu-cyrillic-ext-700-normal.woff2": "./dist/fonts/ubuntu-cyrillic-ext-700-normal.woff2", + "./fonts/ubuntu-greek-400-normal.woff2": "./dist/fonts/ubuntu-greek-400-normal.woff2", + "./fonts/ubuntu-greek-500-normal.woff2": "./dist/fonts/ubuntu-greek-500-normal.woff2", + "./fonts/ubuntu-greek-700-normal.woff2": "./dist/fonts/ubuntu-greek-700-normal.woff2", + "./fonts/ubuntu-greek-ext-400-normal.woff2": "./dist/fonts/ubuntu-greek-ext-400-normal.woff2", + "./fonts/ubuntu-greek-ext-500-normal.woff2": "./dist/fonts/ubuntu-greek-ext-500-normal.woff2", + "./fonts/ubuntu-greek-ext-700-normal.woff2": "./dist/fonts/ubuntu-greek-ext-700-normal.woff2", + "./fonts/ubuntu-latin-400-normal.woff2": "./dist/fonts/ubuntu-latin-400-normal.woff2", + "./fonts/ubuntu-latin-500-normal.woff2": "./dist/fonts/ubuntu-latin-500-normal.woff2", + "./fonts/ubuntu-latin-700-normal.woff2": "./dist/fonts/ubuntu-latin-700-normal.woff2", + "./fonts/ubuntu-latin-ext-400-normal.woff2": "./dist/fonts/ubuntu-latin-ext-400-normal.woff2", + "./fonts/ubuntu-latin-ext-500-normal.woff2": "./dist/fonts/ubuntu-latin-ext-500-normal.woff2", + "./fonts/ubuntu-latin-ext-700-normal.woff2": "./dist/fonts/ubuntu-latin-ext-700-normal.woff2" + } + }, + "scripts": { + "build": "tsdown && tailwindcss --input src/browser/styles.css --output dist/styles.css --minify && tailwindcss --input src/browser/docs-editor.css --output dist/docs-editor.css --minify && node scripts/check-docs-editor-css.ts && node scripts/build-iterate-css.ts && node scripts/build-agent-kind-view-frame.ts && node scripts/build-docs-tree.ts", + "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.worker.json", + "test": "vitest run", + "prepack": "pnpm build" + }, + "devDependencies": { + "@atomic-editor/editor": "0.6.2", + "@base-ui/react": "catalog:", + "@cloudflare/workers-types": "catalog:", + "@codemirror/autocomplete": "catalog:", + "@codemirror/commands": "^6.10.2", + "@codemirror/lang-cpp": "^6.0.3", + "@codemirror/lang-css": "catalog:", + "@codemirror/lang-go": "^6.0.1", + "@codemirror/lang-html": "catalog:", + "@codemirror/lang-java": "^6.0.2", + "@codemirror/lang-javascript": "catalog:", + "@codemirror/lang-json": "catalog:", + "@codemirror/lang-markdown": "catalog:", + "@codemirror/lang-php": "^6.0.2", + "@codemirror/lang-python": "^6.2.1", + "@codemirror/lang-rust": "^6.0.2", + "@codemirror/lang-sql": "catalog:", + "@codemirror/lang-xml": "^6.1.0", + "@codemirror/lang-yaml": "catalog:", + "@codemirror/language": "catalog:", + "@codemirror/legacy-modes": "^6.5.4", + "@codemirror/lint": "^6.9.5", + "@codemirror/merge": "^6.12.2", + "@codemirror/search": "catalog:", + "@codemirror/state": "catalog:", + "@codemirror/view": "catalog:", + "@fontsource/ubuntu": "5.3.0", + "@fsegurai/codemirror-theme-bundle": "catalog:", + "@iterate-com/shared": "workspace:*", + "@lezer/common": "^1.5.2", + "@lezer/highlight": "^1.2.4", + "@lezer/markdown": "^1.7.2", + "@pierre/trees": "catalog:", + "@tailwindcss/cli": "catalog:", + "@tanstack/charts": "0.18.0", + "@tanstack/react-query": "^5.107.1", + "@tanstack/react-router": "catalog:", + "@tanstack/react-virtual": "^3.14.26", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "capnweb": "catalog:", + "class-variance-authority": "catalog:", + "cmdk": "^1.1.1", + "cn": "catalog:", + "codemirror": "catalog:", + "es-module-lexer": "^2.1.0", + "fake-indexeddb": "6.2.8", + "htm": "3.1.1", + "iterate": "workspace:*", + "ivya": "1.8.2", + "jsdom": "30.1.1", + "lucide-react": "catalog:", + "next-themes": "^0.4.6", + "postcss": "8.5.28", + "posthog-js": "catalog:", + "prettier": "3.9.9", + "react": "catalog:", + "react-dom": "catalog:", + "shadcn": "catalog:", + "sonner": "catalog:", + "streamdown": "catalog:", + "sucrase": "^3.35.1", + "tailwindcss": "catalog:", + "tsdown": "catalog:", + "tw-animate-css": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:", + "y-codemirror.next": "catalog:", + "y-protocols": "^1.0.6", + "yaml": "catalog:", + "yjs": "catalog:", + "zod": "catalog:" + } +}
A registry.json
@@ -0,0 +1,2091 @@ +{ + "$schema": "https://ui.shadcn.com/schema/registry.json", + "name": "iterate", + "homepage": "https://github.com/iterate/packages/tree/main/packages/ui", + "items": [ + { + "name": "agent-chat", + "type": "registry:component", + "description": "One agent's conversation: its chat with a composer, its events, and the traces of its LLM requests and script runs, for a page that holds the agent's context.", + "dependencies": [ + "@base-ui/react", + "@codemirror/state", + "@codemirror/view", + "cn", + "iterate", + "lucide-react", + "sonner", + "streamdown", + "yaml", + "zod" + ], + "registryDependencies": [ + "avatar", + "button", + "dropdown-menu", + "empty", + "iterate/packages/agent-summary", + "iterate/packages/app-shell", + "iterate/packages/call", + "iterate/packages/code-block", + "iterate/packages/code-editor", + "iterate/packages/context-path-text", + "iterate/packages/context-view", + "iterate/packages/iterate-logo", + "iterate/packages/itx-session", + "iterate/packages/presence", + "iterate/packages/virtual-log", + "iterate/packages/widget", + "popover", + "sheet", + "spinner", + "tabs" + ], + "cssVars": { + "theme": { + "color-success": "var(--success)", + "color-warning": "var(--warning)", + "color-info": "var(--info)", + "text-2xs": "0.6875rem", + "text-2xs--line-height": "calc(1 / 0.6875)" + }, + "light": { + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))", + "warning": "light-dark(oklch(0.555 0.163 48.998), oklch(0.828 0.189 84.429))", + "info": "light-dark(oklch(0.5 0.134 242.749), oklch(0.746 0.16 232.661))" + } + }, + "files": [ + { + "path": "src/components/agent-chat/agent-chat-search.ts", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-chat.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-event-inspectors.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-events.ts", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-facts.ts", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-feed-list.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-feed.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-inspectors.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-page-header.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-progress.ts", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-reading.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-shell-contexts.ts", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-shell.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-strip.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-traces.ts", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/agent-ui-reducer.ts", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/chat-parts.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/choice-in-words.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/choice-syntax.ts", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/chunked-text.ts", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/composer-attachments.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/composer-textarea.client.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/composer-textarea.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/composer.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/full-text-snapshot.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/llm-request-trace-view.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/llm-request-trace.ts", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/message.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/participant.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/presence-line.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/queued-messages.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/stream-event.ts", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/streaming-text.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/use-composer-attachments.ts", + "type": "registry:component" + }, + { + "path": "src/components/agent-chat/use-ticking-now-ms.ts", + "type": "registry:component" + } + ] + }, + { + "name": "agent-summary", + "type": "registry:lib", + "description": "The rows of a mind's agents, from the catalog's live state: which to list, in what order, and what to call each.", + "dependencies": [ + "iterate", + "zod" + ], + "files": [ + { + "path": "src/lib/agent-summary.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "agents-nav", + "type": "registry:component", + "description": "The Agents app's sidebar: New agent, pinned agents and the rest, each with what runs it and what it is doing.", + "dependencies": [ + "cn", + "lucide-react", + "zod" + ], + "registryDependencies": [ + "iterate/packages/agent-summary", + "iterate/packages/context-path-text", + "iterate/packages/plain-left-click", + "sidebar" + ], + "cssVars": { + "theme": { + "color-success": "var(--success)", + "color-warning": "var(--warning)", + "text-2xs": "0.6875rem", + "text-2xs--line-height": "calc(1 / 0.6875)" + }, + "light": { + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))", + "warning": "light-dark(oklch(0.555 0.163 48.998), oklch(0.828 0.189 84.429))" + } + }, + "files": [ + { + "path": "src/components/agents-nav.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-look.ts", + "type": "registry:component" + } + ] + }, + { + "name": "agents-home", + "type": "registry:component", + "description": "The Agents app's home page: a composer whose first message starts an agent, and the agents active most recently; each half on its own, and every agent as a virtual list.", + "dependencies": [ + "@tanstack/react-virtual", + "cn", + "iterate", + "lucide-react" + ], + "registryDependencies": [ + "card", + "iterate/packages/agent-chat", + "iterate/packages/agent-summary", + "iterate/packages/agents-nav", + "iterate/packages/context-catalog", + "iterate/packages/context-path-text", + "iterate/packages/list-row-text", + "iterate/packages/px-per-rem" + ], + "cssVars": { + "theme": { + "text-2xs": "0.6875rem", + "text-2xs--line-height": "calc(1 / 0.6875)" + } + }, + "files": [ + { + "path": "src/components/agents-home.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "approvals-alert", + "type": "registry:component", + "description": "The alert that requests wait for a member's yes: the first thing in a Dash's sidebar, a link to where the member answers. It draws nothing when nothing waits.", + "dependencies": [ + "@base-ui/react", + "lucide-react" + ], + "cssVars": { + "theme": { + "color-warning": "var(--warning)" + }, + "light": { + "warning": "light-dark(oklch(0.555 0.163 48.998), oklch(0.828 0.189 84.429))" + } + }, + "files": [ + { + "path": "src/components/approvals-alert.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "analytics-page", + "type": "registry:component", + "description": "The analytics page of a Dash, for a mind that has telemetry: the last hour live, the last day, the busiest context paths and event types, what each context stores, and a box that runs a SELECT. It knows no router: the page gives it one query function.", + "dependencies": [ + "cn" + ], + "registryDependencies": [ + "button", + "card", + "input", + "iterate/packages/time-chart", + "sheet", + "spinner", + "table", + "tabs", + "textarea" + ], + "cssVars": { + "theme": { + "color-success": "var(--success)", + "color-chart-1": "var(--chart-1)" + }, + "light": { + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))", + "chart-1": "light-dark(#2a78d6, #78b4ff)" + } + }, + "files": [ + { + "path": "src/components/analytics-page.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "app-build", + "type": "registry:component", + "description": "One installed version of an app: its build's state, and Check to ask again.", + "dependencies": [ + "iterate" + ], + "registryDependencies": [ + "button", + "spinner" + ], + "files": [ + { + "path": "src/components/app-build.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "app-shell", + "type": "registry:component", + "description": "The client apps' shell: the sidebar with brand or item switcher, the app's pages, the account menu, and ⌘K over the sidebar's pages.", + "dependencies": [ + "cmdk", + "cn", + "iterate", + "lucide-react" + ], + "registryDependencies": [ + "avatar", + "button", + "command", + "dialog", + "dropdown-menu", + "iterate/packages/iterate-logo", + "iterate/packages/plain-left-click", + "iterate/packages/posthog", + "iterate/packages/saved-log-tail", + "sidebar", + "skeleton" + ], + "cssVars": { + "theme": { + "color-warning": "var(--warning)" + }, + "light": { + "warning": "light-dark(oklch(0.555 0.163 48.998), oklch(0.828 0.189 84.429))" + } + }, + "files": [ + { + "path": "src/components/app-shell.tsx", + "type": "registry:component" + }, + { + "path": "src/components/app-shell-palette.tsx", + "type": "registry:component" + }, + { + "path": "src/components/app-shell-palette-entries.ts", + "type": "registry:component" + } + ] + }, + { + "name": "connect-mind", + "type": "registry:component", + "description": "The page that points an app at a mind by its address.", + "dependencies": [ + "zod" + ], + "registryDependencies": [ + "button", + "field", + "input", + "iterate/packages/iterate-logo" + ], + "files": [ + { + "path": "src/components/connect-mind.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "change-my-mind", + "type": "registry:lib", + "description": "The words of the Change my mind button, and the instructions it copies for a reader's iterate mind.", + "files": [ + { + "path": "src/lib/change-my-mind.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "call-rules", + "type": "registry:lib", + "description": "The pure rules of a call in a page: the call facet's live state, who may press Join, the network path, the ICE servers, a saved device, the repair of a connection, the simulcast layer of a tile, and the voice agent's idle clock.", + "dependencies": [ + "zod" + ], + "files": [ + { + "path": "src/lib/call-rules.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "call-engine", + "type": "registry:lib", + "description": "A call in this tab over Cloudflare's SFU, signalled by the call facet on the agent's context, and the hook that holds it for a page.", + "dependencies": [ + "iterate" + ], + "registryDependencies": [ + "iterate/packages/call-rules" + ], + "files": [ + { + "path": "src/lib/call-engine.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "call", + "type": "registry:component", + "description": "A call on an agent's context: its lobby before a join, its controls and Share for a header, its tiles beside the chat, the quiet caption strip, the transcript, and one feed row for a run of lines said, with each speaker's face.", + "dependencies": [ + "cn", + "lucide-react" + ], + "registryDependencies": [ + "alert", + "avatar", + "button", + "button-group", + "checkbox", + "input", + "iterate/packages/call-engine", + "iterate/packages/call-rules", + "iterate/packages/copy-text", + "iterate/packages/iterate-logo", + "iterate/packages/virtual-log", + "label", + "native-select", + "popover", + "spinner", + "tooltip" + ], + "cssVars": { + "theme": { + "color-success": "var(--success)", + "text-2xs": "0.6875rem", + "text-2xs--line-height": "calc(1 / 0.6875)" + }, + "light": { + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))" + } + }, + "files": [ + { + "path": "src/components/call/spoken-lines.ts", + "type": "registry:component" + }, + { + "path": "src/components/call/face.tsx", + "type": "registry:component" + }, + { + "path": "src/components/call/caption-strip.tsx", + "type": "registry:component" + }, + { + "path": "src/components/call/transcript-history.tsx", + "type": "registry:component" + }, + { + "path": "src/components/call/transcript-rollup.tsx", + "type": "registry:component" + }, + { + "path": "src/components/call/calendar-invite.ts", + "type": "registry:component" + }, + { + "path": "src/components/call/call-controls.tsx", + "type": "registry:component" + }, + { + "path": "src/components/call/call-share.tsx", + "type": "registry:component" + }, + { + "path": "src/components/call/call-bar.tsx", + "type": "registry:component" + }, + { + "path": "src/components/call/call-tiles.tsx", + "type": "registry:component" + }, + { + "path": "src/components/call/call-pip.tsx", + "type": "registry:component" + }, + { + "path": "src/components/call/call-lobby.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "change-my-mind-button", + "type": "registry:component", + "description": "The Change my mind button: it copies instructions that a reader gives to their own iterate mind, to make the change a post describes.", + "dependencies": [ + "cn", + "lucide-react" + ], + "registryDependencies": [ + "button", + "iterate/packages/change-my-mind", + "popover", + "textarea", + "tooltip" + ], + "files": [ + { + "path": "src/components/change-my-mind-button.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "checklist", + "type": "registry:component", + "description": "A list of things that must be true before going on, each turning done by itself, with a link or button that makes it so.", + "dependencies": [ + "cn", + "lucide-react" + ], + "registryDependencies": [ + "spinner" + ], + "cssVars": { + "theme": { + "color-success": "var(--success)", + "color-warning": "var(--warning)" + }, + "light": { + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))", + "warning": "light-dark(oklch(0.555 0.163 48.998), oklch(0.828 0.189 84.429))" + } + }, + "files": [ + { + "path": "src/components/checklist.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "cloudflare-button", + "type": "registry:component", + "description": "The button that goes to Cloudflare: its orange, its cloud in white. And the cloud on its own.", + "dependencies": [ + "cn" + ], + "cssVars": { + "theme": { + "color-cloudflare": "var(--cloudflare)", + "color-cloudflare-glow": "var(--cloudflare-glow)" + }, + "light": { + "cloudflare": "#f6821f", + "cloudflare-glow": "#fbad41" + } + }, + "files": [ + { + "path": "src/components/cloudflare-button.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "code-block", + "type": "registry:component", + "description": "Read-only CodeMirror for a source file or a serialized object (YAML or JSON), loaded in the browser only.", + "dependencies": [ + "@codemirror/lang-javascript", + "@codemirror/lang-json", + "@codemirror/lang-markdown", + "@codemirror/lang-yaml", + "@codemirror/language", + "@codemirror/search", + "@codemirror/state", + "@codemirror/view", + "@fsegurai/codemirror-theme-bundle", + "cn", + "codemirror", + "lucide-react", + "prettier", + "sonner", + "yaml" + ], + "registryDependencies": [ + "iterate/packages/codemirror-theme", + "spinner", + "tooltip" + ], + "cssVars": { + "theme": { + "color-success": "var(--success)" + }, + "light": { + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))" + } + }, + "files": [ + { + "path": "src/components/code-block.tsx", + "type": "registry:component" + }, + { + "path": "src/components/code-block.client.tsx", + "type": "registry:component" + }, + { + "path": "src/components/source-code-block.client.tsx", + "type": "registry:component" + }, + { + "path": "src/lib/format-script.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "code-editor", + "type": "registry:component", + "description": "An editable CodeMirror buffer, loaded in the browser only.", + "dependencies": [ + "@codemirror/autocomplete", + "@codemirror/lang-json", + "@codemirror/lang-yaml", + "@codemirror/state", + "@codemirror/view", + "@fsegurai/codemirror-theme-bundle", + "cn", + "codemirror" + ], + "registryDependencies": [ + "iterate/packages/codemirror-theme", + "spinner" + ], + "files": [ + { + "path": "src/components/code-editor.tsx", + "type": "registry:component" + }, + { + "path": "src/components/code-editor.client.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "source-editor", + "type": "registry:lib", + "description": "The shared source editor setup for the repo IDE and collaborative Docs buffers.", + "dependencies": [ + "@codemirror/autocomplete", + "@codemirror/commands", + "@codemirror/language", + "@codemirror/lint", + "@codemirror/search", + "@codemirror/state", + "@codemirror/view", + "@fsegurai/codemirror-theme-bundle" + ], + "registryDependencies": [ + "iterate/packages/codemirror-theme" + ], + "files": [ + { + "path": "src/lib/source-editor.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "codemirror-theme", + "type": "registry:lib", + "description": "VS Code light or dark for a CodeMirror editor, as the OS is, swapped in place when it changes.", + "dependencies": [ + "@codemirror/state", + "@codemirror/view" + ], + "files": [ + { + "path": "src/lib/codemirror-theme.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "context-catalog", + "type": "registry:component", + "description": "A mind's catalog of its contexts: the most recently active as a filtered list, what one context says about itself (description, processors, event types, metadata), a ⌘K palette of the contexts active in the last five minutes that searches every context, and the hook that reads the catalog.", + "dependencies": [ + "@tanstack/react-virtual", + "cmdk", + "cn", + "lucide-react", + "zod" + ], + "registryDependencies": [ + "badge", + "button", + "command", + "dialog", + "input", + "iterate/packages/agent-summary", + "iterate/packages/agents-nav", + "iterate/packages/context-path-text", + "iterate/packages/context-view", + "iterate/packages/list-row-text", + "iterate/packages/px-per-rem", + "popover", + "textarea", + "tooltip" + ], + "cssVars": { + "theme": { + "color-success": "var(--success)", + "color-warning": "var(--warning)", + "text-2xs": "0.6875rem", + "text-2xs--line-height": "calc(1 / 0.6875)" + }, + "light": { + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))", + "warning": "light-dark(oklch(0.555 0.163 48.998), oklch(0.828 0.189 84.429))" + } + }, + "files": [ + { + "path": "src/components/context-catalog/context-catalog.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-catalog/context-activity-stack.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-catalog/context-activity-stack-view.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-catalog/context-icon.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-catalog/context-catalog-list.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-catalog/context-about.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-catalog/context-catalog-rows.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-catalog/context-palette.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-catalog/context-palette-rows.ts", + "type": "registry:component" + } + ] + }, + { + "name": "context-view", + "type": "registry:component", + "description": "One context's event stream, its processors' live state and who is here: the Contexts page's view.", + "dependencies": [ + "@tanstack/react-virtual", + "cn", + "lucide-react", + "yaml", + "zod" + ], + "registryDependencies": [ + "button", + "dropdown-menu", + "input", + "input-group", + "iterate/packages/code-block", + "iterate/packages/code-editor", + "iterate/packages/context-path-text", + "iterate/packages/plain-left-click", + "iterate/packages/presence", + "iterate/packages/virtual-log", + "sheet", + "spinner" + ], + "cssVars": { + "theme": { + "color-success": "var(--success)", + "color-warning": "var(--warning)", + "color-info": "var(--info)", + "text-2xs": "0.6875rem", + "text-2xs--line-height": "calc(1 / 0.6875)" + }, + "light": { + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))", + "warning": "light-dark(oklch(0.555 0.163 48.998), oklch(0.828 0.189 84.429))", + "info": "light-dark(oklch(0.5 0.134 242.749), oklch(0.746 0.16 232.661))" + } + }, + "files": [ + { + "path": "src/components/context-view/append-completions.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-view/append-composer.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/append-events.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-view/context-path.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/context-tree.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/context-view-search.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-view/context-view.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/core-events.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/event-inspector-log.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-view/event-inspector.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/event-row.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/feed-list.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/feed-rows.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/filter-row.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/filters.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/folds.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/live-state-value.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/presence-strip.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/pretty-state.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/processors-panel.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/payload-readers.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-view/types.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-view/context-path-links.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-view/context-tree-rows.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-view/event-row-format.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-view/print-expression.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-view/awake-dot.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "context-explorer", + "type": "registry:component", + "description": "A mind's contexts as one page: the tree of every context, live, and beside it one context's log, processors and presence. It knows no router: the page names the context shown and where a path's link goes.", + "dependencies": [ + "iterate", + "zod" + ], + "registryDependencies": [ + "iterate/packages/context-catalog", + "iterate/packages/context-view", + "iterate/packages/itx-session", + "iterate/packages/saved-context", + "tabs" + ], + "files": [ + { + "path": "src/components/context-explorer/context-explorer.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "dash", + "type": "registry:component", + "description": "A mind's Dash drawn from lists: the shell, a sidebar with recent agents and foot rows (Approvals, Settings), the page the URL names, what waits for a member's yes, and the kit's pages (contexts, repo, secrets, integrations, analytics, settings), each loaded when it first draws.", + "dependencies": [ + "iterate", + "lucide-react" + ], + "registryDependencies": [ + "dropdown-menu", + "iterate/packages/agent-summary", + "iterate/packages/agents-nav", + "iterate/packages/analytics-page", + "iterate/packages/app-shell", + "iterate/packages/approvals-alert", + "iterate/packages/context-catalog", + "iterate/packages/context-explorer", + "iterate/packages/context-path-text", + "iterate/packages/dash-paths", + "iterate/packages/integrations-page", + "iterate/packages/itx-session", + "iterate/packages/page-tools", + "iterate/packages/page-url", + "iterate/packages/reconnecting-mark", + "iterate/packages/repo-ide", + "iterate/packages/saved-context", + "iterate/packages/saved-log-tail", + "iterate/packages/secrets-page", + "iterate/packages/virtual-log", + "iterate/packages/waiting-approvals", + "sidebar", + "skeleton", + "sonner" + ], + "cssVars": { + "theme": { + "color-warning": "var(--warning)", + "text-2xs": "0.6875rem", + "text-2xs--line-height": "calc(1 / 0.6875)" + }, + "light": { + "warning": "light-dark(oklch(0.555 0.163 48.998), oklch(0.828 0.189 84.429))" + } + }, + "files": [ + { + "path": "src/components/dash/dash.tsx", + "type": "registry:component" + }, + { + "path": "src/components/dash/dash-pages.tsx", + "type": "registry:component" + }, + { + "path": "src/components/dash/serves.ts", + "type": "registry:component" + }, + { + "path": "src/components/dash/dash-agents-nav.tsx", + "type": "registry:component" + }, + { + "path": "src/components/dash/dash-href.ts", + "type": "registry:component" + } + ] + }, + { + "name": "dash-paths", + "type": "registry:component", + "description": "Pure canonical URL codec for a mind's Dash (path and query formatting/parsing, zero side effects).", + "dependencies": [ + "zod" + ], + "registryDependencies": [ + "iterate/packages/page-url" + ], + "files": [ + { + "path": "src/components/dash/dash-paths.ts", + "type": "registry:component" + } + ] + }, + { + "name": "copy-text", + "type": "registry:component", + "description": "A value to copy, such as a password or a command, with a copy button.", + "dependencies": [ + "cn", + "lucide-react" + ], + "registryDependencies": [ + "button" + ], + "files": [ + { + "path": "src/components/copy-text.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "environment-head-content", + "type": "registry:component", + "description": "<HeadContent /> that names the deployment off production, in the tab's title and icon.", + "dependencies": [ + "@tanstack/react-router", + "iterate" + ], + "files": [ + { + "path": "src/components/environment-head-content.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "last-mind-redirect", + "type": "registry:component", + "description": "/ in an app that shows one mind at a time: the mind used last, or the connect page.", + "dependencies": [ + "@tanstack/react-router", + "zod" + ], + "registryDependencies": [ + "iterate/packages/route-defaults" + ], + "files": [ + { + "path": "src/components/last-mind-redirect.tsx", + "type": "registry:component" + }, + { + "path": "src/components/connected-minds.ts", + "type": "registry:component" + } + ] + }, + { + "name": "identifier", + "type": "registry:component", + "description": "A compact fixed-width pill for an id, a slug or a path, with a button that copies it.", + "dependencies": [ + "cn", + "lucide-react" + ], + "files": [ + { + "path": "src/components/identifier.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "integrations-page", + "type": "registry:component", + "description": "The integrations page of a Dash: a card for each integration the mind's packages registered, with its connections and buttons, live from one subscription. It knows no router.", + "dependencies": [ + "cn", + "iterate", + "lucide-react", + "zod" + ], + "registryDependencies": [ + "alert-dialog", + "button", + "spinner" + ], + "cssVars": { + "theme": { + "color-success": "var(--success)", + "color-warning": "var(--warning)" + }, + "light": { + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))", + "warning": "light-dark(oklch(0.555 0.163 48.998), oklch(0.828 0.189 84.429))" + } + }, + "files": [ + { + "path": "src/components/integrations-page.tsx", + "type": "registry:component" + }, + { + "path": "src/lib/facet-view.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "iterate-logo", + "type": "registry:component", + "description": "The iterate mark.", + "dependencies": [ + "cn" + ], + "files": [ + { + "path": "src/components/iterate-logo.tsx", + "type": "registry:component" + }, + { + "path": "src/components/iterate-logo.svg", + "type": "registry:component" + } + ] + }, + { + "name": "log-in-with-iterate", + "type": "registry:component", + "description": "The Log in with iterate button.", + "dependencies": [ + "cn" + ], + "registryDependencies": [ + "iterate/packages/iterate-logo" + ], + "files": [ + { + "path": "src/components/log-in-with-iterate.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "mcp-connect", + "type": "registry:component", + "description": "How to connect a coding agent to a mind over MCP: the server's address and the commands for Claude Code and the Codex CLI, each with a copy button.", + "dependencies": [ + "iterate" + ], + "registryDependencies": [ + "card", + "iterate/packages/copy-text" + ], + "files": [ + { + "path": "src/components/mcp-connect.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "not-recorded", + "type": "registry:component", + "description": "A block PostHog's session replay never records, for a secret shown on screen.", + "dependencies": [ + "cn" + ], + "files": [ + { + "path": "src/components/not-recorded.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "context-path-text", + "type": "registry:component", + "description": "A context path as one plain path from the root, in the fixed-width face; a short line keeps its end.", + "dependencies": [ + "cn" + ], + "files": [ + { + "path": "src/components/context-path-text.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "list-row-text", + "type": "registry:component", + "description": "The text of one row of a list of contexts: a title when it has one, its path always, and one more line; the Agents list and the Contexts list draw a row with it.", + "dependencies": [ + "cn" + ], + "registryDependencies": [ + "iterate/packages/context-path-text", + "iterate/packages/px-per-rem" + ], + "cssVars": { + "theme": { + "text-2xs": "0.6875rem", + "text-2xs--line-height": "calc(1 / 0.6875)" + } + }, + "files": [ + { + "path": "src/components/list-row-text.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "px-per-rem", + "type": "registry:lib", + "description": "The page's root font size in px, for a virtual list that positions rows of a height in rem.", + "files": [ + { + "path": "src/lib/px-per-rem.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "plain-left-click", + "type": "registry:lib", + "description": "Whether a click is a plain left click, not one that opens a new tab or window.", + "files": [ + { + "path": "src/lib/plain-left-click.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "page-url", + "type": "registry:lib", + "description": "The URL of a page with no router: the page and its keys in the query string, its view as JSON in one key, and links that change it in place.", + "dependencies": [ + "zod" + ], + "registryDependencies": [ + "iterate/packages/plain-left-click" + ], + "files": [ + { + "path": "src/lib/page-url.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "posthog", + "type": "registry:component", + "description": "PostHog in the browser: init, identity and exception capture, with secrets redacted from URLs.", + "dependencies": [ + "iterate", + "posthog-js" + ], + "files": [ + { + "path": "src/components/posthog.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "mind-app-shell", + "type": "registry:component", + "description": "The app shell for a page inside one mind, with its breadcrumb, and the frame it shows while the page loads.", + "dependencies": [ + "@tanstack/react-router", + "iterate" + ], + "registryDependencies": [ + "iterate/packages/app-shell", + "iterate/packages/route-defaults" + ], + "files": [ + { + "path": "src/components/mind-app-shell.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "repo-ide", + "type": "registry:component", + "description": "A small IDE over one of a mind's repos: file tree, editor, diff, staging, commit and history.", + "dependencies": [ + "@codemirror/lang-css", + "@codemirror/lang-html", + "@codemirror/lang-javascript", + "@codemirror/lang-json", + "@codemirror/lang-markdown", + "@codemirror/lang-sql", + "@codemirror/lang-yaml", + "@codemirror/merge", + "@codemirror/state", + "@codemirror/view", + "@pierre/trees", + "cn", + "iterate", + "lucide-react", + "sonner", + "streamdown", + "zod" + ], + "registryDependencies": [ + "badge", + "button", + "input", + "iterate/packages/source-editor", + "tabs" + ], + "cssVars": { + "theme": { + "color-success": "var(--success)", + "color-info": "var(--info)", + "text-2xs": "0.6875rem", + "text-2xs--line-height": "calc(1 / 0.6875)" + }, + "light": { + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))", + "info": "light-dark(oklch(0.5 0.134 242.749), oklch(0.746 0.16 232.661))" + } + }, + "files": [ + { + "path": "src/components/repo-ide/codemirror.ts", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/commit-diff-pane.tsx", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/commit-history-panel.tsx", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/file-chrome.tsx", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/git-panel.tsx", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/html-preview.tsx", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/markdown-preview.tsx", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/repo-client.ts", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/repo-code-editor.tsx", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/repo-editor-pane.tsx", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/repo-file-discard.ts", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/repo-file-kinds.ts", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/repo-file-tree-paths.ts", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/repo-file-tree.tsx", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/repo-ide-activity-strip.tsx", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/repo-ide-search.ts", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/repo-ide.tsx", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/staged-changes.ts", + "type": "registry:component" + }, + { + "path": "src/components/repo-ide/use-repo-ide-actions.ts", + "type": "registry:component" + } + ] + }, + { + "name": "docs-editor", + "type": "registry:component", + "description": "A markdown doc of a mind's repo, co-edited live (Yjs over the doc's context) in Atomic's live-preview editor: its comments, autosave's status, and the repo's docs as a list and a tree.", + "dependencies": [ + "@atomic-editor/editor", + "@codemirror/autocomplete", + "@codemirror/commands", + "@codemirror/lang-markdown", + "@codemirror/language", + "@codemirror/search", + "@codemirror/state", + "@codemirror/view", + "@pierre/trees", + "cn", + "iterate", + "lucide-react", + "y-codemirror.next", + "y-protocols", + "yjs", + "zod" + ], + "registryDependencies": [ + "button", + "dropdown-menu", + "input", + "iterate/packages/plain-left-click", + "iterate/packages/source-editor", + "iterate/packages/stream-link", + "native-select", + "separator", + "spinner", + "textarea" + ], + "cssVars": { + "theme": { + "color-success": "var(--success)", + "color-warning": "var(--warning)", + "color-info": "var(--info)", + "color-highlight": "var(--highlight)", + "color-chart-1": "var(--chart-1)", + "color-chart-2": "var(--chart-2)", + "color-chart-3": "var(--chart-3)", + "color-chart-4": "var(--chart-4)", + "color-chart-5": "var(--chart-5)" + }, + "light": { + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))", + "warning": "light-dark(oklch(0.555 0.163 48.998), oklch(0.828 0.189 84.429))", + "info": "light-dark(oklch(0.5 0.134 242.749), oklch(0.746 0.16 232.661))", + "highlight": "light-dark(#ffc53d, #755800)", + "chart-1": "light-dark(#2a78d6, #78b4ff)", + "chart-2": "light-dark(#eb6834, #ff966b)", + "chart-3": "light-dark(#1baf7a, #65d6a6)", + "chart-4": "light-dark(#eda100, #f4c45f)", + "chart-5": "light-dark(#e87ba4, #f3a0c0)" + } + }, + "files": [ + { + "path": "src/components/docs-editor/docs-editor.tsx", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/anchor.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/collab.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/comment-marks.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/comments-panel.tsx", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/comments.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/commands.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/create-doc.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/doc-list-panel.tsx", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/doc-list.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/doc-session.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/extensions.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/file-kind.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/frames.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/frontmatter.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/install.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/doc-tree.ts", + "type": "registry:component" + }, + { + "path": "src/components/docs-editor/doc-tree-nav.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "route-defaults", + "type": "registry:component", + "description": "TanStack Router's pending, not-found and error components.", + "dependencies": [ + "@tanstack/react-router" + ], + "registryDependencies": [ + "button", + "iterate/packages/posthog", + "spinner" + ], + "files": [ + { + "path": "src/components/route-defaults.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "secrets-page", + "type": "registry:component", + "description": "The secrets page of a Dash: the mind's secrets with what each may be sent to, an update and a delete per row, and a sheet that sets one. It knows no router: the page gives the list and holds the sheet's state.", + "dependencies": [ + "iterate", + "lucide-react", + "zod" + ], + "registryDependencies": [ + "alert-dialog", + "button", + "field", + "input", + "iterate/packages/identifier", + "sheet", + "spinner", + "table", + "textarea" + ], + "files": [ + { + "path": "src/components/secrets-page.tsx", + "type": "registry:component" + }, + { + "path": "src/lib/secrets.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "setup-steps", + "type": "registry:component", + "description": "The steps of a setup flow beside its content, done ones ticked with what was chosen, and a phone's progress bar.", + "dependencies": [ + "cn", + "lucide-react" + ], + "cssVars": { + "theme": { + "color-success": "var(--success)", + "color-cloudflare": "var(--cloudflare)" + }, + "light": { + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))", + "cloudflare": "#f6821f" + } + }, + "files": [ + { + "path": "src/components/setup-steps.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "standalone-page", + "type": "registry:component", + "description": "The frame of a page outside any app's shell, such as sign-in and consent.", + "dependencies": [ + "cn" + ], + "files": [ + { + "path": "src/components/standalone-page.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "step-row", + "type": "registry:component", + "description": "One step of work in a feed, as a quiet line among the messages: done, running, waiting on the person with their buttons, or failed.", + "dependencies": [ + "cn", + "lucide-react" + ], + "registryDependencies": [ + "spinner" + ], + "cssVars": { + "theme": { + "color-success": "var(--success)", + "color-warning": "var(--warning)" + }, + "light": { + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))", + "warning": "light-dark(oklch(0.555 0.163 48.998), oklch(0.828 0.189 84.429))" + } + }, + "files": [ + { + "path": "src/components/step-row.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "stream-link", + "type": "registry:component", + "description": "Stream ↗: a link from a page to the context its data lives on, in the Dash's Contexts page.", + "registryDependencies": [ + "iterate/packages/dash-paths" + ], + "files": [ + { + "path": "src/components/stream-link.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "time-chart", + "type": "registry:component", + "description": "Telemetry over time, charted with TanStack Charts: the admin app's /telemetry panels and the dash's mind Analytics page.", + "dependencies": [ + "@tanstack/charts" + ], + "cssVars": { + "theme": { + "color-chart-1": "var(--chart-1)", + "color-chart-2": "var(--chart-2)", + "color-chart-3": "var(--chart-3)", + "color-chart-4": "var(--chart-4)", + "color-chart-5": "var(--chart-5)" + }, + "light": { + "chart-1": "light-dark(#2a78d6, #78b4ff)", + "chart-2": "light-dark(#eb6834, #ff966b)", + "chart-3": "light-dark(#1baf7a, #65d6a6)", + "chart-4": "light-dark(#eda100, #f4c45f)", + "chart-5": "light-dark(#e87ba4, #f3a0c0)" + } + }, + "files": [ + { + "path": "src/components/time-chart.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "virtual-log", + "type": "registry:component", + "description": "A log as one virtual list: only the rows in view are in the DOM, it follows its tail, a reader in history is never moved, and older pages load near the top. A view brings its rows and how to draw one.", + "dependencies": [ + "@tanstack/react-virtual", + "cn", + "lucide-react" + ], + "registryDependencies": [ + "spinner" + ], + "files": [ + { + "path": "src/components/virtual-log/older-pages.ts", + "type": "registry:component" + }, + { + "path": "src/components/virtual-log/read-progress.tsx", + "type": "registry:component" + }, + { + "path": "src/components/virtual-log/remembered.ts", + "type": "registry:component" + }, + { + "path": "src/components/virtual-log/use-reader.ts", + "type": "registry:component" + }, + { + "path": "src/components/virtual-log/virtual-log.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "theme", + "description": "iterate's look over shadcn's: Ubuntu for the chrome and controls, monospace for ids, code and readme-like notes (font-readme), light on dark, square corners, hard shadows on what floats.", + "type": "registry:theme", + "dependencies": [ + "@fontsource/ubuntu" + ], + "cssVars": { + "theme": { + "color-link": "var(--link)", + "font-sans": "\"Ubuntu\", ui-sans-serif, system-ui, sans-serif", + "font-readme": "var(--font-mono)", + "radius": "0", + "radius-xs": "0", + "radius-sm": "0", + "radius-md": "0", + "radius-lg": "0", + "radius-xl": "0", + "radius-2xl": "0", + "radius-3xl": "0", + "radius-4xl": "0", + "radius-full": "0", + "shadow-2xs": "0 0 #0000", + "shadow-xs": "0 0 #0000", + "shadow-sm": "0 0 #0000", + "shadow": "0 0 #0000", + "shadow-md": "3px 3px 0 0 var(--foreground)", + "shadow-lg": "4px 4px 0 0 var(--foreground)", + "shadow-xl": "6px 6px 0 0 var(--foreground)", + "shadow-2xl": "8px 8px 0 0 var(--foreground)" + }, + "light": { + "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))", + "card-foreground": "light-dark(oklch(0.145 0 0), oklch(0.985 0 0))", + "popover": "light-dark(oklch(1 0 0), oklch(0.205 0 0))", + "popover-foreground": "light-dark(oklch(0.145 0 0), oklch(0.985 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))", + "secondary": "light-dark(oklch(0.97 0 0), oklch(0.269 0 0))", + "secondary-foreground": "light-dark(oklch(0.205 0 0), oklch(0.985 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))", + "accent-foreground": "light-dark(oklch(0.205 0 0), oklch(0.985 0 0))", + "destructive": "light-dark(oklch(0.577 0.245 27.325), oklch(0.704 0.191 22.216))", + "success": "light-dark(oklch(0.508 0.118 165.612), oklch(0.765 0.177 163.223))", + "warning": "light-dark(oklch(0.555 0.163 48.998), oklch(0.828 0.189 84.429))", + "info": "light-dark(oklch(0.5 0.134 242.749), oklch(0.746 0.16 232.661))", + "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))", + "link": "light-dark(oklch(0.205 0 0), oklch(0.922 0 0))", + "cloudflare": "#f6821f", + "cloudflare-foreground": "oklch(0.145 0 0)", + "cloudflare-button": "#c65102", + "cloudflare-button-foreground": "#fff", + "cloudflare-button-hover": "#ad4702", + "sidebar": "light-dark(oklch(1 0 0), oklch(0.145 0 0))", + "sidebar-foreground": "light-dark(oklch(0.145 0 0), oklch(0.985 0 0))", + "sidebar-primary": "light-dark(oklch(0.205 0 0), oklch(0.922 0 0))", + "sidebar-primary-foreground": "light-dark(oklch(0.985 0 0), oklch(0.205 0 0))", + "sidebar-accent": "light-dark(oklch(0.97 0 0), oklch(0.269 0 0))", + "sidebar-accent-foreground": "light-dark(oklch(0.205 0 0), oklch(0.985 0 0))", + "sidebar-border": "light-dark(oklch(0.922 0 0), oklch(1 0 0 / 10%))", + "sidebar-ring": "light-dark(oklch(0.708 0 0), oklch(0.556 0 0))" + } + }, + "css": { + "@import \"@fontsource/ubuntu/400.css\"": {}, + "@import \"@fontsource/ubuntu/500.css\"": {}, + "@import \"@fontsource/ubuntu/700.css\"": {}, + ":root": { + "color-scheme": "light" + }, + "@layer base": { + ":where([data-slot=\"card-description\"], [data-slot=\"dialog-description\"], [data-slot=\"alert-dialog-description\"], [data-slot=\"sheet-description\"], [data-slot=\"field-description\"], [data-slot=\"empty-title\"], [data-slot=\"empty-description\"], [data-slot=\"command-empty\"], [data-slot=\"table-caption\"])": { + "@apply font-readme": {} + }, + ":where(:not(pre) > code)": { + "@apply bg-muted px-1": {}, + "box-decoration-break": "clone" + }, + ":where([data-slot=\"dialog-content\"], [data-slot=\"alert-dialog-content\"])": { + "@apply shadow-lg": {} + }, + ":where([data-slot=\"tooltip-content\"])": { + "@apply shadow-md": {} + } + } + } + }, + { + "name": "waiting-approvals", + "type": "registry:lib", + "description": "What waits for a member's yes in a mind: the requests held by a secret's rule and the mails and calls held by the gate, read from the mind's logs, and the count of them as a hook.", + "dependencies": [ + "iterate", + "zod" + ], + "files": [ + { + "path": "src/lib/waiting-approvals.ts", + "type": "registry:lib" + }, + { + "path": "src/lib/approvals.ts", + "type": "registry:lib" + }, + { + "path": "src/lib/held-acts.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "agent-context", + "type": "registry:component", + "description": "A shared conversation feed with host event rows, safe agent progress, messages and activity, and call, captions and canvas parts.", + "dependencies": [ + "cn" + ], + "registryDependencies": [ + "iterate/packages/agent-chat", + "iterate/packages/call", + "iterate/packages/context-view", + "iterate/packages/virtual-log" + ], + "files": [ + { + "path": "src/components/agent-context.tsx", + "type": "registry:component" + }, + { + "path": "src/components/agent-context-rows.ts", + "type": "registry:component" + } + ] + }, + { + "name": "presence", + "type": "registry:lib", + "description": "Who is here now in a context, and who is typing, with nothing durable in its log: the pages open now from the subscriptions table's rows and the lent stubs (who holds each is the platform's stamp), and each page's own status (hidden, typing, marks) in one ephemeral event that only the row's holder may say; one page as a store, and a hook.", + "dependencies": [ + "zod" + ], + "files": [ + { + "path": "src/lib/presence.ts", + "type": "registry:lib" + }, + { + "path": "src/lib/principal-label.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "itx-session", + "type": "registry:lib", + "description": "A page's connection to its mind over reconnects, as plain functions: the session's epoch and state as a store, a keeper of a value's last settled answer, and a keeper of a context's log that holds its rows while a new session reads and puts the new rows after them.", + "files": [ + { + "path": "src/lib/itx-session.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "saved-context", + "type": "registry:lib", + "description": "A context's log that a reload draws at once: what useIterateContext returns, kept over reconnects and seeded with the tail of the log that the last page load saved, read from there for what is newer.", + "dependencies": [ + "iterate" + ], + "registryDependencies": [ + "iterate/packages/itx-session", + "iterate/packages/saved-log-tail" + ], + "files": [ + { + "path": "src/lib/saved-context.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "saved-log-tail", + "type": "registry:lib", + "description": "The saved tail of a context's log in the browser's IndexedDB, as plain functions: a store per mind and member that keeps each context's newest durable events within bounds, so a reload draws the last rows at once and reads only what is newer, and a wipe of every store when the sign-in ends.", + "dependencies": [ + "zod" + ], + "files": [ + { + "path": "src/lib/saved-log-tail.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "reconnecting-mark", + "type": "registry:component", + "description": "The one small line a page shows when its connection to the mind has been gone for two seconds: Reconnecting, or that the mind cannot be reached and the page keeps trying.", + "registryDependencies": [ + "iterate/packages/itx-session", + "spinner" + ], + "files": [ + { + "path": "src/components/reconnecting-mark.tsx", + "type": "registry:component" + } + ] + }, + { + "name": "page-tools", + "type": "registry:component", + "description": "Tools that an agent runs in the page that shows it, lent while a signed-in person has the page open: a banner with buttons, and Playwright's locators (fill, click, press, highlight, read) inside the part of the page that the host marks. The person sees a label with a Stop button while a call runs, and no call runs in a background tab; a jailed agent gets nothing.", + "dependencies": [ + "capnweb", + "ivya", + "lucide-react", + "zod" + ], + "registryDependencies": [ + "button", + "iterate/packages/itx-session" + ], + "files": [ + { + "path": "src/components/page-tools.tsx", + "type": "registry:component" + }, + { + "path": "src/lib/page-tools.ts", + "type": "registry:lib" + } + ] + }, + { + "name": "widget", + "type": "registry:component", + "description": "An agent's widget: HTML that an agent's script shows a person as one fact on its log, drawn in a sandboxed frame that speaks the MCP Apps messages (data, height, theme, words after a press, the console), with no network but the origins its csp declares. The same frame draws another server's MCP App, whose tool calls the page makes as the agent.", + "dependencies": [ + "cn", + "zod" + ], + "files": [ + { + "path": "src/components/widget/widget-frame.tsx", + "type": "registry:component" + }, + { + "path": "src/components/widget/widget-row.tsx", + "type": "registry:component" + }, + { + "path": "src/components/widget/widget.ts", + "type": "registry:component" + }, + { + "path": "src/components/widget/widget-mcp.ts", + "type": "registry:component" + } + ] + } + ] +}
A scripts/build-agent-kind-view-frame.ts
@@ -0,0 +1,37 @@ +// dist/agent-kind-view-frame.js, after tsdown's modules: the script of the frame a kind's chat view +// runs in (browser-entries.ts `AGENT_KIND_VIEW_FRAME` says why it is one classic script). Every +// dependency is inside it, React among them: the frame shares nothing with the page that made it. +// `pnpm build` runs it. +import { resolve } from "node:path"; +import { build } from "tsdown"; +import { AGENT_KIND_VIEW_FRAME } from "../browser-entries.ts"; + +const ui = resolve(import.meta.dirname, ".."); + +await build({ + // no config file: tsdown.config.ts is the modules' build, which cleans dist + config: false, + cwd: ui, + entry: { [AGENT_KIND_VIEW_FRAME.replace(/\.js$/, "")]: "src/browser/agent-kind-view-frame.ts" }, + format: "iife", + outDir: "dist", + clean: false, + platform: "browser", + target: "es2022", + hash: false, + minify: true, + dts: false, + define: { + "import.meta.env.SSR": "false", + "import.meta.env.DEV": "false", + "import.meta.env.BASE_URL": JSON.stringify("/"), + "process.env.NODE_ENV": JSON.stringify("production"), + }, + loader: { ".svg": "dataurl" }, + deps: { alwaysBundle: [/./], onlyBundle: false }, + inputOptions: { + // React libraries mark their modules "use client", which means nothing outside a server build + onLog: (level, log, handler) => log.code === "MODULE_LEVEL_DIRECTIVE" || handler(level, log), + }, + outputOptions: { entryFileNames: AGENT_KIND_VIEW_FRAME }, +});
A scripts/build-docs-tree.ts
@@ -0,0 +1,27 @@ +// dist/components/docs-editor/doc-tree.mjs, after tsdown's modules: the docs editor's file tree +// (src/components/docs-editor/doc-tree.ts) with its own @pierre/trees, which `DocTree` imports +// when it first draws (tsdown.config.ts keeps it out of the modules' build). The repo IDE keeps its +// copy inside its own file, so a page that shows the IDE loads no file more; a page shows one tree +// or the other, never both. `pnpm build` runs it. +import { resolve } from "node:path"; +import { build } from "tsdown"; + +const ui = resolve(import.meta.dirname, ".."); + +await build({ + // no config file: tsdown.config.ts is the modules' build, which cleans dist + config: false, + cwd: ui, + entry: { "components/docs-editor/doc-tree": "src/components/docs-editor/doc-tree.ts" }, + format: "esm", + fixedExtension: true, + outDir: "dist", + clean: false, + platform: "browser", + target: "es2022", + hash: false, + minify: true, + dts: false, + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + deps: { alwaysBundle: [/./], onlyBundle: false }, +});
A scripts/build-iterate-css.ts
@@ -0,0 +1,59 @@ +// dist/iterate.css and dist/fonts/, after dist/styles.css: the look's overlay for a no-build page +// (iterate-look.ts says how it is cut). `pnpm build` runs it after the stylesheets. +// +// THE DOCS EDITOR'S PAGE links dist/docs-editor.css in place of dist/styles.css, and this same +// dist/iterate.css after it. The overlay is cut from styles.css, which leaves the docs editor's +// own classes out. So the build also cuts the overlay from docs-editor.css and fails when that one +// holds a rule this one lacks: a class that only the docs editor uses, with a value that the look +// changes, would be drawn in the neutral look on that page. +import { execFileSync } from "node:child_process"; +import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { LOOK_SOURCE, overlayCss, packagesOf, withFontsBeside } from "./iterate-look.ts"; + +const ui = resolve(import.meta.dirname, ".."); +/** The overlay cut from a build of `source` (a sheet with the look over it) against `neutral`, + * the built sheet without it. */ +const overlayOf = (source: string, neutral: string) => + withFontsBeside( + overlayCss({ + neutral: readFileSync(join(ui, neutral), "utf8"), + look: execFileSync( + join(ui, "node_modules/.bin/tailwindcss"), + ["--input", source, "--minify"], + { cwd: ui, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }, + ), + }), + ); +const { css, files } = overlayOf("src/browser/iterate.css", "dist/styles.css"); + +const docsOnly = overlayCss({ + neutral: css, + look: overlayOf("src/browser/docs-editor-look.css", "dist/docs-editor.css").css, +}); +if (docsOnly) + throw new Error( + `dist/iterate.css lacks the look of classes that only the docs editor uses, so the docs editor's page would draw them in the neutral look. Use a class that another component uses too, or one whose value the look does not change. The rules: ${docsOnly.slice(0, 600)}`, + ); + +const require = createRequire(join(ui, "package.json")); +const fontPackages = packagesOf(readFileSync(join(ui, LOOK_SOURCE), "utf8")).map((name) => + dirname(require.resolve(`${name}/package.json`)), +); +mkdirSync(join(ui, "dist/fonts"), { recursive: true }); +for (const file of files) { + const from = fontPackages.map((root) => join(root, "files", file)).find(existsSync); + if (!from) throw new Error(`${file} is in none of ${fontPackages.join(", ")}`); + copyFileSync(from, join(ui, "dist/fonts", file)); +} +const exported = JSON.parse(readFileSync(join(ui, "package.json"), "utf8")).publishConfig.exports; +const unexported = files.filter((file) => !exported[`./fonts/${file}`]); +if (unexported.length > 0) + throw new Error( + `package.json does not export ${unexported.join(", ")}: run node scripts/ci/shadcn-registry.ts update`, + ); +writeFileSync(join(ui, "dist/iterate.css"), css); +console.log( + `dist/iterate.css: ${css.length} bytes, ${files.length} font files; it is the look of the docs editor's classes too`, +);
A scripts/check-docs-editor-css.ts
@@ -0,0 +1,17 @@ +// After `pnpm build`'s stylesheets: dist/docs-editor.css, which the docs editor's page links in +// place of dist/styles.css, holds every rule of dist/styles.css in its order (stylesheet-order.ts), +// or the build fails. +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { rulesMissingInOrder } from "./stylesheet-order.ts"; + +const dist = resolve(import.meta.dirname, "../dist"); +const missing = rulesMissingInOrder({ + sheet: readFileSync(resolve(dist, "styles.css"), "utf8"), + whole: readFileSync(resolve(dist, "docs-editor.css"), "utf8"), +}); +if (missing.length > 0) + throw new Error( + `dist/docs-editor.css lacks ${missing.length} rules of dist/styles.css, or has them out of order, so the docs editor's page would compute other styles than every other page:\n${missing.slice(0, 20).join("\n\n")}`, + ); +console.log("dist/docs-editor.css holds every rule of dist/styles.css, in its order");
A scripts/component-tokens.test.ts
@@ -0,0 +1,48 @@ +import { expect, test } from "vitest"; +import { componentTokens } from "./component-tokens.ts"; + +test("an item carries the tokens its files use, and only those", () => { + const tokens = componentTokens({ + tokensCss: TOKENS_CSS, + sources: [ + `<span className="bg-success/10 text-2xs">Live</span>`, + `const gutter = { backgroundColor: "var(--info)" };`, + `<div className="bg-chart-10" />`, + ], + }); + + expect(tokens).toEqual({ + cssVars: { + theme: { + "color-success": "var(--success)", + "color-info": "var(--info)", + "text-2xs": "0.6875rem", + "text-2xs--line-height": "calc(1 / 0.6875)", + }, + light: { success: "oklch(0.5 0.1 165)", info: "oklch(0.5 0.1 242)" }, + }, + }); +}); + +test("an item that uses none carries nothing", () => { + expect( + componentTokens({ tokensCss: TOKENS_CSS, sources: [`<p className="text-sm">Hi</p>`] }), + ).toEqual({}); +}); + +const TOKENS_CSS = ` +@theme inline { + --color-success: var(--success); + --color-warning: var(--warning); + --color-info: var(--info); + --color-chart-1: var(--chart-1); + --text-2xs: 0.6875rem; + --text-2xs--line-height: calc(1 / 0.6875); +} +:root { + --success: oklch(0.5 0.1 165); + --warning: oklch(0.5 0.1 49); + --info: oklch(0.5 0.1 242); + --chart-1: #2a78d6; +} +`;
A scripts/component-tokens.ts
@@ -0,0 +1,39 @@ +// component-tokens.ts — what a registry component item carries of src/styles/tokens.css, the +// variables packages/ui's components use beyond shadcn's own (the status colours, the highlight, +// chart series, `text-2xs`). An app that installs the item from the shadcn registry gets the ones its +// files use as the item's `cssVars`: each theme name, and a colour's neutral value. shadcn 4.21's +// `add` writes a component item's values only where the app has none, so an app that installed +// iterate's `theme` item first keeps iterate's colours. +import postcss from "postcss"; + +/** The path of the tokens' file in packages/ui. */ +export const TOKENS_SOURCE = "src/styles/tokens.css"; + +/** The `cssVars` for what `sources` use of `tokensCss`: a colour by any utility (`bg-success/10`) + * or `var(--success)`, any other theme value by its utility (`text-2xs`, and its line height with + * it). Nothing when they use none. Pure. */ +export function componentTokens(input: { tokensCss: string; sources: string[] }) { + const root = postcss.parse(input.tokensCss); + const values = new Map<string, string>(); + root.walkRules(":root", (rule) => + rule.walkDecls((decl) => void values.set(decl.prop.slice(2), decl.value)), + ); + const theme: Record<string, string> = {}; + const light: Record<string, string> = {}; + root.walkAtRules("theme", (atRule) => + atRule.walkDecls((decl) => { + const name = decl.prop.slice(2); + const colour = name.match(/^color-(.+)$/)?.[1]; + const used = colour + ? new RegExp(`(?<![\\w-])[a-z-]+-${colour}(?:/\\d+)?(?![\\w-])|var\\(--${colour}\\)`) + : new RegExp(`(?<![\\w-])${name.replace(/--.*$/, "")}(?![\\w-])`); + if (!input.sources.some((source) => used.test(source))) return; + theme[name] = decl.value; + if (colour) light[colour] = values.get(colour)!; + }), + ); + if (Object.keys(theme).length === 0) return {}; + return { + cssVars: { theme, ...(Object.keys(light).length > 0 && { light }) }, + }; +}
A scripts/iterate-look.test.ts
@@ -0,0 +1,92 @@ +import { expect, test } from "vitest"; +import { + fontFilesOf, + overlayCss, + themeAppliedProblems, + themeItem, + withFontsBeside, +} from "./iterate-look.ts"; + +test("the overlay keeps what the look's build has and the neutral build lacks, in the at-rules around it, with its font files beside it", () => { + const neutral = [ + "@layer theme{:root,:host{--font-sans:system-ui;--radius-2xl:1rem}}", + "@layer utilities{.p-1{padding:.25rem}.rounded-full{border-radius:calc(infinity*1px)}", + "@media (width>=40rem){.sm\\:rounded-full{border-radius:calc(infinity*1px)}}}", + ":root{--background:oklch(1 0 0)}", + ].join(""); + const look = [ + "@layer theme{:root,:host{--font-sans:Ubuntu;--radius-2xl:0}}", + "@layer utilities{.p-1{padding:.25rem}.rounded-full{border-radius:0}", + "@media (width>=40rem){.sm\\:rounded-full{border-radius:0}}", + ".font-readme{font-family:var(--font-mono)}}", + ":root{--background:oklch(1 0 0)}:root{--background:#fff}", + '@font-face{font-family:Ubuntu;src:url(./files/ubuntu-latin-400-normal.woff2)format("woff2"),url(./files/ubuntu-latin-400-normal.woff)format("woff")}', + ].join(""); + + expect(withFontsBeside(overlayCss({ neutral, look }))).toMatchInlineSnapshot(` + { + "css": "@layer theme{:root,:host{--font-sans:Ubuntu;--radius-2xl:0}}@layer utilities{.rounded-full{border-radius:0}}@layer utilities{@media (width>=40rem){.sm\\:rounded-full{border-radius:0}}}@layer utilities{.font-readme{font-family:var(--font-mono)}}:root{--background:#fff}@font-face{font-family:Ubuntu;src:url(./fonts/ubuntu-latin-400-normal.woff2) format("woff2")}", + "files": [ + "ubuntu-latin-400-normal.woff2", + ], + } + `); +}); + +test("a stylesheet the theme item was added to is checked for each of its values", () => { + const item = themeItem({ + css: `@import "@fontsource/ubuntu/400.css"; +:root { color-scheme: light dark; --background: light-dark(#ffffff, #111111); } +@theme inline { --font-sans: "Ubuntu", sans-serif; } +@layer base { :where([data-slot="card-description"]) { @apply font-readme; } }`, + read: () => "", + }); + expect(item).toMatchObject({ + cssVars: { light: { background: "light-dark(#ffffff, #111111)" } }, + css: { ":root": { "color-scheme": "light dark" } }, + }); + const added = `@import "tailwindcss"; +@import "@fontsource/ubuntu/400.css"; +@theme inline { --color-background: var(--background); --font-sans: "Ubuntu", sans-serif; } +:root { --background: light-dark(#ffffff, #111111); color-scheme: light dark; } +@layer base { :where([data-slot="card-description"]) { @apply font-readme; } }`; + + expect(themeAppliedProblems({ item, css: added })).toEqual([]); + expect( + themeAppliedProblems({ + item, + css: added + .replace('@import "@fontsource/ubuntu/400.css";', "") + .replace("light-dark(#ffffff, #111111)", "oklch(1 0 0)") + .replace(" color-scheme: light dark;", "") + .replace("@apply font-readme;", ""), + }), + ).toEqual([ + ":root --background: oklch(1 0 0)", + '@import "@fontsource/ubuntu/400.css" missing', + ":root color-scheme: undefined", + ':where([data-slot="card-description"]) lacks @apply font-readme', + ]); +}); + +test("the font files are each woff2 the look's font imports name, which the package exports one by one", () => { + const faces = (weight: number) => + ["latin", "latin-ext"] + .map( + (subset) => + `@font-face{font-weight:${weight};src:url(./files/ubuntu-${subset}-${weight}-normal.woff2) format("woff2"),url(./files/ubuntu-${subset}-${weight}-normal.woff) format("woff")}`, + ) + .join(""); + + expect( + fontFilesOf({ + css: `@import "@fontsource/ubuntu/700.css";\n@import "@fontsource/ubuntu/400.css";\n@import "iterate/tokens.css";`, + read: (specifier) => faces(Number(/(\d+)\.css$/.exec(specifier)![1])), + }), + ).toEqual([ + "ubuntu-latin-400-normal.woff2", + "ubuntu-latin-700-normal.woff2", + "ubuntu-latin-ext-400-normal.woff2", + "ubuntu-latin-ext-700-normal.woff2", + ]); +});
A scripts/iterate-look.ts
@@ -0,0 +1,250 @@ +// iterate-look.ts — ITERATE'S LOOK, THREE WAYS, FROM ONE FILE. src/styles/iterate.css is the look as +// a Tailwind build reads it: the apps import it after globals.css. The other two ways are cut from it, +// so none can say something the file does not: +// +// - dist/iterate.css, for a no-build page, linked after dist/styles.css (scripts/build-iterate-css.ts). +// `overlayCss` compiles both stylesheets and keeps the rules of the look's that the neutral one does +// not have: the custom properties, and every utility whose value Tailwind wrote into the rule +// (`rounded-full`, the shadows, `font-readme`). Each sits in the same @layer as the rule it replaces +// and comes later, so it wins. The font files go beside it in dist/fonts, named by relative url()s, +// so the overlay works from any host of the package (esm.sh, jsDelivr, pkg.pr.new). +// - The registry's `theme` item, for an app that installs from the shadcn registry +// (scripts/ci/shadcn-registry.ts writes it into registry.json; Lint and Typecheck fails when it is +// stale). `themeItem` turns the file into the item's fields, as shadcn 4.21's `add` applies them: +// `cssVars.theme` into the app's `@theme inline`, `cssVars.light` into its `:root`, each replacing +// the app's own value, and `css` as written (an `@import "<package>"` after the app's last import, +// `color-scheme` into its `:root`, and `@layer base` rules with their `@apply`). +// +// test/playwright/ui/iterate-look.spec.ts holds the three to one look: the same elements, styled each +// way, compute the same styles. +import postcss, { type ChildNode, type Container } from "postcss"; + +/** The look's file, by its path in packages/ui. */ +export const LOOK_SOURCE = "src/styles/iterate.css"; + +/** At-rules that only group the rules inside them. */ +const GROUPING = new Set(["layer", "media", "supports", "container", "starting-style"]); + +/** dist/iterate.css: what a build of the look (`look`) has that the neutral build (`neutral`) does + * not, each rule in the at-rules it sits in. Pure. */ +export function overlayCss(input: { neutral: string; look: string }) { + const known = new Set( + leavesOf(postcss.parse(input.neutral)).map((leaf) => leafKey(leaf.path, leaf.node)), + ); + const out = postcss.root(); + let open: { path: string; container: Container } = { path: "", container: out }; + for (const { path, node } of leavesOf(postcss.parse(input.look))) { + if (known.has(leafKey(path, node))) continue; + if (open.path !== path.join("\n")) { + let container: Container = out; + for (const wrapper of path) { + const [, name, params] = /^@(\S+) ?(.*)$/s.exec(wrapper)!; + const atRule = postcss.atRule({ name: name!, params: params! }); + container.append(atRule); + container = atRule; + } + open = { path: path.join("\n"), container }; + } + open.container.append(node.clone()); + } + return out.toString(); +} + +/** Every rule or ungrouped at-rule, with the grouping at-rules around it. */ +function leavesOf( + container: Container, + path: string[] = [], +): { path: string[]; node: ChildNode }[] { + return (container.nodes || []).flatMap((node) => { + if (node.type === "comment") return []; + if (node.type === "atrule" && GROUPING.has(node.name) && node.nodes) + return leavesOf(node, [...path, `@${node.name} ${node.params}`]); + return [{ path, node }]; + }); +} + +function leafKey(path: string[], node: ChildNode) { + const clone = node.clone(); + clone.cleanRaws(); + return [...path, clone.toString()].join("\n"); +} + +/** `overlay` with each @font-face's `src` cut to its woff2 file, named beside the stylesheet in + * `fonts/`, and the files it names. A font package's faces name `./files/<file>` (fontsource's + * layout), relative to the package. Pure. */ +export function withFontsBeside(overlay: string) { + const root = postcss.parse(overlay); + const files: string[] = []; + root.walkAtRules("font-face", (face) => { + face.walkDecls("src", (src) => { + const woff2 = woff2Of(src.value); + files.push(woff2); + src.value = `url(./fonts/${woff2}) format("woff2")`; + }); + }); + return { css: root.toString(), files }; +} + +/** The woff2 files the font packages the look's file (`css`) imports name, which the overlay + * ships in dist/fonts and the published package exports one by one (esm.sh serves a file by an + * export only when the export names it). `read` gives an imported file's text. Pure. */ +export function fontFilesOf(input: { css: string; read: (specifier: string) => string }) { + const files: string[] = []; + postcss.parse(input.css).walkAtRules("import", (atRule) => { + const specifier = unquote(atRule.params); + if (specifier.startsWith("iterate/")) return; + postcss + .parse(input.read(specifier)) + .walkAtRules("font-face", (face) => + face.walkDecls("src", (src) => void files.push(woff2Of(src.value))), + ); + }); + return [...new Set(files)].sort(); +} + +function woff2Of(src: string) { + const woff2 = /url\(["']?\.\/files\/([\w.-]+\.woff2)["']?\)/.exec(src)?.[1]; + if (!woff2) throw new Error(`a font face with no ./files/*.woff2 source: ${src}`); + return woff2; +} + +/** The packages the look's file imports (the font). */ +export function packagesOf(css: string) { + const packages = new Set<string>(); + postcss.parse(css).walkAtRules("import", (atRule) => { + const specifier = unquote(atRule.params); + if (!specifier.startsWith("iterate/")) packages.add(packageOf(specifier)); + }); + return [...packages].sort(); +} + +/** The registry's `theme` item's fields, from the look's file (`css`). `read` gives the text of a + * file it imports from `iterate` (tokens.css), which the item carries as values: an app outside this + * repo need not install `iterate` for its colours. Throws on anything the item cannot carry. Pure. */ +export function themeItem(input: { css: string; read: (specifier: string) => string }) { + const theme: Record<string, string> = {}; + const light: Record<string, string> = {}; + // `@import "<package>"`, `:root`'s declarations that are not colours (`color-scheme`), and each + // `@layer`'s rules + const css: Record< + string, + Record<string, Record<string, Record<string, never> | string> | string> + > = {}; + const addLight = (container: Container) => + container.each((node) => { + if (node.type !== "decl") return; + if (node.prop.startsWith("--")) light[node.prop.slice(2)] = node.value; + else (css[":root"] ||= {})[node.prop] = node.value; + }); + postcss.parse(input.css).each((node) => { + if (node.type === "comment") return; + if (node.type === "atrule" && node.name === "import") { + const specifier = unquote(node.params); + if (specifier.startsWith("iterate/")) + return void postcss.parse(input.read(specifier)).walkRules(":root", addLight); + css[`@import "${specifier}"`] = {}; + return; + } + if (node.type === "rule" && node.selector === ":root") return void addLight(node); + if (node.type === "atrule" && node.name === "theme" && node.params === "inline") + return void node.each((child) => { + if (child.type === "decl") theme[child.prop.replace(/^--/, "")] = child.value; + }); + if (node.type === "atrule" && node.name === "layer") { + const layer = (css[`@layer ${node.params}`] ||= {}); + return void node.each((rule) => { + if (rule.type === "comment") return; + if (rule.type !== "rule") throw new Error(`${LOOK_SOURCE}: @layer holds ${rule.type}`); + const body: Record<string, Record<string, never> | string> = {}; + rule.each((child) => { + if (child.type === "atrule" && child.name === "apply") + body[`@apply ${child.params}`] = {}; + else if (child.type === "decl") body[child.prop] = child.value; + else if (child.type !== "comment") + throw new Error(`${LOOK_SOURCE}: ${rule.selector} holds ${child.toString()}`); + }); + layer[rule.selector.replace(/\s+/g, " ").replace(/\( /g, "(").replace(/ \)/g, ")")] = body; + }); + } + throw new Error(`${LOOK_SOURCE}: a registry theme item cannot carry ${node.toString()}`); + }); + // A colour that names another (`--sidebar: var(--background)`) goes as the other's value: shadcn + // maps a light value it does not take for a colour into `@theme inline` under its own name, which + // for `var(--background)` writes `--sidebar: var(--sidebar)`. + for (const [name, value] of Object.entries(light)) { + const alias = /^var\(--([\w-]+)\)$/.exec(value)?.[1]; + if (alias && alias in light) light[name] = light[alias]!; + } + return { + dependencies: packagesOf(input.css), + cssVars: { theme, light }, + css, + }; +} + +function unquote(params: string) { + return params.replace(/^(["'])(.*)\1$/, "$2"); +} + +function packageOf(specifier: string) { + return specifier + .split("/") + .slice(0, specifier.startsWith("@") ? 2 : 1) + .join("/"); +} + +/** What `shadcn add` of the theme item (`item`) left out of the app's stylesheet (`css`, after the + * add): each theme value in its `@theme inline`, each light value and `color-scheme` in its + * `:root`, each import and each base rule. Empty when the app has the look. Pure. */ +export function themeAppliedProblems(input: { item: ReturnType<typeof themeItem>; css: string }) { + const root = postcss.parse(input.css); + const declsOf = (containers: Container[]) => + new Map( + containers.flatMap((container) => + (container.nodes || []).flatMap((node) => + node.type === "decl" ? [[node.prop.replace(/^--/, ""), node.value] as const] : [], + ), + ), + ); + const theme = declsOf( + (root.nodes || []).filter( + (node): node is Container & ChildNode => + node.type === "atrule" && node.name === "theme" && node.params === "inline", + ), + ); + const light = declsOf( + (root.nodes || []).filter( + (node): node is Container & ChildNode => node.type === "rule" && node.selector === ":root", + ), + ); + const imports = new Set<string>(); + root.walkAtRules("import", (atRule) => void imports.add(`@import ${atRule.params}`)); + const baseRules = new Map<string, string>(); + root.walkAtRules("layer", (layer) => { + if (layer.params === "base") + layer.walkRules((rule) => void baseRules.set(rule.selector, rule.toString())); + }); + const problems: string[] = []; + for (const [name, value] of Object.entries(input.item.cssVars.theme)) + if (theme.get(name) !== value) problems.push(`@theme inline --${name}: ${theme.get(name)}`); + for (const [name, value] of Object.entries(input.item.cssVars.light)) + if (light.get(name) !== value) problems.push(`:root --${name}: ${light.get(name)}`); + for (const [key, rules] of Object.entries(input.item.css)) { + if (key.startsWith("@import ")) { + if (!imports.has(key)) problems.push(`${key} missing`); + continue; + } + for (const [selector, body] of Object.entries(rules)) { + // a declaration of `:root` itself + if (typeof body === "string") { + if (light.get(selector) !== body) + problems.push(`${key} ${selector}: ${light.get(selector)}`); + continue; + } + for (const line of Object.keys(body)) + // react-doctor-disable-next-line react-doctor/js-set-map-lookups -- a substring of the rule's text, not a lookup in an array + if (!baseRules.get(selector)?.includes(line)) problems.push(`${selector} lacks ${line}`); + } + } + return problems; +}
A scripts/stylesheet-order.test.ts
@@ -0,0 +1,65 @@ +// The check that dist/docs-editor.css holds dist/styles.css in its order. The sheets here are cut +// from Tailwind's minified output; the build runs the check on the real ones +// (check-docs-editor-css.ts). +import { expect, test } from "vitest"; +import { rulesMissingInOrder } from "./stylesheet-order.ts"; + +const styles = [ + "@layer theme,base,components,utilities;", + "@layer theme{:root,:host{--color-red-500:red}}", + "@layer utilities{.hidden{display:none}.flex{display:flex}", + "@media (width>=48rem){.md\\:block{display:block}.md\\:hidden{display:none}}}", + "@supports (-moz-orient:inline){@layer base{*{--tw-ring-color:initial}}}", +].join(""); + +test.for([ + { name: "the same sheet", whole: styles, missing: [] }, + { + name: "a whole build with the docs editor's classes too: a utility and a variant more, a theme and fallback with more properties, Atomic's rules after", + whole: [ + "@layer theme,base,components,utilities;", + "@layer theme{:root,:host{--color-red-500:red;--color-highlight:var(--highlight)}}", + "@layer utilities{.hidden{display:none}.flex{display:flex}.grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}", + "@media (width>=48rem){.md\\:block{display:block}.md\\:flex-row{flex-direction:row}.md\\:hidden{display:none}}}", + "@supports (-moz-orient:inline){@layer base{*{--tw-ring-color:initial;--tw-shadow:0 0 #0000}}}", + ".atomic-cm-editor{position:relative}", + ].join(""), + missing: [], + }, + { + // a second sheet of utilities alone, linked after styles.css, is not a whole: its plain + // `.hidden` would come after styles.css's `md:block` in the one `utilities` layer, and win + name: "the docs editor's utilities alone, as a second sheet", + whole: + "@layer utilities{.hidden{display:none}.grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}}", + missing: [ + "@layer theme,base,components,utilities", + "@layer theme\n:root,:host", + "@layer utilities\n.flex", + "@layer utilities\n@media (width>=48rem)\n.md\\:block", + "@layer utilities\n@media (width>=48rem)\n.md\\:hidden", + "@supports (-moz-orient:inline)\n@layer base\n*", + ], + }, + { + name: "a variant before the plain utility it overrides", + whole: [ + "@layer theme,base,components,utilities;", + "@layer theme{:root,:host{--color-red-500:red}}", + "@layer utilities{@media (width>=48rem){.md\\:block{display:block}.md\\:hidden{display:none}}", + ".hidden{display:none}.flex{display:flex}}", + "@supports (-moz-orient:inline){@layer base{*{--tw-ring-color:initial}}}", + ].join(""), + missing: [ + "@layer utilities\n@media (width>=48rem)\n.md\\:block", + "@layer utilities\n@media (width>=48rem)\n.md\\:hidden", + ], + }, + { + name: "a rule whose declarations differ", + whole: styles.replace(".flex{display:flex}", ".flex{display:inline-flex}"), + missing: ["@layer utilities\n.flex"], + }, +])("$name", ({ whole, missing }) => { + expect(rulesMissingInOrder({ sheet: styles, whole })).toEqual(missing); +});
A scripts/stylesheet-order.ts
@@ -0,0 +1,59 @@ +// stylesheet-order.ts — ONE STYLESHEET HOLDS ANOTHER, IN ITS ORDER: the comparison behind the +// build's check of dist/docs-editor.css against dist/styles.css (check-docs-editor-css.ts; +// src/browser/docs-editor.css says why one sheet must hold the other). +import postcss, { type ChildNode, type Container } from "postcss"; + +/** At-rules that only group the rules inside them. */ +const GROUPING = new Set(["layer", "media", "supports", "container", "starting-style"]); + +/** The rules of `sheet` that `whole` lacks, or has only out of `sheet`'s order: none when `whole` + * holds `sheet`. A rule counts as held when `whole` has, later than the last one matched, a rule at + * the same place (selector and the at-rules around it) with at least its declarations: a bigger + * build lists more custom properties in its theme and its `@property` fallbacks. Pure. */ +export function rulesMissingInOrder(input: { sheet: string; whole: string }) { + const whole = leavesOf(postcss.parse(input.whole)); + const missing: string[] = []; + let at = 0; + for (const leaf of leavesOf(postcss.parse(input.sheet))) { + let found = at; + while ( + found < whole.length && + !( + whole[found]!.place === leaf.place && + [...leaf.declarations].every((d) => whole[found]!.declarations.has(d)) + ) + ) + found++; + if (found === whole.length) missing.push(leaf.place); + else at = found + 1; + } + return missing; +} + +/** Each rule with its own declarations, by its place: the at-rules and selectors around it, and its + * selector. An at-rule that is not a grouping one (`@property`, `@keyframes`, `@font-face`) is a + * place of its own, its whole text. */ +function leavesOf( + container: Container, + path: string[] = [], +): { place: string; declarations: Set<string> }[] { + return (container.nodes || []).flatMap((node: ChildNode) => { + if (node.type === "comment" || node.type === "decl") return []; + if (node.type === "atrule" && GROUPING.has(node.name) && node.nodes) + return leavesOf(node, [...path, `@${node.name} ${node.params}`]); + if (node.type === "rule") { + const inner = [...path, node.selector]; + const declarations = new Set( + (node.nodes || []).flatMap((child) => + child.type === "decl" + ? [`${child.prop}:${child.value}${child.important ? "!important" : ""}`] + : [], + ), + ); + return [{ place: inner.join("\n"), declarations }, ...leavesOf(node, inner)]; + } + const clone = node.clone(); + clone.cleanRaws(); + return [{ place: [...path, clone.toString()].join("\n"), declarations: new Set<string>() }]; + }); +}
A src/agent-kind-view/bridge.test.ts
@@ -0,0 +1,49 @@ +// The host sends the frame what changed: fields by identity, events as the pages added at either end. +import { expect, test } from "vitest"; +import { applyUpdate, updateBetween, type AgentKindViewInputs } from "./bridge.ts"; + +test("a new event at the head goes alone, and the frame's copy matches the host's", () => { + const first = inputs([event(5), event(6)]); + const next = { ...first, events: [...first.events, event(7)], caughtUp: true }; + const update = updateBetween(first, next); + expect(update).toEqual({ caughtUp: true, events: { prepend: [], append: [event(7)] } }); + expect(applyUpdate(first, update!)).toEqual(next); +}); + +test("an older page goes as a prepend; an unchanged view sends nothing", () => { + const held = inputs([event(5), event(6)]); + const next = { ...held, events: [event(3), event(4), ...held.events] }; + expect(updateBetween(held, next)).toEqual({ + events: { prepend: [event(3), event(4)], append: [] }, + }); + expect(updateBetween(next, next)).toBeNull(); +}); + +test("a window that moved otherwise (a reconnect) is sent whole", () => { + const held = inputs([event(5), event(6)]); + const next = { ...held, events: [event(9)] }; + expect(updateBetween(held, next)).toEqual({ events: { reset: [event(9)] } }); + expect(applyUpdate(held, updateBetween(held, next)!)).toEqual(next); +}); + +function event(offset: number) { + return { offset, type: "test/said", createdAt: "2026-11-10T00:00:00.000Z", payload: { offset } }; +} + +function inputs(events: AgentKindViewInputs["events"]): AgentKindViewInputs { + return { + path: "/agents/echo/1", + events, + caughtUp: false, + error: undefined, + head: 6, + older: null, + processors: { rows: [], loaded: true }, + presence: { actors: [], rpcStubs: [] }, + liveState: {}, + version: undefined, + hostError: undefined, + state: {}, + documentClass: "dark", + }; +}
A src/agent-kind-view/bridge.ts
@@ -0,0 +1,145 @@ +// THE BRIDGE between a page that shows an agent (host.tsx) and the sandboxed frame that runs its +// kind's view (frame.tsx): capnweb over a MessagePort, a main object each way. +// +// host → frame `update(delta)`: what changed of the view's inputs since the last update. Events +// go as the pages added at either end, never the whole log again. +// host → frame `start(input)`: the kind's `newAgent.start`, for the Dash's New agent. +// frame → host `loaded(…)` once (what the live read should include), then the verbs: message, +// append, fileUrl, storeFiles, setState, loadOlder, and an MCP App's callTool and +// readResource. Each acts on the one agent the host shows; +// the host never hands over its context stub, whose `invoke` and `cd` reach the +// whole mind. +import type { AgentChatState } from "../components/agent-chat/agent-chat-search.ts"; +import type { ContextViewSource } from "../components/context-view/context-view.tsx"; +import type { AgentKindNewAgent, AgentKindViewProps } from "./types.ts"; + +type Event = ContextViewSource["events"][number]; + +/** The first message, host → frame, carrying the port. `source` is the kind file's text, or + * `null` when the agent's kind has none. */ +export type AgentKindViewHello = { + type: "iterate/agent-kind-view"; + name: string; + source: string | null; +}; +/** The frame's script has run and is listening for the hello. */ +export const AGENT_KIND_VIEW_READY = "iterate/agent-kind-view-ready"; + +/** Everything a view's props are built from, as plain data. */ +export type AgentKindViewInputs = { + path: string; + events: readonly Event[]; + caughtUp: boolean; + error: string | undefined; + head: number | undefined; + /** Reading older pages: `null` when the whole log is held. */ + older: { loading: boolean; exhausted: boolean } | null; + processors: AgentKindViewProps["context"]["processors"]; + presence: ContextViewSource["presence"]; + liveState: ContextViewSource["liveState"]; + /** The version of the agent's path that `events` are of, once a read has said it (`versionOf`). */ + version: number | undefined; + hostError: string | undefined; + state: AgentChatState; + /** The page's `<html>` classes (its theme), for the frame's own. */ + documentClass: string; + /** `true`: the page draws Chat | Events in its own header, and the tab is `state.view`: the + * view's shell draws no strip, and its status is a line at the feed's foot. */ + tabsInHeader?: boolean; + /** The viewer's actor id, when the page knows it (`AgentKindViewProps.me`). */ + me?: string; + /** `true`: the page shows who else is here (`AgentKindViewProps.presence`). */ + presenceOn?: boolean; +}; + +/** What changed: the fields that did, and the events added at either end, or all of them again + * when the held window moved otherwise (a reconnect). */ +export type AgentKindViewUpdate = Partial<Omit<AgentKindViewInputs, "events">> & { + events?: { reset: Event[] } | { prepend: Event[]; append: Event[] }; +}; + +/** What a kind file says of how its agents start (types.ts `AgentKindNewAgent`), as data: its + * `start` runs in the frame (`AgentKindViewFrameApi.start`). */ +export type AgentKindNewAgentSummary = Omit<AgentKindNewAgent, "start" | "describe">; + +/** What the frame reports once it has read the kind file. */ +export type AgentKindViewLoaded = + | { ephemeralEvents: string[]; newAgent?: AgentKindNewAgentSummary } + | { error: string } + /** The agent's kind has no file: the frame shows the Events tab. */ + | { none: true }; + +export interface AgentKindViewHostApi { + loaded(result: AgentKindViewLoaded): void; + message(input: Parameters<AgentKindViewProps["onMessage"]>[0]): Promise<void>; + append(events: unknown[]): Promise<void>; + fileUrl(path: string): Promise<string>; + storeFiles( + files: Parameters<NonNullable<AgentKindViewProps["storeFiles"]>>[0], + key?: string, + ): ReturnType<NonNullable<AgentKindViewProps["storeFiles"]>>; + setState(patch: Partial<AgentChatState>): void; + loadOlder(): void; + /** An MCP App's tool call, made as the agent at `path` (the host's own agent alone). */ + callTool( + call: Parameters<NonNullable<AgentKindViewProps["widgetCalls"]>["callTool"]>[0], + ): Promise<unknown>; + /** An MCP App's resource read, likewise. */ + readResource( + read: Parameters<NonNullable<AgentKindViewProps["widgetCalls"]>["readResource"]>[0], + ): Promise<unknown>; +} + +export interface AgentKindViewFrameApi { + update(update: AgentKindViewUpdate): void; + /** The kind's `newAgent.start(input)`, run in the frame: the events that start an agent of the + * kind at `input.path`. The page appends them; the kind file never runs in the page. */ + start(input: Parameters<AgentKindNewAgent["start"]>[0]): unknown[] | Promise<unknown[]>; +} + +/** The update from `previous` (what the frame holds) to `next`, or `null` when nothing changed. */ +export function updateBetween( + previous: AgentKindViewInputs | undefined, + next: AgentKindViewInputs, +): AgentKindViewUpdate | null { + const update: AgentKindViewUpdate = {}; + let changed = false; + for (const key of Object.keys(next) as (keyof AgentKindViewInputs)[]) { + if (key === "events" || (previous && previous[key] === next[key])) continue; + (update as Record<string, unknown>)[key] = next[key]; + changed = true; + } + if (!previous || previous.events !== next.events) { + update.events = eventsBetween(previous?.events || [], next.events); + changed = true; + } + return changed ? update : null; +} + +/** The pages added at either end of what was held, or everything when it moved otherwise. */ +function eventsBetween( + held: readonly Event[], + next: readonly Event[], +): AgentKindViewUpdate["events"] { + const first = held[0]; + const last = held.at(-1); + if (!first || !last) return { reset: [...next] }; + const start = next.findIndex((event) => event.offset === first.offset); + const end = start + held.length - 1; + if (start < 0 || next[end]?.offset !== last.offset) return { reset: [...next] }; + return { prepend: next.slice(0, start), append: next.slice(end + 1) }; +} + +/** `held` with `update` applied. */ +export function applyUpdate( + held: AgentKindViewInputs | undefined, + update: AgentKindViewUpdate, +): AgentKindViewInputs { + const { events: change, ...fields } = update; + const events = !change + ? held?.events || [] + : "reset" in change + ? change.reset + : [...change.prepend, ...(held?.events || []), ...change.append]; + return { ...(held as AgentKindViewInputs), ...fields, events }; +}
A src/agent-kind-view/call-presence.ts
@@ -0,0 +1,21 @@ +// call-presence.ts — WHO IS IN AN AGENT'S CALL, for the faces of who is here: the call's live +// state (lib/call-rules.ts `CallLive`) read by actor. The Dash's agent page loads it with the +// call's other parts (./dash-call.tsx), only where calls are on. +import type { InCall } from "#/components/agent-chat/presence-line.tsx"; +import { CallLive } from "#/lib/call-rules.ts"; + +/** Who is in the call, by actor, and whether they send a camera or a screen from any of their + * pages; undefined while the call's live state is not there. */ +export function inCallOf(liveValue: unknown): InCall | undefined { + const live = CallLive.safeParse(liveValue); + if (!live.success) return undefined; + const people = new Map<string, { camera: boolean; screen: boolean }>(); + for (const { who, tracks } of Object.values(live.data.inCall)) { + const held = people.get(who.actor); + people.set(who.actor, { + camera: Boolean(held?.camera) || "camera" in tracks, + screen: Boolean(held?.screen) || "screen" in tracks, + }); + } + return people; +}
A src/agent-kind-view/dash-agent-calls.test.ts
@@ -0,0 +1,112 @@ +// The Dash's calls let go of every handle they open, a refusal included, and check the events +// that come from outside the page's code before they are appended. +import { expect, test } from "vitest"; +import { + appendEvents, + appendTo, + fileUrl, + messageAgent, + storeAgentFiles, +} from "./dash-agent-calls.ts"; + +test("a malformed event from outside the page is refused before anything is appended", async () => { + const { itx, appended } = mind(); + const context = await itx.cd("/agents/claude/c"); + await expect( + appendEvents(context, [ + { type: "events.example.com/kind/started", payload: {} }, + { payload: {} }, + ]), + ).rejects.toThrow(); + await expect(appendEvents(context, [{ type: "x", payload: "words" }])).rejects.toThrow(); + expect(appended).toEqual([]); +}); + +test("a message lets go of the agent's handle, whether the agent takes it or refuses it", async () => { + const taking = mind(); + await messageAgent(taking.itx, "/agents/a", { message: "Hello" }); + expect(taking).toMatchObject({ handles: { opened: 1, disposed: 1 } }); + + const refusing = mind({ refuseMessage: true }); + await expect(messageAgent(refusing.itx, "/agents/a", { message: "Hello" })).rejects.toThrow( + "NOT_CREATED", + ); + expect(refusing).toMatchObject({ handles: { opened: 1, disposed: 1 } }); +}); + +test("a file's URL is asked of the mind, which has `files`, and its handle is let go, a refusal included", async () => { + // the agent's own context has no `files`, as a Claude Code agent's has none + const signing = mind(); + expect(await fileUrl(signing.itx, "/agents/claude/c/photo.png")).toBe( + "https://files.example.com/agents/claude/c/photo.png", + ); + expect(signing).toMatchObject({ handles: { opened: 1, disposed: 1 } }); + + const refusing = mind({ refuseFile: true }); + await expect(fileUrl(refusing.itx, "/agents/claude/c/photo.png")).rejects.toThrow("NOT_FOUND"); + expect(refusing).toMatchObject({ handles: { opened: 1, disposed: 1 } }); +}); + +test("a message's files are stored under the agent's path as message() stores them: a key gives the same path again", async () => { + const { itx, handles, puts } = mind(); + const file = { contentType: "image/png", filename: "my photo.png", data: "AAAA" }; + const keyed = await storeAgentFiles(itx, "/agents/a", [file], "page:1"); + const again = await storeAgentFiles(itx, "/agents/a", [file], "page:1"); + await storeAgentFiles(itx, "/agents/a", [file]); + expect(again).toEqual(keyed); + expect(keyed).toMatchObject([{ contentType: "image/png", filename: "my photo.png", size: 4 }]); + // a stem of 16 hex characters from the key, the place, the type and the content; else 8 random + expect(puts.map((put) => put.path)).toMatchObject([ + expect.stringMatching(/^\/agents\/a\/[0-9a-f]{16}-my-photo\.png$/), + keyed[0]!.path, + expect.stringMatching(/^\/agents\/a\/[0-9a-f-]{8}-my-photo\.png$/), + ]); + expect(handles).toEqual({ opened: 3, disposed: 3 }); +}); + +test("an append to a path lets go of the context's handle", async () => { + const { itx, handles, appended } = mind(); + await appendTo(itx, "/agents/a", [{ type: "events.example.com/x", payload: {} }]); + expect({ handles, appended }).toEqual({ + handles: { opened: 1, disposed: 1 }, + appended: [{ type: "events.example.com/x", payload: {} }], + }); +}); + +/** A mind that counts the handles it gives out and the ones let go, and keeps what is appended. + * Its root has `files`; a context that `cd` answers has none. */ +function mind({ refuseMessage = false, refuseFile = false } = {}) { + const handles = { opened: 0, disposed: 0 }; + const appended: unknown[] = []; + const puts: { path: string; contentType?: string }[] = []; + const handle = <T extends object>(stub: T) => { + handles.opened++; + return { ...stub, [Symbol.dispose]: () => void handles.disposed++ }; + }; + const itx = { + cd: async () => + handle({ append: async (...events: unknown[]) => void appended.push(...events) }), + agents: { + get: () => + handle({ + message: async () => { + if (refuseMessage) throw new Error("NOT_CREATED"); + }, + }), + }, + files: { + get: (path: string) => + handle({ + url: async () => { + if (refuseFile) throw new Error("NOT_FOUND"); + return { url: `https://files.example.com${path}` }; + }, + put: async ({ contentType, data }: { contentType?: string; data: string }) => { + puts.push({ path, contentType }); + return { path, contentType, size: data.length }; + }, + }), + }, + } as unknown as Parameters<typeof messageAgent>[0]; + return { itx, handles, appended, puts }; +}
A src/agent-kind-view/dash-agent-calls.ts
@@ -0,0 +1,178 @@ +// The Dash's calls that open a handle on the mind: a message to an agent, and the events a view +// appends. Each lets go of the handle it opens on every path, a refusal included: +// in capnweb the caller disposes every stub it gets, and a stub it never disposes stays held on +// the other side until the socket closes. +import { z } from "zod"; +import type { AuthenticatedApp } from "iterate/app"; +import type { OutgoingFile, StoredFile } from "#/components/agent-chat/agent-facts.ts"; +import { + widgetMcpHost, + type WidgetMcpCalls, + type WidgetMcpConnection, +} from "#/components/widget/widget-mcp.ts"; + +type Itx = AuthenticatedApp["itx"]; + +/** The member's itx with `itx.agents`, which the mind's agents app adds by a rewrite rule: the + * two calls these pages make (iterate/agents api.ts has the whole root). `get` answers a handle, + * a stub of its own. */ +type AgentsRoot = { + agents: { + create(path: string): Promise<unknown>; + get(path: string): { + message( + input: { message: string; files?: unknown }, + options?: { key: string }, + ): Promise<unknown>; + [Symbol.dispose](): void; + }; + }; +}; + +/** `itx` with the `agents` root. The cast is safe to make and cannot be a check: `Itx` names only + * the platform's own roots, and `agents` is a root a rewrite rule adds at run time, which no type + * can see. On a mind without it, the call is refused over RPC and the refusal reaches the caller. */ +export const withAgents = (itx: Itx) => itx as Itx & AgentsRoot; + +/** The events a view asks to append, as far as this page checks them: each has a type, + * and a payload that is an object. Every other key goes on as it is: the platform parses each + * event as it commits. */ +const AppendedEvents = z.array( + z.looseObject({ + type: z.string(), + payload: z.record(z.string(), z.unknown()).optional(), + }), +); + +/** Appends events that came from outside this page's code (a kind's frame, the chat's raw + * composer) to `context`, after the check above: a malformed one is refused here, with nothing + * appended. */ +export async function appendEvents( + context: Awaited<ReturnType<Itx["cd"]>>, + events: unknown[], +): Promise<void> { + await context.append(...AppendedEvents.parse(events)); +} + +/** Appends `events` to the context at `path` (after the check above), then lets go of its handle, + * whatever the answer. */ +export async function appendTo(itx: Itx, path: string, events: unknown[]): Promise<void> { + const context = await itx.cd(path); + try { + await appendEvents(context, events); + } finally { + context[Symbol.dispose](); + } +} + +/** Says `input` to the agent at `path` (`itx.agents.get(path).message`), then lets go of the + * agent's handle, whatever the answer. With `key`, the message's own key from the chat, the + * same message sent again lands once (a mind whose platform does not know keys yet ignores it). */ +export async function messageAgent( + itx: Itx, + path: string, + input: { message: string; files?: unknown }, + key?: string, +): Promise<void> { + const agent = withAgents(itx).agents.get(path); + try { + await (key ? agent.message(input, { key }) : agent.message(input)); + } finally { + agent[Symbol.dispose](); + } +} + +/** A SIGNED DOWNLOAD URL FOR A FILE, ASKED OF THE MIND (`itx.files.get(path).url()`), never of an + * agent's context. Only an agent of the mind's own kind links its context to the root, where + * `files` is. The context of a Claude Code, Codex, ACP or Herdr agent has its own names alone, so + * `itx.cd(path).files` matches no rule there, and no attachment of its chat would show. Lets go + * of the file's handle, whatever the answer. */ +export async function fileUrl(itx: Itx, filePath: string): Promise<string> { + const file = itx.files.get(filePath); + try { + return (await file.url()).url; + } finally { + file[Symbol.dispose](); + } +} + +/** STORES A MESSAGE'S FILES under the agent's path, as the platform's `message()` stores them + * (core/lib agents/message.ts `appendMessage`): `<path>/<stem>-<name>`, where the stem, for a + * message with a key, is made from the key, the file's place, its type and the SHA-256 of its + * content, so the same file sent again goes to the same path; with no key, 8 characters of a + * random id. Answers each file as the store holds it. Lets go of each file's handle. */ +export async function storeAgentFiles( + itx: Itx, + path: string, + files: readonly OutgoingFile[], + key?: string, +): Promise<StoredFile[]> { + const stored: StoredFile[] = []; + for (const [index, file] of files.entries()) { + const filename = file.filename.replace(/[^A-Za-z0-9._-]+/g, "-"); + const stem = key + ? ( + await sha256Hex( + `${key}\n${String(index)}\n${file.contentType}\n${await sha256Hex(file.data)}`, + ) + ).slice(0, 16) + : crypto.randomUUID().slice(0, 8); + const handle = itx.files.get(`${path}/${stem}-${filename}`); + try { + const record = await handle.put({ contentType: file.contentType, data: file.data }); + stored.push({ + contentType: record.contentType, + filename: file.filename, + path: record.path, + size: record.size, + }); + } finally { + handle[Symbol.dispose](); + } + } + return stored; +} + +/** The SHA-256 of a text, in hex. */ +async function sha256Hex(text: string): Promise<string> { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)); + return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); +} + +/** One host of MCP App calls for each agent the page has shown, kept while the page lives: its + * connections stay open for the next call (widget-mcp.ts). */ +const widgetHosts = new WeakMap<Itx, Map<string, WidgetMcpCalls>>(); + +/** THE CALLS OF THE MCP APPS IN AN AGENT'S FEED, made as that agent: `itx.cd(path)` holds the + * connection, so a widget reaches what the agent at `path` reaches. Its context and its + * connections are held from an app's first call while the page lives, one connection for each + * server and headers. */ +export function widgetCallsOf(itx: Itx, path: string): WidgetMcpCalls { + let byPath = widgetHosts.get(itx); + if (!byPath) widgetHosts.set(itx, (byPath = new Map())); + let host = byPath.get(path); + if (!host) { + // opened at an app's first call, not when the chat draws: most feeds have no app + let opened: Promise<Awaited<ReturnType<Itx["cd"]>>> | undefined; + const context = () => { + opened ||= Promise.resolve(itx.cd(path)); + // a context that did not open is opened again by the next call + opened.catch(() => (opened = undefined)); + return opened; + }; + host = widgetMcpHost({ + path, + // The connection's type is the platform's `McpConnectionApi`; a mind whose platform predates + // `callToolResult` and `readResource` refuses those calls over RPC, and the refusal reaches + // the widget as its call's error. So the structural type is safe to assume and cannot be + // checked here. + open: async (server, headers) => + (await ( + await context() + ).connectToMcp(server, { headers })) as unknown as WidgetMcpConnection, + append: async (events) => await appendEvents(await context(), events), + }); + byPath.set(path, host); + } + return host; +}
A src/agent-kind-view/dash-agents.test.tsx
@@ -0,0 +1,3669 @@ +// @vitest-environment jsdom +// The Dash's agent pages: the home says what waits for the member in a place of its own (nothing, +// or the requests and the integrations that ask for them), New agent is a composer alone, and the +// agent view draws any path under one header row (the path, the stack of who is here and can use +// the conversation where presence is on, and Chat | Events), with the agent's +// status at the feed's foot, and says the opener once into an empty chat. Where the Agents page +// turns calls on, the header has the call's controls and the faces say who is in the call. +import { act, Suspense, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, test, vi } from "vitest"; +import { BotIcon } from "lucide-react"; +import { newMessagePortRpcSession, RpcTarget } from "capnweb"; +import { codedError } from "iterate/lib"; +import { + AGENT_KIND_VIEW_READY, + type AgentKindNewAgentSummary, + type AgentKindViewHostApi, +} from "./bridge.ts"; +import { DashAgents, DashHome } from "./dash-agents.tsx"; +import { AgentCall } from "./dash-call.tsx"; +import { AppShell } from "#/components/app-shell.tsx"; +import type { DashPage, DashPageProps } from "#/components/dash/dash.tsx"; +import { agentRowsOf } from "#/lib/agent-summary.ts"; +import { createCall, useCall, type CallContext } from "#/lib/call-engine.ts"; +import { CallLive, viewOf } from "#/lib/call-rules.ts"; +import { savedLogTails } from "#/lib/saved-log-tail.ts"; + +// jsdom lays nothing out; the composer's CodeMirror measures text ranges after each change +Object.assign(Range.prototype, { + getClientRects: () => [], + getBoundingClientRect: () => new DOMRect(), +}); + +const now = new Date().toISOString(); +const agents = agentRowsOf({ + agents: { + "/agents/onboarding": { createdAt: now, kind: "iterate", title: "Set up the mind" }, + }, +}); + +test("the home with nothing waiting: the composer, the words that say so, and the recent agents", async () => { + const { itx } = mind({}); + await using page = await draw(DashHome, itx, { waiting: 0 }); + await composerOf(page.host); + const waiting = page.host.querySelector('section[aria-labelledby="needs-you"]'); + expect(waiting?.textContent).toBe("Waiting for youNothing waits for you."); + expect( + page.host.querySelector('[data-agent-path="/agents/onboarding"]')?.getAttribute("href"), + ).toBe("/agents/agents/onboarding"); +}); + +test("the home before the count of what waits is known says nothing false, in the same room", async () => { + const { itx } = mind({}); + await using page = await draw(DashHome, itx, { waiting: undefined }); + const waiting = page.host.querySelector('section[aria-labelledby="needs-you"]'); + expect(waiting?.textContent).toBe("Waiting for youLooking…"); + // one row's room, kept while it is read: the list under it does not move for the answer + expect([...waiting!.classList]).toContain("min-h-22"); +}); + +test("the home with something waiting: the requests, and each integration that asks", async () => { + const { itx } = mind({ + serves: ["itx.integrations"], + integrations: { + integrations: { + slack: { title: "Slack", status: { kind: "attention", text: "Connect a workspace" } }, + github: { title: "GitHub", status: { kind: "ok" } }, + }, + connections: { + "github/acme": { account: "acme", status: { kind: "error", text: "The app was removed" } }, + }, + }, + }); + await using page = await draw(DashHome, itx, { waiting: 2 }); + const rows = [...page.host.querySelectorAll('section[aria-labelledby="needs-you"] li a')].map( + (row) => [row.textContent, row.getAttribute("href")], + ); + expect(rows).toEqual([ + [ + "2 requests wait for your yesYour agents wait until you answer.", + "https://iterate.example.com/secrets/approvals", + ], + ["SlackConnect a workspace", "/integrations"], + ["GitHub: acmeThe app was removed", "/integrations"], + ]); +}); + +test("the home's box holds the draft that the address brought, unsent", async () => { + const { itx, born } = mind({}); + history.replaceState( + null, + "", + `/#draft=${encodeURIComponent("Read tasks/a.md and tell me what is being decided.")}`, + ); + await using page = await draw(DashHome, itx, { waiting: 0 }); + await composerOf(page.host); + await act(() => + vi.waitFor(() => + expect(page.host.textContent).toContain("Read tasks/a.md and tell me what is being decided."), + ), + ); + // nothing was sent: no agent was born for it + expect(born).toEqual([]); + history.replaceState(null, "", "/"); +}); + +test.for([ + { name: "the Dash knows who is signed in", known: true }, + { + name: "the Dash does not know yet who is signed in, and the mind is asked first", + known: false, + }, +])( + "a first message on the home, when $name, starts the agent in that person's folder", + async ({ known }) => { + const { itx, born, asked } = mind({}); + history.replaceState(null, "", "/"); + await using page = await draw(DashHome, itx, { waiting: 0, account: known }); + const composer = await composerOf(page.host); + // the words, as a paste puts them in the editor (jsdom has no DataTransfer) + const paste = new Event("paste", { bubbles: true, cancelable: true }); + Object.defineProperty(paste, "clipboardData", { + value: { + files: [], + items: [{ kind: "string", type: "text/plain", getAsFile: () => null }], + getData: (format: string) => (format === "text/plain" ? "hello" : ""), + }, + }); + await act(async () => composer!.dispatchEvent(paste)); + const send = page.host.querySelector<HTMLButtonElement>('button[title="Send message"]'); + await act(async () => send!.click()); + await act(() => vi.waitFor(() => expect(born).toHaveLength(1))); + expect(born[0]).toMatch(/^\/agents\/people\/jo\/web\//); + expect(asked()).toBe(known ? 0 : 1); + }, +); + +test("the agent view takes any path, has no button to its raw view, and says the opener once into an empty chat", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const { itx, appended } = mind({}); + history.replaceState(null, "", "/agents/agents/onboarding"); + await using page = await draw(DashAgents, itx, { + waiting: 0, + openers: { "/agents/onboarding": "Begin with step 1." }, + }); + expect(page.host.textContent).toContain("/agents/onboarding"); + expect(page.host.textContent).not.toContain("Raw view"); + // the opener goes once the whole log is read, which may end after the page drew: the wait is + // outside act, which would hold the render that appends it until the wait ends + await vi.waitFor( + () => + expect(appended).toEqual([ + { + path: "/agents/onboarding", + events: [ + { + type: "events.iterate.com/agent/context-added", + idempotencyKey: "opener:/agents/onboarding", + payload: { role: "developer", content: "Begin with step 1." }, + }, + ], + }, + ]), + { timeout: 5_000 }, + ); + // a path that is no agent's draws as well, and an opener for another path says nothing + history.replaceState(null, "", "/agents/secrets/slack"); + await using other = await draw(DashAgents, itx, { waiting: 0, openers: {} }); + expect(other.host.textContent).toContain("/secrets/slack"); + expect(appended).toHaveLength(1); +}); + +test("an agent page's header shows the stack of who is here, which opens who can use the conversation, only where the mind's config turned presence on", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + history.replaceState(null, "", "/agents/agents/onboarding"); + { + // the default: no typing status, nothing sent, and the header's stack is the mind's face + // alone, named by its hostname, with iterate's mark: no button, no viewer + const { itx, sent, appended } = mind({}); + await using page = await draw(DashAgents, itx, { waiting: 0 }); + expect({ sent, appended }).toEqual({ sent: [], appended: [] }); + expect(page.host.querySelector("[data-slot=agent-presence]")?.outerHTML).toBeUndefined(); + const place = page.host.querySelector("[data-page-header] [data-slot=agent-header-aside]"); + expect([ + [...(place?.querySelectorAll("[data-slot=avatar]") || [])].map((face) => + face.getAttribute("aria-label"), + ), + place?.querySelector("[data-mind-face] img")?.getAttribute("src"), + place?.querySelectorAll("button").length, + ]).toEqual([["iterate.example.com"], expect.stringMatching(/^data:image\/svg/), 0]); + } + { + // alone: the typing status over the composer holds no words, and the header's place holds + // the button with the mind's face (its own logo and name) and one plain circle, as the page + // does not know its own row yet + const { itx, sent, appended } = mind({}); + await using page = await draw(DashAgents, itx, { + waiting: 0, + presence: true, + mindFace: { name: "Acme", logo: <img src="/acme.svg" alt="" /> }, + }); + expect({ sent, appended }).toEqual({ sent: [], appended: [] }); + expect(page.host.querySelector("[data-slot=agent-presence]")?.textContent).toBe(""); + const access = await vi.waitFor(() => { + const button = page.host.querySelector( + "[data-page-header] [data-slot=agent-header-aside] button[data-conversation-access]", + ); + if (!button) throw new Error("the header has no button yet"); + return button; + }); + expect([ + access.getAttribute("aria-label"), + access.getAttribute("data-here"), + [...access.querySelectorAll("[data-slot=avatar]")].map((face) => + face.hasAttribute("data-viewer-unknown") ? "viewer" : face.getAttribute("aria-label"), + ), + access.querySelector("[data-mind-face] img")?.getAttribute("src"), + ]).toEqual(["Who can use this conversation", "0", ["Acme", "viewer"], "/acme.svg"]); + } + // another member's page open on this agent's context: a face in the header's stack, none over + // the composer. The SDK does not say this page's own row yet, so the page says no status of its + // own. + const { itx, sent, appended } = mind({ + pages: { + "/agents/onboarding": [ + { name: "b-page", principal: { actor: "/members/b", email: "b@example.com" } }, + ], + }, + }); + await using page = await draw(DashAgents, itx, { waiting: 0, presence: true }); + const access = () => + page.host.querySelector("[data-slot=agent-header-aside] button[data-conversation-access]"); + await vi.waitFor(() => + expect(access()?.getAttribute("aria-label")).toBe( + "Who can use this conversation. Here now: b@example.com.", + ), + ); + expect([ + [...(access()?.querySelectorAll("[data-slot=avatar]") || [])].map((face) => face.textContent), + page.host.querySelector("[data-slot=agent-presence] [data-slot=avatar]")?.outerHTML, + ]).toEqual([["", "B", ""], undefined]); + expect(access()?.querySelector("[data-slot=avatar]")?.hasAttribute("data-mind-face")).toBe(true); + expect({ sent, appended }).toEqual({ sent: [], appended: [] }); +}); + +test("an agent page lends the agent tools only where the mind's config turned `pageTools` on, under the member's name", async () => { + history.replaceState(null, "", "/agents/agents/onboarding"); + { + // the default: nothing is lent + const { itx, lent } = mind({}); + await using _page = await draw(DashAgents, itx, { waiting: 0 }); + expect(lent).toEqual([]); + } + const { itx, lent } = mind({}); + await using _page = await draw(DashAgents, itx, { waiting: 0, pageTools: true }); + expect(lent).toEqual([ + { path: "/agents/onboarding", match: expect.stringMatching(/^itx\.page\.jo\.[a-z2-7]{12}$/) }, + ]); +}); + +test("the header's count of held events leaves out a page's presence status", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + history.replaceState(null, "", "/agents/agents/onboarding"); + const { itx } = mind({ + logs: { + "/agents/onboarding": [ + { + offset: 1, + type: "events.iterate.com/agent/context-added", + payload: { role: "user", content: "hello", actor: { type: "user" } }, + }, + { + offset: 2, + type: "presence/status", + payload: { subscription: "b-page", away: false, typing: false }, + source: { origin: "/", principal: { actor: "/members/b", email: "b@example.com" } }, + }, + ], + }, + }); + await using page = await draw(DashAgents, itx, { waiting: 0, presence: true }); + const events = [...page.host.querySelectorAll("[data-page-header] [role=tab]")].find((tab) => + tab.textContent?.startsWith("Events"), + ); + expect(events?.textContent).toBe("Events1"); +}); + +test.for<{ name: string; path: string; kind: string }>([ + { name: "an iterate agent", path: "/agents/onboarding", kind: "iterate" }, + { name: "an agent of a kind with its own view", path: "/agents/session", kind: "claude" }, +])( + "$name: one header row holds the path and Chat | Events, no strip stands over the feed, and Events in the header is the Events tab", + async ({ path, kind }) => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const { itx } = mind({ kinds: { claude: "agent-kinds/claude.ts" } }); + history.replaceState(null, "", `/agents${path}`); + await using page = await draw(DashAgents, itx, { + waiting: 0, + agents: agentRowsOf({ agents: { [path]: { createdAt: now, kind } } }), + }); + const header = page.host.querySelector("[data-page-header]"); + expect(header?.textContent).toContain(path); + // the page's only tabs are the header's: the view under it draws no strip + const tabs = [...page.host.querySelectorAll("[role=tablist]")]; + expect(tabs.map((list) => header?.contains(list))).toEqual([true]); + expect(tabs[0]?.closest("[inert]")).toBe(null); + if (kind === "iterate") + // the agent's status is a line at the feed's foot, over the composer (this mind has no live + // state to read) + expect(page.host.querySelector("[data-slot=agent-foot-status]")?.textContent).toBe( + "Live state unavailable", + ); + const events = [...tabs[0]!.querySelectorAll("[role=tab]")].find((tab) => + tab.textContent?.startsWith("Events"), + ); + await act(async () => (events as HTMLElement).click()); + await page.settle(); + expect(new URLSearchParams(location.search).get("view")).toBe('{"view":"events"}'); + // an iterate agent's Events tab is drawn in this page; a kind's, in its frame, which the page + // tells (frame-view.test.tsx draws it) + if (kind === "iterate") + expect(page.host.textContent).toContain("Nothing has happened on this agent yet."); + }, +); + +test("the agent page while its view is not there: the header's tabs, which cannot be pressed, and one loading line", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const { itx } = mind({}); + history.replaceState(null, "", "/agents/agents/onboarding"); + await using page = await draw(DashAgents, itx, { waiting: 0, agents: "unread" }); + const tabs = [...page.host.querySelectorAll("[role=tablist]")]; + expect(tabs).toHaveLength(1); + expect(tabs[0]?.closest("[data-page-header] [inert]")).not.toBe(null); + expect(page.host.querySelectorAll("[data-slot=log-reading]")).toHaveLength(1); +}); + +test("a chat draws a message's image for an agent whose context has no `files`: the mind signs its URL", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _layout = laidOut(); + const path = "/agents/claude/c"; + const file = { contentType: "image/png", filename: "photo.png", path: `${path}/photo.png` }; + const { itx } = mind({ + logs: { + [path]: [ + { + offset: 1, + type: "events.iterate.com/agent/context-added", + payload: { role: "user", content: "A photo", files: [{ ...file, size: 3 }] }, + }, + ], + }, + }); + history.replaceState(null, "", `/agents${path}`); + await using page = await draw(DashAgents, itx, { waiting: 0 }); + await act(() => + vi.waitFor(() => + expect(page.host.querySelector('img[alt="photo.png"]')?.getAttribute("src")).toBe( + `https://files.example.com${file.path}`, + ), + ), + ); +}); + +test("a message's image is signed once, however often the page draws the chat again", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _layout = laidOut(); + const path = "/agents/talk"; + const file = { contentType: "image/png", filename: "photo.png", path: `${path}/photo.png` }; + const { itx, signed } = mind({ + logs: { + [path]: [ + { + offset: 1, + type: "events.iterate.com/agent/context-added", + payload: { role: "user", content: "A photo", files: [{ ...file, size: 3 }] }, + }, + ], + }, + }); + history.replaceState(null, "", `/agents${path}`); + await using page = await draw(DashAgents, itx, { waiting: 0 }); + await act(() => + vi.waitFor(() => expect(page.host.querySelector('img[alt="photo.png"]')).not.toBe(null)), + ); + await page.draw(agents); + await page.draw(agents); + expect(signed).toEqual([file.path]); +}); + +test("a message the signed-in member sent has no line under it that says who sent it; another member's has their short name", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _layout = laidOut(); + const path = "/agents/talk"; + const said = (offset: number, content: string, principal: { actor: string; email: string }) => ({ + offset, + type: "events.iterate.com/agent/context-added", + payload: { role: "user", actor: { type: "user" }, content }, + source: { principal }, + }); + const { itx } = mind({ + logs: { + [path]: [ + said(1, "mine", { actor: "/members/a", email: "jo@example.com" }), + said(2, "theirs", { actor: "/members/b", email: "bo@example.com" }), + ], + }, + }); + history.replaceState(null, "", `/agents${path}`); + await using page = await draw(DashAgents, itx, { waiting: 0 }); + const lines = () => + [...page.host.querySelectorAll("[data-kind=user]")].map( + (bubble) => bubble.querySelector("[data-said-by]")?.textContent ?? null, + ); + await act(() => vi.waitFor(() => expect(lines()).toEqual([null, "bo"]))); +}); + +test("an agent of another kind, before the catalog says its kind: no chat of iterate's, and never its words for an empty chat", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const { itx } = mind({ kinds: { claude: "agent-kinds/claude.ts" } }); + history.replaceState(null, "", "/agents/agents/session"); + await using page = await draw(DashAgents, itx, { waiting: 0, agents: "unread" }); + // the header is there, and one loading state: no view is chosen yet + expect(page.host.textContent).toContain("/agents/session"); + expect(page.host.querySelectorAll("[data-slot=log-reading]")).toHaveLength(1); + expect(page.host.querySelector("[role=log]")).toBe(null); + expect(page.host.querySelector("iframe")).toBe(null); + // the catalog answers: the kind's own view, in its frame, under the same loading state until + // the frame has drawn a log that answered + await page.draw( + agentRowsOf({ agents: { "/agents/session": { createdAt: now, kind: "claude" } } }), + ); + expect(page.host.querySelector("iframe")).not.toBe(null); + expect(page.host.querySelectorAll("[data-slot=log-reading]")).toHaveLength(1); + expect(page.host.querySelector("[role=log]")).toBe(null); + expect(page.said.filter((text) => text.includes("Nothing said"))).toEqual([]); +}); + +test("a kind's file that cannot be read is read once: its agent's view draws, and no later render reads again", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const { itx, reads } = mind({ kinds: { claude: "agent-kinds/claude.ts" }, unreadable: true }); + history.replaceState(null, "", "/agents/agents/session"); + const rows = () => + agentRowsOf({ agents: { "/agents/session": { createdAt: now, kind: "claude" } } }); + await using page = await draw(DashAgents, itx, { waiting: 0, agents: rows() }); + // drawn again, as each change of a live catalog draws it + for (let again = 0; again < 3; again += 1) await page.draw(rows()); + expect(reads()).toBe(1); + expect(page.host.textContent).toContain("/agents/session"); + expect(page.host.textContent).not.toContain("Loading the page…"); +}); + +test("an iterate agent, before the catalog says its kind, waits under the same loading state, then is iterate's chat", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const { itx } = mind({}); + history.replaceState(null, "", "/agents/agents/onboarding"); + await using page = await draw(DashAgents, itx, { waiting: 0, agents: "unread" }); + expect(page.host.querySelectorAll("[data-slot=log-reading]")).toHaveLength(1); + expect(page.host.querySelector("[role=log]")).toBe(null); + await page.draw(agents); + // the log of this mind is empty and has answered: now, and only now, the chat says so + expect(page.host.querySelector("[role=log]")?.textContent).toContain("Nothing said yet"); + expect(page.host.querySelector("[data-slot=log-reading]")).toBe(null); +}); + +test("the Agents page of a mind with folders and no agent says so, and counts none", async () => { + const { itx } = mind({}); + history.replaceState(null, "", "/agents"); + const folders = agentRowsOf({ + agents: { + "/agents/people": { createdAt: now }, + "/agents/people/jo": { createdAt: now }, + }, + }); + await using page = await draw(DashAgents, itx, { waiting: 0, agents: folders }); + expect(page.host.textContent).toContain("0 agents"); + expect(page.host.textContent).toContain("No agents yet."); + expect(page.host.querySelector('[aria-label="Every agent"]')).toBe(null); +}); + +test("New agent is the composer alone, on the home and the Agents page, whatever kinds the mind has", async () => { + const { itx } = mind({ kinds: { claude: "agent-kinds/claude.ts" } }); + for (const [Page, url] of [ + [DashHome, "/"], + [DashAgents, "/agents"], + ] as const) { + history.replaceState(null, "", url); + await using page = await draw(Page, itx, { waiting: 0 }); + await composerOf(page.host); + // no choice of kind, and no kind's frame loaded for one + expect(page.host.querySelector("select")).toBe(null); + expect(page.host.querySelector("iframe")).toBe(null); + } +}); + +test("a mind whose kind says `default: true`: New agent starts that kind by its own facts, with no agent made and no message()", async () => { + const { itx, born, appended } = mind({ + kinds: { agent: "agent-kinds/agent.ts", claude: "agent-kinds/claude.ts" }, + source: "export default { newAgent: { default: true } };", + }); + history.replaceState(null, "", "/"); + await using page = await draw(DashHome, itx, { waiting: 0 }); + const composer = await composerOf(page.host); + // the kind file runs in a hidden frame of its own, never in the page + const frames = await act(() => + vi.waitFor(() => { + const found = [...page.host.querySelectorAll("iframe")]; + expect( + found.map((frame) => [frame.title, frame.hidden, frame.getAttribute("sandbox")]), + ).toEqual([ + ["agent-kinds/agent.ts", true, "allow-scripts"], + ["agent-kinds/claude.ts", true, "allow-scripts"], + ]); + return found; + }), + ); + // the frame of agent-kinds/agent.ts says its kind is the default; it starts with one fact + const started: unknown[] = []; + await act(() => + starterFrame(frames[0]!, { + newAgent: { default: true, choices: [{ id: "agent", label: "Agent", byPerson: true }] }, + start: (input) => { + started.push(input); + return [{ type: "events.iterate.com/agent-ui/agent-requested", payload: {} }]; + }, + }), + ); + await act(() => starterFrame(frames[1]!, { newAgent: undefined, start: () => [] })); + await pasteAndSend(page.host, composer!, "hello"); + await act(() => vi.waitFor(() => expect(appended).toHaveLength(2))); + const path = appended[0]!.path; + expect(path).toMatch(/^\/agents\/people\/jo\/agent\//); + expect({ born, started, appended }).toMatchObject({ + born: [], + started: [{ choice: "agent", fields: {}, path }], + appended: [ + { path, events: [{ type: "events.iterate.com/agent-ui/agent-requested" }] }, + { + path, + events: [ + { + type: "events.iterate.com/agent-ui/message-received", + payload: { message: "hello", client: "web" }, + }, + ], + }, + ], + }); +}); + +test("a mind whose kinds say no default: New agent makes an iterate agent, as it did", async () => { + const { itx, born, appended } = mind({ kinds: { claude: "agent-kinds/claude.ts" } }); + history.replaceState(null, "", "/"); + await using page = await draw(DashHome, itx, { waiting: 0 }); + const composer = await composerOf(page.host); + await pasteAndSend(page.host, composer!, "hello"); + await act(() => vi.waitFor(() => expect(born).toHaveLength(1))); + expect(born[0]).toMatch(/^\/agents\/people\/jo\/web\//); + expect(appended).toEqual([]); + expect(page.host.querySelector("iframe")).toBe(null); +}); + +test("an iterate agent's view drawn a second time shows the saved rows while the mind has not answered", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _layout = laidOut(); + const path = "/agents/saved"; + const { itx, hold } = mind({ + logs: { + [path]: [ + { + offset: 1, + type: "events.iterate.com/agent/context-added", + payload: { role: "user", content: "Words from the last visit" }, + }, + ], + }, + }); + history.replaceState(null, "", `/agents${path}`); + { + await using first = await draw(DashAgents, itx, { waiting: 0 }); + expect(first.host.querySelector("[role=log]")?.textContent).toContain( + "Words from the last visit", + ); + } + hold(); + await using again = await draw(DashAgents, itx, { waiting: 0 }); + expect(again.host.querySelector("[role=log]")?.textContent).toContain( + "Words from the last visit", + ); + expect(again.said.filter((text) => text.includes("Nothing said"))).toEqual([]); + // and at no moment of the second draw did the page say that it reads the log: not before the + // view was there (the kinds and the catalog were read behind a quiet page), not after + expect(again.said.filter((text) => text.includes("Reading the log"))).toEqual([]); +}); + +test("the agent page while its view is not there says nothing of a read when saved rows of its log wait, and says it when none do", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _layout = laidOut(); + const path = "/agents/kept"; + const { itx } = mind({ + logs: { + [path]: [ + { + offset: 1, + type: "events.iterate.com/agent/context-added", + payload: { role: "user", content: "Words from the last visit" }, + }, + ], + }, + }); + history.replaceState(null, "", `/agents${path}`); + { + // a first visit reads the log, and the page keeps its rows + await using first = await draw(DashAgents, itx, { waiting: 0 }); + expect(first.host.querySelector("[role=log]")?.textContent).toContain( + "Words from the last visit", + ); + } + { + // again, and the catalog has not said the agent's kind yet: the wait is for the view, and the + // rows are held, so the page does not say that it reads + await using again = await draw(DashAgents, itx, { waiting: 0, agents: "unread" }); + expect(again.host.querySelectorAll("[role=tablist]")).toHaveLength(1); + expect(again.host.querySelectorAll("[data-slot=log-reading]")).toHaveLength(0); + } + // another agent, of whose log nothing is held: the page says that it reads + history.replaceState(null, "", "/agents/agents/never-seen"); + await using other = await draw(DashAgents, itx, { waiting: 0, agents: "unread" }); + expect(other.host.querySelectorAll("[data-slot=log-reading]")).toHaveLength(1); +}); + +test("the opener is not appended while the chat's rows are a saved copy, only when the mind's log says it is empty", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const path = "/agents/opened"; + const { itx, appended, hold, release } = mind({ + logs: { + // nothing said: a system note is context, not a start + [path]: [ + { + offset: 1, + type: "events.iterate.com/agent/context-added", + payload: { role: "system", content: "You are helpful." }, + }, + ], + }, + }); + history.replaceState(null, "", `/agents${path}`); + { + await using _first = await draw(DashAgents, itx, { waiting: 0, openers: {} }); + } + hold(); + await using again = await draw(DashAgents, itx, { + waiting: 0, + openers: { [path]: "Begin with step 1." }, + }); + expect(appended).toEqual([]); + release(); + await act(() => vi.waitFor(() => expect(appended).toHaveLength(1))); + expect(again.host.textContent).toContain(path); +}); + +test("an iterate agent drawn a second time, before the catalog and the kinds answer, is its chat with the saved rows at once", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _layout = laidOut(); + const path = "/agents/remembered"; + const logs = { [path]: [words(1, "Words from the last visit")] }; + history.replaceState(null, "", `/agents${path}`); + { + await using _first = await draw(DashAgents, mind({ logs }).itx, { waiting: 0 }); + } + const second = mind({ logs }); + second.holdKinds(); + second.hold(); + await using again = await draw(DashAgents, second.itx, { waiting: 0, agents: "unread" }); + expect(again.host.querySelector("[role=log]")?.textContent).toContain( + "Words from the last visit", + ); + // no loading state at any moment: the view was there before the mind said anything + expect(again.host.querySelectorAll("[data-slot=log-reading]")).toHaveLength(0); + expect(again.said.filter((text) => text.includes("Reading"))).toEqual([]); + second.release(); + second.releaseKinds(); +}); + +test("an agent of a kind with a file, drawn a second time, has its frame before the kinds answer, and the same file keeps that frame", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const path = "/agents/claude-same"; + await rememberKindView(path, "export default {};"); + const second = mind({ kinds: { claude: "agent-kinds/claude.ts" } }); + second.holdKinds(); + await using again = await draw(DashAgents, second.itx, { waiting: 0, agents: "unread" }); + const frame = again.host.querySelector("iframe"); + expect(frame).not.toBe(null); + second.releaseKinds(); + await again.draw(claudeRows(path)); + // the same element: the frame's document is not loaded again + expect(again.host.querySelector("iframe")).toBe(frame); +}); + +test("when the kinds answer with another source for the remembered file, the frame mounts again and the store keeps the new source", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const path = "/agents/claude-changed"; + await rememberKindView(path, "export default { old: true };"); + const second = mind({ kinds: { claude: "agent-kinds/claude.ts" }, source: "export default {};" }); + second.holdKinds(); + await using again = await draw(DashAgents, second.itx, { waiting: 0, agents: "unread" }); + const frame = again.host.querySelector("iframe"); + expect(frame).not.toBe(null); + second.releaseKinds(); + await again.draw(claudeRows(path)); + const now = again.host.querySelector("iframe"); + expect(now).not.toBe(null); + expect(now).not.toBe(frame); + expect(savedLogTails(member).peek(path)).toMatchObject({ + view: { kind: "claude", file: { name: "agent-kinds/claude.ts", source: "export default {};" } }, + }); +}); + +test("when the catalog says another kind than the remembered one, the view changes to that kind's", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const path = "/agents/claude-now-iterate"; + await rememberKindView(path, "export default {};"); + const { itx } = mind({ kinds: { claude: "agent-kinds/claude.ts" } }); + await using again = await draw(DashAgents, itx, { waiting: 0, agents: "unread" }); + expect(again.host.querySelector("iframe")).not.toBe(null); + await again.draw(agentRowsOf({ agents: { [path]: { createdAt: now, kind: "iterate" } } })); + expect(again.host.querySelector("iframe")).toBe(null); + expect(again.host.querySelector("[role=log]")).not.toBe(null); +}); + +test("another member's remembered view is never drawn: the page waits for the kinds and the catalog as on a first visit", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const path = "/agents/claude-of-a"; + await rememberKindView(path, "export default {};"); + const second = mind({ kinds: { claude: "agent-kinds/claude.ts" } }); + second.holdKinds(); + await using other = await draw(DashAgents, second.itx, { + waiting: 0, + agents: "unread", + actor: "/members/b", + }); + expect(other.host.querySelector("iframe")).toBe(null); + expect(other.host.querySelectorAll("[data-slot=log-reading]")).toHaveLength(1); + second.releaseKinds(); + await other.draw(claudeRows(path)); + expect(other.host.querySelector("iframe")).not.toBe(null); +}); + +test("the opener is not appended from a remembered view over a saved copy, only once the mind's log says it is empty", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const path = "/agents/opened-again"; + const logs = { + [path]: [ + { + offset: 1, + type: "events.iterate.com/agent/context-added", + payload: { role: "system", content: "You are helpful." }, + }, + ], + }; + history.replaceState(null, "", `/agents${path}`); + { + await using _first = await draw(DashAgents, mind({ logs }).itx, { waiting: 0, openers: {} }); + } + const second = mind({ logs }); + second.hold(); + second.holdKinds(); + await using again = await draw(DashAgents, second.itx, { + waiting: 0, + agents: "unread", + openers: { [path]: "Begin with step 1." }, + }); + // the remembered view is drawn, over the saved copy + expect(again.host.querySelector("[role=log]")).not.toBe(null); + expect(second).toMatchObject({ appended: [] }); + second.release(); + await act(() => vi.waitFor(() => expect(second.appended).toHaveLength(1))); + second.releaseKinds(); +}); + +test("a path at a later version: the chat is that version's alone, and the opener is said into it when nothing was said there, whatever the earlier version said", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _layout = laidOut(); + const path = "/agents/second-version"; + const { itx, appended } = mind({ + logs: { [path]: [words(1, "Words of the earlier version"), ...borderOf(path, 2, 2)] }, + versions: { [path]: { version: 2, startedAt: 3 } }, + }); + history.replaceState(null, "", `/agents${path}`); + await using page = await draw(DashAgents, itx, { + waiting: 0, + openers: { [path]: "Begin with step 1." }, + }); + // the chat's part may load after the page drew: the wait is outside act, as the first opener's + await vi.waitFor(() => expect(appended).toHaveLength(1), { timeout: 5_000 }); + expect(appended).toMatchObject([{ path, events: [{ idempotencyKey: `opener:${path}` }] }]); + expect(page.host.textContent).not.toContain("Words of the earlier version"); +}); + +test("a path that takes a new version while its chat is open: the earlier version's words go, and the opener is said into the new one", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _layout = laidOut(); + const path = "/agents/started-over"; + const logs: Record<string, { offset: number; type: string; payload: object }[]> = { + [path]: [words(1, "Words of the earlier version")], + }; + const versions: Record<string, { version: number; startedAt: number }> = {}; + const { itx, appended, push } = mind({ logs, versions }); + history.replaceState(null, "", `/agents${path}`); + await using page = await draw(DashAgents, itx, { + waiting: 0, + openers: { [path]: "Begin with step 1." }, + }); + await act(() => + vi.waitFor(() => + expect(page.host.querySelector("[role=log]")?.textContent).toContain( + "Words of the earlier version", + ), + ), + ); + // something was said: no opener + expect(appended).toEqual([]); + // the new version: the log goes on, and the kernel's last batch reaches each of the page's rows + const border = borderOf(path, 2, 2); + logs[path].push(...border); + versions[path] = { version: 2, startedAt: 3 }; + await act(async () => push(path, border)); + await act(() => vi.waitFor(() => expect(appended).toHaveLength(1))); + expect(appended).toMatchObject([{ path, events: [{ idempotencyKey: `opener:${path}` }] }]); + expect(page.host.textContent).not.toContain("Words of the earlier version"); +}); + +test("with the Agents page's `call` off, an agent page has no call: no place, no button, no tiles, nothing turned on", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + history.replaceState(null, "", "/agents/agents/onboarding"); + const { itx, invoked } = mind({ row: "a-page" }); + await using page = await draw(DashAgents, itx, { waiting: 0, presence: true }); + expect({ + place: page.host.querySelector("[data-slot=agent-header-call]")?.outerHTML, + start: page.host.querySelector("[data-slot=call-go-in]")?.outerHTML, + tiles: page.host.querySelector("[data-slot=agent-call-tiles]")?.outerHTML, + facet: invoked.filter((one) => Array.isArray(one.call)), + }).toEqual({ place: undefined, start: undefined, tiles: undefined, facet: [] }); +}); + +test("with `call` on and `share` off, an agent page has no Share: no place, no button", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + history.replaceState(null, "", "/agents/agents/onboarding"); + const { itx } = mind({ row: "a-page" }); + await using page = await draw(DashAgents, itx, { waiting: 0, call: { enable: async () => {} } }); + await act(() => vi.waitFor(() => goIn(page.host.querySelector("[data-slot=agent-header-call]")))); + expect(page.host.querySelector("[data-slot=agent-header-share]")).toBeNull(); + expect(page.host.querySelector('button[aria-label="Share this agent"]')).toBeNull(); +}); + +test("the header's stack, call and Share are drawn from the first paint, never an empty place, in this order: who is here, Start call, Share, the tabs", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + history.replaceState(null, "", "/agents/agents/onboarding"); + const held = mind({ row: "a-page" }); + held.holdKinds(); + const share = { make: vi.fn(), end: vi.fn() }; + const options = { waiting: 0, presence: true, call: { enable: async () => {} }, share }; + await using page = await draw(DashAgents, held.itx, options); + const header = () => page.host.querySelector("[data-page-header]")!; + /** The header's places at the right, in order, and the buttons each holds. */ + const places = () => + [...header().querySelectorAll("[data-slot^=agent-header-]")].map((place) => [ + place.getAttribute("data-slot"), + buttonsOf(place).filter((one) => one !== "Here: you"), + ]); + // the view is not there yet: the buttons are, and cannot be pressed + expect(page.host.querySelector("[role=log]")).toBe(null); + expect(places()).toEqual([ + ["agent-header-aside", []], + ["agent-header-call", ["Start call"]], + ["agent-header-share", ["Share this agent"]], + ]); + // who is here, before the chat says it: the mind's face and a plain circle for the viewer + expect( + [...header().querySelectorAll("[data-slot=agent-header-aside] [data-slot=avatar]")].map( + (face) => face.getAttribute("aria-label") || "viewer", + ), + ).toEqual(["iterate.example.com", "viewer"]); + expect( + [...header().querySelectorAll("[aria-disabled=true]")].map((one) => + one.getAttribute("aria-label"), + ), + ).toEqual(["Start call", "Share this agent"]); + // out of the call there is no button group: Start call alone + expect(header().querySelector("[data-slot=agent-header-call] [data-slot=button-group]")).toBe( + null, + ); + // the places have no box of their own: nothing is drawn where they are empty + expect( + [...header().querySelectorAll("[data-slot^=agent-header-]")].map((place) => place.className), + ).toEqual(["contents", "contents", "contents"]); + held.releaseKinds(); + await page.settle(); + await act(() => vi.waitFor(() => goIn(header().querySelector("[data-slot=agent-header-call]")))); + await shareOf(page.host); + expect(places().map(([slot]) => slot)).toEqual([ + "agent-header-aside", + "agent-header-call", + "agent-header-share", + ]); + expect(header().querySelector("[data-conversation-access-waiting]")).toBe(null); + expect( + header().querySelector("[data-slot=agent-header-aside] button[data-conversation-access]"), + ).not.toBe(null); +}); + +test("Share: a link made once and shown once, the call's live links with their guests, End, and an invite to the page or the link", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + history.replaceState(null, "", "/agents/agents/onboarding"); + const until = Date.parse("2026-11-21T12:00:00Z"); + const made = { + url: "https://meet.example.com/join/agents/onboarding#the-secret", + until, + link: "l-made", + }; + const { itx } = mind({ + row: "a-page", + facets: { + "/agents/onboarding": { + agent: {}, + call: { + ...callLive({}), + links: [ + { link: "l-old", until, madeBy: "jo", guests: ["Grace"] }, + { link: "l-made", until, madeBy: "jo", guests: [] }, + ], + }, + }, + }, + }); + const enable = vi.fn(async () => {}); + const share = { make: vi.fn(async () => made), end: vi.fn(async () => {}) }; + await using page = await draw(DashAgents, itx, { waiting: 0, call: { enable }, share }); + await act(async () => (await shareOf(page.host)).click()); + const pane = await act(() => + vi.waitFor(() => { + const found = document.querySelector("[data-slot=share-pane]"); + if (!found?.querySelector("[data-slot=share-links]")) throw new Error("no links yet"); + return found; + }), + ); + // the call is on already: Share turns nothing on + expect(enable).not.toHaveBeenCalled(); + expect( + [...pane.querySelectorAll("[data-slot=share-links] li")].map((row) => + row.textContent?.replace(/until .*?(\d guest|No guest)/, "until …$1"), + ), + ).toEqual(["Made by jo, until …1 guest: GraceEnd", "Made by jo, until …No guest yetEnd"]); + const google = () => + new URL(pane.querySelector<HTMLAnchorElement>('a[href^="https://calendar.google.com"]')!.href) + .searchParams; + // before a link: the invite holds the agent's page, for members + expect(google().get("location")).toBe(`${location.origin}/agents/agents/onboarding`); + expect(google().get("text")).toBe("Set up the mind"); + await act(async () => buttonOf(pane, "Make a link").click()); + expect(share.make).toHaveBeenCalledExactlyOnceWith(itx, "/agents/onboarding", 24 * 3_600_000); + expect(pane.querySelector("[data-slot=share-made] code")?.textContent).toBe(made.url); + // the invite may hold the new link, while the call lists it + await act(async () => pane.querySelector<HTMLElement>("[data-slot=checkbox]")!.click()); + expect(google().get("location")).toBe(made.url); + await act(async () => buttonOf(pane.querySelector("[data-slot=share-links] li"), "End").click()); + expect(share.end).toHaveBeenCalledExactlyOnceWith(itx, "/agents/onboarding", "l-old"); +}); + +test("Share on an agent with no call turns the call on once, at its first open", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + history.replaceState(null, "", "/agents/agents/onboarding"); + const { itx } = mind({ row: "a-page", facets: { "/agents/onboarding": { agent: {} } } }); + const enable = vi.fn(async () => {}); + const share = { make: vi.fn(), end: vi.fn() }; + await using page = await draw(DashAgents, itx, { waiting: 0, call: { enable }, share }); + await act(async () => (await shareOf(page.host)).click()); + await act(() => vi.waitFor(() => expect(enable).toHaveBeenCalledTimes(1))); + expect(enable).toHaveBeenCalledWith(itx, "/agents/onboarding"); + await page.settle(); + expect(enable).toHaveBeenCalledTimes(1); +}); + +test("with `call` on and no call on the agent: Start call turns the call on once, then joins with the microphone", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _media = browserMedia(); + history.replaceState(null, "", "/agents/agents/onboarding"); + const { itx, invoked, steps } = mind({ row: "a-page" }); + const enable = vi.fn(async () => void steps.push("enable")); + await using page = await draw(DashAgents, itx, { waiting: 0, call: { enable } }); + const place = page.host.querySelector("[data-page-header] [data-slot=agent-header-call]"); + const mic = await act(() => vi.waitFor(() => goIn(place))); + // one button in the header, and no microphone before the call + expect(buttonsOf(page.host).filter((one) => one === "Start call")).toHaveLength(1); + expect(buttonsOf(page.host)).not.toContain("Microphone"); + // no call facet: its live state is never asked for, so no entry of it fails + expect(invoked.filter((one) => String(one.call).includes("'call'"))).toEqual([]); + await act(async () => mic.click()); + await act(() => vi.waitFor(() => expect(steps.slice(0, 2)).toEqual(["enable", "join"]))); + expect(enable).toHaveBeenCalledExactlyOnceWith(itx, "/agents/onboarding"); + await act(() => vi.waitFor(() => expect(isOn(place, "Microphone")).toBe(true))); +}); + +test("`call=join` on an agent with no call: the lobby opens and turns nothing on, the key leaves the address, and Start the call starts and joins listening", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using media = browserMedia(); + history.replaceState(null, "", "/agents/agents/onboarding?call=join"); + const { itx, steps } = mind({ row: "a-page" }); + const enable = vi.fn(async () => void steps.push("enable")); + await using page = await draw(DashAgents, itx, { waiting: 0, call: { enable } }); + const lobby = await act(() => + vi.waitFor(() => { + const found = document.body.querySelector("[data-slot=call-lobby]"); + if (!found) throw new Error("no lobby"); + return found; + }), + ); + expect(lobby.textContent).toContain("Nobody is in the call yet: you start it."); + expect(new URLSearchParams(location.search).get("call")).toBe(null); + expect(location).toMatchObject({ pathname: "/agents/agents/onboarding" }); + // a link is no press: nothing was turned on, opened or joined + expect(enable).not.toHaveBeenCalled(); + expect(steps).toEqual([]); + expect(capturedNothing(media)).toEqual({ opened: [], tracksSent: [] }); + await pressInLobby({ mic: false, text: "Start the call" }); + await act(() => vi.waitFor(() => expect(steps.slice(0, 2)).toEqual(["enable", "join"]))); + expect(enable).toHaveBeenCalledOnce(); + const place = page.host.querySelector("[data-slot=agent-header-call]"); + await act(() => vi.waitFor(() => expect(isOn(place, "Microphone")).toBe(false))); + expect(capturedNothing(media)).toEqual({ opened: [], tracksSent: [] }); +}); + +test("`call=join` opens the lobby and joins nothing; its microphone and camera hand their tracks to the join, opened once", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using media = browserMedia(); + history.replaceState(null, "", "/agents/agents/onboarding?call=join"); + const { itx, steps } = mind({ + row: "a-page", + pages: { "/agents/onboarding": [{ name: "b-page", principal: memberB }] }, + facets: { "/agents/onboarding": { call: callLive({ "b-page": ["mic"] }) } }, + }); + const enable = vi.fn(async () => {}); + await using page = await draw(DashAgents, itx, { waiting: 0, call: { enable } }); + const lobby = await act(() => + vi.waitFor(() => { + const found = document.body.querySelector("[data-slot=call-lobby]"); + if (!found?.textContent?.includes("In the call now:")) throw new Error("no lobby yet"); + return found; + }), + ); + expect(new URLSearchParams(location.search).get("call")).toBe(null); + // nothing joined and nothing captured until the person's press + expect(steps).not.toContain("join"); + expect(capturedNothing(media)).toEqual({ opened: [], tracksSent: [] }); + await act(async () => buttonOf(lobby, "Turn the microphone on").click()); + await act(async () => buttonOf(lobby, "Turn the camera on").click()); + await act(() => + vi.waitFor(() => expect(lobby.querySelector("video[aria-label]")).not.toBe(null)), + ); + expect(capturedNothing(media)).toMatchObject({ opened: ["audio", "video"] }); + expect(steps).not.toContain("join"); + await pressInLobby(); + const place = page.host.querySelector("[data-slot=agent-header-call]"); + await act(() => vi.waitFor(() => expect(isOn(place, "Microphone")).toBe(true))); + await act(() => vi.waitFor(() => expect(isOn(place, "Camera")).toBe(true))); + expect(enable).not.toHaveBeenCalled(); + // the lobby's tracks are the call's: the browser was not asked again + expect(capturedNothing(media)).toMatchObject({ opened: ["audio", "video"] }); + expect(document.body.querySelector("[data-slot=call-lobby]")).toBe(null); +}); + +test("a microphone the browser refuses: Join call joins listening, says why, and the camera can then go on", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using media = browserMedia(); + history.replaceState(null, "", "/agents/agents/onboarding"); + const { itx, steps } = mind({ + row: "a-page", + pages: { "/agents/onboarding": [{ name: "b-page", principal: memberB }] }, + facets: { "/agents/onboarding": { call: callLive({ "b-page": ["mic"] }) } }, + }); + await using page = await draw(DashAgents, itx, { waiting: 0, call: { enable: async () => {} } }); + const place = page.host.querySelector("[data-slot=agent-header-call]"); + media.refuseNext("NotAllowedError"); + await act(async () => (await vi.waitFor(() => goIn(place))).click()); + await act(() => + vi.waitFor(() => + expect(place?.querySelector("[role=alert]")?.textContent).toContain( + "The browser did not give this page the microphone, so you only listen.", + ), + ), + ); + // the page is in the call, and listens + expect(isOn(place, "Microphone")).toBe(false); + expect(steps).toContain("join"); + await act(async () => buttonOf(place, "Camera").click()); + await act(() => vi.waitFor(() => expect(isOn(place, "Camera")).toBe(true))); + // no microphone was opened, the camera alone was + expect(media.opened.map((track) => track.kind)).toEqual(["video"]); +}); + +test("a start that fails says why in words, and the row can be pressed again", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + history.replaceState(null, "", "/agents/agents/onboarding"); + const { itx, steps } = mind({ row: "a-page" }); + await using page = await draw(DashAgents, itx, { + waiting: 0, + call: { + enable: async () => { + throw new Error("the call's module is not in this mind's config"); + }, + }, + }); + const place = page.host.querySelector("[data-slot=agent-header-call]"); + await act(async () => (await vi.waitFor(() => goIn(place))).click()); + await act(() => + vi.waitFor(() => + expect(place?.querySelector("[role=alert]")?.textContent).toBe( + "The call could not start: the call's module is not in this mind's config", + ), + ), + ); + expect(goIn(place)).toBeTruthy(); + expect(steps).toEqual([]); +}); + +test("a call another member is in: Join in the header, a ring on their face, and the card says so", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + history.replaceState(null, "", "/agents/agents/onboarding"); + const { itx } = mind({ + row: "a-page", + pages: { "/agents/onboarding": [{ name: "b-page", principal: memberB }] }, + facets: { "/agents/onboarding": { call: callLive({ "b-page": ["mic", "camera"] }) } }, + }); + await using page = await draw(DashAgents, itx, { + waiting: 0, + presence: true, + call: { enable: async () => {} }, + }); + const place = page.host.querySelector("[data-slot=agent-header-call]"); + // others are in it: Join call, with how many + await act(() => + vi.waitFor(() => + expect(goIn(place).getAttribute("aria-label")).toBe("Join call: 1 person is in it"), + ), + ); + const access = page.host.querySelector<HTMLElement>("button[data-conversation-access]"); + await act(() => + vi.waitFor(() => + expect( + [...(access?.querySelectorAll("[data-slot=avatar]") || [])].map((face) => [ + face.textContent, + face.classList.contains("outline-success"), + ]), + ).toEqual([ + // the mind's face first, never in the call + ["", false], + ["B", true], + ["", false], + ]), + ), + ); + await act(async () => access!.click()); + await act(() => + vi.waitFor(() => + expect(document.querySelector("[data-shared-here]")?.textContent).toBe( + "Here now: b@example.com (in the call, camera)", + ), + ), + ); +}); + +test("in the call: the row's buttons and Leave in the same place, the voice agent's too, and the tiles over the feed", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _media = browserMedia(); + history.replaceState(null, "", "/agents/agents/onboarding"); + const { itx } = mind({ + row: "a-page", + pages: { "/agents/onboarding": [{ name: "b-page", principal: memberB }] }, + facets: { + "/agents/onboarding": { call: callLive({ "a-page": ["mic"], "b-page": ["mic"] }) }, + }, + }); + await using page = await draw(DashAgents, itx, { waiting: 0, call: { enable: async () => {} } }); + const place = page.host.querySelector("[data-slot=agent-header-call]"); + const mic = await act(() => vi.waitFor(() => goIn(place))); + await act(async () => mic.click()); + // a member's row: the voice agent's button is there (a guest's has none: call-controls.test.tsx) + await act(() => + vi.waitFor(() => + expect(buttonsOf(place!)).toEqual([ + "Microphone", + "Camera", + "Share screen", + "Voice agent", + "Devices", + "Leave the call", + ]), + ), + ); + // Join call's press took the focus to the microphone, now that Join call is gone + expect(buttonOf(place, "Microphone")).toBe(document.activeElement); + expect(place?.contains(mic)).toBe(false); + expect(page.host.querySelector("[data-slot=agent-header-call]")).toBe(place); + // the tiles stand over the feed, out of the header; the path each connection takes is read at + // the engine's next look + const tiles = page.host.querySelector("[data-slot=agent-call-tiles]"); + expect([ + tiles?.closest("[data-page-header]"), + tiles?.querySelector("[data-slot=call-tiles]")?.textContent, + ]).toEqual([null, expect.stringContaining("Connecting…")]); +}); + +test("a start whose call's live state comes before the join ends: the row waits, never goes in again, then the joined row; one join", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _media = browserMedia(); + const facet = callFacet(); + const joining = facet.hold("join"); + await using page = await drawCall(facet, async () => { + // the call is on: its row and its live state come before `enable` answers + page.update({ facetOn: true, live: callLive({}) }); + }); + await act(async () => goIn(page.place).click()); + await act(() => vi.waitFor(() => expect(facet).toMatchObject({ steps: ["join"] }))); + expect(waits(page.place)).toBe(true); + await act(async () => joining.release()); + await act(() => vi.waitFor(() => buttonOf(page.place, "Leave the call"))); + expect(facet.steps.filter((step) => step === "join")).toEqual(["join"]); +}); + +test("a start whose call's live state comes after the join ended: the joined row at once, never an empty header", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _media = browserMedia(); + const facet = callFacet(); + await using page = await drawCall(facet, async () => page.update({ facetOn: true })); + await act(async () => goIn(page.place).click()); + await act(() => vi.waitFor(() => buttonOf(page.place, "Leave the call"))); + await act(async () => page.update({ facetOn: true, live: callLive({ "a-page": ["mic"] }) })); + expect(buttonOf(page.place, "Leave the call").getAttribute("aria-disabled")).toBe(null); + expect(page.seen.filter((buttons) => buttons.length === 0)).toEqual([]); +}); + +test("Leave wins against the live state: one that says 'not in the call' while the leave is on its way joins nothing again", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _media = browserMedia(); + let now = Date.now(); + vi.spyOn(Date, "now").mockImplementation(() => now); + const facet = callFacet(); + await using page = await drawCall(facet, async () => page.update({ facetOn: true })); + await act(async () => goIn(page.place).click()); + await act(async () => page.update({ facetOn: true, live: callLive({ "a-page": ["mic"] }) })); + await act(() => vi.waitFor(() => buttonOf(page.place, "Leave the call"))); + now += 6_000; + const leaving = facet.hold("leave"); + await act(async () => buttonOf(page.place, "Leave the call").click()); + // the call already took the page out: its live state says so before the leave answers + await act(async () => page.update({ facetOn: true, live: callLive({}) })); + await act(async () => leaving.release()); + await act(() => vi.waitFor(() => goIn(page.place))); + now += 10_000; + await act(async () => page.update({ facetOn: true, live: callLive({ "b-page": ["mic"] }) })); + expect(facet.steps.filter((step) => step === "join")).toEqual(["join"]); + expect(goIn(page.place)).toBeTruthy(); +}); + +test("no live state says nothing of who is in the call: a joined page does not join again for it", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _media = browserMedia(); + let now = Date.now(); + vi.spyOn(Date, "now").mockImplementation(() => now); + const facet = callFacet(); + await using page = await drawCall(facet, async () => page.update({ facetOn: true })); + await act(async () => goIn(page.place).click()); + await act(async () => page.update({ facetOn: true, live: callLive({ "a-page": ["mic"] }) })); + await act(() => vi.waitFor(() => buttonOf(page.place, "Leave the call"))); + now += 6_000; + // the call's row is there, its live state is no more (a facet that restarts, a lost read) + await act(async () => page.update({ facetOn: true })); + expect(facet.steps.filter((step) => step === "join")).toEqual(["join"]); + expect(buttonOf(page.place, "Leave the call")).toBeTruthy(); +}); + +test("a Leave while the microphone is published stops the publish: no connection and no microphone stay open", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + const publishing = facet.hold("signal"); + const joining = call.join(); + await vi.waitFor(() => expect(facet).toMatchObject({ steps: ["join", "signal"] })); + await call.leave(); + publishing.release(); + await joining; + expect({ + joined: call.ui.joined, + open: media.connections.filter((one) => !one.closed).length, + mic: media.mic.readyState, + steps: facet.steps, + }).toEqual({ joined: false, open: 0, mic: "ended", steps: ["join", "signal", "leave"] }); +}); + +test("a dispose while the page joins again keeps it out: no join, no connection, no microphone", async () => { + using media = browserMedia(); + vi.useFakeTimers({ toFake: ["Date"] }); + try { + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const resetting = facet.hold("signal"); + vi.setSystemTime(Date.now() + 6_000); + const syncing = call.sync(viewOf(CallLive.parse(callLive({})), "a-page")); + // the publish, then both resets + await vi.waitFor(() => + expect(facet).toMatchObject({ steps: ["join", "signal", "signal", "signal"] }), + ); + call.dispose(); + resetting.release(); + await syncing; + expect({ + joined: call.ui.joined, + open: media.connections.filter((one) => !one.closed).length, + mic: media.mic.readyState, + joins: facet.steps.filter((step) => step === "join"), + }).toEqual({ joined: false, open: 0, mic: "ended", joins: ["join"] }); + } finally { + vi.useRealTimers(); + } +}); + +test("a Leave while the receiving connection connects frees the receive queue at once, and says nothing", async () => { + using _media = browserMedia({ receives: false }); + const facet = callFacet(); + const call = engineOn(facet); + const view = viewOf(CallLive.parse(callLive({ "a-page": ["mic"], "b-page": ["mic"] })), "a-page"); + // as the page's 5-s tick does: a sync while the join's own reconcile runs subscribes nothing + const synced = (check: () => void) => + vi.waitFor(async () => { + await call.sync(view); + check(); + }); + await call.join(); + await synced(() => expect(facet.signals).toContain("renegotiate")); + await call.leave(); + await call.join(); + await synced(() => expect(facet.signals.filter((step) => step === "subscribe")).toHaveLength(2)); + expect(call.ui).toMatchObject({ error: "" }); + call.dispose(); +}); + +test("a microphone the browser refuses tells the call nothing: no join, no leave", async () => { + using _media = browserMedia({ refuse: "NotAllowedError" }); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + expect({ steps: facet.steps, joined: call.ui.joined, error: call.ui.error }).toEqual({ + steps: [], + joined: false, + error: + "The browser did not give this page the microphone. Allow it for this site, then join again.", + }); +}); + +test("a dispose while the call takes the page in tells the call to let go of it", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + const taking = facet.hold("join"); + const joining = call.join(); + await vi.waitFor(() => expect(facet).toMatchObject({ steps: ["join"] })); + call.dispose(); + taking.release(); + await joining; + // the leave at once, and again when the join answers, as the facet may take the join in after + // the first: both are this admission's, so the second removes nothing newer + await vi.waitFor(() => expect(facet).toMatchObject({ steps: ["join", "leave", "leave"] })); + expect({ joined: call.ui.joined, mic: media.mic.readyState }).toEqual({ + joined: false, + mic: "ended", + }); +}); + +test("a page that joins again keeps its microphone: the browser is not asked for it again", async () => { + using media = browserMedia(); + vi.useFakeTimers({ toFake: ["Date"] }); + try { + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + vi.setSystemTime(Date.now() + 6_000); + // the call's live state says this page is not in it: the page joins again + await call.sync(viewOf(CallLive.parse(callLive({})), "a-page")); + expect({ + joins: facet.steps.filter((step) => step === "join"), + joined: call.ui.joined, + opened: media.opened.map((track) => track.readyState), + }).toEqual({ joins: ["join", "join"], joined: true, opened: ["live"] }); + call.dispose(); + } finally { + vi.useRealTimers(); + } +}); + +test("a change of the call while its subscriptions are made is followed once they are", async () => { + using _media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const subscribing = facet.hold("signal"); + void call.sync( + viewOf(CallLive.parse(callLive({ "a-page": ["mic"], "b-page": ["mic"] })), "a-page"), + ); + await vi.waitFor(() => expect(facet.signals).toContain("subscribe")); + // the other page turns its camera on while the first subscribe runs + const camera = callLive({ "a-page": ["mic"], "b-page": ["mic", "camera"] }); + void call.sync(viewOf(CallLive.parse(camera), "a-page")); + subscribing.release(); + await vi.waitFor(() => + expect(facet.signals.filter((step) => step === "subscribe")).toHaveLength(2), + ); + call.dispose(); +}); + +test("a receiving connection that never connects is made anew, as one that broke", async () => { + using _media = browserMedia({ receives: false }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + void call.sync(viewOf(CallLive.parse(callLive({ "b-page": ["mic"] })), "a-page")); + await vi.advanceTimersByTimeAsync(12_000 + 1_000); + expect(facet.signals).toContain("reset"); + call.dispose(); + } finally { + vi.useRealTimers(); + } +}); + +test("a camera pressed while the microphone is still on its way comes on once it is there", async () => { + using _media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + const publishing = facet.hold("signal"); + const joining = call.join(); + await vi.waitFor(() => expect(facet).toMatchObject({ steps: ["join", "signal"] })); + const camera = call.toggleCamera(); + publishing.release(); + await joining; + await camera; + expect({ camera: call.ui.camera, published: facet.published }).toEqual({ + camera: true, + published: ["mic", "camera"], + }); + call.dispose(); +}); + +test("a camera turned off stops its sender: later offers do not carry it", async () => { + using media = browserMedia(); + const call = engineOn(callFacet()); + await call.join(); + await call.toggleCamera(); + await call.toggleCamera(); + expect(media.connections[0]!.transceivers.map((one) => one.stopped)).toEqual([false, true]); + call.dispose(); +}); + +test("a microphone the sender refuses is closed again, and the old one goes on", async () => { + using media = browserMedia({ replaceFails: true }); + const call = engineOn(callFacet()); + await call.join(); + await call.chooseDevice("mic", "another-mic"); + expect({ + opened: media.opened.map((track) => track.readyState), + notice: call.ui.notice, + }).toEqual({ + opened: ["live", "ended"], + notice: "The new microphone could not be used (the sender refused the track).", + }); + call.dispose(); +}); + +test("sound the browser held back plays at the person's next click on the page", async () => { + using media = browserMedia(); + media.play.mockRejectedValueOnce(Object.assign(new Error("no"), { name: "NotAllowedError" })); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + await call.sync(viewOf(CallLive.parse(callLive({ "b-page": ["mic"] })), "a-page")); + await vi.waitFor(() => expect(facet.signals).toContain("renegotiate")); + media.connections[1]!.fire("track", { + transceiver: { mid: "m-b-page:mic" }, + track: { kind: "audio" }, + }); + await vi.waitFor(() => + expect(call.ui).toMatchObject({ + notice: "The browser held back the sound: click anywhere on the page.", + }), + ); + document.body.click(); + expect(media.play).toHaveBeenCalledTimes(2); + call.dispose(); +}); + +test("a track under a mid this page did not subscribe to has no tile", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + await call.sync(viewOf(CallLive.parse(callLive({ "b-page": ["mic"] })), "a-page")); + await vi.waitFor(() => expect(facet.signals).toContain("renegotiate")); + media.connections[1]!.fire("track", { + transceiver: { mid: "m-other" }, + track: { kind: "video" }, + }); + expect(call.ui).toMatchObject({ videos: [] }); + call.dispose(); +}); + +test("a voice agent that left before its voice was sent is not sent", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + await call.aiInvite(); + expect(call.ui).toMatchObject({ ai: "on" }); + const voice = media.connections.at(-1)!; + await call.aiDismiss(); + voice.fire("track", { track: { kind: "audio" } }); + // a camera switch is a job on the sending queue: it ends after the voice's turn + await call.chooseDevice("camera", ""); + expect({ published: facet.published, error: call.ui.error }).toEqual({ + published: ["mic"], + error: "", + }); + call.dispose(); +}); + +test("a dispose closes the voice agent at once: its session at OpenAI and its audio", async () => { + using media = browserMedia(); + const call = engineOn(callFacet()); + await call.join(); + await call.aiInvite(); + call.dispose(); + expect({ + ai: call.ui.ai, + sent: media.connections.at(-1)!.channels[0]!.sent, + audio: media.contexts.map((context) => context.closed), + }).toEqual({ ai: "off", sent: ['{"type":"session.close"}'], audio: [true] }); +}); + +test("a refusal of another tab's voice agent says why, and throws nothing", async () => { + using _media = browserMedia(); + const call = engineOn(callFacet({ voiceAgent: new Error("only a member can send it away") })); + await call.join(); + await call.aiDismiss(); + expect(call.ui).toMatchObject({ error: "only a member can send it away" }); + call.dispose(); +}); + +test("a page whose row is new after a reconnect is out of the call, and is told how to come back", async () => { + using _media = browserMedia(); + const host = document.body.appendChild(document.createElement("div")); + const root = createRoot(host); + const held: { call?: ReturnType<typeof useCall>["call"] } = {}; + function Page({ stub, page }: { stub: CallContext; page: string }) { + const { call, ui } = useCall(stub, page, undefined); + held.call = call; + return <p>{ui.notice}</p>; + } + try { + await act(async () => root.render(<Page stub={callFacet()} page="a-page" />)); + await act(async () => held.call!.join()); + await act(async () => root.render(<Page stub={callFacet()} page="a-page-2" />)); + expect(host).toMatchObject({ + textContent: + "The connection to the mind came back as a new session, so this page left the call. Press Join to come back into it.", + }); + } finally { + act(() => root.unmount()); + host.remove(); + } +}); + +test("a Mute pressed while the page joins again holds for the next call", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const resetting = facet.hold("signal", "reset"); + const rejoining = outOfTouch(call); + await vi.waitFor(() => expect(facet.signals).toContain("reset")); + call.toggleMute(); + resetting.release(); + await rejoining; + expect({ + joins: facet.steps.filter((step) => step === "join").length, + muted: call.ui.muted, + sending: media.mic.enabled, + }).toEqual({ joins: 2, muted: true, sending: false }); + call.dispose(); +}); + +test("a Mute pressed while a new microphone takes the old one's place holds for the new one", async () => { + using media = browserMedia(); + const call = engineOn(callFacet()); + await call.join(); + const replacing = media.hold("replaceTrack"); + const switching = call.chooseDevice("mic", "another-mic"); + await vi.waitFor(() => expect(media.opened).toHaveLength(2)); + call.toggleMute(); + replacing.release(); + await switching; + expect({ muted: call.ui.muted, sending: media.opened[1]!.enabled }).toEqual({ + muted: true, + sending: false, + }); + call.dispose(); +}); + +test("a microphone switch that a rejoin overtakes stops its own new microphone, never the kept one", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const opening = media.hold("open"); + const switching = call.chooseDevice("mic", "another-mic"); + const rejoining = outOfTouch(call); + await vi.waitFor(() => expect(facet.steps.filter((step) => step === "join")).toHaveLength(2)); + opening.release(); + await switching; + await rejoining; + // its caller settled at the call's end; the switch's own cleanup still stops what it opened + await vi.waitFor(() => expect(media.opened[1]!).toMatchObject({ readyState: "ended" })); + const sending = media.connections.filter((one) => !one.closed)[0]!; + expect({ + joined: call.ui.joined, + opened: media.opened.map((track) => track.readyState), + sent: sending.transceivers[0]!.track === media.opened[0], + }).toEqual({ joined: true, opened: ["live", "ended"], sent: true }); + call.dispose(); +}); + +test("a repair that joins afresh while the first microphone publish waits still joins, and a dispose then stops everything", async () => { + using media = browserMedia({ receives: false }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const facet = callFacet(); + const call = engineOn(facet); + const publishing = facet.hold("signal", "publish"); + const joining = call.join(); + await vi.advanceTimersByTimeAsync(0); + void call.sync(viewOf(CallLive.parse(callLive({ "b-page": ["mic"] })), "a-page")); + // the receiving connection never connects: five repairs, then the page joins afresh + await vi.advanceTimersByTimeAsync(120_000); + expect(call.ui).toMatchObject({ joined: true }); + call.dispose(); + publishing.release(); + await joining; + expect({ + opened: media.opened.filter((track) => track.readyState === "live").length, + connections: media.connections.filter((one) => !one.closed).length, + }).toEqual({ opened: 0, connections: 0 }); + } finally { + vi.useRealTimers(); + } +}); + +test("a page that only listens and joins afresh after a repair still opens no microphone", async () => { + using media = browserMedia({ receives: false }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const facet = callFacet(); + const call = engineOn(facet); + await call.join({ listenOnly: true }); + void call.sync(viewOf(CallLive.parse(callLive({ "b-page": ["mic"] })), "a-page")); + // the receiving connection never connects: five repairs, then the page joins afresh + await vi.advanceTimersByTimeAsync(120_000); + expect({ + joined: call.ui.joined, + muted: call.ui.muted, + joins: facet.steps.filter((one) => one === "join").length > 1, + }).toEqual({ + joined: true, + muted: true, + joins: true, + }); + expect(media).toMatchObject({ opened: [] }); + call.dispose(); + } finally { + vi.useRealTimers(); + } +}); + +test("a page that only listens sends nothing until its Unmute, which publishes the microphone once while the bar shows it at work", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join({ listenOnly: true }); + expect({ published: facet.published, connections: media.connections.length }).toEqual({ + published: [], + connections: 0, + }); + const publishing = facet.hold("signal", "publish"); + call.toggleMute(); + await vi.waitFor(() => expect(facet).toMatchObject({ published: ["mic"] })); + expect({ unmuting: call.ui.unmuting, muted: call.ui.muted }).toEqual({ + unmuting: true, + muted: true, + }); + // a second press while the first is at work changes nothing + call.toggleMute(); + publishing.release(); + await vi.waitFor(() => expect(call.ui).toMatchObject({ unmuting: false })); + expect({ + published: facet.published, + muted: call.ui.muted, + opened: media.opened.map((track) => track.kind), + }).toEqual({ published: ["mic"], muted: false, opened: ["audio"] }); + call.dispose(); +}); + +test("a first Unmute whose publish fails leaves the page muted, says why, and closes the microphone", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join({ listenOnly: true }); + facet.failNext("signal", new Error("the SFU refused the offer")); + call.toggleMute(); + await vi.waitFor(() => expect(call.ui).toMatchObject({ unmuting: false })); + expect({ + muted: call.ui.muted, + notice: call.ui.notice, + microphone: media.mic.readyState, + sending: media.connections.filter((one) => !one.closed).length, + }).toEqual({ + muted: true, + notice: expect.stringContaining("so you are still muted (the SFU refused the offer)"), + microphone: "ended", + sending: 0, + }); + call.dispose(); +}); + +test("a first Unmute whose sending connection never connects leaves the page muted, and the call forgets its track", async () => { + using media = browserMedia(); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const facet = callFacet(); + const call = engineOn(facet); + await call.join({ listenOnly: true }); + media.sends = false; + call.toggleMute(); + await vi.advanceTimersByTimeAsync(15_000); + expect({ + muted: call.ui.muted, + unmuting: call.ui.unmuting, + notice: call.ui.notice, + signals: facet.signals, + open: media.connections.filter((one) => !one.closed).length, + microphone: media.mic.readyState, + }).toEqual({ + muted: true, + unmuting: false, + notice: expect.stringContaining("so you are still muted (Sending: no connection"), + signals: ["publish", "reset"], + open: 0, + microphone: "ended", + }); + call.dispose(); + } finally { + vi.useRealTimers(); + } +}); + +test("a page that only listens sends its camera as its first track, and an Unmute then puts the microphone beside it", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join({ listenOnly: true }); + await call.toggleCamera(); + expect({ camera: call.ui.camera, published: facet.published }).toEqual({ + camera: true, + published: ["camera"], + }); + call.toggleMute(); + await vi.waitFor(() => expect(call.ui).toMatchObject({ muted: false })); + expect({ + published: facet.published, + // one sending connection, with both senders + senders: media.connections.map((one) => one.transceivers.length), + }).toEqual({ published: ["camera", "mic"], senders: [2] }); + call.dispose(); +}); + +test("a receiving session the SFU ended (410) is made anew by the repair, and the page says no error", async () => { + using _media = browserMedia(); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + facet.failNext("signal", sessionEnded()); + void call.sync(viewOf(CallLive.parse(callLive({ "b-page": ["mic"] })), "a-page")); + await vi.advanceTimersByTimeAsync(5_000); + expect({ + subscribes: facet.signals.filter((step) => step === "subscribe").length, + resets: facet.signals.filter((step) => step === "reset").length, + error: call.ui.error, + repair: call.ui.repair, + }).toEqual({ subscribes: 2, resets: 1, error: "", repair: "" }); + call.dispose(); + } finally { + vi.useRealTimers(); + } +}); + +test("a receiving session the SFU keeps refusing (410): the bounded repair, one rejoin, then the page leaves, says so, and asks nothing more", async () => { + using _media = browserMedia(); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const facet = callFacet(); + const call = engineOn(facet); + facet.failStep("subscribe", sessionEnded()); + await call.join(); + void call.sync(viewOf(CallLive.parse(callLive({ "b-page": ["mic"] })), "a-page")); + await vi.advanceTimersByTimeAsync(10 * 60_000); + const steps = facet.steps.length; + await vi.advanceTimersByTimeAsync(10 * 60_000); + expect({ + more: facet.steps.length - steps, + leaves: facet.steps.filter((step) => step === "leave").length, + joined: call.ui.joined, + error: call.ui.error, + }).toEqual({ + more: 0, + leaves: 1, + joined: false, + error: expect.stringMatching( + /^Your receiving connection could not be repaired \(The SFU answered 410.*\)\. Press Join/, + ), + }); + } finally { + vi.useRealTimers(); + } +}); + +test("a camera's prompt left open does not hold up the next call's microphone", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const prompt = media.hold("open"); + const camera = call.toggleCamera(); + await call.leave(); + await call.join(); + expect({ joined: call.ui.joined, published: facet.published }).toEqual({ + joined: true, + published: ["mic", "mic"], + }); + prompt.release(); + await camera; + // the camera came after its call ended: it is closed, and not on in the new one + await vi.waitFor(() => expect(media.opened).toHaveLength(3)); + await vi.waitFor(() => expect(media.opened.at(-1)).toMatchObject({ readyState: "ended" })); + expect({ camera: call.ui.camera, track: media.opened.at(-1)!.readyState }).toEqual({ + camera: false, + track: "ended", + }); + call.dispose(); +}); + +test("a Leave while the first microphone publish waits lets a new Join start at once", async () => { + using _media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + const publishing = facet.hold("signal", "publish"); + const first = call.join(); + await vi.waitFor(() => expect(facet).toMatchObject({ published: ["mic"] })); + await call.leave(); + await call.join(); + expect(call.ui).toMatchObject({ joined: true, joining: false }); + publishing.release(); + await first; + // the first join's end does not touch the call that came after it + expect(call.ui).toMatchObject({ joined: true, joining: false }); + call.dispose(); +}); + +test("a dispose while a new camera takes the old one's place stops the new camera too", async () => { + using media = browserMedia(); + const call = engineOn(callFacet()); + await call.join(); + await call.toggleCamera(); + const scaling = media.hold("setParameters"); + const switching = call.chooseDevice("camera", "another-camera"); + await vi.waitFor(() => expect(media.opened).toHaveLength(3)); + call.dispose(); + scaling.release(); + await switching; + expect(media.opened.map((track) => track.readyState)).toEqual(["ended", "ended", "ended"]); +}); + +test("a dispose while a camera waits for its first publish stops the camera", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const publishing = facet.hold("signal", "publish"); + const camera = call.toggleCamera(); + await vi.waitFor(() => expect(facet).toMatchObject({ published: ["mic", "camera"] })); + call.dispose(); + publishing.release(); + await camera; + expect({ camera: call.ui.camera, track: media.opened[1]!.readyState }).toEqual({ + camera: false, + track: "ended", + }); +}); + +test("a dispose while the microphone waits for the call's answer closes its connection at once", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + const publishing = facet.hold("signal", "publish"); + const joining = call.join(); + await vi.waitFor(() => expect(facet).toMatchObject({ published: ["mic"] })); + call.dispose(); + expect(media.connections.map((one) => one.closed)).toEqual([true]); + publishing.release(); + await joining; +}); + +test("a receiving connection that never connects: one rejoin, then the page leaves and says so, and nothing loops", async () => { + using _media = browserMedia({ receives: false }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + void call.sync(viewOf(CallLive.parse(callLive({ "b-page": ["mic"] })), "a-page")); + await vi.advanceTimersByTimeAsync(10 * 60_000); + const steps = facet.steps.length; + await vi.advanceTimersByTimeAsync(10 * 60_000); + expect({ + more: facet.steps.length - steps, + leaves: facet.steps.filter((step) => step === "leave").length, + resets: facet.signals.filter((step) => step === "reset").length, + joined: call.ui.joined, + error: call.ui.error, + }).toEqual({ + more: 0, + leaves: 1, + // five repairs in each of the two calls, and the rejoin's two + resets: 12, + joined: false, + error: expect.stringMatching(/^Your receiving connection could not be repaired .*Press Join/), + }); + } finally { + vi.useRealTimers(); + } +}); + +test("a dispose while a repair resets the receiving session leaves no connection open", async () => { + using media = browserMedia({ receives: false }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const resetting = facet.hold("signal", "reset"); + void call.sync(viewOf(CallLive.parse(callLive({ "b-page": ["mic"] })), "a-page")); + await vi.advanceTimersByTimeAsync(12_000 + 1_000); + expect(facet.signals).toContain("reset"); + call.dispose(); + resetting.release(); + await vi.advanceTimersByTimeAsync(0); + expect(media.connections.filter((one) => !one.closed)).toEqual([]); + } finally { + vi.useRealTimers(); + } +}); + +test("an invite's late answer after a leave and a new invite leaves the new voice agent alone", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const answering = facet.hold("voiceAgent"); + const first = call.aiInvite(); + await vi.waitFor(() => expect(facet.steps).toContain("voiceAgent")); + await call.leave(); + await call.join(); + await call.aiInvite(); + answering.release(); + await first; + expect({ + ai: call.ui.ai, + closed: media.connections.at(-1)!.channels[0]!.sent, + }).toEqual({ ai: "on", closed: [] }); + call.dispose(); +}); + +test("a Leave while hosting the voice agent closes the microphone at once, and the call hears one leave, which ends the agent", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + await call.aiInvite(); + const leaving = call.leave(); + expect({ + mic: media.mic.readyState, + open: media.connections.filter((one) => !one.closed).length, + }).toEqual({ mic: "ended", open: 0 }); + await leaving; + expect(facet.steps.slice(-2)).toEqual(["voiceAgent", "leave"]); +}); + +test("a Leave whose voice agent's channel throws still closes the microphone and the camera", async () => { + using media = browserMedia(); + const call = engineOn(callFacet()); + await call.join(); + await call.toggleCamera(); + await call.aiInvite(); + Object.assign(media.connections.at(-1)!.channels[0]!, { + send: () => { + throw Object.assign(new Error("the channel is closing"), { name: "OperationError" }); + }, + }); + await call.leave(); + expect({ + tracks: media.opened.map((track) => track.readyState), + open: media.connections.filter((one) => !one.closed).length, + }).toEqual({ tracks: ["ended", "ended"], open: 0 }); +}); + +test("a Join right after a Leave of a voice agent's host: the old leave never comes after the new join", async () => { + using _media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + await call.aiInvite(); + const stopping = facet.hold("voiceAgent"); + const leaving = call.leave(); + await call.join(); + stopping.release(); + await leaving; + expect({ + joined: call.ui.joined, + afterJoin: facet.steps.slice(facet.steps.lastIndexOf("join")).includes("leave"), + }).toEqual({ joined: true, afterJoin: false }); + call.dispose(); +}); + +test("a join the call took in after its Leave, behind a newer join: the next Leave is still sent", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + const admitting = facet.hold("join"); + const first = call.join(); + await vi.waitFor(() => expect(facet.steps).toContain("join")); + await call.leave(); + const opening = media.hold("open"); + const second = call.join(); + admitting.release(); + await first; + await call.leave(); + opening.release(); + await second; + // the first Leave's, at once and again at the late answer: both the first admission's + expect(facet.steps.filter((step) => step === "leave")).toEqual(["leave", "leave"]); +}); + +test("an old sending repair whose reset answers after a Leave and a Join offers the new call nothing", async () => { + using media = browserMedia(); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const sending = media.connections[0]!; + sending.fire("connectionstatechange", {}); + sending.connectionState = "failed"; + const resetting = facet.hold("signal", "reset"); + sending.fire("connectionstatechange", {}); + await vi.advanceTimersByTimeAsync(1_000); + expect(facet.signals).toContain("reset"); + await call.leave(); + await call.join(); + const offers = facet.published.length; + resetting.release(); + await vi.advanceTimersByTimeAsync(0); + expect(facet.published.length).toBe(offers); + call.dispose(); + } finally { + vi.useRealTimers(); + } +}); + +test("a second Share press while the screen's picker is open turns it off: the chosen screen is not sent", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const choosing = media.hold("display"); + const first = call.toggleScreen(); + const second = call.toggleScreen(); + choosing.release(); + await first; + await second; + expect({ + screen: call.ui.screen, + published: facet.published, + pickers: media.displays, + picture: media.opened.at(-1)!.readyState, + }).toEqual({ screen: false, published: ["mic"], pickers: 1, picture: "ended" }); + call.dispose(); +}); + +test("a screen whose share the browser stopped while it waited for the microphone is not sent", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + const publishing = facet.hold("signal", "publish"); + const joining = call.join(); + await vi.waitFor(() => expect(facet).toMatchObject({ published: ["mic"] })); + const screen = call.toggleScreen(); + await vi.waitFor(() => expect(media.opened).toHaveLength(2)); + // the browser's own "Stop sharing" + media.opened[1]!.readyState = "ended"; + publishing.release(); + await joining; + await screen; + expect({ screen: call.ui.screen, published: facet.published }).toEqual({ + screen: false, + published: ["mic"], + }); + call.dispose(); +}); + +test("device changes behind an unanswered microphone prompt settle at a Leave, and put no error on the next call", async () => { + using media = browserMedia(); + const call = engineOn(callFacet()); + await call.join(); + await call.toggleCamera(); + const opening = media.hold("open"); + const switchingMic = call.chooseDevice("mic", "another-mic"); + const switchingCamera = call.chooseDevice("camera", "another-camera"); + // the microphone's prompt is open, and the camera's switch waits behind it + await new Promise((resolve) => setTimeout(resolve, 0)); + await call.leave(); + await switchingMic; + await switchingCamera; + await call.join(); + opening.release(); + await vi.waitFor(() => expect(media.opened.at(-1)?.readyState).toBe("ended")); + expect(call.ui).toMatchObject({ joined: true, error: "" }); + call.dispose(); +}); + +test("a new call subscribes while the old call's subscribe is still unanswered", async () => { + using _media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const subscribing = facet.hold("signal", "subscribe"); + const others = viewOf(CallLive.parse(callLive({ "b-page": ["mic"] })), "a-page"); + void call.sync(others); + await vi.waitFor(() => expect(facet.signals).toContain("subscribe")); + await call.leave(); + await call.join(); + void call.sync(others); + await vi.waitFor(() => + expect(facet.signals.filter((step) => step === "subscribe")).toHaveLength(2), + ); + subscribing.release(); + call.dispose(); +}); + +test("a live state that keeps saying 'not in the call' makes one rejoin, then the page leaves and says so", async () => { + using _media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + for (const _ of [1, 2, 3]) await outOfTouch(call); + expect({ + joins: facet.steps.filter((step) => step === "join").length, + joined: call.ui.joined, + error: call.ui.error, + }).toEqual({ + joins: 2, + joined: false, + error: "This page was out of touch with the call. Press Join to try again.", + }); +}); + +test("a kept microphone unplugged while the call takes the page in again: the default is sent, with its mute", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + call.toggleMute(); + const admitting = facet.hold("join"); + const rejoining = outOfTouch(call); + await vi.waitFor(() => expect(facet.steps.filter((step) => step === "join")).toHaveLength(2)); + media.mic.stop(); + admitting.release(); + await rejoining; + const sending = media.connections.filter((one) => !one.closed)[0]!; + expect({ + sent: sending.transceivers[0]!.track.readyState, + muted: !sending.transceivers[0]!.track.enabled, + ui: call.ui.muted, + }).toEqual({ sent: "live", muted: true, ui: true }); + call.dispose(); +}); + +test("an invite still making its offer after a Leave and a Join asks the new call for no agent", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const offering = media.hold("offer"); + const inviting = call.aiInvite(); + await vi.waitFor(() => expect(media.contexts).toHaveLength(1)); + await call.leave(); + await call.join(); + offering.release(); + await inviting; + expect({ ai: call.ui.ai, asked: facet.steps.filter((step) => step === "voiceAgent") }).toEqual({ + ai: "off", + asked: [], + }); + call.dispose(); +}); + +test("an old rejoin whose agent stop answers after a Leave and a Join resets nothing of the new call", async () => { + using _media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + await call.aiInvite(); + const stopping = facet.hold("voiceAgent"); + const rejoining = outOfTouch(call); + await vi.waitFor(() => expect(facet.steps.at(-1)).toBe("voiceAgent")); + await call.leave(); + await call.join(); + const resets = facet.signals.filter((step) => step === "reset").length; + stopping.release(); + await rejoining; + expect({ + joined: call.ui.joined, + resets: facet.signals.filter((step) => step === "reset").length, + }).toEqual({ joined: true, resets }); + call.dispose(); +}); + +test("a receiving connection that comes back by itself before its first try takes its error with it", async () => { + using media = browserMedia({ receives: false }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const call = engineOn(callFacet()); + await call.join(); + void call.sync(viewOf(CallLive.parse(callLive({ "b-page": ["mic"] })), "a-page")); + await vi.advanceTimersByTimeAsync(12_000); + expect(call.ui.error).toMatch(/^Receiving: no connection to Cloudflare in 12 s/); + media.connections.at(-1)!.connectionState = "connected"; + await vi.advanceTimersByTimeAsync(1_000); + expect(call.ui).toMatchObject({ error: "" }); + call.dispose(); + } finally { + vi.useRealTimers(); + } +}); + +test("admission order 1: an old engine's owed Leave carries its own admission, never the new engine's", async () => { + using _media = browserMedia(); + const facet = callFacet(); + const old = engineOn(facet); + const taking = facet.hold("join"); + const joining = old.join(); + await vi.waitFor(() => expect(facet.steps).toContain("join")); + // the context object changed, the row stayed: a new engine on the same row + old.dispose(); + const fresh = engineOn(facet); + await fresh.join(); + taking.release(); + await joining; + const [oldAdmission, newAdmission] = admissionsOf(facet, "join"); + expect(newAdmission).not.toBe(oldAdmission); + expect(new Set(admissionsOf(facet, "leave"))).toEqual(new Set([oldAdmission])); + fresh.dispose(); +}); + +test("admission order 3: an old camera offer still gathering after a Leave and a Join is never sent", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const offering = media.hold("offer"); + const camera = call.toggleCamera(); + await vi.waitFor(() => expect(media.opened).toHaveLength(2)); + await call.leave(); + await call.join(); + offering.release(); + await camera; + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(facet).toMatchObject({ published: ["mic", "mic"] }); + call.dispose(); +}); + +test("admission order 4: an old switch's late microphone never takes the newer switch's Mute", async () => { + using media = browserMedia(); + const call = engineOn(callFacet()); + await call.join(); + const opening = media.hold("open"); + const oldSwitch = call.chooseDevice("mic", "mic-old"); + await new Promise((resolve) => setTimeout(resolve, 0)); + await call.leave(); + await call.join(); + const replacing = media.hold("replaceTrack"); + const newSwitch = call.chooseDevice("mic", "mic-new"); + await vi.waitFor(() => expect(media.opened).toHaveLength(3)); + opening.release(); + await oldSwitch; + // the old switch's capture comes back while the new one replaces its track: then Mute + await vi.waitFor(() => expect(media.opened).toHaveLength(4)); + await new Promise((resolve) => setTimeout(resolve, 0)); + call.toggleMute(); + // the new microphone is silent from the press, also while its track is being put in place + expect(media.opened[2]).toMatchObject({ enabled: false }); + replacing.release(); + await newSwitch; + // opened: the first mic, the second call's, the new switch's, then the old switch's late one + const [, , switched, late] = media.opened; + expect({ + muted: call.ui.muted, + sending: switched!.enabled, + live: switched!.readyState, + late: late!.readyState, + }).toEqual({ muted: true, sending: false, live: "live", late: "ended" }); + call.dispose(); +}); + +test("admission order 4: a chosen device that fails after a Leave opens no default device", async () => { + using media = browserMedia(); + const call = engineOn(callFacet()); + await call.join(); + const opening = media.hold("open"); + media.refuseNext("NotFoundError"); + const switching = call.chooseDevice("mic", "gone-mic"); + await new Promise((resolve) => setTimeout(resolve, 0)); + await call.leave(); + opening.release(); + await switching; + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(media.opened.map((track) => track.readyState)).toEqual(["ended"]); +}); + +test("admission order 5: a TURN refresh carries its admission, and one that answers after a Leave sets no new refresh", async () => { + using _media = browserMedia(); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const refreshing = facet.hold("join"); + await vi.advanceTimersByTimeAsync(60 * 750); + expect(facet.calls.filter((one) => one.method === "join").map(({ args }) => args)).toEqual([ + [{ admit: admissionsOf(facet, "join")[0], seq: expect.any(Number) }], + [{ admission: admissionsOf(facet, "join")[0] }], + ]); + await call.leave(); + refreshing.release(); + await vi.advanceTimersByTimeAsync(10 * 60_000); + expect(facet.steps.filter((step) => step === "join")).toHaveLength(2); + } finally { + vi.useRealTimers(); + } +}); + +test("admission order 6: a join whose answer failed after the call may have taken the page in still sends its leave", async () => { + using _media = browserMedia(); + const facet = callFacet({ join: new Error("the call's setup failed") }); + const call = engineOn(facet); + await call.join(); + expect({ joined: call.ui.joined, leaves: admissionsOf(facet, "leave") }).toEqual({ + joined: false, + leaves: admissionsOf(facet, "join"), + }); +}); + +test("admission order 6: a dispose of a page in the call sends its admission's leave", async () => { + using _media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + call.dispose(); + await vi.waitFor(() => expect(admissionsOf(facet, "leave")).toEqual(admissionsOf(facet, "join"))); +}); + +test("admission order 7: a dispose while the microphone's prompt is open settles the Join at once", async () => { + using media = browserMedia(); + const call = engineOn(callFacet()); + media.hold("open"); + const joining = call.join(); + await new Promise((resolve) => setTimeout(resolve, 0)); + call.dispose(); + await joining; + expect(call.ui).toMatchObject({ joined: false, joining: false }); +}); + +test("admission order 7: a screen chosen after its press was turned off closes at once, not at its turn", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + const publishing = facet.hold("signal", "publish"); + const joining = call.join(); + await vi.waitFor(() => expect(facet).toMatchObject({ published: ["mic"] })); + const choosing = media.hold("display"); + const first = call.toggleScreen(); + const off = call.toggleScreen(); + choosing.release(); + await first; + expect(media.opened.at(-1)).toMatchObject({ kind: "video", readyState: "ended" }); + publishing.release(); + await joining; + await off; + call.dispose(); +}); + +test("follow-up order 2: a dismiss while the voice agent's start is under way withdraws that invite, by its id", async () => { + using _media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const starting = facet.hold("voiceAgent"); + const inviting = call.aiInvite(); + await vi.waitFor(() => expect(facet.steps).toContain("voiceAgent")); + await call.aiDismiss(); + starting.release(); + await inviting; + const [start, stop] = facet.calls + .filter((one) => one.method === "voiceAgent") + .map(({ args }) => args[0] as { invite?: string }); + // no `stop`: a call from before `withdraw` refuses it, and sends away no other page's agent + expect([start, stop]).toEqual([ + { start: "v=0", invite: expect.any(String) }, + { withdraw: start?.invite, why: "sent away" }, + ]); + call.dispose(); +}); + +test("follow-up order 2: an invite after a dismissed one waits for that one's answer: one start of a page at a time", async () => { + using _media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + const starting = facet.hold("voiceAgent"); + const first = call.aiInvite(); + await vi.waitFor(() => expect(facet.steps).toContain("voiceAgent")); + await call.aiDismiss(); + const second = call.aiInvite(); + await new Promise((resolve) => setTimeout(resolve, 20)); + const starts = () => + facet.calls.filter((one) => one.method === "voiceAgent" && "start" in (one.args[0] as object)) + .length; + expect(starts()).toBe(1); + starting.release(); + await first; + await second; + expect(starts()).toBe(2); + call.dispose(); +}); + +test("follow-up order 5: a rejoin whose new admission fails sends the earlier admission's leave", async () => { + using _media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + facet.failNext("join", new Error("the call's setup failed")); + await outOfTouch(call); + const [first, second] = admissionsOf(facet, "join"); + expect(new Set(admissionsOf(facet, "leave"))).toEqual(new Set([first, second])); +}); + +test("follow-up order 7: an Off of a screen that waits for its turn stops it at once", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + const publishing = facet.hold("signal", "publish"); + const joining = call.join(); + await vi.waitFor(() => expect(facet).toMatchObject({ published: ["mic"] })); + const sharing = call.toggleScreen(); + await vi.waitFor(() => expect(media.opened).toHaveLength(2)); + const off = call.toggleScreen(); + expect(media.opened[1]).toMatchObject({ readyState: "ended" }); + publishing.release(); + await joining; + await sharing; + await off; + expect(facet).toMatchObject({ published: ["mic"] }); + call.dispose(); +}); + +test("follow-up order 7: a dispose while the call has not answered the join settles the Join, and the late answer gets its leave", async () => { + using _media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + const taking = facet.hold("join"); + const joining = call.join(); + await vi.waitFor(() => expect(facet.steps).toContain("join")); + call.dispose(); + await joining; + expect(call.ui).toMatchObject({ joined: false, joining: false }); + taking.release(); + await vi.waitFor(() => expect(admissionsOf(facet, "leave")).toHaveLength(2)); + expect(new Set(admissionsOf(facet, "leave"))).toEqual(new Set(admissionsOf(facet, "join"))); +}); + +test("a voice agent sent away while a sending repair offers its voice again: that voice goes out of the call", async () => { + using media = browserMedia(); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + await call.aiInvite(); + media.connections.at(-1)!.fire("track", { track: { kind: "audio" } }); + await vi.waitFor(() => expect(facet).toMatchObject({ published: ["mic", "ai"] })); + const sending = media.connections[0]!; + sending.fire("connectionstatechange", {}); + sending.connectionState = "failed"; + const resetting = facet.hold("signal", "reset"); + sending.fire("connectionstatechange", {}); + await vi.advanceTimersByTimeAsync(1_000); + expect(facet.signals).toContain("reset"); + // the rebuilt connection offers the microphone first, then the voice + const offeringMic = media.hold("offer"); + resetting.release(); + await vi.advanceTimersByTimeAsync(0); + const rebuilt = media.connections.at(-1)!; + await vi.waitFor(() => expect(rebuilt.transceivers).toHaveLength(1)); + const offering = media.hold("offer"); + offeringMic.release(); + await vi.waitFor(() => expect(rebuilt.transceivers).toHaveLength(2)); + await call.aiDismiss(); + offering.release(); + await vi.advanceTimersByTimeAsync(0); + expect(rebuilt.transceivers.map((one) => one.stopped)).toEqual([false, true]); + call.dispose(); + } finally { + vi.useRealTimers(); + } +}); + +test("a voice agent sent away while its voice is offered: the voice goes out of the call again", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + await call.join(); + await call.aiInvite(); + const offering = facet.hold("signal", "publish"); + media.connections.at(-1)!.fire("track", { track: { kind: "audio" } }); + await vi.waitFor(() => expect(facet).toMatchObject({ published: ["mic", "ai"] })); + await call.aiDismiss(); + offering.release(); + await vi.waitFor(() => expect(facet.signals).toContain("unpublish")); + expect(media.connections[0]!.transceivers.map((one) => one.stopped)).toEqual([false, true]); + call.dispose(); +}); + +test("the screen's picker opens from the press itself, while the microphone is still on its way", async () => { + using media = browserMedia(); + const facet = callFacet(); + const call = engineOn(facet); + const publishing = facet.hold("signal", "publish"); + const joining = call.join(); + await vi.waitFor(() => expect(facet).toMatchObject({ published: ["mic"] })); + const screen = call.toggleScreen(); + expect(media).toMatchObject({ displays: 1 }); + publishing.release(); + await joining; + await screen; + expect({ screen: call.ui.screen, published: facet.published }).toEqual({ + screen: true, + published: ["mic", "screen"], + }); + // a screen chosen after its call ended is closed + await call.toggleScreen(); + const choosing = media.hold("display"); + const late = call.toggleScreen(); + await call.leave(); + choosing.release(); + await late; + expect(media.opened.at(-1)).toMatchObject({ kind: "video", readyState: "ended" }); +}); + +test("a receiving connection's error goes once its repair worked", async () => { + using media = browserMedia({ receives: false }); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const call = engineOn(callFacet()); + await call.join(); + void call.sync(viewOf(CallLive.parse(callLive({ "b-page": ["mic"] })), "a-page")); + await vi.advanceTimersByTimeAsync(12_000); + expect(call.ui.error).toMatch(/^Receiving: no connection to Cloudflare in 12 s/); + media.receives = true; + await vi.advanceTimersByTimeAsync(1_000); + expect(call.ui).toMatchObject({ + error: "", + notice: "Your receiving connection is repaired.", + }); + call.dispose(); + } finally { + vi.useRealTimers(); + } +}); + +test("why the voice agent did not come is gone when the next call starts", async () => { + using _media = browserMedia(); + const call = engineOn(callFacet({ voiceAgent: new Error("no key") })); + await call.join(); + await call.aiInvite(); + expect(call.ui).toMatchObject({ aiRefusal: { message: "no key" } }); + await call.leave(); + await call.join(); + expect(call.ui).toMatchObject({ aiRefusal: null }); + call.dispose(); +}); + +test("a Start whose page went into the back-forward cache while the call came on joins nothing on its return", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using media = browserMedia(); + const facet = callFacet(); + let enabled = () => {}; + await using page = await drawCall( + facet, + () => new Promise<void>((resolve) => (enabled = resolve)), + ); + await act(async () => goIn(page.place).click()); + await act(async () => { + dispatchEvent(new Event("pagehide")); + dispatchEvent(new Event("pageshow")); + }); + await act(async () => enabled()); + // the microphone opens with the join, which never came: nothing was opened or sent + expect({ steps: facet.steps, opened: media.opened }).toEqual({ steps: [], opened: [] }); + expect(waits(page.place)).toBe(false); +}); + +test("a Start whose page went away while the call came on joins nothing and opens no microphone", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using media = browserMedia(); + const facet = callFacet(); + let enabled = () => {}; + const page = await drawCall(facet, () => new Promise<void>((resolve) => (enabled = resolve))); + await act(async () => goIn(page.place).click()); + await page[Symbol.asyncDispose](); + enabled(); + await act(async () => {}); + expect({ steps: facet.steps, opened: media.opened }).toEqual({ steps: [], opened: [] }); +}); + +test("someone watching an empty call hears the first arrival, and a page alone sees its notice", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _media = browserMedia(); + const facet = callFacet(); + await using page = await drawCall(facet, async () => {}); + await act(async () => page.update({ facetOn: true, live: callLive({}) })); + await act(async () => page.update({ facetOn: true, live: callLive({ "b-page": ["mic"] }) })); + const tiles = () => document.querySelector("[data-slot=agent-call-tiles]"); + expect(tiles()?.querySelector("[aria-live=polite]")?.textContent).toBe( + "b@example.com joined the call.", + ); + // this page alone in the call, then a new row after a reconnect: the notice says how to come back + await act(async () => page.update({ facetOn: true, live: callLive({}) })); + await act(async () => goIn(page.place).click()); + await act(() => vi.waitFor(() => buttonOf(page.place, "Leave the call"))); + await act(async () => page.update({ facetOn: true, live: callLive({}), row: "a-page-2" })); + expect(tiles()?.querySelector("[data-slot=call-tiles]")?.textContent).toContain( + "Press Join to come back into it.", + ); +}); + +test("a start whose microphone is open while it publishes: the microphone and Leave show at once", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _media = browserMedia(); + const facet = callFacet(); + const publishing = facet.hold("signal"); + await using page = await drawCall(facet, async () => page.update({ facetOn: true })); + await act(async () => goIn(page.place).click()); + await act(() => vi.waitFor(() => expect(facet).toMatchObject({ steps: ["join", "signal"] }))); + expect(isOn(page.place, "Microphone")).toBe(true); + expect(buttonOf(page.place, "Leave the call").getAttribute("aria-disabled")).toBe(null); + // a Leave before the join has ended: the row can go in again, and waits for nothing + await act(async () => buttonOf(page.place, "Leave the call").click()); + expect(goIn(page.place)).toBeTruthy(); + await act(async () => publishing.release()); +}); + +test("on a phone, Start call is in the header itself, waits while the start runs, and in the call the controls are behind one button that says so", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _media = browserMedia(); + const facet = callFacet(); + let enabled = () => {}; + await using page = await drawCall( + facet, + () => new Promise<void>((resolve) => (enabled = resolve)), + { narrow: true }, + ); + await act(async () => (await vi.waitFor(() => goIn(page.place))).click()); + expect(waits(page.place)).toBe(true); + await act(async () => { + page.update({ facetOn: true }); + enabled(); + }); + await act(() => + vi.waitFor(() => + expect(page.place.querySelector("button")?.getAttribute("aria-label")).toBe( + "Call: you are in it", + ), + ), + ); +}); + +test("on a phone, a page in the call with an error: the call's button says both", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _media = browserMedia(); + const facet = callFacet({ voiceAgent: new Error("no key") }); + await using page = await drawCall(facet, async () => {}, { narrow: true }); + await act(async () => page.update({ facetOn: true, live: callLive({}) })); + await act(async () => (await vi.waitFor(() => goIn(page.place))).click()); + const trigger = await act(() => + vi.waitFor(() => { + const found = page.place.querySelector("button"); + if (found?.getAttribute("aria-label") !== "Call: you are in it") throw new Error("not in"); + return found; + }), + ); + await act(async () => trigger.click()); + await act(async () => buttonOf(document.body, "Voice agent").click()); + await act(() => + vi.waitFor(() => + expect(trigger.getAttribute("aria-label")).toBe("Call: you are in it, and an error"), + ), + ); +}); + +test("a mind with no SFU app: the tiles over the feed say why Join cannot be pressed", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const facet = callFacet(); + await using page = await drawCall(facet, async () => {}); + await act(async () => + page.update({ + facetOn: true, + live: { ...callLive({}), setup: { sfu: false, turn: false, voice: false } }, + }), + ); + expect(goInOf(page.place).getAttribute("aria-disabled")).toBe("true"); + expect(document.querySelector("[data-slot=agent-call-tiles]")?.textContent).toContain( + "This mind has no Cloudflare Realtime SFU app yet", + ); +}); + +test("a start whose call came on but whose join failed: the call's words, and Join to press again", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _media = browserMedia(); + const facet = callFacet({ join: new Error("the call has no SFU app") }); + await using page = await drawCall(facet, async () => page.update({ facetOn: true })); + await act(async () => goIn(page.place).click()); + await act(() => + vi.waitFor(() => + expect(page.place.querySelector("[role=alert]")?.textContent).toBe("the call has no SFU app"), + ), + ); + expect(goIn(page.place)).toBeTruthy(); + expect(page.seen.filter((buttons) => buttons.length === 0)).toEqual([]); +}); + +test("a start whose join fails before the table shows the call: Join, never Start again", async () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + using _media = browserMedia(); + const facet = callFacet({ join: new Error("the call has no SFU app") }); + // the call came on, but neither its row nor its live state has reached the page yet + await using page = await drawCall(facet, async () => {}); + await act(async () => goIn(page.place).click()); + await act(() => + vi.waitFor(() => + expect(page.place.querySelector("[role=alert]")?.textContent).toBe("the call has no SFU app"), + ), + ); + // Join: the call is on, so a press joins and turns nothing on again + expect(goIn(page.place)).toBeTruthy(); +}); + +/** A mind whose logs are empty but for `logs`: what the page appends to a log is kept in + * `appended`, and the ephemeral events it sends (its `presence/status`) in `sent`. `pages`: the + * pages other members hold open on a context, by path, as its subscription rows and lent stubs. + * `hold()` keeps every read of a log unanswered until `release()`, and `holdKinds()` the read of + * the kinds until `releaseKinds()`. `kinds`: each kind's file in the config repo, by kind, each + * with `source`. Its root has `files`, and a context has none: only an iterate agent's context + * links to the root, and the page must not count on it. `row`: the name of the page's own row + * on a context, which the context answers (none: the page does not know it). `facets`: the + * processors each context hosts, by name, with each one's live state. What the page invokes on a + * context is kept in `invoked`, and each call of the call facet's methods, by method, in `steps`. */ +function mind({ + serves = [], + integrations, + kinds, + unreadable = false, + source = "export default {};", + logs = {}, + versions = {}, + pages = {}, + row, + facets = {}, +}: { + serves?: string[]; + integrations?: object; + kinds?: Record<string, string>; + /** the config repo refuses each read of a file, on a connection that is up */ + unreadable?: boolean; + /** the source of every kind's file */ + source?: string; + logs?: Record<string, { offset: number; type: string; payload: object; source?: object }[]>; + /** the version of a path that its pages say, and the offset where it started */ + versions?: Record<string, { version: number; startedAt: number }>; + pages?: Record<string, { name: string; principal: { actor: string; email: string } }[]>; + row?: string; + facets?: Record<string, Record<string, unknown>>; +}) { + const invoked: { path: string; call: unknown }[] = []; + const steps: string[] = []; + const appended: { path: string; events: unknown[] }[] = []; + const sent: { path: string; type: string }[] = []; + /** the path of each file whose URL the page asked the mind to sign */ + const signed: string[] = []; + /** each name a page lent a live stub under, and the context it lent it at */ + const lent: { path: string; match: string }[] = []; + /** the path of each agent the page started */ + const born: string[] = []; + let reads = 0; + let gate = Promise.resolve(); + let release = () => {}; + let kindsGate = Promise.resolve(); + let releaseKinds = () => {}; + let asked = 0; + /** each live callback a page subscribed, with its context's path */ + const rows: { path: string; target: (events: unknown[]) => void }[] = []; + const contextOf = (path: string) => ({ + readEvents: async (after = 0) => { + await gate; + const held = (logs[path] || []).map((event) => ({ ...event, path, createdAt: now })); + return { + events: held.filter((event) => event.offset > after), + atHead: true, + scannedThroughOffset: held.at(-1)?.offset || 0, + version: versions[path]?.version, + versionStartedAtOffset: versions[path]?.startedAt, + }; + }, + subscribe: async ({ target }: { target: (events: unknown[]) => void }) => { + rows.push({ path, target }); + return { name: row, [Symbol.dispose]() {} }; + }, + subscriptions: { + list: async () => [ + ...(pages[path] || []).map(({ name, principal }) => ({ + name, + target: `itx.builtins.rpcStubs.get('subscription:${name}')`, + consumes: ["*", "presence/status"], + configuredAtOffset: 1, + heldBy: { principal, via: { appPage: "dash" } }, + })), + ...Object.keys(facets[path] || {}).map((name) => ({ + name, + consumes: [], + configuredAtOffset: 1, + hostedFacet: { name, className: "Facet" }, + })), + ], + }, + rpcStubs: { list: async () => (pages[path] || []).map(({ name }) => `subscription:${name}`) }, + rewriteRules: { + list: async () => [ + { match: "itx.run", target: "itx.builtins.run" }, + { match: "itx.cd", target: "itx.builtins.cd" }, + ], + }, + provide: async (match: string) => { + lent.push({ path, match }); + return { [Symbol.dispose]() {} }; + }, + invoke: async (call: unknown) => { + invoked.push({ path, call }); + // a facet's method, as an expression: `["itx", "facets", ["get", name], [method, ...args]]` + if (Array.isArray(call)) { + const method = String(call[3][0]); + steps.push(method); + return method === "signal" ? { sdp: "v=0", tracks: [] } : {}; + } + const facet = /facets\.get\('([^']+)'\)\.liveSnapshot/.exec(String(call))?.[1]; + const state = path === "/integrations" ? integrations : facet && facets[path]?.[facet]; + return { rev: 1, state: state || {} }; + }, + append: async (...events: { type: string; ephemeral?: boolean }[]) => { + // an ephemeral event is never in a log + for (const event of events) if (event.ephemeral) sent.push({ path, type: event.type }); + const durable = events.filter((event) => !event.ephemeral); + if (durable.length > 0) appended.push({ path, events: durable }); + }, + [Symbol.dispose]() {}, + }); + const itx = { + kv: { + get: async (key: string) => { + await kindsGate; + return key === "agent-kinds" && kinds ? JSON.stringify(kinds) : null; + }, + }, + repos: { + get: () => ({ + readFile: async () => { + reads += 1; + if (unreadable) throw new Error("no such file"); + return kinds ? source : null; + }, + }), + }, + rewriteRules: { get: async (root: string) => (serves.includes(root) ? { target: "x" } : null) }, + whoami: async () => { + asked += 1; + return { principal: { actor: "/members/a", email: "jo@example.com" } }; + }, + agents: { + create: async (path: string) => void born.push(path), + get: () => ({ message: async () => {}, [Symbol.dispose]() {} }), + }, + cd: async (path: string) => contextOf(path), + files: { + get: (path: string) => ({ + url: async () => { + signed.push(path); + return { url: `https://files.example.com${path}` }; + }, + [Symbol.dispose]() {}, + }), + }, + } as unknown as DashPageProps["itx"]; + return { + itx, + invoked, + steps, + appended, + sent, + signed, + lent, + born, + reads: () => reads, + asked: () => asked, + /** A batch to every live callback of `path`, as the context delivers it. */ + push: (path: string, events: { offset: number; type: string; payload: object }[]) => { + for (const one of rows.filter((held) => held.path === path)) + one.target(events.map((event) => ({ ...event, path, createdAt: now }))); + }, + hold: () => { + gate = new Promise((resolve) => (release = resolve)); + }, + release: () => release(), + holdKinds: () => { + kindsGate = new Promise((resolve) => (releaseKinds = resolve)); + }, + releaseKinds: () => releaseKinds(), + }; +} + +/** Another member, whose page is open on the agent. */ +const memberB = { actor: "/members/b", email: "b@example.com" }; + +/** The call's live state, with each page in it (by its row) sending `tracks`. */ +function callLive(inCall: Record<string, string[]>) { + const who = (page: string) => + page === "a-page" + ? { actor: "/members/a", name: "jo@example.com" } + : { actor: memberB.actor, name: memberB.email }; + return { + since: 1, + inCall: Object.fromEntries( + Object.entries(inCall).map(([page, tracks]) => [ + page, + { who: who(page), tracks: Object.fromEntries(tracks.map((track) => [track, 1])) }, + ]), + ), + voiceAgent: null, + setup: null, + links: [], + }; +} + +/** A browser with a microphone, a camera, a screen, WebRTC and Web Audio, as far as the call's + * engine uses them: jsdom has none. Each connection is connected at once, over UDP straight to + * the SFU; while `receives` is false, a receiving connection never connects. `refuse`: the name + * of the error each open of a device throws. `replaceFails`: each sender refuses a new track. + * `hold(step)` keeps the next of these steps unanswered until `release()`: "open" (a device), + * "display" (the screen's picker), "replaceTrack", "setParameters", "offer" (any connection's). + * `refuseNext(name)`: the next open of a device throws an error of that name. `connections` holds every + * connection made (`fire(type, event)` gives it an event; each transceiver keeps its `track`), + * `opened` every track the browser opened, `mic` the first microphone's, `displays` how often the + * screen's picker was asked for, `contexts` every AudioContext, `play` the media elements' + * `play`. Disposing takes the devices back. */ +function browserMedia({ + receives = true, + refuse, + replaceFails = false, +}: { receives?: boolean; refuse?: string; replaceFails?: boolean } = {}) { + type Track = ReturnType<typeof trackOf>; + const connections: FakeConnection[] = []; + const opened: Track[] = []; + const contexts: { closed: boolean }[] = []; + const state = { receives, sends: true, displays: 0, refuseNext: "" }; + const gates = new Map<string, Promise<void>>(); + /** The next `step` waits while it is held. */ + const gate = async (step: string) => { + const held = gates.get(step); + gates.delete(step); + await held; + }; + const trackOf = (kind: "audio" | "video") => { + const track = { + kind, + enabled: true, + readyState: "live", + getSettings: () => ({ deviceId: "default", width: 1280 }), + addEventListener() {}, + removeEventListener() {}, + stop() { + track.readyState = "ended"; + }, + }; + return track; + }; + const streamOf = (tracks: Track[]) => ({ + getAudioTracks: () => tracks.filter((one) => one.kind === "audio"), + getVideoTracks: () => tracks.filter((one) => one.kind === "video"), + getTracks: () => tracks, + }); + Object.defineProperty(navigator, "mediaDevices", { + configurable: true, + value: { + getUserMedia: async (constraints: { audio?: object }) => { + await gate("open"); + const once = state.refuseNext; + state.refuseNext = ""; + if (once) throw Object.assign(new Error("refused"), { name: once }); + if (refuse) throw Object.assign(new Error("refused"), { name: refuse }); + const track = trackOf(constraints.audio ? "audio" : "video"); + opened.push(track); + return streamOf([track]); + }, + getDisplayMedia: async () => { + state.displays += 1; + await gate("display"); + const track = trackOf("video"); + opened.push(track); + return streamOf([track]); + }, + enumerateDevices: async () => [], + }, + }); + class FakeConnection { + closed = false; + connectionState = "connected"; + iceGatheringState = "complete"; + localDescription: { type: string; sdp: string } | null = null; + transceivers: { mid: string; stopped: boolean; track: Track }[] = []; + channels: { sent: string[] }[] = []; + listeners = new Map<string, ((event: object) => void)[]>(); + constructor() { + connections.push(this); + } + addEventListener(type: string, listener: (event: object) => void) { + this.listeners.set(type, [...(this.listeners.get(type) || []), listener]); + } + fire(type: string, event: object) { + for (const listener of this.listeners.get(type) || []) listener(event); + } + addTransceiver = (track: Track) => { + const transceiver = { + mid: String(this.transceivers.length), + stopped: false, + track, + sender: { + replaceTrack: async () => { + await gate("replaceTrack"); + if (replaceFails) throw new Error("the sender refused the track"); + }, + getParameters: () => ({ encodings: [] }), + setParameters: async () => gate("setParameters"), + }, + stop: () => void (transceiver.stopped = true), + }; + this.transceivers.push(transceiver); + return transceiver; + }; + addTrack() {} + createDataChannel = () => { + const channel = { readyState: "open", sent: [] as string[], addEventListener() {} }; + this.channels.push(channel); + return Object.assign(channel, { send: (message: string) => channel.sent.push(message) }); + }; + createOffer = async () => { + await gate("offer"); + return { type: "offer", sdp: "v=0" }; + }; + createAnswer = async () => { + if (!state.receives) this.connectionState = "new"; + return { type: "answer", sdp: "v=0" }; + }; + setLocalDescription = async (description: { type: string; sdp: string }) => { + this.localDescription = description; + }; + setRemoteDescription = async (description: { type: string }) => { + if (description.type === "answer" && !state.sends) this.connectionState = "new"; + }; + getConfiguration = () => ({}); + setConfiguration() {} + close() { + this.closed = true; + } + getStats = async () => + new Map<string, object>([ + ["t", { type: "transport", selectedCandidatePairId: "p" }], + ["p", { localCandidateId: "l", currentRoundTripTime: 0.02 }], + ["l", { candidateType: "host", protocol: "udp" }], + ]); + } + vi.stubGlobal("RTCPeerConnection", FakeConnection); + vi.stubGlobal( + "MediaStream", + class { + tracks: Track[]; + constructor(tracks: Track[] = []) { + this.tracks = tracks; + } + getTracks = () => this.tracks; + getAudioTracks = () => this.tracks.filter((one) => one.kind === "audio"); + }, + ); + vi.stubGlobal( + "AudioContext", + class { + closed = false; + constructor() { + contexts.push(this); + } + resume = async () => {}; + createMediaStreamDestination = () => ({ stream: streamOf([trackOf("audio")]) }); + createMediaStreamSource = () => ({ connect() {}, disconnect() {} }); + close = async () => void (this.closed = true); + }, + ); + const play = vi.spyOn(HTMLMediaElement.prototype, "play").mockImplementation(async () => {}); + vi.spyOn(HTMLMediaElement.prototype, "pause").mockImplementation(() => {}); + return { + connections, + opened, + contexts, + play, + get mic() { + return opened.find((one) => one.kind === "audio")!; + }, + get displays() { + return state.displays; + }, + set receives(on: boolean) { + state.receives = on; + }, + /** false: a sending connection made from here never connects. */ + set sends(on: boolean) { + state.sends = on; + }, + /** The next open of a device throws an error of this name. */ + refuseNext(name: string) { + state.refuseNext = name; + }, + hold(step: "open" | "display" | "replaceTrack" | "setParameters" | "offer") { + let release = () => {}; + gates.set(step, new Promise((resolve) => (release = resolve))); + return { release: () => release() }; + }, + [Symbol.dispose]: () => void Reflect.deleteProperty(navigator, "mediaDevices"), + }; +} + +/** The admission each call of `method` carried: a join's `{ admit }`, a refresh's `{ admission }`, + * or the last argument of a leave, a signal or a voice agent call. */ +function admissionsOf(facet: ReturnType<typeof callFacet>, method: string) { + return facet.calls + .filter((one) => one.method === method) + .map(({ args }) => { + const last = args.at(-1) as { admit?: string; admission?: string } | string | undefined; + return typeof last === "object" ? last.admit || last.admission : last; + }); +} + +/** An agent's call facet, as a page's context holds it: each method called, in `steps`, answers at + * once, or throws what `fails` names for it (`failNext(method, error)`: its next call alone); + * `calls` holds each with its arguments after the page. `hold(method)` keeps that method's next call + * unanswered until `release()`; `hold("signal", step)` the next signalling step of that kind + * ("publish", "reset", …). Each signalling step is in `signals`, by its first key, and the + * kind of each publish in `published`. A subscribe's answer puts each track under the mid + * `m-<track>`. */ +function callFacet(fails: Record<string, Error> = {}) { + const steps: string[] = []; + /** Each method called, with its arguments after the page. */ + const calls: { method: string; args: unknown[] }[] = []; + const signals: string[] = []; + const published: string[] = []; + const held = new Map<string, Promise<void>>(); + const once = new Map<string, Error>(); + const failingSteps = new Map<string, Error>(); + return { + steps, + calls, + /** The next call of `method` throws `error`. */ + failNext(method: string, error: Error) { + once.set(method, error); + }, + /** Every signalling step of this kind ("subscribe", …) throws `error` from now on. */ + failStep(step: string, error: Error) { + failingSteps.set(step, error); + }, + signals, + published, + hold(method: string, step?: string) { + let release = () => {}; + held.set(step ? `${method}:${step}` : method, new Promise((resolve) => (release = resolve))); + return { release: () => release() }; + }, + async invoke(call: unknown) { + const method = Array.isArray(call) ? String(call[3][0]) : ""; + steps.push(method); + if (Array.isArray(call)) calls.push({ method, args: call[3].slice(2) }); + const step = method === "signal" && Array.isArray(call) ? call[3][2] : {}; + if (method === "signal") signals.push(Object.keys(step)[0]!); + if (step.publish) published.push(step.publish); + for (const key of [method, `${method}:${Object.keys(step)[0]}`]) { + const gate = held.get(key); + held.delete(key); + await gate; + } + const failing = once.get(method); + once.delete(method); + if (failing) throw failing; + const stepFailing = method === "signal" && failingSteps.get(Object.keys(step)[0]!); + if (stepFailing) throw stepFailing; + if (fails[method]) throw fails[method]; + // each track subscribed to comes under the mid `m-<track>` + const tracks = (step.subscribe || []).map((track: string) => ({ track, mid: `m-${track}` })); + return method === "signal" ? { sdp: "v=0", tracks } : {}; + }, + }; +} + +/** The call's live state says this page is not in it, 6 s after its join: the page joins again. + * Answers the sync. */ +function outOfTouch(call: ReturnType<typeof engineOn>) { + const later = Date.now() + 6_000; + vi.spyOn(Date, "now").mockReturnValue(later); + return call.sync(viewOf(CallLive.parse(callLive({})), "a-page")); +} + +/** The call's engine for the page `a-page`, on `facet`. */ +function engineOn(facet: ReturnType<typeof callFacet>) { + return createCall({ + facet: (method, ...args) => facet.invoke(["itx", "facets", ["get", "call"], [method, ...args]]), + page: "a-page", + }); +} + +/** One agent page's call, on a wide screen (`narrow`: a phone's), as `a-page`, with no call on the + * agent: `enable` is what a start turns the call on with. `update` gives the page what the context + * says next: the call's row, its live state, the page's own row (a new one after a reconnect). `place` is the header's place for the controls, and `seen` the + * buttons it had at each moment after the first. */ +async function drawCall( + facet: ReturnType<typeof callFacet>, + enable: () => Promise<unknown>, + { narrow = false } = {}, +) { + vi.stubGlobal("matchMedia", (query: string) => ({ + matches: narrow, + media: query, + addEventListener() {}, + removeEventListener() {}, + })); + const host = document.body.appendChild(document.createElement("div")); + const place = host.appendChild(document.createElement("div")); + const seen: string[][] = []; + const watcher = new MutationObserver(() => seen.push(buttonsOf(place))); + watcher.observe(place, { + childList: true, + subtree: true, + characterData: true, + }); + const root = createRoot(host.appendChild(document.createElement("div"))); + const update = ({ + facetOn = false, + live, + row = "a-page", + }: { + facetOn?: boolean; + live?: object; + row?: string; + }) => + root.render( + <AgentCall + stub={facet} + context={{ + subscription: row, + processors: { + rows: facetOn ? [{ hostedFacet: { name: "call" } }] : [], + loaded: true, + }, + liveState: live ? { call: { value: live } } : {}, + }} + enable={enable} + barIn={place} + />, + ); + await act(async () => update({})); + return { + place, + seen, + update, + async [Symbol.asyncDispose]() { + watcher.disconnect(); + await act(async () => root.unmount()); + host.remove(); + }, + }; +} + +/** The text of every button in `element`, its title where it has one. */ +function buttonsOf(element: Element) { + return [...element.querySelectorAll("button")].map( + (one) => one.title || one.getAttribute("aria-label") || one.textContent?.trim() || "", + ); +} + +/** Share in the agent's header, once it can be pressed. */ +async function shareOf(host: Element) { + return await act(() => + vi.waitFor(() => { + const share = buttonOf( + host.querySelector("[data-page-header] [data-slot=agent-header-share]"), + "Share this agent", + ); + if (share.getAttribute("aria-disabled") === "true") throw new Error("Share waits"); + return share; + }), + ); +} + +/** Start call or Join call, out of the call, which a press takes in; throws while the page is in + * the call, or while the button cannot be pressed (a start under way, no call service). */ +function goIn(place: Element | null | undefined) { + if (place?.querySelector('[aria-label="Leave the call"]')) throw new Error("in the call"); + const button = goInOf(place); + if (button.getAttribute("aria-disabled") === "true") throw new Error("the button waits"); + return button; +} + +/** Start call or Join call; throws while there is none. */ +function goInOf(place: Element | null | undefined) { + const button = place?.querySelector<HTMLButtonElement>("button[data-slot=call-go-in]"); + if (!button) throw new Error("no Start call or Join call"); + return button; +} + +/** The page is in the call, and its switch `label` is on; throws while the page is out of it. */ +function isOn(place: Element | null | undefined, label: string) { + buttonOf(place, "Leave the call"); + return buttonOf(place, label).getAttribute("aria-pressed") === "true"; +} + +/** The row waits: out of the call, and Start call or Join call cannot be pressed. */ +function waits(place: Element | null | undefined) { + return ( + !place?.querySelector('[aria-label="Leave the call"]') && + goInOf(place).getAttribute("aria-disabled") === "true" + ); +} + +/** The button in `element` whose words or title say `text`; throws while there is none. */ +/** The lobby that a Join or a Start opened (a dialog, on the body): its main button, pressed once + * the microphone it opens by itself is open (`mic`), or at once. */ +async function pressInLobby({ mic = true, text }: { mic?: boolean; text?: string } = {}) { + const lobby = await act(() => + vi.waitFor(() => { + const found = document.body.querySelector("[data-slot=call-lobby]"); + if (!found) throw new Error("no lobby"); + if (mic && !found.querySelector("[aria-label=Microphone][aria-pressed=true]")) + throw new Error("the lobby's microphone is not open yet"); + return found; + }), + ); + const button = text + ? buttonOf(lobby, text) + : [...lobby.querySelectorAll("button")].find((one) => + ["Join now", "Start the call"].includes(one.textContent?.trim() ?? ""), + ); + if (!button) throw new Error("no Join now in the lobby"); + await act(async () => button.click()); +} + +function buttonOf(element: Element | null | undefined, text: string) { + const found = [...(element?.querySelectorAll("button") || [])].find( + (one) => + one.title === text || + one.getAttribute("aria-label") === text || + one.textContent?.trim() === text, + ); + if (!found) throw new Error(`no button "${text}"`); + return found; +} + +/** The member every page signs in as, unless a test says another. */ +const member = { mind: "iterate.example.com", actor: "/members/a" }; + +/** The catalog with one Claude agent at `path`. */ +function claudeRows(path: string) { + return agentRowsOf({ agents: { [path]: { createdAt: now, kind: "claude" } } }); +} + +/** Something a person said in a chat, at `offset`. */ +function words(offset: number, content: string) { + return { + offset, + type: "events.iterate.com/agent/context-added", + payload: { role: "user", content }, + }; +} + +/** The kernel's border of a version of `path`, from `offset`: the earlier version's end, and the + * `itx/created` of `version`. */ +function borderOf(path: string, offset: number, version: number) { + return [ + { + offset, + type: "events.iterate.com/itx/started-over", + payload: { version: version - 1 }, + }, + { offset: offset + 1, type: "events.iterate.com/itx/created", payload: { path, version } }, + ]; +} + +/** A first visit to the Claude agent at `path`, whose kind's file has `source`: the page works out + * its view and keeps it. jsdom loads no frame, so the frame's read never starts and saves no + * rows: the rows it would have shown are saved here. */ +async function rememberKindView(path: string, source: string) { + history.replaceState(null, "", `/agents${path}`); + const { itx } = mind({ kinds: { claude: "agent-kinds/claude.ts" }, source }); + { + await using first = await draw(DashAgents, itx, { waiting: 0, agents: claudeRows(path) }); + expect(first.host.querySelector("iframe")).not.toBe(null); + } + savedLogTails(member).save(path, [{ ...words(1, "Hello"), createdAt: now }], true, 1); +} + +/** A page with height, which jsdom lacks, so the chat's virtual log draws its rows; disposing takes + * it back. */ +function laidOut() { + const sizes = { clientHeight: 600, offsetHeight: 0 }; + const own = Object.keys(sizes).map( + (name) => [name, Object.getOwnPropertyDescriptor(HTMLElement.prototype, name)] as const, + ); + for (const [name, value] of Object.entries(sizes)) + Object.defineProperty(HTMLElement.prototype, name, { configurable: true, get: () => value }); + return { + [Symbol.dispose]: () => { + for (const [name, descriptor] of own) + if (descriptor) Object.defineProperty(HTMLElement.prototype, name, descriptor); + // the cast: the prototype's own keys are not indexable by a string in its type + else delete (HTMLElement.prototype as unknown as Record<string, unknown>)[name]; + }, + }; +} + +/** Words into a composer as a paste puts them in the editor (jsdom has no DataTransfer), then a + * press of Send. */ +async function pasteAndSend(host: HTMLElement, composer: Element, words: string) { + const paste = new Event("paste", { bubbles: true, cancelable: true }); + Object.defineProperty(paste, "clipboardData", { + value: { + files: [], + items: [{ kind: "string", type: "text/plain", getAsFile: () => null }], + getData: (format: string) => (format === "text/plain" ? words : ""), + }, + }); + await act(async () => composer.dispatchEvent(paste)); + const send = host.querySelector<HTMLButtonElement>('button[title="Send message"]'); + await act(async () => send!.click()); +} + +/** THE FRAME'S SIDE OF A STARTER FRAME, as frame.ts plays it: it says it is ready, takes the + * page's port, reports the kind's `newAgent`, and answers `start`. jsdom runs no frame script. */ +async function starterFrame( + iframe: HTMLIFrameElement, + kind: { + newAgent: AgentKindNewAgentSummary | undefined; + start: (input: { choice: string; fields: Record<string, string>; path: string }) => unknown[]; + }, +) { + const window = iframe.contentWindow!; + const port = new Promise<MessagePort>((resolve) => { + // the cast: the page calls `postMessage(hello, "*", [port])`, the overload the spy's type omits + vi.spyOn(window, "postMessage").mockImplementation((...args: unknown[]) => + resolve((args[2] as MessagePort[])[0]!), + ); + }); + globalThis.dispatchEvent( + new MessageEvent("message", { source: window, data: { type: AGENT_KIND_VIEW_READY } }), + ); + class Frame extends RpcTarget { + update() {} + start(input: Parameters<typeof kind.start>[0]) { + return kind.start(input); + } + } + const host = newMessagePortRpcSession<AgentKindViewHostApi>(await port, new Frame()); + await host.loaded({ ephemeralEvents: [], newAgent: kind.newAgent }); +} + +/** The new-agent composer of a drawn page. Its editor is a part that loads after the page drew, + * so this waits for the element, not for a time. */ +function composerOf(host: HTMLElement) { + return act(() => + vi.waitFor(() => { + const composer = host.querySelector('[aria-label="Message a new agent"], [data-placeholder]'); + expect(composer).not.toBe(null); + return composer; + }), + ); +} + +async function draw( + Page: (props: DashPageProps) => ReactNode, + itx: DashPageProps["itx"], + { + waiting, + openers, + presence, + call, + share, + pageTools, + agents: first = agents, + account = true, + actor = "/members/a", + mindFace, + }: { + /** The Dash's name and logo of the mind; absent: the page names it by its hostname. */ + mindFace?: DashPageProps["mindFace"]; + /** How many requests wait; undefined: the count is not known yet. */ + waiting: number | undefined; + /** false: the Dash has not heard yet who is signed in */ + account?: boolean; + /** the member signed in */ + actor?: string; + openers?: Record<string, string>; + /** The Agents page's `presence`: a member's open agent page shows who else is here. */ + presence?: boolean; + /** The Agents page's `call`. */ + call?: DashPage["call"]; + /** The Agents page's `share`. */ + share?: DashPage["share"]; + /** The Agents page's `pageTools`. */ + pageTools?: DashPage["pageTools"]; + /** The catalog of the mind's agents; "unread": it has not answered yet. */ + agents?: typeof agents | "unread"; + }, +) { + vi.stubGlobal("matchMedia", (query: string) => ({ + matches: false, + media: query, + addEventListener() {}, + removeEventListener() {}, + })); + vi.stubGlobal("fetch", async () => Response.json({ minds: [], lastUsed: null })); + vi.stubGlobal( + "ResizeObserver", + class { + observe() {} + unobserve() {} + disconnect() {} + }, + ); + const row = (id: string): DashPage => ({ id, name: id, icon: BotIcon, component: () => null }); + const pages = [ + row("home"), + { ...row("agents"), openers, presence, call, share, pageTools }, + row("contexts"), + row("integrations"), + ]; + const host = document.body.appendChild(document.createElement("div")); + // every text the page showed, at any moment + const said: string[] = []; + const watcher = new MutationObserver(() => said.push(host.textContent || "")); + watcher.observe(host, { childList: true, subtree: true, characterData: true }); + const root = createRoot(host); + const settle = async () => { + // the page's parts load, its reads answer, and the chat reads the log + for (let round = 0; round < 200 && host.textContent?.includes("Loading the page…"); round++) + await act(() => new Promise((resolve) => setTimeout(resolve, 20))); + // the log is published at most once a frame + for (let round = 0; round < 10; round++) + await act(() => new Promise((resolve) => setTimeout(resolve, 20))); + }; + const drawWith = async (rows: typeof agents | undefined) => { + await act(() => + root.render( + <AppShell app="Dash" mind="iterate.example.com" account={null} locationKey="/"> + <Suspense fallback="Loading the page…"> + <Page + itx={itx} + mind="iterate.example.com" + mindFace={mindFace} + principal={account ? { actor, email: "jo@example.com" } : undefined} + page={pages[1]!} + pages={pages} + links={[]} + catalog={undefined} + agents={rows} + waiting={waiting} + /> + </Suspense> + </AppShell>, + ), + ); + await settle(); + }; + await drawWith(first === "unread" ? undefined : first); + return { + host, + said, + /** Draw again with the catalog's answer. */ + draw: drawWith, + settle, + [Symbol.asyncDispose]: async () => { + watcher.disconnect(); + await act(() => root.unmount()); + host.remove(); + }, + }; +} + +/** The devices opened, and a mark for each sender of each connection: a join on arrival has none. */ +function capturedNothing(media: ReturnType<typeof browserMedia>) { + return { + opened: media.opened.map((track) => track.kind), + tracksSent: media.connections.flatMap((connection) => + connection.transceivers.map(() => "a track"), + ), + }; +} + +/** The call's refusal of a signalling step whose SFU session is gone (call/rules.ts). */ +function sessionEnded() { + return codedError( + "CALL_SESSION_ENDED", + "The SFU answered 410 to POST /sessions/…/tracks/new: Session appears to be disconnected.", + ); +}
A src/agent-kind-view/dash-agents.tsx
@@ -0,0 +1,1191 @@ +// dash-agents.tsx — THE DASH'S AGENT PAGES, for a mind's own no-build Dash: rows of its `pages` +// (components/dash/dash.tsx), with the Dash's props (`DashPageProps`). +// +// DashHome a composer that starts a new agent, what waits for the member, and the agents +// active most recently. +// DashAgents the Agents page (its row's id is `agents`): the composer and every agent, or, with +// `/agents/<path>`, ANY context seen as an agent. iterate's own agents are its chat +// (`AgentChat`); an agent of a kind with a file of its own (`agent-kinds/<kind>.ts` +// in the config repo) is that kind's view, in a sandboxed frame (./host.ts). Its +// header is the kit's one row (components/agent-chat/agent-page-header.tsx): the +// agent's title and path, who is here and can use the conversation (the mind's +// face first, always; the people with presence on), the call's controls (with +// `call` on: ./dash-call.tsx, an iterate agent's chat alone), Share (with `share` +// on), and Chat | Events. The row's `openers` are what the mind says first in an +// empty chat. +// +// They live here, out of the shadcn registry, because they host kinds' frames: a registry item may +// not import this folder. Each loads its larger part when it first draws (the composer, the chat), +// and reads the kinds once for the page's life: which kind has which file (the mind's KV, +// `agent-kinds`, which worker.ts writes at every publish), and each file's source. +import { + createContext, + Suspense, + use, + useCallback, + useEffect, + useMemo, + useState, + useSyncExternalStore, + type ComponentProps, +} from "react"; +import { ShieldAlertIcon, TriangleAlertIcon } from "lucide-react"; +import { z } from "zod"; +import type { AuthenticatedApp } from "iterate/app"; +import { facetSnapshotOf } from "iterate/react"; +import type { AgentKindViewInputs, AgentKindViewLoaded } from "./bridge.ts"; +import { + appendEvents, + appendTo, + fileUrl, + messageAgent, + storeAgentFiles, + widgetCallsOf, + withAgents, +} from "./dash-agent-calls.ts"; +import { + AgentKindStarterFrame, + AgentKindViewFrame, + AgentKindViewLink, + useAgentKindViewLink, + type AgentKindViewVerbs, +} from "./host.ts"; +import { + defaultKindCandidates, + defaultKindOf, + newAgentStartOf, + sendFirstMessage, + type DefaultKind, + type KindFile, + type KindStarter, +} from "./default-kind.ts"; +import { useHeldContext } from "#/hooks/use-itx-session.ts"; +import { useHasSavedTail, useSavedContext, type TailsOfMember } from "#/lib/saved-context.ts"; +import { AgentChatState } from "#/components/agent-chat/agent-chat-search.ts"; +import { AgentReading } from "#/components/agent-chat/agent-reading.tsx"; +import { + AgentPageHeader as AgentPageHeaderOfKit, + heldRowsOf, + type AgentPageHeaderProps, + type MindFace, +} from "#/components/agent-chat/agent-page-header.tsx"; +import { + DashNote, + DashScroll, + type DashCall, + type DashPage, + type DashPageProps, + type DashShare, +} from "#/components/dash/dash.tsx"; +import { agentViewHref } from "#/components/dash/dash-href.ts"; +import { servesOf } from "#/components/dash/serves.ts"; +import { + agentGroups, + draftOfAddress, + findAgents, + newAgentPath, + personOf, + type AgentRow, +} from "#/lib/agent-summary.ts"; +import { itxSessionOf, keptRead, versionOf, type KeptRead } from "#/lib/itx-session.ts"; +import { sameView, savedLogTails, type SavedView } from "#/lib/saved-log-tail.ts"; +import { go, hrefOf, linkTo, pageHref, usePageParam, useView } from "#/lib/page-url.ts"; + +type Itx = AuthenticatedApp["itx"]; + +/** A module, imported the first time a page asks for it and kept: the same promise after. */ +function once<T>(load: () => Promise<T>) { + let loading: Promise<T> | undefined; + return () => (loading ||= load()); +} + +const homePart = once(() => import("#/components/agents-home.tsx")); +const chatPart = once(() => import("#/components/agent-chat/agent-chat.tsx")); +// only where the Agents page's row turns the page's tools on +const toolsPart = once(() => import("#/components/page-tools.tsx")); +// only where the Agents page's row turns calls on: the call's view, who is in it, and Share +const callPart = once(async () => { + // the two modules load at once + const people = import("./call-presence.ts"); + const share = import("./dash-share.tsx"); + const { AgentCall } = await import("./dash-call.tsx"); + const { inCallOf } = await people; + const { AgentShare } = await share; + return { AgentCall, AgentShare, inCallOf }; +}); + +// ── the kinds ── + +const KindPaths = z.record(z.string(), z.string()); + +/** Every kind's file, read once for the page's life, whoever asks: one promise at every render. + * No key, or a key that is not JSON, is no kind, and a file that cannot be read has no source. + * Those answers stand. They are read again only when the session they failed with was gone and a + * new one has opened (`keptRead`). */ +const kindFiles = new WeakMap<object, KeptRead<KindFile[]>>(); +/** What each read of the kinds answered, once it has: a view that is drawn already reads it + * without suspending. */ +const answeredKinds = new WeakMap<Promise<KindFile[]>, KindFile[]>(); +function kindFilesOf(itx: Itx): Promise<KindFile[]> { + const files = keptRead(itx, kindFiles.get(itx), (failed) => + (async () => { + const forget = () => { + failed(); + return null; + }; + const text = await Promise.resolve(itx.kv.get("agent-kinds")).catch(forget); + let paths: Record<string, string> = {}; + try { + paths = KindPaths.safeParse(JSON.parse(text || "{}")).data || {}; + } catch { + // not JSON: no kind has a file + } + const config = itx.repos.get("/repos/config"); + return await Promise.all( + Object.entries(paths).map(async ([kind, name]) => ({ + kind, + name, + source: await Promise.resolve(config.readFile(name)).then( + (source) => source || null, + forget, + ), + })), + ); + })(), + ); + // a new read: its answer is kept for the renders that do not suspend on it + if (files !== kindFiles.get(itx)) + files.answer.then( + (kinds) => void answeredKinds.set(files.answer, kinds), + () => {}, + ); + kindFiles.set(itx, files); + return files.answer; +} + +/** The kinds of `itx`, or undefined while they are read. Never suspends: the view drawn from what + * the page remembered stays the same element when they come. */ +function useKindFiles(itx: Itx) { + const files = kindFilesOf(itx); + const subscribe = useCallback( + (changed: () => void) => { + let current = true; + // a read that fails is `use`'s to throw: here it only leaves the view as it is + files.then( + () => { + if (current) changed(); + }, + () => {}, + ); + return () => { + current = false; + }; + }, + [files], + ); + return { files, kinds: useSyncExternalStore(subscribe, () => answeredKinds.get(files)) }; +} + +/** THE KIND FRAME'S SCRIPT: one classic file of the build of this package that the page's import + * map pins, named by its place in the package. `?raw` asks the module server for the file as it + * is, not a module that wraps it. Read once. */ +let frameScript: string | undefined; +function frameScriptOfPage(): string { + if (!frameScript) { + const map = ImportMap.safeParse( + JSON.parse(document.querySelector('script[type="importmap"]')?.textContent || "{}"), + ); + frameScript = `${map.data?.imports["@iterate-com/ui/"] || "/"}dist/agent-kind-view-frame.js?raw`; + } + return frameScript; +} +const ImportMap = z.object({ imports: z.record(z.string(), z.string()) }); + +// ── the pages ── + +/** THE HOME: a composer whose first message starts a new agent, what waits for the member, and + * the agents active most recently. */ +export function DashHome({ itx, mind, principal, pages, agents, waiting }: DashPageProps) { + const { RecentAgents } = use(homePart()); + const links = useAgentLinks(pages); + return ( + <DashScroll> + <div className="mx-auto flex w-full max-w-3xl flex-col gap-8 px-4 pt-8 pb-12 md:px-8 md:pt-16"> + <NewAgent itx={itx} principal={principal} links={links} /> + <NeedsYou itx={itx} mind={mind} pages={pages} waiting={waiting} /> + {agents ? ( + // the most recently active, whoever's: no person's agents first + <RecentAgents agents={agents} {...links} /> + ) : ( + <DashNote waiting>Reading the agents…</DashNote> + )} + </div> + </DashScroll> + ); +} +// holds nothing of a session: the composer's draft stays over a new one +DashHome.staysOverReconnect = true; + +/** THE AGENTS PAGE: every agent, or one context as an agent (`/agents/<path>`). */ +export function DashAgents(props: DashPageProps) { + const path = usePageParam("agent"); + if (path) return <AgentView key={path} {...props} path={path} />; + return <AgentsOverview {...props} />; +} +// an agent view holds its context with `useHeldContext` and keeps its rows (`useSavedContext`) +DashAgents.staysOverReconnect = true; + +function AgentsOverview({ itx, principal, pages, agents }: DashPageProps) { + const { AllAgents } = use(homePart()); + const links = useAgentLinks(pages); + const now = useNow(5_000); + // the agents, not their folders: the count the palette and the list show + const count = useMemo(() => agents && findAgents(agents, "").length, [agents]); + // the list that is drawn: an agent at the top for each row, so folders alone draw none + const groups = useMemo(() => agents && agentGroups(agents), [agents]); + return ( + <div className="flex min-h-0 flex-1 flex-col"> + <div className="mx-auto flex w-full max-w-3xl flex-col gap-6 px-4 pt-8 md:px-8"> + <header className="flex items-baseline justify-between gap-3"> + <h1 className="text-2xl font-semibold tracking-tight">Agents</h1> + <span className="text-sm text-muted-foreground tabular-nums"> + {count === undefined + ? "" + : `${count.toLocaleString("en")} ${count === 1 ? "agent" : "agents"}`} + </span> + </header> + <NewAgent itx={itx} principal={principal} links={links} /> + <h2 className="text-sm font-medium text-muted-foreground">Most recently active</h2> + </div> + {!agents || !groups ? ( + <DashNote waiting>Reading the agents…</DashNote> + ) : groups.length ? ( + <AllAgents agents={agents} nowMs={now} className="pb-8" {...links} /> + ) : ( + <p className="mx-auto w-full max-w-3xl px-4 font-readme text-sm text-muted-foreground md:px-8"> + No agents yet. Say something above to start one. + </p> + )} + </div> + ); +} + +/** Where an agent's view is (the Agents page for none), and the in-page way to go there. */ +function useAgentLinks(pages: DashPage[]) { + const overview = pages.find((row) => row.id === "agents")?.id; + return useMemo(() => { + const agentHref = (path: string | undefined) => + path ? agentViewHref(path) : pageHref(overview); + return { agentHref, onOpen: (path: string | undefined) => go(agentHref(path)) }; + }, [overview]); +} + +// ── a new agent ── + +/** THE COMPOSER whose first message starts a new agent, in the folder of the person signed in: an + * iterate agent, or an agent of the mind's default kind (default-kind.ts). While the Dash does + * not know yet who that is (`principal` undefined), a first message asks the mind before the + * agent is born: no agent lands outside its person's folder because the page drew before the + * account was there. */ +function NewAgent({ + itx, + principal, + links, +}: { + itx: Itx; + principal: DashPageProps["principal"]; + links: ReturnType<typeof useAgentLinks>; +}) { + const { NewAgentComposer } = use(homePart()); + const { frames, resolve, chosen } = useDefaultKind(itx); + // the draft that the address brought (`#draft=`), read once: the box holds it, unsent + const [initialDraft] = useState(() => draftOfAddress(globalThis.location?.hash)); + return ( + <> + {frames} + <NewAgentComposer + initialDraft={initialDraft} + person={ + // oxlint-disable-next-line iterate/simple-truthiness-check -- undefined is not known yet, null is signed in as someone with no address + principal === undefined + ? async () => personOf((await itx.whoami()).principal?.email) + : personOf(principal?.email) + } + pathFor={async (person, date) => { + const found = await resolve(); + if (!found) return newAgentPath("web", date, person); + const start = newAgentStartOf(found, person, date); + chosen.set(start.path, { found, start }); + return start.path; + }} + onCreate={async (path) => { + const kind = chosen.get(path); + if (!kind) return await withAgents(itx).agents.create(path); + await appendTo(itx, path, await kind.found.starter.start(kind.start)); + }} + onMessage={(path, { message, files }) => + chosen.has(path) + ? sendFirstMessage( + path, + { message, files }, + { + storeFiles: (at, stored) => storeAgentFiles(itx, at, stored), + append: (at, events) => appendTo(itx, at, events), + }, + ) + : messageAgent(itx, path, { message, files }) + } + {...links} + /> + </> + ); +} + +/** THE MIND'S DEFAULT KIND, for New agent: a hidden starter frame for each kind file that may be + * it (default-kind.ts), the way to find it when a first message is sent, and the kind each new + * path was born of. A link is kept for each file and source, so its frame loads once. */ +function useDefaultKind(itx: Itx) { + const { files, kinds } = useKindFiles(itx); + const [links] = useState(() => new Map<string, AgentKindViewLink>()); + const [chosen] = useState( + () => new Map<string, { found: DefaultKind; start: ReturnType<typeof newAgentStartOf> }>(), + ); + const linkOf = useCallback( + (file: KindFile) => { + const key = `${file.name}\n${file.source || ""}`; + const held = links.get(key); + if (held) return held; + const link = new AgentKindViewLink(file.name, file.source); + links.set(key, link); + return link; + }, + [links], + ); + const candidates = useMemo(() => defaultKindCandidates(kinds || []), [kinds]); + const frames = candidates.map((file) => ( + <AgentKindStarterFrame key={file.name} link={linkOf(file)} frameScript={frameScriptOfPage()} /> + )); + const resolve = useCallback(async () => { + const read = await files.catch((): KindFile[] => []); + return defaultKindOf(defaultKindCandidates(read).map((file) => starterOf(file, linkOf(file)))); + }, [files, linkOf]); + return { frames, resolve, chosen }; +} + +/** A starter frame's link as default-kind.ts reads it. */ +function starterOf(file: KindFile, link: AgentKindViewLink): KindStarter { + return { + file, + loaded: link.loaded, + subscribe: link.subscribe, + start: (input) => link.start(input), + }; +} + +// ── what waits for the member ── + +/** What needs the member, in a place of one height while it is read: the requests that wait for + * their yes (the count the Dash keeps), and each integration whose status asks for them. */ +function NeedsYou({ + itx, + mind, + pages, + waiting, +}: Pick<DashPageProps, "itx" | "mind" | "pages" | "waiting">) { + // read once when the home draws + const [integrations] = useState(() => integrationsNeedingYou(itx)); + const integrationsPage = pages.find((row) => row.id === "integrations"); + return ( + // one row's room, kept while it is read: the list under it does not move for one thing + <section aria-labelledby="needs-you" className="flex min-h-22 flex-col gap-3"> + <h2 id="needs-you" className="text-sm font-medium text-muted-foreground"> + Waiting for you + </h2> + <Suspense fallback={<Looking />}> + <NeedsYouRows + integrations={integrations} + approvals={waiting} + approvalsHref={`https://${mind}/secrets/approvals`} + integrationsHref={integrationsPage && pageHref(integrationsPage.id)} + /> + </Suspense> + </section> + ); +} + +/** The line in the section's place while it is read. */ +function Looking() { + return <p className="font-readme text-sm text-muted-foreground">Looking…</p>; +} + +function NeedsYouRows({ + integrations, + approvals, + approvalsHref, + integrationsHref, +}: { + integrations: Promise<Attention[]>; + /** Undefined until the mind has answered: nothing is said of what waits before that. */ + approvals: number | undefined; + approvalsHref: string; + integrationsHref: string | undefined; +}) { + const asking = use(integrations); + if (approvals === undefined) return <Looking />; + if (!approvals && !asking.length) + return <p className="font-readme text-sm text-muted-foreground">Nothing waits for you.</p>; + return ( + <ul className="flex flex-col gap-2"> + {approvals ? ( + <NeedsYouRow + href={approvalsHref} + icon={<ShieldAlertIcon aria-hidden className="size-4 shrink-0 text-warning" />} + title={ + approvals === 1 + ? "1 request waits for your yes" + : `${String(approvals)} requests wait for your yes` + } + text="Your agents wait until you answer." + /> + ) : null} + {asking.map((item) => ( + <NeedsYouRow + key={item.key} + href={integrationsHref} + inPage + icon={ + <TriangleAlertIcon + aria-hidden + className={ + item.kind === "error" + ? "size-4 shrink-0 text-destructive" + : "size-4 shrink-0 text-warning" + } + /> + } + title={item.title} + text={item.text} + /> + ))} + </ul> + ); +} + +function NeedsYouRow({ + href, + inPage, + icon, + title, + text, +}: { + href: string | undefined; + inPage?: boolean; + icon: ComponentProps<"span">["children"]; + title: string; + text: string | undefined; +}) { + const body = ( + <> + {icon} + <span className="flex min-w-0 flex-col"> + <span className="truncate text-sm font-medium">{title}</span> + {text ? <span className="truncate text-xs text-muted-foreground">{text}</span> : null} + </span> + </> + ); + const look = "flex items-center gap-3 rounded-lg border px-3 py-2"; + return ( + <li> + {href ? ( + <a + {...(inPage ? linkTo(href) : { href })} + className={`${look} text-inherit no-underline hover:bg-muted/60`} + > + {body} + </a> + ) : ( + <div className={look}>{body}</div> + )} + </li> + ); +} + +/** An integration, or one connection of it, whose status asks for the member. */ +type Attention = { + key: string; + title: string; + text: string | undefined; + kind: "attention" | "error"; +}; + +const Status = z.object({ + kind: z.enum(["ok", "attention", "error"]), + text: z.string().optional(), +}); +const Registry = z.object({ + integrations: z + .record(z.string(), z.looseObject({ title: z.string(), status: Status.optional() })) + .catch({}) + .default({}), + connections: z + .record(z.string(), z.looseObject({ account: z.string(), status: Status.optional() })) + .catch({}) + .default({}), +}); + +/** The integrations whose card or connection says "attention" or "error", from one read of the + * registry on `/integrations` (the `integration` facet's snapshot). A mind without integrations, + * or a read that fails, has none. */ +async function integrationsNeedingYou(itx: Itx): Promise<Attention[]> { + try { + if (!(await servesOf(itx, "integrations"))) return []; + const registry = await itx.cd("/integrations"); + let state: unknown; + try { + state = (await facetSnapshotOf(registry, "integration")).state; + } finally { + registry[Symbol.dispose](); + } + const { integrations, connections } = Registry.parse(state); + const cards = Object.entries(integrations).flatMap(([name, card]) => + card.status && card.status.kind !== "ok" + ? [{ key: name, title: card.title, text: card.status.text, kind: card.status.kind }] + : [], + ); + const rows = Object.entries(connections).flatMap(([key, row]) => { + const card = integrations[key.split("/")[0]!]; + return row.status && row.status.kind !== "ok" + ? [ + { + key, + title: `${card?.title || key.split("/")[0]}: ${row.account}`, + text: row.status.text, + kind: row.status.kind, + }, + ] + : []; + }); + return [...cards, ...rows]; + } catch { + return []; + } +} + +// ── one context as an agent ── + +/** ANY CONTEXT AS AN AGENT. Its header is one row: the agent's title and path, and Chat | Events, + * which the view under it draws no strip for (its status is a line at the feed's foot). What + * draws it is its kind's: iterate's chat, or a kind's own view in a frame. One loading state + * stands from the first paint to the view's own, under a header of the same shape whose tabs + * cannot be pressed yet: the kinds, the catalog and the chat's part are all read behind it. When + * the member's store remembers the view that drew the saved rows, that view is drawn at once, + * and the kinds and the catalog only correct it. */ +function AgentView({ + itx, + mind, + mindFace, + principal, + page, + agents, + path, +}: DashPageProps & { path: string }) { + // the mind's own face in the header, named by its hostname where the Dash has no name for it + const face = useMemo(() => mindFace || { name: mind }, [mindFace, mind]); + // the member's saved rows, once the mind has said who the member is: none are read or saved + // before, so one member never sees another's + // not known yet who that is: the store is pending, and the view's read waits for it + const tails: TailsOfMember = + // oxlint-disable-next-line iterate/simple-truthiness-check -- undefined is not known yet; null is a member the page cannot name + principal === undefined + ? "pending" + : principal?.actor + ? savedLogTails({ mind, actor: principal.actor }) + : undefined; + // Saved rows of this log wait for the view: the page then says nothing of a read, because + // none holds the reader up. It says so only once the store has answered that it has none. + const saved = useHasSavedTail(tails, path); + const quiet = saved !== false; + // The view that drew the saved rows, from the member's own store alone. The store has answered + // when `saved` is known, so its memory holds the view. + const remembered = saved && tails && tails !== "pending" ? tails.peek(path)?.view : undefined; + return ( + <PageMind value={face}> + <Suspense + fallback={ + <AgentPageReading + path={path} + agents={agents} + quiet={quiet} + presence={Boolean(page.presence)} + call={Boolean(page.call)} + share={Boolean(page.call && page.share)} + /> + } + > + <AgentViewOfKind + itx={itx} + path={path} + agents={agents} + opener={page.openers?.[path]} + presence={Boolean(page.presence)} + call={page.call} + share={page.call ? page.share : undefined} + me={principal?.actor} + tails={tails} + quiet={quiet} + remembered={remembered} + /> + </Suspense> + {page.pageTools && principal ? ( + <AgentPageTools + itx={itx} + path={path} + me={principal} + agent={ + agents?.find((row) => row.path === path)?.title || + path.split("/").findLast(Boolean) || + path + } + tools={page.pageTools === true ? undefined : page.pageTools.tools} + /> + ) : null} + </PageMind> + ); +} + +/** The tools this page lends the agent it shows (the Agents page's `pageTools`). They load beside + * the chat and never hold it up: their part is asked for after the page has drawn, and a part + * that does not load lends nothing and says so in the console. `open(path)` changes the Dash's + * page in place. */ +function AgentPageTools(props: Omit<ComponentProps<PageToolsPart["PageTools"]>, "onOpen">) { + const [part, setPart] = useState<PageToolsPart>(); + useEffect(() => { + toolsPart().then(setPart, (error: unknown) => + console.error({ + event: "page-tools.load-failed", + message: error instanceof Error ? error.message : String(error), + }), + ); + }, []); + return part ? <part.PageTools {...props} onOpen={go} /> : null; +} +type PageToolsPart = Awaited<ReturnType<typeof toolsPart>>; + +/** The mind of the agent page: the first face of the stack of who is here, in its header and in + * the chat's. */ +const PageMind = createContext<MindFace | undefined>(undefined); + +/** The kit's agent page header, with the mind's face. */ +function AgentPageHeader(props: Omit<AgentPageHeaderProps, "mind">) { + return <AgentPageHeaderOfKit {...props} mind={use(PageMind)} />; +} + +/** The page while it does not know yet which view the agent has: the header, and the chat's + * loading line where the first row will stand. */ +function AgentPageReading({ + path, + agents, + quiet, + presence, + call, + share, +}: { + path: string; + agents: readonly AgentRow[] | undefined; + /** Saved rows wait for the view: no loading line (`AgentReading`). */ + quiet: boolean; + /** The header keeps the place of who is here and can use the conversation. */ + presence: boolean; + /** The header draws the call's controls, which cannot be pressed yet. */ + call: boolean; + /** The header draws Share, which cannot be pressed yet. */ + share: boolean; +}) { + return ( + <> + <AgentPageHeader path={path} agents={agents} presence={presence} call={call} share={share} /> + <AgentReading strip={false} quiet={quiet} /> + </> + ); +} + +/** The view of the agent's kind. With none remembered, none until the catalog has said the kind: + * iterate's chat over the log of another kind holds no row, and would say that nothing was said. + * A remembered view is drawn at once, and stays the same element when the kinds and the catalog + * say the same view; when they say another, that one is mounted in its place. A path that the + * catalog does not list draws as iterate's. */ +function AgentViewOfKind({ + itx, + path, + agents, + opener, + presence, + call, + share, + me, + tails, + quiet, + remembered, +}: Pick<DashPageProps, "itx" | "agents"> & { + path: string; + opener: string | undefined; + /** The page shows who else has the agent's conversation open (the Agents page's `presence`). */ + presence: boolean; + /** The Agents page's `call`: an iterate agent's chat has the call's controls. */ + call: DashCall | undefined; + /** The Agents page's `share`, where `call` is on too: Share beside the call's controls. */ + share: DashShare | undefined; + me: string | undefined; + tails: TailsOfMember; + quiet: boolean; + /** The view that drew the saved rows of `path`, in the member's own store. */ + remembered: SavedView | undefined; +}) { + const { files, kinds } = useKindFiles(itx); + // the view the mind's answer says, once the kinds and the catalog have both answered + const said = useMemo(() => kinds && agents && viewOf(path, agents, kinds), [path, agents, kinds]); + // What is drawn, and its mount: a view the mind's answer changes is another element. + const [drawn, setDrawn] = useState<{ view: SavedView; mount: number } | undefined>(); + const shown = drawn || (remembered && { view: remembered, mount: 0 }); + const next = + said && !(shown && sameView(shown.view, said)) + ? { view: said, mount: (shown?.mount ?? 0) + 1 } + : shown; + if (next !== drawn) setDrawn(next); + // the mind's answer replaces the saved view, so the next reload mounts it + useEffect(() => { + if (said && tails && tails !== "pending") tails.saveView(path, said); + }, [said, tails, path]); + if (!next) { + // nothing to draw yet: the kinds are waited for as the page waits for the chat's part + use(files); + return ( + <AgentPageReading + path={path} + agents={agents} + quiet={quiet} + presence={presence} + call={Boolean(call)} + share={Boolean(share)} + /> + ); + } + const { view, mount } = next; + return view.file ? ( + <KindChat + key={mount} + itx={itx} + path={path} + file={view.file} + agents={agents} + presence={presence} + call={Boolean(call)} + share={Boolean(share)} + me={me} + tails={tails} + /> + ) : ( + <IterateChat + key={mount} + itx={itx} + path={path} + kind={view.kind} + agents={agents} + opener={opener} + presence={presence} + call={call} + share={share} + me={me} + tails={tails} + /> + ); +} + +/** The view that the catalog and the kinds say for `path`. */ +function viewOf(path: string, agents: readonly AgentRow[], kinds: KindFile[]): SavedView { + // a row with no kind, and a path with no row, are drawn alike: as iterate's + const kind = agents.find((agent) => agent.path === path)?.kind || undefined; + const file = kind && kind !== "iterate" ? kinds.find((one) => one.kind === kind) : undefined; + return { kind, file: file && { name: file.name, source: file.source } }; +} + +/** Anything said in a chat: by a person, by the agent, or by an opener. Words that raise no turn + * (iterate Cloud's handover) are context, not a start. */ +const Said = z.union([ + z.object({ type: z.literal("events.iterate.com/agent/message-received") }), + z.object({ + type: z.literal("events.iterate.com/agent/context-added"), + payload: z.object({ + role: z.string().refine((role) => role !== "system"), + llmRequestPolicy: z + .object({ behaviour: z.string().refine((said) => said !== "dont-trigger-request") }) + .optional(), + }), + }), +]); + +/** ITERATE'S CHAT for any context: the page holds the context and reads it live. An agent of + * another kind that has no file opens on the Events tab: the chat draws an iterate agent's + * events. The chat's state is `?view`. Drawn from a remembered view, the catalog may not have + * answered yet: the header then has no title, and `kind` is the remembered one. */ +function IterateChat({ + itx, + path, + kind, + agents, + opener, + presence, + call, + share, + me, + tails, +}: { + itx: Itx; + path: string; + /** The agent's kind; undefined for a path that the catalog does not list. */ + kind: string | undefined; + agents: readonly AgentRow[] | undefined; + /** What the mind says first, if the chat is empty: a developer's note, which starts a turn. */ + opener: string | undefined; + /** The chat shows who else is here, and says the page's own status. */ + presence: boolean; + /** The agent's call: its controls in the header, its tiles over the feed. */ + call: DashCall | undefined; + /** Links for guests: Share beside the call's controls. */ + share: DashShare | undefined; + /** The signed-in member's actor id: their own messages have no line under them. */ + me: string | undefined; + tails: TailsOfMember; +}) { + // the call's part loads beside the chat's, behind the same loading state + const calling = call && callPart(); + const { AgentChat } = use(chatPart()); + const callKit = calling && use(calling); + // the header's place for the call's controls, once the header has drawn it + const [callIn, setCallIn] = useState<HTMLElement | null>(null); + // Share's place in the header, once the header has drawn it + const [shareIn, setShareIn] = useState<HTMLElement | null>(null); + const { view, patchView } = useView(); + // `call=join`: the page was opened to join the call (a Mac's Accept opens it so) + const joinOnArrival = usePageParam("call") === "join"; + // the header's place for who is here and can use the conversation, once the header has drawn it + const [aside, setAside] = useState<HTMLElement | null>(null); + // held and read again at each new session: the rows of the last one, or of the last page load, + // stay until then + const session = itxSessionOf(itx); + const agent = useHeldContext(session, () => itx.cd(path), [itx, path]); + const context = useSavedContext({ + held: agent, + options: AgentChat.contextOptions, + path, + session, + tails, + }); + const state = AgentChatState.safeParse(view).data || {}; + const shown = + state.view || !kind || kind === "iterate" ? state : { ...state, view: "events" as const }; + // THE MIND SPEAKS FIRST: once the whole log is read and nothing was said in it, the opener is + // appended once for the mind (its key), whatever reloads or tabs. Never by a saved copy: it may + // be of a log made again under the same path, and only the mind's answer says it is empty. + const { stub } = agent; + // one function while `itx` is the same: each mounted row and attachment keeps its signed URL + const signedUrl = useCallback((file: string) => fileUrl(itx, file), [itx]); + const empty = + !context.savedCopy && + context.caughtUp && + context.older.exhausted && + !context.events.some((event) => Said.safeParse(event).success); + const callLive = context.liveState.call?.value; + // one function while the agent is the same: Share turns the call on at most once by it + const enableCall = useCallback(() => call!.enable(itx, path), [call, itx, path]); + const widgetCalls = useMemo(() => widgetCallsOf(itx, path), [itx, path]); + const inCall = useMemo(() => callKit && callKit.inCallOf(callLive), [callKit, callLive]); + useEffect(() => { + if (!opener || !stub || !empty) return; + stub + .append({ + type: "events.iterate.com/agent/context-added", + idempotencyKey: `opener:${path}`, + payload: { role: "developer", content: opener }, + }) + .catch(() => {}); // another tab said it first, or the chat is not empty after all + }, [opener, stub, empty, path]); + return ( + <> + <AgentPageHeader + path={path} + agents={agents} + tabs={{ + view: shown.view, + hasChat: true, + // no count until the first read has answered + held: context.caughtUp || context.events.length ? heldRowsOf(context.events) : undefined, + wholeLogHeld: context.older.exhausted, + onStateChange: patchView, + }} + presence={presence} + aside={setAside} + call={Boolean(call)} + callIn={setCallIn} + share={Boolean(share)} + shareIn={setShareIn} + /> + {call && share && callKit ? ( + <callKit.AgentShare + share={share} + itx={itx} + path={path} + title={agents?.find((row) => row.path === path)?.title || path.split("/").at(-1) || path} + pageUrl={new URL(agentViewHref(path), location.href).href} + context={context} + enable={enableCall} + shareIn={shareIn} + /> + ) : null} + {call && callKit ? ( + <callKit.AgentCall + stub={stub} + context={context} + enable={() => call.enable(itx, path)} + barIn={callIn} + joinOnArrival={joinOnArrival} + arrived={leaveTheJoinKey} + /> + ) : null} + <AgentChat + path={path} + context={context} + error={agent.error} + state={shown} + onStateChange={patchView} + tabsInHeader + asideIn={aside} + onMessage={async ({ message, files, key }) => { + await messageAgent(itx, path, { message, files }, key); + }} + onAppend={stub ? (events) => appendEvents(stub, events) : undefined} + signedUrl={signedUrl} + me={me} + presence={presence} + inCall={inCall} + mind={use(PageMind)} + widgetCalls={widgetCalls} + /> + </> + ); +} + +/** The join on arrival began: `call=join` leaves the address, in place. */ +function leaveTheJoinKey() { + go(hrefOf({ call: undefined }), true); +} + +/** The page's theme is the class on its root element: the frame follows it when it changes. */ +function watchDocumentClass(changed: () => void) { + const observer = new MutationObserver(changed); + observer.observe(document.documentElement, { attributeFilter: ["class"] }); + return () => observer.disconnect(); +} + +/** AN AGENT OF A KIND THAT BRINGS ITS OWN VIEW. The view is a file of the config repo, which any + * member or any member's agent can change, so it does not run in this page: it runs in a + * sandboxed frame. The page reads the agent's log live, hands it to the frame, and answers the + * frame's few verbs for this one agent. The frame is another document, which loads its script and + * the kind's file before it draws: the page's own loading state stands over it until the frame + * has loaded and the first read has answered, so the wait is one state, whatever the kind's view + * draws meanwhile. */ +function KindChat({ + itx, + path, + file, + agents, + presence, + call, + share, + me, + tails, +}: { + itx: Itx; + path: string; + /** The kind's file: a view of another file is another frame (`AgentViewOfKind` keys it). */ + file: { name: string; source: string | null }; + agents: readonly AgentRow[] | undefined; + /** The page shows who else is here, for a view that draws AgentChat. */ + presence: boolean; + /** The header keeps the call's place as the loading header had it, and empty: a kind's own view + * has no call controls. */ + call: boolean; + /** The header keeps Share's place, empty, as the call's. */ + share: boolean; + /** The signed-in member's actor id, for a view that draws AgentChat. */ + me: string | undefined; + tails: TailsOfMember; +}) { + const { view, patchView } = useView(); + const session = itxSessionOf(itx); + const agent = useHeldContext(session, () => itx.cd(path), [itx, path]); + const { link, loaded } = useAgentKindViewLink(file.name, file.source); + const load = useMemo(() => frameLoadOf(loaded), [loaded]); + // every durable event (the frame's Events tab is the whole log) and, by name, the ephemeral + // ones the view reads, which a wildcard never matches; nothing until the frame has said which + const options = useMemo( + () => ({ consumes: ["*", ...load.ephemeralEvents] }), + [load.ephemeralEvents], + ); + // read again at each new session: the frame keeps the rows of the last one, or of the last page + // load, until then. The saved rows are in `inputs` from the first render, and the link sends + // the latest inputs when the frame says it is ready (`AgentKindViewLink.push`): the frame + // draws them with its first message. + const log = useSavedContext({ + held: { stub: loaded ? agent.stub : undefined, error: agent.error }, + options, + path, + session, + tails, + }); + const documentClass = useSyncExternalStore( + watchDocumentClass, + () => document.documentElement.className, + () => "", + ); + const { loading, exhausted } = log.older; + const older = useMemo(() => (exhausted ? null : { loading, exhausted }), [loading, exhausted]); + const { stub } = agent; + const hostError = agent.error || load.error; + // the cover stands until the frame has drawn (its own document loads first) and the log has + // answered: a saved copy answers at once, so the frame's load is said outright + const reading = + (!loaded || (!log.caughtUp && log.events.length === 0)) && !log.error && !hostError; + const inputs: AgentKindViewInputs = { + path, + events: log.events, + caughtUp: log.caughtUp, + error: log.error, + head: log.head, + older, + processors: log.processors, + presence: log.presence, + liveState: log.liveState, + // the version a read said, never a saved copy's: the frame's chat starts a new conversation + // at a new one + version: versionOf(log), + hostError, + // the chat's own keys checked, and a kind's own keys kept (AgentKindViewState): its controls + // keep what was picked in them + state: AgentChatState.loose().safeParse(view).data || {}, + // the page's theme, for the frame's own + documentClass, + // Chat | Events are the page's header's + tabsInHeader: true, + // oxlint-disable-next-line iterate/simple-truthiness-check -- the wire view: an absent optional field stays absent + ...(me && { me }), + presenceOn: presence, + }; + // the view's state, as the frame reads it + const state = inputs.state; + const verbs = kindViewVerbs({ + itx, + path, + stub, + setState: patchView, + loadOlder: log.older.loadOlder, + }); + const { hasChat } = load; + return ( + <> + <AgentPageHeader + path={path} + agents={agents} + tabs={{ + view: hasChat ? state.view : "events", + hasChat, + // no count until the first read has answered + held: loaded && !reading ? heldRowsOf(log.events) : undefined, + wholeLogHeld: log.older.exhausted, + onStateChange: patchView, + }} + // The call's and Share's places stay as the loading header had them: the kind's view runs + // in a frame, which draws nothing into this page. So who is here is the mind's face alone: + // the frame says nothing of the viewer to this page. + presence={false} + call={call} + share={share} + /> + <div className="relative flex min-h-0 flex-1 flex-col"> + <AgentKindViewFrame + link={link} + frameScript={frameScriptOfPage()} + inputs={inputs} + verbs={verbs} + /> + {reading ? ( + <div className="absolute inset-0 bg-background"> + {/* with saved rows the wait is for the frame's own document, not for a read */} + <AgentReading strip={false} quiet={log.events.length > 0} /> + </div> + ) : null} + </div> + </> + ); +} + +/** What a frame's load says: the ephemeral types its view reads, its failure, and whether it has + * a chat. A kind with no view, or one that failed to load, is the Events tab alone; a frame that + * has not loaded yet is drawn as a chat. */ +function frameLoadOf(loaded: AgentKindViewLoaded | undefined): { + ephemeralEvents: readonly string[]; + error: string | undefined; + hasChat: boolean; +} { + if (!loaded) return { ephemeralEvents: [], error: undefined, hasChat: true }; + if ("ephemeralEvents" in loaded) + return { ephemeralEvents: loaded.ephemeralEvents, error: undefined, hasChat: true }; + return { + ephemeralEvents: [], + error: "error" in loaded ? loaded.error : undefined, + hasChat: false, + }; +} + +/** Everything a kind's frame may do, to this agent alone: never the agent's stub, which reaches + * the whole mind. */ +function kindViewVerbs({ + itx, + path, + stub, + setState, + loadOlder, +}: Pick<AgentKindViewVerbs, "setState" | "loadOlder"> & { + itx: Itx; + path: string; + stub: Parameters<typeof appendEvents>[0] | undefined; +}): AgentKindViewVerbs { + return { + message: ({ message, files, key }) => messageAgent(itx, path, { message, files }, key), + append: async (events) => { + if (!stub) throw new Error("not connected"); + await appendEvents(stub, events); + }, + fileUrl: async (filePath) => { + if (!filePath.startsWith(`${path}/`)) throw new Error(`${filePath} is not a file of ${path}`); + return fileUrl(itx, filePath); + }, + // under this agent's path alone: the frame names no path + storeFiles: (files, key) => storeAgentFiles(itx, path, files, key), + // as this agent alone: a call that names another path is refused (widget-mcp.ts) + callTool: (call) => widgetCallsOf(itx, path).callTool(call), + readResource: (read) => widgetCallsOf(itx, path).readResource(read), + setState, + loadOlder, + }; +} + +/** The time, read again every `everyMs`: what "3 min" is counted from. */ +function useNow(everyMs: number) { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + const timer = setInterval(() => setNow(Date.now()), everyMs); + return () => clearInterval(timer); + }, [everyMs]); + return now; +}
A src/agent-kind-view/dash-call.tsx
@@ -0,0 +1,203 @@ +// dash-call.tsx — A CALL ON AN AGENT IN THE DASH: its controls in the agent page's header, and its +// cameras and screens over the feed while a call is live. The Agents page loads this module, beside +// the chat's part, only where its row turns calls on (`DashPage["call"]`). +// +// - THE CALL is a facet on the agent's context, the processor row `call` (a mind's config: +// `call.ts`). Its live state comes with the chat's own: `AgentChat.contextOptions` names no +// `liveState`, so the chat's hook opens each facet the processors table has, `call` once its row +// is there. A context with no call opens nothing for it, and shows no error. +// - THE PAGE is its own row on the context (`context.subscription`), which the call knows it by. +// - THE HEADER has the kit's call controls (components/call/call-controls.tsx), the same as Meet's: +// out of the call, Start call or Join call; in it, the button group and Leave. Before a call, +// once the table is read and has no `call` row, Start call turns the call on (`DashCall.enable`, +// with the config's spec) and joins. The controls draw the call as this page knows it: in the +// call, with or without the live state; else the call's live state, or, once the call is on (its +// row, or this page's start), a call whose live state has not come yet. While this page's start +// runs, the button waits for it (`starting`, held here, so a row drawn again keeps it). +// - ON A PHONE, in the call, the controls are behind one button in the header, so the path and the +// tabs keep the row. The button marks an error the closed row holds. +// - THE TILES are always there over the feed: they draw what the call has to show, and their +// region for a screen reader stays, so it hears the first arrival and the last departure. +// - A START belongs to the engine it began with: one whose engine changed (a new row) or whose +// page went away does not join. +// - JOIN ON ARRIVAL (`joinOnArrival`: the Dash's `call=join`, the page a Mac's Accept opens): once +// the table is read, the page opens the lobby (`CallLobby`, in a dialog), once, and joins nothing. +// There the person checks their camera and their sound, chooses the devices, sees who is in the +// call, and joins with what is on, or muted; the tracks it opened go to the call as they are. +// ANYONE CAN SEND A MEMBER SUCH A LINK (a guest on a share link of the agent can), so it is no +// press of the person's: this lobby opens no microphone and no camera by itself. `arrived` then +// takes the key out of the address, so a reload does not open it again. +import { useEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import { CallHeaderControls } from "#/components/call/call-controls.tsx"; +import { CallLobby, type LobbyMedia } from "#/components/call/call-lobby.tsx"; +import { CallTiles } from "#/components/call/call-tiles.tsx"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "#/components/ui/dialog.tsx"; +import { useCall, type CallContext, type CallEngine } from "#/lib/call-engine.ts"; +import type { CallLive } from "#/lib/call-rules.ts"; + +/** THE CALL OF ONE AGENT'S PAGE. `stub` is the agent's context as the page holds it; `context` is + * what the chat's hook reads of it; `barIn` is the header's place for the controls. Draws the + * tiles where it stands. */ +export function AgentCall({ + stub, + context, + enable, + barIn, + joinOnArrival = false, + arrived, +}: { + stub: CallContext | undefined; + context: { + subscription?: string; + processors: { rows: readonly { hostedFacet?: { name: string } }[]; loaded: boolean }; + liveState: Readonly<Record<string, { value: unknown }>>; + }; + /** Turns the call on for this agent. */ + enable: () => Promise<unknown>; + barIn: HTMLElement | null; + /** The page was opened to join: it opens the lobby once the table is read. */ + joinOnArrival?: boolean; + /** The join on arrival began: the host takes its key out of the address. */ + arrived?: () => void; +}) { + const { call, ui, live } = useCall(stub, context.subscription, context.liveState.call?.value); + // this page's own start, in flight: which engine's call, and which of its calls (`epoch`). A + // dispose (pagehide), a Leave or a new row ends it, and a new row shows no start of an old one. + const [startedIn, setStartedIn] = useState<{ call: CallEngine; epoch: number } | null>(null); + const starting = Boolean(call && startedIn?.call === call && startedIn.epoch === call.epoch); + // this page turned the call on: Join from now on, even when its join failed before the table or + // the live state said so; a second start would turn on a call that is on + const [enabled, setEnabled] = useState(false); + const facetOn = context.processors.rows.some((row) => row.hostedFacet?.name === "call"); + const barLive = live || (facetOn || enabled ? NOT_READ_YET : undefined); + // the engine this page holds now; none once the page went away + const heldCall = useRef(call); + useEffect(() => { + heldCall.current = call; + return () => { + heldCall.current = null; + }; + }, [call]); + // the lobby of a join on arrival, while it is open + const [lobby, setLobby] = useState(false); + // turns the call on while it is off; nothing before the table is read: an agent with a call + // shows Join, never a start first + const turnOn = + call && !barLive && context.processors.loaded + ? async () => { + const token = { call, epoch: call.epoch }; + setStartedIn(token); + try { + await enable(); + setEnabled(true); + } finally { + setStartedIn((now) => (now === token ? null : now)); + } + } + : undefined; + // the lobby's "Start the call": the call on, then the join with what the lobby opened + const startFromLobby = async (on: () => Promise<void>, { mic, camera }: LobbyMedia) => { + if (!call) return; + const epoch = call.epoch; + await on(); + // the page went away, or its call was closed (a pagehide, a Leave), while the call was turned + // on: joining is the person's next press + if (heldCall.current !== call || call.epoch !== epoch) { + for (const track of [...(mic?.getTracks() || []), ...(camera?.getTracks() || [])]) + track.stop(); + return; + } + await call.join({ mic, camera, listenOnly: !mic }); + }; + // the lobby on arrival, once, with nothing open. What it does is this render's (`arrive`, set + // after each render); when it runs is the table's first read. + const arrival = useRef(joinOnArrival); + const arrive = useRef(() => {}); + useEffect(() => { + arrive.current = () => { + if (!call) return; + arrived?.(); + if (!ui.joined && !ui.joining) setLobby(true); + }; + }); + // the lobby's Join now (or Start the call): the call takes what it opened + const fromLobby = (media: LobbyMedia) => { + setLobby(false); + if (!call) return; + if (turnOn) + startFromLobby(turnOn, media).catch((error: unknown) => + call.fail( + `The call could not start: ${error instanceof Error ? error.message : String(error)}`, + ), + ); + else void call.join({ ...media, listenOnly: !media.mic }); + }; + useEffect(() => { + if (!arrival.current || !call || !context.processors.loaded) return; + arrival.current = false; + arrive.current(); + }, [call, context.processors.loaded]); + return ( + <> + {barIn + ? createPortal( + <CallHeaderControls + call={call} + ui={ui} + live={barLive} + member + start={turnOn} + starting={starting} + />, + barIn, + ) + : null} + <Dialog open={lobby} onOpenChange={(open) => !open && setLobby(false)}> + <DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-lg"> + <DialogHeader> + <DialogTitle>{turnOn ? "Start a call" : "Join the call"}</DialogTitle> + <DialogDescription> + Check your camera and your sound first. Nothing is sent until you join. + </DialogDescription> + </DialogHeader> + {lobby ? ( + <CallLobby + live={live} + action={turnOn ? "start" : "join"} + micAtStart={false} + onJoin={fromLobby} + /> + ) : null} + </DialogContent> + </Dialog> + {/* over the feed, which gives up the room: the composer stays where it is */} + <div data-slot="agent-call-tiles" className="max-h-[40dvh] shrink-0 overflow-y-auto"> + <CallTiles + call={call} + ui={ui} + live={live} + member + className="mx-auto w-full max-w-3xl px-4 pt-2 md:px-6" + /> + </div> + </> + ); +} + +/** A call that is on, whose live state this page has not read yet: no one known in it, its setup + * unknown. */ +const NOT_READ_YET: CallLive = { + since: null, + inCall: {}, + voiceAgent: null, + setup: null, + delegation: null, + links: [], +};
A src/agent-kind-view/dash-share.tsx
@@ -0,0 +1,45 @@ +// dash-share.tsx — SHARE ON AN AGENT IN THE DASH: the kit's Share (components/call/call-share.tsx) +// in the agent page's header, beside the call's controls, with the Dash's `DashShare` bound to this +// agent. The Agents page loads this module with the call's part, only where its row turns both on +// (`DashPage["share"]` beside `DashPage["call"]`). +import { useMemo } from "react"; +import { createPortal } from "react-dom"; +import { CallShare, type ShareContext } from "#/components/call/call-share.tsx"; +import type { DashShare } from "#/components/dash/dash.tsx"; + +/** SHARE, drawn into the header's place `shareIn`. `pageUrl` is the agent's page in this Dash, + * which the members' link and an invite for members hold. */ +export function AgentShare({ + share, + itx, + path, + title, + pageUrl, + context, + enable, + shareIn, +}: { + share: DashShare; + itx: Parameters<DashShare["make"]>[0]; + path: string; + /** The agent's title, or the last part of its path: the invite's title. */ + title: string; + pageUrl: string; + context: ShareContext; + /** Turns the call on for this agent. */ + enable: () => Promise<unknown>; + shareIn: HTMLElement | null; +}) { + const links = useMemo( + () => ({ + make: (lifetimeMs: number) => share.make(itx, path, lifetimeMs), + end: (link: string) => share.end(itx, path, link), + }), + [share, itx, path], + ); + if (!shareIn) return null; + return createPortal( + <CallShare share={links} title={title} pageUrl={pageUrl} context={context} enable={enable} />, + shareIn, + ); +}
A src/agent-kind-view/default-kind.test.ts
@@ -0,0 +1,141 @@ +// The mind's default kind (default-kind.ts): which kind file may be it, which one is by what its +// frame reports, where its new agent is born and what `start` is given, and the first message as +// one fact. The frame itself is host.ts's; the Dash's composer is dash-agents.test.tsx's. +import { expect, test, vi } from "vitest"; +import { + defaultKindCandidates, + defaultKindOf, + newAgentStartOf, + sendFirstMessage, + type KindStarter, +} from "./default-kind.ts"; +import type { AgentKindViewLoaded } from "./bridge.ts"; + +test("only a kind file whose text says `default: true` may be the default, by kind name", () => { + expect( + defaultKindCandidates([ + { kind: "zeta", name: "agent-kinds/zeta.ts", source: "newAgent: { default: true }" }, + { kind: "claude", name: "agent-kinds/claude.ts", source: "export default {};" }, + { kind: "unread", name: "agent-kinds/unread.ts", source: null }, + { kind: "agent", name: "agent-kinds/agent.ts", source: "{ default:true, choices }" }, + ]).map((file) => file.kind), + ).toEqual(["agent", "zeta"]); +}); + +test("the default is the first kind whose frame reports `default: true`; with none, there is none", async () => { + const plain = starter("claude", { ephemeralEvents: [], newAgent: { choices: [CHOICE] } }); + const failed = starter("broken", { error: "agent-kinds/broken.ts does not parse" }); + const agent = starter("agent", { ephemeralEvents: [], newAgent: NEW_AGENT }); + expect(await defaultKindOf([plain, failed, agent])).toMatchObject({ + starter: { file: { kind: "agent" } }, + newAgent: { default: true }, + }); + expect(await defaultKindOf([plain, failed])).toBe(null); + expect(await defaultKindOf([])).toBe(null); +}); + +test("a frame that reports later is waited for; one that never reports leaves New agent as it was", async () => { + vi.useFakeTimers(); + const late = starter("agent", undefined); + const found = defaultKindOf([late], 15_000); + late.report({ ephemeralEvents: [], newAgent: NEW_AGENT }); + expect(await found).toMatchObject({ starter: { file: { kind: "agent" } } }); + + const silent = defaultKindOf([starter("agent", undefined)], 15_000); + await vi.advanceTimersByTimeAsync(15_000); + expect(await silent).toBe(null); + vi.useRealTimers(); +}); + +test("a new agent of the kind is born in the person's folder of the kind, on its first choice, with each field's default", () => { + const found = { starter: starter("agent", undefined), newAgent: NEW_AGENT }; + const at = new Date(Date.UTC(2026, 10, 23, 12, 0, 0)); + expect(newAgentStartOf(found, "ada", at)).toEqual({ + choice: "agent", + // a list whose default is none of its options starts on its first + fields: { model: "openai/gpt-6.2-sol", effort: "high" }, + path: "/agents/people/ada/agent/2026-11-23t12-00-00-000z", + }); + const nobodys = { + ...found, + newAgent: { ...NEW_AGENT, choices: [{ ...CHOICE, byPerson: false }] }, + }; + expect(newAgentStartOf(nobodys, "ada", at)).toMatchObject({ + path: "/agents/agent/2026-11-23t12-00-00-000z", + }); +}); + +test("the first message is its files stored under the new path, then ONE `agent-ui/message-received` there", async () => { + const steps: unknown[] = []; + await sendFirstMessage( + "/agents/people/ada/agent/x", + { message: "look", files: [{ contentType: "image/png", filename: "a.png", data: "AAAA" }] }, + { + storeFiles: async (path, files) => { + steps.push({ stored: path, count: files.length }); + return [{ contentType: "image/png", filename: "a.png", path: `${path}/s-a.png`, size: 3 }]; + }, + append: async (path, events) => void steps.push({ appended: path, events }), + }, + ); + expect(steps).toMatchObject([ + { stored: "/agents/people/ada/agent/x", count: 1 }, + { + appended: "/agents/people/ada/agent/x", + events: [ + { + type: "events.iterate.com/agent-ui/message-received", + payload: { + message: "look", + files: [{ path: "/agents/people/ada/agent/x/s-a.png", size: 3 }], + }, + }, + ], + }, + ]); +}); + +// ── the kinds ── + +const CHOICE = { id: "agent", label: "Agent", byPerson: true }; +const NEW_AGENT = { + default: true as const, + choices: [CHOICE], + fields: [ + { + name: "model", + label: "Model", + type: "select" as const, + defaultValue: "openai/gpt-6.2-sol", + options: ["openai/gpt-6.2-sol", "xai/grok-4.3"], + }, + { + name: "effort", + label: "Effort", + type: "select" as const, + defaultValue: "max", + options: ["high"], + }, + { name: "other", label: "Other", defaultValue: "x", choices: ["another-choice"] }, + ], +}; + +/** A starter frame that reported `loaded`, or reports later by `report`. */ +function starter(kind: string, loaded: AgentKindViewLoaded | undefined) { + let held = loaded; + const listeners = new Set<() => void>(); + const fake: KindStarter & { report(next: AgentKindViewLoaded): void } = { + file: { kind, name: `agent-kinds/${kind}.ts`, source: "default: true" }, + loaded: () => held, + subscribe: (listener) => { + listeners.add(listener); + return () => void listeners.delete(listener); + }, + start: async () => [], + report: (next) => { + held = next; + for (const listener of listeners) listener(); + }, + }; + return fake; +}
A src/agent-kind-view/default-kind.ts
@@ -0,0 +1,124 @@ +// THE DEFAULT KIND OF A MIND: the kind whose file says `newAgent: { default: true, … }`. The Dash's +// New agent then starts that kind's agent, and no iterate agent: it appends the kind's +// `start(…)` events to the new path, then the first message as `agent-ui/message-received`. It +// calls neither `itx.agents.create` nor `message()`. +// +// A kind file is a config repo's code, which any member or any member's agent can change: it never +// runs in the page. A hidden frame loads it (host.ts `AgentKindStarterFrame`), reports its +// `newAgent` as data, and runs its `start` there. Only a file whose text says `default: true` gets +// a frame: what the frame reports decides. +import type { AgentKindNewAgentSummary, AgentKindViewLoaded } from "./bridge.ts"; +import { + agentUiMessage, + type OutgoingFile, + type StoredFile, +} from "#/components/agent-chat/agent-facts.ts"; +import { newAgentPath } from "#/lib/agent-summary.ts"; + +/** A kind of agent with a file of its own, as the Dash reads the kinds: the file's path in the + * config repo, and its source (null when it cannot be read: its view then shows the agent's + * events). */ +export type KindFile = { kind: string; name: string; source: string | null }; + +/** What the page holds of one kind's starter frame. */ +export type KindStarter = { + file: KindFile; + /** What the frame reported, once it has. */ + loaded(): AgentKindViewLoaded | undefined; + /** Calls `listener` at each change of `loaded()`; answers the way to stop. */ + subscribe(listener: () => void): () => void; + /** The kind's `newAgent.start`, in the frame. */ + start(input: { + choice: string; + fields: Record<string, string>; + path: string; + }): Promise<unknown[]>; +}; + +/** The default kind, as the page starts its agents. */ +export type DefaultKind = { starter: KindStarter; newAgent: AgentKindNewAgentSummary }; + +/** The text a kind file that may be the default has. */ +const SAYS_DEFAULT = /\bdefault\s*:\s*true\b/; + +/** The kind files that may be the default, by kind name: the first that is wins. */ +export function defaultKindCandidates(kinds: readonly KindFile[]): KindFile[] { + return kinds + .filter((file) => file.source && SAYS_DEFAULT.test(file.source)) + .toSorted((a, b) => a.kind.localeCompare(b.kind)); +} + +/** How long the page waits for a starter frame to report before New agent does what it does + * without a default kind. */ +const STARTER_WAIT_MS = 15_000; + +/** The default kind among `starters`, in their order: the first whose frame reports a `newAgent` + * with `default: true` and a choice. Null for none, or when no frame reported in `waitMs`. */ +export async function defaultKindOf( + starters: readonly KindStarter[], + waitMs = STARTER_WAIT_MS, +): Promise<DefaultKind | null> { + for (const starter of starters) { + const loaded = await loadedOf(starter, waitMs); + const newAgent = loaded && "ephemeralEvents" in loaded ? loaded.newAgent : undefined; + if (newAgent?.default && newAgent.choices.length > 0) return { starter, newAgent }; + } + return null; +} + +/** What the frame reported, or undefined after `waitMs`. */ +function loadedOf(starter: KindStarter, waitMs: number) { + const now = starter.loaded(); + if (now) return Promise.resolve(now); + return new Promise<AgentKindViewLoaded | undefined>((resolve) => { + const timer = setTimeout(() => { + stop(); + resolve(undefined); + }, waitMs); + const stop = starter.subscribe(() => { + const loaded = starter.loaded(); + if (!loaded) return; + clearTimeout(timer); + stop(); + resolve(loaded); + }); + }); +} + +/** THE START OF A NEW AGENT OF THE KIND: its path (`/agents/people/<person>/<kind>/<moment>` for + * a choice that says `byPerson`, else `/agents/<kind>/<moment>`) and what its `start` is given: + * the first choice, each of its fields at its `defaultValue` (a list's first option when that is + * none of them). */ +export function newAgentStartOf( + found: DefaultKind, + person: string | undefined, + date: Date, +): { choice: string; fields: Record<string, string>; path: string } { + const [choice] = found.newAgent.choices; + const path = newAgentPath(found.starter.file.kind, date, choice.byPerson ? person : undefined); + const fields = Object.fromEntries( + (found.newAgent.fields || []) + .filter((field) => !field.choices || field.choices.includes(choice.id)) + .map((field) => [ + field.name, + field.type === "select" && field.options && !field.options.includes(field.defaultValue) + ? (field.options[0] ?? "") + : field.defaultValue, + ]), + ); + return { choice: choice.id, fields, path }; +} + +/** The first message to a new agent of the kind: its files stored under the agent's path, then + * ONE `agent-ui/message-received` appended there. */ +export async function sendFirstMessage( + path: string, + input: { message: string; files: OutgoingFile[] }, + host: { + storeFiles(path: string, files: OutgoingFile[]): Promise<StoredFile[]>; + append(path: string, events: unknown[]): Promise<void>; + }, +): Promise<void> { + const files = input.files.length > 0 ? await host.storeFiles(path, input.files) : []; + await host.append(path, [agentUiMessage({ message: input.message, files })]); +}
A src/agent-kind-view/frame-view.test.tsx
@@ -0,0 +1,421 @@ +// @vitest-environment jsdom +// A kind's view in the frame, built as a mind's kind file builds it (the shell around a `Feed` +// with the kind's own words for an empty chat), while the host reads the agent's log: the words +// for an empty chat wait for the whole log, and a read that failed shows its error alone: no +// spinner, and no words for an empty chat. A kind file that failed to load is no failed read: the +// Events tab that stands in for the view still pages down the log. +// The last test reads a log with the real reader and holds its first read back: from the reader, +// through the bridge's updates, to the kind's view, the words are never there before the answer. +// jsdom runs no frame, so the page's side and the frame's side share one document here. +import { act, useEffect, useRef } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, test, vi } from "vitest"; +import { useIterateContext } from "iterate/react"; +import { updateBetween, type AgentKindViewInputs } from "./bridge.ts"; +import { InputsStore, type LoadedView } from "./frame.ts"; +import { FrameView } from "./frame-view.tsx"; +import { agentKindViewKit } from "./kit.ts"; +import type { AgentKindViewProps } from "./types.ts"; +import { versionOf } from "#/lib/itx-session.ts"; + +Object.assign(globalThis, { + IS_REACT_ACT_ENVIRONMENT: true, + // jsdom lays nothing out, so it has no ResizeObserver; the virtual log's scroller asks for one + ResizeObserver: class { + observe() {} + unobserve() {} + disconnect() {} + }, +}); + +test.for<{ + name: string; + inputs: Partial<AgentKindViewInputs>; + shown: "reading" | "empty" | "rows" | "nothing"; + error?: string; +}>([ + { + name: "the host has not connected the log yet", + inputs: { caughtUp: false, older: pagesLeft() }, + shown: "reading", + }, + { + name: "the first read is out", + inputs: { caughtUp: false, older: { loading: true, exhausted: false } }, + shown: "reading", + }, + { + name: "the newest page holds nothing the kind draws and older pages remain", + inputs: { caughtUp: true, events: [event(9_000, "test/woken")], older: pagesLeft() }, + shown: "reading", + }, + { + name: "the whole log is read and holds nothing the kind draws", + inputs: { caughtUp: true, events: [event(1, "test/woken")], older: null }, + shown: "empty", + }, + { + name: "the read answered with words", + inputs: { caughtUp: true, events: [event(9_000, "test/said")], older: pagesLeft() }, + shown: "rows", + }, + { + name: "the first read failed", + inputs: { caughtUp: false, error: "the read failed", older: pagesLeft() }, + shown: "nothing", + error: "the read failed", + }, + { + name: "the context could not be opened", + inputs: { caughtUp: false, hostError: "no such context", older: pagesLeft() }, + shown: "nothing", + error: "no such context", + }, + { + name: "an older page failed before any row was read", + inputs: { + caughtUp: true, + events: [event(9_000, "test/woken")], + error: "the read failed", + older: pagesLeft(), + }, + shown: "nothing", + error: "the read failed", + }, +])("a kind's feed when $name: $shown", async ({ inputs, shown, error }) => { + using _layout = laidOut(); + using frame = await mount(inputs); + const log = document.querySelector("[role=log]")!; + expect(Boolean(log.querySelector("[data-slot=log-reading] [data-slot=spinner]"))).toBe( + shown === "reading", + ); + expect(log.textContent?.includes("Nothing said yet.")).toBe(shown === "empty"); + expect(log.textContent?.includes("words at 9000")).toBe(shown === "rows"); + expect(document.querySelector("[data-type=error]")?.textContent).toBe(error); + // a failed read is not asked for again and again, and says nothing in the feed's place + if (error) expect(frame.host.loadOlder).not.toHaveBeenCalled(); + if (shown === "nothing") expect(log).toMatchObject({ textContent: "" }); +}); + +test("a page that draws the tabs in its header: the frame's shell draws no strip, the status stands at the feed's foot, and the page's tab is the frame's", async () => { + { + using _view = await mount({ caughtUp: true, older: null, tabsInHeader: true }); + expect(document.querySelector("[role=tablist]")).toBeNull(); + expect(document.querySelector("[data-slot=agent-foot-status]")?.textContent).toBe("Idle"); + expect(document.body.textContent).toContain("Nothing said yet."); + } + { + using _view = await mount({ + caughtUp: true, + older: null, + tabsInHeader: true, + state: { view: "events" }, + }); + expect(document.querySelector("[role=tablist]")).toBeNull(); + expect(document.body.textContent).toContain("Nothing has happened on this agent yet."); + } + // the default: the strip with its tabs, and no line at the foot + using _view = await mount({ caughtUp: true, older: null }); + expect(document.querySelectorAll("[role=tablist]")).toHaveLength(1); + expect(document.querySelector("[data-slot=agent-foot-status]")).toBeNull(); +}); + +test("a kind file that failed to load is no failed read: the Events tab in its place pages down the log and says it holds a part", async () => { + using _layout = laidOut(); + using frame = await mount( + { + caughtUp: true, + events: [event(9_000, "test/said")], + older: pagesLeft(), + // the host says back what the frame reported of its kind file + hostError: "agent-kinds/claude.ts: Unexpected token", + }, + { error: "agent-kinds/claude.ts: Unexpected token" }, + ); + expect(document.querySelector("[data-type=error]")?.textContent).toBe( + "agent-kinds/claude.ts: Unexpected token", + ); + expect(frame.host.loadOlder).toHaveBeenCalled(); + expect(document.querySelector("[role=tab]")?.textContent).toBe("Events1+"); + expect(document.body.textContent).toContain("1 loaded of ~10,000 events"); +}); + +test("the frame hands the view the viewer the page names: a kind that draws AgentChat hides their own messages' line", async () => { + const seen: (string | undefined)[] = []; + const view: LoadedView = { + component: (props: AgentKindViewProps) => { + seen.push(props.me); + return null; + }, + ephemeralEvents: [], + }; + { + using _view = await mount({ caughtUp: true, older: null, me: "/members/ada" }, view); + expect(seen.at(-1)).toBe("/members/ada"); + } + // a page that does not say who looks: the view is told nothing + using _view = await mount({ caughtUp: true, older: null }, view); + expect(seen.at(-1)).toBeUndefined(); +}); + +test("the frame hands the view the version a read said: a kind that draws AgentChat closes the trace of the earlier version through the host", async () => { + using _layout = laidOut(); + const { html, ui } = agentKindViewKit; + const view: LoadedView = { + // as the kind `agent` writes its view + component: (props: AgentKindViewProps) => html`<${ui.AgentChat} ...${props} />`, + ephemeralEvents: [], + }; + using frame = await mount( + { + caughtUp: true, + older: null, + events: [event(1, "test/said")], + version: 1, + state: { llmRequest: 1 }, + }, + view, + ); + expect(frame.host.setState).not.toHaveBeenCalled(); + await act(async () => + frame.inputs.apply({ version: 2, events: { reset: [event(5, "test/said")] } }), + ); + expect(frame.host.setState.mock).toMatchObject({ + calls: [[{ llmRequest: undefined, scriptRun: undefined, event: undefined }]], + }); +}); + +test("the view's verbs stay the same functions while the host sends updates, so its rows stay drawn and an image is signed once", async () => { + const signedUrls = new Set<unknown>(); + const view: LoadedView = { + component: (props: AgentKindViewProps) => { + signedUrls.add(props.signedUrl); + return null; + }, + ephemeralEvents: [], + }; + using frame = await mount({ caughtUp: true, older: null }, view); + await act(async () => + frame.inputs.apply({ events: { prepend: [], append: [event(1, "test/said")] } }), + ); + await act(async () => + frame.inputs.apply({ events: { prepend: [], append: [event(2, "test/said")] } }), + ); + expect([...signedUrls]).toHaveLength(1); +}); + +test.for<{ name: string; offsets: number[]; answered: "rows" | "empty" }>([ + { name: "a session with words", offsets: [1, 2], answered: "rows" }, + { name: "a session in which nothing was said", offsets: [], answered: "empty" }, +])( + "a Claude-kind agent whose first read takes long never says that nothing was said before the read answers: $name", + async ({ offsets, answered }) => { + using _layout = laidOut(); + const log = heldLog(offsets); + // every text the document showed, at any moment + const said: string[] = []; + const watcher = new MutationObserver(() => said.push(document.body.textContent || "")); + watcher.observe(document.body, { childList: true, subtree: true, characterData: true }); + using _frame = await mountLive(log.itx); + // the read is out: looked at again and again across the wait + for (let round = 0; round < 15; round++) { + await act(() => new Promise((resolve) => setTimeout(resolve, 20))); + expect(document.body.textContent).not.toContain("Nothing said"); + expect(document.querySelectorAll("[data-slot=log-reading] [data-slot=spinner]")).toHaveLength( + 1, + ); + } + expect(log.asked()).toBe(1); + const beforeTheAnswer = said.length; + log.answer(); + // the log is published at most once a frame + for (let round = 0; round < 10; round++) + await act(() => new Promise((resolve) => setTimeout(resolve, 20))); + watcher.disconnect(); + expect(beforeTheAnswer).toBeGreaterThan(0); + expect(said.slice(0, beforeTheAnswer).filter((text) => text.includes("Nothing said"))).toEqual( + [], + ); + // a log that answered empty says so; one with words never did + expect(document.body.textContent?.includes("Nothing said yet.")).toBe(answered === "empty"); + expect(document.body.textContent?.includes("words at 2")).toBe(answered === "rows"); + expect(said.some((text) => text.includes("Nothing said"))).toBe(answered === "empty"); + expect(document.querySelector("[data-slot=log-reading]")).toBeNull(); + }, +); + +/** Older pages remain, and none is being read. */ +function pagesLeft() { + return { loading: false, exhausted: false }; +} + +function event(offset: number, type: string) { + return { offset, type, createdAt: "2026-11-16T00:00:00.000Z", payload: {} }; +} + +/** A kind's chat as a kind file writes one: its rows from the log, in the shell. */ +function kindView({ html, useMemo, ui }: typeof agentKindViewKit) { + return function SessionChat(props: AgentKindViewProps) { + const rows = useMemo( + () => + props.context.events + .filter((one) => one.type === "test/said") + .map((one) => ({ key: String(one.offset), offset: one.offset })), + [props.context.events], + ); + return html` + <${ui.AgentShell} ...${props} status=${{ text: "Idle", tone: "muted" }}> + <${ui.Feed} + rows=${rows} + older=${props.context.older} + empty=${html`<p>Nothing said yet.</p>`} + renderRow=${(row: { offset: number }) => html`<p>words at ${row.offset}</p>`} + /> + </${ui.AgentShell}> + `; + }; +} + +/** A context whose log holds a `test/said` event at each of `offsets`, and whose reads wait for + * `answer`. */ +function heldLog(offsets: number[]) { + let asked = 0; + let answer = () => {}; + const answered = new Promise<void>((resolve) => (answer = resolve)); + const head = offsets.at(-1) ?? 0; + const itx = { + subscribe: async () => ({ [Symbol.dispose]() {} }), + readEvents: async (after = 0) => { + asked += 1; + await answered; + return { + events: offsets + .filter((offset) => offset > after) + .map((offset) => event(offset, "test/said")), + atHead: true, + scannedThroughOffset: head, + }; + }, + subscriptions: { list: async () => [] }, + rpcStubs: { list: async () => [] }, + invoke: async () => ({ offset: head, state: {} }), + }; + return { itx, asked: () => asked, answer }; +} + +/** The page's side of a kind's frame, as the Dash's agent view does it: the agent's log read live, + * and what changed of it sent on as the bridge's updates. */ +function PageSide({ + itx, + inputs, + verbs, +}: { + itx: ReturnType<typeof heldLog>["itx"]; + inputs: InputsStore; + verbs: { loadOlder(): void }; +}) { + const log = useIterateContext(itx as never, { consumes: ["*"] }); + const sent = useRef<AgentKindViewInputs | undefined>(undefined); + useEffect(() => { + verbs.loadOlder = log.older.loadOlder; + const { loading, exhausted } = log.older; + const next: AgentKindViewInputs = { + path: "/agents/session", + events: log.events, + caughtUp: log.caughtUp, + error: log.error, + head: log.head, + older: exhausted ? null : { loading, exhausted }, + processors: log.processors, + presence: log.presence, + liveState: log.liveState, + version: versionOf(log), + hostError: undefined, + state: {}, + documentClass: "", + }; + const update = updateBetween(sent.current, next); + sent.current = next; + if (update) inputs.apply(update); + }); + return null; +} + +/** The page's side and the frame's view over one live log; disposing unmounts them and clears the + * page. */ +async function mountLive(itx: ReturnType<typeof heldLog>["itx"]) { + const inputs = new InputsStore(); + const verbs = { loadOlder: () => {} }; + const host = { loadOlder: () => verbs.loadOlder(), setState: () => {} }; + const root = createRoot(document.body.appendChild(document.createElement("div"))); + await act(async () => + root.render( + <> + <PageSide itx={itx} inputs={inputs} verbs={verbs} /> + <FrameView + inputs={inputs} + host={host as never} + view={{ component: kindView(agentKindViewKit), ephemeralEvents: [] }} + /> + </>, + ), + ); + return { + [Symbol.dispose]: () => { + act(() => root.unmount()); + document.body.replaceChildren(); + }, + }; +} + +/** A page with height, which jsdom lacks, so the virtual log draws its rows; disposing takes it + * back. */ +function laidOut() { + const sizes = { clientHeight: 600, offsetHeight: 0 }; + const own = Object.keys(sizes).map( + (name) => [name, Object.getOwnPropertyDescriptor(HTMLElement.prototype, name)] as const, + ); + for (const [name, value] of Object.entries(sizes)) + Object.defineProperty(HTMLElement.prototype, name, { configurable: true, get: () => value }); + return { + [Symbol.dispose]: () => { + for (const [name, descriptor] of own) + if (descriptor) Object.defineProperty(HTMLElement.prototype, name, descriptor); + else delete (HTMLElement.prototype as unknown as Record<string, unknown>)[name]; + }, + }; +} + +/** The frame's view over what a host sent; disposing unmounts it and clears the page. */ +async function mount( + { events = [], ...sent }: Partial<AgentKindViewInputs>, + view: LoadedView = { component: kindView(agentKindViewKit), ephemeralEvents: [] }, +) { + const inputs = new InputsStore(); + inputs.apply({ + path: "/agents/session", + events: { reset: [...events] }, + error: undefined, + head: 10_000, + processors: { rows: [], loaded: true }, + presence: { actors: [], rpcStubs: [] }, + liveState: {}, + hostError: undefined, + state: {}, + documentClass: "", + ...sent, + }); + const host = { loadOlder: vi.fn(), setState: vi.fn() }; + const root = createRoot(document.body.appendChild(document.createElement("div"))); + await act(async () => + root.render(<FrameView inputs={inputs} host={host as never} view={view} />), + ); + return { + host, + inputs, + [Symbol.dispose]: () => { + act(() => root.unmount()); + document.body.replaceChildren(); + }, + }; +}
A src/agent-kind-view/frame-view.tsx
@@ -0,0 +1,123 @@ +// The frame's React tree (frame.ts starts it): the kind's view with AgentChat-shaped props rebuilt +// from what the host sent, or the Events tab when there is no view, it failed to load, or it threw. +import { Component, useMemo, useSyncExternalStore, type ReactNode } from "react"; +import type { RpcStub } from "capnweb"; +import { AgentReading } from "../components/agent-chat/agent-reading.tsx"; +import { AgentShell } from "../components/agent-chat/agent-shell.tsx"; +import { AgentTabsInHeader } from "../components/agent-chat/agent-shell-contexts.ts"; +import { OLDER_FAILED } from "../components/virtual-log/older-pages.ts"; +import type { AgentKindViewHostApi, AgentKindViewInputs } from "./bridge.ts"; +import type { InputsStore, LoadedView } from "./frame.ts"; +import type { AgentKindViewProps } from "./types.ts"; + +type Host = RpcStub<AgentKindViewHostApi>; + +export function FrameView({ + inputs, + host, + view, +}: { + inputs: InputsStore; + host: Host; + view: LoadedView; +}) { + const held = useSyncExternalStore(inputs.subscribe, inputs.get); + // what the frame itself reported of its kind file, which the host says back as its own error + const kindFileError = "error" in view ? view.error : undefined; + // the verbs are the host's alone: each update of what it sent keeps them, so the view's rows + // stay memoised and an attachment keeps its signed URL + const verbs = useMemo(() => verbsOf(host), [host]); + const props = useMemo( + () => held && propsOf(held, host, verbs, kindFileError), + [held, host, verbs, kindFileError], + ); + // the page's header has the tabs: every shell in the frame draws none + return ( + <AgentTabsInHeader value={Boolean(held?.tabsInHeader)}> + <FrameBody props={props} view={view} /> + </AgentTabsInHeader> + ); +} + +function FrameBody({ props, view }: { props: AgentKindViewProps | undefined; view: LoadedView }) { + // before the host's first word: the loading state the view's own feed goes on with + if (!props) return <AgentReading />; + // the shell takes the view's props: its state is the page's search, which the shell reads whole + const shell = props as unknown as Parameters<typeof AgentShell>[0]; + if ("error" in view) return <AgentShell {...shell} error={view.error} />; + if (!view.component) return <AgentShell {...shell} />; + return ( + <ViewBoundary props={props}> + <view.component {...props} /> + </ViewBoundary> + ); +} + +/** AgentChat's props from what the host sent, its verbs calls back over the port. A read that + * failed (its own error, or a context the host could not open) stands in its error: the view's + * `older` says so, and its feed asks for no page and says nothing of the log. A kind file that + * failed to load (`kindFileError`) is no failed read: the log pages on under the Events tab. */ +function propsOf( + held: AgentKindViewInputs, + host: Host, + verbs: ReturnType<typeof verbsOf>, + kindFileError: string | undefined, +): AgentKindViewProps { + const readFailed = Boolean(held.error || (held.hostError && held.hostError !== kindFileError)); + const older = held.older && { ...held.older, loadOlder: () => void host.loadOlder() }; + return { + path: held.path, + context: { + events: held.events, + caughtUp: held.caughtUp, + error: held.error, + head: held.head, + older: readFailed ? OLDER_FAILED : older || undefined, + processors: held.processors, + presence: held.presence, + liveState: held.liveState, + version: held.version, + }, + error: held.hostError, + state: held.state, + ...verbs, + me: held.me, + presence: held.presenceOn, + }; +} + +/** What the view's props call back over the port. */ +function verbsOf( + host: Host, +): Pick< + AgentKindViewProps, + "onStateChange" | "onMessage" | "onAppend" | "signedUrl" | "storeFiles" | "widgetCalls" +> { + return { + onStateChange: (patch) => void host.setState(patch), + onMessage: async (input) => await host.message(input), + onAppend: async (events) => await host.append(events), + signedUrl: async (path) => await host.fileUrl(path), + storeFiles: async (files, key) => await host.storeFiles(files, key), + widgetCalls: { + callTool: async (call) => await host.callTool(call), + readResource: async (read) => await host.readResource(read), + }, + }; +} + +/** A view that throws while rendering leaves the Events tab, saying why. */ +class ViewBoundary extends Component< + { props: AgentKindViewProps; children: ReactNode }, + { error: string | null } +> { + override state: { error: string | null } = { error: null }; + static getDerivedStateFromError(error: unknown) { + return { error: error instanceof Error ? error.message : String(error) }; + } + override render() { + if (this.state.error) + return <AgentShell {...this.props.props} error={`The view failed: ${this.state.error}`} />; + return this.props.children; + } +}
A src/agent-kind-view/frame.ts
@@ -0,0 +1,138 @@ +// THE FRAME a kind's chat view runs in: a sandboxed iframe with an opaque origin and none of the +// page's cookies (host.ts makes it). View code comes from a config repo any member, or any +// member's agent, can commit to; in the page itself it would run as the viewer, in every mind +// they belong to. Here it holds only what the host hands over for one agent. +// +// `startAgentKindViewFrame()` is the frame's whole script: it says it is ready, takes the host's hello +// (the kind file and a port), loads the file (load.ts), tells the host what to read +// (`ephemeralEvents`), and renders `view(kit)` with AgentChat-shaped props rebuilt from the bridge's +// updates. With no kind file, or one that fails, it shows the Events tab. +import { createElement, type ComponentType } from "react"; +import { createRoot } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { newMessagePortRpcSession, RpcTarget } from "capnweb"; +import { + applyUpdate, + AGENT_KIND_VIEW_READY, + type AgentKindViewFrameApi, + type AgentKindViewHello, + type AgentKindViewHostApi, + type AgentKindNewAgentSummary, + type AgentKindViewInputs, + type AgentKindViewUpdate, +} from "./bridge.ts"; +import { FrameView } from "./frame-view.tsx"; +import { agentKindViewKit } from "./kit.ts"; +import { importAgentKind } from "./load.ts"; +import type { AgentKindNewAgent, AgentKindViewProps } from "./types.ts"; + +export function startAgentKindViewFrame(root: HTMLElement) { + const onHello = (event: MessageEvent) => { + const hello = event.data as AgentKindViewHello | undefined; + if (event.source !== window.parent || hello?.type !== "iterate/agent-kind-view") return; + const port = event.ports[0]; + if (!port) return; + window.removeEventListener("message", onHello); + void open(hello, port, root); + }; + window.addEventListener("message", onHello); + // the parent's origin is the app's, which an opaque origin cannot name: any parent will do, and + // the readiness says nothing + window.parent.postMessage({ type: AGENT_KIND_VIEW_READY }, "*"); +} + +async function open(hello: AgentKindViewHello, port: MessagePort, root: HTMLElement) { + const inputs = new InputsStore(); + const loading = viewOf(hello); + const host = newMessagePortRpcSession<AgentKindViewHostApi>( + port, + new FrameTarget(inputs, loading), + ); + const view = await loading; + void host.loaded( + "error" in view + ? { error: view.error } + : view.component + ? { + ephemeralEvents: view.ephemeralEvents, + newAgent: view.newAgent && newAgentSummary(view.newAgent), + } + : { none: true }, + ); + createRoot(root).render( + createElement( + QueryClientProvider, + { client: new QueryClient() }, + createElement(FrameView, { inputs, host, view }), + ), + ); +} + +/** The kind's component, or why there is none. */ +export type LoadedView = + | { + component: ComponentType<AgentKindViewProps>; + ephemeralEvents: string[]; + newAgent?: AgentKindNewAgent; + } + | { component: null } + | { error: string }; + +async function viewOf({ name, source }: AgentKindViewHello): Promise<LoadedView> { + if (!source) return { component: null }; + try { + const kind = await importAgentKind(source, name); + return { + component: kind.view(agentKindViewKit), + ephemeralEvents: kind.ephemeralEvents || [], + newAgent: kind.newAgent, + }; + } catch (error) { + return { error: `${name}: ${error instanceof Error ? error.message : String(error)}` }; + } +} + +/** What the host last sent, for React to read. */ +export class InputsStore { + #held: AgentKindViewInputs | undefined; + #listeners = new Set<() => void>(); + get = () => this.#held; + subscribe = (listener: () => void) => { + this.#listeners.add(listener); + return () => void this.#listeners.delete(listener); + }; + apply(update: AgentKindViewUpdate) { + this.#held = applyUpdate(this.#held, update); + // the page's theme is the frame's + document.documentElement.className = this.#held.documentClass; + for (const listener of this.#listeners) listener(); + } +} + +class FrameTarget extends RpcTarget implements AgentKindViewFrameApi { + #inputs: InputsStore; + #view: Promise<LoadedView>; + constructor(inputs: InputsStore, view: Promise<LoadedView>) { + super(); + this.#inputs = inputs; + this.#view = view; + } + update(update: Parameters<AgentKindViewFrameApi["update"]>[0]) { + this.#inputs.apply(update); + } + async start(input: Parameters<AgentKindViewFrameApi["start"]>[0]) { + const view = await this.#view; + const newAgent = "newAgent" in view ? view.newAgent : undefined; + if (!newAgent) throw new Error("this kind has no newAgent: its agents are not started here"); + return newAgent.start(input); + } +} + +/** A kind's `newAgent` as data: what crosses to the page. */ +function newAgentSummary(newAgent: AgentKindNewAgent): AgentKindNewAgentSummary { + return { + default: newAgent.default, + choices: newAgent.choices, + fields: newAgent.fields, + }; +}
A src/agent-kind-view/host.test.ts
@@ -0,0 +1,71 @@ +import { createElement } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { expect, test } from "vitest"; +import type { AgentKindViewInputs } from "./bridge.ts"; +import { + AgentKindViewFrame, + AgentKindViewLink, + frameCarriesStyle, + frameSheet, + type AgentKindViewVerbs, +} from "./host.ts"; + +test("the frame carries the page's own style text, and not the rules an editor of the page generated", () => { + // the page's theme, as a no-build app puts it into itself + expect(frameCarriesStyle(":root { color-scheme: light; --radius: 0.625rem; }")).toBe(true); + expect(frameCarriesStyle("")).toBe(true); + // CodeMirror's own: rules for the class names it counts out, which mean other things in a + // frame whose editors count again + expect( + frameCarriesStyle( + ".\u037c1 .cm-content { font-family: monospace }\n.\u037c1.cm-focused { outline: 1px dotted #212121 }", + ), + ).toBe(false); +}); + +test("a sheet on the page's own host goes into the frame as text, since the frame has no sign-in to ask for it with; a sheet of another host stays a link", () => { + const page = "https://agents.example.com"; + const theme = [ + ":root { color-scheme: light; --primary: oklch(0.2 0 0); }", + "body { margin: 0px; }", + ]; + // the mind's theme, behind the app's guard: its rules, and no address for the frame to ask + const own = frameSheet({ href: `${page}/theme.css`, media: "", rules: theme }, page); + expect(own).toBe(`<style>${theme.join("\n")}</style>`); + expect(own).not.toContain("theme.css"); + // this package's sheet on a module server: public, so the link, whether the page can read it or not + const kit = "https://esm.example.com/@iterate-com/ui@1.0.0/dist/styles.css"; + expect([ + frameSheet({ href: kit, media: "", rules: null }, page), + frameSheet({ href: kit, media: "", rules: [".flex { display: flex; }"] }, page), + ]).toEqual([`<link rel="stylesheet" href="${kit}">`, `<link rel="stylesheet" href="${kit}">`]); + // a sheet of the page's own that has not loaded yet: the link, as before + expect(frameSheet({ href: `${page}/app.css`, media: "", rules: null }, page)).toBe( + `<link rel="stylesheet" href="${page}/app.css">`, + ); + // the sheet's media goes with it, and no text of a rule ends the style element early + expect( + frameSheet( + { href: `${page}/print.css`, media: "print", rules: ['a::after { content: "</style>"; }'] }, + page, + ), + ).toBe('<style media="print">a::after { content: "<\\/style>"; }</style>'); +}); + +test("a tab that a link in a kind's view opens escapes the frame's sandbox, and the frame never gets the page's origin", () => { + const html = renderToStaticMarkup( + createElement(AgentKindViewFrame, { + link: new AgentKindViewLink("/agents/claude/demo", null), + frameScript: "https://esm.example.com/frame.js", + inputs: {} as AgentKindViewInputs, + verbs: {} as AgentKindViewVerbs, + }), + ); + const sandbox = (/sandbox="([^"]*)"/.exec(html)?.[1] ?? "").split(" "); + // without the escape, the vault's secret form in that tab is blocked: "the form's frame is + // sandboxed and the 'allow-forms' permission is not set" + expect(sandbox).toEqual( + expect.arrayContaining(["allow-scripts", "allow-popups", "allow-popups-to-escape-sandbox"]), + ); + expect(sandbox).not.toContain("allow-same-origin"); +});
A src/agent-kind-view/host.ts
@@ -0,0 +1,288 @@ +// THE HOST SIDE of a kind's chat view: the page that holds an agent's context puts the kind's view +// in a sandboxed frame (frame.tsx says why), feeds it the agent's live log, and answers its verbs +// for that one agent. The page owns the live read, the URL state and the verbs: +// +// const { link, loaded } = useAgentKindViewLink("agent-kinds/echo.ts", source); +// const log = useIterateContext(loaded && agent, { consumes: ["*", ...ephemeralEvents] }); +// <AgentKindViewFrame link={link} frameScript={url} inputs={{ path, events: log.events, … }} +// verbs={{ message, append, fileUrl, setState }} /> +import { createElement, useEffect, useMemo, useSyncExternalStore } from "react"; +import { newMessagePortRpcSession, RpcTarget, type RpcStub } from "capnweb"; +import { z } from "zod"; +import { + AGENT_KIND_VIEW_READY, + updateBetween, + type AgentKindViewFrameApi, + type AgentKindViewHello, + type AgentKindViewHostApi, + type AgentKindViewInputs, + type AgentKindViewLoaded, +} from "./bridge.ts"; + +/** What the frame may do, all of it to the one agent the page shows. A page that does not give + * `storeFiles` refuses a message with files that a kind appends itself. */ +export type AgentKindViewVerbs = Omit< + AgentKindViewHostApi, + "loaded" | "storeFiles" | "callTool" | "readResource" +> & + Partial<Pick<AgentKindViewHostApi, "storeFiles" | "callTool" | "readResource">>; + +/** One frame's link to the page: its handshake, its session, what it reported, what it holds. */ +export class AgentKindViewLink { + readonly name: string; + readonly source: string | null; + /** The page's verbs as of its last render. */ + verbs: AgentKindViewVerbs | undefined; + #loaded: AgentKindViewLoaded | undefined; + #listeners = new Set<() => void>(); + #frame: RpcStub<AgentKindViewFrameApi> | undefined; + #sent: AgentKindViewInputs | undefined; + #latest: AgentKindViewInputs | undefined; + + constructor(name: string, source: string | null) { + this.name = name; + this.source = source; + } + + loaded = () => this.#loaded; + subscribe = (listener: () => void) => { + this.#listeners.add(listener); + return () => void this.#listeners.delete(listener); + }; + + /** Sends the frame what changed since it last heard. */ + push(inputs: AgentKindViewInputs) { + this.#latest = inputs; + if (!this.#frame) return; + const update = updateBetween(this.#sent, inputs); + this.#sent = inputs; + if (update) void this.#frame.update(update); + } + + /** The iframe's ref: answers its readiness with the hello and a port, each time it loads. */ + attach = (iframe: HTMLIFrameElement | null) => { + if (!iframe) return; + const onReady = (event: MessageEvent) => { + if (event.source !== iframe.contentWindow || event.data?.type !== AGENT_KIND_VIEW_READY) + return; + this.#close(); + const channel = new MessageChannel(); + const hello: AgentKindViewHello = { + type: "iterate/agent-kind-view", + name: this.name, + source: this.source, + }; + // the frame's origin is opaque: "*" is the only name it has + iframe.contentWindow?.postMessage(hello, "*", [channel.port2]); + this.#frame = newMessagePortRpcSession<AgentKindViewFrameApi>( + channel.port1, + new HostTarget(this), + ); + if (this.#latest) this.push(this.#latest); + }; + window.addEventListener("message", onReady); + return () => { + window.removeEventListener("message", onReady); + this.#close(); + }; + }; + + /** The kind's `newAgent.start(input)`, run in the frame: the events that start an agent of the + * kind. Refused until the frame has said it is ready. */ + async start(input: Parameters<AgentKindViewFrameApi["start"]>[0]): Promise<unknown[]> { + if (!this.#frame) throw new Error(`${this.name} has not loaded yet`); + // the frame runs a config repo's code: what it answers is checked to be a list here + return z.array(z.unknown()).parse(await this.#frame.start(input)); + } + + setLoaded(result: AgentKindViewLoaded) { + this.#loaded = result; + for (const listener of this.#listeners) listener(); + } + + #close() { + this.#frame?.[Symbol.dispose](); + this.#frame = undefined; + this.#sent = undefined; + } +} + +/** The page's side of the session: the frame's report, and its verbs, passed to the page's. */ +class HostTarget extends RpcTarget implements AgentKindViewHostApi { + #link: AgentKindViewLink; + constructor(link: AgentKindViewLink) { + super(); + this.#link = link; + } + #verbs(): AgentKindViewVerbs { + if (!this.#link.verbs) throw new Error("the page is not showing this agent"); + return this.#link.verbs; + } + loaded(result: Parameters<AgentKindViewHostApi["loaded"]>[0]) { + this.#link.setLoaded(result); + } + message(input: Parameters<AgentKindViewHostApi["message"]>[0]) { + return this.#verbs().message(input); + } + append(events: unknown[]) { + return this.#verbs().append(events); + } + fileUrl(path: string) { + return this.#verbs().fileUrl(path); + } + storeFiles(...[files, key]: Parameters<AgentKindViewHostApi["storeFiles"]>) { + const { storeFiles } = this.#verbs(); + if (!storeFiles) throw new Error("This page cannot store files for this agent."); + return storeFiles(files, key); + } + setState(patch: Parameters<AgentKindViewHostApi["setState"]>[0]) { + this.#verbs().setState(patch); + } + loadOlder() { + this.#verbs().loadOlder(); + } + callTool(call: Parameters<AgentKindViewHostApi["callTool"]>[0]) { + const { callTool } = this.#verbs(); + if (!callTool) throw new Error("This page cannot call an MCP App's server for this agent."); + return callTool(call); + } + readResource(read: Parameters<AgentKindViewHostApi["readResource"]>[0]) { + const { readResource } = this.#verbs(); + if (!readResource) throw new Error("This page cannot read an MCP App's server for this agent."); + return readResource(read); + } +} + +/** A link for the kind file `name` (its `source`, or `null` for a kind without one), and what its + * frame reported once it read the file: until then, `undefined`. */ +export function useAgentKindViewLink(name: string, source: string | null) { + const link = useMemo(() => new AgentKindViewLink(name, source), [name, source]); + const loaded = useSyncExternalStore(link.subscribe, link.loaded, () => undefined); + return { link, loaded }; +} + +export function AgentKindViewFrame({ + link, + frameScript, + inputs, + verbs, +}: { + link: AgentKindViewLink; + /** The frame's script (`startAgentKindViewFrame()`, bundled): a URL the page serves. */ + frameScript: string; + inputs: AgentKindViewInputs; + verbs: AgentKindViewVerbs; +}) { + // the newest verbs answer the frame: they close over the page's latest render + link.verbs = verbs; + // the frame is another window: what the page renders is sent to it, as it changes + useEffect(() => link.push(inputs), [link, inputs]); + const srcDoc = useMemo(() => frameDocument(frameScript), [frameScript]); + return createElement("iframe", { + ref: link.attach, + title: link.name, + // scripts, and links that open a tab or download a file; never the page's origin. A tab that + // a link opens escapes the sandbox: it is an ordinary page of the link's own origin, which the + // view cannot read. A sandboxed tab would have no origin, so no sign-in, no passkey and, without + // `allow-forms`, no form: the vault's secret form could not be sent from it. + sandbox: "allow-scripts allow-popups allow-popups-to-escape-sandbox allow-downloads", + srcDoc, + className: "min-h-0 w-full flex-1 border-0", + }); +} + +/** A FRAME THAT ONLY LOADS A KIND FILE, drawn nowhere: what it reports (`link.loaded()`: the + * kind's `newAgent`) and its `start` (`link.start`), for the Dash's New agent. It is sent no + * inputs, and has no verbs: it cannot read or change any agent. */ +export function AgentKindStarterFrame({ + link, + frameScript, +}: { + link: AgentKindViewLink; + frameScript: string; +}) { + link.verbs = undefined; + const srcDoc = useMemo(() => frameDocument(frameScript), [frameScript]); + return createElement("iframe", { + ref: link.attach, + title: link.name, + sandbox: "allow-scripts", + srcDoc, + hidden: true, + "aria-hidden": true, + tabIndex: -1, + }); +} + +/** WHETHER THE FRAME CARRIES A `<style>` OF THE PAGE. Not one that CodeMirror made: an editor + * writes its themes into its document as rules for class names it generates by counting + * (`.ͼ1`, `.ͼ2`, …). The frame's own editors count from one again, for other rules, so the + * page's rules would land on the wrong classes there: a composer in a fixed-width font with the + * editor's default dotted focus ring. The frame's editors write their own. */ +export const frameCarriesStyle = (text: string) => !text.includes("\u037c"); + +/** A STYLE SHEET THAT THE PAGE LINKS, AS THE FRAME CARRIES IT. The frame has no sign-in: a request + * from it is answered as nobody's. So a sheet on the page's own host (a mind's theme, an app's own + * sheet), which is behind the app's guard, would come back 401 there, and the view would be drawn + * without the mind's theme. Such a sheet goes as TEXT: the rules that the page has loaded. A sheet + * of another host (this package's, on a module server) is public, large and cached, and stays a + * link. `rules` is null when the page cannot read the sheet (it has not loaded yet): then the + * link, which is what the frame had before. A rule's own `url()` is then read from the page's + * address, not from the sheet's. */ +export function frameSheet( + sheet: { href: string; media: string; rules: string[] | null }, + pageOrigin: string, +): string { + const media = sheet.media ? ` media="${attribute(sheet.media)}"` : ""; + if (!sheet.rules || new URL(sheet.href).origin !== pageOrigin) + return `<link rel="stylesheet" href="${attribute(sheet.href)}"${media}>`; + return `<style${media}>${styleText(sheet.rules.join("\n"))}</style>`; +} + +/** CSS as the text of a `<style>` element: no `</` in it ends the element early. In CSS a + * backslash before the slash is the same slash. */ +const styleText = (css: string) => css.replaceAll("</", "<\\/"); + +/** The rules of a sheet that the page has loaded, each as text, or null when the page may not + * read them: a sheet that is still loading has none, and one of another host refuses. */ +function rulesOf(sheet: CSSStyleSheet | null): string[] | null { + try { + return sheet && [...sheet.cssRules].map((rule) => rule.cssText); + } catch { + return null; + } +} + +/** The frame's page: the host page's own stylesheets (its theme and every class iterate's parts + * use), a root that fills it, and the frame's script. */ +function frameDocument(frameScript: string): string { + // a server render has no document: the frame is the browser's + if (!globalThis.document) return ""; + const styles = [...document.querySelectorAll<HTMLElement>('link[rel="stylesheet"], style')] + .flatMap((element) => { + if (element instanceof HTMLLinkElement) + return [ + frameSheet( + { href: element.href, media: element.media, rules: rulesOf(element.sheet) }, + location.origin, + ), + ]; + const text = element.textContent || ""; + return frameCarriesStyle(text) ? [`<style>${styleText(text)}</style>`] : []; + }) + .join("\n"); + return `<!doctype html> +<html class="${attribute(document.documentElement.className)}"> +<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"> +${styles} +</head> +<body class="${attribute(document.body.className)}" style="margin:0"> +<div id="root" style="height:100vh;display:flex;flex-direction:column"></div> +<script src="${attribute(new URL(frameScript, location.href).href)}"></script> +</body> +</html>`; +} + +function attribute(value: string): string { + return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<"); +}
A src/agent-kind-view/kit.ts
@@ -0,0 +1,21 @@ +// What a kind's `view(kit)` builds with (types.ts `AgentKindViewKit`): htm over React, the derived and +// server-state hooks, and iterate's chat parts. No useState or useEffect: a view derives what it +// shows from its props. +import htm from "htm"; +import { createElement, useMemo } from "react"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import { AgentChat } from "../components/agent-chat/agent-chat.tsx"; +import { AgentShell } from "../components/agent-chat/agent-shell.tsx"; +import { Composer, Feed, Markdown, MessageBubble } from "../components/agent-chat/chat-parts.tsx"; +import { Badge } from "../components/ui/badge.tsx"; +import { Button } from "../components/ui/button.tsx"; +import { Spinner } from "../components/ui/spinner.tsx"; +import type { AgentKindViewKit } from "./types.ts"; + +export const agentKindViewKit: AgentKindViewKit = { + html: htm.bind(createElement), + useMemo, + useQuery, + useMutation, + ui: { AgentShell, AgentChat, Feed, MessageBubble, Composer, Markdown, Badge, Button, Spinner }, +};
A src/agent-kind-view/load.test.ts
@@ -0,0 +1,79 @@ +// A kind file's server-only imports in the frame: harmless while unused, a clear failure when used. +import { expect, test } from "vitest"; +import { importAgentKind } from "./load.ts"; + +test("a kind file whose server import is used only in processEvent loads, view and all", async () => { + const kind = await importAgentKind( + ` + import type { AgentKind } from "@iterate-com/ui/agent-kind-view"; + import { createXai } from "@ai-sdk/xai"; + import installRows, * as install from "iterate/agents/install"; + import { generateText as generate } from "ai"; + + const label = (path: string): string => path.split("/").at(-1)!; + + export default { + kind: "grok", + ephemeralEvents: ["x.ai/grok/token"], + processEvent: async ({ event, itx }) => { + if (event.type === "events.iterate.com/agent/message-received" && event.path.startsWith("/agents/grok/")) { + await installRows(itx, event.path); + install.other(); + await generate({ model: createXai()("grok-4"), prompt: event.payload.message }); + } + }, + view: () => (props: { path: string }) => label(props.path), + } satisfies AgentKind; + `, + "agent-kinds/grok.ts", + ); + expect(kind).toMatchObject({ + kind: "grok", + ephemeralEvents: ["x.ai/grok/token"], + }); + expect((kind.view as any)()({ path: "/agents/grok/1" })).toBe("1"); +}); + +test("a server import used at the top of the file fails, naming the import and where to use it", async () => { + await expect( + importAgentKind( + ` + import { createXai } from "@ai-sdk/xai"; + const xai = createXai({ apiKey: "…" }); + export default { kind: "grok", view: () => () => null }; + `, + "agent-kinds/grok.ts", + ), + ).rejects.toThrow( + "createXai from @ai-sdk/xai only works on the server: this file's view runs in the browser, so use it inside processEvent, not at the top of the file", + ); +}); + +test("a default or namespace import fails the same way once it is used", async () => { + await expect( + importAgentKind( + ` + import xai from "@ai-sdk/xai"; + xai.languageModel("grok-4"); + export default { kind: "grok", view: () => () => null }; + `, + "agent-kinds/grok.ts", + ), + ).rejects.toThrow("The default export of @ai-sdk/xai only works on the server"); + await expect( + importAgentKind( + ` + import * as ai from "ai"; + new ai.Agent(); + export default { kind: "grok", view: () => () => null }; + `, + "agent-kinds/grok.ts", + ), + ).rejects.toThrow("Agent from ai only works on the server"); +}); + +test("a file without a view is refused, saying what to export", async () => { + await expect( + importAgentKind(`export default { kind: "grok" };`, "agent-kinds/grok.ts"), + ).rejects.toThrow("agent-kinds/grok.ts has no default export with a view"); +});
A src/agent-kind-view/load.ts
@@ -0,0 +1,130 @@ +// LOADING A KIND FILE IN THE BROWSER: the frame (frame.tsx) runs `agent-kinds/<kind>.ts` from a +// config repo for its `view`. The file is the worker's too, so it may import server-only packages +// (an AI SDK, `iterate/agents/install`) for its `processEvent`. Here: +// +// 1. its types are stripped by the same sucrase call the platform's worker loader makes (core/mind-worker +// `stripTypes` in src/context/module-resolution.ts), so a file that loads there loads here; +// 2. every static import becomes a `const` destructured from a SERVER-ONLY MODULE: one poisoned +// value per export. Reading an export is fine (an unused import, or one used only inside +// `processEvent`, costs nothing); using one (a property, a call, `new`) throws, naming it: +// +// import { createXai } from "@ai-sdk/xai"; → const { createXai } = serverOnly("@ai-sdk/xai"); +// const xai = createXai(); → Error: createXai from @ai-sdk/xai only works +// on the server: this file's view runs in the … +// +// 3. the result is imported from a data: URL. +import { init, parse } from "es-module-lexer"; +import { transform } from "sucrase"; +import type { AgentKind } from "./types.ts"; + +/** The global a rewritten import reads its server-only module from: a module loaded from a URL + * has no other way to reach the frame's code. */ +const SERVER_ONLY = "__iterateAgentKindServerOnly"; + +/** The kind file at `name`, its `source` loaded as the frame loads it. */ +export async function importAgentKind(source: string, name: string): Promise<AgentKind> { + const code = await browserModuleOf(source, name); + (globalThis as Record<string, unknown>)[SERVER_ONLY] = serverOnlyModule; + const url = `data:text/javascript;base64,${base64(code)}`; + const loaded = (await import(/* @vite-ignore */ url)) as { default?: AgentKind }; + const kind = loaded.default; + if (!kind || typeof kind.view !== "function") + throw new Error(`${name} has no default export with a view: export default { kind, view, … }`); + return kind; +} + +/** A kind file's source as a module the browser can load: types stripped, every import a stub. */ +export async function browserModuleOf(source: string, name: string): Promise<string> { + let code: string; + try { + // the platform's worker loader's own call: core/mind-worker/src/context/module-resolution.ts `stripTypes` + code = transform(source, { + transforms: ["typescript"], + disableESTransforms: true, + filePath: name, + }).code; + } catch (error) { + throw new Error(`${name} does not parse as TypeScript: ${String(error)}`); + } + await init; + const [imports] = parse(code, name); + let out = ""; + let at = 0; + for (const imp of imports) { + // a static import statement (`t` 1): dynamic imports, `import.meta` and re-exports stay as + // they are. A dynamic one only runs if the view calls it. + if (imp.t !== 1 || !imp.n) continue; + const statement = code.slice(imp.ss, imp.se); + if (!statement.startsWith("import")) continue; + out += code.slice(at, imp.ss) + stubbed(statement, imp.n); + at = imp.se; + } + return out + code.slice(at); +} + +/** One import statement as `const`s read from the module's stub. */ +function stubbed(statement: string, specifier: string): string { + const module = `globalThis.${SERVER_ONLY}(${JSON.stringify(specifier)})`; + const clause = statement.match(/^import\s*([\s\S]*?)\s*from\s*["'][^"']*["']/)?.[1]; + // `import "x"`: for its effects, which are the server's + if (!clause) return ""; + const namespace = clause.match(/\*\s*as\s+([\w$]+)/)?.[1]; + const named = clause.match(/\{([\s\S]*)\}/)?.[1]; + const defaultName = clause.match(/^([\w$]+)\s*(,|$)/)?.[1]; + const parts: string[] = []; + if (named) { + const bindings = named + .split(",") + .map((binding) => binding.trim()) + .filter(Boolean) + .map((binding) => { + const [imported, local] = binding.split(/\s+as\s+/); + return local ? `${imported}: ${local}` : imported; + }); + if (bindings.length) parts.push(`{ ${bindings.join(", ")} }`); + } + const lines: string[] = []; + if (defaultName) lines.push(`const ${defaultName} = ${module}.default;`); + if (namespace) lines.push(`const ${namespace} = ${module};`); + for (const part of parts) lines.push(`const ${part} = ${module};`); + return lines.join(" "); +} + +/** A module the frame cannot load: each export, read, is a poisoned value. `then` and + * `__esModule` are absent, so awaiting the module or interop checks see a plain object. */ +export function serverOnlyModule(specifier: string): Record<string, unknown> { + return new Proxy( + {}, + { + get(_, name) { + if (name === "then" || name === "__esModule" || typeof name === "symbol") return undefined; + return poisoned( + name === "default" ? `The default export of ${specifier}` : `${name} from ${specifier}`, + ); + }, + }, + ); +} + +/** A stand-in for a server-only export that throws on any use: a property read, a call, `new`. */ +function poisoned(label: string): unknown { + const fail = (): never => { + throw new Error( + `${label} only works on the server: this file's view runs in the browser, so use it inside processEvent, not at the top of the file`, + ); + }; + return new Proxy(function serverOnly() {}, { + get: (_, property) => (property === "then" ? undefined : fail()), + set: fail, + has: fail, + apply: fail, + construct: fail, + }); +} + +/** UTF-8 text as base64. */ +function base64(text: string): string { + let binary = ""; + for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte); + return btoa(binary); +}
A src/agent-kind-view/types.ts
@@ -0,0 +1,205 @@ +// AN AGENT KIND's view (iterate/agents/kinds `AgentKind` says what a kind is). A kind file's default +// export `satisfies AgentKind` from here, which is that one with `view` typed: the mind worker +// imports the file (`makeAgentKind`) and runs `processEvent`; the Agents app's sandboxed frame loads +// the same source for `view` (frame.ts), its server-only imports stubbed (load.ts). +// +// import type { AgentKind } from "@iterate-com/ui/agent-kind-view"; +// +// export default { +// kind: "echo", +// view: ({ html, useMemo, ui }) => (props) => html`<${ui.AgentShell} ...${props} />`, +// } satisfies AgentKind; +// +// THE AGENT (the kind `agent`: its facts are agent-chat/agent-facts.ts) needs no adapter: `AgentChat` +// reads its facts, its live state and its request traces, and its composer appends the Dash's +// words and files as one `agent-ui/message-received` (`storeFiles`, then `onAppend`). Its file: +// +// export default { +// kind: "agent", +// processEvent, +// // the streamed windows of an answer, which a wildcard never matches +// ephemeralEvents: ["events.iterate.com/llm-request/response-frame-received"], +// newAgent: { default: true, choices: [{ id: "agent", label: "Agent", byPerson: true }], start }, +// view: ({ html, ui }) => (props) => html`<${ui.AgentChat} ...${props} />`, +// } satisfies AgentKind; +// +// Types only: nothing here runs. +// Self-contained (React, react-query and iterate's types only), so a mind's config repo, a test +// program or a package without JSX can name them. +import type { ComponentType } from "react"; +import type { useMutation, useQuery } from "@tanstack/react-query"; +import type { AgentKind as SdkAgentKind } from "iterate/agents/kinds"; + +/** One event of the agent's log, as the view reads it. */ +export type AgentKindViewEvent = { + type: string; + offset: number; + createdAt: string; + payload?: any; + path?: string; + ephemeral?: boolean; + source?: Record<string, unknown>; +}; + +/** The chat's state (agent-chat-search.ts `AgentChatState`): the page's URL search. `view: + * "events"` is the Events tab, and `event` the offset its inspector shows. */ +export type AgentKindViewState = { + view?: "chat" | "events"; + event?: number; + [key: string]: unknown; +}; + +/** What a view is handed: AgentChat's props. Authority over the agent reaches it only through + * these, scoped to this one agent. */ +export type AgentKindViewProps = { + /** The agent's path. */ + path: string; + /** The agent's log, live: every durable event, and the kind's `ephemeralEvents`. */ + context: { + events: readonly AgentKindViewEvent[]; + caughtUp: boolean; + error?: string; + /** Pass it on to `Feed` as it is. None: the whole log is held. `failed`: the read failed. */ + older?: { loadOlder(): void; loading: boolean; exhausted: boolean; failed?: boolean }; + head?: number; + processors: { rows: readonly any[]; loaded: boolean; error?: string }; + presence: { actors: readonly any[]; rpcStubs: readonly string[] }; + liveState: Record<string, any>; + /** The version of the agent's path that `events` are of, once a read has said it. A new + * version is a new conversation: `AgentChat` closes what it had open of the last one. */ + version?: number; + }; + /** The host's own failure (opening the agent's context). */ + error: string | undefined; + /** The chat's state, which is the page's URL: the tab, the Events tab's choices. */ + state: AgentKindViewState; + onStateChange: (patch: Partial<AgentKindViewState>) => void; + /** Say something to the agent: `itx.agents.get(path).message(…)`. */ + onMessage: (input: { + message: string; + files: { contentType: string; filename: string; data: string }[]; + /** The message's own key, from `AgentChat`: the host sends it on, and a send tried again + * lands once. */ + key?: string; + }) => Promise<void>; + /** Append events to the agent's context, as a person wrote them. */ + onAppend: ((events: unknown[]) => Promise<unknown>) | undefined; + /** Stores a message's files under the agent's path, as `message()` stores them (the same path + * form), and answers each as the mind's file store holds it: a view then names them in a fact + * it appends. `key`: the message's own key, so the same files sent again go to the same paths. + * None: the host cannot store files (a page older than this verb). */ + storeFiles?: ( + files: { contentType: string; filename: string; data: string }[], + key?: string, + ) => Promise<{ contentType: string; filename: string; path: string; size: number }[]>; + /** A signed download URL for a file under the agent's path. */ + signedUrl: (path: string) => Promise<string>; + /** The viewer's actor id or address, when the page knows it: `AgentChat` draws no sender line + * under their own messages. */ + me?: string; + /** Another server's MCP App in the feed calls its server through these, as this agent: pass + * them on to `AgentChat` as `widgetCalls`. None: a page older than these verbs. */ + widgetCalls?: { + callTool(call: { + path: string; + key: string; + server: string; + headers?: Record<string, string>; + name: string; + args: Record<string, unknown>; + }): Promise<unknown>; + readResource(read: { + path: string; + server: string; + headers?: Record<string, string>; + uri: string; + }): Promise<unknown>; + }; + /** `true`: `AgentChat` shows who else is here and who is typing. A kind's view that wants it + * also names `PRESENCE_EVENT_TYPES` (the kit's `lib/presence`) in its `ephemeralEvents`: the + * host's row of the log is then a page, and the view hears the others' status. */ + presence?: boolean; +}; + +/** iterate's components a view builds with (agent-chat/chat-parts.tsx and agent-shell.tsx say + * what each takes; `AgentChat` takes a view's own props). */ +export type AgentKindViewUi = Record< + | "AgentShell" + | "AgentChat" + | "Feed" + | "MessageBubble" + | "Composer" + | "Markdown" + | "Badge" + | "Button" + | "Spinner", + ComponentType<any> +>; + +/** What `view` builds with. `html` is htm over React's createElement: the worker strips a kind + * file's types and nothing else, so there is no JSX. No `useState`, no `useEffect`: what a view + * holds is derived (`useMemo`) or is the server's (`useQuery`, `useMutation`). */ +export type AgentKindViewKit = { + html: (strings: TemplateStringsArray, ...values: unknown[]) => any; + useMemo: <T>(factory: () => T, deps: readonly unknown[]) => T; + useQuery: typeof useQuery; + useMutation: typeof useMutation; + ui: AgentKindViewUi; +}; + +/** How one of a kind's agents is started: its `choices`, the `fields` each choice takes, and + * `start`, the events appended to the new agent's path before its first message. The Dash's New + * agent starts iterate agents, or the kind that says `default: true`. */ +export type AgentKindNewAgent = { + /** `true`: the Dash's New agent starts this kind's agent, on its first choice, with each + * field at its `defaultValue`: it appends `start(…)` to the new path, then the first message as + * `agent-ui/message-received`. One kind of a mind says it; with two, the first by kind name. */ + default?: true; + /** `byPerson: true`: this choice's new agents may be born in the folder of the person who + * starts them, `/agents/people/<person>/<kind>/<moment>` (lib/agent-summary.ts + * `newAgentPath`). A kind says it when its own file takes that path. Without it they are born at + * `/agents/<kind>/<moment>`. */ + choices: { id: string; label: string; byPerson?: boolean }[]; + fields?: AgentKindNewAgentField[]; + /** `path` is the new agent's; `fields` are the picked choice's alone, each by its name. */ + start(input: { choice: string; fields: Record<string, string>; path: string }): unknown[]; + /** A line about what the choice and its fields' values as typed will do (a + * runner that has to be started first, say), or null for none. `mind` is the mind's address. + * Text, where `backticks` mark code a person may copy. */ + describe?(input: { choice: string; fields: Record<string, string>; mind: string }): string | null; +}; +/** A field of a choice: a line of text, or with `type: "checkbox"` a tick box, whose value + * is "on" when ticked and "" when not (`defaultValue: "on"` starts it ticked). `choices`: the ids + * of the choices that show the field; none: every choice of the kind. + * + * `type: "select"` with `options`: a list to pick one of (the models a choice can run, say). Its + * value is always one of the options: `defaultValue` at first, or the first option when that is + * not among them. Two fields of one name, each for other `choices`, give each choice its own + * list. A page older than this type draws a line of text with `defaultValue` in it, where a + * person can type anything: `start` must refuse a value that is not an option. + * + * `viewerDefault`: a first value made for the person who looks, where `{name}` is their first + * name, from the address they sign in with (`"{name}.laptop"` opens as `misha.laptop`); for + * someone with no such name the field opens with `defaultValue`. + * + * `offWhen`: a tick box that another field turns off. While the field named `field` has the + * value `is`, the box's value is "" and it is drawn unticked and disabled. A page older than + * this key still draws the box as it was, so `start` decides by the other field's value too. */ +export type AgentKindNewAgentField = { + name: string; + label: string; + defaultValue: string; + type?: "text" | "checkbox" | "select"; + options?: string[]; + choices?: string[]; + viewerDefault?: string; + offWhen?: { field: string; is: string }; +}; + +/** A kind of agent whose view is a React component: iterate/agents/kinds' `AgentKind` (`kind`, + * `processEvent`, `ephemeralEvents`), with the chat filled in, and how one is started. */ +export type AgentKind = SdkAgentKind< + (kit: AgentKindViewKit) => ComponentType<AgentKindViewProps> +> & { + newAgent?: AgentKindNewAgent; +};
A src/apps/base-path.ts
@@ -0,0 +1,75 @@ +// base-path.ts — THE PATH A PROXIED APP IS SERVED UNDER in the browser (packages/notes; iterate/docs' Docs app has a copy). A +// mind's config worker (the app's config-worker.ts) proxies it: on a host of its own under subdomains ingress +// (`notes--<mind>.<base>`) the base path is "", and under paths ingress it is +// `/minds/<mind>/<routingSlug>`. There the platform's edge strips that prefix from the URL the app sees and +// says it in `x-iterate-base-path` (iterate/mind-ingress), while the browser's URLs keep it. So +// every path the page names carries it — its links, its assets (the app's server.ts `transformAssets`), its +// server functions (the app's start.ts) — and the router drops it on the way in (`basePathRewrite`). The +// browser adapter's `/.auth/*` and `/api` stay root paths: the host's, which the platform answers +// (core/mind-worker/src/http.ts); under paths they are its own, on the origin the page shares with it. +// +// A dev server behind `iterate tunnel` under paths starts under the tunnel's base path (README): +// Vite's `base`, which its module URLs and its HMR socket carry. The page's base path takes the +// build's place in every URL the build names (`underBasePath`), and the URL the tunnel hands over, +// base path on, is served as the edge's is (`withoutBuildBasePath`). A deployed build's base is `/`. +import type { LocationRewrite } from "@tanstack/react-router"; +import { ITERATE_BASE_PATH_HEADER } from "iterate/mind-ingress"; + +/** The build's base path: Vite's `base` without its trailing slash, "" but on a dev server + * started under a tunnel's base path. */ +export const buildBasePath = import.meta.env.BASE_URL.replace(/\/$/, ""); + +/** The base path a request says, else the build's — plain path segments only: the header reaches + * the app's Worker from anyone who fetches it, and what it says is written into the page's links. */ +export function basePathOf(headers: Headers) { + const value = headers.get(ITERATE_BASE_PATH_HEADER) || ""; + return /^(?:\/[a-z0-9-]+)+$/.test(value) ? value : buildBasePath; +} + +/** The base path in the browser: the server render writes it on `<html data-base-path>` + * (the app's routes/__root.tsx), before any script runs. */ +export function documentBasePath() { + return document.documentElement.dataset.basePath || ""; +} + +/** A URL the build names — a manifest's script or stylesheet, a `?url` import — under the page's + * base path in place of the build's. */ +export function underBasePath(basePath: string, url: string) { + return url.startsWith(`${buildBasePath}/`) + ? `${basePath}${url.slice(buildBasePath.length)}` + : url; +} + +/** The request as the edge hands a proxied app over, its base path stripped: a dev server under + * a tunnel's base path is handed the URL the browser addressed (the tunnel puts it back). */ +export function withoutBuildBasePath(request: Request) { + if (!buildBasePath) return request; + const url = new URL(request.url); + url.pathname = withoutBasePath(url.pathname, buildBasePath); + return new Request(url, request); +} + +/** The router's side of the base path: the browser's URL without it on the way in, with it on the + * way out. A rewrite, not TanStack's `basepath`, which Start sets from its `router.basepath` + * (the app's vite.config.ts) on every request (start-server-core `createStartHandler`, start-client-core + * `hydrateStart`). */ +export function basePathRewrite(basePath: string): LocationRewrite | undefined { + if (!basePath) return undefined; + return { + input: ({ url }) => { + url.pathname = withoutBasePath(url.pathname, basePath); + return url; + }, + output: ({ url }) => { + url.pathname = `${basePath}${url.pathname}`; + return url; + }, + }; +} + +/** `pathname` without `basePath` in front when it is under it, else as it is. */ +function withoutBasePath(pathname: string, basePath: string) { + return pathname === basePath || pathname.startsWith(`${basePath}/`) + ? pathname.slice(basePath.length) || "/" + : pathname; +}
A src/apps/document.test.tsx
@@ -0,0 +1,68 @@ +// What an app shows when a load fails, from the two pieces every app's routes name: the document +// as the root's `shellComponent`, and a mind's frame as its route's `errorComponent`. Each is the +// server's render of a router whose loader threw. +import { renderToString } from "react-dom/server"; +import { + createMemoryHistory, + createRootRoute, + createRoute, + RouterProvider, +} from "@tanstack/react-router"; +import { expect, test } from "vitest"; +import { MindAppLoadError } from "../components/mind-app-shell.tsx"; +import { AppDocumentShell, AppRoot } from "./document.tsx"; +import { appHead } from "./head.ts"; +import { createAppRouter } from "./router.tsx"; + +test("a root loader that fails still renders the document: the head the root names, the failure and a retry", async () => { + const root = createRootRoute({ + loader: (): { posthogProjectKey: string | null } => { + throw new Error("the deployment's configuration could not be read"); + }, + head: () => appHead({ title: "Agents", stylesheet: "/assets/styles.css" }), + shellComponent: ({ children }) => ( + <AppDocumentShell icon="/client-logo.svg">{children}</AppDocumentShell> + ), + component: () => <AppRoot posthogProjectKey={root.useLoaderData().posthogProjectKey} />, + }); + const router = createAppRouter({ + routeTree: root, + history: createMemoryHistory({ initialEntries: ["/"] }), + origin: "https://agents.example.com", + }); + await router.load(); + const html = renderToString(<RouterProvider router={router} />); + expect(html).toMatch(/^<html lang="en"/); + expect(html).toContain('<link rel="stylesheet" href="/assets/styles.css"'); + expect(html).toContain("<title>Agents</title>"); + expect(html).toContain("Something went wrong"); + expect(html).toContain("the deployment's configuration could not be read"); + expect(html).toContain("Try again"); + expect(html).toContain("</body></html>"); +}); + +test("a mind whose first read fails keeps the app's frame, and says which mind and what failed, with a retry", async () => { + const root = createRootRoute({ component: () => <AppRoot posthogProjectKey={null} /> }); + const mind = createRoute({ + getParentRoute: () => root, + path: "minds/$mind", + loader: () => { + throw new Error("example.com is unavailable (503). Please retry."); + }, + errorComponent: ({ error }) => <MindAppLoadError app="Agents" error={error} />, + component: () => <p>the mind's page</p>, + }); + const router = createAppRouter({ + routeTree: root.addChildren([mind]), + history: createMemoryHistory({ initialEntries: ["/minds/example.com"] }), + origin: "https://agents.example.com", + }); + await router.load(); + const html = renderToString(<RouterProvider router={router} />); + expect(html).not.toContain("the mind's page"); + expect(html).toContain("Agents could not load example.com"); + expect(html).toContain("example.com is unavailable (503). Please retry."); + expect(html).toContain("Try again"); + // the frame: the switcher still names the app and the mind + expect(html).toContain('data-slot="sidebar"'); +});
A src/apps/document.tsx
@@ -0,0 +1,52 @@ +import type { ReactNode } from "react"; +import { Outlet, Scripts, useHydrated } from "@tanstack/react-router"; +import { AppProviders } from "./providers.tsx"; +import { EnvironmentHeadContent } from "#/components/environment-head-content.tsx"; + +/** Every app's root `shellComponent`: the document around whatever the root route shows, its + * pages, its error or its not-found page. It reads no loader data, so a root loader that fails + * still gets a document with the app's styles and scripts. `icon` is the app's icon file in + * production. `basePath` is the path the page is served under when a mind proxies it + * (packages/ui/src/apps/base-path.ts): the icon goes under it, and the browser's router reads it + * from `<html data-base-path>` before it starts. */ +export function AppDocumentShell(props: { icon: string; basePath?: string; children: ReactNode }) { + // false in the server's HTML, true once React owns the page: the specs' hydration-waiter + // (test/playwright/AGENTS.md) holds actions until then + const hydrated = useHydrated(); + const basePath = props.basePath || ""; + return ( + <html lang="en" data-base-path={basePath || undefined}> + <head> + <EnvironmentHeadContent productionIcon={`${basePath}${props.icon}`} /> + </head> + <body className="min-h-svh bg-background font-sans antialiased" data-hydrated={hydrated}> + {props.children} + <Scripts /> + </body> + </html> + ); +} + +/** Every app's root route `component`, inside `AppDocumentShell`: the app's providers around its + * pages. */ +export function AppRoot(props: { posthogProjectKey: string | null }) { + return ( + <AppProviders posthogApiKey={props.posthogProjectKey || undefined}> + <Outlet /> + </AppProviders> + ); +} + +/** The document and the providers in one root `component`: for an app outside this repo that + * names no `shellComponent` yet. Its root loader's failure renders no document. */ +export function AppDocument(props: { + icon: string; + posthogProjectKey: string | null; + basePath?: string; +}) { + return ( + <AppDocumentShell icon={props.icon} basePath={props.basePath}> + <AppRoot posthogProjectKey={props.posthogProjectKey} /> + </AppDocumentShell> + ); +}
A src/apps/head.ts
@@ -0,0 +1,17 @@ +/** Every app's root route `head`: its title, its stylesheet (a `?url` import) and, when it has + * one, its description. */ +export function appHead(page: { title: string; stylesheet: string; description?: string }) { + return { + meta: [ + { charSet: "utf-8" }, + // resizes-content: a phone's keyboard shrinks the page, so what is at its bottom stays in view + { + name: "viewport", + content: "width=device-width, initial-scale=1, interactive-widget=resizes-content", + }, + ...(page.description ? [{ name: "description", content: page.description }] : []), + { title: page.title }, + ], + links: [{ rel: "stylesheet", href: page.stylesheet }], + }; +}
A src/apps/providers.tsx
@@ -0,0 +1,27 @@ +import type { ReactNode } from "react"; +import { initPosthog } from "#/components/posthog.tsx"; +import { Toaster } from "#/components/ui/sonner.tsx"; +import { TooltipProvider } from "#/components/ui/tooltip.tsx"; + +/** Every client app's root providers. PostHog starts when the app has a key (envs.ts hands one to + * prd only). */ +export function AppProviders(props: { children: ReactNode; posthogApiKey?: string }) { + initPosthog(props.posthogApiKey); + + return ( + // Base UI tooltips are intended to share a provider; setting delay=0 + // here makes hover tooltips feel immediate across the app. + // First-party docs: + // https://github.com/mui/base-ui/blob/master/docs/src/app/(docs)/react/components/tooltip/page.mdx + // Base UI tooltips are intended to share a provider; setting delay=0 + // here makes hover tooltips feel immediate across the app. + // First-party docs: + // https://github.com/mui/base-ui/blob/master/docs/src/app/(docs)/react/components/tooltip/page.mdx + <TooltipProvider delay={0}> + {props.children} + {/* Light, as the app is whatever the system says. The vendored Toaster would ask + next-themes, which with no provider answers "system". */} + <Toaster theme="light" /> + </TooltipProvider> + ); +}
A src/apps/router.tsx
@@ -0,0 +1,37 @@ +import { + createRouter, + type AnyRoute, + type RouterConstructorOptions, + type RouterHistory, +} from "@tanstack/react-router"; +import { + DefaultErrorComponent, + DefaultNotFoundComponent, + DefaultPendingComponent, +} from "#/components/route-defaults.tsx"; + +/** Every app's router (its src/router.tsx `getRouter`): TanStack's `createRouter` with the defaults + * every app shares; an app's own options win. */ +export function createAppRouter<TRouteTree extends AnyRoute>( + options: RouterConstructorOptions<TRouteTree, "never", false, RouterHistory, Record<string, any>>, +) { + return createRouter<TRouteTree>({ + defaultPreload: "intent", + scrollRestoration: true, + // Components passed as options are wrapped in lambdas so checking them doesn't traverse the + // registered router types (TS7023). + defaultErrorComponent: (props) => <DefaultErrorComponent {...props} />, + defaultNotFoundComponent: () => <DefaultNotFoundComponent />, + // Without a default pending component, an `ssr: false` route — the whole signed-in `_auth` + // layout — renders a BLANK outlet in the SSR shell and again while `beforeLoad`/`loader` run on + // the client. Blank is bad UX and breaks the "the app always reports progress" contract the + // specs enforce (their spinner-waiter only extends waits while a spinner is visible). + defaultPendingComponent: () => <DefaultPendingComponent />, + // Show that feedback quickly on client-side loads too: the library defaults (1000ms before + // pending shows, 500ms minimum once shown) leave a full second of blank panel before any + // signal appears. + defaultPendingMs: 300, + defaultPendingMinMs: 200, + ...options, + }); +}
A src/apps/server.test.ts
@@ -0,0 +1,120 @@ +// Which part of an app's Worker answers a request (appServerEntry): its health check, the PostHog +// proxy, the app's own routes, the sign-in gate, the assets and the pages. +// The gate's own behaviour is iterate/app-server's (app-server.test.ts). +import { env } from "cloudflare:workers"; +import { expect, test, vi } from "vitest"; +import { appServerEntry } from "./server.ts"; + +// `owns`: the one path the app's own routes answer ("own"), or "*" for every path. +test.for([ + { + name: "/healthz answers ok before the app's own routes", + path: "/healthz", + owns: "*", + expected: "ok", + }, + { + name: "PostHog's files come from PostHog through /e/, before the app's own routes", + path: "/e/static/array.js", + owns: "*", + expected: "fetched https://eu-assets.i.posthog.com/static/array.js", + }, + { + name: "the app's own routes answer before the gate", + path: "/.auth/login", + owns: "/.auth/login", + expected: "own", + }, + { + name: "a static file is the built asset", + path: "/client-logo.svg", + owns: "/.auth/login", + expected: "asset", + }, + { + name: "every other path is a page", + path: "/minds/p1", + owns: "/.auth/login", + expected: "page /minds/p1", + }, + { + name: "a signed-out landing is the landing page", + path: "/", + owns: "/.auth/login", + expected: "page /", + }, +])("$name", async ({ path, owns, expected }) => { + vi.stubGlobal("fetch", async (url: string) => new Response(`fetched ${url}`)); + const response = await testEntry({ + before: async (request) => + owns === "*" || new URL(request.url).pathname === owns ? new Response("own") : null, + }).fetch(new Request(`https://app.example${path}`)); + expect({ status: response.status, body: await response.text() }).toMatchObject({ + status: 200, + body: expected, + }); +}); + +test.for([ + { + name: "the client document names the app, with its logo", + clientName: "iterate Notes", + expected: { client_name: "iterate Notes", logo_uri: "https://app.example/client-logo.svg" }, + }, + { + name: "an app with no client name is named by its host", + clientName: undefined, + expected: { client_name: "app.example" }, + }, +])("$name", async ({ clientName, expected }) => { + const response = await testEntry({ clientName }).fetch( + new Request("https://app.example/.auth/client.json"), + ); + expect(await response.json()).toMatchObject(expected); +}); + +test("a proxied app has no sign-in gate: /.auth/*, and a signed-in landing, are its pages", async () => { + const entry = testEntry({ proxied: true }); + const answer = async (path: string) => { + const response = await entry.fetch( + new Request(`https://app.example${path}`, { + headers: { cookie: `__Host-itx-session=${SIGNED_IN}` }, + }), + ); + return { status: response.status, body: await response.text() }; + }; + expect({ + client: await answer("/.auth/client.json"), + login: await answer("/.auth/login"), + landing: await answer("/"), + }).toEqual({ + client: { status: 200, body: "page /.auth/client.json" }, + login: { status: 200, body: "page /.auth/login" }, + landing: { status: 200, body: "page /" }, + }); +}); + +const SIGNED_IN = "00000000-0000-4000-8000-000000000001"; + +/** The entry over the shim's `env` (vitest.config.ts): the platform at os.example, one built file, + * and one browser session, signed in, whose cookie is `SIGNED_IN`. */ +function testEntry(app: Parameters<typeof appServerEntry>[1]) { + Object.assign(env, { + ITERATE_APP: JSON.stringify({ urls: { os: "https://os.example" } }), + ASSETS: { + fetch: async (request: Request) => + new URL(request.url).pathname === "/client-logo.svg" + ? new Response("asset") + : new Response(null, { status: 404 }), + }, + BROWSER_SESSION: { + getByName: (name: string) => ({ + bearer: async () => (name.endsWith(`:${SIGNED_IN}`) ? "bearer" : null), + }), + }, + }); + return appServerEntry( + { fetch: async (request) => new Response(`page ${new URL(request.url).pathname}`) }, + app, + ); +}
A src/apps/server.ts
@@ -0,0 +1,72 @@ +// server.ts — EVERY APP'S WORKER (dash, agents, notes, voice, admin): its src/server.ts, Start's +// server entry, is `appServerEntry(handler, { … })` with only what the app does differently. +import { env } from "cloudflare:workers"; +import { proxyPosthogRequest } from "@iterate-com/shared/posthog"; +import { startAppConfigOf, type StartAppConfig } from "@iterate-com/shared/start-app-config"; +import { appAuth } from "iterate/app-server"; +import type { BrowserSession } from "iterate/app-session"; + +declare global { + namespace Cloudflare { + /** The bindings every app's Worker config gives it (startAppWorkerConfig, scripts/lib/start-app.ts). */ + interface Env { + ASSETS: Fetcher; + BROWSER_SESSION: DurableObjectNamespace<BrowserSession>; + /** THE APP'S CONFIGURATION, JSON (@iterate-com/shared/start-app-config): its platform, the + * other apps' origins, our own zones and its PostHog key — from envs.ts (startAppWorkerConfig) */ + ITERATE_APP: string; + } + } +} + +type AppServer = { + /** The app's own routes ahead of the sign-in gate; null passes the request on. */ + before?: (request: Request, config: StartAppConfig) => Promise<Response | null>; +} & ( + | { + proxied?: false; + /** The name an issuer's consent page shows (`/.auth/client.json`, beside + * `/client-logo.svg`). Without one the gate names the app by its host. */ + clientName?: string; + } + | { + /** Served only under a mind's hosts, which a config worker fetches it through to (Notes): + * the platform answers those hosts' `/.auth/*` and `/api` itself (core/mind-worker/src/http.ts), so + * the app has no sign-in gate and no OAuth client of its own. */ + proxied: true; + } +); + +/** The app's own origin signs a person in to each mind they connect it to (`appAuth`) and + * proxies the authenticated `/api?mind=<address>`. A `proxied` app skips that gate. + * Everything else is TanStack Start's: the built assets, then `pages`. */ +export function appServerEntry( + pages: { fetch(request: Request): Promise<Response> | Response }, + app: AppServer, +) { + return { + async fetch(request: Request) { + // parsed on the first request, /healthz's included: a malformed config fails the deploy's smoke + const config = startAppConfigOf(env); + const url = new URL(request.url); + if (url.pathname === "/healthz") return new Response("ok"); + // posthog-js's `api_host` (packages/ui posthog.tsx): PostHog EU through our own origin + if (url.pathname.startsWith("/e/")) + return proxyPosthogRequest({ request, proxyPrefix: "/e" }); + const own = await app.before?.(request, config); + if (own) return own; + if (!app.proxied) { + const auth = await appAuth(request, { + client: app.clientName + ? { name: app.clientName, logoUri: "/client-logo.svg" } + : undefined, + sessions: env.BROWSER_SESSION, + }); + if (auth) return auth; + } + const asset = await env.ASSETS.fetch(request); + if (asset.status !== 404) return asset; + return pages.fetch(request); + }, + }; +}
A src/asset-modules.d.ts
@@ -0,0 +1,15 @@ +declare module "*.svg" { + const src: string; + export default src; +} + +interface ImportMetaEnv { + readonly SSR: boolean; + readonly DEV: boolean; + /** Vite's `base`: apps/base-path.ts reads a dev server's under a tunnel. */ + readonly BASE_URL: string; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +}
A src/browser/agent-kind-view-frame.ts
@@ -0,0 +1,5 @@ +// The whole script of the frame a kind's chat view runs in (../agent-kind-view/frame.ts says what +// the frame is). scripts/build-agent-kind-view-frame.ts bundles this file as one classic script. +import { startAgentKindViewFrame } from "../agent-kind-view/frame.ts"; + +startAgentKindViewFrame(document.getElementById("root")!);
A src/browser/change-my-mind.test.ts
@@ -0,0 +1,34 @@ +// @vitest-environment jsdom +// <change-my-mind> copies what the React button copies. +import "./change-my-mind.ts"; +import { expect, test, vi } from "vitest"; +import { changeMyMindInstructions } from "#/lib/change-my-mind.ts"; + +test("the element copies the built instructions, or its own text, and says so", async () => { + const writeText = vi.fn(() => Promise.resolve()); + vi.stubGlobal("navigator", { clipboard: { writeText } }); + const element = document.createElement("change-my-mind"); + element.setAttribute("source", "https://blog.example.com/"); + element.setAttribute("scope", "blog"); + element.setAttribute("variant", "outline"); + document.body.append(element); + const copies: unknown[] = []; + element.addEventListener("change-my-mind-copy", (event) => + copies.push((event as CustomEvent).detail), + ); + + element.shadowRoot!.querySelector("button")!.click(); + await vi.waitFor(() => expect(copies).toHaveLength(1)); + const text = changeMyMindInstructions({ source: "https://blog.example.com/", scope: "blog" }); + expect(writeText).toHaveBeenCalledWith(text); + expect(copies[0]).toEqual({ copied: true, text }); + expect(element.shadowRoot!.querySelector("[role=status]")?.textContent).toBe( + "Copied to clipboard. Paste it to your iterate mind.", + ); + + element.textContent = "Make me a cup of tea."; + element.shadowRoot!.querySelector("button")!.click(); + await vi.waitFor(() => expect(copies).toHaveLength(2)); + expect(writeText).toHaveBeenLastCalledWith("Make me a cup of tea."); + element.remove(); +});
A src/browser/change-my-mind.ts
@@ -0,0 +1,229 @@ +// change-my-mind.ts — `<change-my-mind>`, the "Change my mind" button for a page with no React (a +// plain HTML blog): one script tag defines it, and it brings no React and no stylesheet. +// +// <script type="module" src="https://esm.iterate.com/@iterate-com/ui@<version>/change-my-mind"></script> +// <change-my-mind source="https://blog.example.com/a-post"></change-my-mind> +// +// Attributes: `source` (the post; by default this page without query or hash), `scope="blog"` (the +// whole blog: its feed and README), `instructions` (the exact text; the element's own text does the +// same), `size="sm"` (for a list), `variant="outline"` (the kit's outline Button, quieter), `align="end"` (the tooltip and the card line up with the right +// edge). It dispatches `change-my-mind-copy` ({ copied, text }) after each press. +// +// It looks like the kit's ChangeMyMindButton (components/change-my-mind-button.tsx) and says the +// same words (lib/change-my-mind.ts). Its shadow DOM reads the kit's tokens (`--primary`, `--radius`, +// …) when the page has them, so a page with the kit's stylesheet and its `dark` class gets its look; +// on any other page it takes shadcn's neutral values: dark on a page whose color-scheme is dark, +// light on any other, as the kit's look is light unless the page says otherwise. It takes the +// page's font. +import { + changeMyMindInstructions, + changeMyMindText, + changeMyMindTimes, + copyToClipboard, + currentPageSource, + iterateMark, + type ChangeMyMindScope, +} from "#/lib/change-my-mind.ts"; + +const markSvg = `<svg viewBox="${iterateMark.viewBox}" aria-hidden="true" focusable="false" fill="currentColor">${iterateMark.paths.map((path) => `<path d="${path}"/>`).join("")}</svg>`; +// lucide's "check" (https://lucide.dev, ISC license), the icon the React button shows +const checkSvg = `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>`; +const fonts = 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif'; +const hoverDelay = 300; + +// The kit's Button (its large size; `size="sm"` is its default size), Tooltip and Popover, in plain +// CSS: each value is the kit's token, with shadcn's neutral value (globals.css) for a page that has none. +const css = ` +:host{display:inline-block;vertical-align:middle;font-family:inherit;letter-spacing:normal;text-align:left;line-height:normal} +.wrap{position:relative;display:inline-block; + --p:var(--primary,light-dark(oklch(.205 0 0),oklch(.922 0 0)));--pf:var(--primary-foreground,light-dark(oklch(.985 0 0),oklch(.205 0 0))); + --fg:var(--foreground,light-dark(oklch(.145 0 0),oklch(.985 0 0)));--bg:var(--background,light-dark(oklch(1 0 0),oklch(.145 0 0))); + --pop:var(--popover,light-dark(oklch(1 0 0),oklch(.205 0 0)));--popf:var(--popover-foreground,light-dark(oklch(.145 0 0),oklch(.985 0 0))); + --muted:var(--muted-foreground,light-dark(oklch(.556 0 0),oklch(.708 0 0)));--line:var(--border,light-dark(oklch(.922 0 0),oklch(1 0 0/10%))); + --ring-c:var(--ring,light-dark(oklch(.708 0 0),oklch(.556 0 0))); + --in:var(--input,light-dark(oklch(.922 0 0),oklch(1 0 0/15%)));--mbg:var(--muted,light-dark(oklch(.97 0 0),oklch(.269 0 0)));--o-line:light-dark(var(--line),var(--in));--r:var(--radius,.625rem)} +*{box-sizing:border-box} +button{all:unset;box-sizing:border-box;display:inline-flex;align-items:stretch;height:2.25rem;border:1px solid transparent;background-clip:padding-box;border-radius:var(--r);overflow:hidden; + background:var(--p);color:var(--pf);font-family:inherit;font-size:.875rem;font-weight:500;line-height:1.25rem;white-space:nowrap;cursor:pointer;user-select:none;-webkit-tap-highlight-color:transparent; + transition:all .15s cubic-bezier(.4,0,.2,1)} +button:hover{background:color-mix(in oklab,var(--p) 80%,transparent)} +button:active{translate:0 1px} +button:focus-visible{border-color:var(--ring-c);box-shadow:0 0 0 3px color-mix(in oklab,var(--ring-c) 50%,transparent)} +.mark{display:flex;align-items:center;justify-content:center;width:2.25rem;flex:none;border-right:1px solid color-mix(in oklab,var(--pf) 20%,transparent)} +.mark svg{width:1.125rem;height:1.125rem;display:block} +.label{display:grid;padding:0 .75rem} +.label>span{grid-area:1/1;display:inline-flex;align-items:center;justify-content:center;gap:.375rem} +.label svg{width:1rem;height:1rem;flex:none} +.copied .label .idle,.label .done{visibility:hidden} +.copied .label .done{visibility:visible} +:host([variant=outline]) button{background:light-dark(var(--bg),color-mix(in oklab,var(--in) 30%,transparent));border-color:var(--o-line);color:var(--fg)} +:host([variant=outline]) button:hover,:host([variant=outline]) .open button{background:light-dark(var(--mbg),color-mix(in oklab,var(--in) 50%,transparent));color:var(--fg)} +:host([variant=outline]) button:focus-visible{border-color:var(--ring-c)} +:host([variant=outline]) .mark{border-right-color:var(--o-line);color:var(--fg)} +:host([size=sm]) button{height:2rem} +:host([size=sm]) .mark{width:2rem} +:host([size=sm]) .mark svg{width:1rem;height:1rem} +:host([size=sm]) .label{padding:0 .625rem} +.pop{position:absolute;left:0;z-index:9999;width:max-content;opacity:0;visibility:hidden;pointer-events:none; + transition:opacity .1s,visibility .1s,scale .1s;scale:.95;font-family:inherit;text-align:left} +:host([align=end]) .pop{left:auto;right:0} +.tip{bottom:calc(100% + 6px);transform-origin:bottom left;max-width:min(16rem,calc(100vw - 2rem));padding:.375rem .75rem;border-radius:calc(var(--r) - 2px);background:var(--fg);color:var(--bg);font-size:.75rem;line-height:1rem;font-weight:400} +.wrap.hover:not(.quiet):not(.open) .tip,.wrap:not(.quiet):not(.open) button:focus-visible~.tip{opacity:1;visibility:visible;scale:1} +.note{top:calc(100% + 6px);transform-origin:top left;display:flex;flex-direction:column;gap:.375rem;max-width:min(18rem,calc(100vw - 2rem));padding:.625rem;border-radius:var(--r); + background:var(--pop);color:var(--popf);box-shadow:0 0 0 1px color-mix(in oklab,var(--fg) 10%,transparent),0 4px 6px -1px rgb(0 0 0/.1),0 2px 4px -2px rgb(0 0 0/.1); + font-size:.875rem;line-height:1.25rem;font-weight:400} +.open .note{opacity:1;visibility:visible;pointer-events:auto;scale:1} +.note p{margin:0} +.note a{width:fit-content;color:var(--muted);text-decoration:underline;text-underline-offset:3px} +.note a:hover{color:var(--popf)} +.note a:focus-visible{outline:2px solid var(--ring-c);outline-offset:2px;border-radius:2px} +.note.wide{max-width:min(24rem,calc(100vw - 2rem))} +.note textarea{display:block;width:min(22.75rem,calc(100vw - 3.25rem));height:9rem;padding:.5rem .625rem;border:1px solid var(--line);border-radius:var(--r); + font:.75rem/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--popf);background:transparent;resize:vertical} +.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap} +@media (prefers-reduced-motion:reduce){button,.pop{transition:none}} +`; + +let count = 0; + +// Outside a browser (a test, a server render) the module still loads. +// the cast: the empty class stands in for HTMLElement only where no element is ever made +const Base = globalThis.HTMLElement || (class {} as typeof HTMLElement); + +export class ChangeMyMindElement extends Base { + #wrap?: HTMLElement; + #note?: HTMLElement; + #status?: HTMLElement; + #hover?: ReturnType<typeof setTimeout>; + #labelTimer?: ReturnType<typeof setTimeout>; + #noteTimer?: ReturnType<typeof setTimeout>; + #away = (event: PointerEvent) => { + if (!event.composedPath().includes(this)) this.#close(); + }; + + connectedCallback() { + if (this.shadowRoot) return; + const id = `change-my-mind-${++count}`; + const root = this.attachShadow({ mode: "open" }); + root.innerHTML = `<style>${css}</style><span class="wrap"><button type="button" part="button" aria-describedby="${id}"><span class="mark">${markSvg}</span><span class="label"><span class="idle">${changeMyMindText.label}</span><span class="done">${checkSvg}${changeMyMindText.copied}</span></span></button><div class="pop tip" id="${id}" role="tooltip" part="tooltip">${changeMyMindText.tooltip}</div><div class="pop note" part="note"></div><span class="sr" role="status" aria-live="polite"></span></span>`; + const wrap = root.querySelector<HTMLElement>(".wrap")!; + const button = root.querySelector("button")!; + this.#wrap = wrap; + this.#note = root.querySelector<HTMLElement>(".note")!; + this.#status = root.querySelector<HTMLElement>(".sr")!; + const style = getComputedStyle(this); + // the page's font, unless the page set none (the browser's default serif) + if (/^"?(Times|serif)/i.test(style.fontFamily)) wrap.style.fontFamily = fonts; + button.addEventListener("click", () => void this.copy()); + // the tooltip: after a short delay for a mouse, at once on keyboard focus (CSS), never on touch + button.addEventListener("pointerenter", (event) => { + if (event.pointerType !== "mouse") return; + clearTimeout(this.#hover); + this.#hover = setTimeout(() => wrap.classList.add("hover"), hoverDelay); + }); + button.addEventListener("pointerleave", () => { + clearTimeout(this.#hover); + wrap.classList.remove("hover", "quiet"); + }); + button.addEventListener("blur", () => wrap.classList.remove("quiet")); + this.addEventListener("keydown", (event) => { + if (event.key !== "Escape") return; + wrap.classList.add("quiet"); + this.#close(); + }); + // the card stays while the pointer or the focus is in it, so that its link can be reached + this.#note.addEventListener("pointerenter", () => clearTimeout(this.#noteTimer)); + this.#note.addEventListener("focusin", () => clearTimeout(this.#noteTimer)); + this.#note.addEventListener("pointerleave", () => this.#closeLater()); + this.#note.addEventListener("focusout", () => this.#closeLater()); + } + + disconnectedCallback() { + document.removeEventListener("pointerdown", this.#away); + clearTimeout(this.#hover); + clearTimeout(this.#labelTimer); + clearTimeout(this.#noteTimer); + } + + /** The text a press copies: the `instructions` attribute, the element's text, or the built one. */ + get instructions(): string { + const given = (this.getAttribute("instructions") || this.textContent || "").trim(); + const scope: ChangeMyMindScope = this.getAttribute("scope") === "blog" ? "blog" : "post"; + return ( + given || + changeMyMindInstructions({ + source: this.getAttribute("source") || currentPageSource(), + scope, + }) + ); + } + + async copy(): Promise<boolean> { + const text = this.instructions; + const copied = await copyToClipboard(text); + this.#open(copied, text); + this.dispatchEvent( + new CustomEvent("change-my-mind-copy", { + bubbles: true, + composed: true, + detail: { copied, text }, + }), + ); + return copied; + } + + #open(copied: boolean, text: string) { + const wrap = this.#wrap!; + const note = this.#note!; + clearTimeout(this.#hover); + clearTimeout(this.#labelTimer); + wrap.classList.remove("hover"); + wrap.classList.toggle("copied", copied); + if (copied) + this.#labelTimer = setTimeout(() => wrap.classList.remove("copied"), changeMyMindTimes.label); + const words = copied ? changeMyMindText.copiedNote : changeMyMindText.uncopiedNote; + const paragraph = document.createElement("p"); + paragraph.textContent = words; + note.replaceChildren(paragraph); + note.classList.toggle("wide", !copied); + if (!copied) { + const box = document.createElement("textarea"); + box.readOnly = true; + box.value = text; + box.setAttribute("aria-label", changeMyMindText.textBoxLabel); + note.append(box); + requestAnimationFrame(() => { + box.focus(); + box.select(); + }); + } + const link = document.createElement("a"); + link.href = changeMyMindText.getOneHref; + link.target = "_blank"; + link.rel = "noopener"; + link.textContent = changeMyMindText.getOne; + note.append(link); + this.#status!.textContent = words; + wrap.classList.add("open"); + document.removeEventListener("pointerdown", this.#away); + setTimeout(() => document.addEventListener("pointerdown", this.#away)); + // a failed copy keeps its text box until Escape or a click elsewhere + if (copied) this.#closeLater(); + } + + #closeLater() { + clearTimeout(this.#noteTimer); + if (this.#note?.classList.contains("wide")) return; + this.#noteTimer = setTimeout(() => this.#close(), changeMyMindTimes.note); + } + + #close() { + clearTimeout(this.#noteTimer); + document.removeEventListener("pointerdown", this.#away); + this.#wrap?.classList.remove("open"); + if (this.#status) this.#status.textContent = ""; + } +} + +if (globalThis.customElements && !customElements.get("change-my-mind")) + customElements.define("change-my-mind", ChangeMyMindElement);
A src/browser/chunks.test.ts
@@ -0,0 +1,58 @@ +// The build's named chunks (browser-entries.ts `vendorChunks`): which file goes into which, and +// that each is an export, which is what keeps it one file on a module server. +import { expect, test } from "vitest"; +import { browserEntries, publishExports, vendorChunks } from "../../browser-entries.ts"; + +test("each named chunk has a name of its own and is an export of the published package", () => { + const names = vendorChunks.map(({ name }) => name); + expect([...new Set(names)]).toEqual(names); + expect(publishExports({}, [])).toMatchObject( + Object.fromEntries(names.map((name) => [`./chunks/${name}`, `./dist/chunks/${name}.mjs`])), + ); +}); + +test.for([ + { file: "node_modules/lucide-react/dist/esm/icons/bot.js", chunk: "vendor-icons" }, + { + file: "node_modules/.pnpm/lucide-react@1.48.0/node_modules/lucide-react/dist/esm/createLucideIcon.js", + chunk: "vendor-icons", + }, + { + file: "node_modules/.pnpm/@tanstack+react-query@5.107.1_react@19.3.0/node_modules/@tanstack/react-query/build/modern/useQuery.js", + chunk: "vendor-query", + }, + { + file: "node_modules/.pnpm/@tanstack+query-core@5.107.1/node_modules/@tanstack/query-core/build/modern/queryClient.js", + chunk: "vendor-query", + }, + // another library of the same house is not react-query + { file: "node_modules/@tanstack/react-virtual/dist/esm/index.js", chunk: undefined }, + { file: "packages/ui/src/components/ui/button.tsx", chunk: "ui-base" }, + { file: "packages/ui/src/components/ui/textarea.tsx", chunk: "ui-base" }, + { file: "packages/ui/src/components/ui/dialog.tsx", chunk: "ui-shell" }, + { file: "packages/ui/src/components/ui/dropdown-menu.tsx", chunk: "ui-shell" }, + // a component that brings a library of its own, or that only some pages use, keeps its own file + { file: "packages/ui/src/components/ui/command.tsx", chunk: undefined }, + { file: "packages/ui/src/components/ui/sidebar.tsx", chunk: undefined }, + { file: "packages/ui/src/components/ui/sonner.tsx", chunk: undefined }, + { file: "packages/ui/src/components/ui/card.tsx", chunk: undefined }, + { file: "packages/ui/src/components/ui/input-group.tsx", chunk: "ui-shell" }, + // a component of the kit that is no shadcn file, and a file that only looks like one + { file: "packages/ui/src/components/app-shell.tsx", chunk: undefined }, + { file: "packages/ui/src/components/ui/button.test.tsx", chunk: undefined }, + { file: "packages/ui/src/components/context-view/dialog.tsx", chunk: undefined }, +])("$file goes into the chunk $chunk", ({ file, chunk }) => { + // as the build does it: the first group whose test matches + expect(vendorChunks.find(({ test }) => test.test(file))?.name).toBe(chunk); +}); + +test("the icons and react-query that a page takes from the kit are entries of their own", () => { + expect(browserEntries()).toMatchObject({ + icons: "src/browser/icons.ts", + query: "src/browser/query.ts", + }); + expect(publishExports(browserEntries(), [])).toMatchObject({ + "./icons": "./dist/icons.mjs", + "./query": "./dist/query.mjs", + }); +});
A src/browser/docs-editor-look.css
@@ -0,0 +1,6 @@ +/* What a look for the docs editor's page would be cut from: docs-editor.css with iterate's look + over it, as iterate.css is styles.css with the look over it. No stylesheet is built from this. + The build compiles it to check that dist/iterate.css, which is cut from styles.css, is also the + look of the classes that only the docs editor uses (scripts/build-iterate-css.ts). */ +@import "./docs-editor.css"; +@import "../styles/iterate.css";
A src/browser/docs-editor.css
@@ -0,0 +1,9 @@ +/* The docs editor's page's stylesheet (dist/docs-editor.css), which that page links IN PLACE OF + styles.css, never beside it: stylesheet.css with the docs editor's classes too (styles.css leaves + them out), and Atomic's live preview, which Rich mode draws with classes + (src/components/docs-editor/extensions.ts). One Tailwind build orders every utility against every + variant; two sheets in one `utilities` layer would not (a second sheet's `.hidden` comes after + the first's `md:block`, and wins). scripts/check-docs-editor-css.ts checks after the build that + this sheet holds all of styles.css, in its order. */ +@import "./stylesheet.css"; +@import "@atomic-editor/editor/styles.css";
A src/browser/icons.ts
@@ -0,0 +1,61 @@ +// THE ICONS A NO-BUILD PAGE TAKES FROM THIS PACKAGE: the ones iterate's own apps use, and the +// common ones that this package's components use already. They are Lucide's (https://lucide.dev), +// by the names lucide-react gives them. +// +// import { BotIcon, PlusIcon } from "@iterate-com/ui/icons"; +// +// A page does not import `lucide-react` itself: on a module server that is one module of every +// icon Lucide has (826 kB), for the few a page shows. The build keeps every icon that this +// package's components and this list use in one small file (browser-entries.ts `vendor-icons`), +// which every page loads: so an icon added here is paid for by all of them, about half a +// kilobyte each. +export { + ArrowDownIcon, + ArrowUpIcon, + BlocksIcon, + BookOpenIcon, + BotIcon, + BoxIcon, + ChartLineIcon, + CheckIcon, + ChevronDownIcon, + ChevronsUpDownIcon, + ChevronLeftIcon, + ChevronRightIcon, + ChevronUpIcon, + CircleAlertIcon, + CircleCheckIcon, + CompassIcon, + CopyIcon, + EllipsisIcon, + ExternalLinkIcon, + FileIcon, + FileTextIcon, + FolderGit2Icon, + HistoryIcon, + InboxIcon, + InfoIcon, + KeyRoundIcon, + LayoutDashboardIcon, + LockIcon, + LockKeyholeIcon, + LogOutIcon, + MessageCircleIcon, + PencilIcon, + PhoneIcon, + PinIcon, + PlugIcon, + PlusIcon, + SearchIcon, + SettingsIcon, + ShieldCheckIcon, + SparklesIcon, + SquarePenIcon, + SquareTerminalIcon, + Trash2Icon, + TriangleAlertIcon, + UserIcon, + UsersIcon, + WaypointsIcon, + XIcon, +} from "lucide-react";
A src/browser/iterate.css
@@ -0,0 +1,5 @@ +/* What dist/iterate.css is cut from: the published stylesheet with iterate's look over it. The build + (scripts/build-iterate-css.ts) compiles this and styles.css alike and keeps only the rules that + differ, so a page that links dist/iterate.css after dist/styles.css gets the apps' look. */ +@import "./styles.css"; +@import "../styles/iterate.css";
A src/browser/live.ts
@@ -0,0 +1,33 @@ +// Live data for a no-build page, from the SDK built into this package so its hooks use this +// package's React. On a mind's own host, sign in and connect to the host's /api +// (`createIterateClient`). Anywhere else the page signs in for itself and opens /api with its token +// (`newWebSocketRpcSession`: capnweb's own, the copy the hooks use; examples/any-website.html). +// A page of a mind's own app takes the member's itx from its host's /itx (`memberItx`), which +// dials a new session when its socket closes: such a page holds a context with `useHeldContext`, +// wraps what `useIterateContext` returns in `useKeptContext`, and draws `ReconnectingMark` +// (src/hooks/use-itx-session.ts, src/components/reconnecting-mark.tsx). Its views draw a reload at +// once with `useSavedContext` over the member's `savedLogTails` (#/lib/saved-context.ts), +// and `wipeSavedLogTails` forgets them all when the sign-in ends. +// Then hold a context (`useContextStub`) and read it live for ContextView (`useIterateContext`), or +// one facet's live state alone (`useFacetLiveState`, `facetSnapshotOf`), or, with no React, +// subscribe to its log with `connectEventLog`. +// packages/ui/examples/README.md "Signing in" says which. +export { newWebSocketRpcSession } from "capnweb"; +export { memberItx } from "./member-itx.ts"; +export { itxSessionOf } from "#/lib/itx-session.ts"; +export { savedLogTails, wipeSavedLogTails } from "#/lib/saved-log-tail.ts"; +export { useSavedContext } from "#/lib/saved-context.ts"; +export { + useHeldContext, + useItxConnection, + useKept, + useKeptContext, +} from "#/hooks/use-itx-session.ts"; +export { createIterateClient } from "iterate/app"; +export { connectEventLog } from "iterate/event-log"; +export { + facetSnapshotOf, + useContextStub, + useFacetLiveState, + useIterateContext, +} from "iterate/react";
A src/browser/member-itx.test.tsx
@@ -0,0 +1,1007 @@ +// @vitest-environment jsdom +// The member's itx on a mind's own host, over a socket that closes: a new session is dialled and +// the page stays. Only the end of the sign-in reloads it. A Dash's agent view keeps its rows and +// subscribes again, and a Dash mounts anew a page that cannot. The sockets are fakes; behind each +// one is a capnweb session to a small mind. +import { act, Suspense, useState } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, onTestFinished, test, vi } from "vitest"; +import { newWebSocketRpcSession, RpcTarget } from "capnweb"; +import { IDBFactory } from "fake-indexeddb"; +import { BotIcon } from "lucide-react"; +import { useContextStub, useIterateContext } from "iterate/react"; +import { connectMemberItx, mayReload } from "./member-itx.ts"; +import { DashAgents } from "#/agent-kind-view/dash-agents.tsx"; +import { DashContexts } from "#/components/dash/dash.tsx"; +import { AppShell } from "#/components/app-shell.tsx"; +import { Dash, type DashPage, type DashPageProps } from "#/components/dash/dash.tsx"; +import { ReconnectingMark } from "#/components/reconnecting-mark.tsx"; +import { agentRowsOf } from "#/lib/agent-summary.ts"; +import { itxSessionOf } from "#/lib/itx-session.ts"; +import { liveState, said, type LoggedEvent } from "#/test-support/agent-log.ts"; + +// React's flag for a test that wraps its changes in `act`: a global that no type declares. +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +test("a socket that closes with 1006 is dialled again: no reload, the same itx calls through the new session, and the epoch grows", async () => { + using _clock = clock(); + const net = network(); + const { itx, session, reload } = member(net); + expect(await itx.whoami()).toMatchObject({ principal: { actor: "/members/a" } }); + expect(session.get()).toEqual({ epoch: 1, state: "open" }); + net.drop(1006); + // asked while the new session's socket is not open yet: the call waits for it + expect(session.get()).toEqual({ epoch: 1, state: "opening" }); + expect(await itx.whoami()).toMatchObject({ principal: { actor: "/members/a" } }); + expect(session.get()).toEqual({ epoch: 2, state: "open" }); + expect(net.sockets).toHaveLength(2); + expect(reload).not.toHaveBeenCalled(); +}); + +test.for([ + { name: "is still connecting", open: false }, + { name: "has opened already", open: true }, +])( + "a socket that the page dialled before the app loaded, and that $name, is the first session's: no other is dialled, and it is replaced like any other when it closes", + async ({ open }) => { + using _clock = clock(); + const net = network(); + const early = new net.WebSocket("ws://dash.example.com/itx"); + // a dial opens a moment after it was made + if (open) await vi.advanceTimersByTimeAsync(0); + // 0 is connecting and 1 is open (a plain number: a socket in a failed `expect` is printed whole) + const state = early.readyState; + expect(state).toBe(open ? 1 : 0); + const { itx, session, reload } = member(net, null, early); + expect(await itx.whoami()).toMatchObject({ principal: { actor: "/members/a" } }); + expect(session.get()).toEqual({ epoch: 1, state: "open" }); + expect(net.sockets).toHaveLength(1); + net.drop(1006); + expect(await itx.whoami()).toMatchObject({ principal: { actor: "/members/a" } }); + expect(session.get()).toEqual({ epoch: 2, state: "open" }); + expect(net.sockets).toHaveLength(2); + expect(reload).not.toHaveBeenCalled(); + }, +); + +test("an early socket that closed before the app loaded is not taken, and one that fails after is dialled again as any first dial", async () => { + using _clock = clock(); + // closed already: the app dials at once + const gone = network(); + gone.up = false; + const closed = new gone.WebSocket("ws://dash.example.com/itx"); + await vi.advanceTimersByTimeAsync(0); + const state = closed.readyState; + expect(state).toBe(3); + gone.up = true; + const first = member(gone, null, closed); + expect(await first.itx.whoami()).toMatchObject({ principal: { actor: "/members/a" } }); + expect(gone.sockets).toHaveLength(2); + expect(first.session.get()).toEqual({ epoch: 1, state: "open" }); + // still connecting when the app takes it, and then refused: the next dial comes after 250 ms + const failing = network(); + failing.up = false; + const second = member(failing, null, new failing.WebSocket("ws://dash.example.com/itx")); + await vi.advanceTimersByTimeAsync(0); + failing.up = true; + expect(failing.sockets).toHaveLength(1); + await vi.advanceTimersByTimeAsync(250); + expect(await second.itx.whoami()).toMatchObject({ principal: { actor: "/members/a" } }); + expect(failing.sockets).toHaveLength(2); + expect(second.session.get()).toEqual({ epoch: 1, state: "open" }); + expect(second.reload).not.toHaveBeenCalled(); +}); + +test("the sign-in ended (1008): the saved rows are wiped, then the page reloads and dials nothing; the fourth time in a minute it says so", async () => { + using _clock = clock(); + const root = { textContent: "the app" }; + const browser = new IDBFactory(); + vi.stubGlobal("indexedDB", browser); + const wipe = vi.spyOn(browser, "deleteDatabase"); + for (let time = 1; time <= 4; time += 1) { + const net = network(); + const { itx, reload } = member(net, root); + await itx.whoami(); + net.drop(1008); + await vi.advanceTimersByTimeAsync(1_000); + expect(net.sockets).toHaveLength(1); + expect(reload).toHaveBeenCalledTimes(time < 4 ? 1 : 0); + // the next member of this browser sees none of the saved rows: the wipe came first + expect(wipe).toHaveBeenCalledTimes(time); + if (time < 4) + expect(wipe.mock.invocationCallOrder.at(-1)).toBeLessThan( + reload.mock.invocationCallOrder[0]!, + ); + } + expect(root).toMatchObject({ textContent: "Your sign-in ended. Reload the page to sign in." }); +}); + +test("three closes in a row: no reload, and the page says that it reconnects only after two seconds without a session", async () => { + using _clock = clock(); + const net = network(); + const { itx, session, reload } = member(net); + await itx.whoami(); + // the first: the mind is away for a while + net.up = false; + net.drop(1006); + await vi.advanceTimersByTimeAsync(1_999); + expect(session.get()).toEqual({ epoch: 1, state: "opening" }); + await vi.advanceTimersByTimeAsync(1); + expect(session.get()).toEqual({ epoch: 1, state: "reconnecting" }); + // dialled at once and after 250, 500 and 1,000 ms; the next dial, 2 s later, finds the mind + expect(net.sockets).toHaveLength(5); + net.up = true; + await vi.advanceTimersByTimeAsync(1_750); + expect(session.get()).toEqual({ epoch: 2, state: "open" }); + // the second and the third: each is over at once, and nothing is said of it + net.drop(1006); + await itx.whoami(); + net.drop(1006); + await itx.whoami(); + expect(session.get()).toEqual({ epoch: 4, state: "open" }); + await vi.advanceTimersByTimeAsync(5_000); + expect(session.get()).toEqual({ epoch: 4, state: "open" }); + expect(reload).not.toHaveBeenCalled(); +}); + +test("a mind that cannot be reached: the calls that waited are refused after the quick dials, and a slow dial goes on until one opens", async () => { + using _clock = clock(); + const net = network(); + const { itx, session, reload } = member(net); + await itx.whoami(); + net.up = false; + net.drop(1006); + const asked = itx.whoami().then( + () => "answered", + () => "refused", + ); + // seven dials: at once, then after 250, 500, 1,000, 2,000, 4,000 and 8,000 ms + await vi.advanceTimersByTimeAsync(15_749); + expect(session.get()).toEqual({ epoch: 1, state: "reconnecting" }); + await vi.advanceTimersByTimeAsync(1); + expect(net.sockets).toHaveLength(8); + expect(await asked).toBe("refused"); + expect(session.get()).toEqual({ epoch: 1, state: "unreachable" }); + // one dial every 15 s from here + await vi.advanceTimersByTimeAsync(15_000); + expect(net.sockets).toHaveLength(9); + expect(session.get()).toEqual({ epoch: 1, state: "unreachable" }); + net.up = true; + await vi.advanceTimersByTimeAsync(15_000); + expect(session.get()).toEqual({ epoch: 2, state: "open" }); + expect(await itx.whoami()).toMatchObject({ principal: { actor: "/members/a" } }); + expect(reload).not.toHaveBeenCalled(); +}); + +test("a network that comes back dials at once, not at the slow dial's time", async () => { + using _clock = clock(); + const net = network(); + const { itx, session } = member(net); + await itx.whoami(); + net.up = false; + net.drop(1006); + await vi.advanceTimersByTimeAsync(20_000); + expect(session.get()).toEqual({ epoch: 1, state: "unreachable" }); + net.up = true; + dispatchEvent(new Event("online")); + await itx.whoami(); + expect(session.get()).toEqual({ epoch: 2, state: "open" }); +}); + +test("an open session that leaves a heartbeat unanswered for 15 s is replaced", async () => { + using _clock = clock(); + const net = network(); + const { itx, session, reload } = member(net); + await itx.whoami(); + // the network is gone with no close: nothing arrives, and the socket stays open + net.silent = true; + await vi.advanceTimersByTimeAsync(30_000 + 14_999); + expect(net.sockets).toHaveLength(1); + expect(session.get()).toEqual({ epoch: 1, state: "open" }); + net.silent = false; + await vi.advanceTimersByTimeAsync(1); + expect(net.sockets).toHaveLength(2); + await itx.whoami(); + expect(session.get()).toEqual({ epoch: 2, state: "open" }); + expect(reload).not.toHaveBeenCalled(); +}); + +test("a page that does not read its session says that the mind cannot be reached, and is reloaded when the next session opens", async () => { + using _clock = clock(); + const net = network(); + net.up = false; + const root = { textContent: "Connecting…" }; + const reload = vi.fn(); + const itx = connectMemberItx({ root, url: new URL("ws://dash.example.com/itx"), reload, ...net }); + // the app waits for its first answer before it draws + const asked = itx.whoami().then( + () => "answered", + () => "refused", + ); + await vi.advanceTimersByTimeAsync(15_750); + expect(await asked).toBe("refused"); + expect(root).toMatchObject({ textContent: "Cannot reach the mind. Trying again…" }); + expect(reload).not.toHaveBeenCalled(); + net.up = true; + await vi.advanceTimersByTimeAsync(15_000); + expect(reload).toHaveBeenCalledTimes(1); +}); + +test("a page that only draws the mark holds its stubs for one session: it is reloaded when the next one opens", async () => { + using _clock = clock(); + const net = network(); + const reload = vi.fn(); + const itx = connectMemberItx({ + root: null, + url: new URL("ws://dash.example.com/itx"), + reload, + ...net, + }); + itxSessionOf(itx).watch(() => {}); + await itx.whoami(); + net.drop(1006); + await itx.whoami(); + expect(reload).toHaveBeenCalledTimes(1); +}); + +test("a sign-in that ended while no session was open: an outage alone reloads nothing, and when the host answers 401 over HTTP the page reloads and dials no more", async () => { + using _clock = clock(); + const net = network(); + const { itx, reload } = member(net); + await itx.whoami(); + // an outage: no dial opens, and nothing answers over HTTP + net.up = false; + net.drop(1006); + await vi.advanceTimersByTimeAsync(15_750 + 15_000); + expect(net.asked()).toBe(2); + expect(reload).not.toHaveBeenCalled(); + // the network is back, and the sign-in ended meanwhile: the upgrade is refused, which the + // socket shows as one more close with 1006 + net.up = true; + net.signedOut = true; + await vi.advanceTimersByTimeAsync(15_000); + expect(reload).toHaveBeenCalledTimes(1); + const dialled = net.sockets.length; + await vi.advanceTimersByTimeAsync(60_000); + expect(net.sockets).toHaveLength(dialled); +}); + +test("a host that accepts each socket and closes it 50 ms later: the dials keep to the quick waits and then one every 15 s, the epoch grows no faster, the mark does not flicker, and the probe runs", async () => { + using _clock = clock(); + const net = network(); + const { itx, session, reload } = member(net); + await itx.whoami(); + const states: string[] = []; + session.watch(() => { + const { state } = session.get(); + if (states.at(-1) !== state) states.push(state); + }); + const dialledAt: number[] = []; + net.dialled = () => dialledAt.push(Date.now()); + net.acceptThenCloseMs = 50; + const from = Date.now(); + net.drop(1006); + await vi.advanceTimersByTimeAsync(60_000); + // at once, then after 250, 500, 1,000, 2,000, 4,000 and 8,000 ms, then one every 15 s + expect(dialledAt.map((at) => at - from)).toEqual([ + 0, 300, 850, 1_900, 3_950, 8_000, 16_050, 31_100, 46_150, + ]); + expect(dialledAt.slice(1).every((at, index) => at - dialledAt[index]! >= 200)).toBe(true); + // a hook opens again once for each epoch: one for each dial, and no more + expect(session.get()).toMatchObject({ epoch: 1 + dialledAt.length }); + expect(states).toEqual(["opening", "reconnecting", "unreachable"]); + // the probe ran when the quick dials were over, and after each slow one + expect(net.asked()).toBe(3); + expect(reload).not.toHaveBeenCalled(); +}); + +test("a host that accepts and closes because the sign-in ended: the probe after the quick dials answers 401, and the page reloads and dials no more", async () => { + using _clock = clock(); + const net = network(); + const { itx, reload } = member(net); + await itx.whoami(); + net.acceptThenCloseMs = 50; + net.answers401 = true; + net.drop(1006); + await vi.advanceTimersByTimeAsync(16_100); + expect(net.sockets).toHaveLength(8); + expect(reload).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(60_000); + expect(net.sockets).toHaveLength(8); +}); + +test.each(["refuses", "aborts"] as const)( + "a host that accepts each socket, %s the first call as an overloaded mind does and closes 50 ms later: the dials keep to the quick waits and then one every 15 s, the session is never open, a call fails to its caller, and the probe runs", + async (overloaded) => { + using _clock = clock(); + const net = network(); + const { itx, session, reload } = member(net); + await itx.whoami(); + const states: string[] = []; + session.watch(() => { + const { state } = session.get(); + if (states.at(-1) !== state) states.push(state); + }); + const dialledAt: number[] = []; + net.dialled = () => dialledAt.push(Date.now()); + net.acceptThenCloseMs = 50; + net.overloaded = overloaded; + const from = Date.now(); + net.drop(1006); + const asked = itx.whoami().then( + () => "answered", + (error: Error) => error.message, + ); + await vi.advanceTimersByTimeAsync(60_000); + expect(await asked).toContain("Durable Object is overloaded"); + // an abort ends the session at once, and the page closes the socket; a refusal leaves it to + // the host's close 50 ms later + expect(dialledAt.map((at) => at - from)).toEqual( + overloaded === "aborts" + ? [0, 250, 750, 1_750, 3_750, 7_750, 15_750, 30_750, 45_750] + : [0, 300, 850, 1_900, 3_950, 8_000, 16_050, 31_100, 46_150], + ); + expect(states).toEqual(["opening", "reconnecting", "unreachable"]); + expect(net.asked()).toBe(3); + expect(reload).not.toHaveBeenCalled(); + }, +); + +test("a session that stayed open for 5 s is good, though the host said nothing: when it closes, the next dial is at once", async () => { + using _clock = clock(); + const net = network(); + const { itx, session } = member(net); + await itx.whoami(); + net.acceptThenCloseMs = 6_000; + net.drop(1006); + await vi.advanceTimersByTimeAsync(4_999); + expect(session.get()).toEqual({ epoch: 2, state: "reconnecting" }); + await vi.advanceTimersByTimeAsync(1); + expect(session.get()).toEqual({ epoch: 2, state: "open" }); + // the host answers again from its next socket on + net.acceptThenCloseMs = undefined; + await vi.advanceTimersByTimeAsync(1_000); + // closed at 6 s, and dialled again at once + expect(net.sockets).toHaveLength(3); + expect(session.get()).toEqual({ epoch: 3, state: "open" }); +}); + +test("a first socket that opened and is not good yet keeps its epoch when the page says it is reconnecting", async () => { + using _clock = clock(); + const net = network(); + // the host accepts the first socket and says nothing + net.acceptThenCloseMs = 6_000; + const { session } = member(net); + await vi.advanceTimersByTimeAsync(2_500); + // the epoch the open gave, never back to zero: what a page holds is not opened a second time + expect(session.get()).toEqual({ epoch: 1, state: "reconnecting" }); +}); + +test( + "a Dash page on the SDK's hooks alone is mounted anew at a new session and reads through it; no page is reloaded", + { timeout: 30_000 }, + async () => { + const net = network({ "/notes": [said(1, "first note")] }); + const reload = vi.fn(); + const itx = connectMemberItx({ + root: null, + url: new URL("ws://dash.example.com/itx"), + reload, + ...net, + }); + history.replaceState(null, "", "/notes"); + // as a page's script does before it draws: the first session is open + await itx.whoami(); + let mounts = 0; + /** A mind's own page: it holds a context as the SDK's hooks do, for one session. */ + function Notes({ itx: mind }: DashPageProps) { + const [mount] = useState(() => (mounts += 1)); + const held = useContextStub(() => mind.cd("/notes"), [mind]); + const log = useIterateContext(held.stub); + return ( + <p> + mount {mount}: {log.events.map((event) => JSON.stringify(event.payload)).join(" ")} + </p> + ); + } + const pages: DashPage[] = [{ id: "notes", name: "Notes", icon: BotIcon, component: Notes }]; + stubBrowser(); + const host = document.body.appendChild(document.createElement("div")); + const root = createRoot(host); + await act(() => + root.render( + <Dash + app="Dash" + itx={itx} + mind="notes.example.com" + principal={{ actor: "/members/a", email: "jo@example.com" }} + pages={pages} + links={[]} + />, + ), + ); + await shows(host, "first note"); + const { opened } = net; + expect(opened).toEqual(["/notes"]); + + await act(async () => net.drop(1006)); + await until(() => opened.length === 2); + await act(async () => net.append("/notes", said(2, "second note"))); + await shows(host, "second note"); + expect(host.textContent).toContain("mount 2:"); + expect(opened).toEqual(["/notes", "/notes"]); + expect(reload).not.toHaveBeenCalled(); + await act(() => root.unmount()); + host.remove(); + }, +); + +test( + "the Dash's list of agents over a new session whose catalog does not open: the agents it had read stay", + { timeout: 30_000 }, + async () => { + const catalog = { + agents: { + "/agents/a": { createdAt: "2026-11-16T12:00:00.000Z", kind: "iterate", title: "Alpha" }, + }, + }; + const net = network({}, { "/agents": catalog }); + const itx = connectMemberItx({ root: null, url: new URL("ws://dash.example.com/itx"), ...net }); + history.replaceState(null, "", "/agents"); + await itx.whoami(); + await using page = await drawDash(itx, "agents.example.com", [ + { id: "agents", name: "Agents", icon: BotIcon, component: Blank }, + ]); + await shows(page.host, "Alpha"); + const { opened } = net; + // the next session refuses the catalog, with its socket open + net.refused.add("/agents"); + await act(async () => net.drop(1006)); + await until(() => opened.length === 2); + for (let round = 0; round < 10; round += 1) + await act(() => new Promise((resolve) => setTimeout(resolve, 20))); + expect(opened).toEqual(["/agents", "/agents"]); + expect(page.host.textContent).toContain("Alpha"); + }, +); + +test( + "the Dash's raw view of a context over a cut socket: its rows stay, no alert, and the context is opened once more, from the new session's root", + { timeout: 30_000 }, + async () => { + using _layout = laidOut(); + const net = network( + { "/notes": [said(1, "first words")] }, + { "/": { contexts: { "/notes": {} } } }, + ); + const itx = connectMemberItx({ root: null, url: new URL("ws://dash.example.com/itx"), ...net }); + history.replaceState(null, "", "/contexts/notes"); + await itx.whoami(); + await using page = await drawDash(itx, "contexts.example.com", [ + { id: "contexts", name: "Contexts", icon: BotIcon, component: DashContexts }, + ]); + // the raw view draws an event as its type, and events of one type in a row as one row + await shows(page.host, "agent/context-added"); + const { opened } = net; + expect(opened).toEqual(["/", "/notes"]); + using seen = watch(page.host, "agent/context-added"); + + await act(async () => net.drop(1006)); + await until(() => opened.length === 4); + // the view subscribed again: what the mind appends now arrives + await act(async () => net.append("/notes", said(2, "second words"))); + await shows(page.host, "2 events"); + // one root and one shown context for each session: nothing was opened from the root that ended + expect(opened).toEqual(["/", "/notes", "/", "/notes"]); + expect(seen.alerts()).toBe(0); + expect(seen.withoutRows()).toBe(0); + }, +); + +test( + "a Dash's agent view over a cut socket: its rows and its composer stay, no loading words come back, the mark shows after two seconds, and the new session's log is live", + { + timeout: 30_000, + }, + async () => { + using _layout = laidOut(); + const net = network({ "/agents/a": [said(1, "first words")] }); + const { itx, reload } = member(net); + history.replaceState(null, "", "/agents/agents/a"); + await using page = await draw(itx); + await shows(page.host, "first words"); + await shows(page.host, "Idle"); + const composer = page.host.querySelector("form"); + expect(Boolean(composer)).toBe(true); + // each context the page opened, in order + const { opened } = net; + expect(opened).toEqual(["/agents/a"]); + using seen = watch(page.host); + const row = wordsOf(page.host, "first words"); + expect(Boolean(row)).toBe(true); + + // a deploy cuts the socket, and the mind is away for longer than the quiet time + net.up = false; + await act(async () => net.drop(1006)); + await act(() => new Promise((resolve) => setTimeout(resolve, 1_500))); + expect(markOf(page.host)).toBe(undefined); + await shows(page.host, "Reconnecting…"); + expect(markOf(page.host)).toBe("Reconnecting…"); + net.up = true; + await act(async () => void dispatchEvent(new Event("online"))); + await until(() => opened.length === 2 && !markOf(page.host)); + expect(opened).toEqual(["/agents/a", "/agents/a"]); + expect(markOf(page.host)).toBe(undefined); + + // the view subscribed again: what the mind appends now arrives + await act(async () => net.append("/agents/a", said(2, "second words"))); + await shows(page.host, "second words"); + expect(page.host.textContent).toContain("first words"); + expect(seen.withoutRows()).toBe(0); + expect(seen.words()).toEqual([]); + // nothing that was drawn is drawn again: the first row is the same element, untouched + expect(wordsOf(page.host, "first words") === row).toBe(true); + expect(seen.redrawn()).toBe(0); + // the same element, so what was typed in it is still there (compared here: a failed `toBe` of + // two elements prints both, with all that React hangs on them) + expect(page.host.querySelector("form") === composer).toBe(true); + expect(reload).not.toHaveBeenCalled(); + }, +); + +test("three reloads in a minute stop the reloads; a minute later the page may reload again", () => { + const tab = storage(); + expect([0, 1_000, 2_000, 3_000].map((at) => mayReload(tab, at))).toEqual([ + true, + true, + true, + false, + ]); + expect(mayReload(tab, 70_000)).toBe(true); +}); + +test("storage that cannot be read or holds something else is no reload yet", () => { + const broken = { + getItem: () => { + throw new Error("denied"); + }, + setItem: () => {}, + }; + expect(mayReload(broken, 0)).toBe(true); + const odd = storage(); + odd.setItem("itx-reloads", '{"not":"a list"}'); + expect(mayReload(odd, 0)).toBe(true); +}); + +/** The test's own clock, and a tab with no reloads behind it; disposing gives the real clock + * back. */ +function clock() { + sessionStorage.clear(); + vi.useFakeTimers(); + return { [Symbol.dispose]: () => void vi.useRealTimers() }; +} + +/** A tab's session storage. */ +function storage() { + const kept = new Map<string, string>(); + return { + getItem: (key: string) => kept.get(key) ?? null, + setItem: (key: string, value: string) => void kept.set(key, value), + }; +} + +/** THE NETWORK AND THE MIND BEHIND IT. `WebSocket` is the constructor a page dials with: a dial + * opens while `up`, and else closes with 1006 before it opened. Behind an open socket is a + * capnweb session to a mind that holds `logs` by path. `drop` closes the open socket from the + * mind's side; `silent` loses what the page sends, with no close. */ +function network(logs: Record<string, LoggedEvent[]> = {}, facets: Record<string, object> = {}) { + const subscribers = new Set<{ + path: string; + push: (events: LoggedEvent[]) => unknown; + socket: FakeSocket; + }>(); + let asked = 0; + const net = { + up: true, + silent: false, + /** the sign-in ended: the host refuses each upgrade, and answers 401 over HTTP */ + signedOut: false, + /** the host accepts each upgrade, answers nothing on it, and closes it this long after */ + acceptThenCloseMs: undefined as number | undefined, + /** with `acceptThenCloseMs`: the host answers each call with a refusal, or its first message + * with an abort of the session, as an overloaded mind does */ + overloaded: undefined as "refuses" | "aborts" | undefined, + /** the host answers 401 over HTTP, whatever it does with an upgrade */ + answers401: false, + /** called at each dial */ + dialled: () => {}, + /** how often the page asked the host over HTTP whether it is signed in */ + asked: () => asked, + async fetch() { + asked += 1; + if (!net.up) throw new TypeError("Failed to fetch"); + return new Response(null, { status: net.signedOut || net.answers401 ? 401 : 426 }); + }, + sockets: [] as FakeSocket[], + /** each context a page opened, in order */ + opened: [] as string[], + /** the contexts that the mind refuses to open */ + refused: new Set<string>(), + drop(code: number) { + net.sockets.at(-1)?.end(code); + }, + append(path: string, event: LoggedEvent) { + (logs[path] ||= []).push(event); + for (const one of subscribers) if (one.path === path) void one.push([event]); + }, + // The members that the page's dial and capnweb's transport use, and no more. + WebSocket: undefined as unknown as typeof WebSocket, + }; + + class Listed extends RpcTarget { + #rows: unknown[]; + constructor(rows: unknown[]) { + super(); + this.#rows = rows; + } + list() { + return this.#rows; + } + } + class Handle extends RpcTarget { + #release: () => void; + constructor(release: () => void) { + super(); + this.#release = release; + } + [Symbol.dispose]() { + this.#release(); + } + } + class Context extends RpcTarget { + #path: string; + #socket: FakeSocket; + constructor(path: string, socket: FakeSocket) { + super(); + this.#path = path; + this.#socket = socket; + } + readEvents(after = 0, limit = 1000) { + const held = logs[this.#path] || []; + return { + events: held.filter((event) => event.offset > after).slice(0, limit), + atHead: true, + scannedThroughOffset: held.at(-1)?.offset || 0, + }; + } + subscribe(input: { + consumes?: string[]; + target: { dup(): (events: LoggedEvent[]) => unknown }; + }) { + const durable = input.consumes?.includes("*"); + // the page's function ends with this call unless the mind keeps a copy of its own + const subscriber = { path: this.#path, push: input.target.dup(), socket: this.#socket }; + if (durable) subscribers.add(subscriber); + return new Handle(() => subscribers.delete(subscriber)); + } + get subscriptions() { + return new Listed([{ name: "agent", hostedFacet: { name: "agent" } }]); + } + get rpcStubs() { + return new Listed([]); + } + invoke(call: string) { + return call.includes("liveSnapshot") + ? { rev: 1, state: facets[this.#path] || liveState() } + : { offset: 0, state: {} }; + } + cd(path: string) { + return open(path, this.#socket); + } + } + /** A context, opened from the mind's root or from another context. */ + const open = (path: string, socket: FakeSocket) => { + net.opened.push(path); + if (net.refused.has(path)) throw new Error(`${path} is not yours to open`); + return new Context(path, socket); + }; + class Kv extends RpcTarget { + get() { + return null; + } + } + class Repos extends RpcTarget { + get() { + return new Kv(); + } + } + class Overloaded extends RpcTarget { + whoami(): never { + throw new Error("Durable Object is overloaded"); + } + } + // capnweb's abort frame, as the mind's end sends it + const overloadedAbort = JSON.stringify([ + "abort", + ["error", "Error", "Durable Object is overloaded"], + ]); + class Mind extends RpcTarget { + #socket: FakeSocket; + constructor(socket: FakeSocket) { + super(); + this.#socket = socket; + } + whoami() { + return { principal: { actor: "/members/a", email: "jo@example.com" } }; + } + get kv() { + return new Kv(); + } + get repos() { + return new Repos(); + } + get rewriteRules() { + return new Kv(); + } + get contexts() { + return new Listed([]); + } + cd(path: string) { + return open(path, this.#socket); + } + } + + /** The page's end of a socket, and with `mind` the mind's end of it. */ + class FakeSocket extends EventTarget { + static CONNECTING = 0; + static OPEN = 1; + static CLOSED = 3; + readyState = FakeSocket.CONNECTING; + binaryType = "blob"; + mind = Object.assign(new EventTarget(), { + readyState: FakeSocket.OPEN, + binaryType: "blob", + send: (data: unknown) => { + if (this.readyState === FakeSocket.OPEN && !net.silent) + queueMicrotask(() => this.dispatchEvent(new MessageEvent("message", { data }))); + }, + close: () => this.end(1000), + }); + constructor() { + super(); + net.sockets.push(this); + net.dialled(); + queueMicrotask(() => { + if (this.readyState !== FakeSocket.CONNECTING) return; + if (!net.up || net.signedOut) return this.end(1006); + this.readyState = FakeSocket.OPEN; + if (net.acceptThenCloseMs !== undefined) { + setTimeout(() => this.end(1006), net.acceptThenCloseMs); + if (net.overloaded === "refuses") + newWebSocketRpcSession(this.mind as unknown as WebSocket, new Overloaded()); + if (net.overloaded === "aborts") + this.mind.addEventListener("message", () => this.mind.send(overloadedAbort), { + once: true, + }); + return this.dispatchEvent(new Event("open")); + } + // The mind's end has the members that capnweb's transport uses, and no more. + newWebSocketRpcSession(this.mind as unknown as WebSocket, new Mind(this)); + this.dispatchEvent(new Event("open")); + }); + } + send(data: unknown) { + if (!net.silent) + queueMicrotask(() => this.mind.dispatchEvent(new MessageEvent("message", { data }))); + } + close() { + this.end(1006); + } + end(code: number) { + if (this.readyState === FakeSocket.CLOSED) return; + this.readyState = FakeSocket.CLOSED; + for (const one of subscribers) if (one.socket === this) subscribers.delete(one); + this.mind.dispatchEvent(new CloseEvent("close", { code })); + this.dispatchEvent(new CloseEvent("close", { code })); + } + } + net.WebSocket = FakeSocket as unknown as typeof WebSocket; + return net; +} + +/** A member's itx over `net`, read by one listener as a drawn page reads it. */ +function member( + net: ReturnType<typeof network>, + root: { textContent: string } | null = null, + /** a socket the page dialled before the app loaded */ + early?: WebSocket, +) { + const reload = vi.fn(); + // A page never takes its listeners off its window, and one jsdom window serves every test of + // this file. So a member's listeners are taken off when its test ends. Else a later test's + // "online" has the members of the tests before it dial again, on the real clock, and a socket + // of theirs can close when the file's window is gone: an error that no test owns. + const heard = [window, document].map( + (target) => [target, vi.spyOn(target, "addEventListener")] as const, + ); + const itx = connectMemberItx({ + root, + url: new URL("ws://dash.example.com/itx"), + WebSocket: net.WebSocket, + early, + fetch: net.fetch, + reload, + }); + for (const [target, spy] of heard) { + const listeners = [...spy.mock.calls]; + spy.mockRestore(); + onTestFinished(() => { + for (const [type, listener] of listeners) target.removeEventListener(type, listener); + }); + } + const session = itxSessionOf(itx); + session.subscribe(() => {}); + return { itx, session, reload }; +} + +/** A page with height, which jsdom lacks, so the virtual log draws its rows; disposing takes it + * back. */ +function laidOut() { + const sizes = { clientHeight: 600, offsetHeight: 0 }; + const own = Object.keys(sizes).map( + (name) => [name, Object.getOwnPropertyDescriptor(HTMLElement.prototype, name)] as const, + ); + for (const [name, value] of Object.entries(sizes)) + Object.defineProperty(HTMLElement.prototype, name, { configurable: true, get: () => value }); + return { + [Symbol.dispose]: () => { + for (const [name, descriptor] of own) + if (descriptor) Object.defineProperty(HTMLElement.prototype, name, descriptor); + }, + }; +} + +/** The innermost element that shows exactly `words`. */ +function wordsOf(host: HTMLElement, words: string) { + return [...host.querySelectorAll("[role=log] *")].findLast((one) => one.textContent === words); +} + +/** What the page showed at each change of it, from now: how often the first row was gone, which + * words of a first load came back, how often the first row's words were drawn again, and how + * often it showed an alert. */ +function watch(host: HTMLElement, first = "first words") { + const loading = ["Connecting…", "Reading the log", "Nothing said", "Loading the page…"]; + const found = new Set<string>(); + const row = wordsOf(host, first); + let withoutRows = 0; + let redrawn = 0; + let alerts = 0; + const observer = new MutationObserver((changes) => { + if (host.querySelector("[role=alert]")) alerts += 1; + for (const change of changes) + if ( + row?.contains(change.target) || + [...change.removedNodes].some((gone) => row && gone.contains(row)) + ) + redrawn += 1; + const text = host.textContent || ""; + if (!text.includes(first)) withoutRows += 1; + for (const words of loading) if (text.includes(words)) found.add(words); + }); + observer.observe(host, { childList: true, subtree: true, characterData: true }); + return { + withoutRows: () => withoutRows, + redrawn: () => redrawn, + alerts: () => alerts, + words: () => [...found], + [Symbol.dispose]: () => observer.disconnect(), + }; +} + +/** What the mark says, when the page shows it. */ +function markOf(host: HTMLElement) { + return host.querySelector("[data-slot=reconnecting-mark]")?.textContent || undefined; +} + +/** Lets the page work, 20 ms at a time, until `done` or five seconds are over. Each wait is an + * `act` of its own: React draws what a wait brought when its `act` ends. */ +async function until(done: () => boolean) { + for (let round = 0; round < 250 && !done(); round += 1) + await act(() => new Promise((resolve) => setTimeout(resolve, 20))); +} + +/** Waits until the page shows `words`. */ +async function shows(host: HTMLElement, words: string) { + await until(() => Boolean(host.textContent?.includes(words))); + expect(host.textContent).toContain(words); +} + +/** A page that draws nothing and holds nothing of a session. */ +function Blank() { + return null; +} +Blank.staysOverReconnect = true; + +/** A Dash of `pages`, as a mind's own page draws it. */ +async function drawDash(itx: DashPageProps["itx"], mind: string, pages: DashPage[]) { + stubBrowser(); + const host = document.body.appendChild(document.createElement("div")); + const root = createRoot(host); + await act(() => + root.render( + <Dash + app="Dash" + itx={itx} + mind={mind} + principal={{ actor: "/members/a", email: "jo@example.com" }} + pages={pages} + links={[]} + />, + ), + ); + return { + host, + [Symbol.asyncDispose]: async () => { + await act(() => root.unmount()); + host.remove(); + }, + }; +} + +/** What the shell asks of a browser and jsdom lacks. */ +function stubBrowser() { + vi.stubGlobal("matchMedia", (query: string) => ({ + matches: false, + media: query, + addEventListener() {}, + removeEventListener() {}, + })); + vi.stubGlobal("fetch", async () => Response.json({ minds: [], lastUsed: null })); + vi.stubGlobal( + "ResizeObserver", + class { + observe() {} + unobserve() {} + disconnect() {} + }, + ); +} + +/** The Agents page in the shell, with the mark, as a Dash draws them. */ +async function draw(itx: Parameters<typeof DashAgents>[0]["itx"]) { + stubBrowser(); + const row = (id: string): DashPage => ({ id, name: id, icon: BotIcon, component: () => null }); + const pages = [row("home"), row("agents"), row("contexts")]; + const agents = agentRowsOf({ + agents: { "/agents/a": { createdAt: "2026-11-16T12:00:00.000Z", kind: "iterate", title: "A" } }, + }); + const host = document.body.appendChild(document.createElement("div")); + const root = createRoot(host); + await act(() => + root.render( + <AppShell app="Dash" mind="example.com" account={null} locationKey="/"> + <Suspense fallback="Loading the page…"> + <DashAgents + itx={itx} + mind="example.com" + principal={{ actor: "/members/a", email: "jo@example.com" }} + page={pages[1]!} + pages={pages} + links={[]} + catalog={undefined} + agents={agents} + waiting={0} + /> + </Suspense> + <ReconnectingMark itx={itx} /> + </AppShell>, + ), + ); + return { + host, + [Symbol.asyncDispose]: async () => { + await act(() => root.unmount()); + host.remove(); + }, + }; +}
A src/browser/member-itx.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/browser/page.ts
@@ -0,0 +1,16 @@ +// What a no-build page needs to render this package's components with the React they use: htm's +// `html` tag over React's createElement, `render` into an element, and React's API. +// +// import { html, render, useState } from "@iterate-com/ui/page"; +// import { ContextView } from "@iterate-com/ui/components/context-view/context-view"; +// render(html`<${ContextView} … />`, document.getElementById("root")); +import htm from "htm"; +import { createElement, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; + +export * from "./react.ts"; +export const html = htm.bind(createElement); + +export function render(node: ReactNode, element: Element) { + createRoot(element).render(node); +}
A src/browser/query.ts
@@ -0,0 +1,11 @@ +// REACT-QUERY FOR A NO-BUILD PAGE, from this package: +// +// import { QueryClient, QueryClientProvider, useQuery } from "@iterate-com/ui/query"; +// +// A page does not name `@tanstack/react-query` in its import map. A script that needs a line of +// its own in index.html stops working in every mind whose owner changed that page: an update +// moves the script and leaves the page. The import map names this package, React and nothing +// else. It is also one copy: the build keeps react-query in one file (browser-entries.ts +// `vendor-query`), so a component of this package that asks for a query finds the client that +// the page provided. +export * from "@tanstack/react-query";
A src/browser/react-compiler-runtime.ts
@@ -0,0 +1,8 @@ +// The build's `react/compiler-runtime`, by name (CommonJS), for a page's import map: a library built +// by React Compiler imports it. +// Read untyped: @types/react does not declare it. +import * as runtime from "react/compiler-runtime"; + +const compilerRuntime: Record<string, unknown> = runtime; + +export const { c } = compilerRuntime;
A src/browser/react-dom-client.ts
@@ -0,0 +1,7 @@ +// The build's `react-dom/client`, by name (CommonJS), for a page's import map. +// Read untyped: @types/react-dom has no `version` here. +import * as client from "react-dom/client"; + +const reactDomClient: Record<string, unknown> = client; + +export const { createRoot, hydrateRoot, version } = reactDomClient;
A src/browser/react-dom.ts
@@ -0,0 +1,21 @@ +// The build's `react-dom`, by name (CommonJS), for a page's import map: a library esm.sh builds with +// `?external=react,react-dom` imports it bare, for portals and `flushSync`. +import ReactDOM from "react-dom"; + +export default ReactDOM; +export const { + browser, + createPortal, + flushSync, + preconnect, + prefetchDNS, + preinit, + preinitModule, + preload, + preloadModule, + requestFormReset, + unstable_batchedUpdates, + useFormState, + useFormStatus, + version, +} = ReactDOM;
A src/browser/react-jsx-runtime.ts
@@ -0,0 +1,5 @@ +// The build's `react/jsx-runtime`, by name (React is CommonJS), for a page's import map: a library +// esm.sh builds with `?external=react,react-dom` imports it bare. +import * as runtime from "react/jsx-runtime"; + +export const { Fragment, jsx, jsxs } = runtime;
A src/browser/react-modules.test.ts
@@ -0,0 +1,46 @@ +// The React modules a page's import map points `react`, `react/…` and `react-dom/…` at +// (src/browser/react*.ts). React is CommonJS, so each lists React's API by name; a name missing here +// is an import that fails in a library esm.sh built with `?external=react,react-dom`. +import { createRequire } from "node:module"; +import path from "node:path"; +import { expect, test } from "vitest"; + +test.for([ + { name: "react", entry: "./react.ts", build: "react/cjs/react.production.js" }, + { + name: "react/jsx-runtime", + entry: "./react-jsx-runtime.ts", + build: "react/cjs/react-jsx-runtime.production.js", + }, + { + name: "react/compiler-runtime", + entry: "./react-compiler-runtime.ts", + build: "react/cjs/react-compiler-runtime.production.js", + }, + { name: "react-dom", entry: "./react-dom.ts", build: "react-dom/cjs/react-dom.production.js" }, + { + name: "react-dom/client", + entry: "./react-dom-client.ts", + build: "react-dom/cjs/react-dom-client.production.js", + }, +])( + "the page's $name exports every name React's production build does", + async ({ entry, build }) => { + const exported = Object.keys(await import(entry)).filter((name) => name !== "default"); + expect(exported.sort()).toEqual(productionExports(build)); + }, +); + +/** The public names of one of React's production builds, by its path in the package (React's + * exports map hides cjs/, so the file is required by its path on disk). */ +function productionExports(build: string) { + const require = createRequire(import.meta.url); + const [pkg] = build.split("/"); + const file = path.join( + path.dirname(require.resolve(`${pkg}/package.json`)), + build.slice(pkg!.length + 1), + ); + return Object.keys(require(file)) + .filter((name) => !name.startsWith("__")) + .sort(); +}
A src/browser/react.ts
@@ -0,0 +1,54 @@ +// The build's React for a page's import map (`"react": "…/@iterate-com/ui@<version>/react"`), so a +// React library the page loads from esm.sh with `?external=react,react-dom` uses the same React as this +// package's components. React is CommonJS: `export * from "react"` would export nothing, so its API +// is listed by name (react-modules.test.ts checks the list against React's production build), read +// untyped: @types/react lags the build (it has no `unstable_useCacheRefresh`). +import React from "react"; + +const react: Record<string, unknown> = React; + +export default React; +export const { + Activity, + Children, + Component, + Fragment, + Profiler, + PureComponent, + StrictMode, + Suspense, + ViewTransition, + addTransitionType, + cache, + cacheSignal, + cloneElement, + createContext, + createElement, + createRef, + forwardRef, + isValidElement, + lazy, + memo, + startTransition, + unstable_useCacheRefresh, + use, + useActionState, + useCallback, + useContext, + useDebugValue, + useDeferredValue, + useEffect, + useEffectEvent, + useId, + useImperativeHandle, + useInsertionEffect, + useLayoutEffect, + useMemo, + useOptimistic, + useReducer, + useRef, + useState, + useSyncExternalStore, + useTransition, + version, +} = react;
A src/browser/styles.css
@@ -0,0 +1,4 @@ +/* The published stylesheet (dist/styles.css), which every page links: stylesheet.css without the + docs editor's classes. The docs editor's page links docs-editor.css in its place. */ +@import "./stylesheet.css"; +@source not "../components/docs-editor";
A src/browser/stylesheet.css
@@ -0,0 +1,14 @@ +/* What the published stylesheets have in common: the apps' globals.css, whose Tailwind scans all of + src/, Streamdown's classes for the repo IDE's markdown preview, as Dash's stylesheet adds, and + the example pages'. styles.css is this without the docs editor's classes; docs-editor.css is this + with them, and Atomic's. */ +@import "../styles/globals.css"; +@source "../../node_modules/streamdown/dist/*.js"; +/* the example pages' own classes (examples/), so a page copied from one finds them */ +@source "../../examples/*"; + +/* Tailwind also reads every file of the package for class names. The registry's theme item and the + build's scripts name the look's utilities without using them (shadow-2xl, ring), so they stay + out, and this stylesheet is what the components use. */ +@source not "../../registry.json"; +@source not "../../scripts";
A src/components/agent-chat/AGENTS.md
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-chat-search.ts
@@ -0,0 +1,16 @@ +// The agent chat's state as a URL's search: the tab, the open trace, and every choice of the Events +// tab's context view (`ContextViewState`, whose file says how a route uses a schema like this one). +import { z } from "zod"; +import { ContextViewState } from "#/components/context-view/context-view-search.ts"; + +export const AgentChatState = ContextViewState.extend({ + /** The tab shown; omitted = the chat. */ + view: z.enum(["chat", "events"]).optional().catch(undefined), + /** The LLM request whose trace is open, by its offset. */ + llmRequest: z.number().int().positive().optional().catch(undefined), + /** The script run whose trace is open, by its `itx/run-requested` offset. */ + scriptRun: z.number().int().positive().optional().catch(undefined), +}); + +/** What `AgentChat` reads and patches. */ +export type AgentChatState = z.infer<typeof AgentChatState>;
A src/components/agent-chat/agent-chat.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-chat.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-event-inspectors.tsx
@@ -0,0 +1,40 @@ +// What the Events tab's inspector shows for a fact of the agent (agent-facts.ts), above the event +// as JSON: the words themselves, whole. The rows of the log are the context view's own, and the +// same for every type. +import { AGENT_FACT } from "./agent-facts.ts"; +import { record, str } from "#/components/context-view/payload-readers.ts"; +import type { EventInspectors } from "#/components/context-view/types.tsx"; + +/** The role a context item was added as (the model's conversation has four), as plain text. */ +const role = (name: string) => <span className="text-xs text-muted-foreground">{name}</span>; + +/** Prose as the model saw or said it, whole, wrapped — never a sideways scroll. */ +const prose = (text: string) => <p className="text-sm whitespace-pre-wrap break-words">{text}</p>; + +/** The inspector's rich bodies: the words themselves, whole. */ +export const agentEventInspectors: EventInspectors = { + "events.iterate.com/agent/context-added": (e) => { + const p = record(e.payload); + return ( + <div className="flex flex-col gap-2"> + <div>{role(str(p.role, "?"))}</div> + {prose(str(p.content))} + </div> + ); + }, + [AGENT_FACT.uiMessageSent]: (e) => prose(str(record(e.payload).message)), + [AGENT_FACT.llmSettled]: (e) => { + const result = record(record(e.payload).result); + if (result.status === "succeeded") return prose(str(result.text)); + if (result.status === "failed") + return ( + <div className="flex flex-col gap-2"> + <p data-type="error" className="text-sm text-destructive"> + {str(result.errorMessage)} + </p> + {result.partialText ? prose(str(result.partialText)) : null} + </div> + ); + return result.partialText ? prose(str(result.partialText)) : null; + }, +};
A src/components/agent-chat/agent-events.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-events.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-facts.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-facts.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-feed-list.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-feed.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-inspectors.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-live-activity.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-page-header.test.tsx
@@ -0,0 +1,68 @@ +// @vitest-environment jsdom +// The agent page's header on a page with no AppShell (Meet): a header row of its own, with the way +// back, the title and the path at the left, then who is here (the mind's face first), Start call, +// Share and Chat | Events. Each place is drawn from the first paint. +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, test, vi } from "vitest"; +import { AgentPageHeader, heldRowsOf } from "./agent-page-header.tsx"; + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + +test("with no AppShell the header is a row of its own, in the Dash's order, and nothing is an empty place", async () => { + vi.stubGlobal("matchMedia", (query: string) => ({ + matches: false, + media: query, + addEventListener() {}, + removeEventListener() {}, + })); + const host = document.body.appendChild(document.createElement("div")); + const root = createRoot(host); + await act(() => + root.render( + <AgentPageHeader + path="/agents/meet/standup" + title="Standup" + before={<a href="/">All meetings</a>} + mind={{ name: "Acme", logo: <img src="/acme.svg" alt="" /> }} + presence + call + share + />, + ), + ); + const header = host.querySelector("header")!; + expect(header.querySelector("[data-page-header]")).not.toBe(null); + expect(header.textContent).toContain("All meetings"); + expect(header.textContent).toContain("Standup"); + expect( + [...header.querySelectorAll("[data-slot^=agent-header-]")].map((place) => [ + place.getAttribute("data-slot"), + place.className, + place.children.length > 0, + ]), + ).toEqual([ + ["agent-header-aside", "contents", true], + ["agent-header-call", "contents", true], + ["agent-header-share", "contents", true], + ]); + expect(header.querySelector("[data-mind-face]")?.getAttribute("aria-label")).toBe("Acme"); + // out of the call: Start call, which waits for the call's part + expect( + header.querySelector("[data-slot=agent-header-call] button")?.getAttribute("aria-label"), + ).toBe("Start call"); + // the tabs are there, and cannot be pressed until the page passes them + expect(header.querySelector("[inert] [role=tablist]")).not.toBe(null); + act(() => root.unmount()); + host.remove(); + vi.unstubAllGlobals(); +}); + +test("the Events tab's count leaves out a page's presence status", () => { + expect( + heldRowsOf([ + { type: "events.iterate.com/agent/message-received" }, + { type: "presence/status" }, + ]), + ).toBe(1); +});
A src/components/agent-chat/agent-page-header.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-progress.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-progress.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-reading.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-shell-contexts.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-shell.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-strip.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-traces.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-ui-reducer.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/agent-ui-reducer.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/authored-script.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/chat-parts.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/choice-in-words.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/choice-syntax.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/chunked-text.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/chunked-text.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/composer-attachments.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/composer-textarea.client.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/composer-textarea.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/composer.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/composer.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/full-text-snapshot.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/llm-request-trace-view.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/llm-request-trace.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/llm-request-trace.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/message.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/message.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/multiplayer.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/participant.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/presence-line.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/queued-messages.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/stream-event.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/streaming-text.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/streaming-text.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/use-composer-attachments.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-chat/use-ticking-now-ms.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-context-rows.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-context-rows.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-context.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-context.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agent-look.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agents-home.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agents-home.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agents-nav.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/agents-nav.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/analytics-page.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/analytics-page.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/app-build.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/app-shell-palette-entries.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/app-shell-palette-entries.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/app-shell-palette.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/app-shell.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/app-shell.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/approvals-alert.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/calendar-invite.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/calendar-invite.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/call-bar.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/call-bar.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/call-controls.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/call-controls.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/call-lobby.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/call-lobby.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/call-pip.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/call-pip.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/call-share.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/call-tiles.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/call-tiles.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/caption-strip.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/caption-strip.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/face.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/spoken-lines.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/spoken-lines.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/transcript-history.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/transcript-history.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/transcript-rollup.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/call/transcript-rollup.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/change-my-mind-button.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/change-my-mind-button.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/checklist.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/cloudflare-button.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/code-block.client.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/code-block.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/code-editor.client.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/code-editor.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/connect-mind.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/connected-minds.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-catalog/context-about.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-catalog/context-activity-stack-view.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-catalog/context-activity-stack.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-catalog/context-activity-stack.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-catalog/context-catalog-list.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-catalog/context-catalog-list.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-catalog/context-catalog-rows.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-catalog/context-catalog-rows.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-catalog/context-catalog.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-catalog/context-icon.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-catalog/context-palette-rows.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-catalog/context-palette-rows.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-catalog/context-palette.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-explorer/context-explorer.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-explorer/context-explorer.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-path-text.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/append-completions.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/append-completions.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/append-composer.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/append-events.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/append-events.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/awake-dot.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/context-path-links.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/context-path.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/context-tree-rows.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/context-tree.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/context-tree.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/context-view-search.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/context-view-search.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/context-view.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/core-events.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/event-inspector-log.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/event-inspector-log.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/event-inspector.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/event-inspector.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/event-row-format.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/event-row.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/event-row.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/feed-list.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/feed-rows.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/filter-row.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/filters.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/filters.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/folds.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/folds.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/live-state-value.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/payload-readers.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/presence-strip.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/pretty-state.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/print-expression.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/processors-panel.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/context-view/types.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/copy-text.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/dash/dash-agents-nav.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/dash/dash-href.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/dash/dash-href.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/dash/dash-pages.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/dash/dash-pages.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/dash/dash-paths.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/dash/dash-routes.fixture.json
Not shown: the change is larger than this page shows. A clone has it.
A src/components/dash/dash.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/dash/dash.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/dash/serves.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/dash/serves.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/AGENTS.md
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/anchor.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/anchor.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/collab.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/commands.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/comment-marks.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/comments-panel.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/comments.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/comments.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/create-doc.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/doc-list-panel.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/doc-list.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/doc-session.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/doc-session.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/doc-tree-element.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/doc-tree-nav.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/doc-tree.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/doc-tree.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/docs-editor.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/extensions.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/file-kind.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/frames.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/frames.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/frontmatter.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/icons.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/install.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/docs-editor/install.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/environment-head-content.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/identifier.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/integrations-page-server.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/integrations-page.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/integrations-page.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/iterate-logo.svg
Not shown: the change is larger than this page shows. A clone has it.
A src/components/iterate-logo.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/last-mind-redirect.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/list-row-text.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/log-in-with-iterate.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/mcp-connect.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/mcp-connect.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/mind-app-shell.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/not-recorded.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/page-tools.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/page-tools.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/posthog-replay.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/posthog.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/reconnecting-mark.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/AGENTS.md
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/codemirror.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/commit-diff-pane.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/commit-history-panel.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/file-chrome.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/git-panel.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/html-preview.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/markdown-preview.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/repo-client.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/repo-client.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/repo-code-editor.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/repo-editor-pane.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/repo-file-discard.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/repo-file-discard.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/repo-file-kinds.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/repo-file-tree-paths.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/repo-file-tree-paths.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/repo-file-tree.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/repo-ide-activity-strip.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/repo-ide-search.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/repo-ide.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/staged-changes.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/staged-changes.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/repo-ide/use-repo-ide-actions.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/route-defaults.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/route-defaults.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/secrets-page.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/setup-steps.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/source-code-block.client.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/standalone-page.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/step-row.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/step-row.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/stream-link.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/stream-link.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/time-chart.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/AGENTS.md
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/alert-dialog.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/alert.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/avatar.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/badge.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/breadcrumb.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/button-group.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/button.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/card.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/checkbox.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/collapsible.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/command.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/dialog.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/dropdown-menu.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/empty.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/field.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/input-group.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/input.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/label.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/native-select.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/popover.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/radio-group.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/select.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/separator.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/sheet.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/sidebar.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/skeleton.tsx
@@ -0,0 +1,13 @@ +import { cn } from "cn" + +function Skeleton({ className, ...props }: React.ComponentProps<"div">) { + return ( + <div + data-slot="skeleton" + className={cn("animate-pulse rounded-md bg-muted", className)} + {...props} + /> + ) +} + +export { Skeleton }
A src/components/ui/sonner.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/spinner.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/table.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/tabs.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/textarea.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/ui/tooltip.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/virtual-log/AGENTS.md
Not shown: the change is larger than this page shows. A clone has it.
A src/components/virtual-log/older-pages.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/virtual-log/read-progress.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/virtual-log/read-progress.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/virtual-log/remembered.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/virtual-log/use-reader.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/virtual-log/virtual-log.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/widget/widget-frame.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/widget/widget-frame.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/widget/widget-mcp.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/widget/widget-mcp.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/widget/widget-row.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/components/widget/widget.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/components/widget/widget.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/hooks/use-context-explorer.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/hooks/use-itx-session.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/hooks/use-mobile.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/agent-summary.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/agent-summary.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/approvals.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/approvals.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/call-engine.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/call-engine.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/call-rules.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/call-rules.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/change-my-mind.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/change-my-mind.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/codemirror-theme.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/facet-view.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/format-script.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/format-script.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/held-acts.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/held-acts.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/itx-session.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/itx-session.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/page-tools.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/page-tools.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/page-url.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/page-url.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/plain-left-click.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/presence.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/presence.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/principal-label.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/px-per-rem.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/saved-context.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/saved-context.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/saved-log-tail.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/saved-log-tail.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/secrets.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/source-editor.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/waiting-approvals-hook.test.tsx
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/waiting-approvals.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/lib/waiting-approvals.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/styles/AGENTS.md
Not shown: the change is larger than this page shows. A clone has it.
A src/styles/globals.css
Not shown: the change is larger than this page shows. A clone has it.
A src/styles/iterate.css
Not shown: the change is larger than this page shows. A clone has it.
A src/styles/tokens.css
Not shown: the change is larger than this page shows. A clone has it.
A src/test-support/agent-log.ts
Not shown: the change is larger than this page shows. A clone has it.
A tsconfig.json
Not shown: the change is larger than this page shows. A clone has it.
A tsconfig.worker.json
Not shown: the change is larger than this page shows. A clone has it.
A tsdown.config.ts
Not shown: the change is larger than this page shows. A clone has it.
A vitest.config.ts
Not shown: the change is larger than this page shows. A clone has it.