packages/ui of iterate/private at 5b863d456d2bf5614906676736e7171d6b9685f8
ui release builder, 2026-11-26 23:04 UTC · 2dad9d70df726cde287b3b2066cc14a672d236e8 · parent 6a1d909
33 files changed
- M AGENTS.md
- M browser-entries.ts
- M package.json
- M registry.json
- M src/browser/chunks.test.ts
- A src/browser/db.ts
- M src/components/agent-chat/agent-feed.tsx
- M src/components/agent-chat/composer.tsx
- M src/components/agent-chat/presence-line.tsx
- M src/components/call/call-pip.test.tsx
- M src/components/call/call-pip.tsx
- M src/components/call/face.tsx
- A src/components/context-catalog/catalog-collection.test.ts
- A src/components/context-catalog/catalog-collection.ts
- M src/components/context-catalog/context-activity-stack-view.tsx
- A src/components/context-catalog/context-catalog-live.test.tsx
- A src/components/context-catalog/context-catalog-live.ts
- M src/components/context-catalog/context-catalog.ts
- A src/components/context-stream/context-stream-model.ts
- A src/components/context-stream/context-stream-view.tsx
- A src/components/context-stream/context-stream.test.tsx
- A src/components/context-stream/context-stream.ts
- A src/components/context-stream/windowed-pager.ts
- M src/components/context-view/context-view.tsx
- M src/components/context-view/event-row-format.ts
- M src/components/context-view/event-row.tsx
- M src/components/context-view/feed-rows.tsx
- M src/components/dash/dash.tsx
- M src/components/virtual-log/older-pages.ts
- M src/components/virtual-log/use-reader.ts
- M src/components/virtual-log/virtual-log.tsx
- M src/lib/principal-label.ts
- A src/test-support/fake-catalog.ts
M AGENTS.md
@@ -99,6 +99,15 @@ `/<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/context-catalog` reads the mind's catalog of its contexts. The mind pushes it: + `catalog-collection.ts` is the catalog as TanStack DB collections over `itx.contexts.watch`, on + the page's one socket (an on-demand collection whose live queries become catalog queries, and + one collection for one named query, such as the awake list), and `context-catalog-live.ts` is + the hook that the Dash reads its rows with (`useWatchedContextCatalog`) and the one set of + collections for an `itx` (`catalogOf`). A page writes its own live query of + `catalogOf(itx).contexts` with TanStack DB from the `db` entry (`@iterate-com/ui/db`), never + from an import-map line of its own: the collections and the query must be of one copy. A mind + whose platform has no `contexts.watch` is asked for `contexts.list` every ten seconds, as before. - `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
M browser-entries.ts
@@ -58,6 +58,8 @@ // 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", + // TanStack DB for a page, from this package (src/browser/db.ts) + db: "src/browser/db.ts", react: "src/browser/react.ts", "react/jsx-runtime": "src/browser/react-jsx-runtime.ts", "react/compiler-runtime": "src/browser/react-compiler-runtime.ts", @@ -138,6 +140,9 @@ // 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)[\\/]/ }, + // TanStack DB, which a page takes from the `db` entry: a page's live query and this package's + // collections (the mind's catalog) are of one copy + { name: "vendor-db", test: /node_modules[\\/]@tanstack[\\/](db|db-ivm|react-db)[\\/]/ }, { 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[\\/]/ },
M package.json
@@ -24,6 +24,8 @@ "./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-stream/context-stream": "./src/components/context-stream/context-stream.ts", + "./components/context-stream/*": "./src/components/context-stream/*.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", @@ -52,6 +54,7 @@ "./live": "./dist/live.mjs", "./icons": "./dist/icons.mjs", "./query": "./dist/query.mjs", + "./db": "./dist/db.mjs", "./react": "./dist/react.mjs", "./react/jsx-runtime": "./dist/react/jsx-runtime.mjs", "./react/compiler-runtime": "./dist/react/compiler-runtime.mjs", @@ -92,6 +95,7 @@ "./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-stream/context-stream": "./dist/components/context-stream/context-stream.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", @@ -174,6 +178,7 @@ "./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-db": "./dist/chunks/vendor-db.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", @@ -249,6 +254,8 @@ "@pierre/trees": "catalog:", "@tailwindcss/cli": "catalog:", "@tanstack/charts": "0.18.0", + "@tanstack/db": "1.0.0-rc.1.5", + "@tanstack/react-db": "1.0.0-rc.1.5", "@tanstack/react-query": "^5.107.1", "@tanstack/react-router": "catalog:", "@tanstack/react-virtual": "^3.14.26",
M registry.json
@@ -753,8 +753,10 @@ { "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.", + "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, the catalog as TanStack DB collections that the mind pushes (on demand, with live joins), and the hooks that read it.", "dependencies": [ + "@tanstack/db", + "@tanstack/react-db", "@tanstack/react-virtual", "cmdk", "cn", @@ -771,6 +773,7 @@ "iterate/packages/agents-nav", "iterate/packages/context-path-text", "iterate/packages/context-view", + "iterate/packages/itx-session", "iterate/packages/list-row-text", "iterate/packages/px-per-rem", "popover", @@ -795,6 +798,14 @@ "type": "registry:component" }, { + "path": "src/components/context-catalog/catalog-collection.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-catalog/context-catalog-live.ts", + "type": "registry:component" + }, + { "path": "src/components/context-catalog/context-activity-stack.ts", "type": "registry:component" }, @@ -824,6 +835,49 @@ }, { "path": "src/components/context-catalog/context-palette-rows.ts", + "type": "registry:component" + } + ] + }, + { + "name": "context-stream", + "type": "registry:component", + "description": "Base Slack-proportioned stream view and two-window sparse event pager for any context: actors post stacked messages, react, and open nested subcontext thread bars in a virtualized log.", + "dependencies": [ + "cn", + "lucide-react", + "streamdown" + ], + "registryDependencies": [ + "iterate/packages/call", + "iterate/packages/virtual-log", + "popover" + ], + "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/context-stream/context-stream.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-stream/context-stream-model.ts", + "type": "registry:component" + }, + { + "path": "src/components/context-stream/context-stream-view.tsx", + "type": "registry:component" + }, + { + "path": "src/components/context-stream/windowed-pager.ts", "type": "registry:component" } ]
M src/browser/chunks.test.ts
@@ -46,13 +46,15 @@ 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", () => { +test("the icons, react-query and TanStack DB 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", + db: "src/browser/db.ts", }); expect(publishExports(browserEntries(), [])).toMatchObject({ "./icons": "./dist/icons.mjs", "./query": "./dist/query.mjs", + "./db": "./dist/db.mjs", }); });
A src/browser/db.ts
@@ -0,0 +1,13 @@ +// TANSTACK DB FOR A NO-BUILD PAGE, from this package: +// +// import { eq, useLiveQuery } from "@iterate-com/ui/db"; +// import { catalogOf } from "@iterate-com/ui/components/context-catalog/context-catalog"; +// +// const { data } = useLiveQuery({ query: (q) => +// q.from({ c: catalogOf(itx).contexts }).where(({ c }) => eq(c.metadata.status, "open")) }); +// +// A page does not name `@tanstack/react-db` in its import map, for the reason that +// ./query.ts says. It is also one copy: the build keeps TanStack DB in one file +// (browser-entries.ts `vendor-db`), so a page's live query reads the collections that this +// package's components made (the mind's catalog, components/context-catalog). +export * from "@tanstack/react-db";
M src/components/agent-chat/agent-feed.tsx
@@ -498,6 +498,7 @@ inspect: Inspect; }) { const [toggled, setToggled] = useState<boolean | null>(null); + const running = round.code?.status === "running" || round.llm?.status === "running"; const expanded = toggled ?? round.code?.status === "running"; const failed = round.code?.success === false || round.llm?.outcome === "failed"; return ( @@ -520,7 +521,12 @@ > Round {index + 1} </span> - <span className="min-w-0 truncate font-mono text-xs text-muted-foreground/70"> + <span + className={cn( + "min-w-0 truncate font-mono text-xs text-muted-foreground/70", + running && !failed && "shimmer text-foreground/85", + )} + > {roundHeaderMeta(round)} </span> <ChevronRightIcon @@ -898,7 +904,7 @@ role="status" > {working ? <Spinner className="size-3 shrink-0" /> : null} - <span className="truncate">{text}</span> + <span className={cn("truncate", working && "shimmer")}>{text}</span> </div> ); } @@ -1036,11 +1042,20 @@ )} <span className={cn( - "text-sm font-medium tabular-nums text-primary", + "min-w-0 truncate text-sm font-medium text-primary", + !phaseClock.deadlineExceeded && "shimmer", phaseClock.deadlineExceeded && "text-destructive", )} > - {phaseLabel} {phaseClock.elapsedLabel} + {phaseLabel} + </span>{" "} + <span + className={cn( + "shrink-0 text-sm font-medium tabular-nums text-primary/80", + phaseClock.deadlineExceeded && "text-destructive", + )} + > + {phaseClock.elapsedLabel} </span> {onInspect ? ( <ChevronRightIcon
M src/components/agent-chat/composer.tsx
@@ -67,6 +67,8 @@ isInterrupting = false, onInterrupt, attach = true, + topLip, + below, }: { mode: AgentComposerMode; onModeChange: (mode: AgentComposerMode) => void; @@ -80,6 +82,10 @@ onInterrupt?: () => Promise<void> | void; /** `false`: words only: no `+` (no files, no raw mode), and a paste or drop adds no file. */ attach?: boolean; + /** Optional unified status / activity-stack lip attached directly to the top of the composer card. */ + topLip?: ReactNode; + /** Quiet bar rendered below the composer pill (context utilization, model settings, sticky notices). */ + below?: ReactNode; }) { // the raw editor while it is the open mode; otherwise the message editor is const openRaw = mode === "raw" ? raw : undefined; @@ -110,53 +116,83 @@ <div className="w-full"> <ComposerError error={error} /> <div - {...dropHandlers} - data-drop-active={isDragging ? "true" : undefined} className={cn( - "flex items-end gap-1 rounded-3xl border bg-background p-1 shadow-sm transition-shadow sm:py-2 sm:pr-2 sm:pl-1.5", - isDragging && "ring-2 ring-primary/40 border-primary/40", + "group/composer-card rounded-3xl transition-shadow has-[[data-composer-lip]]:border has-[[data-composer-lip]]:border-border has-[[data-composer-lip]]:bg-muted/45 has-[[data-composer-lip]]:shadow-sm", + isDragging && + "has-[[data-composer-lip]]:border-primary/40 has-[[data-composer-lip]]:ring-2 has-[[data-composer-lip]]:ring-primary/40", )} > - {attach ? ( - <ComposerModeMenu - mode={mode} - onModeChange={onModeChange} - hasRaw={Boolean(raw)} + <ComposerSlot className="px-3.5 py-1">{topLip}</ComposerSlot> + <div + {...dropHandlers} + data-drop-active={isDragging ? "true" : undefined} + className={cn( + "flex items-end gap-1 rounded-3xl border bg-background p-1 shadow-sm transition-shadow sm:py-2 sm:pr-2 sm:pl-1.5 group-has-[[data-composer-lip]]/composer-card:border-x-0 group-has-[[data-composer-lip]]/composer-card:border-b-0 group-has-[[data-composer-lip]]/composer-card:shadow-none", + isDragging && + "border-primary/40 ring-2 ring-primary/40 group-has-[[data-composer-lip]]/composer-card:ring-0", + )} + > + {attach ? ( + <ComposerModeMenu + mode={mode} + onModeChange={onModeChange} + hasRaw={Boolean(raw)} + isSubmitting={isSubmitting} + onAttach={message.onAttach} + /> + ) : null} + {openRaw ? ( + <CodeEditor + value={openRaw.value} + onValueChange={openRaw.onValueChange} + onSubmit={submit} + focusOnMount + placeholder={"type: events.iterate.com/note/added\npayload:\n text: hello"} + className="min-w-0 flex-1 px-2 py-1.5" + /> + ) : ( + <ComposerMessageEditor + message={message} + onSubmit={submit} + focusOnMount={autoFocusMessage} + takesFiles={takesFiles} + /> + )} + <ComposerRoundButton + stops={stops} + sendTitle={mode === "raw" ? "Append events (⌘↵)" : "Send message"} + canSubmit={canSubmit} isSubmitting={isSubmitting} - onAttach={message.onAttach} - /> - ) : null} - {openRaw ? ( - <CodeEditor - value={openRaw.value} - onValueChange={openRaw.onValueChange} + isInterrupting={isInterrupting} onSubmit={submit} - focusOnMount - placeholder={"type: events.iterate.com/note/added\npayload:\n text: hello"} - className="min-w-0 flex-1 px-2 py-1.5" + onInterrupt={interrupt} /> - ) : ( - <ComposerMessageEditor - message={message} - onSubmit={submit} - focusOnMount={autoFocusMessage} - takesFiles={takesFiles} - /> - )} - <ComposerRoundButton - stops={stops} - sendTitle={mode === "raw" ? "Append events (⌘↵)" : "Send message"} - canSubmit={canSubmit} - isSubmitting={isSubmitting} - isInterrupting={isInterrupting} - onSubmit={submit} - onInterrupt={interrupt} - /> + </div> </div> + <ComposerSlot dataSlot="composer-below" className="px-2 pt-1.5"> + {below} + </ComposerSlot> </div> ); } +function ComposerSlot({ + dataSlot, + className, + children, +}: { + dataSlot?: string; + className: string; + children: ReactNode; +}) { + if (!children) return null; + return ( + <div data-slot={dataSlot} className={cn(className, "empty:hidden")}> + {children} + </div> + ); +} + /** The message mode's editor: the attachments over the words. */ function ComposerMessageEditor({ message, @@ -413,6 +449,8 @@ autoFocusMessage = false, attach = true, onTyping, + topLip, + below, }: { draft: ComposerDraft; /** The empty editor's text, which also names its textbox. */ @@ -429,6 +467,10 @@ /** The person writes (`true`, on each change that leaves words in the box), or has stopped: * the box is empty, or the words were sent. For a page that shows the others who is typing. */ onTyping?: (isTyping: boolean) => void; + /** Optional unified status / activity-stack lip attached directly to the top of the composer card. */ + topLip?: ReactNode; + /** Optional slot rendered directly below the composer pill (context management, sticky notices). */ + below?: ReactNode; }) { const { message, setMessage, attachments } = draft; const [mode, setMode] = useState<AgentComposerMode>("message"); @@ -539,6 +581,8 @@ error={error} isInterrupting={interrupt?.isInterrupting} onInterrupt={interrupt?.run} + topLip={topLip} + below={below} /> </> );
M src/components/agent-chat/presence-line.tsx
@@ -210,8 +210,8 @@ ); } -/** THE MIND'S FACE: its logo in a circle of a face's size, or iterate's mark. Its name is its - * tooltip and what a screen reader says. */ +/** THE MIND'S FACE: its logo in a rounded square of a face's size, or iterate's mark. Its name is + * its tooltip and what a screen reader says. */ function MindFaceMark({ mind, className }: { mind: MindFace; className?: string }) { return ( <Avatar @@ -219,7 +219,10 @@ title={mind.name} aria-label={mind.name} role="img" - className={cn("size-6 overflow-hidden bg-background *:size-full! *:rounded-none!", className)} + className={cn( + "size-6 overflow-hidden rounded-[22.37%] bg-background after:rounded-[22.37%] *:size-full! *:rounded-none!", + className, + )} > {mind.logo ?? <IterateLogo alt="" />} </Avatar>
M src/components/call/call-pip.test.tsx
@@ -70,6 +70,25 @@ expect(page.host.querySelector("#tiles")).not.toBeNull(); }); +test("dresses the floating window from parsed document.styleSheets in memory with zero FOUC", async () => { + const hostStyle = document.head.appendChild(document.createElement("style")); + hostStyle.textContent = ".pip-tile { display: flex; }"; + try { + const floating = document.implementation.createHTMLDocument("pip"); + const window = { document: floating, close: vi.fn(), addEventListener: () => {} }; + using _api = documentPip({ requestWindow: vi.fn(async () => window) }); + using page = await mount({ videos: [CAMERA] } as CallUi); + await act(async () => page.host.querySelector("button")!.click()); + const copiedText = Array.from(floating.head.querySelectorAll("style")) + .map((s) => s.textContent || "") + .join("\n"); + expect(copiedText).toContain(".pip-tile"); + expect(floating.head.querySelector('link[rel="stylesheet"]')).toBeNull(); + } finally { + hostStyle.remove(); + } +}); + /** The button's fixed name, whether it is on, and what a press does (its title's first words). */ function pressed(host: HTMLElement) { const button = host.querySelector("button")!;
M src/components/call/call-pip.tsx
@@ -22,16 +22,30 @@ } const documentPip = () => globalThis.documentPictureInPicture; -/** The page's stylesheets and theme, in the floating window, so the tiles look the same there. */ +/** The page's stylesheets and theme, materialised synchronously from `document.styleSheets` in + * memory so the floating window paints styled on its very first frame without waiting on network + * revalidation (`Cache-Control: no-cache`); falls back to cloning `<link>` for cross-origin sheets. */ function dress(floating: Window) { - const head = floating.document.head; - for (const sheet of document.head.querySelectorAll('link[rel="stylesheet"], style')) - head.append(sheet.cloneNode(true)); - const body = floating.document.createElement("style"); + const doc = floating.document; + const head = doc.head; + const base = doc.createElement("base"); + base.href = document.baseURI; + head.append(base); + for (const sheet of Array.from(document.styleSheets)) { + try { + const cssText = Array.from(sheet.cssRules, (rule) => rule.cssText).join("\n"); + const inline = doc.createElement("style"); + inline.textContent = cssText; + head.append(inline); + } catch { + if (sheet.ownerNode instanceof Element) head.append(sheet.ownerNode.cloneNode(true)); + } + } + const body = doc.createElement("style"); body.textContent = "body{margin:0;padding:0.5rem;background:var(--background)}"; head.append(body); - floating.document.documentElement.className = document.documentElement.className; - floating.document.title = document.title; + doc.documentElement.className = document.documentElement.className; + doc.title = document.title; } /** The call's floating window for `ui` (what `useCall` answers). */
M src/components/call/face.tsx
@@ -14,6 +14,7 @@ export function Face({ who, agent = "iterate", + kind, className, small = false, label, @@ -22,15 +23,22 @@ who: string; name?: string; agent?: string; + kind?: "mind" | "guest"; className?: string; small?: boolean; label?: string; }) { const size = small ? "size-5" : "size-8"; if (who === agent) return <IterateLogo alt={agent} className={cn(size, className)} />; + const isMind = kind === "mind"; return ( <Avatar - className={cn(size, "shrink-0", className)} + className={cn( + size, + "shrink-0", + isMind && "rounded-[22.37%] after:rounded-[22.37%]", + className, + )} title={label} aria-label={label} role={label ? "img" : undefined} @@ -41,7 +49,7 @@ depends on the theme. */} <AvatarFallback style={{ background: colourOf(who), color: inkOf(who) }} - className={cn("font-medium", small ? "text-2xs" : "text-xs")} + className={cn("font-medium", small ? "text-2xs" : "text-xs", isMind && "rounded-[22.37%]")} > {initialsOf(name || who)} </AvatarFallback>
A src/components/context-catalog/catalog-collection.test.ts
@@ -0,0 +1,353 @@ +// The catalog as TanStack DB collections (catalog-collection.ts), against a catalog made here that +// answers as iterate/api says a watch does: a `reset` or a `resume`, then `change` frames, one +// batch for one write. +import { + and, + BasicIndex, + createCollection, + createLiveQueryCollection, + eq, + inArray, + localOnlyCollectionOptions, +} from "@tanstack/db"; +import { expect, test } from "vitest"; +import { + CatalogAwakeRow, + catalogQueryOf, + CatalogRow, + catalogWatcher, + compareTextBinary, + contextsCollectionOptions, + watchedQueryCollectionOptions, + type CatalogItx, +} from "./catalog-collection.ts"; +import { ITX_SESSION, type ItxConnection } from "#/lib/itx-session.ts"; +import { fakeCatalog } from "#/test-support/fake-catalog.ts"; + +test("orders as UTF-8 bytes, where JavaScript's own order differs", () => { + const astral = "\u{1F600}"; + const privateUse = "\u{E000}"; + expect(astral < privateUse).toBe(true); + expect(compareTextBinary(astral, privateUse)).toBe(1); + expect(compareTextBinary("/a", "/a/b")).toBe(-1); + expect(compareTextBinary("/a", "/a")).toBe(0); +}); + +test("facts, the tree and each order become one window", async () => { + const catalog = fakeCatalog(); + const { contexts } = page(catalog); + const open = createLiveQueryCollection((q) => + q + .from({ c: contexts }) + .where(({ c }) => + and( + eq(c.metadata?.status, "open"), + inArray("pinned", c.metadata?.tags), + inArray("agent", c.processors), + inArray("/agents", c.under), + ), + ) + .orderBy(({ c }) => c.createdMs, "desc") + .limit(20), + ); + await open.preload(); + expect(catalog.calls[0]?.query).toEqual({ + where: { $processor: "agent", status: "open", tags: "pinned" }, + under: "/agents", + order: "created", + limit: 20, + }); + + const children = createLiveQueryCollection((q) => + q + .from({ c: contexts }) + .where(({ c }) => eq(c.parent, "/agents")) + .orderBy(({ c }) => c.path, "asc") + .limit(5), + ); + await children.preload(); + expect(catalog.calls[1]?.query).toEqual({ childrenOf: "/agents", order: "path", limit: 5 }); +}); + +test("a limit over a condition that the catalog has no index for is refused with the reason", () => { + const refused = createLiveQueryCollection((q) => + q + .from({ + c: createCollection(contextsCollectionOptions({ watcher: page(fakeCatalog()).watcher })), + }) + .where(({ c }) => eq(c.description, "x")) + .orderBy(({ c }) => c.activeMs, "desc") + .limit(5), + ); + return expect(refused.preload()).rejects.toThrow(/no index for a condition/); +}); + +test("an order that the catalog does not keep is refused", () => { + expect(() => + catalogQueryOf({ + limit: 5, + orderBy: [ + { + expression: { type: "ref", path: ["activeMs"] } as never, + compareOptions: { direction: "asc", nulls: "last" }, + }, + ], + }), + ).toThrow(/three orders/); +}); + +test("a window holds the newest rows, and a write moves it", async () => { + const catalog = fakeCatalog(); + catalog.put("/a", 10); + catalog.put("/b", 20); + catalog.put("/c", 30); + const { contexts } = page(catalog); + const recent = createLiveQueryCollection((q) => + q + .from({ c: contexts }) + .orderBy(({ c }) => c.activeMs, "desc") + .limit(2), + ); + await recent.preload(); + expect(recent.toArray.map((row) => row.path)).toEqual(["/c", "/b"]); + expect(catalog.calls.map((call) => call.query)).toEqual([{ order: "active", limit: 2 }]); + + catalog.put("/a", 40); + await tick(); + expect(recent.toArray.map((row) => row.path)).toEqual(["/a", "/c"]); + // the row that left the window left the collection: nothing would keep it true + expect(contexts.has("/b")).toBe(false); + expect(contexts.get("/a")).toMatchObject({ parent: "/", under: ["/", "/a"] }); + + catalog.remove("/a"); + await tick(); + expect(recent.toArray.map((row) => row.path)).toEqual(["/c", "/b"]); + // one watch for the life of the query + expect(catalog.calls).toHaveLength(1); +}); + +test("every join asks by key, and all keys are one catalog query", async () => { + const catalog = fakeCatalog(); + catalog.put("/tasks/1", 10, { description: "the first" }); + catalog.put("/tasks/2", 20, { description: "the second" }); + catalog.put("/other", 30); + const { contexts } = page(catalog); + const tasks = createCollection( + localOnlyCollectionOptions<{ id: string; context: string }>({ + getKey: (task) => task.id, + initialData: [{ id: "t1", context: "/tasks/1" }], + }), + ); + const joined = createLiveQueryCollection((q) => + q + .from({ t: tasks }) + .join({ c: contexts }, ({ t, c }) => eq(t.context, c.path), "left") + .select(({ t, c }) => ({ id: t.id, description: c?.description })), + ); + await joined.preload(); + expect(joined.toArray).toMatchObject([{ id: "t1", description: "the first" }]); + + tasks.insert({ id: "t2", context: "/tasks/2" }); + await tick(); + await tick(); + expect(joined.toArray.map((row) => row.description).toSorted()).toEqual([ + "the first", + "the second", + ]); + const keyCalls = catalog.calls.filter((call) => call.query.keys); + expect(keyCalls.map((call) => call.query.keys)).toEqual([["/tasks/1"], ["/tasks/1", "/tasks/2"]]); + // one watch of keys at a time: the older one ended + expect([...catalog.watching].filter((watch) => watch.query.keys)).toHaveLength(1); + expect(contexts.has("/other")).toBe(false); + + catalog.put("/tasks/2", 50, { description: "changed" }); + await tick(); + expect(joined.toArray.map((row) => row.description).toSorted()).toEqual(["changed", "the first"]); +}); + +test("one write over two watches lands in one turn: a page that draws after it never draws half", async () => { + const catalog = fakeCatalog(); + catalog.put("/a", 10); + const { watcher, contexts } = page(catalog); + const awake = createCollection( + watchedQueryCollectionOptions({ + watcher, + query: { awake: true }, + row: CatalogAwakeRow, + }), + ); + const recent = createLiveQueryCollection((q) => + q + .from({ c: contexts }) + .orderBy(({ c }) => c.activeMs, "desc") + .limit(10), + ); + const rows = createLiveQueryCollection((q) => + q + .from({ c: recent }) + .join({ a: awake }, ({ c, a }) => eq(c.path, a.path), "left") + .select(({ c, a }) => ({ path: c.path, activeMs: c.activeMs, since: a?.since })), + ); + await rows.preload(); + expect(rows.toArray).toMatchObject([{ path: "/a", activeMs: 10 }]); + const seen: string[] = []; + // as React draws: after the turn in which the store changed + rows.subscribeChanges(() => { + queueMicrotask(() => { + seen.push(rows.toArray.map((row) => `${String(row.activeMs)} ${String(row.since)}`).join()); + }); + }); + + let batches = 0; + watcher.onBatch(() => (batches += 1)); + catalog.putAwake("/a", 99); + await tick(); + expect(batches).toBe(1); + expect(rows.toArray).toMatchObject([{ path: "/a", activeMs: 99, since: 99 }]); + expect(new Set(seen)).toEqual(new Set(["99 99"])); +}); + +test("a new session starts each watch again with its cursor, and gets only what it lacks", async () => { + const catalog = fakeCatalog(); + catalog.put("/a", 10); + catalog.put("/b", 20); + catalog.put("/c", 30); + const watcher = catalogWatcher(catalog.itx); + const changes: { del: string[]; put: string[] }[] = []; + const watch = watcher.watch({ order: "active", limit: 10 }, CatalogRow, ({ del, put }) => + changes.push({ del, put: put.map((row) => row.path) }), + ); + await watch.ready; + expect([...watch.rows.keys()]).toEqual(["/c", "/b", "/a"]); + + // while the page is away: one row goes, one comes + catalog.newSession(); + catalog.remove("/b"); + catalog.put("/d", 40); + await tick(); + expect(catalog.calls[1]?.cursor).toMatchObject({ gen: "g1", rev: 3, bound: [10, "/a"] }); + expect(changes.at(-1)).toEqual({ del: ["/b"], put: ["/d"] }); + expect([...watch.rows.keys()].toSorted()).toEqual(["/a", "/c", "/d"]); + + // a catalog of another generation answers every row + catalog.newSession({ newGeneration: true }); + await tick(); + expect(changes.at(-1)?.put.toSorted()).toEqual(["/a", "/c", "/d"]); + expect(watch).toMatchObject({ answers: 3 }); +}); + +test("a change that comes with a gap starts the watch again", async () => { + const catalog = fakeCatalog(); + catalog.put("/a", 10); + const watcher = catalogWatcher(catalog.itx); + const watch = watcher.watch({ order: "active", limit: 10 }, CatalogRow, () => {}); + await watch.ready; + const [live] = catalog.watching; + // a frame whose `from` is not this watch's revision + live?.onFrame({ type: "change", gen: "g1", from: 7, rev: 8, del: ["/a"], rows: [] }); + await tick(); + expect(catalog.calls).toHaveLength(2); + expect(watch.rows.has("/a")).toBe(true); + expect(watch.error).toBeUndefined(); +}); + +test("a platform without contexts.watch says so once, and the watch ends with the reason", async () => { + const itx: CatalogItx = { + contexts: { watch: () => Promise.reject(new TypeError("watch is not a function")) }, + }; + const watcher = catalogWatcher(itx); + const said: string[] = []; + watcher.subscribe(() => said.push(watcher.support())); + const watch = watcher.watch({ awake: true }, CatalogAwakeRow, () => {}); + await expect(watch.ready).rejects.toThrow("watch is not a function"); + expect(said).toEqual(["none"]); +}); + +test("a watch asked before the page's first socket is open is asked once, and a platform without the watch is heard", async () => { + // a page's session as memberItx says it: no socket yet, then the socket, then the proof + let connection: ItxConnection = { epoch: 0, state: "opening" }; + const listeners = new Set<() => void>(); + const say = (next: ItxConnection) => { + connection = next; + for (const changed of listeners) changed(); + }; + const answer = Promise.withResolvers<Disposable>(); + let calls = 0; + const itx: CatalogItx & { [ITX_SESSION]: unknown } = { + [ITX_SESSION]: { + get: () => connection, + subscribe(changed: () => void) { + listeners.add(changed); + return () => listeners.delete(changed); + }, + watch: () => () => {}, + }, + contexts: { + watch() { + calls += 1; + return answer.promise; + }, + }, + }; + const watcher = catalogWatcher(itx); + const watch = watcher.watch({ awake: true }, CatalogAwakeRow, () => {}); + say({ epoch: 1, state: "opening" }); + say({ epoch: 1, state: "open" }); + answer.reject(new Error("No such method: contexts.watch")); + await expect(watch.ready).rejects.toThrow("No such method"); + expect(calls).toBe(1); + expect(watcher.support()).toBe("none"); +}); + +test("a watch that the catalog ends is watched again, and a catalog that ends it three times is given up", async () => { + const ends: (() => void)[] = []; + let calls = 0; + const itx: CatalogItx = { + contexts: { + watch(_query, onFrame) { + calls += 1; + onFrame({ type: "reset", gen: "g1", rev: 1, q: "awake", full: false, rows: [] }); + const ended = Promise.withResolvers<void>(); + ends.push(ended.resolve); + return Promise.resolve({ [Symbol.dispose]: () => {}, ended: () => ended.promise }); + }, + }, + }; + const watcher = catalogWatcher(itx); + const watch = watcher.watch({ awake: true }, CatalogAwakeRow, () => {}); + await watch.ready; + for (const _ of [1, 2, 3]) { + ends.at(-1)?.(); + await tick(); + } + expect(calls).toBe(3); + expect(watch).toMatchObject({ + error: "the catalog ended the watch three times in half a minute", + }); + expect(watcher.support()).toBe("none"); +}); + +test("a query that the catalog refuses ends its watch alone", async () => { + const catalog = fakeCatalog(); + const watcher = catalogWatcher(catalog.itx); + const awake = watcher.watch({ awake: true }, CatalogAwakeRow, () => {}); + await awake.ready; + const refused = watcher.watch({ where: { refused: true } }, CatalogRow, () => {}); + await expect(refused.ready).rejects.toThrow("the catalog refuses this"); + expect(watcher.support()).toBe("live"); + expect(awake.error).toBeUndefined(); +}); + +const tick = () => new Promise((resolve) => setTimeout(resolve, 0)); + +function page(catalog: ReturnType<typeof fakeCatalog>) { + const watcher = catalogWatcher(catalog.itx); + // with indexes, as the Dash makes it (context-catalog-live.ts) + const contexts = createCollection( + contextsCollectionOptions({ + watcher, + index: { defaultIndexType: BasicIndex, autoIndex: "eager" }, + }), + ); + return { watcher, contexts }; +}
A src/components/context-catalog/catalog-collection.ts
@@ -0,0 +1,943 @@ +// catalog-collection.ts — THE MIND'S CATALOG AS TANSTACK DB COLLECTIONS, over the page's one +// socket. The catalog answers a query for as long as a watcher holds it +// (`itx.contexts.watch(query, onFrame, { cursor })`, iterate/api `CatalogQuery`), and pushes each +// change. Nothing here polls, and nothing here opens a socket. No React here, and no import of +// TanStack DB but its types: each function answers a plain config for `createCollection`. +// +// const watcher = catalogWatcher(itx); +// const contexts = createCollection(contextsCollectionOptions({ watcher })); +// const awake = createCollection(watchedQueryCollectionOptions({ +// watcher, query: { awake: true }, row: CatalogAwakeRow })); +// const recent = createLiveQueryCollection((q) => +// q.from({ c: contexts }).orderBy(({ c }) => c.activeMs, "desc").limit(500)); +// const rows = createLiveQueryCollection((q) => +// q.from({ c: recent }).leftJoin({ a: awake }, ({ c, a }) => eq(c.path, a.path))); +// +// `contextsCollectionOptions` is THE WHOLE CATALOG AS ONE ON-DEMAND COLLECTION. A page writes an +// ordinary live query, TanStack DB hands its filter, order and limit to this file (`loadSubset`), +// and this file turns them into ONE catalog query and watches it. So the page's own query is the +// registration: the catalog learns it at run time. +// +// What a live query may say, and what it becomes: +// eq(c.metadata.<fact>, value) → where: { <fact>: value } +// inArray(value, c.metadata.<fact>) → where: { <fact>: value } (a fact that is a list) +// inArray(name, c.processors) → where: { $processor: name } +// eq(c.parent, path) → childrenOf: path +// inArray(path, c.under) → under: path (a path and all below it) +// eq(c.path, path), inArray(c.path, [..]) → keys: [..] (what a JOIN asks for) +// and(...) of the above, limit(n), and one order: +// orderBy(c.activeMs, "desc") | orderBy(c.createdMs, "desc") | orderBy(c.path, "asc") +// Anything else with a limit is REFUSED with the reason: the catalog would have to guess, and a +// guessed window gives wrong rows. With no limit, the facts go to the catalog and TanStack DB +// filters the rest in the page. +// +// A MIND WHOSE PLATFORM HAS NO `contexts.watch` refuses the first watch: `watcher.support()` then +// says "none", and the page reads the catalog as before (`useContextCatalog` polls +// `contexts.list`). +import type { CollectionConfig, LoadSubsetOptions, SyncConfig, UtilsRecord } from "@tanstack/db"; +import { z } from "zod"; +import { ContextActivity } from "./context-activity-stack.ts"; +import { ContextListing } from "./context-catalog-rows.ts"; +import { itxSessionOf } from "#/lib/itx-session.ts"; + +// ── what the catalog says (iterate/api) ── + +/** The orders of a watched window. Each is total: the path breaks a tie. `active` and `created` + * are the newest first, with the path descending; `path` is A to Z. */ +export type CatalogOrder = "active" | "created" | "path"; + +/** A query of the catalog that is watched (iterate/api `CatalogQuery`): a window, exactly these + * `keys`, or the contexts that are `awake` now. */ +export type CatalogQuery = { + where?: Record<string, string | number | boolean>; + under?: string; + childrenOf?: string; + order?: CatalogOrder; + limit?: number; + keys?: string[]; + awake?: true; +}; + +/** What a watcher holds of a query, for a watch that starts again (iterate/api `CatalogCursor`). */ +export type CatalogCursor = { + gen: string; + rev: number; + q: string; + bound?: [at: number, path: string] | null; + have?: string[]; +}; + +/** One context as a watch sends it (iterate/api `CatalogRow`): a listing without `awake` and + * `activities`, with the two numbers that the orders sort by and the catalog's revision at which + * the row last changed. `activeMs` is when it was last active (`lastActivityAt || lastEventAt`) + * and `createdMs` when its first event was written, in milliseconds. A row changes at each + * summary that its context sends: at most one in 15 s while it works. */ +export const CatalogRow = ContextListing.omit({ awake: true, activities: true }).extend({ + activeMs: z.number(), + createdMs: z.number(), + rev: z.number(), +}); +export type CatalogRow = z.infer<typeof CatalogRow>; + +/** One row of the awake list (`{ awake: true }`): it has no revision. */ +export const CatalogAwakeRow = z.looseObject({ + path: z.string(), + since: z.number(), + activities: z.array(ContextActivity).optional(), +}); +export type CatalogAwakeRow = z.infer<typeof CatalogAwakeRow>; + +/** A frame without its rows, which each watch parses as its own kind of row. */ +const Frame = z.intersection( + z.object({ gen: z.string(), rev: z.number(), more: z.literal(true).optional() }), + z.discriminatedUnion("type", [ + z.object({ + type: z.literal("reset"), + q: z.string(), + full: z.boolean(), + rows: z.array(z.unknown()), + }), + z.object({ + type: z.literal("resume"), + q: z.string(), + full: z.boolean(), + ids: z.array(z.string()), + rows: z.array(z.unknown()), + }), + z.object({ + type: z.literal("change"), + from: z.number(), + del: z.array(z.string()), + rows: z.array(z.unknown()), + }), + ]), +); + +/** What this file calls of a member's `itx`. */ +export type CatalogItx = { + contexts: { + watch( + query: CatalogQuery, + onFrame: (frame: unknown) => void, + options?: { cursor?: CatalogCursor }, + ): PromiseLike<CatalogWatchHandle>; + }; +}; + +/** What `contexts.watch` answers: disposing it ends the watch. `ended()` settles when the watch + * ends WITHOUT that (its session ended, or the catalog could not be reached again). */ +export type CatalogWatchHandle = Disposable & { ended?(): PromiseLike<unknown> }; + +// ── the order ── + +/** As the catalog orders paths: by UTF-8 bytes, which is SQLite's BINARY collation. JavaScript's + * own `<` differs for one case: an astral character against U+E000 to U+FFFF. */ +export function compareTextBinary(a: string, b: string): number { + if (a === b) return 0; + const shared = Math.min(a.length, b.length); + for (let i = 0; i < shared; i++) { + const x = a.charCodeAt(i); + const y = b.charCodeAt(i); + if (x === y) continue; + const xSurrogate = x >= 0xd800 && x <= 0xdfff; + const ySurrogate = y >= 0xd800 && y <= 0xdfff; + if (xSurrogate === ySurrogate) return x < y ? -1 : 1; + return xSurrogate ? 1 : -1; + } + return a.length < b.length ? -1 : 1; +} + +type Sortable = { path: string; activeMs?: number; createdMs?: number }; + +/** A row's sort key in `order`, as a cursor's `bound` says it. */ +function sortKeyOf(row: Sortable, order: CatalogOrder): [at: number, path: string] { + if (order === "path") return [0, row.path]; + return [(order === "created" ? row.createdMs : row.activeMs) ?? 0, row.path]; +} + +/** The catalog's order of two rows of a window. */ +export function compareCatalogRows(a: Sortable, b: Sortable, order: CatalogOrder = "active") { + if (order === "path") return compareTextBinary(a.path, b.path); + const [x] = sortKeyOf(a, order); + const [y] = sortKeyOf(b, order); + return x !== y ? y - x : -compareTextBinary(a.path, b.path); +} + +// ── the watcher: every query of this page, over the page's one socket ── + +/** What a watch tells its holder after each frame is in `rows`: the paths that left and the rows + * that came or changed. `answer` marks the answer to a watch that started. `error` is a refusal: + * the watch has ended. */ +export type CatalogChange<Row> = { del: string[]; put: Row[]; answer?: true; error?: string }; + +/** One query that the catalog keeps answering. `rows` is its answer now. */ +export type CatalogWatch<Row> = { + readonly query: CatalogQuery; + readonly rows: ReadonlyMap<string, Row>; + /** True when a window is at its limit: more rows may match than it holds. */ + readonly full: boolean; + /** How many answers have come: 0 until the first. */ + readonly answers: number; + /** How many change frames have been applied. */ + readonly frames: number; + readonly error: string | undefined; + /** Resolves with the first answer, and rejects with a refusal's reason. */ + readonly ready: Promise<void>; + stop(): void; +}; + +/** Whether the mind's catalog answers a watch: "asking" until the first frame or the first + * refusal, then "live". "none" for a platform without `contexts.watch`, and from then on for a + * catalog that stopped being a source (it refused a watch for a reason that is not the query's, + * or a watch lost its place three times in half a minute): the page then reads the list. */ +export type CatalogSupport = "asking" | "live" | "none"; + +export type CatalogWatcher = { + /** Asks the catalog to answer `query` from now on. `row` parses each row. `like` is another + * watch of the same kind whose rows are here: the new watch starts from them and from its + * cursor, so the catalog sends only the rows that the other does not hold. */ + watch<Row extends { path: string }>( + query: CatalogQuery, + row: z.ZodType<Row>, + onChange: (change: CatalogChange<Row>) => void, + like?: CatalogWatch<Row>, + ): CatalogWatch<Row>; + /** `end()` runs after the last frame of each batch. One write of the catalog is one batch over + * all of this page's queries, so a holder applies it as one transaction. */ + onBatch(end: () => void): () => void; + support(): CatalogSupport; + /** For `useSyncExternalStore`: `changed` runs when `support()` answers another word. */ + subscribe(changed: () => void): () => void; + /** Ends every watch and leaves the session. */ + close(): void; +}; + +/** A watch that lost its place (a change frame is missing, or the catalog ended it) starts again. + * Two such starts within half a minute are allowed. A third means that the catalog is no source + * now: the watcher then says "none", and the page reads the list. */ +const RESTARTS_ALLOWED = 2; + +/** A refusal's code, which the platform sends as the error's own property. */ +const Coded = z.object({ code: z.string() }); + +const kindOf = (query: CatalogQuery) => (query.keys ? "keys" : query.awake ? "awake" : "window"); + +type Held<Row> = { + query: CatalogQuery; + row: z.ZodType<Row>; + onChange: (change: CatalogChange<Row>) => void; + rows: Map<string, Row>; + gen: string | undefined; + rev: number; + q: string | undefined; + full: boolean; + answers: number; + frames: number; + /** How many times it started again of late, and when the first of those was. */ + restarts: number; + restartedAt: number; + error: string | undefined; + /** The start that this watch listens to: a frame of an earlier start is of no watch. */ + start: object | undefined; + handle: PromiseLike<CatalogWatchHandle> | undefined; + ready: Promise<void>; + resolveReady(): void; + rejectReady(error: Error): void; + stop(): void; +}; + +/** THE CATALOG'S WATCHES OF ONE PAGE. A watch is of one session and ends with it: when a new + * session opens, each watch starts again with its cursor, and the catalog sends every path of + * the answer and only the rows that this page lacks. */ +export function catalogWatcher(itx: CatalogItx): CatalogWatcher { + const session = itxSessionOf(itx); + const watches = new Set<Held<{ path: string }>>(); + const batchEnds = new Set<() => void>(); + const supportListeners = new Set<() => void>(); + let support: CatalogSupport = "asking"; + /** The session that a call made now goes with. A call made before the first socket is open + * (epoch 0) waits for that socket, so it is of the first session. */ + const sessionNow = () => Math.max(session.get().epoch, 1); + let epoch = 1; + + const say = (next: CatalogSupport) => { + if (support === next) return; + support = next; + for (const changed of supportListeners) changed(); + }; + + function cursorOf(held: Held<{ path: string }>): CatalogCursor | undefined { + if (!held.gen || !held.q) return undefined; + const kind = kindOf(held.query); + if (kind === "awake") return undefined; + const base = { gen: held.gen, rev: held.rev, q: held.q }; + if (kind === "keys") return { ...base, have: [...held.rows.keys()] }; + const order = held.query.order || "active"; + const last = [...held.rows.values()].toSorted((a, b) => compareCatalogRows(a, b, order)).at(-1); + return { ...base, bound: last ? sortKeyOf(last, order) : null }; + } + + function refuse(held: Held<{ path: string }>, error: string) { + held.error = error; + release(held); + held.rejectReady(new Error(error)); + held.onChange({ del: [], put: [], error }); + } + + /** Ends the catalog's side of a watch: the handle, when the call has answered. */ + function release(held: Held<{ path: string }>) { + const handle = held.handle; + held.start = undefined; + held.handle = undefined; + // a call that failed left nothing to end + void Promise.resolve(handle).then( + (answered) => answered?.[Symbol.dispose](), + () => {}, + ); + } + + function start(held: Held<{ path: string }>) { + release(held); + const started = {}; + held.start = started; + const asked = sessionNow(); + const cursor = cursorOf(held); + let handle: PromiseLike<CatalogWatchHandle>; + try { + handle = itx.contexts.watch( + held.query, + (frame) => { + receive(held, started, frame); + }, + cursor ? { cursor } : undefined, + ); + } catch (caught) { + handle = Promise.reject(caught); + } + held.handle = handle; + void Promise.resolve(handle).then(undefined, (caught: unknown) => { + if (held.start !== started) return; + // the session went away under the call: its next epoch starts the watch again + if (sessionNow() !== asked || session.get().state !== "open") return; + // INVALID_INPUT is the refusal of this query. Any other refusal is of the watch itself: a + // platform that has no `contexts.watch`, or a catalog that does not answer. + if (Coded.safeParse(caught).data?.code !== "INVALID_INPUT") say("none"); + refuse(held, caught instanceof Error ? caught.message : String(caught)); + }); + // The catalog ended the watch and this page did not: watch again. A session that went away + // rejects here, and its next epoch starts the watch. + void Promise.resolve(handle) + // a platform whose handle has no `ended` never says that a watch ended + .then((answered) => (answered.ended ? answered.ended() : new Promise<never>(() => {}))) + .then( + () => { + if (held.start === started && session.get().state === "open") + startAgain(held, "the catalog ended the watch three times in half a minute"); + }, + () => {}, + ); + } + + /** Starts a watch that lost its place, or gives the catalog up with `reason`. */ + function startAgain(held: Held<{ path: string }>, reason: string) { + const now = Date.now(); + if (now - held.restartedAt > 30_000) { + held.restarts = 0; + held.restartedAt = now; + } + if (held.restarts >= RESTARTS_ALLOWED) { + say("none"); + refuse(held, reason); + return; + } + held.restarts += 1; + start(held); + } + + function receive(held: Held<{ path: string }>, started: object, raw: unknown) { + const parsed = Frame.safeParse(raw); + const current = held.start === started; + if (current) { + if (parsed.success) apply(held, parsed.data); + else { + say("none"); + refuse(held, "the catalog sent a frame that this page cannot read"); + } + } + // The batch ends with its last frame, whoever that frame was for. + if (!parsed.success || !parsed.data.more) for (const end of batchEnds) end(); + } + + function apply(held: Held<{ path: string }>, frame: z.infer<typeof Frame>) { + if (support === "asking") say("live"); + const rows = frame.rows.flatMap((value) => { + const row = held.row.safeParse(value); + return row.success ? [row.data] : []; + }); + if (frame.type === "change") { + // before its answer a watch has no revision that a change could follow + if (held.gen !== frame.gen || held.rev !== frame.from) { + startAgain(held, "the catalog's changes came with a gap three times in half a minute"); + return; + } + for (const path of frame.del) held.rows.delete(path); + for (const row of rows) held.rows.set(row.path, row); + held.rev = frame.rev; + held.frames += 1; + held.onChange({ del: frame.del, put: rows }); + return; + } + // The answer to a start: every row (`reset`), or every path with only the rows that this + // page lacks (`resume`). + const keep = new Set(frame.type === "reset" ? rows.map((row) => row.path) : frame.ids); + const del = [...held.rows.keys()].filter((path) => !keep.has(path)); + for (const path of del) held.rows.delete(path); + for (const row of rows) held.rows.set(row.path, row); + held.gen = frame.gen; + held.rev = frame.rev; + held.q = frame.q; + held.full = frame.full; + held.error = undefined; + held.answers += 1; + held.onChange({ del, put: rows, answer: true }); + held.resolveReady(); + } + + // A new session: every watch of the last one ended with it. The watcher is in the session's + // list only while it holds a watch, since a page with a subscriber is one that lives on over + // a new session (#/lib/itx-session.ts). + let leave: (() => void) | undefined; + const follow = () => { + epoch = sessionNow(); + leave ||= session.subscribe(() => { + const now = sessionNow(); + if (now === epoch) return; + epoch = now; + for (const held of watches) if (!held.error) start(held); + }); + }; + const unfollow = () => { + if (watches.size > 0) return; + leave?.(); + leave = undefined; + }; + + return { + watch<Row extends { path: string }>( + query: CatalogQuery, + row: z.ZodType<Row>, + onChange: (change: CatalogChange<Row>) => void, + like?: CatalogWatch<Row>, + ): CatalogWatch<Row> { + const settle = Promise.withResolvers<void>(); + // a watch that nobody waits for must not end as an unhandled rejection + settle.promise.catch(() => {}); + const held: Held<Row> = { + query, + row, + onChange, + rows: new Map(), + gen: undefined, + rev: -1, + q: undefined, + full: false, + answers: 0, + frames: 0, + restarts: 0, + restartedAt: 0, + error: undefined, + start: undefined, + handle: undefined, + ready: settle.promise, + resolveReady: settle.resolve, + rejectReady: settle.reject, + stop() { + if (!watches.delete(erased)) return; + release(erased); + unfollow(); + }, + }; + // The set holds watches of every kind of row. A watch reads and writes its rows through + // its own `row` parser and its own `onChange`, so the set's one type forgets nothing that + // is used. + const erased = held as unknown as Held<{ path: string }>; + const from = like as (CatalogWatch<Row> & Partial<Held<Row>>) | undefined; + if (from?.gen && kindOf(from.query) === kindOf(query)) { + held.rows = new Map(from.rows); + held.gen = from.gen; + held.rev = from.rev ?? -1; + held.q = from.q; + } + watches.add(erased); + follow(); + start(erased); + return held; + }, + onBatch(end) { + batchEnds.add(end); + return () => batchEnds.delete(end); + }, + support: () => support, + subscribe(changed) { + supportListeners.add(changed); + return () => supportListeners.delete(changed); + }, + close() { + for (const held of watches) release(held); + watches.clear(); + unfollow(); + }, + }; +} + +// ── a live query's request as a catalog query ── + +/** A catalog row as a page's queries see it: with `parent` and `under` (the path and each of its + * ancestors), so that the tree is two ordinary fields. */ +export type ContextRow = CatalogRow & { parent: string; under: string[] }; + +export function contextRow(row: CatalogRow): ContextRow { + const under = ["/"]; + let prefix = ""; + for (const part of row.path.split("/").filter(Boolean)) under.push((prefix += `/${part}`)); + const cut = row.path.lastIndexOf("/"); + const parent = row.path === "/" ? "" : cut <= 0 ? "/" : row.path.slice(0, cut); + return { ...row, parent, under }; +} + +type Expression = NonNullable<LoadSubsetOptions["where"]>; +type Scalar = string | number | boolean; + +const isRef = (node: Expression | undefined, ...path: string[]) => + node?.type === "ref" && + node.path.length === path.length && + node.path.every((part, index) => part === path[index]); +const isScalar = (value: unknown): value is Scalar => + typeof value === "string" || typeof value === "number" || typeof value === "boolean"; +/** The field that a reference names, when it is a fact: `metadata.<fact>`. */ +const factOf = (node: Expression) => + node.type === "ref" && node.path.length === 2 && node.path[0] === "metadata" + ? node.path[1] + : undefined; + +const ORDER_FIELDS = { activeMs: "active", createdMs: "created", path: "path" } as const; + +type Part = + | { keys: string[] } + | { tie: true } + | { fact: [name: string, value: Scalar] } + | { under: string } + | { childrenOf: string }; + +/** What one condition asks of the catalog, or undefined when the catalog has no index for it. */ +function partOf(node: Expression): Part | undefined { + if (node.type !== "func") return undefined; + const [a, b] = node.args; + if (!a || !b) return undefined; + if (node.name === "eq") { + const [ref, other] = a.type === "ref" ? [a, b] : [b, a]; + if (ref.type !== "ref" || other.type !== "val") return undefined; + const value: unknown = other.value; + if (!isScalar(value)) return undefined; + if (isRef(ref, "path")) return typeof value === "string" ? { keys: [value] } : undefined; + // the rows that tie with a window's last row: the catalog's order is total, so it sent them + if (isRef(ref, "activeMs") || isRef(ref, "createdMs")) return { tie: true }; + if (isRef(ref, "parent")) return typeof value === "string" ? { childrenOf: value } : undefined; + const fact = factOf(ref); + return fact ? { fact: [fact, value] } : undefined; + } + if (node.name !== "in") return undefined; + if (isRef(a, "path") && b.type === "val") { + const keys = z.array(z.string()).safeParse(b.value); + return keys.success ? { keys: keys.data } : undefined; + } + if (a.type !== "val" || b.type !== "ref") return undefined; + const value: unknown = a.value; + if (!isScalar(value)) return undefined; + if (isRef(b, "under")) return typeof value === "string" ? { under: value } : undefined; + if (isRef(b, "processors")) return { fact: ["$processor", value] }; + const fact = factOf(b); + return fact ? { fact: [fact, value] } : undefined; +} + +const conjunctsOf = (node: Expression | undefined): Expression[] => + !node + ? [] + : node.type === "func" && node.name === "and" + ? node.args.flatMap(conjunctsOf) + : [node]; + +/** The catalog's order that a live query's `orderBy` says, or undefined when it says none of + * the three. The path may follow as the tie-break, in the leading field's direction. */ +function orderOf(orderBy: LoadSubsetOptions["orderBy"]): CatalogOrder | undefined { + const [first, second, ...more] = orderBy || []; + if (!first || more.length > 0 || first.expression.type !== "ref") return undefined; + const [field, ...deeper] = first.expression.path; + if (deeper.length > 0 || !field || !Object.hasOwn(ORDER_FIELDS, field)) return undefined; + const order = ORDER_FIELDS[field as keyof typeof ORDER_FIELDS]; + const direction = order === "path" ? "asc" : "desc"; + if (first.compareOptions.direction !== direction) return undefined; + if (second && (order === "path" || !isRef(second.expression, "path"))) return undefined; + if (second && second.compareOptions.direction !== direction) return undefined; + return order; +} + +/** The largest window that the catalog serves. */ +export const CATALOG_WINDOW_LIMIT = 500; + +/** A live query's request as a catalog query: `{ query }`, or `{ keys }` for rows by key, or + * `{ nothing: true }` when the catalog has already sent the rows. `after` marks a request for + * the rows after a row that is here. Throws, with the reason, for a request that the catalog + * cannot answer exactly. */ +export function catalogQueryOf( + options: LoadSubsetOptions, +): + | { nothing: true } + | { keys: string[] } + | { query: CatalogQuery; unlimited: boolean; after?: true } { + const facts: [string, Scalar][] = []; + const place: { under?: string; childrenOf?: string } = {}; + let keys: string[] | undefined; + let unindexed = 0; + for (const node of conjunctsOf(options.where)) { + const part = partOf(node); + if (!part) unindexed += 1; + else if ("tie" in part) return { nothing: true }; + else if ("keys" in part) { + const asked = new Set(part.keys); + keys = keys ? keys.filter((key) => asked.has(key)) : part.keys; + } else if ("fact" in part) facts.push(part.fact); + else if ("under" in part && !place.under) place.under = part.under; + else if ("childrenOf" in part && !place.childrenOf) place.childrenOf = part.childrenOf; + // a second `under` or a second parent: the catalog takes one, the page checks the other + else unindexed += 1; + } + // rows by key: every other condition is checked in the page, over exactly these rows + if (keys) return keys.length > 0 ? { keys: [...new Set(keys)] } : { nothing: true }; + // one spelling for one query, whatever the order of its conditions + const sorted = facts.toSorted(([x], [y]) => compareTextBinary(x, y)); + const filter: CatalogQuery = { + ...(sorted.length > 0 && { where: Object.fromEntries(sorted) }), + ...place, + }; + if (options.limit === undefined) + return { query: { ...filter, limit: CATALOG_WINDOW_LIMIT }, unlimited: true }; + + if (unindexed > 0) + throw new Error( + "the catalog has no index for a condition of this query, and a limit over a guessed set gives wrong rows: use facts (eq(c.metadata.x, value)), or drop the limit", + ); + const order = orderOf(options.orderBy); + if (!order) + throw new Error( + 'the catalog keeps three orders: a query with a limit says orderBy(c.activeMs, "desc"), orderBy(c.createdMs, "desc") or orderBy(c.path, "asc")', + ); + if (options.limit > CATALOG_WINDOW_LIMIT) + throw new Error(`the catalog's largest window is ${String(CATALOG_WINDOW_LIMIT)} rows`); + const query = { ...filter, order, limit: options.limit }; + // the rows after a row that is here: TanStack DB asks for them when a window holds fewer rows + // than its limit + if (options.cursor || options.offset) return { query, unlimited: false, after: true }; + return { query, unlimited: false }; +} + +// ── the collections ── + +/** What `contextsCollectionOptions` shows of itself: each catalog query in use. */ +export type CatalogDemand = { query: CatalogQuery; rows: number; full: boolean; frames: number }; + +/** A collection's own indexes, which the caller names: this file imports no code of TanStack DB. */ +export type CatalogIndexing = Pick< + CollectionConfig<{ path: string }, string>, + "defaultIndexType" | "autoIndex" +>; + +type SyncParams<Row extends object> = Parameters<SyncConfig<Row, string>["sync"]>[0]; + +/** THE WHOLE CATALOG AS ONE ON-DEMAND COLLECTION (this file's header says what a live query of + * it may ask). `collection.utils.demands()` lists the catalog queries in use. */ +export function contextsCollectionOptions({ + watcher, + id, + index, +}: { + watcher: CatalogWatcher; + id?: string; + /** How TanStack DB reads the rows that are here by a field (a window's order, a join's key): + * its `BasicIndex` with `autoIndex: "eager"`. Without it a read scans the rows, and says so + * on the console. */ + index?: CatalogIndexing; +}): CollectionConfig<ContextRow, string, never, { demands: () => CatalogDemand[] }> { + type Demand = { watch: CatalogWatch<CatalogRow>; holds: number; unlimited: boolean }; + /** Each catalog query in use, by its JSON: its watch, and how many requests hold it. */ + const demands = new Map<string, Demand>(); + /** The rows that joins asked for by key, each with how many requests hold it. All of them are + * ONE catalog query, sent again when the set changes: a session has few watches (64), and + * the catalog then sends only the new rows. */ + const keyHolds = new Map<string, number>(); + const keysDemand: { + watch: CatalogWatch<CatalogRow> | undefined; + settled: Promise<void>; + scheduled: boolean; + } = { watch: undefined, settled: Promise.resolve(), scheduled: false }; + /** path → the demands that hold the row. A row that no demand holds leaves the collection: + * nothing would keep it true. */ + const holders = new Map<string, Set<object>>(); + const describe = (): CatalogDemand[] => + [...[...demands.values()].map((demand) => demand.watch), keysDemand.watch].flatMap((watch) => + watch + ? [{ query: watch.query, rows: watch.rows.size, full: watch.full, frames: watch.frames }] + : [], + ); + + return { + id, + ...index, + getKey: (row) => row.path, + syncMode: "on-demand", + utils: { demands: describe }, + sync: { + rowUpdateMode: "full", + sync: ({ begin, write, commit, markReady, collection }: SyncParams<ContextRow>) => { + // One batch of the catalog is one write over ALL of this page's queries: it becomes one + // transaction here, so a join of two of this collection's queries never sees half of it. + let open = false; + let receipt: ReturnType<typeof commit> = true; + /** What the open transaction wrote: path → the row's revision, or false when deleted. */ + const written = new Map<string, number | false>(); + const transaction = () => { + if (!open) begin(); + open = true; + }; + const finish = () => { + if (!open) return; + // closed before the commit: TanStack DB may ask for another subset inside it + open = false; + written.clear(); + receipt = commit(); + }; + const stopBatches = watcher.onBatch(finish); + const revOf = (path: string) => + written.has(path) ? written.get(path) : (collection.get(path)?.rev ?? false); + const hold = (demand: object, row: CatalogRow) => { + const held = holders.get(row.path) ?? new Set(); + holders.set(row.path, held); + held.add(demand); + const now = revOf(row.path); + if (now === row.rev) return; + transaction(); + const value = contextRow(row); + if (now === false) write({ type: "insert", value }); + else write({ type: "update", value }); + written.set(row.path, row.rev); + }; + const release = (demand: object, path: string) => { + const held = holders.get(path); + held?.delete(demand); + if (held?.size) return; + holders.delete(path); + if (revOf(path) === false) return; + transaction(); + write({ type: "delete", key: path }); + written.set(path, false); + }; + const apply = ( + demand: object, + watch: () => CatalogWatch<CatalogRow> | undefined, + change: CatalogChange<CatalogRow>, + ) => { + if (change.error) return; + for (const path of change.del) release(demand, path); + // an answer is the query's whole set: also the rows that the cursor said are here + const rows = change.answer ? (watch()?.rows.values() ?? change.put) : change.put; + for (const row of rows) hold(demand, row); + }; + const end = (demand: object, watch: CatalogWatch<CatalogRow> | undefined) => { + watch?.stop(); + for (const path of watch?.rows.keys() ?? []) release(demand, path); + }; + + /** Sends the one query for every key in demand, once for any number of requests. */ + const sendKeys = async () => { + keysDemand.scheduled = false; + const keys = [...keyHolds.keys()].toSorted(compareTextBinary); + const before = keysDemand.watch; + if (keys.length === 0) { + keysDemand.watch = undefined; + end(keysDemand, before); + finish(); + return; + } + if (JSON.stringify(before?.query.keys) === JSON.stringify(keys)) return before?.ready; + const watch = watcher.watch( + { keys }, + CatalogRow, + (change) => { + apply(keysDemand, () => watch, change); + }, + before, + ); + keysDemand.watch = watch; + // the new query's answer names every row it holds: what only the old one held goes + before?.stop(); + await watch.ready; + }; + const demandKeys = (keys: readonly string[], by: 1 | -1) => { + for (const key of keys) { + const count = (keyHolds.get(key) ?? 0) + by; + if (count > 0) keyHolds.set(key, count); + else keyHolds.delete(key); + } + if (keysDemand.scheduled) return keysDemand.settled; + keysDemand.scheduled = true; + keysDemand.settled = Promise.resolve().then(sendKeys); + // an unload waits for nothing: its refusal is the load's to hear + keysDemand.settled.catch(() => {}); + return keysDemand.settled; + }; + const visible = async () => { + if (receipt !== true) await receipt; + }; + + markReady(); + return { + loadSubset: (options) => { + const asked = catalogQueryOf(options); + if ("nothing" in asked) return true; + if ("keys" in asked) return demandKeys(asked.keys, 1).then(visible); + const key = JSON.stringify(asked.query); + // another limit of the same facts and order + const { limit: _limit, ...facts } = asked.query; + const same = JSON.stringify(facts); + const like = [...demands.values()].find(({ watch }) => { + const { limit: _other, ...other } = watch.query; + return JSON.stringify(other) === same; + })?.watch; + if (asked.after) { + // The catalog keeps a window whole: when a row leaves it, the frame that says so + // brings the row that enters. So the rows after a window's last are never the + // page's to ask for. + if (like && like.answers > 0) return true; + throw new Error("the catalog serves a window from its start: ask for a larger limit"); + } + let demand = demands.get(key); + if (!demand) { + // it starts from the rows that are here + const made: Demand = { + holds: 0, + unlimited: asked.unlimited, + watch: watcher.watch( + asked.query, + CatalogRow, + (change) => { + apply(made, () => made.watch, change); + }, + like, + ), + }; + demand = made; + demands.set(key, demand); + } + demand.holds += 1; + const { watch, unlimited } = demand; + const check = () => { + if (unlimited && watch.full) + throw new Error( + `more than ${String(watch.rows.size)} rows match and the query has no limit: say an order and a limit`, + ); + }; + if (watch.answers > 0 && receipt === true) { + check(); + return true; + } + return watch.ready.then(check).then(visible); + }, + unloadSubset: (options) => { + let asked: ReturnType<typeof catalogQueryOf>; + try { + asked = catalogQueryOf(options); + } catch { + // a request that was refused holds nothing + return; + } + if ("nothing" in asked) return; + if ("keys" in asked) return void demandKeys(asked.keys, -1); + // a request for the rows after a row took no watch + if (asked.after) return; + const key = JSON.stringify(asked.query); + const demand = demands.get(key); + if (!demand) return; + demand.holds -= 1; + if (demand.holds > 0) return; + demands.delete(key); + end(demand, demand.watch); + finish(); + }, + cleanup: () => { + stopBatches(); + for (const demand of demands.values()) demand.watch.stop(); + keysDemand.watch?.stop(); + keysDemand.watch = undefined; + demands.clear(); + keyHolds.clear(); + holders.clear(); + }, + }; + }, + }, + }; +} + +/** ONE CATALOG QUERY AS ONE COLLECTION, for a page that names the catalog query itself: the awake + * list, or a window shown as it is. `row` parses each row. */ +export function watchedQueryCollectionOptions<Row extends { path: string }>({ + watcher, + id, + query, + row, + index, +}: { + watcher: CatalogWatcher; + id?: string; + query: CatalogQuery; + row: z.ZodType<Row>; + /** As `contextsCollectionOptions` takes it. */ + index?: CatalogIndexing; +}): CollectionConfig<Row, string, never, UtilsRecord> { + return { + id, + ...index, + getKey: (value) => value.path, + sync: { + rowUpdateMode: "full", + sync: ({ begin, write, commit, markReady, fail, collection }: SyncParams<Row>) => { + // The rows wait in an open transaction for the end of their batch, as the on-demand + // collection's do. A transaction is of one collection, so one write of the catalog is + // two commits in ONE TURN: a query that joins the two runs twice, and a page that draws + // after the turn (React does) never draws half of a write. + let open = false; + const stopBatches = watcher.onBatch(() => { + if (!open) return; + open = false; + commit(); + markReady(); + }); + const watch = watcher.watch(query, row, ({ del, put, error }) => { + if (error) { + fail(new Error(error)); + return; + } + if (!open) begin(); + open = true; + for (const path of del) if (collection.has(path)) write({ type: "delete", key: path }); + for (const value of put) + write({ type: collection.has(value.path) ? "update" : "insert", value }); + }); + return () => { + stopBatches(); + watch.stop(); + }; + }, + }, + }; +}
M src/components/context-catalog/context-activity-stack-view.tsx
@@ -14,7 +14,6 @@ CodeIcon, ExternalLinkIcon, GlobeIcon, - LayersIcon, SearchIcon, SquareTerminalIcon, } from "lucide-react"; @@ -397,15 +396,9 @@ }) { return ( <> - <div className="flex items-center justify-between gap-2 px-1"> - <span className="inline-flex items-center gap-1.5 font-medium text-foreground"> - <LayersIcon className="size-3.5 text-muted-foreground" aria-hidden /> - Active work ({active.length}) - </span> - {visibleStatus ? ( - <span className="truncate text-2xs text-muted-foreground">{visibleStatus.text}</span> - ) : null} - </div> + {visibleStatus ? ( + <div className="px-2 pt-0.5 text-2xs text-muted-foreground">{visibleStatus.text}</div> + ) : null} <ul className="flex flex-col gap-0.5" data-slot="activity-stack-list"> {active.map((item) => ( <ActivityStackRow
A src/components/context-catalog/context-catalog-live.test.tsx
@@ -0,0 +1,90 @@ +// @vitest-environment jsdom +// The hook that the Dash reads the catalog with: the mind pushes the rows, and a mind without +// `contexts.watch` is asked for the list as before. +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, test, vi } from "vitest"; +import type { CatalogItx } from "./catalog-collection.ts"; +import { useWatchedContextCatalog } from "./context-catalog-live.ts"; +import type { ContextListing } from "./context-catalog-rows.ts"; +import { fakeCatalog } from "#/test-support/fake-catalog.ts"; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +test("the rows are the catalog's window, the newest first, each with its awake row, and a write is pushed", async () => { + const catalog = fakeCatalog(); + catalog.put("/agents/a", 10, { description: "the first", eventCount: 3 }); + catalog.put("/agents/b", 20); + const list = vi.fn(() => Promise.resolve([])); + using page = await drawn(catalog.itx, list); + expect(page.last()?.rows?.map((row) => [row.path, row.awake?.since])).toEqual([ + ["/agents/b", undefined], + ["/agents/a", undefined], + ]); + // a watched row is a listing: what the views read of it is there + expect(page.last()?.rows?.[1]).toMatchObject({ description: "the first", eventCount: 3 }); + + await act(async () => { + catalog.putAwake("/agents/a", 30); + await settled(); + }); + expect(page.last()?.rows?.map((row) => [row.path, row.awake?.since])).toEqual([ + ["/agents/a", 30], + ["/agents/b", undefined], + ]); + expect(page.last()?.error).toBeUndefined(); + // one watch that asks whether the mind answers one; then two for the page's life, the window + // and the awake list; and no poll + expect(catalog.calls.map((call) => call.query)).toEqual([ + { awake: true }, + { order: "active", limit: 500 }, + { awake: true }, + ]); + expect([...catalog.watching].map((watch) => watch.query)).toEqual([ + { order: "active", limit: 500 }, + { awake: true }, + ]); + expect(list).not.toHaveBeenCalled(); +}); + +test("a mind without contexts.watch is asked for the list, and the page says no error", async () => { + const listing: ContextListing = { + path: "/agents/a", + eventCount: 1, + eventTypes: {}, + recentTypes: [], + processors: [], + }; + const list = vi.fn(() => Promise.resolve([listing])); + const itx: CatalogItx = { + contexts: { watch: () => Promise.reject(new Error("No such method: contexts.watch")) }, + }; + const errors = vi.spyOn(console, "error"); + using page = await drawn(itx, list); + expect(page.last()).toEqual({ rows: [listing], error: undefined }); + expect(list).toHaveBeenCalledTimes(1); + // the refusal is an answer: nothing failed, so nothing is said on the console + expect(errors).not.toHaveBeenCalled(); +}); + +/** Draws the hook, and answers what it last returned. */ +async function drawn(itx: CatalogItx, list: () => Promise<unknown>) { + const seen: { rows: ContextListing[] | undefined; error: string | undefined }[] = []; + function Rows() { + seen.push(useWatchedContextCatalog(itx, list, { of: "mind.example.com" })); + return null; + } + const root = createRoot(document.body.appendChild(document.createElement("div"))); + await act(async () => { + root.render(<Rows />); + await settled(); + }); + return { + last: () => seen.at(-1), + [Symbol.dispose]: () => { + act(() => root.unmount()); + }, + }; +} + +const settled = () => new Promise((resolve) => setTimeout(resolve, 5));
A src/components/context-catalog/context-catalog-live.ts
@@ -0,0 +1,126 @@ +// context-catalog-live.ts — THE CATALOG'S ROWS FOR A PAGE, PUSHED: the hook that the Dash reads +// the catalog with. The catalog is TanStack DB collections over `itx.contexts.watch` +// (catalog-collection.ts), and the rows are one live query: the 500 most recently active +// contexts, joined by path with the awake list for the dots and the activities. +// +// const { rows, error } = useWatchedContextCatalog(itx, () => itx.contexts.list({ limit: 500 }), { +// of: mind, +// }); +// +// A page's own query of the catalog is a live query of `catalogOf(itx).contexts`: +// +// const { data } = useLiveQuery({ query: (q) => +// q.from({ c: catalogOf(itx).contexts }).where(({ c }) => inArray("pinned", c.metadata.tags)) }); +// +// A MIND WHOSE PLATFORM HAS NO `contexts.watch` refuses the first watch. The hook then reads the +// catalog as before, with `list` every ten seconds (`useContextCatalog`), and says no error. +import { + BasicIndex, + createCollection, + createLiveQueryCollection, + eq, + useLiveQuery, +} from "@tanstack/react-db"; +import { useEffect, useMemo, useSyncExternalStore } from "react"; +import { + CatalogAwakeRow, + catalogWatcher, + CATALOG_WINDOW_LIMIT, + compareCatalogRows, + contextsCollectionOptions, + watchedQueryCollectionOptions, + type CatalogItx, +} from "./catalog-collection.ts"; +import { useContextCatalog } from "./context-catalog-list.tsx"; +import type { ContextListing } from "./context-catalog-rows.ts"; + +/** A window's order and a join's key are read through an index of the rows that are here. */ +const INDEXED = { defaultIndexType: BasicIndex, autoIndex: "eager" } as const; + +function collectionsOf(itx: CatalogItx) { + const watcher = catalogWatcher(itx); + /** The whole catalog, on demand: a live query of it is a query of the catalog. */ + const contexts = createCollection(contextsCollectionOptions({ watcher, index: INDEXED })); + /** The contexts that have work now. A join reads it by path, through an index. */ + const awake = createCollection( + watchedQueryCollectionOptions({ + watcher, + query: { awake: true }, + row: CatalogAwakeRow, + index: INDEXED, + }), + ); + // The window is a live query of its own, so that the catalog is asked for these rows and no + // more: a join that orders and limits is asked for its whole left side. + const recent = createLiveQueryCollection((q) => + q + .from({ context: contexts }) + .orderBy(({ context }) => context.activeMs, "desc") + .limit(CATALOG_WINDOW_LIMIT), + ); + /** The rows that every page of a Dash shows: the window, each row with its awake row. */ + const listings = createLiveQueryCollection((q) => + q + .from({ context: recent }) + .join({ awake }, ({ context, awake: row }) => eq(context.path, row.path), "left"), + ); + return { watcher, contexts, awake, listings }; +} + +const catalogs = new WeakMap<object, ReturnType<typeof collectionsOf>>(); + +/** THE CATALOG OF ONE MIND, for the life of the page, whoever asks: one watcher and one set of + * collections for an `itx`. A collection that no query reads holds no watch. */ +export function catalogOf(itx: CatalogItx): ReturnType<typeof collectionsOf> { + const held = catalogs.get(itx) ?? collectionsOf(itx); + catalogs.set(itx, held); + return held; +} + +/** The catalog's rows, pushed by the mind: the 500 most recently active contexts, the newest + * first, each with `awake` and `activities` when it has work now. `rows` is undefined until the + * first answer. On a platform without `contexts.watch` the rows are `list`'s, asked again every + * `pollMs` (`useContextCatalog`). `of` names whose catalog it is (the mind's address). */ +export function useWatchedContextCatalog( + itx: CatalogItx, + list: () => PromiseLike<unknown>, + { of, pollMs }: { of: string; pollMs?: number }, +): { rows: ContextListing[] | undefined; error: string | undefined } { + const catalog = catalogOf(itx); + const support = useSyncExternalStore( + catalog.watcher.subscribe, + catalog.watcher.support, + catalog.watcher.support, + ); + // WHETHER THE MIND ANSWERS A WATCH is asked with one watch of the awake list, before a + // collection reads anything: a refusal is then an answer here, and no failed load of a query. + // The watch ends with the answer, and the awake collection then starts its own. + useEffect(() => { + if (support !== "asking") return; + const asked = catalog.watcher.watch({ awake: true }, CatalogAwakeRow, () => {}); + return () => { + asked.stop(); + }; + }, [catalog, support]); + const polled = useContextCatalog(support === "none" ? list : null, { of, pollMs }); + const live = useLiveQuery({ + query: (q) => (support === "live" ? q.from({ listing: catalog.listings }) : undefined), + }); + const data = live.isReady ? live.data : undefined; + const rows = useMemo( + () => + data + ?.map(({ context, awake }): ContextListing & { activeMs: number } => ({ + ...context, + ...(awake && { awake: { since: awake.since } }), + ...(awake?.activities && { activities: awake.activities }), + })) + .toSorted((a, b) => compareCatalogRows(a, b)), + [data], + ); + if (support === "none") return polled; + return { + rows, + error: live.isLoadingError ? "The mind did not answer the catalog's query." : undefined, + }; +}
M src/components/context-catalog/context-catalog.ts
@@ -24,5 +24,7 @@ export * from "./context-catalog-rows.ts"; export * from "./context-palette-rows.ts"; export { ContextCatalog, ContextCatalogList, useContextCatalog } from "./context-catalog-list.tsx"; +export * from "./catalog-collection.ts"; +export { catalogOf, useWatchedContextCatalog } from "./context-catalog-live.ts"; export { ContextAbout, ContextFacts } from "./context-about.tsx"; export { ContextPalette } from "./context-palette.tsx";
A src/components/context-stream/context-stream-model.ts
@@ -0,0 +1,194 @@ +import type { ReactNode } from "react"; + +export type ContextStreamActorKind = "person" | "guest" | "mind" | "context" | "app"; + +export type ContextStreamActorRef = { + kind: ContextStreamActorKind; + id: string; + email?: string; + name?: string; +}; + +export type ContextStreamActorIdentity = ContextStreamActorRef & { + name: string; + label: string; + avatar?: string; + status?: { text: string; until?: string }; + path?: string; +}; + +export type ContextStreamFileRef = { + path: string; + filename: string; + contentType: string; + size: number; + width?: number; + height?: number; +}; + +export type SubcontextPreview = { + path: string; + anchor: number; + startedBy?: ContextStreamActorRef; + title?: string; + replies: number; + participants: readonly ContextStreamActorRef[]; + unread?: boolean; + more?: number; + last?: { offset: number; at: string; by: ContextStreamActorRef; text: string }; + live?: { by: ContextStreamActorRef; text: string; since: string }; + ended?: { at: string; outcome: "done" | "failed" | "stopped" }; +}; + +export type ContextStreamCopyItem = { + label: string; + value: string; + mono?: boolean; +}; + +export type ContextStreamMenuAction = { + label: string; + onSelect: () => void; +}; + +/** Configurable 1-level-deep menu attached to a message's corner `•••` button. + * Keeps offsets, spans, and trace details off the 0-click surface while making them one tap away. */ +export type ContextStreamMessageMenu = { + /** Overview of how this message came to be (e.g. collapsed activity span, model calls, event range). */ + provenance?: ReactNode; + /** Copyable values (defaults to copying the message text when omitted). */ + copyItems?: readonly ContextStreamCopyItem[]; + /** Extra actions (e.g. "Inspect full trace", "View raw events"). */ + actions?: readonly ContextStreamMenuAction[]; +}; + +type BaseRow = { + key: string; + offset: number; + at: number; + by: ContextStreamActorRef; + onBehalfOf?: ContextStreamActorRef; + subcontexts?: readonly SubcontextPreview[]; +}; + +export type ContextStreamMessageItem = BaseRow & { + kind: "message"; + text: string; + files?: readonly ContextStreamFileRef[]; + editedAt?: number; + deleted?: true; + reactions?: readonly { emoji: string; by: readonly ContextStreamActorRef[] }[]; + sending?: "pending" | "failed"; +}; + +export type ContextStreamSubcontextItem = BaseRow & { + kind: "subcontext"; + subcontext: SubcontextPreview; +}; + +export type ContextStreamCustomItem = BaseRow & { + kind: `${string}/${string}`; + data: unknown; + span?: readonly [from: number, to: number]; +}; + +export type ContextStreamDayItem = { + kind: "day"; + key: string; + at: number; + label: string; +}; + +export type ContextStreamItem = + | ContextStreamMessageItem + | ContextStreamSubcontextItem + | ContextStreamCustomItem + | ContextStreamDayItem; + +export type ContextStreamLiveEntry = { + key: string; + by: ContextStreamActorRef; + kind: "typing" | `${string}/${string}`; + text?: string; + sinceMs?: number; + data?: unknown; + /** Optional 1-level-deep `•••` menu for an in-progress row (live offset range, running steps, inspect action). */ + menu?: ContextStreamMessageMenu; +}; + +export type ContextStreamOpenTarget = + | { subcontext: string; anchor?: number } + | { pane: string; data: unknown }; + +export function defaultActorIdentity(ref: ContextStreamActorRef): ContextStreamActorIdentity { + const shortEmail = ref.email?.split("@", 1)[0]; + const rawName = ref.name || shortEmail || ref.id; + const name = ref.kind === "guest" ? `${rawName} (guest)` : rawName; + const baseLabel = ref.email || ref.name || ref.id; + const label = ref.kind === "guest" ? `${baseLabel} (guest)` : baseLabel; + return { ...ref, name, label }; +} + +export function actorFaceProps(actor: ContextStreamActorIdentity, agentName: string) { + const isMind = actor.kind === "mind" || actor.kind === "context"; + const who = isMind && actor.name === agentName ? agentName : actor.email || actor.id; + return { + who, + name: actor.email ? undefined : actor.name, + agent: agentName, + ...(isMind && { kind: "mind" as const }), + }; +} + +export function formatShortTime(timestampMs: number): string { + if (!Number.isFinite(timestampMs)) return ""; + return new Date(timestampMs).toLocaleTimeString([], { + hour: "2-digit", + minute: "2-digit", + hour12: false, + }); +} + +/** Compact gutter timestamp (`14:38`) revealed on hover for stacked continuation messages. */ +export function formatGutterHoverTime(timestampMs: number): string { + return formatShortTime(timestampMs); +} + +/** Maximum gap (`10m`) within which consecutive messages from the same principal stack without repeating the header. */ +const STACK_WINDOW_MS = 10 * 60_000; + +/** Maximum child subcontext bars rendered inline under one parent item before `"+n more"`. */ +export const MAX_INLINE_SUBCONTEXT_BARS = 2; + +export function estimateContextStreamItemSize( + item: ContextStreamItem, + continuesRun = false, +): number { + if (item.kind === "day") return 36; + if (item.kind === "subcontext") return 40; + if (item.kind === "message") { + const bars = Math.min(item.subcontexts?.length ?? 0, MAX_INLINE_SUBCONTEXT_BARS); + return (continuesRun ? 34 : 62) + bars * 32; + } + return 44; +} + +/** Consecutive messages from the same actor within `STACK_WINDOW_MS` stack tightly without repeating + * the face or author header, restarting when another actor speaks, a non-message row intervenes, + * or the gap exceeds `STACK_WINDOW_MS`. */ +export function computeContinuesRunFlags(items: readonly ContextStreamItem[]): boolean[] { + return items.map((item, idx) => { + if (idx === 0 || item.kind !== "message") return false; + const prev = items[idx - 1]!; + if (prev.kind !== "message") return false; + if (prev.by.kind !== item.by.kind || prev.by.id !== item.by.id) return false; + if ( + Number.isFinite(prev.at) && + Number.isFinite(item.at) && + item.at - prev.at > STACK_WINDOW_MS + ) { + return false; + } + return true; + }); +}
A src/components/context-stream/context-stream-view.tsx
@@ -0,0 +1,960 @@ +// Base stream view for any context (`ContextStream`): +// - Zero knowledge of LLMs, `<codemode>`, turns, or `#offset` numbers on the 0-click surface: +// actors (people, guests, minds, subcontexts, apps) post messages, react, and open nested +// subcontexts (`SubcontextPreview`) in a single virtualized log. +// - Every actor — including the viewer — shares the same `2rem` (`size-8`) Slack-proportioned left +// attribution gutter: circular faces for people/guests, rounded-square (`rounded-[22.37%]`) faces for minds. +// - Consecutive messages from the same actor stack tightly without repeating the face or header, +// highlighting individually on hover while revealing a gutter timestamp and a corner hover bar. +// - A faint right-aligned `•••` menu on every message (reachable on touch and hover) opens a +// configurable 1-level-deep menu (`messageMenu`) for copying text/ranges and inspecting provenance. +import { memo, useCallback, useMemo, useState, type ReactNode } from "react"; +import { + CheckIcon, + ChevronRightIcon, + CopyIcon, + MessageSquareTextIcon, + MoreHorizontalIcon, +} from "lucide-react"; +import { Streamdown } from "streamdown"; +import { cn } from "cn"; +import { + actorFaceProps, + computeContinuesRunFlags, + defaultActorIdentity, + estimateContextStreamItemSize, + formatGutterHoverTime, + formatShortTime, + MAX_INLINE_SUBCONTEXT_BARS, + type ContextStreamActorIdentity, + type ContextStreamActorRef, + type ContextStreamCopyItem, + type ContextStreamCustomItem, + type ContextStreamItem, + type ContextStreamLiveEntry, + type ContextStreamMenuAction, + type ContextStreamMessageItem, + type ContextStreamMessageMenu, + type ContextStreamOpenTarget, + type SubcontextPreview, +} from "./context-stream-model.ts"; +import { Face } from "#/components/call/face.tsx"; +import { Popover, PopoverContent, PopoverTrigger } from "#/components/ui/popover.tsx"; +import { + NEWER_EXHAUSTED, + OLDER_EXHAUSTED, + type NewerPages, + type OlderPages, +} from "#/components/virtual-log/older-pages.ts"; +import { LogReading } from "#/components/virtual-log/read-progress.tsx"; +import { VirtualLog, type VirtualLogRowInfo } from "#/components/virtual-log/virtual-log.tsx"; + +/** `2rem` (`size-8` = 32px) Slack avatar gutter beside the content column. */ +const GUTTER_GRID = "grid grid-cols-[2rem_minmax(0,1fr)] gap-x-2.5"; + +const ROW_INFO: VirtualLogRowInfo<ContextStreamItem> = { + key: (item) => item.key, + estimateSize: estimateContextStreamItemSize, + offset: (item) => (item.kind === "day" ? undefined : item.offset), + span: (item) => (item.kind !== "day" && "span" in item ? item.span : undefined), +}; + +export function ContextStream({ + items, + live, + older = OLDER_EXHAUSTED, + newer = NEWER_EXHAUSTED, + arrivals, + actor = defaultActorIdentity, + agentName = "iterate", + reveal, + followTail, + onOpen, + onToggleReaction, + onJumpToLatest, + messageMenu, + rows, + liveRows, + under, + composer, + aboveComposer, + belowComposer, + empty, + label = "Context stream", + columnClassName = "mx-auto w-full max-w-3xl px-4 md:px-6", + className, +}: { + items: readonly ContextStreamItem[]; + live?: readonly ContextStreamLiveEntry[]; + older?: OlderPages; + newer?: NewerPages; + arrivals?: readonly { offset: number }[]; + actor?: (ref: ContextStreamActorRef) => ContextStreamActorIdentity; + agentName?: string; + reveal?: number; + followTail?: number; + onOpen?: (target: ContextStreamOpenTarget) => void; + onToggleReaction?: (offset: number, emoji: string) => void; + onJumpToLatest?: () => void; + messageMenu?: (item: ContextStreamMessageItem) => ContextStreamMessageMenu | undefined; + rows?: Readonly<Record<string, (item: ContextStreamCustomItem) => ReactNode>>; + liveRows?: Readonly<Record<string, (entry: ContextStreamLiveEntry) => ReactNode>>; + under?: (item: ContextStreamItem) => ReactNode; + composer?: ReactNode; + aboveComposer?: ReactNode; + belowComposer?: ReactNode; + empty?: ReactNode; + label?: string; + columnClassName?: string; + className?: string; +}) { + const continuesRunFlags = useMemo(() => computeContinuesRunFlags(items), [items]); + + const renderRow = useCallback( + (item: ContextStreamItem, index: number) => ( + <ContextStreamRow + item={item} + continuesRun={continuesRunFlags[index] ?? false} + actor={actor} + agentName={agentName} + onOpen={onOpen} + onToggleReaction={onToggleReaction} + messageMenu={messageMenu} + rows={rows} + under={under} + /> + ), + [continuesRunFlags, actor, agentName, onOpen, onToggleReaction, messageMenu, rows, under], + ); + + let emptyNode: ReactNode = ( + <div className="py-3"> + <LogReading label="Loading stream" /> + </div> + ); + if (older.failed) { + emptyNode = null; + } else if (older.exhausted) { + emptyNode = empty; + } + + const tailNode = + live && live.length > 0 ? ( + <ContextStreamTail live={live} actor={actor} agentName={agentName} liveRows={liveRows} /> + ) : undefined; + + const hasFooter = Boolean(aboveComposer || composer || belowComposer); + + return ( + <VirtualLog + rows={items} + rowInfo={ROW_INFO} + renderRow={renderRow} + older={older} + newer={newer} + arrivals={arrivals} + reveal={reveal} + followTail={followTail} + onJumpToLatest={onJumpToLatest} + empty={emptyNode} + tail={tailNode} + label={label} + footer={ + hasFooter ? ( + <ContextStreamFooter + aboveComposer={aboveComposer} + composer={composer} + belowComposer={belowComposer} + /> + ) : undefined + } + paddingStart={8} + paddingEnd={8} + columnClassName={columnClassName} + className={className} + /> + ); +} + +function ContextStreamFooter({ + aboveComposer, + composer, + belowComposer, +}: { + aboveComposer: ReactNode; + composer: ReactNode; + belowComposer: ReactNode; +}) { + return ( + <div + data-slot="context-stream-footer" + className="pointer-events-none bg-linear-to-t from-background from-80% to-transparent px-4 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] md:px-6" + > + <div className="pointer-events-auto mx-auto flex w-full max-w-3xl flex-col"> + {aboveComposer ? ( + <div data-slot="context-stream-above-composer" className="pb-1.5 empty:hidden"> + {aboveComposer} + </div> + ) : null} + {composer} + {belowComposer ? ( + <div data-slot="context-stream-below-composer" className="px-1 pt-1.5 empty:hidden"> + {belowComposer} + </div> + ) : null} + </div> + </div> + ); +} + +function ContextStreamTail({ + live, + actor, + agentName, + liveRows, +}: { + live: readonly ContextStreamLiveEntry[]; + actor: (ref: ContextStreamActorRef) => ContextStreamActorIdentity; + agentName: string; + liveRows: Readonly<Record<string, (entry: ContextStreamLiveEntry) => ReactNode>> | undefined; +}) { + return ( + <div data-slot="context-stream-tail" className="flex flex-col gap-2 py-2"> + {live.map((entry) => { + const resolved = actor(entry.by); + const custom = liveRows?.[entry.kind]?.(entry); + return ( + <div + key={entry.key} + data-live-actor={entry.by.id} + data-live-kind={entry.kind} + className={cn( + GUTTER_GRID, + "group/msg relative -mx-2 gap-y-0.5 rounded-md px-2 py-1 transition-colors hover:bg-muted/55 focus-within:bg-muted/55", + )} + > + {entry.kind !== "typing" ? <LiveEntryCornerMenu entry={entry} /> : null} + <span className="relative col-start-1 row-start-1 row-span-2 inline-flex size-8 self-start pt-0.5"> + <Face {...actorFaceProps(resolved, agentName)} label={resolved.label} /> + <span className="absolute -right-0.5 -bottom-0.5 size-2.5 rounded-full bg-success ring-2 ring-background" /> + </span> + <span className="col-start-2 row-start-1 truncate pr-7 text-sm font-semibold text-foreground"> + {resolved.name} + </span> + <div className="col-start-2 row-start-2 min-w-0 pr-7"> + {custom ?? <DefaultLiveEntryBody entry={entry} label={resolved.label} />} + </div> + </div> + ); + })} + </div> + ); +} + +function LiveEntryCornerMenu({ entry }: { entry: ContextStreamLiveEntry }) { + const [open, setOpen] = useState(false); + const menuConfig = entry.menu; + const copyItems: readonly ContextStreamCopyItem[] = + menuConfig?.copyItems || (entry.text ? [{ label: "Copy status text", value: entry.text }] : []); + const actions: readonly ContextStreamMenuAction[] = menuConfig?.actions || []; + + return ( + <div + data-slot="message-hover-actions" + className={cn( + "absolute top-1.5 right-1.5 z-10 flex items-center gap-0.5 rounded-md transition-all", + open + ? "border border-border bg-background p-0.5 shadow-xs" + : "group-hover/msg:-top-2.5 group-hover/msg:border group-hover/msg:border-border group-hover/msg:bg-background group-hover/msg:p-0.5 group-hover/msg:shadow-xs group-focus-within/msg:-top-2.5 group-focus-within/msg:border group-focus-within/msg:border-border group-focus-within/msg:bg-background group-focus-within/msg:p-0.5 group-focus-within/msg:shadow-xs", + )} + > + <Popover open={open} onOpenChange={setOpen}> + <PopoverTrigger + render={ + <button + type="button" + data-slot="message-more-trigger" + aria-label="In-progress message options and details" + className={cn( + "inline-flex size-6 cursor-pointer items-center justify-center rounded transition-opacity hover:bg-muted hover:text-foreground", + open + ? "text-foreground opacity-100" + : "text-muted-foreground opacity-35 group-hover/msg:opacity-100 group-focus-within/msg:opacity-100", + )} + /> + } + > + <MoreHorizontalIcon className="size-3.5" /> + </PopoverTrigger> + <PopoverContent + align="end" + data-slot="message-more-menu" + className="flex w-64 flex-col gap-1.5 p-2 text-xs" + > + {copyItems.map((item) => ( + <MenuCopyRow key={item.label} entry={item} /> + ))} + {menuConfig?.provenance ? ( + <div + data-slot="message-provenance" + className="mt-0.5 rounded-md border border-border/70 bg-muted/35 p-2 text-2xs leading-relaxed text-muted-foreground" + > + {menuConfig.provenance} + </div> + ) : ( + <div + data-slot="message-provenance" + className="mt-0.5 rounded-md border border-border/70 bg-muted/35 p-2 text-2xs leading-relaxed text-muted-foreground" + > + Response in progress… + </div> + )} + {actions.map((actItem) => ( + <button + key={actItem.label} + type="button" + onClick={() => { + setOpen(false); + actItem.onSelect(); + }} + className="flex w-full cursor-pointer items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left font-medium text-foreground hover:bg-muted" + > + <span className="truncate">{actItem.label}</span> + <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground" /> + </button> + ))} + </PopoverContent> + </Popover> + </div> + ); +} + +function DefaultLiveEntryBody({ entry, label }: { entry: ContextStreamLiveEntry; label: string }) { + if (entry.kind === "typing") { + return ( + <span className="flex h-5 items-center gap-1" aria-label={`${label} is typing`}> + <span className="size-1.5 rounded-full bg-muted-foreground motion-safe:animate-pulse" /> + <span className="size-1.5 rounded-full bg-muted-foreground motion-safe:animate-pulse [animation-delay:150ms]" /> + <span className="size-1.5 rounded-full bg-muted-foreground motion-safe:animate-pulse [animation-delay:300ms]" /> + </span> + ); + } + if (entry.text) { + return <span className="shimmer block truncate text-sm font-medium">{entry.text}</span>; + } + return null; +} + +const ContextStreamRow = memo(function ContextStreamRow({ + item, + continuesRun, + actor, + agentName, + onOpen, + onToggleReaction, + messageMenu, + rows, + under, +}: { + item: ContextStreamItem; + continuesRun: boolean; + actor: (ref: ContextStreamActorRef) => ContextStreamActorIdentity; + agentName: string; + onOpen: ((target: ContextStreamOpenTarget) => void) | undefined; + onToggleReaction: ((offset: number, emoji: string) => void) | undefined; + messageMenu: + | ((item: ContextStreamMessageItem) => ContextStreamMessageMenu | undefined) + | undefined; + rows: Readonly<Record<string, (item: ContextStreamCustomItem) => ReactNode>> | undefined; + under: ((item: ContextStreamItem) => ReactNode) | undefined; +}) { + if (item.kind === "day") { + return ( + <div className="flex items-center gap-3 py-2.5" data-slot="context-stream-day"> + <div className="h-px flex-1 bg-border/70" /> + <span className="shrink-0 whitespace-nowrap text-xs font-medium text-muted-foreground"> + {item.label} + </span> + <div className="h-px flex-1 bg-border/70" /> + </div> + ); + } + + if (item.kind === "subcontext") { + const resolved = actor(item.by); + return ( + <div className={cn(GUTTER_GRID, "items-center py-1.5")} data-slot="context-stream-subcontext"> + <span className="inline-flex size-8 items-center justify-center self-start"> + <Face small {...actorFaceProps(resolved, agentName)} label={resolved.label} /> + </span> + <div className="min-w-0"> + <SubcontextBar + preview={item.subcontext} + actor={actor} + agentName={agentName} + onOpen={onOpen} + /> + </div> + </div> + ); + } + + if (item.kind !== "message") { + const customRenderer = rows?.[item.kind]; + if (!customRenderer) return null; + const resolved = actor(item.by); + return ( + <div + className={cn(GUTTER_GRID, "items-start py-1.5")} + data-slot="context-stream-custom" + data-item-kind={item.kind} + > + <span className="inline-flex size-8 items-center justify-center self-start pt-0.5"> + <Face small {...actorFaceProps(resolved, agentName)} label={resolved.label} /> + </span> + <div className="min-w-0">{customRenderer(item)}</div> + </div> + ); + } + + return ( + <ContextStreamMessageRow + item={item} + continuesRun={continuesRun} + actor={actor} + agentName={agentName} + onOpen={onOpen} + onToggleReaction={onToggleReaction} + messageMenu={messageMenu} + under={under} + /> + ); +}); + +function ContextStreamMessageRow({ + item, + continuesRun, + actor, + agentName, + onOpen, + onToggleReaction, + messageMenu, + under, +}: { + item: ContextStreamMessageItem; + continuesRun: boolean; + actor: (ref: ContextStreamActorRef) => ContextStreamActorIdentity; + agentName: string; + onOpen: ((target: ContextStreamOpenTarget) => void) | undefined; + onToggleReaction: ((offset: number, emoji: string) => void) | undefined; + messageMenu: + | ((item: ContextStreamMessageItem) => ContextStreamMessageMenu | undefined) + | undefined; + under: ((item: ContextStreamItem) => ReactNode) | undefined; +}) { + const resolved = actor(item.by); + const underNode = under?.(item); + const subcontexts = item.subcontexts || []; + const menuConfig = messageMenu?.(item); + + return ( + <div + data-slot="context-stream-message" + data-actor={item.by.id} + data-continues-run={continuesRun ? "true" : undefined} + className={cn( + GUTTER_GRID, + "group/msg relative -mx-2 gap-y-0.5 rounded-md px-2 transition-colors hover:bg-muted/55 focus-within:bg-muted/55", + continuesRun ? "py-1" : "pt-2.5 pb-1", + )} + > + <MessageCornerControls + item={item} + primarySubcontextPath={subcontexts[0]?.path} + menuConfig={menuConfig} + onOpen={onOpen} + onToggleReaction={onToggleReaction} + /> + + {continuesRun ? ( + <StackedGutterTimestamp at={item.at} /> + ) : ( + <MessageRunHeader resolved={resolved} agentName={agentName} item={item} /> + )} + + <div + className={cn( + "col-start-2 flex min-w-0 flex-col gap-1 pr-7", + !continuesRun && "row-start-2", + )} + > + <span className="sr-only">{`${resolved.label}:`}</span> + <MessageBody item={item} /> + <MessageUnderBar + offset={item.offset} + reactions={item.reactions} + underNode={underNode} + onToggleReaction={onToggleReaction} + /> + {subcontexts.length > 0 ? ( + <MessageSubcontextStack + anchorOffset={item.offset} + subcontexts={subcontexts} + actor={actor} + agentName={agentName} + onOpen={onOpen} + /> + ) : null} + </div> + </div> + ); +} + +function StackedGutterTimestamp({ at }: { at: number }) { + const short = formatGutterHoverTime(at); + if (!short) return null; + return ( + <time + data-slot="stacked-hover-time" + className="pointer-events-none col-start-1 row-start-1 self-start pt-1 text-right text-2xs leading-none text-muted-foreground tabular-nums opacity-0 transition-opacity select-none group-hover/msg:opacity-100 group-focus-within/msg:opacity-100" + > + {short} + </time> + ); +} + +function MessageRunHeader({ + resolved, + agentName, + item, +}: { + resolved: ContextStreamActorIdentity; + agentName: string; + item: ContextStreamMessageItem; +}) { + return ( + <> + <span + aria-hidden="true" + className="col-start-1 row-start-1 row-span-2 inline-flex size-8 self-start pt-0.5" + > + <Face {...actorFaceProps(resolved, agentName)} /> + </span> + <div className="col-start-2 row-start-1 flex items-baseline gap-2 pr-7"> + <span + data-said-by + title={resolved.label} + className="truncate text-sm font-bold text-foreground" + > + {resolved.name} + </span> + <time className="shrink-0 whitespace-nowrap text-xs text-muted-foreground tabular-nums"> + {formatShortTime(item.at)} + </time> + {item.editedAt ? ( + <span className="shrink-0 whitespace-nowrap text-2xs text-muted-foreground"> + (edited) + </span> + ) : null} + </div> + </> + ); +} + +/** Faint right-aligned `•••` at rest (always tappable on mobile) that expands into a Slack-style + * corner hover toolbar (`👍`, `🚀`, `Reply in thread`, `•••`) on hover or while open. */ +function MessageCornerControls({ + item, + primarySubcontextPath, + menuConfig, + onOpen, + onToggleReaction, +}: { + item: ContextStreamMessageItem; + primarySubcontextPath: string | undefined; + menuConfig: ContextStreamMessageMenu | undefined; + onOpen: ((target: ContextStreamOpenTarget) => void) | undefined; + onToggleReaction: ((offset: number, emoji: string) => void) | undefined; +}) { + const [open, setOpen] = useState(false); + const targetSubcontext = primarySubcontextPath || `t/${String(item.offset)}`; + + return ( + <div + data-slot="message-hover-actions" + className={cn( + "absolute top-1.5 right-1.5 z-10 flex items-center gap-0.5 rounded-md transition-all", + open + ? "border border-border bg-background p-0.5 shadow-xs" + : "group-hover/msg:-top-2.5 group-hover/msg:border group-hover/msg:border-border group-hover/msg:bg-background group-hover/msg:p-0.5 group-hover/msg:shadow-xs group-focus-within/msg:-top-2.5 group-focus-within/msg:border group-focus-within/msg:border-border group-focus-within/msg:bg-background group-focus-within/msg:p-0.5 group-focus-within/msg:shadow-xs", + )} + > + <HoverQuickButtons + visible={open} + offset={item.offset} + targetSubcontext={targetSubcontext} + onOpen={onOpen} + onToggleReaction={onToggleReaction} + /> + + <Popover open={open} onOpenChange={setOpen}> + <PopoverTrigger + render={ + <button + type="button" + data-slot="message-more-trigger" + aria-label="Message options and details" + className={cn( + "inline-flex size-6 cursor-pointer items-center justify-center rounded transition-opacity hover:bg-muted hover:text-foreground", + open + ? "text-foreground opacity-100" + : "text-muted-foreground opacity-35 group-hover/msg:opacity-100 group-focus-within/msg:opacity-100", + )} + /> + } + > + <MoreHorizontalIcon className="size-3.5" /> + </PopoverTrigger> + <PopoverContent + align="end" + data-slot="message-more-menu" + className="flex w-64 flex-col gap-1.5 p-2 text-xs" + > + <MessageMoreMenuBody + item={item} + targetSubcontext={targetSubcontext} + menuConfig={menuConfig} + onOpen={onOpen} + onClose={() => setOpen(false)} + /> + </PopoverContent> + </Popover> + </div> + ); +} + +function HoverQuickButtons({ + visible, + offset, + targetSubcontext, + onOpen, + onToggleReaction, +}: { + visible: boolean; + offset: number; + targetSubcontext: string; + onOpen: ((target: ContextStreamOpenTarget) => void) | undefined; + onToggleReaction: ((offset: number, emoji: string) => void) | undefined; +}) { + const showClass = visible + ? "inline-flex" + : "hidden group-hover/msg:inline-flex group-focus-within/msg:inline-flex"; + + return ( + <> + {onToggleReaction ? ( + <> + <button + type="button" + aria-label="React with thumbs up" + onClick={() => onToggleReaction(offset, "👍")} + className={cn( + showClass, + "size-6 cursor-pointer items-center justify-center rounded text-xs hover:bg-muted", + )} + > + 👍 + </button> + <button + type="button" + aria-label="React with rocket" + onClick={() => onToggleReaction(offset, "🚀")} + className={cn( + showClass, + "size-6 cursor-pointer items-center justify-center rounded text-xs hover:bg-muted", + )} + > + 🚀 + </button> + </> + ) : null} + {onOpen ? ( + <button + type="button" + aria-label="Reply in thread" + title="Reply in thread" + onClick={() => onOpen({ subcontext: targetSubcontext, anchor: offset })} + className={cn( + showClass, + "size-6 cursor-pointer items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground", + )} + > + <MessageSquareTextIcon className="size-3.5" /> + </button> + ) : null} + </> + ); +} + +function MessageMoreMenuBody({ + item, + targetSubcontext, + menuConfig, + onOpen, + onClose, +}: { + item: ContextStreamMessageItem; + targetSubcontext: string; + menuConfig: ContextStreamMessageMenu | undefined; + onOpen: ((target: ContextStreamOpenTarget) => void) | undefined; + onClose: () => void; +}) { + const copyItems: readonly ContextStreamCopyItem[] = menuConfig?.copyItems || [ + { label: "Copy message text", value: item.text }, + ]; + const actions: readonly ContextStreamMenuAction[] = menuConfig?.actions || []; + + return ( + <> + {onOpen ? ( + <button + type="button" + onClick={() => { + onClose(); + onOpen({ subcontext: targetSubcontext, anchor: item.offset }); + }} + className="flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left text-foreground hover:bg-muted" + > + <MessageSquareTextIcon className="size-3.5 shrink-0 text-muted-foreground" /> + <span>Reply in thread</span> + </button> + ) : null} + + {copyItems.map((entry) => ( + <MenuCopyRow key={entry.label} entry={entry} /> + ))} + + {menuConfig?.provenance ? ( + <div + data-slot="message-provenance" + className="mt-0.5 rounded-md border border-border/70 bg-muted/35 p-2 text-2xs leading-relaxed text-muted-foreground" + > + {menuConfig.provenance} + </div> + ) : null} + + {actions.map((actItem) => ( + <button + key={actItem.label} + type="button" + onClick={() => { + onClose(); + actItem.onSelect(); + }} + className="flex w-full cursor-pointer items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left font-medium text-foreground hover:bg-muted" + > + <span className="truncate">{actItem.label}</span> + <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground" /> + </button> + ))} + </> + ); +} + +function MenuCopyRow({ entry }: { entry: ContextStreamCopyItem }) { + const [copied, setCopied] = useState(false); + return ( + <button + type="button" + onClick={() => { + navigator.clipboard?.writeText(entry.value).catch(() => {}); + setCopied(true); + setTimeout(() => setCopied(false), 1_200); + }} + className="flex w-full cursor-pointer items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left text-foreground hover:bg-muted" + > + <span className="inline-flex min-w-0 items-center gap-2"> + {copied ? ( + <CheckIcon className="size-3.5 shrink-0 text-success" /> + ) : ( + <CopyIcon className="size-3.5 shrink-0 text-muted-foreground" /> + )} + <span className={cn("truncate", entry.mono && "font-mono text-2xs")}>{entry.label}</span> + </span> + </button> + ); +} + +function MessageBody({ item }: { item: ContextStreamMessageItem }) { + if (item.deleted) { + return <p className="m-0 text-sm italic text-muted-foreground">This message was deleted.</p>; + } + return ( + <Streamdown + className="min-w-0 max-w-full text-sm leading-relaxed [&>*:first-child]:mt-0 [&>*:last-child]:mb-0" + mode="static" + parseIncompleteMarkdown={false} + > + {item.text} + </Streamdown> + ); +} + +function MessageUnderBar({ + offset, + reactions, + underNode, + onToggleReaction, +}: { + offset: number; + reactions: ContextStreamMessageItem["reactions"]; + underNode: ReactNode; + onToggleReaction: ((offset: number, emoji: string) => void) | undefined; +}) { + const hasReactions = Boolean(reactions && reactions.length > 0); + if (!hasReactions && !underNode) return null; + return ( + <div className="flex flex-wrap items-center gap-1.5 pt-0.5"> + {reactions?.map((r) => ( + <button + key={r.emoji} + type="button" + onClick={() => onToggleReaction?.(offset, r.emoji)} + className="inline-flex h-6 shrink-0 cursor-pointer items-center gap-1 whitespace-nowrap rounded-full border border-border/70 bg-background px-2 text-2xs text-foreground hover:bg-muted" + > + <span>{r.emoji}</span> + <span className="font-mono tabular-nums text-muted-foreground">{r.by.length}</span> + </button> + ))} + {underNode} + </div> + ); +} + +function MessageSubcontextStack({ + anchorOffset, + subcontexts, + actor, + agentName, + onOpen, +}: { + anchorOffset: number; + subcontexts: readonly SubcontextPreview[]; + actor: (ref: ContextStreamActorRef) => ContextStreamActorIdentity; + agentName: string; + onOpen: ((target: ContextStreamOpenTarget) => void) | undefined; +}) { + const shown = subcontexts.slice(0, MAX_INLINE_SUBCONTEXT_BARS); + const overflow = Math.max(0, subcontexts.length - shown.length); + return ( + <div className="flex flex-col items-start gap-1 pt-0.5" data-slot="subcontext-bars"> + {shown.map((sub) => ( + <SubcontextBar + key={sub.path} + preview={sub} + actor={actor} + agentName={agentName} + onOpen={onOpen} + /> + ))} + {overflow > 0 ? ( + <button + type="button" + onClick={() => + onOpen?.({ + subcontext: subcontexts[MAX_INLINE_SUBCONTEXT_BARS]!.path, + anchor: anchorOffset, + }) + } + className="cursor-pointer px-1 text-2xs text-muted-foreground hover:text-foreground" + > + +{overflow} more threads + </button> + ) : null} + </div> + ); +} + +/** Slack-style thread reply bar (`[i] [face] 5 replies • Unread`). */ +function SubcontextBar({ + preview, + actor, + agentName, + onOpen, +}: { + preview: SubcontextPreview; + actor: (ref: ContextStreamActorRef) => ContextStreamActorIdentity; + agentName: string; + onOpen: ((target: ContextStreamOpenTarget) => void) | undefined; +}) { + const faces = preview.participants.slice(0, 4); + const summaryText = preview.live?.text || preview.last?.text || preview.title; + const countLabel = preview.replies === 1 ? "1 reply" : `${String(preview.replies)} replies`; + + return ( + <button + type="button" + data-slot="subcontext-bar" + data-subcontext-path={preview.path} + onClick={() => onOpen?.({ subcontext: preview.path, anchor: preview.anchor })} + className="group/sub inline-flex h-7 max-w-full min-w-0 cursor-pointer items-center gap-1.5 rounded-md px-1.5 -ml-1.5 text-left text-xs transition-colors hover:bg-background hover:ring-1 hover:ring-border" + > + {faces.length > 0 ? ( + <span className="inline-flex shrink-0 items-center gap-1"> + {faces.map((p) => { + const resolved = actor(p); + return ( + <Face + key={`${p.kind}:${p.id}`} + small + {...actorFaceProps(resolved, agentName)} + className="size-5" + /> + ); + })} + </span> + ) : ( + <MessageSquareTextIcon className="size-3.5 shrink-0 text-primary" /> + )} + <span className="shrink-0 whitespace-nowrap font-semibold text-primary group-hover/sub:underline"> + {preview.title ? `${preview.title} · ${countLabel}` : countLabel} + </span> + <SubcontextSecondaryLabel + unread={preview.unread} + live={Boolean(preview.live)} + summaryText={summaryText} + /> + <ChevronRightIcon className="size-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover/sub:opacity-100" /> + </button> + ); +} + +function SubcontextSecondaryLabel({ + unread, + live, + summaryText, +}: { + unread: boolean | undefined; + live: boolean; + summaryText: string | undefined; +}) { + if (unread) { + return ( + <span className="inline-flex shrink-0 items-center gap-1 whitespace-nowrap font-medium text-destructive"> + <span className="size-1.5 rounded-full bg-destructive" /> + <span>Unread</span> + </span> + ); + } + if (!summaryText) return null; + return ( + <span + className={cn( + "min-w-0 flex-1 truncate text-muted-foreground", + live && "shimmer text-foreground/90", + )} + > + {summaryText} + </span> + ); +}
A src/components/context-stream/context-stream.test.tsx
@@ -0,0 +1,657 @@ +// @vitest-environment jsdom +import { act, useState, type ReactElement } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, test, vi } from "vitest"; +import { + ContextStream, + useWindowedEventPager, + type ContextStreamActorRef, + type ContextStreamItem, + type ContextStreamOpenTarget, + type OffsetEvent, +} from "./context-stream.ts"; + +Object.assign(globalThis, { + IS_REACT_ACT_ENVIRONMENT: true, + ResizeObserver: class { + observe() {} + unobserve() {} + disconnect() {} + }, +}); + +const JONAS: ContextStreamActorRef = { + kind: "person", + id: "u_jonas", + email: "jonas@nustom.com", + name: "jonas", +}; + +const ITERATE: ContextStreamActorRef = { + kind: "mind", + id: "iterate.com", + name: "iterate", +}; + +const JEEVES: ContextStreamActorRef = { + kind: "mind", + id: "jeeves.jonas.com", + name: "jeeves", +}; + +test("keeps offsets off the 0-click surface, stacks same-principal messages with individual hover + faint ••• menu, and reveals provenance 1 click deep", async () => { + const reacted: [number, string][] = []; + const inspected: number[] = []; + const items: ContextStreamItem[] = [ + { + kind: "message", + key: "m1", + offset: 80, + at: Date.parse("2026-11-25T14:38:00Z"), + by: JONAS, + text: "First message from Jonas", + }, + { + kind: "message", + key: "m2", + offset: 81, + at: Date.parse("2026-11-25T14:38:20Z"), + by: JONAS, + text: "Second consecutive message from Jonas", + }, + { + kind: "message", + key: "m3", + offset: 92, + at: Date.parse("2026-11-25T14:39:00Z"), + by: ITERATE, + text: "Updated both titles and preserved existing ones.", + }, + { + kind: "message", + key: "m4", + offset: 98, + at: Date.parse("2026-11-25T14:40:00Z"), + by: JEEVES, + text: "Verified from jeeves", + }, + ]; + + using view = mount( + <ContextStream + items={items} + onToggleReaction={(offset, emoji) => reacted.push([offset, emoji])} + messageMenu={(item) => + item.offset === 92 + ? { + provenance: <span>Events 80..92 · 2 model calls · 18s</span>, + copyItems: [ + { label: "Copy message text", value: item.text }, + { label: "Copy offset range 80..92", value: "/agents/em#80..92", mono: true }, + ], + actions: [ + { label: "Inspect full trace", onSelect: () => inspected.push(item.offset) }, + ], + } + : undefined + } + />, + ); + + // Zero offset numbers appear anywhere on the 0-click normie surface! + expect(view.container.textContent).not.toContain("80..92"); + expect(view.container.textContent).not.toContain("92"); + + const messageRows = [...view.container.querySelectorAll('[data-slot="context-stream-message"]')]; + expect(messageRows.length).toBe(4); + for (const row of messageRows) { + expect(row.className).toContain("group/msg"); + expect(row.className).toContain("hover:bg-muted/55"); + expect(row.querySelector('[data-slot="message-more-trigger"]')).toBeTruthy(); + } + + // `m1` starts Jonas's run; `m2` stacks (`data-continues-run="true"`, no avatar, reveals stacked-hover-time on hover). + expect(messageRows[0]!.getAttribute("data-continues-run")).toBeNull(); + expect(messageRows[1]!.getAttribute("data-continues-run")).toBe("true"); + expect(messageRows[1]!.querySelector('[data-slot="avatar"]')).toBeNull(); + expect( + messageRows[1]!.querySelector('[data-slot="stacked-hover-time"]')?.textContent, + ).toBeTruthy(); + + // Quick hover reaction on `m2` targets `m2`'s individual offset (`81`). + act(() => { + messageRows[1]! + .querySelector<HTMLButtonElement>('[aria-label="React with thumbs up"]')! + .click(); + }); + expect(reacted).toEqual([[81, "👍"]]); + + // Clicking the faint right-aligned `•••` on `iterate`'s reply (`m3`) reveals `80..92` 1 level deep! + await act(async () => { + messageRows[2]!.querySelector<HTMLButtonElement>('[data-slot="message-more-trigger"]')!.click(); + }); + const menu = document.body.querySelector('[data-slot="message-more-menu"]'); + expect(menu?.textContent).toContain("80..92"); + expect(menu?.textContent).toContain("Copy offset range 80..92"); + + const saidByLabels = [...view.container.querySelectorAll("[data-said-by]")].map( + (el) => el.textContent, + ); + expect(saidByLabels).toEqual(["jonas", "iterate", "jeeves"]); + + // `jeeves` (`kind: "mind"`) gets `rounded-[22.37%]`; `jonas` (`kind: "person"`) stays circular. + const jeevesAvatar = view.container + .querySelector('[data-actor="jeeves.jonas.com"]')! + .querySelector('[data-slot="avatar"]')!; + expect(jeevesAvatar.className).toContain("rounded-[22.37%]"); + const jonasAvatar = view.container + .querySelector('[data-actor="u_jonas"]')! + .querySelector('[data-slot="avatar"]')!; + expect(jonasAvatar.className).not.toContain("rounded-[22.37%]"); +}); + +test("renders Slack-style thread bars (`5 replies • Unread`, capped at 2 + overflow) and plugs in 2-layer slots without border-t", () => { + const opened: ContextStreamOpenTarget[] = []; + const items: ContextStreamItem[] = [ + { + kind: "message", + key: "m100", + offset: 100, + at: Date.parse("2026-11-25T12:05:00Z"), + by: ITERATE, + text: "Shipped the rollout plan.", + subcontexts: [ + { + path: "/agents/rollout/t/100", + anchor: 100, + replies: 5, + unread: true, + participants: [ITERATE, JONAS], + }, + { + path: "/agents/rollout/security-audit", + anchor: 100, + title: "security-audit", + replies: 3, + participants: [ITERATE], + last: { offset: 12, at: "2026-11-25T12:05:30Z", by: ITERATE, text: "All checks green" }, + }, + { + path: "/agents/rollout/perf-bench", + anchor: 100, + title: "perf-bench", + replies: 2, + participants: [JEEVES], + }, + ], + }, + { + kind: "mcp/widget", + key: "w120", + offset: 120, + at: Date.parse("2026-11-25T12:07:00Z"), + by: ITERATE, + span: [105, 120], + data: { title: "Rollout Plan Widget" }, + }, + ]; + + using view = mount( + <ContextStream + items={items} + onOpen={(target) => opened.push(target)} + rows={{ + "mcp/widget": (item) => ( + <div data-testid="mcp-widget">{(item.data as { title: string }).title}</div> + ), + }} + live={[ + { + key: "live-iterate", + by: ITERATE, + kind: "agent/working", + data: { stackCount: 3 }, + }, + ]} + liveRows={{ + "agent/working": () => <div data-testid="grokbot-stack">Checking CI & reviewing…</div>, + }} + composer={<div data-testid="stream-composer">Composer box</div>} + belowComposer={<div data-testid="below-bar">Standard mode · Ready</div>} + />, + ); + + const bars = view.container.querySelectorAll('[data-slot="subcontext-bar"]'); + expect(bars.length).toBe(2); + expect(bars[0]!.textContent).toContain("5 replies"); + expect(bars[0]!.textContent).toContain("Unread"); + expect(view.container.textContent).toContain("+1 more threads"); + expect(view.container.querySelector('[data-testid="mcp-widget"]')?.textContent).toBe( + "Rollout Plan Widget", + ); + expect(view.container.querySelector('[data-testid="grokbot-stack"]')?.textContent).toBe( + "Checking CI & reviewing…", + ); + + const footerEl = view.container.querySelector('[data-slot="context-stream-footer"]')!; + expect(footerEl.className).not.toContain("border-t"); + + act(() => { + (bars[0] as HTMLButtonElement).click(); + }); + expect(opened).toEqual([{ subcontext: "/agents/rollout/t/100", anchor: 100 }]); +}); + +test("suppresses live tail when detached in history (!newer.exhausted) and supports span-based reveal", () => { + const items: ContextStreamItem[] = [ + { + kind: "agent/receipt", + key: "r120", + offset: 120, + at: Date.parse("2026-11-25T12:07:00Z"), + by: ITERATE, + span: [105, 120], + data: { summary: "Folded span" }, + }, + ]; + + using view = mount( + <ContextStream + items={items} + newer={{ exhausted: false, loading: false, failed: false, loadNewer: () => {} }} + reveal={112} + rows={{ + "agent/receipt": (item) => ( + <div data-testid="span-row">{(item.data as { summary: string }).summary}</div> + ), + }} + live={[ + { + key: "live-iterate", + by: ITERATE, + kind: "agent/working", + data: {}, + }, + ]} + liveRows={{ + "agent/working": () => <div data-testid="live-tail-should-hide">Live tail</div>, + }} + />, + ); + + expect(view.container.querySelector('[data-testid="span-row"]')?.textContent).toBe("Folded span"); + expect(view.container.querySelector('[data-testid="live-tail-should-hide"]')).toBeNull(); +}); + +test("useWindowedEventPager jumps across sparse offsets via openAt, pages older/newer, trims past maxHeldEvents, and merges back into live tail", async () => { + type Ev = OffsetEvent & { label: string }; + const allEvents: Ev[] = [ + { offset: 10, label: "genesis" }, + { offset: 500, label: "mid-a" }, + { offset: 505, label: "mid-b" }, + { offset: 510, label: "mid-c" }, + { offset: 990, label: "tail-a" }, + { offset: 1000, label: "tail-b" }, + ]; + const tailEvents = allEvents.slice(4); + const readEvents = vi.fn(async (afterOffset: number, limit: number) => + allEvents.filter((e) => e.offset > afterOffset).slice(0, limit), + ); + + let api!: ReturnType<typeof useWindowedEventPager<Ev>>; + function Harness() { + api = useWindowedEventPager({ + tailEvents, + readEvents, + pageSize: 2, + maxHeldEvents: 4, + }); + return ( + <div> + <span data-testid="attached">{String(api.attachedToHead)}</span> + <span data-testid="offsets">{api.events.map((e) => e.offset).join(",")}</span> + <span data-testid="reveal">{String(api.reveal ?? "")}</span> + </div> + ); + } + + using view = mount(<Harness />); + expect(view.container.querySelector('[data-testid="attached"]')?.textContent).toBe("true"); + expect(view.container.querySelector('[data-testid="offsets"]')?.textContent).toBe("990,1000"); + + await act(async () => { + await api.openAt(420); + }); + expect(api).toMatchObject({ attachedToHead: false, reveal: 500 }); + expect(api.events.map((e) => e.offset)).toContain(500); + + await act(async () => { + api.newer.loadNewer(); + }); + expect(api).toMatchObject({ attachedToHead: true }); + expect(api.events.map((e) => e.offset)).toEqual([500, 505, 510, 990, 1000]); + + act(() => { + api.jumpToLatest(); + }); + expect(api.events.map((e) => e.offset)).toEqual([990, 1000]); +}); + +test("useWindowedEventPager keeps pre-tail rows when openAt bridges into live tail, reopens newer if rolling tail advances past history, trims around anchor, and leaves zero gap in dense logs", async () => { + type Ev = OffsetEvent & { label: string }; + const denseEvents: Ev[] = Array.from({ length: 1_090 }, (_, idx) => ({ + offset: idx + 1, + label: `ev-${String(idx + 1)}`, + })); + const readEvents = vi.fn(async (afterOffset: number, limit: number) => + denseEvents.filter((e) => e.offset > afterOffset).slice(0, limit), + ); + + let api!: ReturnType<typeof useWindowedEventPager<Ev>>; + let setTailSlice!: (next: readonly Ev[]) => void; + let setMaxHeld!: (next: number) => void; + function Harness() { + const [tail, setTail] = useState<readonly Ev[]>(() => denseEvents.slice(999, 1_050)); + const [maxHeld, updateMaxHeld] = useState(3_000); + setTailSlice = setTail; + setMaxHeld = updateMaxHeld; + api = useWindowedEventPager({ tailEvents: tail, readEvents, maxHeldEvents: maxHeld }); + return null; + } + + using _view = mount(<Harness />); + + // 1. Opening offset 950 when live tail is 1000..1050 bridges into tail WITHOUT discarding 871..999: + await act(async () => { + await api.openAt(950); + }); + expect(api).toMatchObject({ attachedToHead: true, reveal: 950 }); + expect(api.newer).toMatchObject({ exhausted: true }); + expect(api.events.map((e) => e.offset)).toEqual( + Array.from({ length: 180 }, (_, idx) => 871 + idx), + ); + + // 2. If the rolling live tail later advances to 1040..1090 (past history's 1029), `attachedToHead` + // flips back to `false` and `newer` reopens instead of silently skipping 1030..1039: + act(() => { + setTailSlice(denseEvents.slice(1_039, 1_090)); + }); + expect(api).toMatchObject({ attachedToHead: false }); + expect(api.newer).toMatchObject({ exhausted: false }); + expect(api.events.map((e) => e.offset)).toEqual( + Array.from({ length: 159 }, (_, idx) => 871 + idx), + ); + await act(async () => { + api.newer.loadNewer(); + }); + expect(api).toMatchObject({ attachedToHead: true }); + expect(api.newer).toMatchObject({ exhausted: true }); + expect(api.events.map((e) => e.offset)).toEqual( + Array.from({ length: 220 }, (_, idx) => 871 + idx), + ); + + // 3. Opening offset 500 in a dense log with defaults (pageSize = 80) yields contiguous 421..579 with zero gap: + await act(async () => { + await api.openAt(500); + }); + expect(api).toMatchObject({ attachedToHead: false, reveal: 500 }); + expect(api.events.map((e) => e.offset)).toEqual( + Array.from({ length: 159 }, (_, idx) => 421 + idx), + ); + + // 4. Paging older from 421 loads 341..420 with zero gap: + await act(async () => { + api.older.loadOlder(); + }); + expect(api.events.map((e) => e.offset)).toEqual( + Array.from({ length: 239 }, (_, idx) => 341 + idx), + ); + + // 5. With `maxHeldEvents < pageSize` (40 < 80), opening offset 500 trims around 500 (481..520) so 500 stays loaded: + act(() => { + setMaxHeld(40); + }); + await act(async () => { + await api.openAt(500); + }); + expect(api).toMatchObject({ attachedToHead: false, reveal: 500 }); + expect(api.events.map((e) => e.offset)).toEqual( + Array.from({ length: 40 }, (_, idx) => 481 + idx), + ); + + // 6. Concurrent `loadOlder` + `loadNewer` calls at capacity serialize instead of creating an internal hole: + await act(async () => { + api.older.loadOlder(); + api.newer.loadNewer(); + }); + expect(api.events.map((e) => e.offset)).toEqual( + Array.from({ length: 40 }, (_, idx) => 401 + idx), + ); +}); + +test("useWindowedEventPager does not skip offsets if rolling tail advances while a short read is in flight", async () => { + type Ev = OffsetEvent & { label: string }; + let serverEvents: Ev[] = Array.from({ length: 1_029 }, (_, idx) => ({ + offset: idx + 1, + label: `ev-${String(idx + 1)}`, + })); + let releaseShortRead!: () => void; + const readEvents = vi.fn(async (afterOffset: number, limit: number) => { + const snapshot = serverEvents.filter((e) => e.offset > afterOffset).slice(0, limit); + if (afterOffset === 949 && limit === 80) { + await new Promise<void>((resolve) => { + releaseShortRead = resolve; + }); + } + return snapshot; + }); + + let api!: ReturnType<typeof useWindowedEventPager<Ev>>; + let setTailSlice!: (next: readonly Ev[]) => void; + function Harness() { + const [tail, setTail] = useState<readonly Ev[]>(() => serverEvents.slice(999, 1_029)); + setTailSlice = setTail; + api = useWindowedEventPager({ tailEvents: tail, readEvents }); + return null; + } + + using _view = mount(<Harness />); + + const openPromise = api.openAt(950); + await act(async () => { + await Promise.resolve(); + }); + + // While the short read (seeing EOF at 1029) is still in flight, new events 1030..1080 land and + // the rolling tail advances to 1040..1080: + serverEvents = Array.from({ length: 1_080 }, (_, idx) => ({ + offset: idx + 1, + label: `ev-${String(idx + 1)}`, + })); + act(() => { + setTailSlice(serverEvents.slice(1_039, 1_080)); + }); + + await act(async () => { + releaseShortRead(); + await openPromise; + }); + + // `provenUpTo` stays at 1029 (not raised to 1039), so `newer` remains open to fetch 1030..1039! + expect(api).toMatchObject({ attachedToHead: false, reveal: 950 }); + expect(api.newer).toMatchObject({ exhausted: false }); + expect(api.events.map((e) => e.offset)).toEqual( + Array.from({ length: 159 }, (_, idx) => 871 + idx), + ); +}); + +test("useWindowedEventPager clears loading flags when a concurrent openAt fails so paging never gets stuck", async () => { + type Ev = OffsetEvent & { label: string }; + const denseEvents: Ev[] = Array.from({ length: 600 }, (_, idx) => ({ + offset: idx + 1, + label: `ev-${String(idx + 1)}`, + })); + let releaseOlderRead!: () => void; + let failNextProbe = false; + const readEvents = vi.fn(async (afterOffset: number, limit: number) => { + if (failNextProbe && limit === 1) { + failNextProbe = false; + throw new Error("transient read failure"); + } + if (afterOffset === 140 && limit === 80) { + await new Promise<void>((resolve) => { + releaseOlderRead = resolve; + }); + } + return denseEvents.filter((e) => e.offset > afterOffset).slice(0, limit); + }); + + let api!: ReturnType<typeof useWindowedEventPager<Ev>>; + function Harness() { + api = useWindowedEventPager({ tailEvents: denseEvents.slice(550), readEvents }); + return null; + } + + using _view = mount(<Harness />); + + await act(async () => { + await api.openAt(300); + }); + expect(api.events[0]).toMatchObject({ offset: 221 }); + + // Start an older page read (scans 140..220) and keep it pending: + act(() => { + api.older.loadOlder(); + }); + expect(api.older).toMatchObject({ loading: true }); + + // Jump to another historical offset whose anchor probe rejects: + failNextProbe = true; + await act(async () => { + await expect(api.openAt(100)).rejects.toThrow("transient read failure"); + releaseOlderRead(); + }); + + // Loading flags are cleared, and subsequent `loadNewer` pages cleanly instead of being stuck! + expect(api.older).toMatchObject({ loading: false }); + expect(api.newer).toMatchObject({ loading: false, exhausted: false }); + await act(async () => { + api.newer.loadNewer(); + }); + expect(api.events.at(-1)).toMatchObject({ offset: 459 }); +}); + +test("renders the three-dots corner menu on an in-progress live row and opens its provenance", async () => { + const inspected: string[] = []; + using view = mount( + <ContextStream + items={[]} + older={{ exhausted: true, loading: false, failed: false, loadOlder: () => {} }} + agentName="iterate" + live={[ + { + key: "live:iterate", + by: { id: "/agents/em", name: "iterate", kind: "mind" }, + kind: "agent/working", + text: "Verifying preview Workers…", + menu: { + copyItems: [ + { label: "Copy event range (#18..#21)", value: "/agents/em#18..#21", mono: true }, + ], + provenance: "Streaming claude-fable-5-2 (#18..#21)", + actions: [{ label: "Inspect live trace", onSelect: () => inspected.push("live:18") }], + }, + }, + ]} + />, + ); + + expect(view.container.textContent).not.toContain("#18..#21"); + const moreBtn = view.container.querySelector<HTMLButtonElement>( + '[data-slot="context-stream-tail"] [data-slot="message-more-trigger"]', + ); + expect(moreBtn).not.toBeNull(); + + await act(async () => { + moreBtn!.click(); + }); + + const menu = document.body.querySelector('[data-slot="message-more-menu"]'); + expect(menu?.textContent).toContain("Streaming claude-fable-5-2 (#18..#21)"); + const actionBtn = Array.from(menu?.querySelectorAll("button") || []).find((b) => + b.textContent?.includes("Inspect live trace"), + ); + expect(actionBtn).toBeDefined(); + await act(async () => { + actionBtn!.click(); + }); + expect(inspected).toEqual(["live:18"]); +}); + +test("does not snap scrollTop back to bottom when the reader scrolls up (mobile touch & wheel)", async () => { + const manyItems: ContextStreamItem[] = Array.from({ length: 30 }, (_, idx) => ({ + kind: "message", + key: `m-${String(idx + 1)}`, + offset: idx + 1, + at: 1_700_000_000_000 + idx * 60_000, + by: { id: "/members/jonas", name: "jonas", kind: "person" }, + text: `Message line #${String(idx + 1)}`, + })); + + using view = mount( + <ContextStream + items={manyItems} + older={{ exhausted: true, loading: false, failed: false, loadOlder: () => {} }} + agentName="iterate" + />, + ); + + const scroller = view.container.querySelector<HTMLDivElement>('[data-slot="virtual-log"]')!; + expect(scroller).not.toBeNull(); + Object.defineProperty(scroller, "scrollHeight", { configurable: true, get: () => 2_400 }); + scroller.scrollTop = 1_800; + + // Simulate mobile touch scroll upward (`y` moving from 200 -> 420 while scrollTop moves 1800 -> 900) + await act(async () => { + scroller.dispatchEvent( + new TouchEvent("touchstart", { bubbles: true, touches: [{ clientY: 200 } as Touch] }), + ); + scroller.dispatchEvent( + new TouchEvent("touchmove", { bubbles: true, touches: [{ clientY: 420 } as Touch] }), + ); + scroller.scrollTop = 900; + scroller.dispatchEvent(new Event("scroll")); + scroller.dispatchEvent(new TouchEvent("touchend", { bubbles: true, touches: [] })); + }); + + // `scrollTop` MUST stay at 900 (not get reset to 1800 by `setAtEnd(false)` re-rendering VirtualLog!) + expect(scroller).toMatchObject({ scrollTop: 900 }); + expect(view.container.querySelector('[aria-label^="Scroll to bottom"]')).not.toBeNull(); +}); + +function mount(element: ReactElement) { + 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 }); + const container = document.createElement("div"); + document.body.appendChild(container); + const root = createRoot(container); + act(() => { + root.render(element); + }); + return { + container, + root, + [Symbol.dispose]() { + act(() => root.unmount()); + container.remove(); + document.body.replaceChildren(); + 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]; + }, + }; +}
A src/components/context-stream/context-stream.ts
@@ -0,0 +1,26 @@ +export { ContextStream } from "./context-stream-view.tsx"; +export { + defaultActorIdentity, + type ContextStreamActorIdentity, + type ContextStreamActorKind, + type ContextStreamActorRef, + type ContextStreamCopyItem, + type ContextStreamCustomItem, + type ContextStreamDayItem, + type ContextStreamFileRef, + type ContextStreamItem, + type ContextStreamLiveEntry, + type ContextStreamMenuAction, + type ContextStreamMessageItem, + type ContextStreamMessageMenu, + type ContextStreamOpenTarget, + type ContextStreamSubcontextItem, + type SubcontextPreview, +} from "./context-stream-model.ts"; +export { + mergeEventsByOffset, + trimEventWindow, + useWindowedEventPager, + type OffsetEvent, + type ReadEventsAfter, +} from "./windowed-pager.ts";
A src/components/context-stream/windowed-pager.ts
@@ -0,0 +1,391 @@ +// Two-window pager for infinite scrolling and offset deep-linking over sparse append-only logs: +// - When no history jump is active (`!history`), the view reads directly from the live `tailEvents` +// window (`useIterateContext`) with zero extra state or copies. +// - Calling `openAt(targetOffset)` opens a bounded `history` window centered around `targetOffset` +// (snapping across sparse offset gaps via `readEvents(targetOffset - 1, 1)`), paging backward +// (`loadOlder`) and forward (`loadNewer`), trimming past `maxHeldEvents`, and bridging seamlessly +// into `tailEvents` whenever `provenUpTo >= tailFirst - 1` (reopening `newer` paging automatically +// if a rolling `tailEvents` window advances past `provenUpTo + 1`). +import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { + NEWER_EXHAUSTED, + OLDER_EXHAUSTED, + type NewerPages, + type OlderPages, +} from "#/components/virtual-log/older-pages.ts"; + +export type OffsetEvent = { offset: number }; + +/** Reads up to `limit` stored events strictly after `afterOffset` (`offset > afterOffset`), ordered + * ascending by `offset` (the contract of `itx.readEvents`). */ +export type ReadEventsAfter<E extends OffsetEvent> = ( + afterOffset: number, + limit: number, +) => Promise<readonly E[]>; + +/** Merges two ascending-offset event slices, deduplicating by `offset`. */ +export function mergeEventsByOffset<E extends OffsetEvent>( + left: readonly E[], + right: readonly E[], +): E[] { + if (left.length === 0) return [...right]; + if (right.length === 0) return [...left]; + const byOffset = new Map<number, E>(); + for (const item of left) byOffset.set(item.offset, item); + for (const item of right) byOffset.set(item.offset, item); + return [...byOffset.values()].toSorted((a, b) => a.offset - b.offset); +} + +/** Trims `events` to at most `maxHeld` items, dropping from the side opposite `keepEnd`. */ +export function trimEventWindow<E extends OffsetEvent>( + events: readonly E[], + maxHeld: number, + keepEnd: "start" | "end", +): readonly E[] { + if (events.length <= maxHeld) return events; + return keepEnd === "end" ? events.slice(events.length - maxHeld) : events.slice(0, maxHeld); +} + +/** Trims `events` to at most `maxHeld` contiguous items centered around `targetOffset` so the + * requested anchor row is always retained even when `maxHeld < 2 * pageSize`. */ +function trimAroundOffset<E extends OffsetEvent>( + events: readonly E[], + maxHeld: number, + targetOffset: number, +): readonly E[] { + if (events.length <= maxHeld) return events; + const foundIndex = events.findIndex((e) => e.offset >= targetOffset); + const anchorIndex = foundIndex >= 0 ? foundIndex : events.length - 1; + const halfBefore = Math.floor((maxHeld - 1) / 2); + const start = Math.min(Math.max(0, anchorIndex - halfBefore), events.length - maxHeld); + return events.slice(start, start + maxHeld); +} + +/** Reads a gap-free slice of stored events in `(scanFrom, olderCursor]` (up to `pageSize` items + * immediately preceding `olderCursor`) so exponential step growth across sparse gaps never leaves + * unread rows between the returned slice and `olderCursor`. */ +async function readOlderSlice<E extends OffsetEvent>( + readEvents: ReadEventsAfter<E>, + scanFrom: number, + olderCursor: number, + pageSize: number, +): Promise<{ slice: readonly E[]; nextOlderCursor: number }> { + const firstBatch = await readEvents(scanFrom, pageSize); + const firstBelow = firstBatch.filter((e) => e.offset <= olderCursor); + if (firstBelow.length === 0) { + return { slice: [], nextOlderCursor: scanFrom }; + } + const lastFetched = firstBatch.at(-1)!; + if (firstBatch.length < pageSize || lastFetched.offset >= olderCursor) { + return { slice: firstBelow, nextOlderCursor: scanFrom }; + } + let tailBelow: E[] = [...firstBelow]; + let cursor = lastFetched.offset; + while (cursor < olderCursor) { + const batch = await readEvents(cursor, pageSize); + if (batch.length === 0) break; + for (const item of batch) { + if (item.offset <= olderCursor) tailBelow.push(item); + } + if (tailBelow.length > pageSize) { + tailBelow = tailBelow.slice(tailBelow.length - pageSize); + } + const batchLast = batch.at(-1)!; + if (batch.length < pageSize || batchLast.offset >= olderCursor) break; + cursor = batchLast.offset; + } + const lowestKept = tailBelow[0]!.offset; + return { slice: tailBelow, nextOlderCursor: Math.max(0, lowestKept - 1) }; +} + +type HistoryWindow<E extends OffsetEvent> = { + events: readonly E[]; + /** Highest offset below `events` proven to have no unread gap up to `events[0]`. */ + olderCursor: number; + olderStep: number; + olderExhausted: boolean; + olderLoading: boolean; + olderFailed: boolean; + newerLoading: boolean; + newerFailed: boolean; + /** Highest offset covered by `events` (or proven empty at the time of a read). */ + provenUpTo: number; + /** True only when `tailEvents` is empty and forward reads hit EOF of the log. */ + reachedEof: boolean; + revealOffset?: number; +}; + +export function useWindowedEventPager<E extends OffsetEvent>({ + tailEvents, + tailOlder = OLDER_EXHAUSTED, + readEvents, + pageSize = 80, + maxHeldEvents = 3_000, +}: { + tailEvents: readonly E[]; + tailOlder?: OlderPages; + readEvents?: ReadEventsAfter<E>; + pageSize?: number; + maxHeldEvents?: number; +}): { + events: readonly E[]; + older: OlderPages; + newer: NewerPages; + attachedToHead: boolean; + reveal: number | undefined; + openAt: (targetOffset: number) => Promise<void>; + jumpToLatest: () => void; +} { + const safePageSize = Math.max(1, pageSize); + const safeMaxHeld = Math.max(1, maxHeldEvents); + const [history, setHistory] = useState<HistoryWindow<E> | null>(null); + const [tailReveal, setTailReveal] = useState<number | undefined>(undefined); + const generationRef = useRef(0); + const tailRef = useRef(tailEvents); + + useLayoutEffect(() => { + tailRef.current = tailEvents; + }, [tailEvents]); + + const tailFirst = tailEvents[0]?.offset; + let isCaughtUp = true; + if (history) { + if (tailFirst !== undefined) { + isCaughtUp = history.provenUpTo >= tailFirst - 1; + } else { + isCaughtUp = history.reachedEof; + } + } + + const jumpToLatest = useCallback(() => { + generationRef.current += 1; + setTailReveal(undefined); + setHistory(null); + }, []); + + const openAt = useCallback( + async (targetOffset: number) => { + const currentTail = tailRef.current; + const currentFirst = currentTail[0]?.offset; + const currentLast = currentTail.at(-1)?.offset; + if ( + currentFirst !== undefined && + currentLast !== undefined && + targetOffset >= currentFirst && + targetOffset <= currentLast + ) { + const snappedInTail = + currentTail.find((e) => e.offset >= targetOffset)?.offset ?? targetOffset; + generationRef.current += 1; + setHistory(null); + setTailReveal(snappedInTail); + return; + } + if (!readEvents) { + setTailReveal(targetOffset); + return; + } + + const gen = ++generationRef.current; + // Advancing `generationRef` cancels any in-flight `older`/`newer` page read, so clear its + // loading flag immediately — otherwise a failing `openAt` would leave paging stuck loading. + setHistory((prev) => + prev && (prev.olderLoading || prev.newerLoading) + ? { ...prev, olderLoading: false, newerLoading: false } + : prev, + ); + const anchorProbe = await readEvents(Math.max(0, targetOffset - 1), 1); + if (gen !== generationRef.current) return; + const snappedAnchor = anchorProbe[0]?.offset ?? targetOffset; + const backStep = Math.min(snappedAnchor, safePageSize); + const backStart = Math.max(0, snappedAnchor - backStep); + // Capture `tailFirstBeforeSlice` BEFORE dispatching `afterSlice` so a short read only raises + // `provenUpTo` to an offset that already existed before the read began (never to a newer + // rolling-tail start that arrived while the read was in flight). + const tailFirstBeforeSlice = tailRef.current[0]?.offset; + const [beforeSlice, afterSlice] = await Promise.all([ + readEvents(backStart, safePageSize), + readEvents(Math.max(0, snappedAnchor - 1), safePageSize), + ]); + if (gen !== generationRef.current) return; + + const unbounded = mergeEventsByOffset(beforeSlice, afterSlice); + const combined = trimAroundOffset(unbounded, safeMaxHeld, snappedAnchor); + const lowestKept = combined[0]?.offset; + const droppedOlder = lowestKept !== undefined && lowestKept > (unbounded[0]?.offset ?? 0); + const initialOlderCursor = droppedOlder ? Math.max(backStart, lowestKept - 1) : backStart; + const combinedLast = combined.at(-1)?.offset; + const unboundedLast = unbounded.at(-1)?.offset; + const keptForwardEdge = combinedLast === unboundedLast; + let provenUpTo = combinedLast ?? initialOlderCursor; + if ( + keptForwardEdge && + afterSlice.length < safePageSize && + tailFirstBeforeSlice !== undefined + ) { + provenUpTo = Math.max(provenUpTo, tailFirstBeforeSlice - 1); + } + + setTailReveal(undefined); + setHistory({ + events: combined, + olderCursor: initialOlderCursor, + olderStep: safePageSize, + olderExhausted: initialOlderCursor === 0, + olderLoading: false, + olderFailed: false, + newerLoading: false, + newerFailed: false, + provenUpTo, + reachedEof: keptForwardEdge && afterSlice.length < safePageSize, + revealOffset: snappedAnchor, + }); + }, + [readEvents, safePageSize, safeMaxHeld], + ); + + const loadHistoryOlder = useCallback(() => { + if (!readEvents) return; + setHistory((prev) => { + // Serialize `older` and `newer` reads so concurrent capacity trims cannot create an internal gap. + if ( + !prev || + prev.olderLoading || + prev.newerLoading || + prev.olderExhausted || + prev.olderFailed + ) { + return prev; + } + const gen = generationRef.current; + const scanFrom = Math.max(0, prev.olderCursor - prev.olderStep); + const targetCursor = prev.olderCursor; + const currentStep = prev.olderStep; + void readOlderSlice(readEvents, scanFrom, targetCursor, safePageSize).then( + ({ slice, nextOlderCursor }) => { + if (gen !== generationRef.current) return; + setHistory((curr) => { + if (!curr) return null; + if (curr.olderCursor !== targetCursor) { + return curr.olderLoading ? { ...curr, olderLoading: false } : curr; + } + const unbounded = mergeEventsByOffset(slice, curr.events); + const droppedNewer = unbounded.length > safeMaxHeld; + const merged = trimEventWindow(unbounded, safeMaxHeld, "start"); + const mergedLast = merged.at(-1)?.offset; + return { + ...curr, + events: merged, + olderCursor: nextOlderCursor, + olderStep: slice.length === 0 ? currentStep * 2 : safePageSize, + olderExhausted: nextOlderCursor === 0, + olderLoading: false, + provenUpTo: droppedNewer ? (mergedLast ?? nextOlderCursor) : curr.provenUpTo, + reachedEof: droppedNewer ? false : curr.reachedEof, + }; + }); + }, + () => { + if (gen !== generationRef.current) return; + setHistory((curr) => + curr ? { ...curr, olderLoading: false, olderFailed: true, olderExhausted: true } : null, + ); + }, + ); + return { ...prev, olderLoading: true }; + }); + }, [readEvents, safePageSize, safeMaxHeld]); + + const loadHistoryNewer = useCallback(() => { + if (!readEvents) return; + setHistory((prev) => { + if (!prev || prev.olderLoading || prev.newerLoading || prev.newerFailed) return prev; + const tailFirstBeforeRead = tailRef.current[0]?.offset; + const alreadyBridged = + tailFirstBeforeRead !== undefined + ? prev.provenUpTo >= tailFirstBeforeRead - 1 + : prev.reachedEof; + if (alreadyBridged) return prev; + const highest = Math.max(prev.events.at(-1)?.offset ?? prev.olderCursor, prev.provenUpTo); + const gen = generationRef.current; + void readEvents(highest, safePageSize).then( + (fetched) => { + if (gen !== generationRef.current) return; + setHistory((curr) => { + if (!curr) return null; + const currHighest = Math.max( + curr.events.at(-1)?.offset ?? curr.olderCursor, + curr.provenUpTo, + ); + if (currHighest !== highest) { + return curr.newerLoading ? { ...curr, newerLoading: false } : curr; + } + const unbounded = mergeEventsByOffset(curr.events, fetched); + const merged = trimEventWindow(unbounded, safeMaxHeld, "end"); + const droppedOlder = unbounded.length > merged.length; + const lowestKept = merged[0]?.offset; + const mergedLast = merged.at(-1)?.offset; + const hitEof = fetched.length < safePageSize; + let provenUpTo = mergedLast ?? curr.provenUpTo; + if (hitEof && tailFirstBeforeRead !== undefined) { + provenUpTo = Math.max(provenUpTo, tailFirstBeforeRead - 1); + } + return { + ...curr, + events: merged, + olderCursor: + droppedOlder && lowestKept !== undefined + ? Math.max(curr.olderCursor, lowestKept - 1) + : curr.olderCursor, + olderExhausted: curr.olderExhausted && !droppedOlder, + newerLoading: false, + provenUpTo, + reachedEof: hitEof, + }; + }); + }, + () => { + if (gen !== generationRef.current) return; + setHistory((curr) => (curr ? { ...curr, newerLoading: false, newerFailed: true } : null)); + }, + ); + return { ...prev, newerLoading: true }; + }); + }, [readEvents, safePageSize, safeMaxHeld]); + + const older: OlderPages = useMemo(() => { + if (!history) return tailOlder; + return { + loadOlder: loadHistoryOlder, + loading: history.olderLoading, + exhausted: history.olderExhausted, + ...(history.olderFailed && { failed: true }), + }; + }, [history, tailOlder, loadHistoryOlder]); + + const newer: NewerPages = useMemo(() => { + if (isCaughtUp || !history) return NEWER_EXHAUSTED; + return { + loadNewer: loadHistoryNewer, + loading: history.newerLoading, + exhausted: false, + ...(history.newerFailed && { failed: true }), + }; + }, [isCaughtUp, history, loadHistoryNewer]); + + const events = useMemo(() => { + if (!history) return tailEvents; + if (!isCaughtUp) return history.events; + return mergeEventsByOffset(history.events, tailEvents); + }, [history, isCaughtUp, tailEvents]); + + return { + events, + older, + newer, + attachedToHead: isCaughtUp, + reveal: history ? history.revealOffset : tailReveal, + openAt, + jumpToLatest, + }; +}
M src/components/context-view/context-view.tsx
@@ -145,7 +145,7 @@ "--offset-width": `${String(String(events.at(-1)?.offset ?? 0).length + 1)}ch`, } as CSSProperties; return ( - <div className={cn("flex min-h-0 min-w-0 flex-col", className)} style={gutter}> + <div className={cn("@container flex min-h-0 min-w-0 flex-col", className)} style={gutter}> <div className={columnClassName}> <ContextStrip title={title} @@ -303,9 +303,9 @@ onStateChange: (patch: Partial<ContextViewState>) => void; }) { return ( - <div className="flex flex-wrap items-center gap-x-4 gap-y-1 px-3 sm:px-4 py-1.5"> - <div className="flex min-w-0 items-baseline gap-4"> - <div className="min-w-0 truncate text-sm">{title}</div> + <div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-2.5 py-1.5 @2xl:px-4"> + <div className="flex min-w-0 items-baseline gap-3"> + {title ? <div className="min-w-0 truncate text-sm">{title}</div> : null} <span className="shrink-0 text-xs text-muted-foreground tabular-nums"> {count} {caughtUp ? "" : " · loading"} @@ -313,12 +313,12 @@ </span> </div> <PresenceStrip - className="hidden min-w-0 xl:flex" + className="hidden min-w-0 @3xl:flex" actors={presence.actors} rpcStubs={presence.rpcStubs} onPick={(actor) => onStateChange({ actor: pickedActor === actor ? undefined : actor })} /> - <div className="ml-auto flex items-center gap-3 text-xs"> + <div className="ml-auto flex items-center gap-2 text-xs"> <button type="button" onClick={() => onStateChange({ filter: filtering ? undefined : true })}
M src/components/context-view/event-row-format.ts
@@ -21,11 +21,10 @@ return `+${String(Math.floor(minutes / 60))}h${String(minutes % 60)}m`; } -/** The frame every row shares: full width, the columns on one line from `sm` (a phone wraps the - * body above the rest), 26px tall, the hover, the inspected row's left bar. Rows are buttons - * (inspect, or open a fold). */ +/** The frame every row shares: full width, columns on one line from `@md` (`448px` container width; + * narrower containers wrap the body above the meta line), 26px tall, hover, and inspected left bar. */ export const rowClass = (selected?: boolean) => cn( - "flex w-full min-w-0 flex-wrap items-baseline gap-x-3.5 px-3 sm:px-4 py-[3px] text-left hover:bg-muted/60 max-sm:gap-x-2 max-sm:py-1.5 sm:flex-nowrap", + "flex w-full min-w-0 flex-wrap items-baseline gap-x-2 px-2.5 py-[3px] text-left hover:bg-muted/60 @max-md:py-1 @md:flex-nowrap @2xl:px-4 @3xl:gap-x-3.5", selected && "bg-muted shadow-[inset_2px_0_0_var(--color-foreground)] hover:bg-muted", );
M src/components/context-view/event-row.tsx
Not shown: the change is larger than this page shows. A clone has it.
M src/components/context-view/feed-rows.tsx
Not shown: the change is larger than this page shows. A clone has it.
M src/components/dash/dash.tsx
Not shown: the change is larger than this page shows. A clone has it.
M src/components/virtual-log/older-pages.ts
Not shown: the change is larger than this page shows. A clone has it.
M src/components/virtual-log/use-reader.ts
Not shown: the change is larger than this page shows. A clone has it.
M src/components/virtual-log/virtual-log.tsx
Not shown: the change is larger than this page shows. A clone has it.
M src/lib/principal-label.ts
Not shown: the change is larger than this page shows. A clone has it.
A src/test-support/fake-catalog.ts
Not shown: the change is larger than this page shows. A clone has it.