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

useComposerContextImport.ts

398 lines15.9 KB

1import type { RefObject } from "react";
2import type { ChatComposerProps } from "./ChatComposer";
3import {
4 type ComposerContextClipboardFragment,
5 type ComposerContextRecord,
6 type EnvironmentId,
7 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
8} from "@t3tools/contracts";
9import {
10 type ComposerFileAttachment,
11 type ComposerImageAttachment,
12 type DraftId,
13 composerFileMatchesReattachMarker,
14 composerFileNeedsReattach,
15 useComposerDraftStore,
16} from "../../composerDraftStore";
17import { type PendingUserInput } from "../../session-logic";
18import {
19 asKnownContextRecord,
20 composerContextImportLookupIds,
21 isSameComposerContextPayload,
22 previewAnnotationContextId,
23 previewAnnotationContextRecord,
24 previewAnnotationFromRecord,
25 reviewCommentContextId,
26 reviewCommentContextRecord,
27 reviewCommentFromRecord,
28 terminalContextDraftFromRecord,
29 terminalContextRecord,
30 terminalContextReference,
31} from "~/lib/composerContextRecords";
32import { assetEnvironment } from "~/state/assets";
33import { copiedComposerAttachmentFile } from "~/lib/copiedComposerAttachments";
34import { countQuestionAttachments, questionAttachmentDraftId } from "../../questionAttachments";
35import { elementContextToPreviewAnnotation } from "../../lib/elementContext";
36import { orchestrationEnvironment } from "~/state/orchestration";
37import { pendingDraftWork } from "./pendingDraftWork";
38import { randomUUID } from "~/lib/utils";
39import { readPreparedConnection } from "~/state/session";
40import { resolveAssetUrl } from "~/assets/assetUrls";
41import { toKindScopedComposerContextId } from "@t3tools/shared/composerContextReferences";
42import { toastManager } from "../ui/toast";
43import {
44 type ComposerDraftContextRecords,
45 uploadedContextRecordFromDraft,
46} from "../composerContextPresentation";
47import { useAtomCommand } from "../../state/use-atom-command";
48import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
49import { useStableCallback } from "../../hooks/useStableCallback";
50​
51async function downloadAttachmentBlob(url: string): Promise<Blob | null> {
52 try {
53 const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
54 return response.ok ? await response.blob() : null;
55 } catch {
56 return null;
57 }
59​
60/**
61 * Imports copied composer context (terminal output, review comments, annotations, threads,
62 * images and files) into the open draft, and counts the attachment slots already spoken for.
63 */
64export function useComposerContextImport(input: {
65 readonly environmentId: EnvironmentId;
66 readonly activeThread: ChatComposerProps["activeThread"];
67 readonly activeThreadId: ChatComposerProps["activeThreadId"];
68 readonly composerDraftTarget: ChatComposerProps["composerDraftTarget"];
69 readonly attachmentDraftTarget: ChatComposerProps["composerDraftTarget"];
70 readonly attachmentTargetKey: string;
71 readonly attachmentTargetKeyRef: RefObject<string>;
72 readonly questionAttachmentTarget: DraftId | null;
73 readonly pendingUserInputs: ReadonlyArray<PendingUserInput>;
74 readonly composerContextRecords: ComposerDraftContextRecords;
75 readonly composerImages: ReadonlyArray<ComposerImageAttachment>;
76 readonly composerFilesRef: ChatComposerProps["composerFilesRef"];
77 readonly pendingImageCompressionsRef: RefObject<Map<string, number>>;
78 readonly pendingThreadImportsRef: RefObject<Map<string, number>>;
79 readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[];
80}) {
81 const {
82 environmentId,
83 activeThread,
84 activeThreadId,
85 composerDraftTarget,
86 attachmentDraftTarget,
87 attachmentTargetKey,
88 attachmentTargetKeyRef,
89 questionAttachmentTarget,
90 pendingUserInputs,
91 composerContextRecords,
92 composerImages,
93 composerFilesRef,
94 pendingImageCompressionsRef,
95 pendingThreadImportsRef,
96 addComposerFilesToDraft,
97 } = input;
98 const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
99 const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
100 const addComposerDraftTerminalContexts = useComposerDraftStore(
101 (store) => store.addTerminalContexts,
102 );
103 const addComposerDraftReviewComment = useComposerDraftStore((store) => store.addReviewComment);
104 const addComposerDraftPreviewAnnotation = useComposerDraftStore(
105 (store) => store.addPreviewAnnotation,
106 );
107 const addComposerDraftThreadContexts = useComposerDraftStore((store) => store.addThreadContexts);
108 const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false });
109 const loadThreadTranscript = useAtomCommand(orchestrationEnvironment.threadTranscript, {
110 reportFailure: false,
111 });
112 const countReservedAttachments = () => {
113 const questionRequest = pendingUserInputs[0];
114 const otherQuestionKeys =
115 questionAttachmentTarget && questionRequest && activeThreadId
116 ? questionRequest.questions
117 .map((question) =>
118 questionAttachmentDraftId(
119 environmentId,
120 activeThreadId,
121 questionRequest.requestId,
122 question.id,
123 ),
124 )
125 .filter((key) => key !== questionAttachmentTarget)
126 : [];
127 const draft = getComposerDraft(attachmentDraftTarget);
128 return (
129 (draft?.images.length ?? 0) +
130 (draft?.files.length ?? 0) +
131 (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) +
132 (pendingThreadImportsRef.current.get(attachmentTargetKey) ?? 0) +
133 countQuestionAttachments(otherQuestionKeys)
134 );
135 };
136 const countReservedAttachmentsStable = useStableCallback(countReservedAttachments);
137 const runAttachmentImport = async (
138 record: Extract<ComposerContextRecord, { kind: "image" | "file" }>,
139 localId: string,
140 sourceEnvironmentId: EnvironmentId,
141 importTargetKey: string,
142 ) => {
143 const fail = (reason: string) => {
144 toastManager.add({
145 type: "error",
146 title: `Couldn't bring ${record.name} into this message`,
147 description: `${reason} Remove the chip or attach the file again.`,
148 });
149 };
150 let file = copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId);
151 if (!file) {
152 const sourceConnection = readPreparedConnection(sourceEnvironmentId);
153 if (!sourceConnection) {
154 fail("The environment it came from is not connected.");
155 return;
156 }
157 const result = await createAssetUrl({
158 environmentId: sourceEnvironmentId,
159 input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } },
160 });
161 const url =
162 result._tag === "Success"
163 ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl)
164 : null;
165 if (!url) {
166 fail("The original attachment is no longer available.");
167 return;
168 }
169 const blob = await downloadAttachmentBlob(url);
170 if (!blob) {
171 fail("Downloading it from the source failed.");
172 return;
173 }
174 file = new File([blob], record.name, { type: record.mimeType || blob.type });
175 }
176 // The draft these bytes belong to may have been sent or switched away from while they
177 // downloaded. Dropping them here keeps them out of whatever draft is open now.
178 if (attachmentTargetKeyRef.current !== importTargetKey) return;
179 const replacesFileMarker =
180 record.kind === "file" &&
181 composerFilesRef.current.some(
182 (candidate) =>
183 composerFileNeedsReattach(candidate) &&
184 composerFileMatchesReattachMarker(candidate, {
185 name: record.name,
186 mimeType: file.type,
187 sizeBytes: file.size,
188 }),
189 );
190 if (
191 !replacesFileMarker &&
192 (pendingThreadImportsRef.current.get(importTargetKey) ?? 0) > 0 &&
193 countReservedAttachments() >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS
194 ) {
195 fail("The attachment limit has been reached.");
196 return;
197 }
198 if (record.kind === "image") {
199 const accepted = addComposerDraftImages(
200 attachmentDraftTarget,
201 [
202 {
203 type: "image",
204 id: localId,
205 name: record.name,
206 mimeType: file.type,
207 sizeBytes: file.size,
208 previewUrl: URL.createObjectURL(file),
209 file,
210 },
211 ],
212 {
213 allowDuplicates:
214 getComposerDraft(composerDraftTarget)?.previewAnnotations.some(
215 (annotation) => annotation.id === localId,
216 ) ?? false,
217 },
218 );
219 if (!accepted.includes(localId))
220 fail("The draft rejected this attachment (duplicate or attachment limit reached).");
221 } else {
222 const accepted = addComposerFilesToDraft([
223 {
224 type: "file",
225 id: localId,
226 name: record.name,
227 mimeType: file.type,
228 sizeBytes: file.size,
229 file,
230 },
231 ]);
232 if (!accepted.includes(localId))
233 fail("The draft rejected this attachment (duplicate or attachment limit reached).");
234 }
235 };
236 const importAttachmentRecord = async (
237 record: Extract<ComposerContextRecord, { kind: "image" | "file" }>,
238 localId: string,
239 sourceEnvironmentId: EnvironmentId,
240 ) => {
241 // The chip lands in the draft immediately while these bytes are still downloading. Count
242 // the transfer against its own draft so a send cannot snapshot a message whose chip has no
243 // attachment behind it, and so bytes for an abandoned draft never enter the next one.
244 const importTargetKey = attachmentTargetKey;
245 pendingDraftWork.begin(importTargetKey);
246 await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey).finally(() =>
247 pendingDraftWork.end(importTargetKey),
248 );
249 };
250 const importContextRecords = (
251 records: ReadonlyArray<ComposerContextRecord>,
252 sourceEnvironmentId: EnvironmentId | null,
253 threadDraftTarget = attachmentDraftTarget,
254 ): ReadonlyMap<string, string> => {
255 const rewritten = new Map<string, string>();
256 const dependentAttachmentLocalIds = new Map<string, string>();
257 const skippedDependentAttachmentIds = new Set<string>();
258 // Resolve annotations before their dependent screenshot records even if a foreign
259 // clipboard producer emitted the records in a different order.
260 const orderedRecords = records.toSorted((left, right) =>
261 left.kind === "preview-annotation" && right.kind !== "preview-annotation"
262 ? -1
263 : right.kind === "preview-annotation" && left.kind !== "preview-annotation"
264 ? 1
265 : 0,
266 );
267 for (const candidate of orderedRecords) {
268 // Producer ids fold into context ids, so two different excerpts can collide. Only skip
269 // when the draft already holds the same payload; a colliding but different record is
270 // re-minted under a fresh id so both survive the paste.
271 const record = asKnownContextRecord(candidate);
272 if (!record) continue;
273 // A reminted annotation needs its screenshot under the new annotation id.
274 const existing = dependentAttachmentLocalIds.has(record.contextId)
275 ? undefined
276 : composerContextImportLookupIds(record).flatMap((contextId) => {
277 const found = composerContextRecords.get(contextId);
278 return found ? [found] : [];
279 })[0];
280 // Upload completion can change the server id since copy; the local bytes still match.
281 if (
282 sourceEnvironmentId !== null &&
283 (record.kind === "image" || record.kind === "file") &&
284 (existing?.kind === "image" || existing?.kind === "file") &&
285 existing.record.file !== null &&
286 existing.record.file ===
287 copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId)
288 )
289 continue;
290 const existingRecord =
291 existing?.kind === "terminal"
292 ? terminalContextRecord(existing.record)
293 : existing?.kind === "review-comment"
294 ? reviewCommentContextRecord(existing.record)
295 : existing?.kind === "preview-annotation"
296 ? previewAnnotationContextRecord(existing.record, {
297 screenshotContextId: composerImages.some(
298 (image) => image.id === existing.record.id,
299 )
300 ? existing.record.id
301 : undefined,
302 })
303 : existing?.kind === "thread"
304 ? existing.record
305 : existing
306 ? (uploadedContextRecordFromDraft(existing) ?? undefined)
307 : undefined;
308 if (
309 existingRecord &&
310 isSameComposerContextPayload(existingRecord, record) &&
311 (record.kind !== "thread" || threadDraftTarget === attachmentDraftTarget)
312 ) {
313 if (record.kind === "preview-annotation" && record.screenshotContextId) {
314 skippedDependentAttachmentIds.add(record.screenshotContextId);
315 }
316 continue;
317 }
318 const conflicts = existing !== undefined;
319 switch (record.kind) {
320 case "terminal": {
321 const threadId = activeThread?.id ?? activeThreadId;
322 if (!threadId) break;
323 const imported = terminalContextDraftFromRecord(record, threadId);
324 const draft = conflicts ? { ...imported, id: randomUUID() } : imported;
325 addComposerDraftTerminalContexts(composerDraftTarget, [draft], {
326 appendReference: false,
327 });
328 rewritten.set(record.contextId, terminalContextReference(draft).contextId);
329 break;
330 }
331 case "review-comment": {
332 const imported = reviewCommentFromRecord(record);
333 const comment = conflicts ? { ...imported, id: randomUUID() } : imported;
334 addComposerDraftReviewComment(composerDraftTarget, comment, {
335 appendReference: false,
336 });
337 rewritten.set(record.contextId, reviewCommentContextId(comment.id));
338 break;
339 }
340 case "element":
341 case "preview-annotation": {
342 const imported =
343 record.kind === "element"
344 ? elementContextToPreviewAnnotation(record, randomUUID(), new Date().toISOString())
345 : previewAnnotationFromRecord(record);
346 const annotation = conflicts ? { ...imported, id: randomUUID() } : imported;
347 if (record.kind === "preview-annotation" && record.screenshotContextId) {
348 dependentAttachmentLocalIds.set(record.screenshotContextId, annotation.id);
349 }
350 addComposerDraftPreviewAnnotation(composerDraftTarget, annotation, {
351 appendReference: false,
352 });
353 rewritten.set(record.contextId, previewAnnotationContextId(annotation.id));
354 break;
355 }
356 case "thread": {
357 // The agent can only read threads on its own server; a pasted foreign one is dropped.
358 if (record.environmentId !== environmentId) break;
359 addComposerDraftThreadContexts(threadDraftTarget, [record], {
360 appendReference: false,
361 });
362 rewritten.set(record.contextId, record.contextId);
363 break;
364 }
365 case "image":
366 case "file": {
367 if (skippedDependentAttachmentIds.has(record.contextId)) break;
368 if (sourceEnvironmentId === null && !conflicts) {
369 rewritten.set(record.contextId, record.contextId);
370 break;
371 }
372 if (sourceEnvironmentId === null) break;
373 const localId = dependentAttachmentLocalIds.get(record.contextId) ?? randomUUID();
374 rewritten.set(record.contextId, toKindScopedComposerContextId(record.kind, localId));
375 void importAttachmentRecord(record, localId, sourceEnvironmentId);
376 break;
377 }
378 default:
379 break;
380 }
381 }
382 return rewritten;
383 };
384 const importContextFragment = (
385 fragment: ComposerContextClipboardFragment,
386 ): ReadonlyMap<string, string> =>
387 importContextRecords(fragment.records, fragment.source.environmentId);
388 const importContextFragmentStable = useStableCallback(importContextFragment);
389​
390 return {
391 loadThreadTranscript,
392 countReservedAttachments,
393 countReservedAttachmentsStable,
394 importContextRecords,
395 importContextFragment,
396 importContextFragmentStable,
397 };