perf(web): defer image URL requests for thread history (#9760)
This commit is contained in:
1 parent
6365919f2e
commit
15eda897d3
4 files changed
+196
-30
No files matched your search
@@ -104,6 +104,7 @@ import {
|
||||
deriveWorkLogEntries,
|
||||
hasActionableProposedPlan,
|
||||
isLatestTurnSettled,
|
||||
selectHandoffImageResources,
|
||||
type TimelineEntriesProjection,
|
||||
} from "../session-logic";
|
||||
import { type LegendListRef } from "@legendapp/list/react";
|
||||
@@ -2763,35 +2764,20 @@ export default function ChatView(props: ChatViewProps) {
|
||||
},
|
||||
[activeThreadRef, downloadFileAttachment],
|
||||
);
|
||||
const serverAttachmentIds = useMemo(() => {
|
||||
const attachmentIds = new Set<string>();
|
||||
for (const message of serverMessages ?? []) {
|
||||
for (const attachment of message.attachments ?? []) {
|
||||
if (isImageAttachment(attachment)) {
|
||||
attachmentIds.add(attachment.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...attachmentIds];
|
||||
}, [serverMessages]);
|
||||
const serverAttachmentResources = useMemo(
|
||||
() =>
|
||||
serverAttachmentIds.map((attachmentId) => ({
|
||||
_tag: "attachment" as const,
|
||||
attachmentId,
|
||||
})),
|
||||
[serverAttachmentIds],
|
||||
() => selectHandoffImageResources(serverMessages, attachmentPreviewHandoffByMessageId),
|
||||
[serverMessages, attachmentPreviewHandoffByMessageId],
|
||||
);
|
||||
const serverAttachmentUrls = useAssetUrls(environmentId, serverAttachmentResources);
|
||||
const serverAttachmentUrlById = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
serverAttachmentIds.flatMap((attachmentId, index) => {
|
||||
serverAttachmentResources.flatMap((resource, index) => {
|
||||
const url = serverAttachmentUrls[index];
|
||||
return url ? [[attachmentId, url] as const] : [];
|
||||
return url ? [[resource.attachmentId, url] as const] : [];
|
||||
}),
|
||||
),
|
||||
[serverAttachmentIds, serverAttachmentUrls],
|
||||
[serverAttachmentResources, serverAttachmentUrls],
|
||||
);
|
||||
const displayServerMessages = useMemo<ReadonlyArray<ChatMessage>>(() => {
|
||||
if (!serverMessages) return [];
|
||||
|
||||
@@ -52,7 +52,9 @@ import {
|
||||
import { FileDiff } from "@pierre/diffs/react";
|
||||
import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
|
||||
import {
|
||||
createMessageAttachmentPreviewProjector,
|
||||
deriveTimelineEntries,
|
||||
selectMessageImageResources,
|
||||
workEntryDisplayIndicatesToolFailure,
|
||||
workEntrySignalsSevereFailure,
|
||||
workLogEntryIsToolLike,
|
||||
@@ -99,7 +101,7 @@ import {
|
||||
ZapIcon,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { useAssetUrlRefresh, useAssetUrlState } from "../../assets/assetUrls";
|
||||
import { useAssetUrlRefresh, useAssetUrls, useAssetUrlState } from "../../assets/assetUrls";
|
||||
import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
|
||||
import { getVirtualizedScrollFadeClassName } from "../ui/scroll-area";
|
||||
import {
|
||||
@@ -1227,9 +1229,24 @@ function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) {
|
||||
|
||||
function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const resources = useMemo(
|
||||
() => selectMessageImageResources(row.message.attachments),
|
||||
[row.message.attachments],
|
||||
);
|
||||
const previewUrls = useAssetUrls(ctx.activeThreadEnvironmentId, resources);
|
||||
const [projectPreviews] = useState(createMessageAttachmentPreviewProjector);
|
||||
const messageWithPreviews = useMemo(() => {
|
||||
const urlsById = new Map(
|
||||
resources.flatMap((resource, index) => {
|
||||
const url = previewUrls[index];
|
||||
return url ? [[resource.attachmentId, url] as const] : [];
|
||||
}),
|
||||
);
|
||||
return projectPreviews(row.message, (attachment) => urlsById.get(attachment.id));
|
||||
}, [previewUrls, projectPreviews, resources, row.message]);
|
||||
// The attachment union has an open member, so guards (not literal type
|
||||
// comparisons) split it. Unknown types render as inert rows below the files.
|
||||
const userImages = (row.message.attachments ?? []).filter(isImageAttachment);
|
||||
const userImages = (messageWithPreviews.attachments ?? []).filter(isImageAttachment);
|
||||
const userFiles = (row.message.attachments ?? []).filter(isFileAttachment);
|
||||
const userVideos = userFiles.filter(isVideoAttachment);
|
||||
const otherUserFiles = userFiles.filter((file) => !isVideoAttachment(file));
|
||||
|
||||
@@ -21,6 +21,8 @@ import {
|
||||
findLatestProposedPlan,
|
||||
hasActionableProposedPlan,
|
||||
isLatestTurnSettled,
|
||||
selectHandoffImageResources,
|
||||
selectMessageImageResources,
|
||||
workEntryIndicatesToolFailure,
|
||||
workEntryIndicatesToolNeutralStatus,
|
||||
workEntryIndicatesToolSuccess,
|
||||
@@ -2075,6 +2077,128 @@ describe("deriveWorkLogEntries", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("image asset requests", () => {
|
||||
const image = {
|
||||
type: "image" as const,
|
||||
id: "image",
|
||||
name: "image.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 42,
|
||||
};
|
||||
const message = {
|
||||
id: MessageId.make("image-message"),
|
||||
role: "user" as const,
|
||||
text: "Inspect these images",
|
||||
turnId: null,
|
||||
createdAt: "2026-09-04T00:00:00.000Z",
|
||||
updatedAt: "2026-09-04T00:00:00.000Z",
|
||||
streaming: false,
|
||||
attachments: [image],
|
||||
};
|
||||
|
||||
it("requests the whole row's gallery and crops without signing local preview IDs", () => {
|
||||
const attachments = Object.freeze([
|
||||
image,
|
||||
{ ...image, id: "second" },
|
||||
{ ...image, id: "crop", name: "preview-annotation-1.png" },
|
||||
{ ...image, id: "local", previewUrl: "blob:local" },
|
||||
{ ...image, id: "inline", previewUrl: "data:image/png;base64,AA==" },
|
||||
{ ...image, id: "provided", previewUrl: "https://preview.test/image" },
|
||||
{ ...image, type: "file" as const, id: "file", mimeType: "application/pdf" },
|
||||
{ ...image, type: "future", id: "unknown" },
|
||||
image,
|
||||
]);
|
||||
|
||||
expect(selectMessageImageResources(attachments)).toEqual([
|
||||
{ _tag: "attachment", attachmentId: "image" },
|
||||
{ _tag: "attachment", attachmentId: "second" },
|
||||
{ _tag: "attachment", attachmentId: "crop" },
|
||||
{ _tag: "attachment", attachmentId: "provided" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("requests offscreen handoffs without signing the rest of the loaded history", () => {
|
||||
const history = {
|
||||
...message,
|
||||
id: MessageId.make("history"),
|
||||
attachments: [{ ...image, id: "history-image" }],
|
||||
};
|
||||
const offscreen = {
|
||||
...message,
|
||||
id: MessageId.make("offscreen"),
|
||||
attachments: [image, { ...image, id: "crop", name: "preview-annotation-1.png" }],
|
||||
};
|
||||
const empty = {
|
||||
...message,
|
||||
id: MessageId.make("empty"),
|
||||
attachments: [{ ...image, id: "empty" }],
|
||||
};
|
||||
const assistant = {
|
||||
...message,
|
||||
id: MessageId.make("assistant"),
|
||||
role: "assistant" as const,
|
||||
attachments: [{ ...image, id: "assistant-image" }],
|
||||
};
|
||||
expect(
|
||||
selectHandoffImageResources([history, message, offscreen, empty, assistant], {
|
||||
[message.id]: ["blob:message"],
|
||||
[offscreen.id]: ["blob:offscreen", "blob:crop"],
|
||||
[empty.id]: [],
|
||||
[assistant.id]: ["blob:unused"],
|
||||
}),
|
||||
).toEqual([
|
||||
{ _tag: "attachment", attachmentId: "image" },
|
||||
{ _tag: "attachment", attachmentId: "crop" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not scan history when no handoff is pending", () => {
|
||||
let reads = 0;
|
||||
const messages = new Proxy([message], {
|
||||
get(target, property, receiver) {
|
||||
if (property === "0") reads += 1;
|
||||
return Reflect.get(target, property, receiver);
|
||||
},
|
||||
});
|
||||
const empty = selectHandoffImageResources(messages, {});
|
||||
expect(reads).toBe(0);
|
||||
expect(empty).toHaveLength(0);
|
||||
expect(selectHandoffImageResources(undefined, { missing: ["blob:missing"] })).toBe(empty);
|
||||
expect(selectMessageImageResources(undefined)).toBe(empty);
|
||||
});
|
||||
|
||||
it("hands signed URLs to a mounted row only after the local preview is released", () => {
|
||||
const server = createMessageAttachmentPreviewProjector();
|
||||
const handoff = createMessageAttachmentPreviewProjector();
|
||||
const row = createMessageAttachmentPreviewProjector();
|
||||
const pending = handoff(
|
||||
server(message, () => undefined),
|
||||
() => "blob:pending",
|
||||
);
|
||||
expect(selectMessageImageResources(pending.attachments)).toEqual([]);
|
||||
expect(selectHandoffImageResources([message], { [message.id]: ["blob:pending"] })).toEqual([
|
||||
{ _tag: "attachment", attachmentId: image.id },
|
||||
]);
|
||||
|
||||
const ready = server(message, () => "https://server.test/image");
|
||||
expect(selectMessageImageResources(handoff(ready, () => "blob:pending").attachments)).toEqual(
|
||||
[],
|
||||
);
|
||||
const released = server(message, () => undefined);
|
||||
expect(selectMessageImageResources(released.attachments)).toEqual([
|
||||
{ _tag: "attachment", attachmentId: image.id },
|
||||
]);
|
||||
const displayed = row(released, () => "https://server.test/image");
|
||||
expect(displayed).toEqual(ready);
|
||||
expect(pending.attachments?.[0]).toMatchObject({ previewUrl: "blob:pending" });
|
||||
expect(row(released, () => "https://server.test/renewed").attachments?.[0]).toMatchObject({
|
||||
previewUrl: "https://server.test/renewed",
|
||||
});
|
||||
expect(displayed.attachments?.[0]).toMatchObject({ previewUrl: "https://server.test/image" });
|
||||
expect(row(released, () => undefined)).toBe(message);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveTimelineEntries", () => {
|
||||
const streamingMessage = {
|
||||
id: MessageId.make("streaming-message"),
|
||||
|
||||
@@ -12,6 +12,7 @@ import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-lo
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
isToolLifecycleItemType,
|
||||
type AssetResource,
|
||||
type OrchestrationLatestTurn,
|
||||
type OrchestrationThreadActivity,
|
||||
type OrchestrationProposedPlanId,
|
||||
@@ -24,14 +25,15 @@ import {
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type {
|
||||
ChatAttachment,
|
||||
ChatMessage,
|
||||
ProposedPlan,
|
||||
SessionPhase,
|
||||
Thread,
|
||||
ThreadSession,
|
||||
TurnDiffSummary,
|
||||
import {
|
||||
isImageAttachment,
|
||||
type ChatAttachment,
|
||||
type ChatMessage,
|
||||
type ProposedPlan,
|
||||
type SessionPhase,
|
||||
type Thread,
|
||||
type ThreadSession,
|
||||
type TurnDiffSummary,
|
||||
} from "./types";
|
||||
|
||||
export type ProviderPickerKind = ProviderDriverKind;
|
||||
@@ -1883,6 +1885,43 @@ function mergeTimelineEntrySuffix(
|
||||
return merged;
|
||||
}
|
||||
|
||||
type AttachmentResource = Extract<AssetResource, { readonly _tag: "attachment" }>;
|
||||
const EMPTY_IMAGE_RESOURCES = Object.freeze<ReadonlyArray<AttachmentResource>>([]);
|
||||
|
||||
/** A mounted row requests its stored images. Local previews keep their existing URLs. */
|
||||
export function selectMessageImageResources(
|
||||
attachments: ChatMessage["attachments"],
|
||||
): ReadonlyArray<AttachmentResource> {
|
||||
const attachmentIds = new Set<string>();
|
||||
for (const attachment of attachments ?? []) {
|
||||
if (!isImageAttachment(attachment)) continue;
|
||||
const previewUrl = attachment.previewUrl;
|
||||
if (previewUrl?.startsWith("blob:") || previewUrl?.startsWith("data:")) continue;
|
||||
attachmentIds.add(attachment.id);
|
||||
}
|
||||
return attachmentIds.size === 0
|
||||
? EMPTY_IMAGE_RESOURCES
|
||||
: Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
|
||||
}
|
||||
|
||||
/** Handoffs need server URLs even while their message rows are unmounted. */
|
||||
export function selectHandoffImageResources(
|
||||
messages: ReadonlyArray<ChatMessage> | undefined,
|
||||
handoffs: Readonly<Record<string, ReadonlyArray<string>>>,
|
||||
): ReadonlyArray<AttachmentResource> {
|
||||
if (Object.keys(handoffs).length === 0) return EMPTY_IMAGE_RESOURCES;
|
||||
const attachmentIds = new Set<string>();
|
||||
for (const message of messages ?? []) {
|
||||
if (message.role !== "user" || !handoffs[message.id]?.length) continue;
|
||||
for (const attachment of message.attachments ?? []) {
|
||||
if (isImageAttachment(attachment)) attachmentIds.add(attachment.id);
|
||||
}
|
||||
}
|
||||
return attachmentIds.size === 0
|
||||
? EMPTY_IMAGE_RESOURCES
|
||||
: Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
|
||||
}
|
||||
|
||||
/** Own one mapper per preview stage. Immutable messages retain unchanged preview objects. */
|
||||
export function createMessageAttachmentPreviewProjector() {
|
||||
const attachmentsBySource = new WeakMap<
|
||||
|
||||
Reference in new issue
Block a user