Open History to see the last commit
1import { useStableCallback } from "../../hooks/useStableCallback";
2import { type EnvironmentId, type MessageId } from "@t3tools/contracts";
3import { useEffect, useLayoutEffect, useRef, useState } from "react";
4import { selectHandoffImageResources } from "../../session-logic";
5import { type ChatMessage } from "../../types";
6import type { useQuietThreadVisibleTurnItems } from "../../state/entities";
7import { revokeBlobPreviewUrl, revokeUserMessagePreviewUrls } from "../ChatView.logic";
8import { useAssetUrls } from "../../assets/assetUrls";
9interface AttachmentPreviewHandoffInput {
10 readonly environmentId: EnvironmentId;
11 readonly serverVisibleTurnItems: ReturnType<typeof useQuietThreadVisibleTurnItems>;
12 readonly optimisticUserMessages: ReadonlyArray<ChatMessage>;
13}
14
15/**
16 * A sent image keeps showing its local blob preview until the server's copy has loaded, so the
17 * timeline does not flash an empty frame. Returns the attachment URLs the timeline renders and
18 * the handoff for a message whose optimistic row was replaced by the server's.
19 */
20export function useAttachmentPreviewHandoff(input: AttachmentPreviewHandoffInput) {
21 const { environmentId, serverVisibleTurnItems, optimisticUserMessages } = input;
22
23 const optimisticUserMessagesRef = useRef(optimisticUserMessages);
24 useLayoutEffect(() => {
25 optimisticUserMessagesRef.current = optimisticUserMessages;
26 });
27 const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
28 Record<string, string[]>
29 >({});
30 const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
31 const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});
32 useEffect(() => {
33 attachmentPreviewHandoffByMessageIdRef.current = attachmentPreviewHandoffByMessageId;
34 }, [attachmentPreviewHandoffByMessageId]);
35 const clearAttachmentPreviewHandoff = (
36 messageId: MessageId,
37 previewUrls?: ReadonlyArray<string>,
38 ) => {
39 delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];
40 const currentPreviewUrls =
41 previewUrls ?? attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];
42 setAttachmentPreviewHandoffByMessageId((existing) => {
43 if (!(messageId in existing)) {
44 return existing;
45 }
46 const next = { ...existing };
47 delete next[messageId];
48 attachmentPreviewHandoffByMessageIdRef.current = next;
49 return next;
50 });
51 for (const previewUrl of currentPreviewUrls) {
52 revokeBlobPreviewUrl(previewUrl);
53 }
54 };
55 const clearAttachmentPreviewHandoffStable = useStableCallback(clearAttachmentPreviewHandoff);
56 const clearAttachmentPreviewHandoffs = () => {
57 attachmentPreviewPromotionInFlightByMessageIdRef.current = {};
58 for (const previewUrls of Object.values(attachmentPreviewHandoffByMessageIdRef.current)) {
59 for (const previewUrl of previewUrls) {
60 revokeBlobPreviewUrl(previewUrl);
61 }
62 }
63 attachmentPreviewHandoffByMessageIdRef.current = {};
64 setAttachmentPreviewHandoffByMessageId({});
65 };
66 const clearAttachmentPreviewHandoffsStable = useStableCallback(clearAttachmentPreviewHandoffs);
67 useEffect(() => {
68 return () => {
69 clearAttachmentPreviewHandoffsStable();
70 for (const message of optimisticUserMessagesRef.current) {
71 revokeUserMessagePreviewUrls(message);
72 }
73 };
74 }, [clearAttachmentPreviewHandoffsStable]);
75 const handoffAttachmentPreviews = (messageId: MessageId, previewUrls: string[]) => {
76 if (previewUrls.length === 0) return;
77
78 const previousPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];
79 const nextPreviewUrlSet = new Set(previewUrls);
80 for (const previewUrl of previousPreviewUrls) {
81 if (!nextPreviewUrlSet.has(previewUrl)) {
82 revokeBlobPreviewUrl(previewUrl);
83 }
84 }
85 setAttachmentPreviewHandoffByMessageId((existing) => {
86 const next = {
87 ...existing,
88 [messageId]: previewUrls,
89 };
90 attachmentPreviewHandoffByMessageIdRef.current = next;
91 return next;
92 });
93 };
94 const handoffAttachmentPreviewsStable = useStableCallback(handoffAttachmentPreviews);
95 const serverAttachmentResources = selectHandoffImageResources(
96 Object.keys(attachmentPreviewHandoffByMessageId).length === 0
97 ? undefined
98 : serverVisibleTurnItems.flatMap(({ item }) =>
99 item.type === "user_message"
100 ? [{ id: item.messageId, role: "user" as const, attachments: item.attachments }]
101 : [],
102 ),
103 attachmentPreviewHandoffByMessageId,
104 );
105 const serverAttachmentUrls = useAssetUrls(environmentId, serverAttachmentResources);
106 const serverAttachmentUrlById = new Map(
107 serverAttachmentResources.flatMap((resource, index) => {
108 const url = serverAttachmentUrls[index];
109 return url ? [[resource.attachmentId, url] as const] : [];
110 }),
111 );
112 useEffect(() => {
113 if (typeof Image === "undefined" || serverVisibleTurnItems.length === 0) {
114 return;
115 }
116
117 const cleanups: Array<() => void> = [];
118 const userMessagesById = new Map(
119 serverVisibleTurnItems.flatMap((row) =>
120 row.item.type === "user_message" ? [[String(row.item.messageId), row.item] as const] : [],
121 ),
122 );
123
124 for (const [messageId, handoffPreviewUrls] of Object.entries(
125 attachmentPreviewHandoffByMessageId,
126 )) {
127 if (attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]) {
128 continue;
129 }
130
131 const serverMessage = userMessagesById.get(messageId);
132 if (serverMessage === undefined || serverMessage.attachments.length === 0) {
133 continue;
134 }
135
136 const serverPreviewUrls = serverMessage.attachments.flatMap((attachment) =>
137 attachment.type === "image"
138 ? [serverAttachmentUrlById.get(attachment.id)].filter(
139 (previewUrl): previewUrl is string => previewUrl !== undefined,
140 )
141 : [],
142 );
143 if (
144 serverPreviewUrls.length === 0 ||
145 serverPreviewUrls.length !== handoffPreviewUrls.length ||
146 serverPreviewUrls.some((previewUrl) => previewUrl.startsWith("blob:"))
147 ) {
148 continue;
149 }
150
151 attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId] = true;
152
153 let cancelled = false;
154 const imageInstances: HTMLImageElement[] = [];
155
156 const preloadServerPreviews = Promise.all(
157 serverPreviewUrls.map(
158 (previewUrl) =>
159 new Promise<void>((resolve, reject) => {
160 const image = new Image();
161 imageInstances.push(image);
162 const handleLoad = () => resolve();
163 const handleError = () =>
164 reject(new Error(`Failed to load server preview for ${messageId}.`));
165 image.addEventListener("load", handleLoad, { once: true });
166 image.addEventListener("error", handleError, { once: true });
167 image.src = previewUrl;
168 }),
169 ),
170 );
171
172 void preloadServerPreviews
173 .then(() => {
174 if (cancelled) {
175 return;
176 }
177 clearAttachmentPreviewHandoffStable(messageId as MessageId, handoffPreviewUrls);
178 })
179 .catch(() => {
180 if (!cancelled) {
181 delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];
182 }
183 });
184
185 cleanups.push(() => {
186 cancelled = true;
187 delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];
188 for (const image of imageInstances) {
189 image.src = "";
190 }
191 });
192 }
193
194 return () => {
195 for (const cleanup of cleanups) {
196 cleanup();
197 }
198 };
199 }, [
200 attachmentPreviewHandoffByMessageId,
201 clearAttachmentPreviewHandoffStable,
202 serverAttachmentUrlById,
203 serverVisibleTurnItems,
204 ]);
205 const timelineAttachmentUrlById = (() => {
206 const urls = new Map(serverAttachmentUrlById);
207 for (const row of serverVisibleTurnItems) {
208 if (row.item.type !== "user_message") continue;
209 const handoffUrls = attachmentPreviewHandoffByMessageId[row.item.messageId];
210 if (handoffUrls === undefined) continue;
211 let imageIndex = 0;
212 for (const attachment of row.item.attachments) {
213 if (attachment.type !== "image") continue;
214 const handoffUrl = handoffUrls[imageIndex];
215 imageIndex += 1;
216 if (handoffUrl !== undefined) urls.set(attachment.id, handoffUrl);
217 }
218 }
219 return urls;
220 })();
221 return {
222 handoffAttachmentPreviewsStable,
223 timelineAttachmentUrlById,
224 };
225}