|
| 1 | +import { Check, Globe2, Hand, RotateCw } from "lucide-react-native"; |
| 2 | +import { createContext, useContext, useEffect, useState } from "react"; |
| 3 | +import { ActivityIndicator, AppState, Image, Text, View } from "react-native"; |
| 4 | +import { z } from "zod"; |
| 5 | +import type { BrowserSession } from "../../../packages/domain/src"; |
| 6 | +import { Button, Card, colors, ErrorNotice, s } from "./ui"; |
| 7 | +import { useWorkspace } from "./workspace"; |
| 8 | + |
| 9 | +export const BrowserRunContext = createContext({ running: false, active: false }); |
| 10 | + |
| 11 | +const observationSchema = z.object({ |
| 12 | + sessionId: z.string(), |
| 13 | + title: z.string(), |
| 14 | + url: z.url(), |
| 15 | +}); |
| 16 | + |
| 17 | +function resultValue(result: unknown) { |
| 18 | + if (typeof result !== "string") return result; |
| 19 | + try { |
| 20 | + return JSON.parse(result); |
| 21 | + } catch { |
| 22 | + return undefined; |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +function siteLabel(url: unknown) { |
| 27 | + if (typeof url !== "string") return "Opening a page"; |
| 28 | + try { |
| 29 | + return new URL(url).hostname.replace(/^www\./, ""); |
| 30 | + } catch { |
| 31 | + return "Opening a page"; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +/** A server tool result stays with the request that produced it, including on replay. */ |
| 36 | +export function BrowserToolCard({ |
| 37 | + url, |
| 38 | + result, |
| 39 | + loading, |
| 40 | +}: { |
| 41 | + url: unknown; |
| 42 | + result: unknown; |
| 43 | + loading: boolean; |
| 44 | +}) { |
| 45 | + const { api, workspace, open } = useWorkspace(); |
| 46 | + const { running, active } = useContext(BrowserRunContext); |
| 47 | + const working = loading && active; |
| 48 | + const value = resultValue(result); |
| 49 | + const observation = observationSchema.safeParse(value); |
| 50 | + const toolError = z.object({ error: z.string() }).safeParse(value); |
| 51 | + const sessionId = observation.success ? observation.data.sessionId : undefined; |
| 52 | + const current = workspace.browsers.find((browser) => browser.id === sessionId); |
| 53 | + const [browser, setBrowser] = useState<BrowserSession>(); |
| 54 | + const [error, setError] = useState(""); |
| 55 | + const [previewFailed, setPreviewFailed] = useState(false); |
| 56 | + const [retry, setRetry] = useState(0); |
| 57 | + |
| 58 | + useEffect(() => { |
| 59 | + if (!sessionId) return; |
| 60 | + let active = true; |
| 61 | + async function connect() { |
| 62 | + setError(""); |
| 63 | + setPreviewFailed(false); |
| 64 | + try { |
| 65 | + const session = await api.request<BrowserSession>( |
| 66 | + `/api/browsers/${encodeURIComponent(sessionId || "")}`, |
| 67 | + ); |
| 68 | + if (active) setBrowser(session); |
| 69 | + } catch (e) { |
| 70 | + if (active) setError(e instanceof Error ? e.message : String(e)); |
| 71 | + } |
| 72 | + } |
| 73 | + void connect(); |
| 74 | + const subscription = AppState.addEventListener("change", (state) => { |
| 75 | + if (state === "active") void connect(); |
| 76 | + }); |
| 77 | + return () => { |
| 78 | + active = false; |
| 79 | + subscription.remove(); |
| 80 | + }; |
| 81 | + }, [api, sessionId, current?.updatedAt, retry]); |
| 82 | + |
| 83 | + const visited = observation.success ? observation.data : undefined; |
| 84 | + // A later turn can reuse the same browser. Never label that new page as an old source. |
| 85 | + const preview = |
| 86 | + browser?.status === "active" && browser.url === visited?.url && !previewFailed |
| 87 | + ? browser.previewUrl |
| 88 | + : undefined; |
| 89 | + const failure = toolError.success |
| 90 | + ? toolError.data.error |
| 91 | + : !loading && !visited |
| 92 | + ? "The browser did not return a page. Try your request again." |
| 93 | + : ""; |
| 94 | + return ( |
| 95 | + <Card |
| 96 | + style={{ padding: 13, backgroundColor: "#EEEEF0", gap: 12, width: "100%", maxWidth: 440 }} |
| 97 | + > |
| 98 | + <View style={[s.row, { gap: 10 }]}> |
| 99 | + <View style={[s.iconBox, { width: 36, height: 36, borderRadius: 10 }]}> |
| 100 | + <Globe2 size={21} color={colors.blueDark} /> |
| 101 | + </View> |
| 102 | + <View style={{ flex: 1, gap: 1 }}> |
| 103 | + <Text style={[s.text, { fontWeight: "600" }]}>Browser</Text> |
| 104 | + <Text numberOfLines={1} style={[s.small, { fontSize: 12 }]}> |
| 105 | + {working |
| 106 | + ? "Reading the page…" |
| 107 | + : loading |
| 108 | + ? "Browsing paused" |
| 109 | + : failure |
| 110 | + ? "Couldn’t read the page" |
| 111 | + : siteLabel(visited?.url)} |
| 112 | + </Text> |
| 113 | + </View> |
| 114 | + {working ? ( |
| 115 | + <ActivityIndicator size="small" color={colors.blueDark} /> |
| 116 | + ) : visited ? ( |
| 117 | + <Check size={17} color="#47896C" accessibilityLabel="Page read" /> |
| 118 | + ) : null} |
| 119 | + </View> |
| 120 | + {preview ? ( |
| 121 | + <Image |
| 122 | + accessibilityLabel={`Browser preview: ${visited?.title}`} |
| 123 | + source={{ uri: api.url(preview) }} |
| 124 | + style={{ width: "100%", aspectRatio: 1.7, borderRadius: 12, backgroundColor: "#FFF" }} |
| 125 | + resizeMode="contain" |
| 126 | + onError={() => setPreviewFailed(true)} |
| 127 | + /> |
| 128 | + ) : ( |
| 129 | + <View style={{ backgroundColor: "#FAFAFB", borderRadius: 12, padding: 21, gap: 12 }}> |
| 130 | + <Text numberOfLines={2} style={[s.text, { fontSize: 14 }]}> |
| 131 | + {visited?.title || siteLabel(url)} |
| 132 | + </Text> |
| 133 | + {working ? ( |
| 134 | + <View style={{ gap: 8 }}> |
| 135 | + {(["90%", "74%", "84%"] as const).map((width) => ( |
| 136 | + <View |
| 137 | + key={width} |
| 138 | + style={{ height: 7, width, borderRadius: 4, backgroundColor: "#E3E9ED" }} |
| 139 | + /> |
| 140 | + ))} |
| 141 | + </View> |
| 142 | + ) : visited ? ( |
| 143 | + <Text style={s.small}> |
| 144 | + {browser && browser.url !== visited.url |
| 145 | + ? "Page visited. The browser has moved on." |
| 146 | + : browser?.status === "closed" |
| 147 | + ? "Session saved. Take control to reopen it." |
| 148 | + : browser?.status === "error" |
| 149 | + ? "Session needs attention. Take control to reconnect." |
| 150 | + : previewFailed |
| 151 | + ? "Preview unavailable. You can still take control." |
| 152 | + : "Connecting to the saved session…"} |
| 153 | + </Text> |
| 154 | + ) : null} |
| 155 | + </View> |
| 156 | + )} |
| 157 | + <ErrorNotice error={failure || error} /> |
| 158 | + {!loading && visited && ( |
| 159 | + <Button |
| 160 | + icon={Hand} |
| 161 | + disabled={!browser || running} |
| 162 | + onPress={() => browser && open({ type: "browser", browser })} |
| 163 | + style={{ backgroundColor: "#F9F9FA", minHeight: 38, paddingVertical: 8 }} |
| 164 | + > |
| 165 | + Take control |
| 166 | + </Button> |
| 167 | + )} |
| 168 | + {!!error && ( |
| 169 | + <Button small icon={RotateCw} onPress={() => setRetry((attempt) => attempt + 1)}> |
| 170 | + Reconnect preview |
| 171 | + </Button> |
| 172 | + )} |
| 173 | + </Card> |
| 174 | + ); |
| 175 | +} |
0 commit comments