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