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