Skip to content

Commit 4f54ed5

Browse files
refactor(web): ChatView's attachment preview handoff lives in useAttachmentPreviewHandoff
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 1ff7eb6 commit 4f54ed5

2 files changed

Lines changed: 232 additions & 201 deletions

File tree

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 7 additions & 201 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { useAttachmentPreviewHandoff } from "./chat/useAttachmentPreviewHandoff";
12
import { useTimelineRewind } from "./chat/useTimelineRewind";
23
import { useThreadLifecycle } from "./chat/useThreadLifecycle";
34
import { useRightPanelActions } from "./chat/useRightPanelActions";
@@ -125,7 +126,6 @@ import { useActiveThreadRef } from "../hooks/useActiveThreadRef";
125126
import { composerRequiresModifier } from "../composer-logic";
126127
import {
127128
derivePhase,
128-
selectHandoffImageResources,
129129
deriveActivePlanState,
130130
selectComposerTasksPlan,
131131
deriveActiveWorkStartedAt,
@@ -343,7 +343,6 @@ import {
343343
resolveComposerProviderSelection,
344344
resolveThreadMetadataUpdateForNextTurn,
345345
resolveSendEnvMode,
346-
revokeBlobPreviewUrl,
347346
revokeUserMessagePreviewUrls,
348347
startNewThreadForProject,
349348
codexArtifactTemplatePromptToAppend,
@@ -359,7 +358,6 @@ import { useAtomCommand } from "../state/use-atom-command";
359358
import { useOrchestrationCommand } from "../state/use-orchestration-command";
360359
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
361360
import { Button } from "./ui/button";
362-
import { useAssetUrls } from "../assets/assetUrls";
363361
import { observeResize } from "~/lib/observeResize";
364362
import { ThreadVisitWatermark } from "./chat/ThreadVisitWatermark";
365363
import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers";
@@ -697,10 +695,6 @@ export default function ChatView(props: ChatViewProps) {
697695
const feedbackUploading = feedbackSubmissions.some(
698696
(submission) => submission.status === "uploading",
699697
);
700-
const optimisticUserMessagesRef = useRef(optimisticUserMessages);
701-
useLayoutEffect(() => {
702-
optimisticUserMessagesRef.current = optimisticUserMessages;
703-
});
704698
const [localDraftErrorsByDraftId, setLocalDraftErrorsByDraftId] = useState<
705699
Record<string, LocalThreadErrorEntry>
706700
>({});
@@ -732,9 +726,6 @@ export default function ChatView(props: ChatViewProps) {
732726
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
733727
const [terminalUiLaunchContext, setTerminalUiLaunchContext] =
734728
useState<TerminalLaunchContext | null>(null);
735-
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
736-
Record<string, string[]>
737-
>({});
738729
// Overrides chosen before a server thread's first turn; they belong to that thread only.
739730
const [pendingServerThreadEnvModeEntry, setPendingServerThreadEnvModeEntry] = useState<{
740731
readonly threadId: ThreadId;
@@ -761,8 +752,6 @@ export default function ChatView(props: ChatViewProps) {
761752
const composerMountedRef = useRef(true);
762753
const [scrollToEndClearance, setScrollToEndClearance] = useState(0);
763754
const [timelineOverflows, setTimelineOverflows] = useState(false);
764-
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
765-
const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});
766755
const fanoutSelectionsAtom = draftFanoutSelectionsAtom(routeThreadKey);
767756
const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey);
768757
const multipleModelSelections = useAtomValue(fanoutSelectionsAtom);
@@ -1693,69 +1682,6 @@ export default function ChatView(props: ChatViewProps) {
16931682
const sendQueuesBehindSetup =
16941683
isServerThread && (activeRunPreparing || activeActivityRun?.status === "starting");
16951684
const [setupQueueSendThreadKey, setSetupQueueSendThreadKey] = useState<string | null>(null);
1696-
useEffect(() => {
1697-
attachmentPreviewHandoffByMessageIdRef.current = attachmentPreviewHandoffByMessageId;
1698-
}, [attachmentPreviewHandoffByMessageId]);
1699-
const clearAttachmentPreviewHandoff = (
1700-
messageId: MessageId,
1701-
previewUrls?: ReadonlyArray<string>,
1702-
) => {
1703-
delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];
1704-
const currentPreviewUrls =
1705-
previewUrls ?? attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];
1706-
setAttachmentPreviewHandoffByMessageId((existing) => {
1707-
if (!(messageId in existing)) {
1708-
return existing;
1709-
}
1710-
const next = { ...existing };
1711-
delete next[messageId];
1712-
attachmentPreviewHandoffByMessageIdRef.current = next;
1713-
return next;
1714-
});
1715-
for (const previewUrl of currentPreviewUrls) {
1716-
revokeBlobPreviewUrl(previewUrl);
1717-
}
1718-
};
1719-
const clearAttachmentPreviewHandoffStable = useStableCallback(clearAttachmentPreviewHandoff);
1720-
const clearAttachmentPreviewHandoffs = () => {
1721-
attachmentPreviewPromotionInFlightByMessageIdRef.current = {};
1722-
for (const previewUrls of Object.values(attachmentPreviewHandoffByMessageIdRef.current)) {
1723-
for (const previewUrl of previewUrls) {
1724-
revokeBlobPreviewUrl(previewUrl);
1725-
}
1726-
}
1727-
attachmentPreviewHandoffByMessageIdRef.current = {};
1728-
setAttachmentPreviewHandoffByMessageId({});
1729-
};
1730-
const clearAttachmentPreviewHandoffsStable = useStableCallback(clearAttachmentPreviewHandoffs);
1731-
useEffect(() => {
1732-
return () => {
1733-
clearAttachmentPreviewHandoffsStable();
1734-
for (const message of optimisticUserMessagesRef.current) {
1735-
revokeUserMessagePreviewUrls(message);
1736-
}
1737-
};
1738-
}, [clearAttachmentPreviewHandoffsStable]);
1739-
const handoffAttachmentPreviews = (messageId: MessageId, previewUrls: string[]) => {
1740-
if (previewUrls.length === 0) return;
1741-
1742-
const previousPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];
1743-
const nextPreviewUrlSet = new Set(previewUrls);
1744-
for (const previewUrl of previousPreviewUrls) {
1745-
if (!nextPreviewUrlSet.has(previewUrl)) {
1746-
revokeBlobPreviewUrl(previewUrl);
1747-
}
1748-
}
1749-
setAttachmentPreviewHandoffByMessageId((existing) => {
1750-
const next = {
1751-
...existing,
1752-
[messageId]: previewUrls,
1753-
};
1754-
attachmentPreviewHandoffByMessageIdRef.current = next;
1755-
return next;
1756-
});
1757-
};
1758-
const handoffAttachmentPreviewsStable = useStableCallback(handoffAttachmentPreviews);
17591685
const downloadFileAttachment = async (attachment: ChatFileAttachment) => {
17601686
const connection = readPreparedConnection(environmentId);
17611687
if (!connection) {
@@ -1790,132 +1716,12 @@ export default function ChatView(props: ChatViewProps) {
17901716
}
17911717
};
17921718
const openFileAttachmentStable = useStableCallback(openFileAttachment);
1793-
const serverAttachmentResources = selectHandoffImageResources(
1794-
Object.keys(attachmentPreviewHandoffByMessageId).length === 0
1795-
? undefined
1796-
: serverVisibleTurnItems.flatMap(({ item }) =>
1797-
item.type === "user_message"
1798-
? [{ id: item.messageId, role: "user" as const, attachments: item.attachments }]
1799-
: [],
1800-
),
1801-
attachmentPreviewHandoffByMessageId,
1802-
);
1803-
const serverAttachmentUrls = useAssetUrls(environmentId, serverAttachmentResources);
1804-
const serverAttachmentUrlById = new Map(
1805-
serverAttachmentResources.flatMap((resource, index) => {
1806-
const url = serverAttachmentUrls[index];
1807-
return url ? [[resource.attachmentId, url] as const] : [];
1808-
}),
1809-
);
1810-
useEffect(() => {
1811-
if (typeof Image === "undefined" || serverVisibleTurnItems.length === 0) {
1812-
return;
1813-
}
1814-
1815-
const cleanups: Array<() => void> = [];
1816-
const userMessagesById = new Map(
1817-
serverVisibleTurnItems.flatMap((row) =>
1818-
row.item.type === "user_message" ? [[String(row.item.messageId), row.item] as const] : [],
1819-
),
1820-
);
1821-
1822-
for (const [messageId, handoffPreviewUrls] of Object.entries(
1823-
attachmentPreviewHandoffByMessageId,
1824-
)) {
1825-
if (attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]) {
1826-
continue;
1827-
}
1828-
1829-
const serverMessage = userMessagesById.get(messageId);
1830-
if (serverMessage === undefined || serverMessage.attachments.length === 0) {
1831-
continue;
1832-
}
1833-
1834-
const serverPreviewUrls = serverMessage.attachments.flatMap((attachment) =>
1835-
attachment.type === "image"
1836-
? [serverAttachmentUrlById.get(attachment.id)].filter(
1837-
(previewUrl): previewUrl is string => previewUrl !== undefined,
1838-
)
1839-
: [],
1840-
);
1841-
if (
1842-
serverPreviewUrls.length === 0 ||
1843-
serverPreviewUrls.length !== handoffPreviewUrls.length ||
1844-
serverPreviewUrls.some((previewUrl) => previewUrl.startsWith("blob:"))
1845-
) {
1846-
continue;
1847-
}
1848-
1849-
attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId] = true;
1850-
1851-
let cancelled = false;
1852-
const imageInstances: HTMLImageElement[] = [];
1853-
1854-
const preloadServerPreviews = Promise.all(
1855-
serverPreviewUrls.map(
1856-
(previewUrl) =>
1857-
new Promise<void>((resolve, reject) => {
1858-
const image = new Image();
1859-
imageInstances.push(image);
1860-
const handleLoad = () => resolve();
1861-
const handleError = () =>
1862-
reject(new Error(`Failed to load server preview for ${messageId}.`));
1863-
image.addEventListener("load", handleLoad, { once: true });
1864-
image.addEventListener("error", handleError, { once: true });
1865-
image.src = previewUrl;
1866-
}),
1867-
),
1868-
);
1869-
1870-
void preloadServerPreviews
1871-
.then(() => {
1872-
if (cancelled) {
1873-
return;
1874-
}
1875-
clearAttachmentPreviewHandoffStable(messageId as MessageId, handoffPreviewUrls);
1876-
})
1877-
.catch(() => {
1878-
if (!cancelled) {
1879-
delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];
1880-
}
1881-
});
1882-
1883-
cleanups.push(() => {
1884-
cancelled = true;
1885-
delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];
1886-
for (const image of imageInstances) {
1887-
image.src = "";
1888-
}
1889-
});
1890-
}
1891-
1892-
return () => {
1893-
for (const cleanup of cleanups) {
1894-
cleanup();
1895-
}
1896-
};
1897-
}, [
1898-
attachmentPreviewHandoffByMessageId,
1899-
clearAttachmentPreviewHandoffStable,
1900-
serverAttachmentUrlById,
1901-
serverVisibleTurnItems,
1902-
]);
1903-
const timelineAttachmentUrlById = (() => {
1904-
const urls = new Map(serverAttachmentUrlById);
1905-
for (const row of serverVisibleTurnItems) {
1906-
if (row.item.type !== "user_message") continue;
1907-
const handoffUrls = attachmentPreviewHandoffByMessageId[row.item.messageId];
1908-
if (handoffUrls === undefined) continue;
1909-
let imageIndex = 0;
1910-
for (const attachment of row.item.attachments) {
1911-
if (attachment.type !== "image") continue;
1912-
const handoffUrl = handoffUrls[imageIndex];
1913-
imageIndex += 1;
1914-
if (handoffUrl !== undefined) urls.set(attachment.id, handoffUrl);
1915-
}
1916-
}
1917-
return urls;
1918-
})();
1719+
const { handoffAttachmentPreviewsStable, timelineAttachmentUrlById } =
1720+
useAttachmentPreviewHandoff({
1721+
environmentId,
1722+
serverVisibleTurnItems,
1723+
optimisticUserMessages,
1724+
});
19191725
const anchoredTimelineMessages = feedbackSubmissions.flatMap((submission) =>
19201726
submission.status === "interrupted"
19211727
? []

0 commit comments

Comments
 (0)