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