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

composerContextClipboard.ts

294 lines10.1 KB

1import { requireNativeModule } from "expo";
2import { msg } from "gt-react-native";
3import { m } from "../i18n/messages";
4import {
5 type ComposerContextClipboardFragment,
6 type ComposerContextRecord,
7 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
8 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
9 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
10 COMPOSER_CONTEXT_MAX_RECORDS,
11 type EnvironmentId,
12} from "@t3tools/contracts";
13import {
14 decodeComposerContextClipboardHtml,
15 decodeComposerContextFragment,
16 encodeComposerContextFragment,
17} from "@t3tools/shared/composerContextClipboard";
18import {
19 threadContextsOutsideEnvironment,
20 threadLinkContextReferences,
21} from "@t3tools/shared/composerContextReferences";
22import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
23import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
24import * as Option from "effect/Option";
25import { appAtomRegistry } from "../state/atom-registry";
26import { assetEnvironment } from "../state/assets";
27import { environmentSession } from "../state/session";
28import { environmentThreadShells } from "../state/threads";
29import { workspaceConnections } from "../state/workspace";
30import { downloadAttachmentForPreview } from "./attachmentDownload";
31import {
32 persistComposerAttachmentFile,
33 removePersistedComposerAttachmentFile,
34 type DraftComposerAttachment,
35} from "./composerImages";
36import { referencedComposerContext, reidentifyComposerContext } from "./composerContext";
37import { uuidv4 } from "./uuid";
38import {
39 findLocalComposerClipboardAttachment,
40 waitForComposerDraftsLoaded,
41} from "../state/use-composer-drafts";
42import { loadLocalAttachmentPreview } from "./localAttachmentPreview";
43​
44export interface NativeContextClipboard {
45 readonly text: string;
46 readonly fragment: string;
47 readonly html: string;
49​
50function checkAborted(signal: AbortSignal): void {
51 if (signal.aborted) throw new Error("Context import cancelled");
53​
54const nativeClipboard = () =>
55 requireNativeModule<{
56 writeContextClipboard: (text: string, fragment: string) => Promise<void>;
57 attachContextClipboard?: (
58 text: string,
59 fragment: string,
60 expectedText?: string,
61 ) => Promise<void>;
62 }>("T3ComposerEditor");
63​
64export function writeComposerContextClipboard(
65 text: string,
66 fragment: ComposerContextClipboardFragment,
67): Promise<void> {
68 const encoded = encodeComposerContextFragment(fragment);
69 if (!encoded)
70 return Promise.reject(
71 new Error(m(msg("This context selection is too large to copy. Select fewer items."))),
72 );
73 return nativeClipboard().writeContextClipboard(text, encoded);
75​
76/** Attaches context metadata to the current clipboard entry while preserving rich representations. */
77export function attachComposerContextClipboard(
78 text: string,
79 fragment: ComposerContextClipboardFragment,
80 expectedText?: string,
81): Promise<void> {
82 const encoded = encodeComposerContextFragment(fragment);
83 if (!encoded)
84 return Promise.reject(
85 new Error(m(msg("This context selection is too large to copy. Select fewer items."))),
86 );
87 const clipboard = nativeClipboard();
88 if (clipboard.attachContextClipboard) {
89 return clipboard.attachContextClipboard(text, encoded, expectedText ?? text);
90 }
91 return clipboard.writeContextClipboard(text, encoded);
93​
94export async function importComposerContextClipboard(
95 input: NativeContextClipboard,
96 existingCount: number,
97 signal: AbortSignal,
98 existingContextCount = 0,
99 destinationEnvironmentId?: EnvironmentId,
100 /** The machines the destination links to, whose threads its agent can read too. */
101 linkedEnvironments: ReadonlyMap<EnvironmentId, string> = new Map(),
102 /** Server attachments the destination already sends, such as a queued edit's own files. */
103 sentAttachmentIds: ReadonlySet<string> = new Set(),
104) {
105 const copied =
106 decodeComposerContextFragment(input.fragment) ?? decodeComposerContextClipboardHtml(input.html);
107 // A thread link becomes a chip only where this agent can read its machine; others stay links.
108 const threads = threadLinkContextReferences(
109 input.text,
110 copied?.records ?? [],
111 (ref) => appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref))?.title,
112 (record) =>
113 destinationEnvironmentId === undefined ||
114 record.environmentId === destinationEnvironmentId ||
115 linkedEnvironments.has(record.environmentId)
116 ? record.contextId
117 : undefined,
118 );
119 const source =
120 copied?.source ??
121 (threads.records[0] ? { environmentId: threads.records[0].environmentId } : null);
122 if (!source) return null;
123 const fragment = {
124 source,
125 records: [
126 ...(copied?.records ?? []).filter((record) =>
127 threads.records.every((thread) => thread.contextId !== record.contextId),
128 ),
129 ...threads.records,
130 ],
131 };
132 const selected = referencedComposerContext(threads.text, {
133 version: 1,
134 records: fragment.records,
135 });
136 const imported = reidentifyComposerContext(threads.text, selected?.records ?? [], uuidv4);
137 const skippedThreads =
138 destinationEnvironmentId === undefined
139 ? []
140 : threadContextsOutsideEnvironment({
141 text: imported.text,
142 records: imported.context.records,
143 environmentId: destinationEnvironmentId,
144 linkedEnvironments,
145 });
146 const skippedIds = new Set(skippedThreads.map((record) => record.contextId));
147 const retained = imported.context.records.filter((record) => !skippedIds.has(record.contextId));
148 if (existingContextCount + retained.length > COMPOSER_CONTEXT_MAX_RECORDS)
149 throw new Error(m(msg("Remove some context items from the draft before pasting more.")));
150 const attachments: DraftComposerAttachment[] = [];
151 const records: ComposerContextRecord[] = [];
152 const failures: string[] = [];
153 try {
154 for (const record of retained) {
155 checkAborted(signal);
156 if (
157 !("attachmentId" in record) ||
158 (fragment.source.environmentId === destinationEnvironmentId &&
159 sentAttachmentIds.has(record.attachmentId))
160 ) {
161 records.push(record);
162 continue;
163 }
164 try {
165 if (existingCount + attachments.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS)
166 throw new Error(m(msg("Attachment limit reached")));
167 const file = await importAttachment(record, fragment.source.environmentId, signal);
168 attachments.push(file);
169 records.push({ ...record, attachmentId: file.id });
170 } catch (error) {
171 if (signal.aborted) throw error;
172 failures.push(record.name);
173 }
174 }
175 // The last copy can be cancelled after its own check; a cancelled import must not return files nobody will release.
176 checkAborted(signal);
177 return {
178 text: imported.text,
179 context: { version: 1 as const, records },
180 attachments,
181 failures,
182 skippedThreads: skippedThreads.map((record) => record.title),
183 };
184 } catch (error) {
185 await Promise.all(
186 attachments.map((attachment) =>
187 attachment.fileUri
188 ? removePersistedComposerAttachmentFile(attachment.fileUri)
189 : Promise.resolve(),
190 ),
191 );
192 throw error;
193 }
195​
196async function importAttachment(
197 record: Extract<ComposerContextRecord, { attachmentId: string }>,
198 environmentId: EnvironmentId,
199 signal: AbortSignal,
200): Promise<DraftComposerAttachment> {
201 await waitForComposerDraftsLoaded();
202 checkAborted(signal);
203 const local = findLocalComposerClipboardAttachment(
204 appAtomRegistry
205 .get(workspaceConnections.environmentsAtom)
206 .map((environment) => environment.environmentId),
207 environmentId,
208 record.attachmentId,
209 );
210 if (local) {
211 if (!local.fileUri && local.type === "image" && local.dataUrl)
212 return {
213 ...local,
214 id: uuidv4(),
215 uploadedAttachmentId: undefined,
216 uploadEnvironmentId: undefined,
217 };
218 if (local.fileUri) {
219 const preview = await loadLocalAttachmentPreview(
220 { ...local, fileUri: local.fileUri },
221 signal,
222 );
223 if (!preview) throw new Error("Context import cancelled");
224 try {
225 return await persistImportedAttachment(record, preview.uri, signal);
226 } finally {
227 preview.dispose();
228 }
229 }
230 }
231 const connection = appAtomRegistry.get(
232 environmentSession.preparedConnectionValueAtom(environmentId),
233 );
234 if (Option.isNone(connection)) throw new Error(m(msg("Reconnect to the source environment")));
235 const result = await executeAtomQuery(
236 appAtomRegistry,
237 assetEnvironment.createUrl({
238 environmentId,
239 input: {
240 resource: { _tag: "attachment", attachmentId: record.attachmentId, fileName: record.name },
241 },
242 }),
243 { refresh: true, reportFailure: false },
244 );
245 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
246 checkAborted(signal);
247 const url = resolveAssetUrl(connection.value.httpBaseUrl, result.value.relativeUrl);
248 if (!url) throw new Error(m(msg("Attachment URL unavailable")));
249 const temporary = await downloadAttachmentForPreview({
250 attachment: { name: record.name, mimeType: record.mimeType },
251 url,
252 signal,
253 });
254 if (!temporary) throw new Error("Attachment import cancelled");
255 try {
256 return await persistImportedAttachment(record, temporary.uri, signal);
257 } finally {
258 temporary.dispose();
259 }
261​
262async function persistImportedAttachment(
263 record: Extract<ComposerContextRecord, { attachmentId: string }>,
264 uri: string,
265 signal: AbortSignal,
266): Promise<DraftComposerAttachment> {
267 const fileUri = await persistComposerAttachmentFile(
268 uri,
269 record.name,
270 record.kind === "image"
271 ? PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
272 : PROVIDER_SEND_TURN_MAX_FILE_BYTES,
273 );
274 if (signal.aborted) {
275 await removePersistedComposerAttachmentFile(fileUri);
276 checkAborted(signal);
277 }
278 const { File } = await import("expo-file-system");
279 const common = {
280 id: uuidv4(),
281 fileUri,
282 name: record.name,
283 mimeType: record.mimeType,
284 sizeBytes: new File(fileUri).size,
285 };
286 return record.kind === "image"
287 ? {
288 ...common,
289 type: "image",
290 previewUri: fileUri,
291 ...(record.source ? { source: record.source } : {}),
292 }
293 : { ...common, type: "file" };