mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-23 04:54:00 +01:00
Fix browser polling for unsaved agent chats (#15298)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agent Chat uses the shared task surface and browser panel. > - An unsaved chat has a temporary ID instead of a stored task UUID. > - The browser poll sent that ID to a PostgreSQL UUID query and returned a server error. > - This pull request waits for a saved task and validates task IDs before the query. > - Saved chats keep their browser tools and access checks. ## Linked Issues or Issue Description Refs #14331. That report describes the same draft-ID problem in email requests. This change covers the browser routes; it does not change email behavior. Opening an unsaved Agent Chat sends `chat:<agent-id>` to `/issues/:issueId/browsers` every three seconds. PostgreSQL rejects this as a task UUID. The draft is only a UI view model. The first send or upload creates its stored task. ## What Changed - Disable browser polling for unsaved chat IDs. Resume polling when the chat has a task UUID. - Return the existing task-not-found response for malformed task IDs before database access. Keep board authentication first and company and credential checks unchanged. - Test all six task browser routes, draft-to-saved polling, normal tasks, saved chats, and denied access. Keep canonical UUID v4, v7, and nil values queryable. - Document the draft and saved-chat browser contract. ## Verification - `pnpm install --frozen-lockfile` passed with pnpm 9.15.4 and Node 24.21.0. - `pnpm exec vitest run server/src/__tests__/browser-use-route-scope.test.ts server/src/__tests__/browser-use-connection.test.ts` passed all 35 tests. - `pnpm exec vitest run ui/src/hooks/useTaskBrowsers.test.ts` passed all 5 tests. - Independent review passed 14 hook and route tests plus both real task and saved-chat authorization cases. - `pnpm check:token-gates` and `git diff --check` passed. - Full workspace `pnpm -r typecheck` and `pnpm build` passed. - Full Linux CI passed on `dafff44a32`: 53 successful checks and two intentional Storybook skips. This includes all general and serialized test groups, UI and browser tests, typecheck, build, and the canary dry run. No CI retries were needed. - The full local `TMPDIR=/private/tmp pnpm test:run` started but did not complete. It was stopped after full Linux CI passed. Before the stop, three company-skills cache cases failed on macOS. A focused rerun reproduced all three as `EACCES` while renaming immutable cache staging directories. The test, company-skills service, and runtime cache files are byte-identical to the baseline previously reproduced on `e99854249c` for #15291. Other local groups were not reached; the full Linux CI run provides aggregate coverage. - Greptile scored the exact head `dafff44a32` 5/5 with no findings or unresolved review threads. ## Risks - Malformed task IDs now return 404 instead of reaching PostgreSQL and returning 500. The route does not map draft IDs to agents or tasks. - No schema, browser provider, task creation, or authorization policy changes. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository editing, code execution, and independent agent review. The exact deployment model ID and context window are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub references) - [x] My branch name describes the change and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass (focused suites; full local run limitations are reported above) - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
81cd03b3b5
commit
858094ba81
6 files changed
+150
-6
No files matched your search
@@ -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:<agent-id>` 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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<Parameters<typeof browserUseRoutes>[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<Parameters<typeof browserUseRoutes>[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();
|
||||
});
|
||||
});
|
||||
@@ -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)
|
||||
|
||||
@@ -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<R, P = undefined>(callback: (props: P) => R, options?: { initialProps: P }) {
|
||||
function renderHook<R, P = undefined>(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));
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user