Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useComposerContextImport.ts

486 lines19.9 KB

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