Files
PaperClipAI/ui/src/components/task-side-panel/TaskBrowserPanel.tsx
T
DottaandPaperclip d72389bee2 feat: add Browser Use Cloud connector and live task browsers (#14627)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Apps gateway gives agents governed access to external tools.
> - Browser Use Cloud can run browser work, but a tool result alone does
not let a person watch or take over.
> - A task needs a durable browser session, a visible viewer, and
recorded costs.
> - This pull request adds a Browser Use Cloud v4 connection and
interactive browser tabs on tasks.
> - People can follow the work, interact with the page, and retain the
browser after the agent finishes.

## Linked Issues or Issue Description

**Problem or motivation**

Agents need governed access to Browser Use Cloud. People need to see and
interact with the same browser from the task. A browser must remain
available after a run finishes and appear at the correct point in the
task feed.

**Proposed solution**

Add a native REST connection for the v4 API. Bind each session to its
company, task, agent, and credential grant. Open its interactive viewer
in the task side panel. Record provider costs as financial events. Use
`browser-use-cloud` as the app and connector key. Keep its skill with
the connector and deliver it only with authorized connection tools.

**Alternatives considered**

A v3 MCP connection would expose tools without the v4 lifecycle
integration. An external viewer link would leave the task. A fixed
viewer size would prevent pages from responding to changes in the task
pane.

**Roadmap alignment**

This extends the governed Apps gateway and Connected Apps roadmap. It
uses the existing task, grant, secret, approval, and financial records.
The work was requested by the maintainer. A search found no duplicate
Browser Use connector PR or issue.

## What Changed

- Add the Browser Use Cloud app, brand asset, API-key connection, and
profile settings under the `browser-use-cloud` key.
- Bundle the `browser-use-cloud` skill with the connector. Keep it out
of global `skills/` discovery. Deliver it only with authorized task/run
connection tools. Remove retired connector skill keys from runtime
overlays and preserve unrelated browser skills.
- Expose seven v4 tools through the governed gateway and deliver them to
native and CLI agents.
- Persist sessions, browsers, runs, event and recovery cursors, shutdown
leases, and cumulative cost accounting. Recover uncertain paid starts
without replaying them.
- Enforce task ownership, credential grants, approvals, revoked access,
and budget limits.
- Add interactive task browser tabs and compact chronological feed
entries. Retain the viewer across tab switches and keep visible idle
browsers open.
- Add debounced automatic viewport fitting, standard size presets, and a
viewer ownership lease.
- Add lifecycle, authorization, accounting, viewport, UI, and Storybook
coverage.
- Add an idempotent database migration after the current master
migration. Preserve deployed migration hashes. Migrate pre-release Cloud
connection and financial keys without replacing grants, credentials, or
browser history.
- Document provider behavior, live acceptance results, and the lack of
documented passkey forwarding.

## Verification

- Full workspace typecheck and production build pass on the updated
branch.
- Token gates, brand asset validation, module boundaries, and migration
ordering pass.
- Cloud tests verify global skill exclusion, authorized task/run
delivery, unassigned agents, disabled connections, revocation, adapter
isolation, and secret exclusion. The existing AgentMail connector
assignment test also passes.
- Migration replay runs twice against existing browser work and
financial records. It preserves the records and avoids duplicate costs.
- The focused provider, app catalog, OpenAPI, connection gateway, and
migration regression suites pass. Recovery coverage includes lost
replies, process crashes, provider rejection, and browser arrival
acknowledgement.
- All 54 checks pass on `2974b5f03641ad0cea3c941d8c02579316fa8c92`,
including the full test matrix, browser E2E shards, build, typecheck,
security, and release canary. Two optional Storybook jobs are skipped.
- Greptile is 5/5 on the same commit, with zero unresolved review
threads. The corrected review uses the actual master-to-head diff.
- The local `pnpm test:run` started and was stopped after the full CI
matrix passed. It did not complete locally; the full-suite result above
comes from CI.
- Earlier live acceptance used an isolated company with a capped
provider credential. The agent opened paperclip.ing, the embedded viewer
accepted navigation, and the same browser stayed available after
completion and tab switches.
- The local Storybook build passes. Stories cover the panel, footer,
feed entries, settings, lifecycle failures, and viewport modes with an
offline viewer fixture.

## Risks

- Browser Use charges for hosted work. Provider caps and local budget
checks reduce exposure; reported costs can arrive after work completes.
- Viewer and CDP URLs grant access to the browser. The server validates
and restricts them. They are excluded from agent results and durable
event data.
- Runtime resizing of v4 agent browsers uses a provider option confirmed
by live testing but absent from its published agent schema. Resizing
during a click may invalidate coordinates. Fixed presets remain
available.
- Viewport ownership is process-local and resets on restart. The
lifecycle and accounting records remain in the database.
- The original intermittent embedded-viewer stall has not been fully
diagnosed. A bounded reconnect and active-session recovery cover the
observed failure paths.
- Live tests did not cover every revocation, approval, rate-limit, or
restart case. Deterministic integration tests cover those paths. Passkey
forwarding is not claimed.
- Unknown create outcomes keep the credential available for cleanup.
Run-list absence cannot prove a paid POST was rejected, so recovery
stays pending until it can identify provider work.

## Model Used

OpenAI Codex, GPT-6. Used reasoning, repository search, code execution,
browser interaction, and test tools. The exact serving model ID and
context-window size were 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 `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [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>
2026-09-30 07:13:16 -05:00

302 lines
10 KiB
TypeScript

import { useEffect, useRef, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { type BrowserUseControl, type TaskBrowser } from "@paperclipai/shared";
import { browserUseApi } from "@/api/browser-use";
import { Button } from "@/components/ui/button";
import { Globe, LoaderCircle } from "lucide-react";
import { useBrowserViewport } from "@/hooks/useBrowserViewport";
import { TaskBrowserFooter } from "./TaskBrowserFooter";
export function TaskBrowserPanel({
issueId,
browser,
accessError = false,
active = true,
onOpenActiveBrowser,
}: {
issueId: string;
browser?: TaskBrowser;
accessError?: boolean;
active?: boolean;
onOpenActiveBrowser?: () => void;
}) {
const cache = useQueryClient();
const [url, setUrl] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [refresh, setRefresh] = useState(0);
const automaticReconnects = useRef(0);
const reconnect = () => {
automaticReconnects.current = 0;
setRefresh((n) => n + 1);
};
const [viewerLoad, setViewerLoad] = useState<
"loading" | "loaded" | "timed-out"
>("loading");
const [now, setNow] = useState(Date.now());
const frameRef = useRef<HTMLIFrameElement>(null);
const viewable =
browser && ["running", "idle"].includes(browser.status) && !accessError;
const viewport = useBrowserViewport({
issueId,
browserId: browser?.id,
enabled: Boolean(viewable && url && viewerLoad === "loaded"),
active,
frameRef,
});
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 1000);
return () => clearInterval(timer);
}, []);
useEffect(() => {
setUrl(null);
setError(null);
if (!viewable || !browser) return;
let disposed = false;
const controller = new AbortController();
// Keep the bearer viewer URL in component memory only. Revalidate even
// when hidden so a revoked credential promptly unmounts its iframe.
const load = () => {
const version = viewport.version.current;
return browserUseApi
.viewer(issueId, browser.id, controller.signal, viewport.viewerId)
.then((result) => {
if (!disposed) {
setUrl(result.url);
setError(null);
viewport.receive(
result.viewportState ?? { preset: result.viewport ?? "fit" },
version,
);
}
})
.catch(() => {
if (!disposed) {
setUrl(null);
setError(
"The live view disconnected. Use Reconnect view in Browser options to try again.",
);
}
});
};
void load();
const timer = setInterval(() => {
void load();
}, 15000);
return () => {
disposed = true;
controller.abort();
clearInterval(timer);
};
}, [issueId, browser?.id, viewable, refresh]);
useEffect(() => {
setViewerLoad("loading");
}, [url, refresh]);
useEffect(() => {
automaticReconnects.current = 0;
}, [browser?.id]);
useEffect(() => {
// A hidden iframe may not navigate until shown. Give the selected viewer
// a full load window, then reconnect once before asking the user to act.
if (!active || !url || viewerLoad !== "loading") return;
const timer = setTimeout(() => {
if (automaticReconnects.current === 0) {
automaticReconnects.current += 1;
setRefresh((n) => n + 1);
} else {
setViewerLoad("timed-out");
}
}, 15_000);
return () => clearTimeout(timer);
}, [active, url, refresh, viewerLoad]);
const [presenceError, setPresenceError] = useState(false);
useEffect(() => {
if (!active || !viewable || !url || !browser || browser.status !== "idle")
return;
let disposed = false;
let pending = false;
const renew = async () => {
const frame = frameRef.current;
if (
pending ||
document.visibilityState === "hidden" ||
!frame ||
!frame.getClientRects().length ||
(frame.checkVisibility &&
!frame.checkVisibility({
checkOpacity: true,
checkVisibilityCSS: true,
}))
)
return;
pending = true;
try {
const result = await browserUseApi.presence(issueId, browser.id);
if (!disposed && result.accepted) setPresenceError(false);
} catch {
if (!disposed) setPresenceError(true);
} finally {
pending = false;
}
};
void renew();
const timer = setInterval(() => void renew(), 30_000);
document.addEventListener("visibilitychange", renew);
return () => {
disposed = true;
clearInterval(timer);
document.removeEventListener("visibilitychange", renew);
};
}, [active, viewable, url, browser?.id, browser?.status, issueId]);
const action = useMutation({
mutationFn: (value: BrowserUseControl) =>
browserUseApi.control(issueId, browser!.id, value),
onSuccess: () => {
void cache.invalidateQueries({ queryKey: ["task-browsers", issueId] });
},
onError: () => setError("The browser action failed. Try again."),
});
const message = accessError
? "You no longer have access to this browser."
: (browser?.error ?? error);
const heading = accessError
? "Browser access unavailable"
: browser?.status === "starting"
? "Starting browser…"
: browser?.status === "stopping"
? "Closing browser…"
: browser?.status === "closed"
? "Browser closed"
: browser?.status === "failed"
? "Browser could not start"
: error
? "Live view disconnected"
: viewable
? "Connecting to browser…"
: "No browser open";
const waiting =
!message &&
(browser?.status === "starting" ||
browser?.status === "stopping" ||
viewable);
return (
<div className="flex h-full min-h-0 flex-col">
{viewable && url ? (
<div className="relative min-h-0 flex-1">
<iframe
ref={frameRef}
key={refresh}
title="Live Browser Use browser"
src={url}
onLoad={() => setViewerLoad("loaded")}
referrerPolicy="no-referrer"
allow="autoplay; clipboard-write"
className="absolute inset-0 h-full w-full border-0"
/>
{viewerLoad !== "loaded" && (
<div
role={viewerLoad === "timed-out" ? "alert" : "status"}
className="absolute inset-0 flex flex-col items-center justify-center gap-3 bg-background p-6 text-center"
>
{viewerLoad === "loading" ? (
<>
<LoaderCircle
className="size-5 animate-spin text-muted-foreground motion-reduce:animate-none"
aria-hidden="true"
/>
<p className="text-sm">Connecting to browser…</p>
</>
) : (
<>
<p className="text-sm font-medium">
The live view did not load
</p>
<p className="max-w-sm text-sm text-muted-foreground">
Reconnect the view or open this task in another browser. The
remote browser is still running.
</p>
<Button
variant="outline"
size="sm"
onClick={reconnect}
>
Reconnect view
</Button>
</>
)}
</div>
)}
</div>
) : (
<div
role={message ? "alert" : "status"}
className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 overflow-auto p-6 text-center"
>
{waiting ? (
<LoaderCircle
className="size-5 animate-spin text-muted-foreground motion-reduce:animate-none"
aria-hidden="true"
/>
) : (
<Globe
className="size-5 text-muted-foreground"
aria-hidden="true"
/>
)}
<div className="max-w-sm space-y-2">
<p className="text-sm font-medium">{heading}</p>
<p className="text-sm text-muted-foreground">
{message ??
(browser?.status === "closed"
? onOpenActiveBrowser
? "Another browser is still open on this task."
: "Send a task message to ask the agent to open another browser."
: browser?.status === "starting"
? "The live view will appear here when it is ready."
: browser?.status === "stopping"
? "Waiting for Browser Use to confirm shutdown."
: !viewable
? "Ask the agent to browse a website in a task message."
: null)}
</p>
</div>
{browser?.status === "closed" && !accessError && onOpenActiveBrowser && (
<Button variant="outline" size="sm" onClick={onOpenActiveBrowser}>
Open active browser
</Button>
)}
</div>
)}
{viewable && url && message && (
<p role="alert" className="px-3 py-2 text-xs text-destructive">
{message}
</p>
)}
{viewable && presenceError && (
<p role="alert" className="px-3 py-2 text-xs text-destructive">
Could not keep this browser open. Check your connection before the
timer runs out.
</p>
)}
{viewable && viewport.error && (
<p role="alert" className="px-3 py-2 text-xs text-destructive">
{viewport.error}
</p>
)}
{browser && !accessError && (
<TaskBrowserFooter
browser={browser}
now={now}
disabled={action.isPending}
onControl={(value) => action.mutate(value)}
onReconnect={reconnect}
viewport={viewport.state.preset}
controlledElsewhere={viewport.state.controlledElsewhere}
resizing={viewport.resizing}
resizeAvailable={viewerLoad === "loaded"}
onResize={viewport.select}
/>
)}
</div>
);
}