Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AcpRegistryIcon.tsx

157 lines5.3 KB

1import { useEffect, 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 });
28​
29/** Fetches an official icon once, then serves it from persistent browser cache. */
30export function loadCachedAcpRegistryIcon(iconUrl: string): Promise<Blob> {
31 if (resolveOfficialAcpRegistryIconUrl(iconUrl) !== iconUrl) {
32 return Promise.reject(new Error("ACP registry icon URL was not allowed."));
33 }
34 const pending = inFlightIcons.get(iconUrl);
35 if (pending) return pending;
36 const load = (async () => {
37 let cache: Cache | null = null;
38 if (typeof caches !== "undefined") {
39 try {
40 cache = await caches.open(ACP_REGISTRY_ICON_CACHE);
41 } catch {
42 // Some privacy modes expose CacheStorage but reject access. Icons can
43 // still load normally from the allowlisted registry CDN.
44 }
45 }
46 if (cache !== null) {
47 try {
48 const cached = await cache.match(iconUrl);
49 if (cached) return await checkedIconBlob(cached);
50 } catch {
51 // Ignore unreadable or invalid cache entries and repair from network.
52 }
53 }
54​
55 const response = await fetch(iconUrl, {
56 credentials: "omit",
57 redirect: "error",
58 referrerPolicy: "no-referrer",
59 });
60 const clone = response.clone();
61 const blob = await checkedIconBlob(response);
62 await cache?.put(iconUrl, clone).catch(() => undefined);
63 return blob;
64 })();
65 inFlightIcons.set(iconUrl, load);
66 void load.then(
67 () => inFlightIcons.delete(iconUrl),
68 () => inFlightIcons.delete(iconUrl),
69 );
70 return load;
72​
73export function AcpRegistryAgentIcon({
74 icon,
75 className,
76 fallbackClassName,
77}: {
78 readonly icon: string | null;
79 readonly className?: string;
80 readonly fallbackClassName?: string;
81}) {
82 const iconUrl = resolveOfficialAcpRegistryIconUrl(icon);
83 const [image, setImage] = useState<{
84 readonly iconUrl: string;
85 readonly source: string;
86 readonly status: "loading" | "loaded" | "failed";
87 } | null>(null);
88 const currentImage = image?.iconUrl === iconUrl ? image : null;
89 // Render only after the load pipeline resolves: the validated blob when the
90 // fetch succeeds, or the raw allowlisted CDN URL when it fails (the official
91 // CDN serves no CORS headers, so the validating fetch is often blocked in
92 // cross-origin browser contexts while native <img> loading still works).
93 const source = currentImage?.source ?? null;
94 const status = currentImage?.status ?? "loading";
95​
96 useEffect(() => {
97 if (iconUrl === null) return;
98 let active = true;
99 let objectUrl: string | null = null;
100 void loadCachedAcpRegistryIcon(iconUrl)
101 .then((blob) => {
102 if (!active) return;
103 objectUrl = URL.createObjectURL(blob);
104 setImage({ iconUrl, source: objectUrl, status: "loading" });
105 })
106 .catch(() => {
107 if (!active) return;
108 setImage((current) =>
109 current?.iconUrl === iconUrl ? current : { iconUrl, source: iconUrl, status: "loading" },
110 );
111 });
112 return () => {
113 active = false;
114 if (objectUrl !== null) URL.revokeObjectURL(objectUrl);
115 };
116 }, [iconUrl]);
117​
118 return (
119 <span
120 aria-hidden
121 className={cn(
122 "relative flex size-8 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted text-muted-foreground",
123 className,
124 )}
125 >
126 {status !== "loaded" ? (
127 <ACPRegistryIcon
128 className={cn("size-4", fallbackClassName)}
129 data-slot="acp-icon-fallback"
130 />
131 ) : null}
132 {source !== null && status !== "failed" ? (
133 <img
134 alt=""
135 className={cn(
136 "size-full object-contain",
137 status !== "loaded" && "invisible absolute inset-0",
138 )}
139 decoding="async"
140 referrerPolicy="no-referrer"
141 src={source}
142 onError={() => {
143 if (iconUrl === null) return;
144 setImage((current) =>
145 current?.iconUrl === iconUrl && current.source !== source
146 ? current
147 : { iconUrl, source, status: "failed" },
148 );
149 }}
150 onLoad={() => {
151 if (iconUrl !== null) setImage({ iconUrl, source, status: "loaded" });
152 }}
153 />
154 ) : null}
155 </span>
156 );