From bfd32261ead5aa31e3f13f612c37ce485db8dbab Mon Sep 17 00:00:00 2001 From: Keith Kowal <3362598+keithpk@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:46:16 -0800 Subject: [PATCH 1/4] feat(shared-browser): choose which new agents get the browser tool Adds an opt-in host setting, "agent-access". The default mode, "all", keeps today's behaviour. In "listed" mode the agent.create hook injects the MCP adapter only when the new agent's provider id, its workspace id or its project id is listed; an empty configuration means no agent. The check runs first in the hook, so an agent that is not allowed gets no ticket and starts no supervisor. A setting that cannot be read or is invalid falls back to "all". A small settings screen edits the mode and the lists. 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 (the deepest containing directory; workspaces sharing a directory all match). --- paseo-shared-browser/README.md | 16 ++ .../client/agent-access-settings.tsx | 106 ++++++++++ paseo-shared-browser/index.client.tsx | 8 + paseo-shared-browser/index.server.ts | 41 +++- paseo-shared-browser/package.json | 4 +- paseo-shared-browser/shared/agent-access.ts | 120 +++++++++++ .../tests/agent-filter.test.ts | 189 ++++++++++++++++++ paseo-shared-browser/tests/contracts.test.ts | 103 +++++++++- 8 files changed, 580 insertions(+), 7 deletions(-) create mode 100644 paseo-shared-browser/client/agent-access-settings.tsx create mode 100644 paseo-shared-browser/shared/agent-access.ts create mode 100644 paseo-shared-browser/tests/agent-filter.test.ts diff --git a/paseo-shared-browser/README.md b/paseo-shared-browser/README.md index fe107e420..3abe3ee35 100644 --- a/paseo-shared-browser/README.md +++ b/paseo-shared-browser/README.md @@ -157,6 +157,22 @@ 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. Workspaces that share a directory cannot be told apart, so listing any of +them matches them all. 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. + ## 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 000000000..4d84e5f7a --- /dev/null +++ b/paseo-shared-browser/client/agent-access-settings.tsx @@ -0,0 +1,106 @@ +import { type PluginSurfaceProps, useSettings } from "@getpaseo/plugin/client"; +import { + SettingsAction, + SettingsCard, + SettingsInput, + type SettingsInputHandle, + SettingsSection, + SettingsSelect, +} from "@getpaseo/plugin/client/ui"; +import { useRef } 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" }, +]; + +/** 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); + 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 save = (next: typeof values) => void settings.save(next, settings.revision); + return ( + + + save({ ...values, mode })} + /> + {}} + disabled={settings.saving} + /> + {}} + disabled={settings.saving} + /> + {}} + disabled={settings.saving} + /> + + save({ + ...values, + providers: parseEntries(providers.current?.getText() ?? ""), + workspaces: parseEntries(workspaces.current?.getText() ?? ""), + projects: parseEntries(projects.current?.getText() ?? ""), + }) + } + /> + + + ); +} diff --git a/paseo-shared-browser/index.client.tsx b/paseo-shared-browser/index.client.tsx index ce768f301..f1c1453b6 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 f8bca316f..3163f495c 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 { + accessFromState, + agentAccessSettings, + agentGetsBrowser, + DEFAULT_AGENT_ACCESS, + type WorkspaceRef, +} from "./shared/agent-access"; import { acquireControlRpc, applyDevicePresetRpc, @@ -85,6 +92,23 @@ async function issueTicketWithinDeadline(ticket: string): Promise { } } +const WORKSPACE_PAGE_SIZE = 200; +const WORKSPACE_PAGE_LIMIT = 20; + +async function listWorkspaces(paseo: PluginHookContext["paseo"]): Promise { + const workspaces: WorkspaceRef[] = []; + let cursor: string | undefined; + for (let page = 0; page < WORKSPACE_PAGE_LIMIT; page += 1) { + const result = await paseo.workspaces.list({ + page: { limit: WORKSPACE_PAGE_SIZE, ...(cursor ? { cursor } : {}) }, + }); + workspaces.push(...result.entries); + cursor = result.pageInfo.nextCursor ?? undefined; + if (!result.pageInfo.hasMore || !cursor) break; + } + return workspaces; +} + function paseoHome(): string { return process.env.PASEO_HOME ?? join(homedir(), ".paseo"); } @@ -95,6 +119,14 @@ function mcpBundlePath(): string { export default function contribute(server: PluginServerContext) { server.registerSettings(browserDisplayPreferences); + const agentAccess = server.registerSettings(agentAccessSettings); + const readAccess = async () => { + try { + return accessFromState(await agentAccess.read()); + } catch { + return DEFAULT_AGENT_ACCESS; + } + }; server.handle(attachBrowserRpc, handleAttachBrowser); server.handle(detachBrowserRpc, handleDetachBrowser); server.handle(closeBrowserRpc, handleCloseBrowser); @@ -118,8 +150,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, () => + listWorkspaces(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 cb9285218..8b756186f 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/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/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/shared/agent-access.ts b/paseo-shared-browser/shared/agent-access.ts new file mode 100644 index 000000000..60c5b3c32 --- /dev/null +++ b/paseo-shared-browser/shared/agent-access.ts @@ -0,0 +1,120 @@ +/** + * 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; +} + +const trimEnd = (path: string) => path.replace(/\\/g, "/").replace(/\/+$/, ""); + +/** + * 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 = trimEnd(cwd); + let depth = -1; + let found: WorkspaceRef[] = []; + for (const workspace of workspaces) { + if (!workspace.workspaceDirectory) continue; + const directory = trimEnd(workspace.workspaceDirectory); + if (target !== directory && !target.startsWith(`${directory}/`)) 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; + } +} + +/** The comma or line separated names typed in the settings screen. */ +export function parseEntries(text: string): string[] { + const names: string[] = []; + for (const piece of text.split(/[,\n]/)) { + const name = piece.trim(); + if (name !== "" && name.length <= MAX_ENTRY_LENGTH && !names.includes(name)) names.push(name); + } + return names.slice(0, MAX_ENTRIES); +} 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 000000000..5522920e8 --- /dev/null +++ b/paseo-shared-browser/tests/agent-filter.test.ts @@ -0,0 +1,189 @@ +import { describe, expect, it, vi } from "vitest"; +import { + type AgentAccess, + accessFromState, + agentAccessSchema, + agentGetsBrowser, + DEFAULT_AGENT_ACCESS, + 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(["a", "b", "c"]); + expect(parseEntries("")).toEqual([]); + expect(parseEntries("x".repeat(257))).toEqual([]); + }); +}); diff --git a/paseo-shared-browser/tests/contracts.test.ts b/paseo-shared-browser/tests/contracts.test.ts index ebddcb281..643b96e21 100644 --- a/paseo-shared-browser/tests/contracts.test.ts +++ b/paseo-shared-browser/tests/contracts.test.ts @@ -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,98 @@ 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.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 when the setting %s", async (_name, read) => { + const hook = captureAgentCreateHook(read as () => Promise); + const transformed = await hook({ request: request("anything") }); + expect(transformed.config.mcpServers).toHaveProperty("shared-browser"); + }); + + 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( From 03d1e01b33f4d2c108e74705a23da1a4f6cd97db Mon Sep 17 00:00:00 2001 From: Keith Kowal <3362598+keithpk@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:54:24 -0800 Subject: [PATCH 2/4] fix(shared-browser): bound and harden the agent access decision Normalize both directories before matching, so a path with dot segments cannot match a workspace it is not in. List background workspaces and treat a list still incomplete after the page limit as a failed lookup. Race the whole decision against a 2 second deadline, where a timeout counts as no match. Key the settings inputs on the revision, report an over-long entry or list instead of dropping it, and log one line when an unreadable setting falls back to every agent. --- paseo-shared-browser/README.md | 12 ++- .../client/agent-access-settings.tsx | 38 ++++++-- paseo-shared-browser/index.server.ts | 71 ++++++++------ paseo-shared-browser/package.json | 4 +- paseo-shared-browser/server/workspace-list.ts | 42 +++++++++ paseo-shared-browser/shared/agent-access.ts | 55 +++++++++-- .../tests/agent-filter.test.ts | 52 +++++++++- paseo-shared-browser/tests/contracts.test.ts | 94 ++++++++++++++++++- .../tests/workspace-list.test.ts | 55 +++++++++++ 9 files changed, 364 insertions(+), 59 deletions(-) create mode 100644 paseo-shared-browser/server/workspace-list.ts create mode 100644 paseo-shared-browser/tests/workspace-list.test.ts diff --git a/paseo-shared-browser/README.md b/paseo-shared-browser/README.md index 3abe3ee35..ff12e9133 100644 --- a/paseo-shared-browser/README.md +++ b/paseo-shared-browser/README.md @@ -168,10 +168,16 @@ By default every new agent gets the adapter. Settings, under Shared Browser, can `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. Workspaces that share a directory cannot be told apart, so listing any of -them matches them all. The check runs before the adapter, its credential or the supervisor are set up, so +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. The whole decision (the +settings read and the lookup) has a 2 second deadline, and a timeout counts as no match, so 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. +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 diff --git a/paseo-shared-browser/client/agent-access-settings.tsx b/paseo-shared-browser/client/agent-access-settings.tsx index 4d84e5f7a..0565e89d1 100644 --- a/paseo-shared-browser/client/agent-access-settings.tsx +++ b/paseo-shared-browser/client/agent-access-settings.tsx @@ -7,7 +7,7 @@ import { SettingsSection, SettingsSelect, } from "@getpaseo/plugin/client/ui"; -import { useRef } from "react"; +import { useRef, useState } from "react"; import { Text } from "react-native"; import { type AgentAccessMode, agentAccessSettings, parseEntries } from "../shared/agent-access"; @@ -16,12 +16,20 @@ const MODE_OPTIONS: readonly { label: string; value: AgentAccessMode }[] = [ { 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); + const [listErrors, setListErrors] = useState>(NO_ERRORS); const muted = { color: theme.colors.foregroundMuted, fontSize: 13, lineHeight: 19 }; if (settings.status === "loading") { @@ -53,7 +61,8 @@ export function AgentAccessSettings({ theme }: PluginSurfaceProps) { const save = (next: typeof values) => void settings.save(next, settings.revision); return ( - + {/* Keyed on the revision, so the text inputs start over from the saved lists when another client changes them. */} + {}} disabled={settings.saving} /> @@ -76,6 +86,7 @@ export function AgentAccessSettings({ theme }: PluginSurfaceProps) { label="Workspace ids" hint="Every new agent in a listed workspace gets the tool." initialValue={values.workspaces.join(", ")} + error={listErrors.workspaces} onChangeText={() => {}} disabled={settings.saving} /> @@ -84,6 +95,7 @@ export function AgentAccessSettings({ theme }: PluginSurfaceProps) { label="Project ids" hint="Every new agent in a workspace of a listed project gets the tool." initialValue={values.projects.join(", ")} + error={listErrors.projects} onChangeText={() => {}} disabled={settings.saving} /> @@ -91,14 +103,26 @@ export function AgentAccessSettings({ theme }: PluginSurfaceProps) { label="Save the lists" actionLabel="Save" disabled={settings.saving} - onPress={() => - save({ - ...values, + onPress={() => { + 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, + }; + setListErrors(errors); + if (errors.providers || errors.workspaces || errors.projects) return; + save({ + ...values, + providers: parsed.providers.entries, + workspaces: parsed.workspaces.entries, + projects: parsed.projects.entries, + }); + }} /> diff --git a/paseo-shared-browser/index.server.ts b/paseo-shared-browser/index.server.ts index 3163f495c..4dc685c06 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 { PluginHookContext, PluginServerContext } from "@getpaseo/plugin/server"; +import type { PluginServerContext } from "@getpaseo/plugin/server"; import { bindAgentTicket, cleanupBrowserServer, @@ -33,12 +33,12 @@ import { revokeAgentBrowserAccess, } from "./server/browser"; import { resolveBrowserRuntimeRoot } from "./server/runtime-path"; +import { listAllWorkspaces } from "./server/workspace-list"; import { accessFromState, agentAccessSettings, agentGetsBrowser, DEFAULT_AGENT_ACCESS, - type WorkspaceRef, } from "./shared/agent-access"; import { acquireControlRpc, @@ -70,43 +70,35 @@ 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(); }), ]); - return true; - } catch { - return false; } finally { clearTimeout(timer); } } -const WORKSPACE_PAGE_SIZE = 200; -const WORKSPACE_PAGE_LIMIT = 20; - -async function listWorkspaces(paseo: PluginHookContext["paseo"]): Promise { - const workspaces: WorkspaceRef[] = []; - let cursor: string | undefined; - for (let page = 0; page < WORKSPACE_PAGE_LIMIT; page += 1) { - const result = await paseo.workspaces.list({ - page: { limit: WORKSPACE_PAGE_SIZE, ...(cursor ? { cursor } : {}) }, - }); - workspaces.push(...result.entries); - cursor = result.pageInfo.nextCursor ?? undefined; - if (!result.pageInfo.hasMore || !cursor) break; +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; } - return workspaces; } function paseoHome(): string { @@ -122,8 +114,18 @@ export default function contribute(server: PluginServerContext) { const agentAccess = server.registerSettings(agentAccessSettings); const readAccess = async () => { try { - return accessFromState(await agentAccess.read()); - } catch { + const state = await agentAccess.read(); + 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.name : "error"}); every new agent gets the browser tool`, + ); return DEFAULT_AGENT_ACCESS; } }; @@ -153,9 +155,16 @@ export default function contribute(server: PluginServerContext) { 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, () => - listWorkspaces(context.paseo), - ); + // The whole decision (settings read and workspace lookup) shares one deadline, so a stalled lookup + // cannot hold up agent creation; a timeout counts as no match. + const allowed = await withinDeadline( + (async () => + agentGetsBrowser(await readAccess(), request.config, () => + listAllWorkspaces(context.paseo), + ))(), + ACCESS_DECISION_TIMEOUT_MS, + "Shared Browser access decision timed out", + ).catch(() => false); if (!allowed) return request; const ticket = randomBytes(32).toString("base64url"); if (!(await issueTicketWithinDeadline(ticket))) return request; diff --git a/paseo-shared-browser/package.json b/paseo-shared-browser/package.json index 8b756186f..6dd9f1529 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-filter.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/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 000000000..edfdcd2d7 --- /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 index 60c5b3c32..71f5ec3bd 100644 --- a/paseo-shared-browser/shared/agent-access.ts +++ b/paseo-shared-browser/shared/agent-access.ts @@ -60,7 +60,27 @@ export interface WorkspaceRef { workspaceDirectory?: string | undefined; } -const trimEnd = (path: string) => path.replace(/\\/g, "/").replace(/\/+$/, ""); +/** + * A directory in one canonical form: backslashes become slashes, repeated slashes collapse, and `.` + * and `..` segments resolve (a `..` above the root of an absolute path stays at the root). This is + * what posix normalize does; it is written out here because shared code does not import Node modules. + */ +export function normalizeDirectory(path: string): string { + const absolute = path.replace(/\\/g, "/").startsWith("/"); + const kept: string[] = []; + for (const segment of path.replace(/\\/g, "/").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 ? `/${joined}`.replace(/\/+$/, "") : joined; +} /** * The workspaces whose directory is the agent's directory, or the deepest directory that contains it. @@ -70,12 +90,12 @@ export function workspacesForDirectory( cwd: string, workspaces: readonly WorkspaceRef[], ): WorkspaceRef[] { - const target = trimEnd(cwd); + const target = normalizeDirectory(cwd); let depth = -1; let found: WorkspaceRef[] = []; for (const workspace of workspaces) { if (!workspace.workspaceDirectory) continue; - const directory = trimEnd(workspace.workspaceDirectory); + const directory = normalizeDirectory(workspace.workspaceDirectory); if (target !== directory && !target.startsWith(`${directory}/`)) continue; if (directory.length > depth) { depth = directory.length; @@ -109,12 +129,31 @@ export async function agentGetsBrowser( } } -/** The comma or line separated names typed in the settings screen. */ -export function parseEntries(text: string): string[] { - const names: string[] = []; +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 !== "" && name.length <= MAX_ENTRY_LENGTH && !names.includes(name)) names.push(name); + 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 names.slice(0, MAX_ENTRIES); + return { entries, error: null }; } diff --git a/paseo-shared-browser/tests/agent-filter.test.ts b/paseo-shared-browser/tests/agent-filter.test.ts index 5522920e8..3f3c66678 100644 --- a/paseo-shared-browser/tests/agent-filter.test.ts +++ b/paseo-shared-browser/tests/agent-filter.test.ts @@ -5,6 +5,7 @@ import { agentAccessSchema, agentGetsBrowser, DEFAULT_AGENT_ACCESS, + normalizeDirectory, parseEntries, type WorkspaceRef, workspacesForDirectory, @@ -182,8 +183,53 @@ describe("the setting", () => { }); it("parses typed lists: commas or new lines, trimmed, without blanks or repeats", () => { - expect(parseEntries("a, b\nc ,, a\n \n")).toEqual(["a", "b", "c"]); - expect(parseEntries("")).toEqual([]); - expect(parseEntries("x".repeat(257))).toEqual([]); + 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"], + ["../x", "../x"], + ["a/../..", ".."], + ])("%s", (input, expected) => { + expect(normalizeDirectory(input)).toBe(expected); + }); +}); + +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 643b96e21..c6d2ab78d 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, @@ -346,6 +346,72 @@ describe("agent access", () => { 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.each([ + ["the settings read", () => new Promise(() => {}), undefined], + [ + "the workspace lookup", + ready({ workspaces: ["ws_a"] }), + { paseo: { workspaces: { list: () => new Promise(() => {}) } } }, + ], + ])( + "a stalled %s counts as no match and does not block creation", + async (_name, read, context) => { + vi.useFakeTimers(); + const hook = captureAgentCreateHook(read as () => Promise); + const input = request("claude"); + const pending = hook({ request: input }, context); + await vi.advanceTimersByTimeAsync(2_000); + await expect(pending).resolves.toBe(input); + expect(browserMocks.issueAgentTicket).not.toHaveBeenCalled(); + }, + ); + + 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"))], [ @@ -355,10 +421,28 @@ describe("agent access", () => { }, ], ["is invalid", async () => ({ status: "invalid", revision: "1", error: "bad" })], - ])("falls back to every agent when the setting %s", async (_name, read) => { - const hook = captureAgentCreateHook(read as () => Promise); - const transformed = await hook({ request: request("anything") }); - expect(transformed.config.mcpServers).toHaveProperty("shared-browser"); + ])("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 () => { 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 000000000..03f9978ca --- /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/); + }); +}); From b04a80757027e746e8914980c2e43a547a6131d3 Mon Sep 17 00:00:00 2001 From: Keith Kowal <3362598+keithpk@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:02:33 -0800 Subject: [PATCH 3/4] fix(shared-browser): keep the filesystem root canonical and scope field errors to a revision Normalize the root directory to a single slash so a relative or empty directory can no longer equal a workspace at the root, and match a root workspace by its slash prefix. Tie the settings field errors to the revision they were found on, so a newer revision clears them. --- .../client/agent-access-settings.tsx | 9 +++++++-- paseo-shared-browser/shared/agent-access.ts | 7 ++++--- .../tests/agent-filter.test.ts | 18 ++++++++++++++++-- 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/paseo-shared-browser/client/agent-access-settings.tsx b/paseo-shared-browser/client/agent-access-settings.tsx index 0565e89d1..f217c4df7 100644 --- a/paseo-shared-browser/client/agent-access-settings.tsx +++ b/paseo-shared-browser/client/agent-access-settings.tsx @@ -29,7 +29,11 @@ export function AgentAccessSettings({ theme }: PluginSurfaceProps) { const providers = useRef(null); const workspaces = useRef(null); const projects = useRef(null); - const [listErrors, setListErrors] = useState>(NO_ERRORS); + // 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") { @@ -58,6 +62,7 @@ export function AgentAccessSettings({ theme }: PluginSurfaceProps) { } const { values } = settings; + const listErrors = found.revision === settings.revision ? found.errors : NO_ERRORS; const save = (next: typeof values) => void settings.save(next, settings.revision); return ( @@ -114,7 +119,7 @@ export function AgentAccessSettings({ theme }: PluginSurfaceProps) { workspaces: parsed.workspaces.error, projects: parsed.projects.error, }; - setListErrors(errors); + setFound({ revision: settings.revision, errors }); if (errors.providers || errors.workspaces || errors.projects) return; save({ ...values, diff --git a/paseo-shared-browser/shared/agent-access.ts b/paseo-shared-browser/shared/agent-access.ts index 71f5ec3bd..ac606a572 100644 --- a/paseo-shared-browser/shared/agent-access.ts +++ b/paseo-shared-browser/shared/agent-access.ts @@ -62,7 +62,7 @@ export interface WorkspaceRef { /** * A directory in one canonical form: backslashes become slashes, repeated slashes collapse, and `.` - * and `..` segments resolve (a `..` above the root of an absolute path stays at the root). This is + * and `..` segments resolve (a `..` above the root of an absolute path stays at the root, which is `/`). This is * what posix normalize does; it is written out here because shared code does not import Node modules. */ export function normalizeDirectory(path: string): string { @@ -79,7 +79,7 @@ export function normalizeDirectory(path: string): string { } } const joined = kept.join("/"); - return absolute ? `/${joined}`.replace(/\/+$/, "") : joined; + return absolute ? `/${joined}` : joined; } /** @@ -96,7 +96,8 @@ export function workspacesForDirectory( for (const workspace of workspaces) { if (!workspace.workspaceDirectory) continue; const directory = normalizeDirectory(workspace.workspaceDirectory); - if (target !== directory && !target.startsWith(`${directory}/`)) continue; + const prefix = directory.endsWith("/") ? directory : `${directory}/`; + if (target !== directory && !target.startsWith(prefix)) continue; if (directory.length > depth) { depth = directory.length; found = [workspace]; diff --git a/paseo-shared-browser/tests/agent-filter.test.ts b/paseo-shared-browser/tests/agent-filter.test.ts index 3f3c66678..e95bad51e 100644 --- a/paseo-shared-browser/tests/agent-filter.test.ts +++ b/paseo-shared-browser/tests/agent-filter.test.ts @@ -200,8 +200,10 @@ describe("normalizeDirectory", () => { it.each([ ["/repos/one/../outside", "/repos/outside"], ["/repos/one/./src//deep/", "/repos/one/src/deep"], - ["/repos/one/src/../../..", ""], - ["/../..", ""], + ["/repos/one/src/../../..", "/"], + ["/../..", "/"], + ["/", "/"], + [".", ""], ["C:\\repos\\one\\..\\two", "C:/repos/two"], ["../x", "../x"], ["a/../..", ".."], @@ -210,6 +212,18 @@ describe("normalizeDirectory", () => { }); }); +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("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", () => { From 97ec65f3c2cd1894455ddd2780742bc79db07305 Mon Sep 17 00:00:00 2001 From: Keith Kowal <3362598+keithpk@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:23:01 -0800 Subject: [PATCH 4/4] fix(shared-browser): put the deadline on the settings read, tighten path normalization A settings read that is too slow now falls back to the default like an unreadable setting, with a log line, and the workspace lookup has its own deadline where a timeout stays a no match and is logged. Keep a Windows drive root from being climbed above, state that matching is lexical, and carry unsaved list text through a mode change. --- paseo-shared-browser/README.md | 4 +- .../client/agent-access-settings.tsx | 46 ++++++++++------- paseo-shared-browser/index.server.ts | 40 ++++++++++----- paseo-shared-browser/shared/agent-access.ts | 17 ++++--- .../tests/agent-filter.test.ts | 21 ++++++++ paseo-shared-browser/tests/contracts.test.ts | 51 ++++++++++++++----- 6 files changed, 124 insertions(+), 55 deletions(-) diff --git a/paseo-shared-browser/README.md b/paseo-shared-browser/README.md index ff12e9133..d79120e57 100644 --- a/paseo-shared-browser/README.md +++ b/paseo-shared-browser/README.md @@ -171,9 +171,7 @@ workspace or project is matched by directory: the workspace whose directory is t 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. The whole decision (the -settings read and the lookup) has a 2 second deadline, and a timeout counts as no match, so a slow lookup -never holds up agent creation. The check runs before the adapter, its credential or the supervisor are set up, so +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 diff --git a/paseo-shared-browser/client/agent-access-settings.tsx b/paseo-shared-browser/client/agent-access-settings.tsx index f217c4df7..e8a38e45c 100644 --- a/paseo-shared-browser/client/agent-access-settings.tsx +++ b/paseo-shared-browser/client/agent-access-settings.tsx @@ -64,6 +64,27 @@ export function AgentAccessSettings({ theme }: PluginSurfaceProps) { 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. */} @@ -75,7 +96,10 @@ export function AgentAccessSettings({ theme }: PluginSurfaceProps) { value={values.mode} options={MODE_OPTIONS} disabled={settings.saving} - onValueChange={(mode) => save({ ...values, mode })} + onValueChange={(mode) => { + const lists = typedLists(); + if (lists) save({ ...values, ...lists, mode }); + }} /> { - 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; - save({ - ...values, - providers: parsed.providers.entries, - workspaces: parsed.workspaces.entries, - projects: parsed.projects.entries, - }); + const lists = typedLists(); + if (lists) save({ ...values, ...lists }); }} /> diff --git a/paseo-shared-browser/index.server.ts b/paseo-shared-browser/index.server.ts index 4dc685c06..d8cdb6264 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, @@ -112,9 +112,15 @@ 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 agentAccess.read(); + 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( @@ -124,11 +130,26 @@ export default function contribute(server: PluginServerContext) { return access; } catch (error) { console.warn( - `shared-browser: the agent-access setting could not be read (${error instanceof Error ? error.name : "error"}); every new agent gets the browser tool`, + `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); @@ -155,16 +176,9 @@ export default function contribute(server: PluginServerContext) { 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. - // The whole decision (settings read and workspace lookup) shares one deadline, so a stalled lookup - // cannot hold up agent creation; a timeout counts as no match. - const allowed = await withinDeadline( - (async () => - agentGetsBrowser(await readAccess(), request.config, () => - listAllWorkspaces(context.paseo), - ))(), - ACCESS_DECISION_TIMEOUT_MS, - "Shared Browser access decision timed out", - ).catch(() => false); + 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; diff --git a/paseo-shared-browser/shared/agent-access.ts b/paseo-shared-browser/shared/agent-access.ts index ac606a572..09ff32aa7 100644 --- a/paseo-shared-browser/shared/agent-access.ts +++ b/paseo-shared-browser/shared/agent-access.ts @@ -61,14 +61,19 @@ export interface WorkspaceRef { } /** - * A directory in one canonical form: backslashes become slashes, repeated slashes collapse, and `.` - * and `..` segments resolve (a `..` above the root of an absolute path stays at the root, which is `/`). This is - * what posix normalize does; it is written out here because shared code does not import Node modules. + * 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 absolute = path.replace(/\\/g, "/").startsWith("/"); + 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 path.replace(/\\/g, "/").split("/")) { + for (const segment of rest.split("/")) { if (segment === "" || segment === ".") continue; if (segment !== "..") { kept.push(segment); @@ -79,7 +84,7 @@ export function normalizeDirectory(path: string): string { } } const joined = kept.join("/"); - return absolute ? `/${joined}` : joined; + return absolute ? `${drive}/${joined}` : joined; } /** diff --git a/paseo-shared-browser/tests/agent-filter.test.ts b/paseo-shared-browser/tests/agent-filter.test.ts index e95bad51e..0c362e9fb 100644 --- a/paseo-shared-browser/tests/agent-filter.test.ts +++ b/paseo-shared-browser/tests/agent-filter.test.ts @@ -205,6 +205,12 @@ describe("normalizeDirectory", () => { ["/", "/"], [".", ""], ["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) => { @@ -224,6 +230,21 @@ describe("a workspace at the filesystem root", () => { }); }); +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", () => { diff --git a/paseo-shared-browser/tests/contracts.test.ts b/paseo-shared-browser/tests/contracts.test.ts index c6d2ab78d..eaf5ccf0d 100644 --- a/paseo-shared-browser/tests/contracts.test.ts +++ b/paseo-shared-browser/tests/contracts.test.ts @@ -381,25 +381,48 @@ describe("agent access", () => { vi.useRealTimers(); }); - it.each([ - ["the settings read", () => new Promise(() => {}), undefined], - [ - "the workspace lookup", - ready({ workspaces: ["ws_a"] }), - { paseo: { workspaces: { list: () => new Promise(() => {}) } } }, - ], - ])( - "a stalled %s counts as no match and does not block creation", - async (_name, read, context) => { - vi.useFakeTimers(); - const hook = captureAgentCreateHook(read as () => Promise); + 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();