Multiplayer agent harness for work.
Drop the unused session adopt route and run kept web-ui tests against real modules (#2255)
Regan Bell2208ede0b58c
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex 7a0e6b42b..e550f72bf 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -1913,21 +1913,6 @@ const apiRoutes: readonly WebRoute[] = [);},},- {- method: "POST",- path: "/api/sessions/:id/adopt",- handle: async (c) => {- const p = await readJson<{ parentSessionId?: unknown }>(c.req, c.res);- if (!p) return;- if (typeof p.parentSessionId !== "string") return json(c.res, 400, { error: "bad_request" });- return relayCore(- c.res,- "POST",- `/v1/sessions/${encodeURIComponent(c.params.id!)}/adopt`,- JSON.stringify({ principalId: c.user, parentSessionId: p.parentSessionId }),- );- },- },{method: "POST",path: "/api/sessions/:id/detach",diff --git a/plugins/web-ui/src/settings.ts b/plugins/web-ui/src/settings.tsindex ae1df7956..5d75984e0 100644--- a/plugins/web-ui/src/settings.ts+++ b/plugins/web-ui/src/settings.ts@@ -10,7 +10,7 @@ import { sessionsState, setWebOnly } from "./sessions";import { errMessage } from "../../chassis/src/errors";import { importTheme, isPalette, themeCss, themeTokens, type Palette } from "./theme-import";-export type ThemeChoice = "light" | "dark" | "system" | "custom";+type ThemeChoice = "light" | "dark" | "system" | "custom";const THEME_KEY = "theme";const CUSTOM_THEME_KEY = "theme:custom";@@ -28,7 +28,7 @@ const THEME_OPTIONS: Array<{ value: ThemeChoice; label: string; glyph: IconNodelet settingsHost: HTMLElement | null = null;let themeImportError: string | null = null;-export function storedTheme(): ThemeChoice {+function storedTheme(): ThemeChoice {try {const stored = localStorage.getItem(THEME_KEY);if (stored === "light" || stored === "dark") return stored;@@ -39,7 +39,7 @@ export function storedTheme(): ThemeChoice {return "system";}-export function storedCustomTheme(): Palette | null {+function storedCustomTheme(): Palette | null {try {const parsed: unknown = JSON.parse(localStorage.getItem(CUSTOM_THEME_KEY) ?? "null");return isPalette(parsed) ? parsed : null;@@ -95,7 +95,7 @@ export function applyTheme(): void {publishTheme();}-export function setTheme(choice: ThemeChoice): void {+function setTheme(choice: ThemeChoice): void {themeImportError = null;try {if (choice === "system") localStorage.removeItem(THEME_KEY);@@ -107,12 +107,12 @@ export function setTheme(choice: ThemeChoice): void {drawSettings();}-export function installCustomTheme(palette: Palette): void {+function installCustomTheme(palette: Palette): void {storeCustomTheme(palette);setTheme("custom");}-export function removeCustomTheme(): void {+function removeCustomTheme(): void {const wasActive = storedTheme() === "custom";storeCustomTheme(null);setTheme(wasActive ? "system" : storedTheme());diff --git a/plugins/web-ui/test/app-shell-theme.test.ts b/plugins/web-ui/test/app-shell-theme.test.tsindex bb9ef19fc..696a9f7fe 100644--- a/plugins/web-ui/test/app-shell-theme.test.ts+++ b/plugins/web-ui/test/app-shell-theme.test.ts@@ -1,13 +1,10 @@import { test } from "node:test";import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import { stripTypeScriptTypes } from "node:module";-import { runInNewContext } from "node:vm";-import { isPalette, themeCss, themeTokens } from "../src/theme-import.ts";import { JSDOM, type DOMWindow } from "jsdom";+import { createServer } from "vite";import { appShellHtml } from "../../../src/deploy/app-shell.ts";+import { harness } from "./deep-link-boot-fixture.ts";-const settings = readFileSync(new URL("../src/settings.ts", import.meta.url), "utf8");const keys = ["--background", "--foreground", "--secondary", "--muted-foreground", "--border", "--brand-accent"];test("the app bar accepts the chat palette only from its portal iframe, even while closed", () => {@@ -50,27 +47,45 @@ test("the app bar accepts the chat palette only from its portal iframe, even whidom.window.close();});-test("embedded chat publishes active colors and tracks theme changes from other tabs", () => {+test("embedded chat publishes active colors and tracks theme changes from other tabs", async (t) => {const dom = new JSDOM("<iframe></iframe>", { url: "https://portal.example.com", runScripts: "outside-only" });const frame = dom.window.document.querySelector("iframe")!.contentWindow as unknown as DOMWindow;const messages: Array<{ data: { dark: boolean; colors: Record<string, string> }; origin: string }> = [];dom.window.postMessage = (data, origin) => messages.push({ data, origin: origin as string });- Object.assign(frame, { isPalette, themeCss, themeTokens });- frame.eval("window.matchMedia = () => ({ matches: false, addEventListener() {} });");- const source =- settings.slice(settings.indexOf("export function storedTheme"), settings.indexOf("let themeParentOrigin")) +- settings.slice(settings.indexOf("let themeParentOrigin"), settings.indexOf("export function setTheme")) +- settings.slice(settings.indexOf("export function watchSystemTheme"), settings.indexOf("function themeSwatches"));- frame.eval(- stripTypeScriptTypes(- 'const THEME_KEY = "theme", CUSTOM_THEME_KEY = "theme:custom", CUSTOM_THEME_STYLE_ID = "custom-theme";\n' +- source.replaceAll("export function", "function"),- ),- );+ frame.document.body.innerHTML = '<div id="app"></div>';+ frame.matchMedia = () =>+ ({ matches: false, addEventListener() {}, removeEventListener() {} }) as unknown as MediaQueryList;+ const descriptors = new Map<string, PropertyDescriptor | undefined>();+ for (const [key, value] of Object.entries({+ window: frame,+ document: frame.document,+ location: frame.location,+ history: frame.history,+ localStorage: frame.localStorage,+ sessionStorage: frame.sessionStorage,+ navigator: frame.navigator,+ HTMLElement: frame.HTMLElement,+ Element: frame.Element,+ Node: frame.Node,+ customElements: frame.customElements,+ getComputedStyle: frame.getComputedStyle.bind(frame),+ })) {+ descriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));+ Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });+ }+ const vite = await createServer({ server: { middlewareMode: true, hmr: false, ws: false }, appType: "custom" });+ t.after(async () => {+ await vite.close();+ for (const [key, descriptor] of descriptors) {+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);+ else delete (globalThis as Record<string, unknown>)[key];+ }+ dom.window.close();+ });+ await vite.ssrLoadModule("/src/shell.ts");const style = frame.document.createElement("style");style.textContent = `:root { ${keys.map((key) => `${key}: #abcdef;`).join(" ")} }`;frame.document.head.appendChild(style);- frame.eval("applyTheme(); watchSystemTheme();");frame.dispatchEvent(new frame.MessageEvent("message", {source: dom.window as unknown as Window,@@ -100,25 +115,22 @@ test("embedded chat publishes active colors and tracks theme changes from otherframe.localStorage.clear();frame.dispatchEvent(new frame.StorageEvent("storage", { key: null }));assert.equal(messages.at(-1)!.data.dark, false);- dom.window.close();});test("theme-only startup stops before authenticated chat boot", async () => {- const shell = readFileSync(new URL("../src/shell.ts", import.meta.url), "utf8");- const boot = stripTypeScriptTypes(shell.slice(shell.indexOf("export async function boot():")).replace("export ", ""));- const location = { search: "?slug=demo&embed=1&themeOnly=1" };- let started = false;- const run = runInNewContext(boot + "; boot", {- location,- URLSearchParams,- captureConnectionReturn: () => {- started = true;- throw new Error("chat boot");- },- }) as () => Promise<void>;- await run();- assert.equal(started, false);- location.search = "?slug=demo&embed=1";- await assert.rejects(run(), /chat boot/);- assert.equal(started, true);+ const themeOnly = await harness({ path: "/?slug=demo&embed=1&themeOnly=1" });+ try {+ await themeOnly.boot();+ assert.deepEqual(themeOnly.requests, []);+ } finally {+ await themeOnly.close();+ }+ const chat = await harness({ path: "/?slug=demo&embed=1" });+ try {+ chat.releaseSessions();+ await chat.boot();+ assert.ok(chat.requests.includes("/me"));+ } finally {+ await chat.close();+ }});diff --git a/plugins/web-ui/test/browser-env.ts b/plugins/web-ui/test/browser-env.tsnew file mode 100644index 000000000..24e818b2e--- /dev/null+++ b/plugins/web-ui/test/browser-env.ts@@ -0,0 +1,99 @@+import { JSDOM, type ConstructorOptions } from "jsdom";+import { createServer, type PluginOption, type ViteDevServer } from "vite";++export interface BrowserEnv {+ dom: JSDOM;+ vite: ViteDevServer;+ close: () => Promise<void>;+}++export async function browserEnv(+ options: {+ dom?: ConstructorOptions;+ html?: string;+ fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;+ plugins?: PluginOption[];+ } = {},+): Promise<BrowserEnv> {+ const dom = new JSDOM(options.html ?? '<!doctype html><div id="app"></div><main id="main"></main>', {+ url: "http://localhost/",+ pretendToBeVisual: true,+ ...options.dom,+ });+ Object.defineProperty(dom.window, "matchMedia", {+ value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),+ });+ dom.window.HTMLElement.prototype.getAnimations = () => [];+ dom.window.HTMLElement.prototype.scrollIntoView = () => {};+ const timers = new Set<ReturnType<typeof setTimeout>>();+ const realSetTimeout = globalThis.setTimeout;+ const realSetInterval = globalThis.setInterval;+ const track = <T extends ReturnType<typeof setTimeout>>(id: T): T => (timers.add(id), id);+ const globals: Record<string, unknown> = {+ window: dom.window,+ document: dom.window.document,+ location: dom.window.location,+ history: dom.window.history,+ localStorage: dom.window.localStorage,+ sessionStorage: dom.window.sessionStorage,+ navigator: dom.window.navigator,+ HTMLElement: dom.window.HTMLElement,+ Element: dom.window.Element,+ Node: dom.window.Node,+ Event: dom.window.Event,+ CustomEvent: dom.window.CustomEvent,+ InputEvent: dom.window.InputEvent,+ KeyboardEvent: dom.window.KeyboardEvent,+ MouseEvent: dom.window.MouseEvent,+ PointerEvent: dom.window.PointerEvent,+ customElements: dom.window.customElements,+ getComputedStyle: dom.window.getComputedStyle.bind(dom.window),+ ResizeObserver: class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ EventSource: undefined,+ fetch: options.fetch ?? globalThis.fetch,+ setTimeout: ((...args: Parameters<typeof setTimeout>) => track(realSetTimeout(...args))) as typeof setTimeout,+ setInterval: ((...args: Parameters<typeof setInterval>) => track(realSetInterval(...args))) as typeof setInterval,+ requestAnimationFrame: (callback: FrameRequestCallback) =>+ track(realSetTimeout(() => callback(Date.now()), 0)) as unknown as number,+ cancelAnimationFrame: clearTimeout,+ };+ const descriptors = new Map<string, PropertyDescriptor | undefined>();+ for (const [key, value] of Object.entries(globals)) {+ descriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));+ Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });+ }+ const restore = () => {+ for (const id of timers) clearTimeout(id);+ for (const [key, descriptor] of descriptors) {+ if (descriptor) Object.defineProperty(globalThis, key, descriptor);+ else Reflect.deleteProperty(globalThis, key);+ }+ dom.window.close();+ };+ let vite: ViteDevServer;+ try {+ vite = await createServer({+ server: { middlewareMode: true, hmr: false, ws: false },+ appType: "custom",+ plugins: options.plugins,+ });+ } catch (error) {+ restore();+ throw error;+ }+ return {+ dom,+ vite,+ close: async () => {+ try {+ await vite.close();+ } finally {+ restore();+ }+ },+ };+}diff --git a/plugins/web-ui/test/deep-link-boot-fixture.ts b/plugins/web-ui/test/deep-link-boot-fixture.tsindex 2019bd485..9687577d2 100644--- a/plugins/web-ui/test/deep-link-boot-fixture.ts+++ b/plugins/web-ui/test/deep-link-boot-fixture.ts@@ -1,5 +1,4 @@-import { JSDOM } from "jsdom";-import { createServer } from "vite";+import { browserEnv } from "./browser-env.ts";import type { Conversation } from "../src/conv-types.ts";import type { CoreContext, CoreSession, TranscriptPage } from "../src/core-bridge.ts";@@ -58,10 +57,19 @@ export const SESSION = {export async function harness(opts: HarnessOptions): Promise<Harness> {const session = opts.session ?? SESSION;let transcriptStatus = opts.transcriptStatus;- const dom = new JSDOM('<!doctype html><div id="app"></div>', {- url: `http://localhost${opts.path}`,- pretendToBeVisual: true,+ const requests: string[] = [];+ const inFlight = new Set<Promise<Response>>();+ const env = await browserEnv({+ dom: { url: `http://localhost${opts.path}` },+ html: '<!doctype html><div id="app"></div>',+ fetch: (input) => {+ const answer = respond(input);+ inFlight.add(answer);+ void answer.finally(() => inFlight.delete(answer)).catch(() => {});+ return answer;+ },});+ const { dom, vite } = env;if (opts.savedCanvas)dom.window.localStorage.setItem("web-ui:split-canvas:v1",@@ -105,12 +113,6 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {dom.window.HTMLElement.prototype.scrollIntoView = function () {this.setAttribute("data-scrolled", "true");};- dom.window.HTMLElement.prototype.getAnimations = () => [];- const timers = new Set<ReturnType<typeof setTimeout>>();- const realSetTimeout = globalThis.setTimeout;- const realSetInterval = globalThis.setInterval;- const requests: string[] = [];- const inFlight = new Set<Promise<Response>>();let releaseSessions = (): void => {};let releaseTranscript = (): void => {};let releaseApprovals = (): void => {};@@ -192,61 +194,6 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {return Response.json({ contexts: opts.contexts ?? [], items: [], crons: [] });};- const globals = {- fetch: (input: RequestInfo | URL): Promise<Response> => {- const answer = respond(input);- inFlight.add(answer);- void answer.finally(() => inFlight.delete(answer)).catch(() => {});- return answer;- },- window: dom.window,- document: dom.window.document,- location: dom.window.location,- history: dom.window.history,- localStorage: dom.window.localStorage,- sessionStorage: dom.window.sessionStorage,- navigator: dom.window.navigator,- HTMLElement: dom.window.HTMLElement,- Element: dom.window.Element,- Node: dom.window.Node,- Event: dom.window.Event,- PointerEvent: dom.window.PointerEvent,- MouseEvent: dom.window.MouseEvent,- customElements: dom.window.customElements,- getComputedStyle: dom.window.getComputedStyle.bind(dom.window),- cancelAnimationFrame: clearTimeout,- EventSource: undefined,- ResizeObserver: class {- observe() {}- unobserve() {}- disconnect() {}- },- setTimeout: ((...args: Parameters<typeof setTimeout>) => {- const id = realSetTimeout(...args);- timers.add(id);- return id;- }) as typeof setTimeout,- setInterval: ((...args: Parameters<typeof setInterval>) => {- const id = realSetInterval(...args);- timers.add(id);- return id;- }) as typeof setInterval,- requestAnimationFrame: (callback: FrameRequestCallback) => {- const id = realSetTimeout(() => callback(Date.now()), 0);- timers.add(id);- return id as unknown as number;- },- };- const descriptors = new Map<string, PropertyDescriptor | undefined>();- for (const [key, value] of Object.entries(globals)) {- descriptors.set(key, Object.getOwnPropertyDescriptor(globalThis, key));- Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });- }- Object.defineProperty(dom.window, "matchMedia", {- value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),- });-- const vite = await createServer({ server: { middlewareMode: true, hmr: false, ws: false }, appType: "custom" });const shell = await vite.ssrLoadModule("/src/shell.ts");const sessions = await vite.ssrLoadModule("/src/sessions.ts");const conversations = await vite.ssrLoadModule("/src/conversations.ts");@@ -291,15 +238,9 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {releaseRemoteSplit();for (let drain = 0; drain < 5 && inFlight.size; drain++) {await Promise.allSettled(inFlight);- await new Promise((resolve) => realSetTimeout(resolve, 0));- }- await vite.close();- dom.window.close();- for (const id of timers) clearTimeout(id);- for (const [key, descriptor] of descriptors) {- if (descriptor) Object.defineProperty(globalThis, key, descriptor);- else delete (globalThis as Record<string, unknown>)[key];+ await new Promise((resolve) => setTimeout(resolve, 0));}+ await env.close();},};}diff --git a/plugins/web-ui/test/deploys-page.test.ts b/plugins/web-ui/test/deploys-page.test.tsnew file mode 100644index 000000000..59ef79137--- /dev/null+++ b/plugins/web-ui/test/deploys-page.test.ts@@ -0,0 +1,188 @@+import assert from "node:assert/strict";+import test, { after, beforeEach } from "node:test";+import { browserEnv } from "./browser-env.ts";+import type { DeploymentView } from "../src/deploy-view.ts";++let requests: Array<{ path: string; resolve: (body: unknown) => void }> = [];+const { vite, close } = await browserEnv({+ dom: { url: "http://localhost/apps" },+ fetch: (input) => {+ const path = String(input);+ if (path === "/api/contexts") return Promise.resolve(Response.json({ contexts: [] }));+ return new Promise<Response>((resolve) => requests.push({ path, resolve: (body) => resolve(Response.json(body)) }));+ },+});+after(close);++let appState: {+ currentView: string;+ viewRenderSeq: number;+ mainEl: HTMLElement | null;+ me: { user: string; org: string } | null;+};+let renderDeploys: () => Promise<void>;+let openDeployById: (id: string) => void;+let main: HTMLElement;++beforeEach(async () => {+ requests = [];+ document.body.innerHTML = '<div id="app"></div><main></main>';+ main = document.querySelector("main")!;+ vite.moduleGraph.invalidateAll();+ ({ appState } = await vite.ssrLoadModule("/src/shell.ts"));+ ({ renderDeploys, openDeployById } = await vite.ssrLoadModule("/src/deploys.ts"));+ appState.currentView = "deploys";+ appState.mainEl = main;+ appState.me = { user: "tester", org: "test" };+});++const settle = () => new Promise((resolve) => setTimeout(resolve, 0));+const request = (path: string) => {+ const found = requests.find((r) => r.path === path);+ assert.ok(found, `requested ${path}`);+ return found;+};+const listedIds = () =>+ [...main.querySelectorAll(".deploy-row .list-row-title")].map((row) => row.textContent?.trim() ?? "");+const detail = () => main.querySelector(".deploy-detail-pane");+const loadingDetail = () => Boolean(detail()?.querySelector(".hint")?.textContent?.includes("Loading"));++test("the initial list refresh redraws the list when no detail was opened", async () => {+ const rendering = renderDeploys();+ await settle();+ assert.match(main.textContent ?? "", /Loading apps…/);+ request("/api/deployments").resolve({ deployments: [{ id: "app", ownerScopeId: "personal:tester" }] });+ await rendering;+ assert.deepEqual(listedIds(), ["app"]);+});++test("the initial list refresh leaves an opened detail and its loading state untouched", async () => {+ const first = renderDeploys();+ await settle();+ request("/api/deployments").resolve({ deployments: [{ id: "opened-app", ownerScopeId: "personal:tester" }] });+ await first;+ requests = [];+ const rendering = renderDeploys();+ await settle();+ main.querySelector<HTMLButtonElement>(".deploy-manage")!.click();+ await settle();+ assert.deepEqual(+ requests.map((r) => r.path),+ ["/api/deployments", "/api/deployments/opened-app"],+ );+ request("/api/deployments").resolve({ deployments: [] });+ await rendering;+ assert.equal(listedIds().length, 0);+ assert.ok(loadingDetail());+ request("/api/deployments/opened-app").resolve({ deployment: { id: "opened-app", displayName: "Opened" } });+ await settle();+ assert.equal(detail()?.querySelector("h2")?.textContent, "Opened");+ assert.equal(loadingDetail(), false);+});++for (const listed of [false, true]) {+ test(`app deep links load details when the requested app is ${listed ? "in" : "absent from"} the list`, async () => {+ openDeployById("linked-app");+ const rendering = renderDeploys();+ await settle();+ request("/api/deployments").resolve({+ deployments: listed ? [{ id: "linked-app", displayName: "Linked app" }] : [],+ });+ await settle();+ assert.ok(request("/api/deployments/linked-app"));+ assert.ok(loadingDetail());+ request("/api/deployments/linked-app").resolve({ deployment: { id: "linked-app" } });+ await rendering;+ assert.ok(detail());+ assert.equal(loadingDetail(), false);+ });+}++for (const supersede of ["view", "render"] as const) {+ test(`a pending app deep link cannot open after another ${supersede}`, async () => {+ openDeployById("linked-app");+ const rendering = renderDeploys();+ await settle();+ if (supersede === "view") appState.currentView = "skills";+ else appState.viewRenderSeq++;+ request("/api/deployments").resolve({ deployments: [{ id: "linked-app" }] });+ await rendering;+ assert.deepEqual(+ requests.map((r) => r.path),+ ["/api/deployments"],+ );+ assert.equal(detail(), null);+ });+}++async function openDetail(deployment: DeploymentView): Promise<HTMLElement> {+ openDeployById(deployment.id);+ const rendering = renderDeploys();+ await settle();+ request("/api/deployments").resolve({ deployments: [] });+ await settle();+ request(`/api/deployments/${deployment.id}`).resolve({ deployment });+ await rendering;+ return detail() as HTMLElement;+}++for (const count of [0, 7, 23, 150]) {+ test(`version history reveals ${count} versions in newest-first batches of ten`, async () => {+ const deployment = {+ id: "history-app",+ currentVersion: count,+ appliedVersion: 1,+ versions: Array.from({ length: count }, (_, index) => ({ version: index + 1, createdAt: 1000 })),+ };+ const pane = await openDetail(deployment);+ const history = () =>+ [...pane.querySelectorAll(".deploy-detail-section")].find(+ (s) => s.querySelector("h3")?.textContent === "Version history",+ )!;+ const olderButton = () =>+ [...history().querySelectorAll("button")].find((b) => b.textContent?.includes("Show older versions"));+ let shown = 10;+ for (;;) {+ const section = history();+ const numbers = [...section.querySelectorAll(".deploy-version-row strong")].map((s) =>+ Number(s.textContent!.slice(1)),+ );+ assert.deepEqual(+ numbers,+ Array.from({ length: Math.min(shown, count) }, (_, index) => count - index),+ );+ assert.equal(section.textContent!.includes("No version history available."), count === 0);+ assert.equal(Boolean(section.querySelector(".badge.ok")), count > 0 && shown >= count);+ assert.equal(+ [...section.querySelectorAll(".badge")].some((b) => b.textContent === "Latest"),+ count > 1,+ );+ assert.equal(Boolean(olderButton()), shown < count);+ if (shown >= count) break;+ olderButton()!.click();+ shown += 10;+ }+ assert.deepEqual(+ deployment.versions.map((version) => version.version),+ Array.from({ length: count }, (_, index) => index + 1),+ );+ });+}++test("detail redraws reuse the scroll container and retain focus", async () => {+ openDeployById("app");+ const rendering = renderDeploys();+ await settle();+ request("/api/deployments").resolve({ deployments: [] });+ await settle();+ const host = detail() as HTMLElement;+ const button = host.querySelector<HTMLButtonElement>("button")!;+ host.scrollTop = 450;+ button.focus();+ request("/api/deployments/app").resolve({ deployment: { id: "app", displayName: "App" } });+ await rendering;+ assert.equal(loadingDetail(), false);+ assert.equal(main.firstElementChild, host);+ assert.equal(host.scrollTop, 450);+ assert.equal(document.activeElement, button);+});diff --git a/plugins/web-ui/test/deploys-source.test.ts b/plugins/web-ui/test/deploys-source.test.tsdeleted file mode 100644index 4813ef08e..000000000--- a/plugins/web-ui/test/deploys-source.test.ts+++ /dev/null@@ -1,236 +0,0 @@-import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import test from "node:test";-import { stripTypeScriptTypes } from "node:module";-import { createContext, runInContext } from "node:vm";-import { JSDOM } from "jsdom";-import { deploymentListRefreshCanRedraw, type DeploymentView } from "../src/deploy-view.ts";-import {- withDeploymentListNotice,- withDeploymentDetailNotice,- withoutDeploymentDetailNotice,-} from "../src/deploy-notices.ts";-import { deepLinkPath } from "../src/deep-link.ts";--const source = readFileSync(new URL("../src/deploys.ts", import.meta.url), "utf8");--function bodyOf(name: string): string {- const start = source.indexOf(`function ${name}(`);- assert.notEqual(start, -1, `${name} exists`);- const next = source.indexOf("\nfunction ", start + 1);- return source.slice(start, next < 0 ? source.length : next);-}--function renderHarness(requestedId: string | null = null) {- const requests: Array<{ path: string; resolve: (response: unknown) => void }> = [];- const frames: Array<{ view: "list" | "detail"; id?: string; loading?: boolean }> = [];- const context = createContext({- appState: { currentView: "deploys", viewRenderSeq: 1 },- pendingDeployId: requestedId,- archiveCandidate: null,- restoreArchiveFocus: false,- scopedSession: { active: null },- contextsState: { selected: null },- deployScope: null,- deployList: [],- deployLoading: false,- deployNotices: { list: "", detail: null },- activeDeploy: null,- visibleVersionCount: 70,- editingDeploy: null,- deployDraft: "",- deployRefreshSeq: 0,- setDeployBackgroundInert() {},- async ensureContexts() {},- withDeploymentListNotice,- withDeploymentDetailNotice,- withoutDeploymentDetailNotice,- deploymentListRefreshCanRedraw,- deepLinkPath,- UI_BASE: "",- history: { replaceState() {} },- errMessage: (error: Error) => error.message,- drawDeploysPage() {- frames.push({ view: "list" });- },- drawDeployDetail(deployment: DeploymentView, loading = false) {- frames.push({ view: "detail", id: deployment.id, loading });- },- api: (path: string) => new Promise((resolve) => requests.push({ path, resolve })),- });- const open = source.slice(source.indexOf("async function openDeploy("), source.indexOf("function drawDeployDetail("));- const refreshAndRender = source- .slice(source.indexOf("async function refreshDeployments("))- .replace("export async function", "async function");- runInContext(stripTypeScriptTypes(open + refreshAndRender), context);- return {- context,- requests,- frames,- render: () => runInContext("renderDeploys()", context) as Promise<void>,- open: () => runInContext('openDeploy({id: "opened-app"})', context) as Promise<void>,- };-}--test("the initial list refresh redraws the list when no detail was opened", async () => {- const h = renderHarness();- const rendering = h.render();- await new Promise((resolve) => setImmediate(resolve));- h.requests[0]!.resolve({ deployments: [{ id: "app" }] });- await rendering;- assert.deepEqual(h.frames, [{ view: "list" }, { view: "list" }]);-});--test("the initial list refresh leaves an opened detail and its loading state untouched", async () => {- const h = renderHarness();- const rendering = h.render();- await new Promise((resolve) => setImmediate(resolve));- const opening = h.open();- assert.equal(h.context.visibleVersionCount, 10);- assert.equal(h.requests[0]!.path, "/api/deployments");- assert.equal(h.requests[1]!.path, "/api/deployments/opened-app");- h.requests[0]!.resolve({ deployments: [] });- await rendering;- assert.deepEqual(h.frames, [{ view: "list" }, { view: "detail", id: "opened-app", loading: true }]);- h.requests[1]!.resolve({ deployment: { id: "opened-app" } });- await opening;- assert.deepEqual(h.frames.at(-1), { view: "detail", id: "opened-app", loading: false });-});--for (const listed of [false, true]) {- test(`app deep links load details when the requested app is ${listed ? "in" : "absent from"} the list`, async () => {- const h = renderHarness("linked-app");- const rendering = h.render();- await new Promise((resolve) => setImmediate(resolve));- assert.equal(h.context.pendingDeployId, null);- h.requests[0]!.resolve({ deployments: listed ? [{ id: "linked-app", displayName: "Linked app" }] : [] });- await new Promise((resolve) => setImmediate(resolve));- assert.equal(h.requests[1]!.path, "/api/deployments/linked-app");- assert.deepEqual(h.frames.at(-1), { view: "detail", id: "linked-app", loading: true });- h.requests[1]!.resolve({ deployment: { id: "linked-app" } });- await rendering;- assert.deepEqual(h.frames.at(-1), { view: "detail", id: "linked-app", loading: false });- });-}--for (const supersede of ["view", "render"] as const) {- test(`a pending app deep link cannot open after another ${supersede}`, async () => {- const h = renderHarness("linked-app");- const rendering = h.render();- await new Promise((resolve) => setImmediate(resolve));- if (supersede === "view") h.context.appState.currentView = "skills";- else h.context.appState.viewRenderSeq++;- h.requests[0]!.resolve({ deployments: [{ id: "linked-app" }] });- await rendering;- assert.equal(h.requests.length, 1);- assert.deepEqual(h.frames, [{ view: "list" }]);- });-}--for (const count of [0, 7, 23, 150]) {- test(`version history reveals ${count} versions in newest-first batches of ten`, () => {- const deployment = {- id: "history-app",- currentVersion: count,- appliedVersion: 1,- versions: Array.from({ length: count }, (_, index) => ({ version: index + 1, createdAt: 1000 })),- };- const handlers: Array<() => void> = [];- const redraws: unknown[] = [];- const context = createContext({- d: deployment,- nothing: "",- drawDeployDetail: (value: unknown) => redraws.push(value),- html(strings: TemplateStringsArray, ...values: unknown[]) {- const text = (value: unknown): string => {- if (typeof value === "function") {- handlers.push(value as () => void);- return "";- }- return Array.isArray(value) ? value.map(text).join("") : String(value);- };- return strings.reduce(- (result, part, index) => result + part + (index < values.length ? text(values[index]) : ""),- "",- );- },- });- const initialCount = source.match(/let visibleVersionCount = \d+;/)?.[0];- const orderedVersions = bodyOf("drawDeployDetail").match(/const versions = [^;]+;/)?.[0];- const section = source.match(- /<section class="deploy-detail-section">\s*<h3>Version history<\/h3>[\s\S]*?<\/section>/,- )?.[0];- assert.ok(initialCount && orderedVersions && section);- runInContext(stripTypeScriptTypes(initialCount + orderedVersions), context);- let shown = 10;- for (;;) {- handlers.length = 0;- const rendered = runInContext(stripTypeScriptTypes(`html\`${section}\``), context) as string;- const numbers = [...rendered.matchAll(/<strong>v(\d+)<\/strong/g)].map((match) => Number(match[1]));- assert.deepEqual(- numbers,- Array.from({ length: Math.min(shown, count) }, (_, index) => count - index),- );- assert.equal(rendered.includes("No version history available."), count === 0);- assert.equal(rendered.includes('class="badge ok">Live'), count > 0 && shown >= count);- assert.equal(rendered.includes('class="badge">Latest'), count > 1);- assert.equal(rendered.includes("Show older versions"), shown < count);- assert.equal(handlers.length, shown < count ? 1 : 0);- if (shown >= count) break;- handlers[0]!();- assert.equal(redraws.at(-1), deployment);- shown += 10;- }- assert.deepEqual(- deployment.versions.map((version) => version.version),- Array.from({ length: count }, (_, index) => index + 1),- );- });-}--test("detail redraws reuse the scroll container and retain focus", () => {- const dom = new JSDOM("<main></main>");- try {- const mainEl = dom.window.document.querySelector("main")!;- const deployment = { id: "app" };- const context = createContext({- appState: { currentView: "deploys", mainEl },- document: dom.window.document,- d: deployment,- activeDeploy: deployment,- editingDeploy: null,- deployNotices: {},- archiveCandidate: null,- deployToast: null,- visibleVersionCount: 10,- nothing: "",- html: () => "",- render(_template: unknown, host: HTMLElement) {- if (!host.firstChild) host.append(dom.window.document.createElement("button"));- },- deploymentContextScope: () => null,- listBackLink: () => "",- returnToDeploysList() {},- deploymentTitle: () => "App",- statusClass: () => "",- statusLabel: () => "",- deploymentSlug: () => "app",- deploymentLatestAt: () => null,- ownerLabel: () => "",- permissionBadge: () => "",- canManage: () => false,- });- runInContext(stripTypeScriptTypes(bodyOf("drawDeployDetail")), context);- runInContext("drawDeployDetail(d)", context);- const host = mainEl.firstElementChild as HTMLElement;- const button = host.querySelector("button")!;- host.scrollTop = 450;- button.focus();- runInContext("drawDeployDetail(d)", context);- assert.equal(mainEl.firstElementChild, host);- assert.equal(host.scrollTop, 450);- assert.equal(dom.window.document.activeElement, button);- } finally {- dom.window.close();- }-});diff --git a/plugins/web-ui/test/inbox-composer-fixture.ts b/plugins/web-ui/test/inbox-composer-fixture.tsindex a8760033a..00953bb65 100644--- a/plugins/web-ui/test/inbox-composer-fixture.ts+++ b/plugins/web-ui/test/inbox-composer-fixture.ts@@ -1,5 +1,6 @@-import { JSDOM, type ConstructorOptions } from "jsdom";-import { createServer, type PluginOption } from "vite";+import type { ConstructorOptions } from "jsdom";+import type { PluginOption } from "vite";+import { browserEnv } from "./browser-env.ts";import { metadata } from "./model-metadata.ts";export const inboxRuntime = {scopeId: "personal:[email protected]",@@ -24,73 +25,15 @@ export async function until(check: () => boolean): Promise<void> {}export async function createInboxFixture(options: { dom?: ConstructorOptions; plugins?: PluginOption[] } = {}) {- const dom = new JSDOM('<!doctype html><div id="app"></div><main id="main"></main>', {- url: "http://localhost/",- ...options.dom,- });- Object.defineProperty(dom.window, "matchMedia", {- value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }),- });- const originals = new Map<string, PropertyDescriptor | undefined>();- const setGlobal = (key: string, value: unknown) => {- originals.set(key, Object.getOwnPropertyDescriptor(globalThis, key));- Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });- };- let vite: Awaited<ReturnType<typeof createServer>> | undefined;+ const env = await browserEnv({ dom: { pretendToBeVisual: false, ...options.dom }, plugins: options.plugins });+ const host = env.dom.window.document.getElementById("main")!;const close = async () => {try {- if (vite) {- try {- const { render } = await vite.ssrLoadModule("lit");- render(null, dom.window.document.getElementById("main")!);- } finally {- await vite.close();- }- }+ const { render } = await env.vite.ssrLoadModule("lit");+ render(null, host);} finally {- dom.window.close();- for (const [key, descriptor] of originals) {- if (descriptor) Object.defineProperty(globalThis, key, descriptor);- else Reflect.deleteProperty(globalThis, key);- }+ await env.close();}};- try {- for (const key of [- "window",- "document",- "location",- "history",- "localStorage",- "navigator",- "Element",- "HTMLElement",- "Node",- "CustomEvent",- "Event",- "customElements",- ])- setGlobal(key, key === "window" ? dom.window : dom.window[key as keyof typeof dom.window]);- setGlobal("getComputedStyle", dom.window.getComputedStyle.bind(dom.window));- setGlobal(- "requestAnimationFrame",- options.dom?.pretendToBeVisual- ? dom.window.requestAnimationFrame.bind(dom.window)- : (fn: FrameRequestCallback) => setTimeout(() => fn(Date.now()), 0),- );- setGlobal(- "cancelAnimationFrame",- options.dom?.pretendToBeVisual ? dom.window.cancelAnimationFrame.bind(dom.window) : clearTimeout,- );- setGlobal("fetch", globalThis.fetch);- vite = await createServer({- server: { middlewareMode: true, hmr: false },- appType: "custom",- plugins: options.plugins,- });- return { dom, vite, host: dom.window.document.getElementById("main")!, close };- } catch (error) {- await close();- throw error;- }+ return { dom: env.dom, vite: env.vite, host, close };}diff --git a/plugins/web-ui/test/search-race.test.ts b/plugins/web-ui/test/search-race.test.tsindex 3fa05335e..875bf5f60 100644--- a/plugins/web-ui/test/search-race.test.ts+++ b/plugins/web-ui/test/search-race.test.ts@@ -1,265 +1,279 @@import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import { stripTypeScriptTypes } from "node:module";-import { test } from "node:test";-import { createContext, runInContext } from "node:vm";+import { after, afterEach, beforeEach, test } from "node:test";+import { browserEnv } from "./browser-env.ts";-const source = readFileSync(new URL("../src/search.ts", import.meta.url), "utf8");-const handlers = source.slice(source.indexOf("function onQueryInput("), source.indexOf("function groupHitsBySession("));-const selection = source.slice(source.indexOf("function rowCount("), source.indexOf("function onQueryInput("));-const lifecycle = source- .slice(source.indexOf("export function openChatSearch("), source.indexOf("function ensureHost("))- .replace("export function", "function");+type Pending = { signal: AbortSignal; resolve: (body: unknown) => void; reject: (error: Error) => void };+let requests: Pending[] = [];+let resourceRequests: Pending[] = [];+let opened: string[] = [];+const sessions = ["old", "document", "first", "second", "chat", "chat1"].map((id) => ({+ id,+ threadRef: `web:tester:${id}`,+ scopeId: "personal:tester",+ title: id,+}));+const runtimeConfig = {+ scopeId: "personal:tester",+ approvedHarnesses: [],+ modelsByHarness: {},+ modelCatalog: {},+ orgDefault: { harnessId: "pi", modelId: "m", revision: 1 },+ scopeOverride: null,+ effective: { harnessId: "pi", modelId: "m" },+ upgradeAvailable: false,+};+const env = await browserEnv({+ fetch: (input, init) => {+ const path = String(input);+ const chats = path.startsWith("/api/search?");+ if (chats || path.startsWith("/api/resources/search?"))+ return new Promise<Response>((resolve, reject) =>+ (chats ? requests : resourceRequests).push({+ signal: init!.signal!,+ resolve: (body) => resolve(Response.json(body)),+ reject,+ }),+ );+ const id = path.match(/^\/api\/sessions\/([^/?]+)\?/)?.[1];+ if (id) opened.push(id);+ if (path.startsWith("/api/runtime-config")) return Promise.resolve(Response.json(runtimeConfig));+ if (path.endsWith("/approvals")) return Promise.resolve(Response.json({ approvals: [] }));+ if (path === "/api/sessions") return Promise.resolve(Response.json({ sessions }));+ if (id) return Promise.resolve(Response.json({ session: sessions.find((s) => s.id === id), entries: [] }));+ return Promise.resolve(Response.json({}));+ },+});+const realLocation = env.dom.window.location;+Object.defineProperty(globalThis, "location", {+ configurable: true,+ writable: true,+ value: new Proxy(+ {},+ {+ get: (_, key) =>+ key === "assign" ? (href: string) => opened.push(href) : (Reflect.get(realLocation, key) as unknown),+ },+ ),+});+after(env.close);-const keyboard = source.slice(- source.indexOf("function onPaletteKeydown("),- source.indexOf("function scrollSelectedIntoView("),-);+let openChatSearch: () => void;-function harness() {- const state = {- open: true,- query: "",- hits: [] as unknown[],- resources: [] as unknown[],- loading: false,- failed: false,- sel: 0,- selectionMoved: false,- };- const requests: Array<{ signal: AbortSignal; resolve: (value: unknown) => void; reject: (error: Error) => void }> =- [];- const resourceRequests: typeof requests = [];- let asks = 0;- const opened: unknown[] = [];- let timer: (() => void) | undefined;- const context = createContext({- searchState: state,- MIN_QUERY_LEN: 2,- DEBOUNCE_MS: 150,- debounceTimer: null,- inflight: null,- fetchSeq: 0,- AbortController,- draw() {},- resourceResults: (r: unknown) => r,- UI_BASE: "",- resourceHits: () => state.resources,- openResource: (hit: unknown) => opened.push(hit),- openHit: (hit: unknown) => opened.push(hit),- scrollSelectedIntoView() {},- askQm() {- asks++;- },- requestAnimationFrame() {},- groupHitsBySession: (hits: unknown[]) => hits,- clearTimeout() {- timer = undefined;- },- setTimeout(fn: () => void) {- timer = fn;- return 1;- },- api: (_path: string, { signal }: { signal: AbortSignal }) =>- _path.startsWith("/api/resources/")- ? new Promise((resolve, reject) => {- resourceRequests.push({ signal, resolve, reject });- })- : new Promise((resolve, reject) => {- requests.push({ signal, resolve, reject });- }),- });- runInContext(stripTypeScriptTypes(selection + handlers + lifecycle + keyboard), context);- return {- state,- requests,- resourceRequests,- asks: () => asks,- opened,- resources(hits: unknown[]) {- state.resources = hits;- },- down() {- runInContext("onPaletteKeydown({key: 'ArrowDown', preventDefault(){}})", context);- },- enter() {- runInContext("onPaletteKeydown({key: 'Enter', preventDefault(){}})", context);- },- input(value: string) {- context.inputValue = value;- runInContext("onQueryInput({currentTarget:{value:inputValue}})", context);- },- fire() {- const fn = timer;- timer = undefined;- fn?.();- },- close() {- runInContext("closeChatSearch()", context);- },- open() {- runInContext("openChatSearch()", context);- },- };-}+beforeEach(async () => {+ requests = [];+ resourceRequests = [];+ opened = [];+ document.body.innerHTML = '<div id="app"></div><main></main>';+ env.vite.moduleGraph.invalidateAll();+ const { appState } = await env.vite.ssrLoadModule("/src/shell.ts");+ const { sessionsState } = await env.vite.ssrLoadModule("/src/sessions.ts");+ ({ openChatSearch } = await env.vite.ssrLoadModule("/src/search.ts"));+ appState.me = { user: "tester", org: "test" };+ appState.currentView = "chats";+ appState.mainEl = document.querySelector("main");+ sessionsState.list = sessions;+ openChatSearch();+});++afterEach(() => {+ if (input()) close();+});++const settle = () => new Promise((resolve) => setTimeout(resolve, 0));+const fire = () => new Promise((resolve) => setTimeout(resolve, 200));+const input = () => document.querySelector<HTMLInputElement>(".chat-search-input");+const type = (value: string) => {+ input()!.value = value;+ input()!.dispatchEvent(new InputEvent("input", { bubbles: true }));+};+const press = (key: string, init: KeyboardEventInit = {}) =>+ input()!.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...init }));+const close = () => press("Escape");+const results = () => document.querySelector(".chat-search-results")?.textContent ?? "";+const chatRows = () =>+ [...document.querySelectorAll(".chat-search-row")]+ .filter((row) => row.querySelector(".chat-search-who.user, .chat-search-who.agent"))+ .map((row) => row.querySelector(".chat-search-snippet")!.textContent);+const resourceRows = () =>+ [...document.querySelectorAll(".chat-search-row:not(.chat-search-ask)")]+ .filter((row) => !row.querySelector(".chat-search-who.user, .chat-search-who.agent"))+ .map((row) => row.querySelector(".chat-search-snippet")!.textContent);+const asked = () => document.querySelector("main")!.textContent!.includes("Find the chat");+const hit = (sessionId: string) => ({ sessionId, entryType: "user", snippet: `${sessionId} text`, createdAt: 1 });+const resource = (title: string) => ({ kind: "skills", id: title.toLowerCase(), title, snippet: "" });for (const outcome of ["resolve", "reject"] as const) {test(`typing invalidates an old ${outcome} before the next debounce fires`, async () => {- const h = harness();- h.input("old");- h.fire();- h.input("document");- assert.equal(h.requests[0]!.signal.aborted, true);- if (outcome === "resolve") h.requests[0]!.resolve({ hits: [{ sessionId: "old" }] });- else h.requests[0]!.reject(new Error("timeout"));- await new Promise((resolve) => setImmediate(resolve));- assert.equal(h.state.hits.length, 0);- assert.equal(h.state.failed, false);- assert.equal(h.state.loading, true);- h.fire();- h.requests[1]!.resolve({ hits: [{ sessionId: "document" }] });- await new Promise((resolve) => setImmediate(resolve));- assert.deepEqual(h.state.hits, [{ sessionId: "document" }]);- assert.equal(h.state.loading, false);+ type("old");+ await fire();+ type("document");+ assert.equal(requests[0]!.signal.aborted, true);+ if (outcome === "resolve") requests[0]!.resolve({ hits: [hit("old")] });+ else requests[0]!.reject(new Error("timeout"));+ await settle();+ assert.deepEqual(chatRows(), []);+ assert.doesNotMatch(results(), /Search failed/);+ assert.match(results(), /Searching…/);+ await fire();+ requests[1]!.resolve({ hits: [hit("document")] });+ await settle();+ assert.deepEqual(chatRows(), ["document text"]);+ assert.doesNotMatch(results(), /Searching…/);});}-test("new input clears selectable stale hits and previous errors", () => {- const h = harness();- h.state.hits = [{ sessionId: "old" }];- h.state.failed = true;- h.input("document");- assert.equal(h.state.hits.length, 0);- assert.equal(h.state.failed, false);+test("new input clears selectable stale hits and previous errors", async () => {+ type("old");+ await fire();+ requests[0]!.resolve({ hits: [hit("old")] });+ await settle();+ assert.deepEqual(chatRows(), ["old text"]);+ type("older");+ assert.deepEqual(chatRows(), []);+ await fire();+ requests[1]!.reject(new Error("timeout"));+ await settle();+ assert.match(results(), /Search failed/);+ type("document");+ assert.deepEqual(chatRows(), []);+ assert.doesNotMatch(results(), /Search failed/);});test("closing and reopening cannot accept a previous request", async () => {- const h = harness();- h.input("old");- h.fire();- h.close();- h.open();- h.requests[0]!.resolve({ hits: [{ sessionId: "old" }] });- await new Promise((resolve) => setImmediate(resolve));- assert.equal(h.state.hits.length, 0);- assert.equal(h.state.query, "");+ type("old");+ await fire();+ close();+ openChatSearch();+ requests[0]!.resolve({ hits: [hit("old")] });+ await settle();+ assert.deepEqual(chatRows(), []);+ assert.equal(input()!.value, "");+ press("Enter");+ await settle();+ assert.deepEqual(opened, []);});test("clearing the query cancels pending and in-flight searches", async () => {- const h = harness();- h.input("old");- h.fire();- h.input("document");- h.input("");- h.fire();- assert.equal(h.requests.length, 1);- h.requests[0]!.resolve({ hits: [{ sessionId: "old" }] });- await new Promise((resolve) => setImmediate(resolve));- assert.equal(h.state.hits.length, 0);- assert.equal(h.state.loading, false);+ type("old");+ await fire();+ type("document");+ type("");+ await fire();+ assert.equal(requests.length, 1);+ requests[0]!.resolve({ hits: [hit("old")] });+ await settle();+ assert.deepEqual(chatRows(), []);+ assert.doesNotMatch(results(), /Searching…/);+ press("Enter");+ await settle();+ assert.deepEqual(opened, []);});-test("Enter while searching does not start an unintended agent conversation", () => {- const h = harness();- h.input("document");- h.enter();- assert.equal(h.asks(), 0);+test("Enter while searching does not start an unintended agent conversation", async () => {+ type("document");+ press("Enter");+ await settle();+ assert.equal(asked(), false);});-test("Enter opens resources before chats and offsets chat selection correctly", () => {- const h = harness();- h.input("skill");- const resource = { title: "Skill", href: "/skills/1" };- const chat = { sessionId: "chat1" };- h.resources([resource]);- h.state.hits = [chat];- h.state.loading = true;- h.enter();- assert.deepEqual(h.opened, [resource]);- h.state.loading = false;- h.state.sel = 1;- h.enter();- assert.deepEqual(h.opened, [resource, chat]);- h.state.sel = 2;- Object.assign(h.state, { resourcesLoading: false });- h.enter();- assert.equal(h.asks(), 1);+test("Enter opens resources before chats and offsets chat selection correctly", async () => {+ type("zzq");+ await fire();+ resourceRequests[0]!.resolve({ hits: [resource("Skill")], failed: [] });+ await settle();+ press("Enter");+ assert.deepEqual(opened, ["/skills/skill"]);+ openChatSearch();+ type("zzq");+ await fire();+ resourceRequests[1]!.resolve({ hits: [resource("Skill")], failed: [] });+ requests[1]!.resolve({ hits: [hit("chat1")] });+ await settle();+ press("ArrowDown");+ press("Enter");+ await settle();+ assert.deepEqual(opened, ["/skills/skill", "chat1"]);+ openChatSearch();+ type("zzq");+ await fire();+ resourceRequests[2]!.resolve({ hits: [resource("Skill")], failed: [] });+ requests[2]!.resolve({ hits: [hit("chat1")] });+ await settle();+ press("ArrowDown");+ press("ArrowDown");+ press("Enter");+ await settle();+ assert.equal(asked(), true);});test("chat results do not wait for resource results, and stale resource replies are ignored", async () => {- const h = harness();- h.input("old");- h.fire();- h.requests[0]!.resolve({ hits: [{ sessionId: "old" }] });- await new Promise((resolve) => setImmediate(resolve));- assert.equal(h.state.loading, false);- assert.equal(h.state.hits.length, 1);- h.input("new");- h.fire();- h.resourceRequests[0]!.resolve({ hits: [{ title: "Old" }], failed: [] });- await new Promise((resolve) => setImmediate(resolve));- assert.equal(JSON.stringify((h.state as unknown as { resources: unknown[] }).resources), "[]");- h.resourceRequests[1]!.resolve({ hits: [{ title: "New" }], failed: [] });- await new Promise((resolve) => setImmediate(resolve));- assert.equal(JSON.stringify((h.state as unknown as { resources: unknown[] }).resources), '[{"title":"New"}]');- assert.equal(h.state.loading, true);+ type("old");+ await fire();+ requests[0]!.resolve({ hits: [hit("old")] });+ await settle();+ assert.deepEqual(chatRows(), ["old text"]);+ type("new");+ await fire();+ resourceRequests[0]!.resolve({ hits: [resource("Old")], failed: [] });+ await settle();+ assert.deepEqual(resourceRows(), []);+ resourceRequests[1]!.resolve({ hits: [resource("New")], failed: [] });+ await settle();+ assert.deepEqual(resourceRows(), ["New"]);+ assert.match(results(), /Searching…/);});test("closing search aborts both requests and prevents old resources reappearing after reopen", async () => {- const h = harness();- h.input("old");- h.fire();- h.close();- h.open();- assert.equal(h.resourceRequests[0]!.signal.aborted, true);- h.resourceRequests[0]!.resolve({ hits: [{ title: "Old" }], failed: [] });- await new Promise((resolve) => setImmediate(resolve));- assert.equal(JSON.stringify((h.state as unknown as { resources: unknown[] }).resources), "[]");+ type("old");+ await fire();+ close();+ openChatSearch();+ assert.equal(resourceRequests[0]!.signal.aborted, true);+ resourceRequests[0]!.resolve({ hits: [resource("Old")], failed: [] });+ await settle();+ assert.deepEqual(resourceRows(), []);});for (const navigate of [false, true]) {test(`late resources preserve the ${navigate ? "keyboard-selected" : "first"} chat`, async () => {- const h = harness();- h.input("document");- h.fire();- const chats = [{ sessionId: "first" }, { sessionId: "second" }];- h.requests[0]!.resolve({ hits: chats });- await new Promise((resolve) => setImmediate(resolve));- if (navigate) h.down();- h.resourceRequests[0]!.resolve({ hits: [{ title: "One" }, { title: "Two" }], failed: [] });- await new Promise((resolve) => setImmediate(resolve));- h.enter();- assert.deepEqual(h.opened, [chats[navigate ? 1 : 0]]);+ type("zzq");+ await fire();+ requests[0]!.resolve({ hits: [hit("first"), hit("second")] });+ await settle();+ if (navigate) press("ArrowDown");+ resourceRequests[0]!.resolve({ hits: [resource("One"), resource("Two")], failed: [] });+ await settle();+ press("Enter");+ await settle();+ assert.deepEqual(opened, [navigate ? "second" : "first"]);});}for (const first of ["chats", "resources"] as const) {test(`late ${first === "chats" ? "resources" : "chats"} preserve the explicitly selected ask row`, async () => {- const h = harness();- h.input("document");- h.fire();- const chats = { hits: [{ sessionId: "chat" }] };- const resources = { hits: [{ title: "Resource" }], failed: [] };- if (first === "chats") h.requests[0]!.resolve(chats);- else h.resourceRequests[0]!.resolve(resources);- await new Promise((resolve) => setImmediate(resolve));- h.down();- if (first === "chats") h.resourceRequests[0]!.resolve(resources);- else h.requests[0]!.resolve(chats);- await new Promise((resolve) => setImmediate(resolve));- h.enter();- assert.equal(h.asks(), 1);- assert.deepEqual(h.opened, []);+ type("zzq");+ await fire();+ const chats = { hits: [hit("chat")] };+ const resources = { hits: [resource("Resource")], failed: [] };+ if (first === "chats") requests[0]!.resolve(chats);+ else resourceRequests[0]!.resolve(resources);+ await settle();+ press("ArrowDown");+ if (first === "chats") resourceRequests[0]!.resolve(resources);+ else requests[0]!.resolve(chats);+ await settle();+ press("Enter");+ await settle();+ assert.equal(asked(), true);+ assert.deepEqual(opened, []);});}test("initial resources select the first result instead of retaining the default ask row", async () => {- const h = harness();- h.input("document");- h.fire();- const resource = { title: "Resource" };- h.resourceRequests[0]!.resolve({ hits: [resource], failed: [] });- await new Promise((resolve) => setImmediate(resolve));- h.enter();- assert.deepEqual(h.opened, [resource]);+ type("zzq");+ await fire();+ resourceRequests[0]!.resolve({ hits: [resource("Resource")], failed: [] });+ await settle();+ press("Enter");+ assert.deepEqual(opened, ["/skills/resource"]);});diff --git a/plugins/web-ui/test/session-scope.test.ts b/plugins/web-ui/test/session-scope.test.tsindex 045b00dce..102f984d0 100644--- a/plugins/web-ui/test/session-scope.test.ts+++ b/plugins/web-ui/test/session-scope.test.ts@@ -1,50 +1,25 @@import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import { stripTypeScriptTypes } from "node:module";-import test from "node:test";-import { runInNewContext } from "node:vm";-import { JSDOM } from "jsdom";+import test, { after } from "node:test";+import { browserEnv } from "./browser-env.ts";import type { SessionTool, SessionTopbarOpts } from "../src/session-scope.ts";-const source = readFileSync(new URL("../src/session-scope.ts", import.meta.url), "utf8");-const dom = new JSDOM("<!doctype html><body></body>");-for (const [key, value] of Object.entries({- window: dom.window,- document: dom.window.document,- HTMLElement: dom.window.HTMLElement,- customElements: dom.window.customElements,-}))- Object.defineProperty(globalThis, key, { configurable: true, value });-const { html, nothing, render } = await import("lit");--function load(api: (path: string) => Promise<unknown> = async () => ({})) {- return runInNewContext(- stripTypeScriptTypes(- source.replace(/^import .*;\n/gm, "").replace(/^export /gm, "") + "\n({ scopeToolCount, sessionTopbarTpl });",- ),- {- api,- html,- nothing,- icon: () => nothing,- tip: () => nothing,- closeFormMenus: () => {},- toggleFormMenu: () => {},- ...Object.fromEntries(- ["ArrowUpLeft", "Box", "Brain", "Clock3", "Ellipsis", "Files", "GitFork", "KeyRound", "Rocket"].map((name) => [- name,- name,- ]),- ),- },- ) as {- scopeToolCount: (tool: SessionTool, scope: string, ready: () => void) => number | null;- sessionTopbarTpl: (opts: SessionTopbarOpts) => ReturnType<typeof html>;- };-}+const requests: string[] = [];+let respond: (path: string) => unknown = () => ({});+const { vite, close } = await browserEnv({+ fetch: async (input) => {+ const path = String(input);+ requests.push(path);+ return Response.json(respond(path));+ },+});+after(close);+const { render } = await vite.ssrLoadModule("lit");+const { scopeToolCount, sessionTopbarTpl } = (await vite.ssrLoadModule("/src/session-scope.ts")) as {+ scopeToolCount: (tool: SessionTool, scope: string, ready: () => void) => number | null;+ sessionTopbarTpl: (opts: SessionTopbarOpts) => unknown;+};test("only Crons and Apps request counts; both count past 100", async () => {- const requests: string[] = [];const crons = Array.from({ length: 137 }, (_, i) => ({id: String(i),ownerScopeId: "personal:test",@@ -55,9 +30,8 @@ test("only Crons and Apps request counts; both count past 100", async () => {ownerScopeId: "personal:test",status: "ready",}));- const { scopeToolCount } = load(async (path) => {- requests.push(path);- return path === "/api/crons"+ respond = (path) =>+ path === "/api/crons"? {crons: [...crons,@@ -74,7 +48,6 @@ test("only Crons and Apps request counts; both count past 100", async () => {{ id: "other", ownerScopeId: "other", status: "ready" },],};- });for (const tool of ["files", "skills", "memory", "keychain"] as const) {assert.equal(scopeToolCount(tool, "personal:test", () => assert.fail("unexpected refresh")),@@ -98,7 +71,6 @@ test("only Crons and Apps request counts; both count past 100", async () => {});test("desktop and mobile put Crons and Apps first and badge only those tools", () => {- const { sessionTopbarTpl } = load();const host = document.createElement("div");const queried: string[] = [];const clicked: string[] = [];@@ -150,6 +122,6 @@ test("desktop and mobile put Crons and Apps first and badge only those tools", (test("zero counts remain hidden in desktop and mobile tools", () => {const host = document.createElement("div");- render(load().sessionTopbarTpl({ crumb: null, title: "Test", onTool: () => {}, toolCount: () => 0 }), host);+ render(sessionTopbarTpl({ crumb: null, title: "Test", onTool: () => {}, toolCount: () => 0 }), host);assert.equal(host.querySelectorAll(".session-tool-count").length, 0);});diff --git a/plugins/web-ui/test/single-view-navigation.test.ts b/plugins/web-ui/test/single-view-navigation.test.tsindex 4a7298e9b..5010e2df6 100644--- a/plugins/web-ui/test/single-view-navigation.test.ts+++ b/plugins/web-ui/test/single-view-navigation.test.ts@@ -1,223 +1,155 @@import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import test from "node:test";-import { runInNewContext } from "node:vm";-import ts from "typescript";-import { deepLinkPath, parseDeepLink } from "../src/deep-link.ts";+import test, { after, beforeEach } from "node:test";+import { browserEnv } from "./browser-env.ts";-import { messageLinkSeq } from "../src/message-link.ts";+type Session = { id: string; threadRef: string; scopeId: string; title: string; parentSessionId?: string };+const session = (id: string, extra: Partial<Session> = {}): Session => ({+ id,+ threadRef: `web:tester:${id}`,+ scopeId: "personal:tester",+ title: `Title ${id}`,+ ...extra,+});+let known: Session[] = [];+const env = await browserEnv({+ fetch: async (input) => {+ const path = String(input);+ if (path.startsWith("/api/runtime-config"))+ return Response.json({+ scopeId: "personal:tester",+ approvedHarnesses: [],+ modelsByHarness: {},+ modelCatalog: {},+ effective: { harnessId: "pi", modelId: "m" },+ });+ if (path.endsWith("/approvals")) return Response.json({ approvals: [] });+ if (path === "/api/sessions") return Response.json({ sessions: known });+ const id = path.match(/^\/api\/sessions\/([^/?]+)/)?.[1];+ if (id) return Response.json({ session: known.find((s) => s.id === id), entries: [] });+ return Response.json({ contexts: [], items: [], crons: [] });+ },+});+after(env.close);-const split = readFileSync(new URL("../src/split.ts", import.meta.url), "utf8");-const shell = readFileSync(new URL("../src/shell.ts", import.meta.url), "utf8");-const functionSource = (source: string, name: string): string => {- const match = source.match(new RegExp(`(?:export )?function ${name}\\([^]*?\\n\\}`));- assert.ok(match);- return match[0].replace("export ", "");-};-const compile = (source: string): string =>- ts.transpileModule(source, {- compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },- }).outputText;+let shell: Record<string, any>;+let sessions: Record<string, any>;+let split: Record<string, any>;-test("pane header updates scan session metadata linearly and retain parent-title invalidation", () => {- let reads = 0;- const list = Array.from({ length: 128 }, (_, index) => ({- get id() {- reads++;- return `session-${index}`;- },- title: `Title ${index}`,- parentSessionId: index === 126 ? "session-0" : undefined,- }));- const panels = [126, 127].map((index) => ({ id: `pane-${index}`, params: { sessionId: `session-${index}` } }));- const signature = runInNewContext(- compile(- `${functionSource(split, "paneSession")}\n${functionSource(split, "computeHeaderSignature")}\ncomputeHeaderSignature;`,- ),- {- sessionsState: { list },- dockApi: { panels },- panelParams: (panel: { params: object }) => panel.params,- paneCrumb: () => null,- paneTitle: () => "Conversation",- paneIsWorking: () => false,- paneAwaitsInput: () => false,- paneBackground: () => null,- paneKindBadge: () => 0,- },- ) as () => string;- const before = signature();- assert.match(before, /session-0\|Title 0/);- assert.ok(reads <= list.length * panels.length * 8, `Header update visited ${reads} session IDs`);- list[0]!.title = "Renamed parent";- assert.notEqual(signature(), before);- assert.match(signature(), /session-0\|Renamed parent/);+beforeEach(async () => {+ document.body.innerHTML = '<div id="app"></div><main></main>';+ env.dom.window.history.replaceState(null, "", "/");+ env.vite.moduleGraph.invalidateAll();+ shell = await env.vite.ssrLoadModule("/src/shell.ts");+ sessions = await env.vite.ssrLoadModule("/src/sessions.ts");+ split = await env.vite.ssrLoadModule("/src/split.ts");+ shell.appState.me = { user: "tester", org: "test" };+ shell.appState.currentView = "chats";+ shell.appState.mainEl = document.querySelector("main");});-test("single-pane navigation follows the pane identity without depending on the session list", () => {- const dockApi = { panels: [] as { params: { sessionId?: string; appId?: string } }[] };- const splitState = { active: true };- const appState = { currentView: "chats" };- let url = "/";- const sync = runInNewContext(- compile(- `${functionSource(split, "singlePaneSessionId")}\n${functionSource(shell, "syncUrlFromState")}\nsyncUrlFromState;`,- ),- {- dockApi,- splitState,- appState,- mainConversation: () => ({ state: { sessionId: "stale-main-session" } }),- panelParams: (panel: { params: object }) => panel.params,- paneKindEntry: (params: { appId?: string }) => params.appId,- contextsState: { selected: null },- UI_BASE: "",- deepLinkPath,- parseDeepLink,- messageLinkSeq,- location: {- get pathname() {- return new URL(url, "https://qm.example").pathname;- },- get search() {- return new URL(url, "https://qm.example").search;- },+const url = () => `${location.pathname}${location.search}`;+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));+async function canvas(...open: Session[]): Promise<void> {+ known = [...known, ...open.filter((s) => !known.includes(s))];+ sessions.sessionsState.list = known;+ split.mountRestoredCanvas();+ await sessions.openSession(open[0]);+ for (const next of open.slice(1)) {+ split.beginSessionDrag(next);+ document.querySelector(".zone-right")!.dispatchEvent(new Event("drop", { bubbles: true, cancelable: true }));+ await settle();+ }+}++const labels = () =>+ [...document.querySelectorAll(".split-pane-actions [aria-label]")].map((el) => el.getAttribute("aria-label"));+const closePane = async (index: number) => {+ document.querySelectorAll<HTMLButtonElement>('.split-pane-actions [aria-label="Close pane"]')[index]!.click();+ await settle();+};++test("pane header updates scan session metadata linearly and retain parent-title invalidation", async () => {+ let reads = 0;+ known = Array.from({ length: 128 }, (_, index) => {+ const row = session(`session-${index}`, index === 126 ? { parentSessionId: "session-0" } : {});+ let id = row.id;+ return Object.defineProperty(row, "id", {+ enumerable: true,+ get() {+ reads++;+ return id;},- history: {- replaceState: (_state: unknown, _title: string, next: string) => {- url = next;- },+ set(value: string) {+ id = value;},- },- ) as (override?: string | null) => void;- dockApi.panels = [{ params: { sessionId: "first" } }];- sync();- assert.equal(url, "/s/first");- url = "/s/first?seq=120";- sync();- assert.equal(url, "/s/first?seq=120");- dockApi.panels = [{ params: { sessionId: "second" } }];- sync("stale-override");- assert.equal(url, "/s/second");- dockApi.panels.push({ params: { sessionId: "third" } });- sync();- assert.equal(url, "/");- dockApi.panels.shift();- sync();- assert.equal(url, "/s/third");- dockApi.panels = [{ params: {} }];- sync();- assert.equal(url, "/");- dockApi.panels[0]!.params.sessionId = "created";- sync();- assert.equal(url, "/s/created");- dockApi.panels = [{ params: { appId: "app", sessionId: "unrelated" } }];- sync();- assert.equal(url, "/");- appState.currentView = "files";- sync();- assert.equal(url, "/files");- appState.currentView = "chats";- splitState.active = false;- sync("phone-session");- assert.equal(url, "/s/phone-session");+ });+ });+ await canvas(known[126]!, known[127]!);+ assert.equal(document.querySelector(".split-pane-parent")?.textContent?.trim(), "Title session-0");+ reads = 0;+ sessions.sessionsState.list.find((row: Session) => row.id === "session-0").title = "Renamed parent";+ split.notifyPanesChanged();+ assert.ok(reads <= known.length * 2 * 8, `Header update visited ${reads} session IDs`);+ assert.equal(document.querySelector(".split-pane-parent")?.textContent?.trim(), "Renamed parent");});-test("background canvas updates preserve non-chat detail routes", () => {- const layout = split.match(/api\.onDidLayoutChange\(\(\) => \{([^]*?)\n {2}\}\);/)?.[1];- assert.ok(layout);- for (const source of [functionSource(split, "refreshHeaders"), `function refreshHeaders() {${layout}\n}`]) {- const appState = { currentView: "crons" };- let syncs = 0;- const refresh = runInNewContext(compile(`${source}\nrefreshHeaders;`), {- appState,- syncUrlFromState: () => {- syncs++;- },- headerSignature: "",- computeHeaderSignature: () => "",- syncDocumentTitle: () => {},- paneTabs: [],- groupActions: [],- paneContents: new Map(),- host: { classList: { contains: () => true, toggle: () => {} } },- api: { panels: [{}], groups: [] },- paneDrag: null,- persistSoon: () => {},- }) as () => void;- for (const view of ["crons", "webhooks", "inbox", "skills", "contexts"]) {- appState.currentView = view;- refresh();- assert.equal(syncs, 0, `${view} detail URL must stay intact`);- }- appState.currentView = "chats";- refresh();- assert.equal(syncs, 1);+test("single-pane navigation follows the pane identity without depending on the session list", async () => {+ known = [];+ await canvas(session("first"));+ assert.equal(url(), "/s/first");+ history.replaceState(null, "", "/s/first?seq=120");+ shell.syncUrlFromState();+ assert.equal(url(), "/s/first?seq=120");+ shell.syncUrlFromState("stale-override");+ assert.equal(url(), "/s/first?seq=120");+ await canvas(session("first"), session("second"));+ assert.equal(url(), "/");+ await closePane(0);+ assert.equal(url(), "/s/second");+ shell.appState.currentView = "files";+ shell.syncUrlFromState();+ assert.equal(url(), "/files");+ shell.appState.currentView = "chats";+ split.exitSplitIfActive();+ shell.syncUrlFromState("phone-session");+ assert.equal(url(), "/s/phone-session");+});++test("background canvas updates preserve non-chat detail routes", async () => {+ known = [];+ await canvas(session("first"));+ for (const view of ["crons", "webhooks", "inbox", "skills", "contexts"]) {+ shell.appState.currentView = view;+ history.replaceState(null, "", `/${view}/detail`);+ sessions.sessionsState.list[0].title = `Renamed for ${view}`;+ split.notifyPanesChanged();+ split.openBackgroundInCanvas(session(`background-${view}`));+ await settle();+ assert.equal(url(), `/${view}/detail`, `${view} detail URL must stay intact`);}+ shell.appState.currentView = "chats";+ sessions.sessionsState.list[0].title = "Back in chats";+ split.notifyPanesChanged();+ const single = split.singlePaneSessionId();+ assert.equal(url(), single ? `/s/${single}` : "/");});-test("single and multiview headers render mutually exclusive tools and pane controls", () => {- const source = split.slice(split.indexOf("class GroupActions"), split.indexOf("function notePaneSession"));- let output = "";- const dockApi = { panels: [{}], groups: [{ id: "group", activePanel: null, panels: [] }] };- const flatten = (value: unknown): string => {- if (Array.isArray(value)) return value.map(flatten).join("");- if (typeof value === "function") return "";- return String(value ?? "");- };- const html = (strings: TemplateStringsArray, ...values: unknown[]): string =>- strings.reduce((result, part, i) => result + part + flatten(values[i]), "");- const actions = runInNewContext(compile(`${source}\nnew GroupActions();`), {- document: { createElement: () => ({}), addEventListener: () => {} },- groupActions: new Set(),- tabMenu: null,- dockApi,- html,- nothing: "",- render: (value: string) => {- output = value;- },- paneScopeId: () => null,- paneKindEntry: () => null,- PANE_TOOLS: ["Crons", "Apps", "Files", "Skills", "Memory", "Your keychain"].map((label) => ({- label,- tool: label,- glyph: label,- })),- icon: () => "",- tip: () => "",- ref: () => "",- Plus: "",- Maximize2: "",- X: "",- MoreHorizontal: "",- Shrink: "",- Expand: "",- }) as { init: (props: unknown) => void; draw: () => void; menuOpen: boolean };- let activePanelChanged: (() => void) | undefined;- actions.init({- group: {- id: "group",- api: {- onDidActivePanelChange: (listener: () => void) => {- activePanelChanged = listener;- return { dispose() {} };- },- },- },- api: { isMaximized: () => false },- });- assert.equal((output.match(/class="session-tool"/g) ?? []).length, 6);- assert.doesNotMatch(output, /split-tools-btn|Split this pane|Open full screen|Close pane/);- dockApi.panels.push({});- assert.ok(activePanelChanged);- activePanelChanged();- assert.doesNotMatch(output, /class="session-tool"/);+test("single and multiview headers render mutually exclusive tools and pane controls", async () => {+ known = [];+ await canvas(session("first"));+ assert.equal(document.querySelectorAll(".split-pane-actions .session-tool").length, 6);+ assert.deepEqual(+ labels().filter((label) => /Tools|Split this pane|Open full screen|Close pane/.test(label!)),+ [],+ );+ await canvas(session("first"), session("second"));+ assert.equal(document.querySelectorAll(".split-pane-actions .session-tool").length, 0);for (const label of ["Tools", "Split this pane with a new session", "Open full screen", "Close pane"])- assert.ok(output.includes(`aria-label="${label}"`) || output.includes(`aria-label=${label}`));- actions.menuOpen = true;- dockApi.panels.pop();- actions.draw();- assert.equal(actions.menuOpen, false);- assert.doesNotMatch(output, /split-tools-btn|role="menu"|Close pane/);+ assert.ok(labels().includes(label), label);+ document.querySelector<HTMLButtonElement>(".split-tools-btn")!.click();+ assert.ok(document.querySelector('.split-pane-actions [role="menu"]'));+ await closePane(1);+ assert.equal(document.querySelector('.split-pane-actions [role="menu"]'), null);+ assert.equal(document.querySelector(".split-tools-btn"), null);+ assert.equal(document.querySelectorAll('.split-pane-actions [aria-label="Close pane"]').length, 0);});diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex e9c05037e..c3b46981e 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -3,12 +3,7 @@ import { principalEntitledToScope } from "../resolution/context-filter.ts";import { createCurrentScopeMembers } from "../resolution/scope-membership.ts";import { notifyDeploymentShared } from "../deploy/share-notice.ts";import { deploymentShareScope } from "../deploy/email-access.ts";-import {- sessionTreeRoot,- sessionTreeRunCount,- SUBAGENT_TREE_RUN_CAP,- workingSessionThreadRefs,-} from "../sessions/session-syscalls.ts";+import { workingSessionThreadRefs } from "../sessions/session-syscalls.ts";import type { PendingApprovalRecord } from "../types.ts";import { orgId as orgIdOf } from "../config.ts";import { parseScopeId, scopeId } from "../types.ts";@@ -93,7 +88,6 @@ export function createSessionMethods(| "authorizesCapabilityScope"| "updateSession"| "detachSession"- | "adoptSession"| "regenerateTitle"| "spawnSession"| "discardSession"@@ -860,42 +854,6 @@ export function createSessionMethods(: detach();},- async adoptSession(sessionId, parentSessionId, principalId) {- const adopt = async () => {- const child = await sessionForViewer(sessionId, principalId);- const parent = await sessionForViewer(parentSessionId, principalId);- if (!child?.spawnMeta || !parent || child.scopeId !== parent.scopeId || child.id === parent.id) return null;- if (parent.threadRef.startsWith("swarm:")) return null;- if (!(await principalCanWriteScope(principalId, child.scopeId))) return null;- const seen = new Set([child.id]);- let ancestor = parent;- while (true) {- if (seen.has(ancestor.id)) return null;- seen.add(ancestor.id);- if (!ancestor.parentSessionId) break;- const next = await deps.sessions.get(ancestor.parentSessionId);- if (!next) return null;- ancestor = next;- }- const root = await sessionTreeRoot(deps.sessions, parent);- const childRoot = await sessionTreeRoot(deps.sessions, child);- if (- root.id !== childRoot.id &&- (await sessionTreeRunCount(deps.sessions, deps.runs, root)) +- (await sessionTreeRunCount(deps.sessions, deps.runs, child)) >- SUBAGENT_TREE_RUN_CAP- )- return null;- await deps.sessions.setParentSession(child.id, parent.id);- return { adopted: true as const };- };- return deps.advisoryLock- ? deps.advisoryLock.withLock("session-tree-admission", () =>- deps.advisoryLock!.withLock("session-run-admission", adopt),- )- : adopt();- },-async regenerateTitle(sessionId, principalId) {const session = await sessionForViewer(sessionId, principalId);if (!session) return null;diff --git a/src/api/app-types.ts b/src/api/app-types.tsindex 94a61d9cc..bef4df075 100644--- a/src/api/app-types.ts+++ b/src/api/app-types.ts@@ -395,7 +395,6 @@ export interface App {): Promise<Session | null>;regenerateTitle(sessionId: string, principalId: string): Promise<{ title: string | null } | null>;detachSession(sessionId: string, principalId: string): Promise<{ detached: true } | null>;- adoptSession(sessionId: string, parentSessionId: string, principalId: string): Promise<{ adopted: true } | null>;spawnSession(principalId: string, opts: { scopeId: ScopeId; title?: string }): Promise<{ session: Session } | null>;discardSession(sessionId: string, principalId: string): Promise<boolean>;forkSession(diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex be9679230..d02ba6165 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -86,14 +86,6 @@ async function detachSession(ctx: ApiCtx): Promise<void> {return sendJson(res, 200, out);}-async function adoptSession(ctx: ApiCtx): Promise<void> {- const { principalId, parentSessionId } = ctx.body as { principalId?: unknown; parentSessionId?: unknown };- if (typeof principalId !== "string" || typeof parentSessionId !== "string" || !principalId || !parentSessionId)- return sendJson(ctx.res, 400, { error: "bad_request" });- const out = await ctx.app.adoptSession(ctx.params.id!, parentSessionId, principalId);- return sendJson(ctx.res, out ? 200 : 404, out ?? { error: "not_found" });-}-async function forkSession(ctx: ApiCtx): Promise<void> {const { res, app, body } = ctx;const id = ctx.params.id!;@@ -1315,7 +1307,6 @@ export const surfaceRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "GET", path: "/v1/sessions/search", auth: "source", handle: searchSessions },{ method: "POST", path: "/v1/sessions/:id/title", auth: "source", handle: regenerateSessionTitle },{ method: "POST", path: "/v1/sessions/:id/fork", auth: "source", handle: forkSession },- { method: "POST", path: "/v1/sessions/:id/adopt", auth: "source", handle: adoptSession },{ method: "POST", path: "/v1/sessions/:id/detach", auth: "source", handle: detachSession },{ method: "GET", path: "/v1/sessions/:id/approvals", auth: "source", handle: listSessionApprovals },{ method: "GET", path: "/v1/sessions/:id/background", auth: "source", handle: getSessionBackground },diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.tsindex 61fc1c318..cb3bacf75 100644--- a/src/api/user-scoped-routes.ts+++ b/src/api/user-scoped-routes.ts@@ -58,7 +58,6 @@ const USER_SCOPED: Rule[] = [pat("POST", "/v1/sessions/:id/title", { in: "body", name: "principalId" }),pat("POST", "/v1/sessions/:id/fork", { in: "body", name: "principalId" }),pat("POST", "/v1/sessions/:id/detach", { in: "body", name: "principalId" }),- pat("POST", "/v1/sessions/:id/adopt", { in: "body", name: "principalId" }),pat("GET", "/v1/sessions", { in: "query", name: "principalId" }),pat("GET", "/v1/resources/search", { in: "query", name: "principalId" }),pat("GET", "/v1/contexts", { in: "query", name: "principalId" }),diff --git a/test/session-parentage.test.ts b/test/session-parentage.test.tsindex 31c9dbbb5..0ace57f85 100644--- a/test/session-parentage.test.ts+++ b/test/session-parentage.test.ts@@ -7,37 +7,22 @@ import { join } from "node:path";import { buildApp } from "../src/wiring.ts";import { SUBAGENT_TREE_RUN_CAP } from "../src/sessions/session-syscalls.ts";import { testConfig } from "./support/test-config.ts";-import type { ScopeId } from "../src/types.ts";-test("session parentage requires current membership and rejects cycles and scope changes", async () => {+test("detaching a subagent session requires current channel membership", async () => {const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "session-parentage-")) }));await built.app.upsertDirectory([{ principalId: "U1", displayName: "User One", type: "internal" }]);const channels = [{ channelId: "C1", name: "private", isPrivate: true }];await built.app.upsertChannels(channels, [{ channelId: "C1", principalId: "U1" }]);- const create = async (name: string, scope: ScopeId = "channel:C1") => {- const session = await built.sessions.getOrCreateByThread(`agent:main:subagent:${name}`, "channel", scope);+ const create = async (name: string) => {+ const session = await built.sessions.getOrCreateByThread(`agent:main:subagent:${name}`, "channel", "channel:C1");await built.sessions.addParticipant(session.id, "U1");- await built.sessions.setSpawnMeta(session.id, {- surface: "slack",- actor: { id: "U1", type: "internal" },- conversation: {- kind: "channel",- threadRef: "ch:C1",- channelRef: "C1",- audience: [{ id: "U1", type: "internal" }],- },- });return session;};const parent = await create("parent");const child = await create("child");- const otherScope = await create("other", "personal:U1");- assert.deepEqual(await built.app.adoptSession(child.id, parent.id, "U1"), { adopted: true });- assert.equal(await built.app.adoptSession(parent.id, child.id, "U1"), null);- assert.equal(await built.app.adoptSession(child.id, otherScope.id, "U1"), null);+ await built.sessions.setParentSession(child.id, parent.id);await built.app.upsertChannels(channels, [], Date.now() + 1, ["C1"]);assert.equal(await built.app.detachSession(child.id, "U1"), null);- assert.equal(await built.app.adoptSession(child.id, parent.id, "U1"), null);assert.equal((await built.sessions.get(child.id))?.parentSessionId, parent.id);await built.app.upsertChannels(channels, [{ channelId: "C1", principalId: "U1" }], Date.now() + 2, ["C1"]);assert.deepEqual(await built.app.detachSession(child.id, "U1"), { detached: true });