diff --git a/paseo-shared-browser/README.md b/paseo-shared-browser/README.md index fe107e42..d79120e5 100644 --- a/paseo-shared-browser/README.md +++ b/paseo-shared-browser/README.md @@ -157,6 +157,26 @@ The provider launches the stdio adapter on the Paseo daemon host, beside the dae runtime. Web, desktop, and mobile clients never own or host the adapter or Chromium, and a client disconnect does not close or reset either process. +### Choosing which agents get the tool + +By default every new agent gets the adapter. Settings, under Shared Browser, can restrict that: + +- **Every new agent** (the default) injects the adapter into every new agent, as above. +- **Only the agents listed** injects it only into a new agent whose provider id is listed, or whose + workspace id or project id is listed. Separate entries with commas or new lines. An empty + configuration means no agent. + +`agent.create` carries the provider and the working directory but no labels and no workspace id, so a +workspace or project is matched by directory: the workspace whose directory is the agent's directory or +the deepest one containing it. Both directories are normalized first (separators, `.` and `..` segments), +so a path that climbs out of a workspace does not match it. The lookup includes background workspaces. If +the list is longer than 20 pages of 200, or the lookup fails, those lists match nothing. Workspaces that +share a directory cannot be told apart, so listing any of them matches them all. Matching is lexical: nothing on disk is consulted, so symlinks are not resolved and letter case is not folded. The settings read has a 2 second deadline, and a read that is too slow is treated like an unreadable setting, so every new agent gets the tool. The workspace lookup has its own 2 second deadline, and a timeout there counts as no match. Either timeout logs one line, and a slow lookup never holds up agent creation. The check runs before the adapter, its credential or the supervisor are set up, so +an agent that is not allowed costs nothing. It applies to agents created after the setting is saved. A +setting that cannot be read or is invalid falls back to every new agent, and the plugin log gets one line +saying so. The settings screen reports an entry over 256 characters or a list over 200 entries instead of +cutting it off. + ## Runtime environment overrides The plugin recognizes only these deployment overrides: diff --git a/paseo-shared-browser/client/agent-access-settings.tsx b/paseo-shared-browser/client/agent-access-settings.tsx new file mode 100644 index 00000000..e8a38e45 --- /dev/null +++ b/paseo-shared-browser/client/agent-access-settings.tsx @@ -0,0 +1,143 @@ +import { type PluginSurfaceProps, useSettings } from "@getpaseo/plugin/client"; +import { + SettingsAction, + SettingsCard, + SettingsInput, + type SettingsInputHandle, + SettingsSection, + SettingsSelect, +} from "@getpaseo/plugin/client/ui"; +import { useRef, useState } from "react"; +import { Text } from "react-native"; +import { type AgentAccessMode, agentAccessSettings, parseEntries } from "../shared/agent-access"; + +const MODE_OPTIONS: readonly { label: string; value: AgentAccessMode }[] = [ + { label: "Every new agent", value: "all" }, + { label: "Only the agents listed below", value: "listed" }, +]; + +type ListName = "providers" | "workspaces" | "projects"; +const NO_ERRORS: Record = { + providers: null, + workspaces: null, + projects: null, +}; + +/** Settings screen: which new agents get the browser tool. */ +export function AgentAccessSettings({ theme }: PluginSurfaceProps) { + const settings = useSettings(agentAccessSettings); + const providers = useRef(null); + const workspaces = useRef(null); + const projects = useRef(null); + // Errors belong to the revision they were found on; a newer revision (another client saved) clears them. + const [found, setFound] = useState<{ + revision: string | null; + errors: Record; + }>({ revision: null, errors: NO_ERRORS }); + const muted = { color: theme.colors.foregroundMuted, fontSize: 13, lineHeight: 19 }; + + if (settings.status === "loading") { + return ( + + Loading + + ); + } + if (settings.status !== "ready") { + return ( + + {settings.error} + + + {settings.status === "invalid" ? ( + + ) : null} + + + ); + } + + const { values } = settings; + const listErrors = found.revision === settings.revision ? found.errors : NO_ERRORS; + const save = (next: typeof values) => void settings.save(next, settings.revision); + // The lists as typed, parsed the same way for Save and for a mode change, so unsaved text is never + // lost to the revision remount. A list that does not parse shows its error and nothing is saved. + const typedLists = () => { + const parsed = { + providers: parseEntries(providers.current?.getText() ?? ""), + workspaces: parseEntries(workspaces.current?.getText() ?? ""), + projects: parseEntries(projects.current?.getText() ?? ""), + }; + const errors = { + providers: parsed.providers.error, + workspaces: parsed.workspaces.error, + projects: parsed.projects.error, + }; + setFound({ revision: settings.revision, errors }); + if (errors.providers || errors.workspaces || errors.projects) return null; + return { + providers: parsed.providers.entries, + workspaces: parsed.workspaces.entries, + projects: parsed.projects.entries, + }; + }; + return ( + + {/* Keyed on the revision, so the text inputs start over from the saved lists when another client changes them. */} + + { + const lists = typedLists(); + if (lists) save({ ...values, ...lists, mode }); + }} + /> + {}} + disabled={settings.saving} + /> + {}} + disabled={settings.saving} + /> + {}} + disabled={settings.saving} + /> + { + const lists = typedLists(); + if (lists) save({ ...values, ...lists }); + }} + /> + + + ); +} diff --git a/paseo-shared-browser/index.client.tsx b/paseo-shared-browser/index.client.tsx index ce768f30..f1c1453b 100644 --- a/paseo-shared-browser/index.client.tsx +++ b/paseo-shared-browser/index.client.tsx @@ -1,4 +1,5 @@ import type { PluginClientContext } from "@getpaseo/plugin/client"; +import { AgentAccessSettings } from "./client/agent-access-settings"; import { contributeSharedBrowserClient, SharedBrowserPanel } from "./client/browser"; import { contributeSharedBrowserSidebar } from "./client/sidebar"; @@ -21,9 +22,16 @@ export default function contribute(client: PluginClientContext) { }, }); + const removeSettings = client.addSettingsScreen({ + id: "agent-access", + title: "Shared Browser", + icon: "PanelsTopLeft", + Component: AgentAccessSettings, + }); const removeSidebar = contributeSharedBrowserSidebar(client); const cleanup = contributeSharedBrowserClient(client); return () => { + removeSettings(); removeSidebar(); return cleanup(); }; diff --git a/paseo-shared-browser/index.server.ts b/paseo-shared-browser/index.server.ts index f8bca316..d8cdb626 100644 --- a/paseo-shared-browser/index.server.ts +++ b/paseo-shared-browser/index.server.ts @@ -1,7 +1,7 @@ import { randomBytes } from "node:crypto"; import { homedir } from "node:os"; import { join } from "node:path"; -import type { PluginServerContext } from "@getpaseo/plugin/server"; +import type { PluginHookContext, PluginServerContext } from "@getpaseo/plugin/server"; import { bindAgentTicket, cleanupBrowserServer, @@ -33,6 +33,13 @@ import { revokeAgentBrowserAccess, } from "./server/browser"; import { resolveBrowserRuntimeRoot } from "./server/runtime-path"; +import { listAllWorkspaces } from "./server/workspace-list"; +import { + accessFromState, + agentAccessSettings, + agentGetsBrowser, + DEFAULT_AGENT_ACCESS, +} from "./shared/agent-access"; import { acquireControlRpc, applyDevicePresetRpc, @@ -63,25 +70,34 @@ import { readBrowserVideoRpc } from "./shared/browser-video"; const TICKET_ENV = "PASEO_SHARED_BROWSER_TICKET"; const MCP_SERVER_ID = "shared-browser"; const TICKET_ISSUE_TIMEOUT_MS = 2_000; +const ACCESS_DECISION_TIMEOUT_MS = 2_000; -async function issueTicketWithinDeadline(ticket: string): Promise { +/** The result of `work`, or a rejection when it has not settled within `ms`. */ +async function withinDeadline(work: Promise, ms: number, message: string): Promise { let timer: NodeJS.Timeout | undefined; try { - await Promise.race([ - issueAgentTicket(ticket), + return await Promise.race([ + work, new Promise((_, reject) => { - timer = setTimeout( - () => reject(new Error("Shared Browser ticket issuance timed out")), - TICKET_ISSUE_TIMEOUT_MS, - ); + timer = setTimeout(() => reject(new Error(message)), ms); timer.unref(); }), ]); + } finally { + clearTimeout(timer); + } +} + +async function issueTicketWithinDeadline(ticket: string): Promise { + try { + await withinDeadline( + issueAgentTicket(ticket), + TICKET_ISSUE_TIMEOUT_MS, + "Shared Browser ticket issuance timed out", + ); return true; } catch { return false; - } finally { - clearTimeout(timer); } } @@ -95,6 +111,45 @@ function mcpBundlePath(): string { export default function contribute(server: PluginServerContext) { server.registerSettings(browserDisplayPreferences); + const agentAccess = server.registerSettings(agentAccessSettings); + // The deadline covers the settings read alone: a setting that cannot be read in time is an unreadable + // setting, and that falls back to the default (every new agent). + const readAccess = async () => { + try { + const state = await withinDeadline( + Promise.resolve(agentAccess.read()), + ACCESS_DECISION_TIMEOUT_MS, + "the read timed out", + ); + const access = accessFromState(state); + if (access === DEFAULT_AGENT_ACCESS) { + console.warn( + `shared-browser: the agent-access setting is ${state?.status ?? "missing"}; every new agent gets the browser tool`, + ); + } + return access; + } catch (error) { + console.warn( + `shared-browser: the agent-access setting could not be read (${error instanceof Error ? error.message : "error"}); every new agent gets the browser tool`, + ); + return DEFAULT_AGENT_ACCESS; + } + }; + // The workspace lookup has its own deadline; a timeout or any other failure there is no match. + const lookupWorkspaces = async (paseo: PluginHookContext["paseo"]) => { + try { + return await withinDeadline( + listAllWorkspaces(paseo), + ACCESS_DECISION_TIMEOUT_MS, + "the workspace lookup timed out", + ); + } catch (error) { + console.warn( + `shared-browser: the workspace lookup failed (${error instanceof Error ? error.message : "error"}); the agent is not matched to a workspace or project`, + ); + throw error; + } + }; server.handle(attachBrowserRpc, handleAttachBrowser); server.handle(detachBrowserRpc, handleDetachBrowser); server.handle(closeBrowserRpc, handleCloseBrowser); @@ -118,8 +173,13 @@ export default function contribute(server: PluginServerContext) { server.handle(resizeBrowserRpc, handleResizeBrowser); server.handle(applyDevicePresetRpc, handleApplyDevicePreset); server.handle(sendBrowserInputRpc, handleSendBrowserInput); - server.before("agent.create", async ({ request }) => { + server.before("agent.create", async ({ request }, context) => { if (request.config.internal) return request; + // Decide before any ticket or supervisor work, so an agent that is not allowed costs nothing. + const allowed = await agentGetsBrowser(await readAccess(), request.config, () => + lookupWorkspaces(context.paseo), + ); + if (!allowed) return request; const ticket = randomBytes(32).toString("base64url"); if (!(await issueTicketWithinDeadline(ticket))) return request; return { diff --git a/paseo-shared-browser/package.json b/paseo-shared-browser/package.json index cb928521..6dd9f152 100644 --- a/paseo-shared-browser/package.json +++ b/paseo-shared-browser/package.json @@ -50,8 +50,8 @@ "check:write": "biome check --write .", "typecheck": "tsc --noEmit", "prepare:runtime": "node scripts/prepare-runtime.mjs", - "test": "vitest run tests/contracts.test.ts tests/lease.test.ts tests/runtime-lifecycle.test.ts tests/chromium-release.test.ts tests/prepare-runtime.test.ts tests/agent-access.test.ts tests/agent-input-safety.test.ts tests/tabs.test.ts tests/tabs-runtime-loss.test.ts tests/composer-pills.test.ts tests/sidebar.test.ts tests/pointer-mapping.test.ts tests/frame-lifecycle.test.ts tests/viewport-resync.test.ts client server shared", - "test:unit": "vitest run tests/contracts.test.ts tests/lease.test.ts tests/runtime-lifecycle.test.ts tests/chromium-release.test.ts tests/prepare-runtime.test.ts tests/agent-access.test.ts tests/agent-input-safety.test.ts tests/tabs.test.ts tests/tabs-runtime-loss.test.ts tests/composer-pills.test.ts tests/sidebar.test.ts tests/pointer-mapping.test.ts tests/frame-lifecycle.test.ts tests/viewport-resync.test.ts client server shared", + "test": "vitest run tests/contracts.test.ts tests/lease.test.ts tests/runtime-lifecycle.test.ts tests/chromium-release.test.ts tests/prepare-runtime.test.ts tests/agent-access.test.ts tests/agent-filter.test.ts tests/workspace-list.test.ts tests/agent-input-safety.test.ts tests/tabs.test.ts tests/tabs-runtime-loss.test.ts tests/composer-pills.test.ts tests/sidebar.test.ts tests/pointer-mapping.test.ts tests/frame-lifecycle.test.ts tests/viewport-resync.test.ts client server shared", + "test:unit": "vitest run tests/contracts.test.ts tests/lease.test.ts tests/runtime-lifecycle.test.ts tests/chromium-release.test.ts tests/prepare-runtime.test.ts tests/agent-access.test.ts tests/agent-filter.test.ts tests/workspace-list.test.ts tests/agent-input-safety.test.ts tests/tabs.test.ts tests/tabs-runtime-loss.test.ts tests/composer-pills.test.ts tests/sidebar.test.ts tests/pointer-mapping.test.ts tests/frame-lifecycle.test.ts tests/viewport-resync.test.ts client server shared", "test:smoke": "vitest run tests/browser.smoke.test.ts tests/browser.drag-cancel.smoke.test.ts tests/xvfb.smoke.test.ts tests/browser.failed-open.smoke.test.ts tests/browser.background-tab.smoke.test.ts --testTimeout=30000", "test:tabs": "vitest run tests/browser-tabs.smoke.test.ts --testTimeout=30000", "test:video": "vitest run tests/video.smoke.test.ts --testTimeout=30000" diff --git a/paseo-shared-browser/server/workspace-list.ts b/paseo-shared-browser/server/workspace-list.ts new file mode 100644 index 00000000..edfdcd2d --- /dev/null +++ b/paseo-shared-browser/server/workspace-list.ts @@ -0,0 +1,42 @@ +import type { WorkspaceRef } from "../shared/agent-access"; + +export const WORKSPACE_PAGE_SIZE = 200; +export const WORKSPACE_PAGE_LIMIT = 20; + +interface WorkspacePage { + entries: readonly WorkspaceRef[]; + pageInfo: { nextCursor?: string | null; hasMore: boolean }; +} + +export interface WorkspaceLister { + workspaces: { + list(options: { + filter: { includeBackground: true }; + page: { limit: number; cursor?: string }; + }): Promise; + }; +} + +/** + * Every workspace the daemon knows, background ones included. An access decision made from a partial + * list could match a shallower workspace than the agent is really in, so a list that is still + * incomplete after the page limit is an error, and the caller counts it as a failed lookup. + */ +export async function listAllWorkspaces( + paseo: WorkspaceLister, + pageLimit: number = WORKSPACE_PAGE_LIMIT, +): Promise { + const workspaces: WorkspaceRef[] = []; + let cursor: string | undefined; + for (let page = 0; page < pageLimit; page += 1) { + const result = await paseo.workspaces.list({ + filter: { includeBackground: true }, + page: { limit: WORKSPACE_PAGE_SIZE, ...(cursor ? { cursor } : {}) }, + }); + workspaces.push(...result.entries); + if (!result.pageInfo.hasMore) return workspaces; + cursor = result.pageInfo.nextCursor ?? undefined; + if (!cursor) throw new Error("Workspace list reports more pages but gave no cursor"); + } + throw new Error(`Workspace list is longer than ${pageLimit} pages`); +} diff --git a/paseo-shared-browser/shared/agent-access.ts b/paseo-shared-browser/shared/agent-access.ts new file mode 100644 index 00000000..09ff32aa --- /dev/null +++ b/paseo-shared-browser/shared/agent-access.ts @@ -0,0 +1,165 @@ +/** + * Which new agents get the Shared Browser tool. + * + * "all" injects the adapter into every new agent (the behaviour before this setting existed, and the + * default). "listed" injects it only when the new agent matches an entry of one of three lists: its + * provider id, the id of its workspace, or the id of its workspace's project. An empty configuration + * means no agent. Agents that already exist are never changed. + * + * `agent.create` carries the provider and the working directory but no labels and no workspace id, so + * the workspace is found by matching the directory against the daemon's workspaces. + */ +import { defineSettings } from "@getpaseo/plugin"; +import { z } from "zod"; + +export const AGENT_ACCESS_MODES = ["all", "listed"] as const; +export type AgentAccessMode = (typeof AGENT_ACCESS_MODES)[number]; + +const MAX_ENTRIES = 200; +const MAX_ENTRY_LENGTH = 256; +const entries = z.array(z.string().min(1).max(MAX_ENTRY_LENGTH)).max(MAX_ENTRIES).default([]); + +export const agentAccessSchema = z.object({ + mode: z.enum(AGENT_ACCESS_MODES).default("all"), + providers: entries, + workspaces: entries, + projects: entries, +}); + +export type AgentAccess = z.output; + +export const agentAccessSettings = defineSettings({ + id: "agent-access", + scope: "host", + version: 1, + schema: agentAccessSchema, +}); + +/** Used when the setting cannot be read or fails validation. */ +export const DEFAULT_AGENT_ACCESS: AgentAccess = { + mode: "all", + providers: [], + workspaces: [], + projects: [], +}; + +export function accessFromState( + state: { status: "ready"; values: AgentAccess } | { status: string } | undefined, +): AgentAccess { + return state?.status === "ready" && "values" in state ? state.values : DEFAULT_AGENT_ACCESS; +} + +export interface NewAgent { + provider: string; + cwd: string; +} + +export interface WorkspaceRef { + id: string; + projectId: string; + workspaceDirectory?: string | undefined; +} + +/** + * A directory in one lexical canonical form: backslashes become slashes, repeated slashes collapse, and + * `.` and `..` segments resolve. An absolute path (a leading slash, or a drive such as `C:`) cannot + * climb above its root, which is `/` or `C:/`. It is the same idea as posix normalize, written out because + * shared code does not import Node modules. Nothing on disk is consulted: symlinks are not resolved and + * letter case is not folded. + */ +export function normalizeDirectory(path: string): string { + const slashed = path.replace(/\\/g, "/"); + const drive = /^[A-Za-z]:(?=\/|$)/.exec(slashed)?.[0] ?? ""; + const rest = slashed.slice(drive.length); + const absolute = drive !== "" || rest.startsWith("/"); + const kept: string[] = []; + for (const segment of rest.split("/")) { + if (segment === "" || segment === ".") continue; + if (segment !== "..") { + kept.push(segment); + } else if (kept.length > 0 && kept[kept.length - 1] !== "..") { + kept.pop(); + } else if (!absolute) { + kept.push(".."); + } + } + const joined = kept.join("/"); + return absolute ? `${drive}/${joined}` : joined; +} + +/** + * The workspaces whose directory is the agent's directory, or the deepest directory that contains it. + * Several workspaces can share one directory, so this returns all of them. + */ +export function workspacesForDirectory( + cwd: string, + workspaces: readonly WorkspaceRef[], +): WorkspaceRef[] { + const target = normalizeDirectory(cwd); + let depth = -1; + let found: WorkspaceRef[] = []; + for (const workspace of workspaces) { + if (!workspace.workspaceDirectory) continue; + const directory = normalizeDirectory(workspace.workspaceDirectory); + const prefix = directory.endsWith("/") ? directory : `${directory}/`; + if (target !== directory && !target.startsWith(prefix)) continue; + if (directory.length > depth) { + depth = directory.length; + found = [workspace]; + } else if (directory.length === depth) { + found.push(workspace); + } + } + return found; +} + +/** + * True when a new agent gets the browser tool. `listWorkspaces` is called only when a workspace or + * project is listed and the provider did not already match; if it throws, those lists do not match. + */ +export async function agentGetsBrowser( + access: AgentAccess, + agent: NewAgent, + listWorkspaces: () => Promise, +): Promise { + if (access.mode === "all") return true; + if (access.providers.includes(agent.provider)) return true; + if (access.workspaces.length === 0 && access.projects.length === 0) return false; + try { + return workspacesForDirectory(agent.cwd, await listWorkspaces()).some( + (workspace) => + access.workspaces.includes(workspace.id) || access.projects.includes(workspace.projectId), + ); + } catch { + return false; + } +} + +export const MAX_LIST_ENTRIES = MAX_ENTRIES; +export const MAX_LIST_ENTRY_LENGTH = MAX_ENTRY_LENGTH; + +/** + * The comma or line separated names typed in the settings screen. Repeats are dropped. A name over the + * length limit or a list over the entry limit is reported in `error` instead of being cut off. + */ +export function parseEntries(text: string): { entries: string[]; error: string | null } { + const entries: string[] = []; + for (const piece of text.split(/[,\n]/)) { + const name = piece.trim(); + if (name === "") continue; + if (name.length > MAX_ENTRY_LENGTH) { + return { + entries: [], + error: `An entry is longer than ${MAX_ENTRY_LENGTH} characters: ${name.slice(0, 24)}...`, + }; + } + if (!entries.includes(name)) entries.push(name); + } + if (entries.length > MAX_ENTRIES) { + return { + entries: [], + error: `A list can hold ${MAX_ENTRIES} entries; this one has ${entries.length}.`, + }; + } + return { entries, error: null }; +} diff --git a/paseo-shared-browser/tests/agent-filter.test.ts b/paseo-shared-browser/tests/agent-filter.test.ts new file mode 100644 index 00000000..0c362e9f --- /dev/null +++ b/paseo-shared-browser/tests/agent-filter.test.ts @@ -0,0 +1,270 @@ +import { describe, expect, it, vi } from "vitest"; +import { + type AgentAccess, + accessFromState, + agentAccessSchema, + agentGetsBrowser, + DEFAULT_AGENT_ACCESS, + normalizeDirectory, + parseEntries, + type WorkspaceRef, + workspacesForDirectory, +} from "../shared/agent-access"; + +const WORKSPACES: WorkspaceRef[] = [ + { id: "ws_a", projectId: "proj_1", workspaceDirectory: "/repos/one" }, + { id: "ws_b", projectId: "proj_1", workspaceDirectory: "/repos/one/packages/b" }, + { id: "ws_c", projectId: "proj_2", workspaceDirectory: "/repos/two/" }, + { id: "ws_d", projectId: "proj_3" }, + { id: "ws_e", projectId: "proj_4", workspaceDirectory: "/repos/shared" }, + { id: "ws_f", projectId: "proj_5", workspaceDirectory: "/repos/shared" }, +]; +const listWorkspaces = async () => WORKSPACES; +const listed = (over: Partial): AgentAccess => ({ + mode: "listed", + providers: [], + workspaces: [], + projects: [], + ...over, +}); + +describe("who gets the browser tool", () => { + const cases: [string, AgentAccess, { provider: string; cwd: string }, boolean][] = [ + ["all: any agent", DEFAULT_AGENT_ACCESS, { provider: "p", cwd: "/x" }, true], + [ + "all ignores the lists", + { ...DEFAULT_AGENT_ACCESS, providers: ["q"] }, + { provider: "p", cwd: "/x" }, + true, + ], + ["listed and empty: no agent", listed({}), { provider: "p", cwd: "/repos/one" }, false], + ["provider listed", listed({ providers: ["p"] }), { provider: "p", cwd: "/x" }, true], + ["provider not listed", listed({ providers: ["q"] }), { provider: "p", cwd: "/x" }, false], + [ + "provider is an exact match", + listed({ providers: ["pp"] }), + { provider: "p", cwd: "/x" }, + false, + ], + [ + "workspace listed, same directory", + listed({ workspaces: ["ws_a"] }), + { provider: "p", cwd: "/repos/one" }, + true, + ], + [ + "workspace listed, directory inside it", + listed({ workspaces: ["ws_a"] }), + { provider: "p", cwd: "/repos/one/src" }, + true, + ], + [ + "the deepest workspace wins", + listed({ workspaces: ["ws_a"] }), + { provider: "p", cwd: "/repos/one/packages/b/src" }, + false, + ], + [ + "the deepest workspace is the match", + listed({ workspaces: ["ws_b"] }), + { provider: "p", cwd: "/repos/one/packages/b/src" }, + true, + ], + [ + "a sibling directory is not inside", + listed({ workspaces: ["ws_a"] }), + { provider: "p", cwd: "/repos/one-other" }, + false, + ], + [ + "trailing slashes are ignored", + listed({ workspaces: ["ws_c"] }), + { provider: "p", cwd: "/repos/two" }, + true, + ], + [ + "project listed", + listed({ projects: ["proj_1"] }), + { provider: "p", cwd: "/repos/one/packages/b" }, + true, + ], + [ + "project not listed", + listed({ projects: ["proj_2"] }), + { provider: "p", cwd: "/repos/one" }, + false, + ], + [ + "no workspace contains the directory", + listed({ workspaces: ["ws_a"], projects: ["proj_1"] }), + { provider: "p", cwd: "/elsewhere" }, + false, + ], + [ + "a workspace without a directory never matches", + listed({ workspaces: ["ws_d"] }), + { provider: "p", cwd: "/repos/one" }, + false, + ], + [ + "any of the three lists is enough", + listed({ providers: ["q"], projects: ["proj_2"] }), + { provider: "p", cwd: "/repos/two/x" }, + true, + ], + ]; + it.each(cases)("%s", async (_name, access, agent, expected) => { + await expect(agentGetsBrowser(access, agent, listWorkspaces)).resolves.toBe(expected); + }); + + it("does not look up workspaces when the mode is all, the lists are empty, or the provider matched", async () => { + const lookup = vi.fn(listWorkspaces); + await agentGetsBrowser(DEFAULT_AGENT_ACCESS, { provider: "p", cwd: "/repos/one" }, lookup); + await agentGetsBrowser(listed({}), { provider: "p", cwd: "/repos/one" }, lookup); + await agentGetsBrowser( + listed({ providers: ["p"], workspaces: ["ws_a"] }), + { provider: "p", cwd: "/repos/one" }, + lookup, + ); + expect(lookup).not.toHaveBeenCalled(); + }); + + it("a failed workspace lookup matches nothing, but a listed provider still matches", async () => { + const failing = async () => { + throw new Error("daemon unavailable"); + }; + const agent = { provider: "p", cwd: "/repos/one" }; + await expect(agentGetsBrowser(listed({ workspaces: ["ws_a"] }), agent, failing)).resolves.toBe( + false, + ); + await expect( + agentGetsBrowser(listed({ providers: ["p"], workspaces: ["ws_a"] }), agent, failing), + ).resolves.toBe(true); + }); +}); + +describe("workspacesForDirectory", () => { + it("accepts Windows separators", () => { + const windows = [{ id: "w", projectId: "p", workspaceDirectory: "C:\\repos\\one" }]; + expect(workspacesForDirectory("C:\\repos\\one\\src", windows).map((w) => w.id)).toEqual(["w"]); + }); + + it("returns every workspace at the deepest matching directory", () => { + expect(workspacesForDirectory("/repos/shared/src", WORKSPACES).map((w) => w.id)).toEqual([ + "ws_e", + "ws_f", + ]); + expect(workspacesForDirectory("/elsewhere", WORKSPACES)).toEqual([]); + }); +}); + +describe("the setting", () => { + it("defaults to all, with empty lists", () => { + expect(agentAccessSchema.parse({})).toEqual(DEFAULT_AGENT_ACCESS); + }); + + it("falls back to all when the setting cannot be read or is invalid", () => { + for (const state of [undefined, { status: "invalid" }, { status: "loading" }]) { + expect(accessFromState(state)).toEqual(DEFAULT_AGENT_ACCESS); + } + expect(accessFromState({ status: "invalid", values: listed({}) } as never)).toEqual( + DEFAULT_AGENT_ACCESS, + ); + expect(accessFromState({ status: "ready", values: listed({ providers: ["p"] }) })).toEqual( + listed({ providers: ["p"] }), + ); + }); + + it("rejects an unknown mode and over-long or empty entries", () => { + expect(agentAccessSchema.safeParse({ mode: "some" }).success).toBe(false); + expect(agentAccessSchema.safeParse({ providers: [""] }).success).toBe(false); + expect(agentAccessSchema.safeParse({ projects: ["x".repeat(257)] }).success).toBe(false); + expect(agentAccessSchema.safeParse({ workspaces: Array(201).fill("w") }).success).toBe(false); + }); + + it("parses typed lists: commas or new lines, trimmed, without blanks or repeats", () => { + expect(parseEntries("a, b\nc ,, a\n \n")).toEqual({ entries: ["a", "b", "c"], error: null }); + expect(parseEntries("")).toEqual({ entries: [], error: null }); + }); + + it("reports an entry over 256 characters or a list over 200 instead of dropping it", () => { + expect(parseEntries(`ok, ${"x".repeat(257)}`).error).toMatch(/longer than 256/); + expect(parseEntries("x".repeat(256)).error).toBeNull(); + const many = Array.from({ length: 201 }, (_, i) => `w${i}`).join(","); + expect(parseEntries(many).error).toMatch(/200 entries/); + expect(parseEntries(many.replace(",w200", "")).error).toBeNull(); + }); +}); + +describe("normalizeDirectory", () => { + it.each([ + ["/repos/one/../outside", "/repos/outside"], + ["/repos/one/./src//deep/", "/repos/one/src/deep"], + ["/repos/one/src/../../..", "/"], + ["/../..", "/"], + ["/", "/"], + [".", ""], + ["C:\\repos\\one\\..\\two", "C:/repos/two"], + ["C:\\..\\repos\\one", "C:/repos/one"], + ["C:\\", "C:/"], + ["C:", "C:/"], + ["c:/a//b/", "c:/a/b"], + ["c:/../x", "c:/x"], + ["C:repos", "C:repos"], + ["../x", "../x"], + ["a/../..", ".."], + ])("%s", (input, expected) => { + expect(normalizeDirectory(input)).toBe(expected); + }); +}); + +describe("a workspace at the filesystem root", () => { + const root = [{ id: "r", projectId: "p", workspaceDirectory: "/" }]; + it("contains every absolute path, and no relative or empty one", () => { + for (const cwd of ["/", "/repos/one", "/repos/../x", "/.."]) { + expect(workspacesForDirectory(cwd, root).map((w) => w.id)).toEqual(["r"]); + } + for (const cwd of ["", ".", "repos/one", "../x"]) { + expect(workspacesForDirectory(cwd, root)).toEqual([]); + } + }); +}); + +describe("a Windows drive root", () => { + const windows = [{ id: "w", projectId: "p", workspaceDirectory: "C:\\repos\\one" }]; + it("cannot be climbed above, and is not another drive", () => { + expect(workspacesForDirectory("C:\\..\\repos\\one", windows).map((w) => w.id)).toEqual(["w"]); + expect(workspacesForDirectory("C:\\repos\\one\\src", windows).map((w) => w.id)).toEqual(["w"]); + expect(workspacesForDirectory("D:\\repos\\one", windows)).toEqual([]); + expect(workspacesForDirectory("repos/one", windows)).toEqual([]); + }); + it("a workspace at a drive root contains that drive only", () => { + const drive = [{ id: "d", projectId: "p", workspaceDirectory: "C:\\" }]; + expect(workspacesForDirectory("C:\\repos", drive).map((w) => w.id)).toEqual(["d"]); + expect(workspacesForDirectory("D:\\repos", drive)).toEqual([]); + }); +}); + +describe("dot segments cannot reach a workspace the agent is not in", () => { + const one = [{ id: "w", projectId: "p", workspaceDirectory: "/repos/one" }]; + it("does not match a path that climbs out of the workspace", () => { + expect(workspacesForDirectory("/repos/one/../outside", one)).toEqual([]); + expect(workspacesForDirectory("/repos/one/src/../../two", one)).toEqual([]); + expect(workspacesForDirectory("/repos/onex", one)).toEqual([]); + }); + it("matches a path that is inside after resolving, and a workspace directory with dots", () => { + expect(workspacesForDirectory("/repos/one/src/../lib", one).map((w) => w.id)).toEqual(["w"]); + expect(workspacesForDirectory("/repos/one/x/..", one).map((w) => w.id)).toEqual(["w"]); + const dotted = [{ id: "d", projectId: "p", workspaceDirectory: "/repos/./one/../two/" }]; + expect(workspacesForDirectory("/repos/two/src", dotted).map((w) => w.id)).toEqual(["d"]); + }); + it("picks the deepest workspace by the resolved path", () => { + const nested = [ + { id: "outer", projectId: "p", workspaceDirectory: "/repos" }, + { id: "inner", projectId: "p", workspaceDirectory: "/repos/one" }, + ]; + expect(workspacesForDirectory("/repos/x/../one/src", nested).map((w) => w.id)).toEqual([ + "inner", + ]); + }); +}); diff --git a/paseo-shared-browser/tests/contracts.test.ts b/paseo-shared-browser/tests/contracts.test.ts index ebddcb28..eaf5ccf0 100644 --- a/paseo-shared-browser/tests/contracts.test.ts +++ b/paseo-shared-browser/tests/contracts.test.ts @@ -1,7 +1,7 @@ import { readFile } from "node:fs/promises"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import contribute from "../index.server"; import { type BrowserState, @@ -60,12 +60,17 @@ type AgentCreateRequest = { env?: Record; }; -type AgentCreateHook = (input: { request: AgentCreateRequest }) => Promise; +type AgentCreateHook = ( + input: { request: AgentCreateRequest }, + context?: unknown, +) => Promise; -function captureAgentCreateHook(): AgentCreateHook { +function captureAgentCreateHook(readAccess?: () => Promise): AgentCreateHook { let hook: AgentCreateHook | undefined; contribute({ - registerSettings: vi.fn(), + registerSettings: vi.fn((definition: { id: string }) => + definition.id === "agent-access" && readAccess ? { read: readAccess } : undefined, + ), handle: vi.fn(), before: vi.fn((name: string, handler: unknown) => { if (name === "agent.create") hook = handler as AgentCreateHook; @@ -274,6 +279,205 @@ describe("agent MCP injection", () => { }); }); +describe("agent access", () => { + beforeEach(() => { + browserMocks.issueAgentTicket.mockClear(); + }); + + const ready = (values: Record) => async () => ({ + status: "ready", + values: { mode: "listed", providers: [], workspaces: [], projects: [], ...values }, + }); + const request = (provider: string, cwd = "/repos/one"): AgentCreateRequest => ({ + config: { provider, cwd }, + env: { EXISTING: "value" }, + }); + const workspaceContext = (entries: unknown[]) => ({ + paseo: { + workspaces: { + list: vi + .fn() + .mockResolvedValue({ entries, pageInfo: { nextCursor: null, hasMore: false } }), + }, + }, + }); + + it("injects only agents whose provider is listed", async () => { + const hook = captureAgentCreateHook(ready({ providers: ["codex"] })); + const allowed = await hook({ request: request("codex") }); + expect(allowed.config.mcpServers).toHaveProperty("shared-browser"); + expect(browserMocks.issueAgentTicket).toHaveBeenCalledTimes(1); + + const other = request("claude"); + await expect(hook({ request: other })).resolves.toBe(other); + expect(browserMocks.issueAgentTicket).toHaveBeenCalledTimes(1); + }); + + it("injects nothing and issues no ticket when listed and the lists are empty", async () => { + const hook = captureAgentCreateHook(ready({})); + const input = request("codex"); + await expect(hook({ request: input })).resolves.toBe(input); + expect(browserMocks.issueAgentTicket).not.toHaveBeenCalled(); + }); + + it("injects every agent in a listed workspace or project, found by directory", async () => { + const entries = [{ id: "ws_a", projectId: "proj_1", workspaceDirectory: "/repos/one" }]; + const byWorkspace = captureAgentCreateHook(ready({ workspaces: ["ws_a"] })); + const first = await byWorkspace( + { request: request("claude", "/repos/one/src") }, + workspaceContext(entries), + ); + expect(first.config.mcpServers).toHaveProperty("shared-browser"); + + const byProject = captureAgentCreateHook(ready({ projects: ["proj_1"] })); + const second = await byProject({ request: request("claude") }, workspaceContext(entries)); + expect(second.config.mcpServers).toHaveProperty("shared-browser"); + + const outside = request("claude", "/repos/two"); + await expect(byProject({ request: outside }, workspaceContext(entries))).resolves.toBe(outside); + }); + + it("treats a failed workspace lookup as no match", async () => { + const hook = captureAgentCreateHook(ready({ workspaces: ["ws_a"] })); + const input = request("claude"); + const context = { + paseo: { workspaces: { list: vi.fn().mockRejectedValue(new Error("down")) } }, + }; + await expect(hook({ request: input }, context)).resolves.toBe(input); + }); + + it("lists background workspaces too, and a list cut off at the page limit is no match", async () => { + const hook = captureAgentCreateHook(ready({ workspaces: ["ws_a"] })); + const entries = [{ id: "ws_a", projectId: "proj_1", workspaceDirectory: "/repos/one" }]; + const context = workspaceContext(entries); + await hook({ request: request("claude") }, context); + expect(context.paseo.workspaces.list).toHaveBeenCalledWith( + expect.objectContaining({ filter: { includeBackground: true } }), + ); + + const endless = { + paseo: { + workspaces: { + list: vi + .fn() + .mockResolvedValue({ entries, pageInfo: { nextCursor: "c", hasMore: true } }), + }, + }, + }; + const input = request("claude"); + await expect(hook({ request: input }, endless)).resolves.toBe(input); + expect(endless.paseo.workspaces.list).toHaveBeenCalledTimes(20); + }); + + it("does not match a directory that climbs out of a listed workspace", async () => { + const hook = captureAgentCreateHook(ready({ workspaces: ["ws_a"] })); + const entries = [{ id: "ws_a", projectId: "proj_1", workspaceDirectory: "/repos/one" }]; + const input = request("claude", "/repos/one/../outside"); + await expect(hook({ request: input }, workspaceContext(entries))).resolves.toBe(input); + }); + + describe("deadline", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it("a stalled settings read falls back to every agent, with a log line", async () => { + vi.useFakeTimers(); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const hook = captureAgentCreateHook(() => new Promise(() => {})); + const pending = hook({ request: request("claude") }); + await vi.advanceTimersByTimeAsync(2_000); + const transformed = await pending; + expect(transformed.config.mcpServers).toHaveProperty("shared-browser"); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toMatch(/timed out/); + } finally { + warn.mockRestore(); + } + }); + + it("a stalled workspace lookup counts as no match, with a log line", async () => { + vi.useFakeTimers(); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const hook = captureAgentCreateHook(ready({ workspaces: ["ws_a"] })); + const input = request("claude"); + const context = { paseo: { workspaces: { list: () => new Promise(() => {}) } } }; + const pending = hook({ request: input }, context); + await vi.advanceTimersByTimeAsync(2_000); + await expect(pending).resolves.toBe(input); + expect(browserMocks.issueAgentTicket).not.toHaveBeenCalled(); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toMatch(/lookup failed.*timed out/); + } finally { + warn.mockRestore(); + } + }); + + it("leaves no timer behind when the read and the lookup finish in time", async () => { + vi.useFakeTimers(); + const hook = captureAgentCreateHook(ready({ workspaces: ["ws_a"] })); + const entries = [{ id: "ws_a", projectId: "proj_1", workspaceDirectory: "/repos/one" }]; + const transformed = await hook({ request: request("claude") }, workspaceContext(entries)); + expect(transformed.config.mcpServers).toHaveProperty("shared-browser"); + expect(vi.getTimerCount()).toBe(0); + }); + + it("does not time out a decision that finishes in time", async () => { + vi.useFakeTimers(); + const hook = captureAgentCreateHook(ready({ providers: ["codex"] })); + const pending = hook({ request: request("codex") }); + await vi.advanceTimersByTimeAsync(1_999); + await expect(pending).resolves.toMatchObject({ + config: { mcpServers: { "shared-browser": expect.anything() } }, + }); + }); + }); + + it.each([ + ["rejects", async () => Promise.reject(new Error("unreadable"))], + [ + "throws synchronously", + () => { + throw new Error("unreadable"); + }, + ], + ["is invalid", async () => ({ status: "invalid", revision: "1", error: "bad" })], + ])("falls back to every agent, with one log line, when the setting %s", async (_name, read) => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const hook = captureAgentCreateHook(read as () => Promise); + const transformed = await hook({ request: request("anything") }); + expect(transformed.config.mcpServers).toHaveProperty("shared-browser"); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toMatch(/every new agent gets the browser tool/); + } finally { + warn.mockRestore(); + } + }); + + it("logs nothing when the setting is readable", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const hook = captureAgentCreateHook(ready({ providers: ["codex"] })); + await hook({ request: request("codex") }); + expect(warn).not.toHaveBeenCalled(); + } finally { + warn.mockRestore(); + } + }); + + it("injects every agent in the default mode", async () => { + const hook = captureAgentCreateHook(async () => ({ + status: "ready", + values: { mode: "all", providers: [], workspaces: [], projects: [] }, + })); + const transformed = await hook({ request: request("anything") }); + expect(transformed.config.mcpServers).toHaveProperty("shared-browser"); + }); +}); + describe("runtime installation compatibility", () => { it("requires at least the Node major required by agent-browser", async () => { const pluginPackage = JSON.parse( diff --git a/paseo-shared-browser/tests/workspace-list.test.ts b/paseo-shared-browser/tests/workspace-list.test.ts new file mode 100644 index 00000000..03f9978c --- /dev/null +++ b/paseo-shared-browser/tests/workspace-list.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it, vi } from "vitest"; +import { listAllWorkspaces, WORKSPACE_PAGE_LIMIT } from "../server/workspace-list"; + +const entry = (id: string) => ({ id, projectId: "p", workspaceDirectory: `/w/${id}` }); + +function pages(count: number, lastHasMore = false) { + return vi.fn( + async ({ + page, + }: { + filter: { includeBackground: true }; + page: { limit: number; cursor?: string }; + }) => { + const index = page.cursor ? Number(page.cursor) : 0; + const more = index + 1 < count || (index + 1 === count && lastHasMore); + return { + entries: [entry(`w${index}`)], + pageInfo: { nextCursor: more ? String(index + 1) : null, hasMore: more }, + }; + }, + ); +} + +describe("listAllWorkspaces", () => { + it("asks for background workspaces and follows the cursor until hasMore is false", async () => { + const list = pages(3); + const result = await listAllWorkspaces({ workspaces: { list } }); + expect(result.map((w) => w.id)).toEqual(["w0", "w1", "w2"]); + expect(list).toHaveBeenCalledTimes(3); + expect(list.mock.calls.map(([options]) => options.page.cursor)).toEqual([undefined, "1", "2"]); + for (const [options] of list.mock.calls) { + expect(options.filter).toEqual({ includeBackground: true }); + } + }); + + it("accepts a list that ends exactly on the last allowed page", async () => { + const list = pages(WORKSPACE_PAGE_LIMIT); + await expect(listAllWorkspaces({ workspaces: { list } })).resolves.toHaveLength( + WORKSPACE_PAGE_LIMIT, + ); + }); + + it("throws when hasMore is still set after the page limit", async () => { + const list = pages(WORKSPACE_PAGE_LIMIT, true); + await expect(listAllWorkspaces({ workspaces: { list } })).rejects.toThrow(/longer than/); + expect(list).toHaveBeenCalledTimes(WORKSPACE_PAGE_LIMIT); + }); + + it("throws when a page says more but gives no cursor", async () => { + const list = vi + .fn() + .mockResolvedValue({ entries: [], pageInfo: { nextCursor: null, hasMore: true } }); + await expect(listAllWorkspaces({ workspaces: { list } })).rejects.toThrow(/no cursor/); + }); +});