@devries-cameron20 / t3code Mirror · read-only
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 21, 04:45 UTC

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