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