import { useMemo, useRef, useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { CircleStop, ExternalLink, LoaderCircle, MonitorCog } from "lucide-react"; import type { APIClient } from "../../api/client"; import type { FullCDPSessionView, RunBrowserCDPPermissionControlView, RunBrowserCDPPermissionView, RunDetailView, ThreadExecutionPermissionView, } from "../../api/types"; import { V2ConfirmDialog } from "./dialog"; import { useLocale, type LocaleText } from "../../lib/locale"; type PermissionMode = ThreadExecutionPermissionView["mode"]; export const browserCDPQueryKey = (runID: string) => ["v2", "run", runID, "browser-cdp-permission"] as const; export const fullCDPSessionQueryKey = (runID: string) => ["v2", "run", runID, "full-cdp-session"] as const; function allowsFullCDP(mode: PermissionMode | null): boolean { return mode === "full" || mode === "full_access" || mode === "debug"; } function statusCopy({ runID, mode, permission, loading, failed, controlEnabled, fullCDPEnabled, sessionControlEnabled, executionRuntimeAvailable }: { runID: string; mode: PermissionMode | null; permission?: RunBrowserCDPPermissionView; loading: boolean; failed: boolean; controlEnabled: boolean; fullCDPEnabled: boolean; sessionControlEnabled: boolean; executionRuntimeAvailable: boolean; }, t: LocaleText): string { if (!runID) return mode === null ? t("先打开一个任务。", "Open a task first.") : t("当前任务还没有可配置的执行。", "This task has no run to configure yet."); if (!allowsFullCDP(mode)) { return t("高风险 CDP 需要在当前任务确认并激活完全访问;受限导航、DOM 与截图不受影响。", "High-risk CDP requires confirmed, active Full access for this task. Restricted navigation, DOM access and screenshots remain available."); } if (!controlEnabled || !fullCDPEnabled) return t("当前运行时未提供完整 CDP 控制。", "This runtime does not provide full CDP control."); if (loading) return t("正在读取当前执行的浏览器权限…", "Loading browser permissions for this run…"); if (failed || !permission) return t("无法读取当前执行的浏览器权限。", "Could not load browser permissions for this run."); if (permission.mode === "full_debug") { return permission.runtime_gate_available ? sessionControlEnabled ? t("浏览器控制已开启,可为当前任务打开、查看和关闭独立浏览器。", "Browser control is enabled. Open, inspect and close a separate browser for this task.") : t("浏览器控制权限已开启,当前服务尚未提供独立浏览器。请连接支持托管浏览器的服务后使用预览。", "Browser control is permitted, but this service has no managed browser. Connect to a service with managed browser support to use the preview.") : t("已选择,但当前运行时尚未授权。", "Selected, but not authorized by this runtime yet."); } if (!executionRuntimeAvailable) { return t("先重新确认并激活当前任务的完全访问权限。", "Reconfirm and activate Full access for this task first."); } return t("当前关闭;内置隔离浏览器仍可导航、读取 DOM 和截图,重新开启需确认高风险控制。", "Currently off. The isolated browser can still navigate, read the DOM and take screenshots. Re-enabling requires confirmation of high-risk controls."); } export function V2BrowserCDPControl({ client, runID, permissionMode, executionRuntimeAvailable }: { client: APIClient; runID: string; permissionMode: PermissionMode | null; executionRuntimeAvailable: boolean; }) { const { t, locale } = useLocale(); const queryClient = useQueryClient(); const [confirmOpen, setConfirmOpen] = useState(false); const [sessionConfirmOpen, setSessionConfirmOpen] = useState(false); const [target, setTarget] = useState("http://127.0.0.1:3000"); const [product, setProduct] = useState<"chrome" | "edge">("edge"); const triggerRef = useRef(null); const sessionTriggerRef = useRef(null); const query = useQuery({ queryKey: browserCDPQueryKey(runID), queryFn: ({ signal }) => client.get( `/runs/${encodeURIComponent(runID)}`, {}, signal), enabled: Boolean(runID), staleTime: 5_000, }); const mutation = useMutation({ mutationFn: (mode: RunBrowserCDPPermissionView["mode"]) => client.postControl( `/runs/${encodeURIComponent(runID)}/browser-cdp-permission`, { mode, reason: "v2 current task Full CDP control", ...(mode === "full_debug" ? { confirm_full_cdp_debug: true } : {}), }, `v2-browser-cdp-${globalThis.crypto.randomUUID()}`), onSuccess: (result) => { queryClient.setQueryData(browserCDPQueryKey(runID), (current) => current ? { ...current, browser_cdp_permission: result.browser_cdp_permission } : current); if (!queryClient.getQueryData(browserCDPQueryKey(runID))) { void queryClient.invalidateQueries({ queryKey: browserCDPQueryKey(runID) }); } setConfirmOpen(false); }, }); const sessionQuery = useQuery({ queryKey: fullCDPSessionQueryKey(runID), queryFn: ({ signal }) => client.getFullCDPSession(runID, signal), enabled: Boolean(runID) && client.hasFullCDPSessionControl, refetchInterval: 1_500, }); const session = sessionQuery.data?.session; const sessionMutation = useMutation({ mutationFn: () => client.openFullCDPSession(runID, { version: "full_cdp_session.v1", target: target.trim(), browser: { product, channel: "stable" }, expected_execution_permission_revision: query.data?.execution_permission.revision ?? 0, expected_browser_cdp_permission_revision: query.data?.browser_cdp_permission.revision ?? 0, confirm_full_cdp: true, reason: "v2 operator-confirmed task browser session", }, `v2-full-cdp-open-${globalThis.crypto.randomUUID()}`), onSuccess: (result) => { queryClient.setQueryData(fullCDPSessionQueryKey(runID), result); setSessionConfirmOpen(false); }, }); const closeMutation = useMutation({ mutationFn: (current: FullCDPSessionView) => client.closeFullCDPSession(runID, { version: "full_cdp_session_close.v1", expected_session_id: current.session_id ?? "", reason: "operator_closed", }, `v2-full-cdp-close-${globalThis.crypto.randomUUID()}`), onSuccess: (result) => queryClient.setQueryData(fullCDPSessionQueryKey(runID), result), }); const eligible = allowsFullCDP(permissionMode); const browserPermission = query.data?.browser_cdp_permission; // A Thread preference may already be confirmed for its next Run. Starting // CDP still needs the exact current Run's own live Full activation. const currentExecutionRuntimeAvailable = executionRuntimeAvailable && query.data?.execution_permission.full_activation === "active" && query.data.execution_permission.runtime_gate_available; const checked = eligible && browserPermission?.mode === "full_debug"; const canDisable = checked && Boolean(runID) && client.hasBrowserCDPPermissionControl; const canEnable = !checked && Boolean(runID) && eligible && currentExecutionRuntimeAvailable && client.hasBrowserCDPPermissionControl && client.hasFullCDPDebug; const disabled = mutation.isPending || query.isLoading || query.isError || !(canDisable || canEnable); const activeSession = session?.state === "starting" || session?.state === "ready" || session?.state === "closing"; const normalizedTarget = target.trim(); const targetValid = useMemo(() => { try { const parsed = new URL(normalizedTarget); return (parsed.protocol === "http:" || parsed.protocol === "https:") && (parsed.hostname === "127.0.0.1" || parsed.hostname === "::1" || parsed.hostname === "[::1]"); } catch { return false; } }, [normalizedTarget]); const canOpenSession = checked && currentExecutionRuntimeAvailable && browserPermission?.runtime_gate_available && session?.runtime_available !== false && !activeSession && targetValid && Boolean(query.data?.execution_permission.revision) && Boolean(browserPermission?.revision) && client.hasFullCDPSessionControl; const detail = statusCopy({ runID, mode: permissionMode, permission: browserPermission, loading: query.isLoading, failed: query.isError, controlEnabled: client.hasBrowserCDPPermissionControl, fullCDPEnabled: client.hasFullCDPDebug, sessionControlEnabled: client.hasFullCDPSessionControl, executionRuntimeAvailable: currentExecutionRuntimeAvailable, }, t); const toggle = () => { mutation.reset(); if (checked) { mutation.mutate("restricted"); return; } if (canEnable) setConfirmOpen(true); }; return
{t("内置浏览器 · 完整 CDP", "Built-in browser · Full CDP")}

{detail}