diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index fb3f6d94476..47e399e98c7 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -1208,6 +1208,11 @@ operator-controlled [runner API tools](runner-api-tools.md) rollout; enabling Agent Chat does not enable that API surface. Failed-turn retries restore the selected run's user comments so the agent can answer the original request. +An unsaved Agent Chat uses an ephemeral `chat:` view-model ID. Task +browser polling starts after the first send or upload creates a persisted task +UUID. Saved chats retain the task browser's company and credential access checks. +Task browser routes reject malformed task IDs with `404` before querying PostgreSQL. + A native continuation that requires reconciliation shows **Recovery needed** with **Inspect run**; inspect the original outcome before resolving its recovery hold. A generic retry cannot resolve this incident. The runner's diff --git a/server/src/__tests__/browser-use-connection.test.ts b/server/src/__tests__/browser-use-connection.test.ts index 49a11010fe3..b206fabe93c 100644 --- a/server/src/__tests__/browser-use-connection.test.ts +++ b/server/src/__tests__/browser-use-connection.test.ts @@ -983,8 +983,15 @@ const actor = { actorType: "user" as const, actorId: "browser-reviewer" }; )[0], ).toMatchObject({ eventCursor: 9, eventsDrained: 1, accountedCents: 15 }); }); - it("protects interactive viewer routes from agent, other-company and read-only access", async () => { + it.each(["task", "saved chat"])("protects %s browser routes from agent, other-company and read-only access", async (kind) => { const f = await fixture(); + if (kind === "saved chat") { + await db.update(issues).set({ + conversationAgentId: f.agent.id, + conversationUserId: actor.actorId, + conversationState: "active", + }).where(eq(issues.id, f.issue.id)); + } await f.service.execute( f.binding, f.grant, @@ -1021,11 +1028,19 @@ const actor = { actorType: "user" as const, actorId: "browser-reviewer" }; }); app.use(browserUseRoutes(db, f.service)); app.use(errorHandler); + const listPath = `/issues/${f.issue.id}/browsers`; + const listed = await http(app).get(listPath); + expect(listed.status).toBe(200); + expect(listed.body).toMatchObject([{ id: browser.id, issueId: f.issue.id }]); + const missing = await http(app).get(`/issues/${randomUUID()}/browsers`); + expect(missing.status).toBe(404); + expect(missing.body).toEqual({ error: "Task not found" }); const path = `/issues/${f.issue.id}/browsers/${browser.id}/viewer`; const ok = await http(app).get(path); expect(ok.status).toBe(200); expect(ok.headers["cache-control"]).toBe("no-store"); expect(ok.headers["referrer-policy"]).toBe("no-referrer"); + const controlPath = path.replace("/viewer", "/control"); const presencePath = path.replace("/viewer", "/presence"); expect((await http(app).post(presencePath)).status).toBe(200); const resizePath = path.replace("/viewer", "/viewport"); @@ -1065,7 +1080,10 @@ const actor = { actorType: "user" as const, actorId: "browser-reviewer" }; (await http(app).post(resizePath).send({ preset: "custom", width: 1 })) .status, ).toBe(400); + expect((await http(app).post(controlPath).send({ action: "cancel" })).status).toBe(200); mode = "agent"; + expect((await http(app).get(listPath)).status).toBe(403); + expect((await http(app).post(controlPath).send({ action: "keep_open" })).status).toBe(403); expect((await http(app).post(presencePath)).status).toBe(403); expect( (await http(app).post(`${resizePath}/release`).send({ viewerId })) @@ -1076,6 +1094,10 @@ const actor = { actorType: "user" as const, actorId: "browser-reviewer" }; ).toBe(403); expect((await http(app).get(path)).status).toBe(403); mode = "other-company"; + const inaccessible = await http(app).get(listPath); + expect(inaccessible.status).toBe(missing.status); + expect(inaccessible.body).toEqual(missing.body); + expect((await http(app).post(controlPath).send({ action: "keep_open" })).status).toBe(404); expect((await http(app).post(presencePath)).status).toBe(404); expect( (await http(app).post(`${resizePath}/release`).send({ viewerId })) @@ -1091,6 +1113,8 @@ const actor = { actorType: "user" as const, actorId: "browser-reviewer" }; .set({ membershipRole: "viewer" }) .where(eq(companyMemberships.companyId, f.company.id)); expect((await http(app).get(path)).status).toBe(403); + expect((await http(app).get(listPath)).body).toEqual([]); + expect((await http(app).post(controlPath).send({ action: "keep_open" })).status).toBe(403); expect((await http(app).post(presencePath)).status).toBe(403); expect( (await http(app).post(resizePath).send({ preset: "phone" })).status, diff --git a/server/src/__tests__/browser-use-route-scope.test.ts b/server/src/__tests__/browser-use-route-scope.test.ts new file mode 100644 index 00000000000..113b4081849 --- /dev/null +++ b/server/src/__tests__/browser-use-route-scope.test.ts @@ -0,0 +1,73 @@ +import { randomUUID } from "node:crypto"; +import express from "express"; +import http from "supertest"; +import { describe, expect, it, vi } from "vitest"; +import type { Db } from "@paperclipai/db"; +import { errorHandler } from "../middleware/error-handler.js"; +import { browserUseRoutes } from "../routes/browser-use.js"; + +const routes = [ + { method: "get", suffix: "" }, + { method: "get", suffix: "/viewer" }, + { method: "post", suffix: "/presence" }, + { method: "post", suffix: "/viewport" }, + { method: "post", suffix: "/viewport/release" }, + { method: "post", suffix: "/control" }, +] as const; + +describe("browser task route scope", () => { + it.each([ + "12345678-1234-4234-8234-123456789abc", + "12345678-1234-7234-8234-123456789ABC", + "00000000-0000-0000-0000-000000000000", + ])("keeps canonical PostgreSQL task UUIDs queryable: %s", async (id) => { + const companyId = randomUUID(); + const limit = vi.fn().mockResolvedValue([{ companyId }]); + const db = { select: () => ({ from: () => ({ where: () => ({ limit }) }) }) } as unknown as Db; + const list = vi.fn().mockResolvedValue([]); + const service = { list } as unknown as NonNullable[1]>; + const app = express(); + app.use((req, _res, next) => { + req.actor = { type: "board", userId: "browser-reviewer", source: "session", companyIds: [companyId] }; + next(); + }); + app.use(browserUseRoutes(db, service)); + app.use(errorHandler); + expect((await http(app).get(`/issues/${id}/browsers`)).status).toBe(200); + expect(limit).toHaveBeenCalledExactlyOnceWith(1); + expect(list).toHaveBeenCalledExactlyOnceWith(companyId, id, "browser-reviewer"); + }); + + it.each(routes)("rejects invalid task IDs before any query: $method $suffix", async ({ method, suffix }) => { + const select = vi.fn(() => { throw new Error("Invalid scope reached the database"); }); + const db = { select } as unknown as Db; + const service = Object.fromEntries( + ["list", "viewer", "presence", "resize", "releaseViewport", "humanSession", "control"] + .map((name) => [name, vi.fn()]), + ) as unknown as NonNullable[1]>; + let actorType: "board" | "agent" | "none" = "board"; + const app = express(); + app.use((req, _res, next) => { + req.actor = actorType === "board" + ? { type: "board", userId: "browser-reviewer", source: "session", companyIds: [] } + : actorType === "agent" + ? { type: "agent", companyId: randomUUID(), agentId: randomUUID(), source: "agent_key" } + : { type: "none" }; + next(); + }); + app.use(browserUseRoutes(db, service)); + app.use(errorHandler); + const id = randomUUID(); + for (const invalidId of [`chat:${id}`, "not-a-uuid", `${id}'`, ` ${id}`, `${id}\n`]) { + const path = `/issues/${encodeURIComponent(invalidId)}/browsers${suffix ? `/${id}${suffix}` : ""}`; + for (const type of ["board", "agent", "none"] as const) { + actorType = type; + const response = await http(app)[method](path); + expect(response.status).toBe(type === "board" ? 404 : 403); + expect(response.body).toEqual({ error: type === "board" ? "Task not found" : "Board access required" }); + } + } + expect(select).not.toHaveBeenCalled(); + for (const handler of Object.values(service)) expect(handler).not.toHaveBeenCalled(); + }); +}); diff --git a/server/src/routes/browser-use.ts b/server/src/routes/browser-use.ts index 343237998ff..0b45801e51e 100644 --- a/server/src/routes/browser-use.ts +++ b/server/src/routes/browser-use.ts @@ -1,5 +1,6 @@ import { Router } from "express"; import { eq } from "drizzle-orm"; +import { z } from "zod"; import { issues, type Db } from "@paperclipai/db"; import { browserUseControlSchema, @@ -15,10 +16,19 @@ import { } from "./authz.js"; import { browserUseService } from "../services/browser-use.js"; +const issueIdSchema = z.string().uuid(); + export function browserUseRoutes(db: Db, service = browserUseService(db)) { const router = Router(); router.use("/issues/:issueId/browsers", async (req, res, next) => { assertBoard(req); + if ( + req.params.issueId !== req.params.issueId.trim() || + !issueIdSchema.safeParse(req.params.issueId).success + ) { + res.status(404).json({ error: "Task not found" }); + return; + } const [issue] = await db .select({ companyId: issues.companyId }) .from(issues) diff --git a/ui/src/hooks/useTaskBrowsers.test.ts b/ui/src/hooks/useTaskBrowsers.test.ts index 603c84db1d2..23b8e0638d2 100644 --- a/ui/src/hooks/useTaskBrowsers.test.ts +++ b/ui/src/hooks/useTaskBrowsers.test.ts @@ -3,18 +3,25 @@ import { act, createElement } from "react"; import { createRoot } from "react-dom/client"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; import type { TaskBrowser } from "@paperclipai/shared"; -import { useBrowserArrivals } from "./useTaskBrowsers"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { browserUseApi } from "@/api/browser-use"; +import { useBrowserArrivals, useTaskBrowsers } from "./useTaskBrowsers"; (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const cleanups = new Set<() => void>(); function cleanup() { for (const unmount of cleanups) unmount(); } -function renderHook(callback: (props: P) => R, options?: { initialProps: P }) { +function renderHook(callback: (props: P) => R, options?: { initialProps: P; client?: QueryClient }) { const host = document.createElement("div"); document.body.append(host); const root = createRoot(host); let props = options?.initialProps as P; const result = {} as { current: R }; function Harness() { result.current = callback(props); return null; } - function rerender(next = props) { props = next; act(() => root.render(createElement(Harness))); } + function rerender(next = props) { + props = next; + act(() => root.render(options?.client + ? createElement(QueryClientProvider, { client: options.client }, createElement(Harness)) + : createElement(Harness))); + } function unmount() { act(() => root.unmount()); host.remove(); cleanups.delete(unmount); } cleanups.add(unmount); rerender(); @@ -26,7 +33,32 @@ const browser = (id: string): TaskBrowser => ({ error: null, createdAt: "2026-09-29T10:00:00Z", }); beforeEach(() => { localStorage.clear(); sessionStorage.clear(); }); -afterEach(() => { cleanup(); vi.restoreAllMocks(); }); +afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.useRealTimers(); }); +it("starts browser polling when a chat draft becomes a saved task and stops on the next draft", async () => { + vi.useFakeTimers(); + const list = vi.spyOn(browserUseApi, "list").mockResolvedValue([]); + const client = new QueryClient(); + const taskId = "12345678-1234-4234-8234-123456789abc"; + const { rerender, unmount } = renderHook(useTaskBrowsers, { + initialProps: undefined as string | undefined, + client, + }); + await act(async () => { await vi.advanceTimersByTimeAsync(6000); }); + expect(list).not.toHaveBeenCalled(); + rerender(`chat:${taskId}`); + await act(async () => { await vi.advanceTimersByTimeAsync(6000); }); + expect(list).not.toHaveBeenCalled(); + rerender(taskId); + await act(async () => { await vi.advanceTimersByTimeAsync(1); }); + expect(list).toHaveBeenCalledExactlyOnceWith(taskId); + await act(async () => { await vi.advanceTimersByTimeAsync(3000); }); + expect(list).toHaveBeenCalledTimes(2); + rerender(`chat:${taskId}`); + await act(async () => { await vi.advanceTimersByTimeAsync(6000); }); + expect(list).toHaveBeenCalledTimes(2); + unmount(); + client.clear(); +}); it("queues simultaneous arrivals and claims only after the panel acknowledges", () => { const browsers = [browser("first"), browser("next")]; const { result, rerender } = renderHook(() => useBrowserArrivals("user", "task", browsers)); diff --git a/ui/src/hooks/useTaskBrowsers.ts b/ui/src/hooks/useTaskBrowsers.ts index 0d59497756d..be8a7d27aca 100644 --- a/ui/src/hooks/useTaskBrowsers.ts +++ b/ui/src/hooks/useTaskBrowsers.ts @@ -6,7 +6,7 @@ export function useTaskBrowsers(issueId?: string) { return useQuery({ queryKey: ["task-browsers", issueId], queryFn: () => browserUseApi.list(issueId!), - enabled: Boolean(issueId), + enabled: Boolean(issueId) && !issueId?.startsWith("chat:"), refetchInterval: 3000, retry: false, });