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

AcpRegistryIcon.tsx

165 lines5.7 KB

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