import { useCallback, useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; import { createPortal } from "react-dom"; import { ArrowLeft, ArrowRight, Expand, Globe, History, LoaderCircle, Plus, RefreshCw, Shrink, X } from "lucide-react"; import { commandSharedBrowser, getSharedBrowser, openSharedBrowser, sharedBrowserNavigationURL, type SharedBrowserCommand, type SharedBrowserOpenRequest, type SharedBrowserState } from "../../lib/desktop-shared-browser"; import { useLocale } from "../../lib/locale"; import { hideUnclaimedSharedBrowser, useSharedBrowserSurface } from "./shared-browser-surface"; import { draftSharedBrowserAdoption, rememberDraftSharedBrowser } from "../shared-browser-session"; import "./shared-browser.css"; export interface SharedBrowserTool { id: string; label: string; icon: ReactNode; onOpen: () => void } export function sharedWorkspaceTabKey(event: KeyboardEvent) { if (event.altKey || event.ctrlKey || event.metaKey || !["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) return; const tabs = Array.from(event.currentTarget.closest('[role="tablist"]')?.querySelectorAll('[role="tab"]:not(:disabled)') ?? []); if (!tabs.length) return; event.preventDefault(); const index = tabs.indexOf(event.currentTarget); const next = event.key === "Home" ? 0 : event.key === "End" ? tabs.length - 1 : (index + (event.key === "ArrowLeft" ? -1 : 1) + tabs.length) % tabs.length; tabs[next]?.click(); tabs[next]?.focus(); } export function V2SharedBrowser({ workspaceID, threadID, runID, onFullscreenChange, tabBarTarget, active = true, onActivate, tools = [] }: { workspaceID: string; threadID?: string; runID?: string; onFullscreenChange?: (fullscreen: boolean) => void; tabBarTarget?: HTMLElement | null; active?: boolean; onActivate?: () => void; tools?: SharedBrowserTool[]; }) { const { t } = useLocale(); const panelID = useId(); const [state, setState] = useState(null); const [error, setError] = useState(""); const [pending, setPending] = useState(false); const [retry, setRetry] = useState(0); const [address, setAddress] = useState(""); const addressRef = useRef(null); const current = useRef(null); const generation = useRef(0); const lastFullscreen = useRef(false); const fullscreenExitRequested = useRef(false); const fullscreenChange = useRef(onFullscreenChange); fullscreenChange.current = onFullscreenChange; useEffect(() => { if (!state || state.fullscreen === lastFullscreen.current) return; lastFullscreen.current = state.fullscreen; fullscreenChange.current?.(state.fullscreen); }, [state?.fullscreen]); useEffect(() => () => { const session = current.current; if (!session?.fullscreen) return; if (lastFullscreen.current) { lastFullscreen.current = false; fullscreenChange.current?.(false); } if (!fullscreenExitRequested.current) void commandSharedBrowser(session.session_id, "exit_fullscreen") .catch((error) => console.error("Could not exit shared browser fullscreen", error)); }, []); const reportError = useCallback((error: unknown) => setError(error instanceof Error ? error.message : String(error)), []); const accept = useCallback((next: SharedBrowserState) => { const previous = current.current; if (previous && (previous.session_id !== next.session_id || previous.revision > next.revision)) return; current.current = next; setState(next); if (!next.fullscreen) fullscreenExitRequested.current = false; }, []); useEffect(() => { const session = current.current; if (active || !session?.fullscreen || fullscreenExitRequested.current) return; fullscreenExitRequested.current = true; void commandSharedBrowser(session.session_id, "exit_fullscreen").then(accept).catch(reportError); }, [active, state?.fullscreen, accept, reportError]); useEffect(() => { const activeGeneration = ++generation.current; let disposed = false; let timer: ReturnType | undefined; current.current = null; setState(null); setError(""); setPending(false); const scope: SharedBrowserOpenRequest = { workspace_id: workspaceID, ...(threadID ? { thread_id: threadID } : {}), ...(runID ? { run_id: runID } : {}), adopt_session_id: draftSharedBrowserAdoption(workspaceID, threadID) }; const refresh = async (sessionID: string) => { try { const next = await getSharedBrowser(sessionID); if (!disposed) accept(next); } catch (error) { if (!disposed) reportError(error); } if (!disposed) timer = setTimeout(() => void refresh(sessionID), 450); }; void openSharedBrowser(scope).then((next) => { rememberDraftSharedBrowser(next); if (disposed || generation.current !== activeGeneration) { void hideUnclaimedSharedBrowser(next).catch(reportError); return; } accept(next); timer = setTimeout(() => void refresh(next.session_id), 450); }).catch((error) => { if (!disposed) reportError(error); }); return () => { disposed = true; clearTimeout(timer); generation.current += 1; }; }, [workspaceID, threadID, runID, retry, accept, reportError]); const activeTab = state?.tabs.find((tab) => tab.tab_id === state.active_tab_id); const isStartPage = !activeTab || activeTab.url === "about:blank"; const surfaceRef = useSharedBrowserSurface(state, reportError, active && !isStartPage); const tabDOMID = (tabID: string) => `${panelID}-tab-${encodeURIComponent(tabID)}`; useEffect(() => { if (document.activeElement !== addressRef.current) setAddress(activeTab?.url === "about:blank" ? "" : activeTab?.url ?? ""); }, [activeTab?.url, activeTab?.tab_id]); useEffect(() => { if (active && isStartPage && state?.state === "ready") addressRef.current?.focus(); }, [active, activeTab?.tab_id, isStartPage, state?.state]); const command = async (name: SharedBrowserCommand, options: { tab_id?: string; url?: string } = {}) => { const session = current.current; if (!session || pending) return; const activeGeneration = generation.current; setPending(true); setError(""); try { const next = await commandSharedBrowser(session.session_id, name, options); if (generation.current === activeGeneration) accept(next); } catch (error) { if (generation.current === activeGeneration) reportError(error); } finally { if (generation.current === activeGeneration) setPending(false); } }; const canEdit = state?.state === "ready" && !pending; const navigate = (url: string) => { onActivate?.(); setAddress(url); addressRef.current?.blur(); void command(activeTab ? "navigate" : "new_tab", { ...(activeTab ? { tab_id: activeTab.tab_id } : {}), url }); }; const tabStrip = <> {state?.tabs.map((tab) => { const selected = active && tab.tab_id === state.active_tab_id; const title = tab.url === "about:blank" ? t("新标签页", "New tab") : tab.title || tab.url; return
; })} ; const history = state?.history?.filter((entry, index, entries) => entries.findIndex((item) => item.url === entry.url) === index).slice(0, 8) ?? []; return
{ if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "l") { event.preventDefault(); addressRef.current?.focus(); addressRef.current?.select(); } }}> {tabBarTarget === undefined ?
{tabStrip}
: tabBarTarget ? createPortal(tabStrip, tabBarTarget) : null}
{ event.preventDefault(); const url = sharedBrowserNavigationURL(address); if (!url) { setError(t("请输入 http://、https:// 地址或 about:blank。", "Enter an http:// or https:// address, or about:blank.")); return; } navigate(url); }}> setAddress(event.target.value)} onFocus={(event) => event.target.select()} onKeyDown={(event) => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); setAddress(isStartPage ? "" : activeTab?.url ?? ""); event.currentTarget.blur(); } }} />
{error &&
{error}
}
{!state && !error && {t("正在打开浏览器…", "Opening browser…")}} {state?.state === "failed" && {state.error || t("浏览器启动失败。", "Browser failed to start.")}} {state?.state === "ready" && isStartPage &&
{tools.length > 0 &&

{t("工具", "Tools")}

{tools.map((tool) => )}
} {history.length > 0 &&

{history.map((entry) => )}
}
}
; }