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

useComposerContextImport.ts

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