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