The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { useAtomValue } from "@effect/atom-react"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 4 | import { useId, useState } from "react"; |
| 5 | import { |
| 6 | resolveOfficialAcpRegistryIconUrl, |
| 7 | officialAcpRegistryIconUrlForAgentId, |
| 8 | } from "@t3tools/contracts"; |
| 9 | |
| 10 | import { cn } from "../../lib/utils"; |
| 11 | import { ACPRegistryIcon } from "../Icons"; |
| 12 | |
| 13 | const ACP_REGISTRY_ICON_CACHE = "t3-acp-registry-icons-v1"; |
| 14 | const MAX_ICON_BYTES = 512 * 1_024; |
| 15 | const inFlightIcons = new Map<string, Promise<Blob>>(); |
| 16 | |
| 17 | export { officialAcpRegistryIconUrlForAgentId, resolveOfficialAcpRegistryIconUrl }; |
| 18 | |
| 19 | async function checkedIconBlob(response: Response): Promise<Blob> { |
| 20 | if (!response.ok || response.redirected) throw new Error("ACP registry icon request failed."); |
| 21 | const contentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim() ?? ""; |
| 22 | if (!contentType.startsWith("image/")) throw new Error("ACP registry icon was not an image."); |
| 23 | const contentLength = Number(response.headers.get("content-length")); |
| 24 | if (Number.isFinite(contentLength) && contentLength > MAX_ICON_BYTES) { |
| 25 | throw new Error("ACP registry icon was too large."); |
| 26 | } |
| 27 | const bytes = await response.arrayBuffer(); |
| 28 | if (bytes.byteLength > MAX_ICON_BYTES) throw new Error("ACP registry icon was too large."); |
| 29 | return new Blob([bytes], { type: contentType }); |
| 30 | } |
| 31 | |
| 32 | export function loadCachedAcpRegistryIcon(iconUrl: string): Promise<Blob> { |
| 33 | if (resolveOfficialAcpRegistryIconUrl(iconUrl) !== iconUrl) { |
| 34 | return Promise.reject(new Error("ACP registry icon URL was not allowed.")); |
| 35 | } |
| 36 | const pending = inFlightIcons.get(iconUrl); |
| 37 | if (pending) return pending; |
| 38 | const load = (async () => { |
| 39 | let cache: Cache | null = null; |
| 40 | if (typeof caches !== "undefined") { |
| 41 | try { |
| 42 | cache = await caches.open(ACP_REGISTRY_ICON_CACHE); |
| 43 | } catch { |
| 44 | // Privacy modes may expose CacheStorage but reject access; icons still load from the allowlisted CDN. |
| 45 | } |
| 46 | } |
| 47 | if (cache !== null) { |
| 48 | try { |
| 49 | const cached = await cache.match(iconUrl); |
| 50 | if (cached) return await checkedIconBlob(cached); |
| 51 | } catch {} |
| 52 | } |
| 53 | |
| 54 | const response = await fetch(iconUrl, { |
| 55 | credentials: "omit", |
| 56 | redirect: "error", |
| 57 | referrerPolicy: "no-referrer", |
| 58 | }); |
| 59 | const clone = response.clone(); |
| 60 | const blob = await checkedIconBlob(response); |
| 61 | await cache?.put(iconUrl, clone).catch(() => undefined); |
| 62 | return blob; |
| 63 | })(); |
| 64 | inFlightIcons.set(iconUrl, load); |
| 65 | void load.then( |
| 66 | () => inFlightIcons.delete(iconUrl), |
| 67 | () => inFlightIcons.delete(iconUrl), |
| 68 | ); |
| 69 | return load; |
| 70 | } |
| 71 | |
| 72 | // Falls back to the raw allowlisted CDN URL when the validating fetch fails: the |
| 73 | // CDN serves no CORS headers, so the fetch is often blocked cross-origin while |
| 74 | // native <img> loading still works. The object URL is shared per agent and |
| 75 | // revoked when the last icon unmounts. |
| 76 | const acpRegistryIconSourceAtom = Atom.family((iconUrl: string) => |
| 77 | Atom.make((get) => { |
| 78 | let disposed = false; |
| 79 | let objectUrl: string | null = null; |
| 80 | get.addFinalizer(() => { |
| 81 | disposed = true; |
| 82 | if (objectUrl !== null) URL.revokeObjectURL(objectUrl); |
| 83 | }); |
| 84 | return Effect.promise(() => |
| 85 | loadCachedAcpRegistryIcon(iconUrl).then( |
| 86 | (blob) => { |
| 87 | if (disposed) return iconUrl; |
| 88 | objectUrl = URL.createObjectURL(blob); |
| 89 | return objectUrl; |
| 90 | }, |
| 91 | () => iconUrl, |
| 92 | ), |
| 93 | ); |
| 94 | }).pipe(Atom.withLabel(`acp-registry-icon:${iconUrl}`)), |
| 95 | ); |
| 96 | |
| 97 | const NO_ICON_SOURCE_ATOM = Atom.make(AsyncResult.initial<string>()); |
| 98 | |
| 99 | export function AcpRegistryAgentIcon({ |
| 100 | icon, |
| 101 | className, |
| 102 | fallbackClassName, |
| 103 | }: { |
| 104 | readonly icon: string | null; |
| 105 | readonly className?: string; |
| 106 | readonly fallbackClassName?: string; |
| 107 | }) { |
| 108 | const colorFilterId = useId(); |
| 109 | const iconUrl = resolveOfficialAcpRegistryIconUrl(icon); |
| 110 | // Render only after the load pipeline resolves, so the fallback icon does |
| 111 | // not flash a broken image. |
| 112 | const source = AsyncResult.getOrElse( |
| 113 | useAtomValue(iconUrl === null ? NO_ICON_SOURCE_ATOM : acpRegistryIconSourceAtom(iconUrl)), |
| 114 | () => null, |
| 115 | ); |
| 116 | const [image, setImage] = useState<{ |
| 117 | readonly source: string; |
| 118 | readonly status: "loaded" | "failed"; |
| 119 | } | null>(null); |
| 120 | const status = source !== null && image?.source === source ? image.status : "loading"; |
| 121 | |
| 122 | return ( |
| 123 | <span |
| 124 | aria-hidden |
| 125 | className={cn( |
| 126 | "relative flex size-8 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted text-muted-foreground", |
| 127 | className, |
| 128 | )} |
| 129 | > |
| 130 | {/* Recolor alpha because external images cannot inherit currentColor; local SVG filters work despite |
| 131 | * CDN mask CORS restrictions. */} |
| 132 | <svg aria-hidden className="pointer-events-none absolute size-0" focusable="false"> |
| 133 | <defs> |
| 134 | <filter id={colorFilterId} colorInterpolationFilters="sRGB"> |
| 135 | <feFlood floodColor="currentColor" /> |
| 136 | <feComposite in2="SourceAlpha" operator="in" /> |
| 137 | </filter> |
| 138 | </defs> |
| 139 | </svg> |
| 140 | {status !== "loaded" ? ( |
| 141 | <ACPRegistryIcon |
| 142 | className={cn("size-4", fallbackClassName)} |
| 143 | data-slot="acp-icon-fallback" |
| 144 | /> |
| 145 | ) : null} |
| 146 | {source !== null && status !== "failed" ? ( |
| 147 | <img |
| 148 | alt="" |
| 149 | className={cn( |
| 150 | "size-full object-contain", |
| 151 | status !== "loaded" && "invisible absolute inset-0", |
| 152 | )} |
| 153 | style={{ filter: `url(#${colorFilterId})` }} |
| 154 | decoding="async" |
| 155 | referrerPolicy="no-referrer" |
| 156 | src={source} |
| 157 | onError={() => setImage({ source, status: "failed" })} |
| 158 | onLoad={() => setImage({ source, status: "loaded" })} |
| 159 | /> |
| 160 | ) : null} |
| 161 | </span> |
| 162 | ); |
| 163 | } |