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

composerContextClipboard.ts

220 lines7.6 KB

1import { requireNativeModule } from "expo";
2import {
3 type ComposerContextClipboardFragment,
4 type ComposerContextRecord,
5 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
6 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
7 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
8 COMPOSER_CONTEXT_MAX_RECORDS,
9 type EnvironmentId,
10} from "@t3tools/contracts";
11import {
12 decodeComposerContextClipboardHtml,
13 decodeComposerContextFragment,
14 encodeComposerContextFragment,
15} from "@t3tools/shared/composerContextClipboard";
16import { threadContextsOutsideEnvironment } from "@t3tools/shared/composerContextReferences";
17import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
18import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
19import * as Option from "effect/Option";
20import { appAtomRegistry } from "../state/atom-registry";
21import { assetEnvironment } from "../state/assets";
22import { environmentSession } from "../state/session";
23import { downloadAttachmentForPreview } from "./attachmentDownload";
24import {
25 persistComposerAttachmentFile,
26 removePersistedComposerAttachmentFile,
27 type DraftComposerAttachment,
28} from "./composerImages";
29import { referencedComposerContext, reidentifyComposerContext } from "./composerContext";
30import { uuidv4 } from "./uuid";
31import {
32 findLocalComposerClipboardAttachment,
33 waitForComposerDraftsLoaded,
34} from "../state/use-composer-drafts";
35import { loadLocalAttachmentPreview } from "./localAttachmentPreview";
36​
37export interface NativeContextClipboard {
38 readonly text: string;
39 readonly fragment: string;
40 readonly html: string;
42​
43function checkAborted(signal: AbortSignal): void {
44 if (signal.aborted) throw new Error("Context import cancelled");
46​
47const nativeClipboard = () =>
48 requireNativeModule<{
49 writeContextClipboard: (text: string, fragment: string) => Promise<void>;
50 }>("T3ComposerEditor");
51​
52export function writeComposerContextClipboard(
53 text: string,
54 fragment: ComposerContextClipboardFragment,
55): Promise<void> {
56 const encoded = encodeComposerContextFragment(fragment);
57 if (!encoded)
58 return Promise.reject(
59 new Error("This context selection is too large to copy. Select fewer items."),
60 );
61 return nativeClipboard().writeContextClipboard(text, encoded);
63​
64export async function importComposerContextClipboard(
65 input: NativeContextClipboard,
66 existingCount: number,
67 signal: AbortSignal,
68 existingContextCount = 0,
69 destinationEnvironmentId?: EnvironmentId,
70 /** The machines the destination links to, whose threads its agent can read too. */
71 linkedEnvironments: ReadonlyMap<EnvironmentId, string> = new Map(),
72) {
73 const fragment =
74 decodeComposerContextFragment(input.fragment) ?? decodeComposerContextClipboardHtml(input.html);
75 if (!fragment) return null;
76 const selected = referencedComposerContext(input.text, { version: 1, records: fragment.records });
77 const imported = reidentifyComposerContext(input.text, selected?.records ?? [], uuidv4);
78 const skippedThreads =
79 destinationEnvironmentId === undefined
80 ? []
81 : threadContextsOutsideEnvironment({
82 text: imported.text,
83 records: imported.context.records,
84 environmentId: destinationEnvironmentId,
85 linkedEnvironments,
86 });
87 const skippedIds = new Set(skippedThreads.map((record) => record.contextId));
88 const retained = imported.context.records.filter((record) => !skippedIds.has(record.contextId));
89 if (existingContextCount + retained.length > COMPOSER_CONTEXT_MAX_RECORDS)
90 throw new Error("Remove some context items from the draft before pasting more.");
91 const attachments: DraftComposerAttachment[] = [];
92 const records: ComposerContextRecord[] = [];
93 const failures: string[] = [];
94 try {
95 for (const record of retained) {
96 checkAborted(signal);
97 if (!("attachmentId" in record)) {
98 records.push(record);
99 continue;
100 }
101 try {
102 if (existingCount + attachments.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS)
103 throw new Error("Attachment limit reached");
104 const file = await importAttachment(record, fragment.source.environmentId, signal);
105 attachments.push(file);
106 records.push({ ...record, attachmentId: file.id });
107 } catch (error) {
108 if (signal.aborted) throw error;
109 failures.push(record.name);
110 }
111 }
112 // The last copy can be cancelled after its own check; a cancelled import must not return files nobody will release.
113 checkAborted(signal);
114 return {
115 text: imported.text,
116 context: { version: 1 as const, records },
117 attachments,
118 failures,
119 skippedThreads: skippedThreads.map((record) => record.title),
120 };
121 } catch (error) {
122 await Promise.all(
123 attachments.map((attachment) =>
124 attachment.fileUri
125 ? removePersistedComposerAttachmentFile(attachment.fileUri)
126 : Promise.resolve(),
127 ),
128 );
129 throw error;
130 }
132​
133async function importAttachment(
134 record: Extract<ComposerContextRecord, { attachmentId: string }>,
135 environmentId: EnvironmentId,
136 signal: AbortSignal,
137): Promise<DraftComposerAttachment> {
138 await waitForComposerDraftsLoaded();
139 checkAborted(signal);
140 const local = findLocalComposerClipboardAttachment(environmentId, record.attachmentId);
141 if (local) {
142 if (!local.fileUri && local.type === "image" && local.dataUrl)
143 return {
144 ...local,
145 id: uuidv4(),
146 uploadedAttachmentId: undefined,
147 uploadEnvironmentId: undefined,
148 };
149 if (local.fileUri) {
150 const preview = await loadLocalAttachmentPreview(
151 { ...local, fileUri: local.fileUri },
152 signal,
153 );
154 if (!preview) throw new Error("Context import cancelled");
155 try {
156 return await persistImportedAttachment(record, preview.uri, signal);
157 } finally {
158 preview.dispose();
159 }
160 }
161 }
162 const connection = appAtomRegistry.get(
163 environmentSession.preparedConnectionValueAtom(environmentId),
164 );
165 if (Option.isNone(connection)) throw new Error("Reconnect to the source environment");
166 const result = await executeAtomQuery(
167 appAtomRegistry,
168 assetEnvironment.createUrl({
169 environmentId,
170 input: {
171 resource: { _tag: "attachment", attachmentId: record.attachmentId, fileName: record.name },
172 },
173 }),
174 { refresh: true, reportFailure: false },
175 );
176 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
177 checkAborted(signal);
178 const url = resolveAssetUrl(connection.value.httpBaseUrl, result.value.relativeUrl);
179 if (!url) throw new Error("Attachment URL unavailable");
180 const temporary = await downloadAttachmentForPreview({
181 attachment: { name: record.name, mimeType: record.mimeType },
182 url,
183 signal,
184 });
185 if (!temporary) throw new Error("Attachment import cancelled");
186 try {
187 return await persistImportedAttachment(record, temporary.uri, signal);
188 } finally {
189 temporary.dispose();
190 }
192​
193async function persistImportedAttachment(
194 record: Extract<ComposerContextRecord, { attachmentId: string }>,
195 uri: string,
196 signal: AbortSignal,
197): Promise<DraftComposerAttachment> {
198 const fileUri = await persistComposerAttachmentFile(
199 uri,
200 record.name,
201 record.kind === "image"
202 ? PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
203 : PROVIDER_SEND_TURN_MAX_FILE_BYTES,
204 );
205 if (signal.aborted) {
206 await removePersistedComposerAttachmentFile(fileUri);
207 checkAborted(signal);
208 }
209 const { File } = await import("expo-file-system");
210 const common = {
211 id: uuidv4(),
212 fileUri,
213 name: record.name,
214 mimeType: record.mimeType,
215 sizeBytes: new File(fileUri).size,
216 };
217 return record.kind === "image"
218 ? { ...common, type: "image", previewUri: fileUri }
219 : { ...common, type: "file" };