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

useAttachmentPreviewHandoff.ts

112 lines4.5 KB

1import { type EnvironmentId, type MessageId, type ThreadId } from "@t3tools/contracts";
2import { useAtomValue } from "@effect/atom-react";
3import { type Dispatch, type SetStateAction, useEffect } from "react";
4import { selectHandoffImageResources } from "../../session-logic";
5import type { useQuietThreadVisibleTurnItems } from "../../state/entities";
6import { useAssetUrls } from "../../assets/assetUrls";
7import {
8 dropOptimisticHandoff,
9 loadedHandoffMessageIdsAtom,
10 type OptimisticBlobPreviews,
11 type OptimisticUserMessages,
12} from "./optimisticUserMessages";
13​
14interface AttachmentPreviewHandoffInput {
15 readonly environmentId: EnvironmentId;
16 readonly threadId: ThreadId;
17 readonly serverVisibleTurnItems: ReturnType<typeof useQuietThreadVisibleTurnItems>;
18 /** Blob previews of acknowledged messages, by message id; they stand in for the server's copy. */
19 readonly handoff: OptimisticUserMessages["handoff"];
20 readonly blobPreviews: OptimisticBlobPreviews;
21 readonly setOptimisticUserMessages: Dispatch<SetStateAction<OptimisticUserMessages>>;
23​
24/**
25 * A sent image keeps showing its local blob preview until the server's copy has loaded, so the
26 * timeline does not flash an empty frame. The handoff ends, and its blobs are revoked, once the
27 * server previews load.
28 */
29export function useAttachmentPreviewHandoff(input: AttachmentPreviewHandoffInput) {
30 const {
31 environmentId,
32 threadId,
33 serverVisibleTurnItems,
34 blobPreviews,
35 setOptimisticUserMessages,
36 } = input;
37 const handoffByMessageId = input.handoff;
38​
39 // Blob URLs are a browser resource owned per thread; leaving the thread or the view ends them.
40 useEffect(() => () => blobPreviews.revokeThread(threadId), [blobPreviews, threadId]);
41​
42 const serverAttachmentResources = selectHandoffImageResources(
43 Object.keys(handoffByMessageId).length === 0
44 ? undefined
45 : serverVisibleTurnItems.flatMap(({ item }) =>
46 item.type === "user_message"
47 ? [{ id: item.messageId, role: "user" as const, attachments: item.attachments }]
48 : [],
49 ),
50 handoffByMessageId,
51 );
52 const serverAttachmentUrls = useAssetUrls(environmentId, serverAttachmentResources);
53 const serverAttachmentUrlById = new Map(
54 serverAttachmentResources.flatMap((resource, index) => {
55 const url = serverAttachmentUrls[index];
56 return url ? [[resource.attachmentId, url] as const] : [];
57 }),
58 );
59​
60 // Each handoff whose server previews are all minted, as [messageId, serverUrls, blobUrls].
61 const pendingPreloads: Array<readonly [MessageId, ReadonlyArray<string>, ReadonlyArray<string>]> =
62 [];
63 for (const row of serverVisibleTurnItems) {
64 if (row.item.type !== "user_message") continue;
65 const handoffUrls = handoffByMessageId[row.item.messageId];
66 if (handoffUrls === undefined || row.item.attachments.length === 0) continue;
67 const serverPreviewUrls = row.item.attachments.flatMap((attachment) => {
68 if (attachment.type !== "image") return [];
69 const url = serverAttachmentUrlById.get(attachment.id);
70 return url === undefined ? [] : [url];
71 });
72 if (
73 serverPreviewUrls.length === 0 ||
74 serverPreviewUrls.length !== handoffUrls.length ||
75 serverPreviewUrls.some((previewUrl) => previewUrl.startsWith("blob:"))
76 ) {
77 continue;
78 }
79 pendingPreloads.push([row.item.messageId, serverPreviewUrls, handoffUrls]);
80 }
81 const loadedHandoffMessageIds = useAtomValue(
82 loadedHandoffMessageIdsAtom(JSON.stringify(pendingPreloads)),
83 );
84 // The handoff is state of the rendering ChatView, so dropping a loaded one here is React's
85 // adjust-state-while-rendering pattern; the preload atom has already revoked its blobs.
86 if (loadedHandoffMessageIds.length > 0) {
87 setOptimisticUserMessages((state) =>
88 loadedHandoffMessageIds.reduce(
89 (next, messageId) => dropOptimisticHandoff(next, threadId, messageId),
90 state,
91 ),
92 );
93 }
94​
95 const timelineAttachmentUrlById = (() => {
96 const urls = new Map(serverAttachmentUrlById);
97 for (const row of serverVisibleTurnItems) {
98 if (row.item.type !== "user_message") continue;
99 const handoffUrls = handoffByMessageId[row.item.messageId];
100 if (handoffUrls === undefined) continue;
101 let imageIndex = 0;
102 for (const attachment of row.item.attachments) {
103 if (attachment.type !== "image") continue;
104 const handoffUrl = handoffUrls[imageIndex];
105 imageIndex += 1;
106 if (handoffUrl !== undefined) urls.set(attachment.id, handoffUrl);
107 }
108 }
109 return urls;
110 })();
111 return { timelineAttachmentUrlById };