@devries-cameron20 / t3code Mirror · read-only / commits / fa3700214e
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 19:30 UTC

refactor(web): composer context imports live in useComposerContextImport (#23048)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 21, 2026 at 13:23 UTC fa3700214ec1701c9b28d1ab5debcc1d66bbb2c9
2 files changed +424 -316
apps/web/src/components/chat/ChatComposer.tsx
+26 -316
@@ -6,10 +6,8 @@ import { isLocalEnvironmentDisabled } from "../../localEnvironment";
6 import { usePrimaryEnvironmentId } from "../../state/environments";
7 import { useRightPanelStore } from "~/rightPanelStore";
8 import { importPastedComposerText, readPastedComposerContext } from "../composerInlineTokenPaste";
9 -import { elementContextToPreviewAnnotation } from "../../lib/elementContext";
9 import {
10 questionAttachmentDraftId,
12 - countQuestionAttachments,
11 trackOpenQuestionAttachmentDraft,
12 useQuestionAttachmentPreparation,
13 changeQuestionAttachmentPreparation,
@@ -179,7 +177,6 @@ import {
177 import {
178 ComposerContextActionsContext,
179 composerContextRecordsFromDraft,
182 - uploadedContextRecordFromDraft,
180 } from "../composerContextPresentation";
181 import { useOpenPrLink } from "~/lib/openPullRequestLink";
182 import {
@@ -192,44 +189,26 @@ import {
189 inlineContextReferenceReplacement,
190 } from "~/lib/composerContextReferences";
191 import {
195 - asKnownContextRecord,
192 attachmentContextRecord,
197 - composerContextImportLookupIds,
198 - isSameComposerContextPayload,
193 uploadedAttachmentContextRecord,
194 fileContextReference,
195 imageContextReference,
196 previewAnnotationContextId,
197 previewAnnotationContextRecord,
204 - previewAnnotationFromRecord,
198 reviewCommentContextId,
199 reviewCommentContextReference,
200 reviewCommentContextRecord,
208 - reviewCommentFromRecord,
209 - terminalContextDraftFromRecord,
201 terminalContextReference,
202 terminalContextRecord,
203 threadContextRecord,
204 threadContextReference,
205 } from "~/lib/composerContextRecords";
215 -import {
216 - copiedComposerAttachmentFile,
217 - rememberCopiedComposerAttachments,
218 -} from "~/lib/copiedComposerAttachments";
206 +import { rememberCopiedComposerAttachments } from "~/lib/copiedComposerAttachments";
207 import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag";
208 import { readThreadShell } from "~/state/entities";
209 import { requestConfirmDialog } from "~/confirmDialog";
210 import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
223 -import type {
224 - ComposerContextClipboardFragment,
225 - ComposerContextRecord,
226 - ThreadPullRequestLink,
227 -} from "@t3tools/contracts";
228 -import { resolveAssetUrl } from "~/assets/assetUrls";
229 -import { assetEnvironment } from "~/state/assets";
230 -import { readPreparedConnection } from "~/state/session";
231 -import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
232 -import { orchestrationEnvironment } from "~/state/orchestration";
211 +import type { ComposerContextRecord, ThreadPullRequestLink } from "@t3tools/contracts";
212 import { threadContextAttachment } from "~/lib/threadContextAttachment";
213 import {
214 type ComposerCommandItem,
@@ -337,7 +316,6 @@ import { useMediaQuery } from "../../hooks/useMediaQuery";
316 import { useSoftwareKeyboardOpen } from "../../hooks/useSoftwareKeyboardOpen";
317 import { useStableCallback } from "../../hooks/useStableCallback";
318 import { usePanelAnimationSettings } from "../../panelAnimations";
340 -import { useAtomCommand } from "../../state/use-atom-command";
319 import { readEnvironmentScope } from "../../state/session";
320 import type { ReviewCommentContext } from "../../reviewCommentContext";
321 import { useComposerRestingTransition } from "./useComposerRestingTransition";
@@ -347,6 +325,7 @@ import { useProviderWorkspaceSnapshotRefresh } from "./useProviderWorkspaceSnaps
325 import { useComposerProviderModel } from "./useComposerProviderModel";
326 import { useComposerImageGroups } from "./useComposerImageGroups";
327 import { useComposerStash } from "./useComposerStash";
328 +import { useComposerContextImport } from "./useComposerContextImport";
329
330 /** Reads and disarms a paste-as-text deadline: the shortcut applies to one paste only. */
331 function consumePasteAsTextShortcut(deadline: { current: number }): boolean {
@@ -355,15 +334,6 @@ function consumePasteAsTextShortcut(deadline: { current: number }): boolean {
334 return armed;
335 }
336
358 -async function downloadAttachmentBlob(url: string): Promise<Blob | null> {
359 - try {
360 - const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
361 - return response.ok ? await response.blob() : null;
362 - } catch {
363 - return null;
364 - }
365 -}
366 -
337 const extendReplacementRangeForTrailingSpace = (
338 text: string,
339 rangeEnd: number,
@@ -1462,9 +1432,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1432 removeComposerDraftFile(attachmentDraftTarget, fileId);
1433 };
1434
1465 - const addComposerDraftTerminalContexts = useComposerDraftStore(
1466 - (store) => store.addTerminalContexts,
1467 - );
1435 const addComposerDraftReviewComment = useComposerDraftStore((store) => store.addReviewComment);
1436 const addComposerDraftPreviewAnnotation = useComposerDraftStore(
1437 (store) => store.addPreviewAnnotation,
@@ -1524,287 +1491,30 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
1491 return fragment;
1492 };
1493 const buildContextClipboardFragmentStable = useStableCallback(buildContextClipboardFragment);
1527 - const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false });
1528 - const loadThreadTranscript = useAtomCommand(orchestrationEnvironment.threadTranscript, {
1529 - reportFailure: false,
1494 + const {
1495 + loadThreadTranscript,
1496 + countReservedAttachments,
1497 + countReservedAttachmentsStable,
1498 + importContextRecords,
1499 + importContextFragment,
1500 + importContextFragmentStable,
1501 + } = useComposerContextImport({
1502 + environmentId,
1503 + activeThread,
1504 + activeThreadId,
1505 + composerDraftTarget,
1506 + attachmentDraftTarget,
1507 + attachmentTargetKey,
1508 + attachmentTargetKeyRef,
1509 + questionAttachmentTarget,
1510 + pendingUserInputs,
1511 + composerContextRecords,
1512 + composerImages,
1513 + composerFilesRef,
1514 + pendingImageCompressionsRef,
1515 + pendingThreadImportsRef,
1516 + addComposerFilesToDraft,
1517 });
1531 - const countReservedAttachments = () => {
1532 - const questionRequest = pendingUserInputs[0];
1533 - const otherQuestionKeys =
1534 - questionAttachmentTarget && questionRequest && activeThreadId
1535 - ? questionRequest.questions
1536 - .map((question) =>
1537 - questionAttachmentDraftId(
1538 - environmentId,
1539 - activeThreadId,
1540 - questionRequest.requestId,
1541 - question.id,
1542 - ),
1543 - )
1544 - .filter((key) => key !== questionAttachmentTarget)
1545 - : [];
1546 - const draft = getComposerDraft(attachmentDraftTarget);
1547 - return (
1548 - (draft?.images.length ?? 0) +
1549 - (draft?.files.length ?? 0) +
1550 - (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) +
1551 - (pendingThreadImportsRef.current.get(attachmentTargetKey) ?? 0) +
1552 - countQuestionAttachments(otherQuestionKeys)
1553 - );
1554 - };
1555 - const countReservedAttachmentsStable = useStableCallback(countReservedAttachments);
1556 - const runAttachmentImport = async (
1557 - record: Extract<ComposerContextRecord, { kind: "image" | "file" }>,
1558 - localId: string,
1559 - sourceEnvironmentId: EnvironmentId,
1560 - importTargetKey: string,
1561 - ) => {
1562 - const fail = (reason: string) => {
1563 - toastManager.add({
1564 - type: "error",
1565 - title: `Couldn't bring ${record.name} into this message`,
1566 - description: `${reason} Remove the chip or attach the file again.`,
1567 - });
1568 - };
1569 - let file = copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId);
1570 - if (!file) {
1571 - const sourceConnection = readPreparedConnection(sourceEnvironmentId);
1572 - if (!sourceConnection) {
1573 - fail("The environment it came from is not connected.");
1574 - return;
1575 - }
1576 - const result = await createAssetUrl({
1577 - environmentId: sourceEnvironmentId,
1578 - input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } },
1579 - });
1580 - const url =
1581 - result._tag === "Success"
1582 - ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl)
1583 - : null;
1584 - if (!url) {
1585 - fail("The original attachment is no longer available.");
1586 - return;
1587 - }
1588 - const blob = await downloadAttachmentBlob(url);
1589 - if (!blob) {
1590 - fail("Downloading it from the source failed.");
1591 - return;
1592 - }
1593 - file = new File([blob], record.name, { type: record.mimeType || blob.type });
1594 - }
1595 - // The draft these bytes belong to may have been sent or switched away from while they
1596 - // downloaded. Dropping them here keeps them out of whatever draft is open now.
1597 - if (attachmentTargetKeyRef.current !== importTargetKey) return;
1598 - const replacesFileMarker =
1599 - record.kind === "file" &&
1600 - composerFilesRef.current.some(
1601 - (candidate) =>
1602 - composerFileNeedsReattach(candidate) &&
1603 - composerFileMatchesReattachMarker(candidate, {
1604 - name: record.name,
1605 - mimeType: file.type,
1606 - sizeBytes: file.size,
1607 - }),
1608 - );
1609 - if (
1610 - !replacesFileMarker &&
1611 - (pendingThreadImportsRef.current.get(importTargetKey) ?? 0) > 0 &&
1612 - countReservedAttachments() >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS
1613 - ) {
1614 - fail("The attachment limit has been reached.");
1615 - return;
1616 - }
1617 - if (record.kind === "image") {
1618 - const accepted = addComposerDraftImages(
1619 - attachmentDraftTarget,
1620 - [
1621 - {
1622 - type: "image",
1623 - id: localId,
1624 - name: record.name,
1625 - mimeType: file.type,
1626 - sizeBytes: file.size,
1627 - previewUrl: URL.createObjectURL(file),
1628 - file,
1629 - },
1630 - ],
1631 - {
1632 - allowDuplicates:
1633 - getComposerDraft(composerDraftTarget)?.previewAnnotations.some(
1634 - (annotation) => annotation.id === localId,
1635 - ) ?? false,
1636 - },
1637 - );
1638 - if (!accepted.includes(localId))
1639 - fail("The draft rejected this attachment (duplicate or attachment limit reached).");
1640 - } else {
1641 - const accepted = addComposerFilesToDraft([
1642 - {
1643 - type: "file",
1644 - id: localId,
1645 - name: record.name,
1646 - mimeType: file.type,
1647 - sizeBytes: file.size,
1648 - file,
1649 - },
1650 - ]);
1651 - if (!accepted.includes(localId))
1652 - fail("The draft rejected this attachment (duplicate or attachment limit reached).");
1653 - }
1654 - };
1655 - const importAttachmentRecord = async (
1656 - record: Extract<ComposerContextRecord, { kind: "image" | "file" }>,
1657 - localId: string,
1658 - sourceEnvironmentId: EnvironmentId,
1659 - ) => {
1660 - // The chip lands in the draft immediately while these bytes are still downloading. Count
1661 - // the transfer against its own draft so a send cannot snapshot a message whose chip has no
1662 - // attachment behind it, and so bytes for an abandoned draft never enter the next one.
1663 - const importTargetKey = attachmentTargetKey;
1664 - pendingDraftWork.begin(importTargetKey);
1665 - await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey).finally(() =>
1666 - pendingDraftWork.end(importTargetKey),
1667 - );
1668 - };
1669 - const importContextRecords = (
1670 - records: ReadonlyArray<ComposerContextRecord>,
1671 - sourceEnvironmentId: EnvironmentId | null,
1672 - threadDraftTarget = attachmentDraftTarget,
1673 - ): ReadonlyMap<string, string> => {
1674 - const rewritten = new Map<string, string>();
1675 - const dependentAttachmentLocalIds = new Map<string, string>();
1676 - const skippedDependentAttachmentIds = new Set<string>();
1677 - // Resolve annotations before their dependent screenshot records even if a foreign
1678 - // clipboard producer emitted the records in a different order.
1679 - const orderedRecords = records.toSorted((left, right) =>
1680 - left.kind === "preview-annotation" && right.kind !== "preview-annotation"
1681 - ? -1
1682 - : right.kind === "preview-annotation" && left.kind !== "preview-annotation"
1683 - ? 1
1684 - : 0,
1685 - );
1686 - for (const candidate of orderedRecords) {
1687 - // Producer ids fold into context ids, so two different excerpts can collide. Only skip
1688 - // when the draft already holds the same payload; a colliding but different record is
1689 - // re-minted under a fresh id so both survive the paste.
1690 - const record = asKnownContextRecord(candidate);
1691 - if (!record) continue;
1692 - // A reminted annotation needs its screenshot under the new annotation id.
1693 - const existing = dependentAttachmentLocalIds.has(record.contextId)
1694 - ? undefined
1695 - : composerContextImportLookupIds(record).flatMap((contextId) => {
1696 - const found = composerContextRecords.get(contextId);
1697 - return found ? [found] : [];
1698 - })[0];
1699 - // Upload completion can change the server id since copy; the local bytes still match.
1700 - if (
1701 - sourceEnvironmentId !== null &&
1702 - (record.kind === "image" || record.kind === "file") &&
1703 - (existing?.kind === "image" || existing?.kind === "file") &&
1704 - existing.record.file !== null &&
1705 - existing.record.file ===
1706 - copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId)
1707 - )
1708 - continue;
1709 - const existingRecord =
1710 - existing?.kind === "terminal"
1711 - ? terminalContextRecord(existing.record)
1712 - : existing?.kind === "review-comment"
1713 - ? reviewCommentContextRecord(existing.record)
1714 - : existing?.kind === "preview-annotation"
1715 - ? previewAnnotationContextRecord(existing.record, {
1716 - screenshotContextId: composerImages.some(
1717 - (image) => image.id === existing.record.id,
1718 - )
1719 - ? existing.record.id
1720 - : undefined,
1721 - })
1722 - : existing?.kind === "thread"
1723 - ? existing.record
1724 - : existing
1725 - ? (uploadedContextRecordFromDraft(existing) ?? undefined)
1726 - : undefined;
1727 - if (
1728 - existingRecord &&
1729 - isSameComposerContextPayload(existingRecord, record) &&
1730 - (record.kind !== "thread" || threadDraftTarget === attachmentDraftTarget)
1731 - ) {
1732 - if (record.kind === "preview-annotation" && record.screenshotContextId) {
1733 - skippedDependentAttachmentIds.add(record.screenshotContextId);
1734 - }
1735 - continue;
1736 - }
1737 - const conflicts = existing !== undefined;
1738 - switch (record.kind) {
1739 - case "terminal": {
1740 - const threadId = activeThread?.id ?? activeThreadId;
1741 - if (!threadId) break;
1742 - const imported = terminalContextDraftFromRecord(record, threadId);
1743 - const draft = conflicts ? { ...imported, id: randomUUID() } : imported;
1744 - addComposerDraftTerminalContexts(composerDraftTarget, [draft], {
1745 - appendReference: false,
1746 - });
1747 - rewritten.set(record.contextId, terminalContextReference(draft).contextId);
1748 - break;
1749 - }
1750 - case "review-comment": {
1751 - const imported = reviewCommentFromRecord(record);
1752 - const comment = conflicts ? { ...imported, id: randomUUID() } : imported;
1753 - addComposerDraftReviewComment(composerDraftTarget, comment, {
1754 - appendReference: false,
1755 - });
1756 - rewritten.set(record.contextId, reviewCommentContextId(comment.id));
1757 - break;
1758 - }
1759 - case "element":
1760 - case "preview-annotation": {
1761 - const imported =
1762 - record.kind === "element"
1763 - ? elementContextToPreviewAnnotation(record, randomUUID(), new Date().toISOString())
1764 - : previewAnnotationFromRecord(record);
1765 - const annotation = conflicts ? { ...imported, id: randomUUID() } : imported;
1766 - if (record.kind === "preview-annotation" && record.screenshotContextId) {
1767 - dependentAttachmentLocalIds.set(record.screenshotContextId, annotation.id);
1768 - }
1769 - addComposerDraftPreviewAnnotation(composerDraftTarget, annotation, {
1770 - appendReference: false,
1771 - });
1772 - rewritten.set(record.contextId, previewAnnotationContextId(annotation.id));
1773 - break;
1774 - }
1775 - case "thread": {
1776 - // The agent can only read threads on its own server; a pasted foreign one is dropped.
1777 - if (record.environmentId !== environmentId) break;
1778 - addComposerDraftThreadContexts(threadDraftTarget, [record], {
1779 - appendReference: false,
1780 - });
1781 - rewritten.set(record.contextId, record.contextId);
1782 - break;
1783 - }
1784 - case "image":
1785 - case "file": {
1786 - if (skippedDependentAttachmentIds.has(record.contextId)) break;
1787 - if (sourceEnvironmentId === null && !conflicts) {
1788 - rewritten.set(record.contextId, record.contextId);
1789 - break;
1790 - }
1791 - if (sourceEnvironmentId === null) break;
1792 - const localId = dependentAttachmentLocalIds.get(record.contextId) ?? randomUUID();
1793 - rewritten.set(record.contextId, toKindScopedComposerContextId(record.kind, localId));
1794 - void importAttachmentRecord(record, localId, sourceEnvironmentId);
1795 - break;
1796 - }
1797 - default:
1798 - break;
1799 - }
1800 - }
1801 - return rewritten;
1802 - };
1803 - const importContextFragment = (
1804 - fragment: ComposerContextClipboardFragment,
1805 - ): ReadonlyMap<string, string> =>
1806 - importContextRecords(fragment.records, fragment.source.environmentId);
1807 - const importContextFragmentStable = useStableCallback(importContextFragment);
1518
1519 useEffect(() => {
1520 if (isLiteralPendingAnswer) return;
apps/web/src/components/chat/useComposerContextImport.ts new
+398
@@ -0,0 +1,398 @@
1 +import type { RefObject } from "react";
2 +import type { ChatComposerProps } from "./ChatComposer";
3 +import {
4 + type ComposerContextClipboardFragment,
5 + type ComposerContextRecord,
6 + type EnvironmentId,
7 + PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
8 +} from "@t3tools/contracts";
9 +import {
10 + type ComposerFileAttachment,
11 + type ComposerImageAttachment,
12 + type DraftId,
13 + composerFileMatchesReattachMarker,
14 + composerFileNeedsReattach,
15 + useComposerDraftStore,
16 +} from "../../composerDraftStore";
17 +import { type PendingUserInput } from "../../session-logic";
18 +import {
19 + asKnownContextRecord,
20 + composerContextImportLookupIds,
21 + isSameComposerContextPayload,
22 + previewAnnotationContextId,
23 + previewAnnotationContextRecord,
24 + previewAnnotationFromRecord,
25 + reviewCommentContextId,
26 + reviewCommentContextRecord,
27 + reviewCommentFromRecord,
28 + terminalContextDraftFromRecord,
29 + terminalContextRecord,
30 + terminalContextReference,
31 +} from "~/lib/composerContextRecords";
32 +import { assetEnvironment } from "~/state/assets";
33 +import { copiedComposerAttachmentFile } from "~/lib/copiedComposerAttachments";
34 +import { countQuestionAttachments, questionAttachmentDraftId } from "../../questionAttachments";
35 +import { elementContextToPreviewAnnotation } from "../../lib/elementContext";
36 +import { orchestrationEnvironment } from "~/state/orchestration";
37 +import { pendingDraftWork } from "./pendingDraftWork";
38 +import { randomUUID } from "~/lib/utils";
39 +import { readPreparedConnection } from "~/state/session";
40 +import { resolveAssetUrl } from "~/assets/assetUrls";
41 +import { toKindScopedComposerContextId } from "@t3tools/shared/composerContextReferences";
42 +import { toastManager } from "../ui/toast";
43 +import {
44 + type ComposerDraftContextRecords,
45 + uploadedContextRecordFromDraft,
46 +} from "../composerContextPresentation";
47 +import { useAtomCommand } from "../../state/use-atom-command";
48 +import { useAtomQueryRunner } from "~/state/use-atom-query-runner";
49 +import { useStableCallback } from "../../hooks/useStableCallback";
50 +
51 +async function downloadAttachmentBlob(url: string): Promise<Blob | null> {
52 + try {
53 + const response = await fetch(url, { signal: AbortSignal.timeout(60_000) });
54 + return response.ok ? await response.blob() : null;
55 + } catch {
56 + return null;
57 + }
58 +}
59 +
60 +/**
61 + * Imports copied composer context (terminal output, review comments, annotations, threads,
62 + * images and files) into the open draft, and counts the attachment slots already spoken for.
63 + */
64 +export function useComposerContextImport(input: {
65 + readonly environmentId: EnvironmentId;
66 + readonly activeThread: ChatComposerProps["activeThread"];
67 + readonly activeThreadId: ChatComposerProps["activeThreadId"];
68 + readonly composerDraftTarget: ChatComposerProps["composerDraftTarget"];
69 + readonly attachmentDraftTarget: ChatComposerProps["composerDraftTarget"];
70 + readonly attachmentTargetKey: string;
71 + readonly attachmentTargetKeyRef: RefObject<string>;
72 + readonly questionAttachmentTarget: DraftId | null;
73 + readonly pendingUserInputs: ReadonlyArray<PendingUserInput>;
74 + readonly composerContextRecords: ComposerDraftContextRecords;
75 + readonly composerImages: ReadonlyArray<ComposerImageAttachment>;
76 + readonly composerFilesRef: ChatComposerProps["composerFilesRef"];
77 + readonly pendingImageCompressionsRef: RefObject<Map<string, number>>;
78 + readonly pendingThreadImportsRef: RefObject<Map<string, number>>;
79 + readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[];
80 +}) {
81 + const {
82 + environmentId,
83 + activeThread,
84 + activeThreadId,
85 + composerDraftTarget,
86 + attachmentDraftTarget,
87 + attachmentTargetKey,
88 + attachmentTargetKeyRef,
89 + questionAttachmentTarget,
90 + pendingUserInputs,
91 + composerContextRecords,
92 + composerImages,
93 + composerFilesRef,
94 + pendingImageCompressionsRef,
95 + pendingThreadImportsRef,
96 + addComposerFilesToDraft,
97 + } = input;
98 + const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
99 + const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
100 + const addComposerDraftTerminalContexts = useComposerDraftStore(
101 + (store) => store.addTerminalContexts,
102 + );
103 + const addComposerDraftReviewComment = useComposerDraftStore((store) => store.addReviewComment);
104 + const addComposerDraftPreviewAnnotation = useComposerDraftStore(
105 + (store) => store.addPreviewAnnotation,
106 + );
107 + const addComposerDraftThreadContexts = useComposerDraftStore((store) => store.addThreadContexts);
108 + const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false });
109 + const loadThreadTranscript = useAtomCommand(orchestrationEnvironment.threadTranscript, {
110 + reportFailure: false,
111 + });
112 + const countReservedAttachments = () => {
113 + const questionRequest = pendingUserInputs[0];
114 + const otherQuestionKeys =
115 + questionAttachmentTarget && questionRequest && activeThreadId
116 + ? questionRequest.questions
117 + .map((question) =>
118 + questionAttachmentDraftId(
119 + environmentId,
120 + activeThreadId,
121 + questionRequest.requestId,
122 + question.id,
123 + ),
124 + )
125 + .filter((key) => key !== questionAttachmentTarget)
126 + : [];
127 + const draft = getComposerDraft(attachmentDraftTarget);
128 + return (
129 + (draft?.images.length ?? 0) +
130 + (draft?.files.length ?? 0) +
131 + (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) +
132 + (pendingThreadImportsRef.current.get(attachmentTargetKey) ?? 0) +
133 + countQuestionAttachments(otherQuestionKeys)
134 + );
135 + };
136 + const countReservedAttachmentsStable = useStableCallback(countReservedAttachments);
137 + const runAttachmentImport = async (
138 + record: Extract<ComposerContextRecord, { kind: "image" | "file" }>,
139 + localId: string,
140 + sourceEnvironmentId: EnvironmentId,
141 + importTargetKey: string,
142 + ) => {
143 + const fail = (reason: string) => {
144 + toastManager.add({
145 + type: "error",
146 + title: `Couldn't bring ${record.name} into this message`,
147 + description: `${reason} Remove the chip or attach the file again.`,
148 + });
149 + };
150 + let file = copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId);
151 + if (!file) {
152 + const sourceConnection = readPreparedConnection(sourceEnvironmentId);
153 + if (!sourceConnection) {
154 + fail("The environment it came from is not connected.");
155 + return;
156 + }
157 + const result = await createAssetUrl({
158 + environmentId: sourceEnvironmentId,
159 + input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } },
160 + });
161 + const url =
162 + result._tag === "Success"
163 + ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl)
164 + : null;
165 + if (!url) {
166 + fail("The original attachment is no longer available.");
167 + return;
168 + }
169 + const blob = await downloadAttachmentBlob(url);
170 + if (!blob) {
171 + fail("Downloading it from the source failed.");
172 + return;
173 + }
174 + file = new File([blob], record.name, { type: record.mimeType || blob.type });
175 + }
176 + // The draft these bytes belong to may have been sent or switched away from while they
177 + // downloaded. Dropping them here keeps them out of whatever draft is open now.
178 + if (attachmentTargetKeyRef.current !== importTargetKey) return;
179 + const replacesFileMarker =
180 + record.kind === "file" &&
181 + composerFilesRef.current.some(
182 + (candidate) =>
183 + composerFileNeedsReattach(candidate) &&
184 + composerFileMatchesReattachMarker(candidate, {
185 + name: record.name,
186 + mimeType: file.type,
187 + sizeBytes: file.size,
188 + }),
189 + );
190 + if (
191 + !replacesFileMarker &&
192 + (pendingThreadImportsRef.current.get(importTargetKey) ?? 0) > 0 &&
193 + countReservedAttachments() >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS
194 + ) {
195 + fail("The attachment limit has been reached.");
196 + return;
197 + }
198 + if (record.kind === "image") {
199 + const accepted = addComposerDraftImages(
200 + attachmentDraftTarget,
201 + [
202 + {
203 + type: "image",
204 + id: localId,
205 + name: record.name,
206 + mimeType: file.type,
207 + sizeBytes: file.size,
208 + previewUrl: URL.createObjectURL(file),
209 + file,
210 + },
211 + ],
212 + {
213 + allowDuplicates:
214 + getComposerDraft(composerDraftTarget)?.previewAnnotations.some(
215 + (annotation) => annotation.id === localId,
216 + ) ?? false,
217 + },
218 + );
219 + if (!accepted.includes(localId))
220 + fail("The draft rejected this attachment (duplicate or attachment limit reached).");
221 + } else {
222 + const accepted = addComposerFilesToDraft([
223 + {
224 + type: "file",
225 + id: localId,
226 + name: record.name,
227 + mimeType: file.type,
228 + sizeBytes: file.size,
229 + file,
230 + },
231 + ]);
232 + if (!accepted.includes(localId))
233 + fail("The draft rejected this attachment (duplicate or attachment limit reached).");
234 + }
235 + };
236 + const importAttachmentRecord = async (
237 + record: Extract<ComposerContextRecord, { kind: "image" | "file" }>,
238 + localId: string,
239 + sourceEnvironmentId: EnvironmentId,
240 + ) => {
241 + // The chip lands in the draft immediately while these bytes are still downloading. Count
242 + // the transfer against its own draft so a send cannot snapshot a message whose chip has no
243 + // attachment behind it, and so bytes for an abandoned draft never enter the next one.
244 + const importTargetKey = attachmentTargetKey;
245 + pendingDraftWork.begin(importTargetKey);
246 + await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey).finally(() =>
247 + pendingDraftWork.end(importTargetKey),
248 + );
249 + };
250 + const importContextRecords = (
251 + records: ReadonlyArray<ComposerContextRecord>,
252 + sourceEnvironmentId: EnvironmentId | null,
253 + threadDraftTarget = attachmentDraftTarget,
254 + ): ReadonlyMap<string, string> => {
255 + const rewritten = new Map<string, string>();
256 + const dependentAttachmentLocalIds = new Map<string, string>();
257 + const skippedDependentAttachmentIds = new Set<string>();
258 + // Resolve annotations before their dependent screenshot records even if a foreign
259 + // clipboard producer emitted the records in a different order.
260 + const orderedRecords = records.toSorted((left, right) =>
261 + left.kind === "preview-annotation" && right.kind !== "preview-annotation"
262 + ? -1
263 + : right.kind === "preview-annotation" && left.kind !== "preview-annotation"
264 + ? 1
265 + : 0,
266 + );
267 + for (const candidate of orderedRecords) {
268 + // Producer ids fold into context ids, so two different excerpts can collide. Only skip
269 + // when the draft already holds the same payload; a colliding but different record is
270 + // re-minted under a fresh id so both survive the paste.
271 + const record = asKnownContextRecord(candidate);
272 + if (!record) continue;
273 + // A reminted annotation needs its screenshot under the new annotation id.
274 + const existing = dependentAttachmentLocalIds.has(record.contextId)
275 + ? undefined
276 + : composerContextImportLookupIds(record).flatMap((contextId) => {
277 + const found = composerContextRecords.get(contextId);
278 + return found ? [found] : [];
279 + })[0];
280 + // Upload completion can change the server id since copy; the local bytes still match.
281 + if (
282 + sourceEnvironmentId !== null &&
283 + (record.kind === "image" || record.kind === "file") &&
284 + (existing?.kind === "image" || existing?.kind === "file") &&
285 + existing.record.file !== null &&
286 + existing.record.file ===
287 + copiedComposerAttachmentFile(sourceEnvironmentId, record.attachmentId)
288 + )
289 + continue;
290 + const existingRecord =
291 + existing?.kind === "terminal"
292 + ? terminalContextRecord(existing.record)
293 + : existing?.kind === "review-comment"
294 + ? reviewCommentContextRecord(existing.record)
295 + : existing?.kind === "preview-annotation"
296 + ? previewAnnotationContextRecord(existing.record, {
297 + screenshotContextId: composerImages.some(
298 + (image) => image.id === existing.record.id,
299 + )
300 + ? existing.record.id
301 + : undefined,
302 + })
303 + : existing?.kind === "thread"
304 + ? existing.record
305 + : existing
306 + ? (uploadedContextRecordFromDraft(existing) ?? undefined)
307 + : undefined;
308 + if (
309 + existingRecord &&
310 + isSameComposerContextPayload(existingRecord, record) &&
311 + (record.kind !== "thread" || threadDraftTarget === attachmentDraftTarget)
312 + ) {
313 + if (record.kind === "preview-annotation" && record.screenshotContextId) {
314 + skippedDependentAttachmentIds.add(record.screenshotContextId);
315 + }
316 + continue;
317 + }
318 + const conflicts = existing !== undefined;
319 + switch (record.kind) {
320 + case "terminal": {
321 + const threadId = activeThread?.id ?? activeThreadId;
322 + if (!threadId) break;
323 + const imported = terminalContextDraftFromRecord(record, threadId);
324 + const draft = conflicts ? { ...imported, id: randomUUID() } : imported;
325 + addComposerDraftTerminalContexts(composerDraftTarget, [draft], {
326 + appendReference: false,
327 + });
328 + rewritten.set(record.contextId, terminalContextReference(draft).contextId);
329 + break;
330 + }
331 + case "review-comment": {
332 + const imported = reviewCommentFromRecord(record);
333 + const comment = conflicts ? { ...imported, id: randomUUID() } : imported;
334 + addComposerDraftReviewComment(composerDraftTarget, comment, {
335 + appendReference: false,
336 + });
337 + rewritten.set(record.contextId, reviewCommentContextId(comment.id));
338 + break;
339 + }
340 + case "element":
341 + case "preview-annotation": {
342 + const imported =
343 + record.kind === "element"
344 + ? elementContextToPreviewAnnotation(record, randomUUID(), new Date().toISOString())
345 + : previewAnnotationFromRecord(record);
346 + const annotation = conflicts ? { ...imported, id: randomUUID() } : imported;
347 + if (record.kind === "preview-annotation" && record.screenshotContextId) {
348 + dependentAttachmentLocalIds.set(record.screenshotContextId, annotation.id);
349 + }
350 + addComposerDraftPreviewAnnotation(composerDraftTarget, annotation, {
351 + appendReference: false,
352 + });
353 + rewritten.set(record.contextId, previewAnnotationContextId(annotation.id));
354 + break;
355 + }
356 + case "thread": {
357 + // The agent can only read threads on its own server; a pasted foreign one is dropped.
358 + if (record.environmentId !== environmentId) break;
359 + addComposerDraftThreadContexts(threadDraftTarget, [record], {
360 + appendReference: false,
361 + });
362 + rewritten.set(record.contextId, record.contextId);
363 + break;
364 + }
365 + case "image":
366 + case "file": {
367 + if (skippedDependentAttachmentIds.has(record.contextId)) break;
368 + if (sourceEnvironmentId === null && !conflicts) {
369 + rewritten.set(record.contextId, record.contextId);
370 + break;
371 + }
372 + if (sourceEnvironmentId === null) break;
373 + const localId = dependentAttachmentLocalIds.get(record.contextId) ?? randomUUID();
374 + rewritten.set(record.contextId, toKindScopedComposerContextId(record.kind, localId));
375 + void importAttachmentRecord(record, localId, sourceEnvironmentId);
376 + break;
377 + }
378 + default:
379 + break;
380 + }
381 + }
382 + return rewritten;
383 + };
384 + const importContextFragment = (
385 + fragment: ComposerContextClipboardFragment,
386 + ): ReadonlyMap<string, string> =>
387 + importContextRecords(fragment.records, fragment.source.environmentId);
388 + const importContextFragmentStable = useStableCallback(importContextFragment);
389 +
390 + return {
391 + loadThreadTranscript,
392 + countReservedAttachments,
393 + countReservedAttachmentsStable,
394 + importContextRecords,
395 + importContextFragment,
396 + importContextFragmentStable,
397 + };
398 +}