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