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 // Privacy modes may expose CacheStorage but reject access; icons still load from the allowlisted CDN.
42 }
43 }
44 if (cache !== null) {
45 try {
46 const cached = await cache.match(iconUrl);
47 if (cached) return await checkedIconBlob(cached);
48 } catch {}
49 }
50
51 const response = await fetch(iconUrl, {
52 credentials: "omit",
53 redirect: "error",
54 referrerPolicy: "no-referrer",
55 });
56 const clone = response.clone();
57 const blob = await checkedIconBlob(response);
58 await cache?.put(iconUrl, clone).catch(() => undefined);
59 return blob;
60 })();
61 inFlightIcons.set(iconUrl, load);
62 void load.then(
63 () => inFlightIcons.delete(iconUrl),
64 () => inFlightIcons.delete(iconUrl),
65 );
66 return load;
67}
68
69export function AcpRegistryAgentIcon({
70 icon,
71 className,
72 fallbackClassName,
73}: {
74 readonly icon: string | null;
75 readonly className?: string;
76 readonly fallbackClassName?: string;
77}) {
78 const colorFilterId = useId();
79 const iconUrl = resolveOfficialAcpRegistryIconUrl(icon);
80 const [image, setImage] = useState<{
81 readonly iconUrl: string;
82 readonly source: string;
83 readonly status: "loading" | "loaded" | "failed";
84 } | null>(null);
85 const currentImage = image?.iconUrl === iconUrl ? image : null;
86 // The CDN lacks CORS headers; native img loading can succeed after a validating fetch fails.
87 const source = currentImage?.source ?? null;
88 const status = currentImage?.status ?? "loading";
89
90 useEffect(() => {
91 if (iconUrl === null) return;
92 let active = true;
93 let objectUrl: string | null = null;
94 void loadCachedAcpRegistryIcon(iconUrl)
95 .then((blob) => {
96 if (!active) return;
97 objectUrl = URL.createObjectURL(blob);
98 setImage({ iconUrl, source: objectUrl, status: "loading" });
99 })
100 .catch(() => {
101 if (!active) return;
102 setImage((current) =>
103 current?.iconUrl === iconUrl ? current : { iconUrl, source: iconUrl, status: "loading" },
104 );
105 });
106 return () => {
107 active = false;
108 if (objectUrl !== null) URL.revokeObjectURL(objectUrl);
109 };
110 }, [iconUrl]);
111
112 return (
113 <span
114 aria-hidden
115 className={cn(
116 "relative flex size-8 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted text-muted-foreground",
117 className,
118 )}
119 >
120 {/* Recolor alpha because external images cannot inherit currentColor; local SVG filters work despite
121 * CDN mask CORS restrictions. */}
122 <svg aria-hidden className="pointer-events-none absolute size-0" focusable="false">
123 <defs>
124 <filter id={colorFilterId} colorInterpolationFilters="sRGB">
125 <feFlood floodColor="currentColor" />
126 <feComposite in2="SourceAlpha" operator="in" />
127 </filter>
128 </defs>
129 </svg>
130 {status !== "loaded" ? (
131 <ACPRegistryIcon
132 className={cn("size-4", fallbackClassName)}
133 data-slot="acp-icon-fallback"
134 />
135 ) : null}
136 {source !== null && status !== "failed" ? (
137 <img
138 alt=""
139 className={cn(
140 "size-full object-contain",
141 status !== "loaded" && "invisible absolute inset-0",
142 )}
143 style={{ filter: `url(#${colorFilterId})` }}
144 decoding="async"
145 referrerPolicy="no-referrer"
146 src={source}
147 onError={() => {
148 if (iconUrl === null) return;
149 setImage((current) =>
150 current?.iconUrl === iconUrl && current.source !== source
151 ? current
152 : { iconUrl, source, status: "failed" },
153 );
154 }}
155 onLoad={() => {
156 if (iconUrl !== null) setImage({ iconUrl, source, status: "loaded" });
157 }}
158 />
159 ) : null}
160 </span>
161 );
162}