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

main
ts 469 lines 15.7 KB
Raw
1 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
2 import {
3 clampFileAttachmentUploadBytes,
4 fileAttachmentTooLargeMessage,
5 } from "@t3tools/client-runtime/state/attachments";
6 import {
7 isProviderSendTurnSupportedImageMimeType,
8 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
9 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
10 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
11 } from "@t3tools/contracts";
12 import * as Schema from "effect/Schema";
13 import type { ResolvedSharePayload, SharePayload } from "expo-sharing";
14 import { msg } from "gt-react-native";
15
16 import { m } from "../../i18n/messages";
17
18 import { DraftComposerAttachmentSchema } from "../../lib/composer-image-schema";
19 import { fitComposerImage } from "../../lib/composerImageFit";
20 import type { DraftComposerAttachment } from "../../lib/composerImages";
21 import { estimateBase64ByteSize } from "../../lib/base64";
22
23 export interface IncomingShareDraft {
24 readonly schemaVersion: 1;
25 readonly id: string;
26 readonly createdAt: string;
27 readonly destination?: IncomingShareDestination;
28 readonly text: string;
29 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
30 readonly warnings: ReadonlyArray<string>;
31 }
32
33 export interface IncomingShareDestination {
34 readonly environmentId: string;
35 readonly projectId: string;
36 }
37
38 const IncomingShareDestinationSchema = Schema.Struct({
39 environmentId: Schema.String,
40 projectId: Schema.String,
41 });
42
43 export const IncomingShareDraftSchema = Schema.Struct({
44 schemaVersion: Schema.Literal(1),
45 id: Schema.String,
46 createdAt: Schema.String,
47 destination: Schema.optional(IncomingShareDestinationSchema),
48 text: Schema.String,
49 attachments: Schema.Array(DraftComposerAttachmentSchema),
50 warnings: Schema.Array(Schema.String),
51 });
52
53 const decodeIncomingShareDraftSync = Schema.decodeUnknownSync(IncomingShareDraftSchema);
54
55 export function decodeIncomingShareDraft(value: unknown): IncomingShareDraft {
56 return decodeIncomingShareDraftSync(value);
57 }
58
59 /** Strip iOS /private so /var and /private/var paths compare equally. */
60 function normalizedFileUriPath(uri: string): string | null {
61 try {
62 const url = new URL(uri);
63 if (url.protocol !== "file:") {
64 return null;
65 }
66 const path = decodeURIComponent(url.pathname);
67 // URL parsing leaves encoded separators; reject decoded .. segments before lexical containment checks.
68 if (path.split("/").includes("..")) {
69 return null;
70 }
71 return path.startsWith("/private/var/") ? path.slice("/private".length) : path;
72 } catch {
73 return null;
74 }
75 }
76
77 /** Delete only inside app-owned roots; iOS shares may reference the sender's original. */
78 export function isShareFileUriUnderOwnedRoots(
79 uri: string,
80 ownedRootUris: ReadonlyArray<string>,
81 ): boolean {
82 const path = normalizedFileUriPath(uri);
83 if (path === null) {
84 return false;
85 }
86 return ownedRootUris.some((rootUri) => {
87 const rootPath = normalizedFileUriPath(rootUri);
88 if (rootPath === null) {
89 return false;
90 }
91 const root = rootPath.endsWith("/") ? rootPath : `${rootPath}/`;
92 return path.startsWith(root) && path.length > root.length;
93 });
94 }
95
96 export interface IncomingShareFileReader {
97 readonly readBase64: (uri: string) => Promise<string>;
98 readonly removeOwnedFile: (uri: string) => Promise<void> | void;
99 readonly persistFile?: (uri: string, name: string) => Promise<string>;
100 readonly readSize?: (uri: string) => Promise<number | null>;
101 }
102
103 export function selectIncomingShareAttachments(input: {
104 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
105 readonly maxFileAttachmentBytes: number | null;
106 }): {
107 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
108 readonly warnings: ReadonlyArray<string>;
109 } {
110 const attachments: DraftComposerAttachment[] = [];
111 const warnings: string[] = [];
112
113 for (const attachment of input.attachments) {
114 if (attachment.type === "image") {
115 attachments.push(attachment);
116 continue;
117 }
118 if (input.maxFileAttachmentBytes === null) {
119 warnings.push(
120 m(
121 msg("''{name}'' was skipped because this server does not support files.", {
122 name: attachment.name,
123 }),
124 ),
125 );
126 continue;
127 }
128 const maxFileAttachmentBytes = clampFileAttachmentUploadBytes(input.maxFileAttachmentBytes);
129 if (attachment.sizeBytes > maxFileAttachmentBytes) {
130 warnings.push(fileAttachmentTooLargeMessage(attachment.name, maxFileAttachmentBytes, m));
131 continue;
132 }
133 attachments.push(attachment);
134 }
135
136 return { attachments, warnings };
137 }
138
139 export function selectIncomingShareAttachmentsForServer(input: {
140 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
141 readonly serverConfig: {
142 readonly environment: {
143 readonly capabilities: {
144 readonly fileAttachments?: { readonly maxUploadBytes: number };
145 };
146 };
147 } | null;
148 }):
149 | { readonly status: "pending" }
150 | {
151 readonly status: "ready";
152 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
153 readonly warnings: ReadonlyArray<string>;
154 } {
155 const hasFiles = input.attachments.some((attachment) => attachment.type === "file");
156 if (hasFiles && input.serverConfig === null) {
157 return { status: "pending" };
158 }
159 const capabilities = input.serverConfig?.environment.capabilities;
160 const maxFileAttachmentBytes = capabilities?.fileAttachments?.maxUploadBytes ?? null;
161 return {
162 status: "ready",
163 ...selectIncomingShareAttachments({
164 attachments: input.attachments,
165 maxFileAttachmentBytes,
166 }),
167 };
168 }
169
170 function sharedText(payloads: ReadonlyArray<SharePayload>): string {
171 const seen = new Set<string>();
172 const values: string[] = [];
173 for (const payload of payloads) {
174 if (payload.shareType !== "text" && payload.shareType !== "url") {
175 continue;
176 }
177 const value = payload.value.trim();
178 if (!value || seen.has(value)) {
179 continue;
180 }
181 seen.add(value);
182 values.push(value);
183 }
184 return values.join("\n\n");
185 }
186
187 function resolvedImageFor(
188 payload: SharePayload,
189 index: number,
190 resolvedPayloads: ReadonlyArray<ResolvedSharePayload>,
191 consumedIndexes: Set<number>,
192 ): ResolvedSharePayload | undefined {
193 const sameIndex = resolvedPayloads[index];
194 if (
195 !consumedIndexes.has(index) &&
196 sameIndex?.shareType === payload.shareType &&
197 sameIndex.value === payload.value
198 ) {
199 consumedIndexes.add(index);
200 return sameIndex;
201 }
202 const matchingIndex = resolvedPayloads.findIndex(
203 (candidate, candidateIndex) =>
204 !consumedIndexes.has(candidateIndex) &&
205 candidate.shareType === payload.shareType &&
206 candidate.value === payload.value,
207 );
208 if (matchingIndex < 0) {
209 return undefined;
210 }
211 consumedIndexes.add(matchingIndex);
212 return resolvedPayloads[matchingIndex];
213 }
214
215 async function releaseOwnedFiles(
216 fileReader: IncomingShareFileReader,
217 uris: ReadonlyArray<string | undefined>,
218 ): Promise<void> {
219 for (const uri of new Set(uris.filter((candidate): candidate is string => Boolean(candidate)))) {
220 try {
221 await fileReader.removeOwnedFile(uri);
222 } catch {}
223 }
224 }
225
226 function fallbackName(uri: string, index: number, mimeType: string): string {
227 try {
228 const pathName = new URL(uri).pathname.split("/").findLast((segment) => segment.length > 0);
229 if (pathName) {
230 return decodeURIComponent(pathName);
231 }
232 } catch {}
233 const family = mimeType.split("/")[0]?.toLowerCase();
234 const kind = family === "image" || family === "audio" || family === "video" ? family : "file";
235 const extension =
236 mimeType.split("/")[1]?.replace(/[^a-z0-9.+-]/gi, "") || (kind === "image" ? "png" : "bin");
237 return `shared-${kind}-${index + 1}.${extension}`;
238 }
239
240 export async function buildIncomingShareDraft(input: {
241 readonly payloads: ReadonlyArray<SharePayload>;
242 readonly resolvedPayloads: ReadonlyArray<ResolvedSharePayload>;
243 readonly fileReader: IncomingShareFileReader;
244 readonly id: string;
245 readonly createdAt: string;
246 }): Promise<IncomingShareDraft> {
247 const attachments: DraftComposerAttachment[] = [];
248 const warnings: string[] = [];
249 const consumedResolvedPayloadIndexes = new Set<number>();
250 let warnedAttachmentLimit = false;
251
252 for (const [index, payload] of input.payloads.entries()) {
253 if (
254 payload.shareType !== "image" &&
255 payload.shareType !== "file" &&
256 payload.shareType !== "audio" &&
257 payload.shareType !== "video"
258 ) {
259 continue;
260 }
261 const resolved = resolvedImageFor(
262 payload,
263 index,
264 input.resolvedPayloads,
265 consumedResolvedPayloadIndexes,
266 );
267 const uri = resolved?.contentUri ?? payload.value;
268 if (attachments.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
269 if (!warnedAttachmentLimit) {
270 warnings.push(
271 payload.shareType === "image"
272 ? m(
273 msg(
274 "{count, plural, other {Only the first {count} shared images were attached.}}",
275 { count: PROVIDER_SEND_TURN_MAX_ATTACHMENTS },
276 ),
277 )
278 : m(
279 msg("{count, plural, other {Only the first {count} shared files were attached.}}", {
280 count: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
281 }),
282 ),
283 );
284 warnedAttachmentLimit = true;
285 }
286 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
287 continue;
288 }
289
290 const mimeType = (
291 resolved?.contentMimeType ??
292 payload.mimeType ??
293 (payload.shareType === "image" ? "image/png" : "application/octet-stream")
294 ).toLowerCase();
295 if (payload.shareType !== "image") {
296 const sharedFileName =
297 typeof payload.originalName === "string" && payload.originalName.trim().length > 0
298 ? payload.originalName
299 : undefined;
300 const name = resolved?.originalName ?? sharedFileName ?? fallbackName(uri, index, mimeType);
301 if (!uri) {
302 warnings.push(m(msg("One shared file could not be read.")));
303 continue;
304 }
305 let persistedFileUri: string | undefined;
306 let retainedFileUri: string | undefined;
307 try {
308 let sizeBytes = resolved?.contentSize ?? (await input.fileReader.readSize?.(uri)) ?? null;
309 if (
310 (sizeBytes === null || (sizeBytes === 0 && uri.startsWith("content:"))) &&
311 input.fileReader.persistFile
312 ) {
313 persistedFileUri = await input.fileReader.persistFile(uri, name);
314 sizeBytes = (await input.fileReader.readSize?.(persistedFileUri)) ?? null;
315 }
316 if (sizeBytes === null) {
317 warnings.push(m(msg("The size of ''{name}'' could not be determined.", { name })));
318 if (persistedFileUri) {
319 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
320 }
321 continue;
322 }
323 if (sizeBytes <= 0) {
324 warnings.push(m(msg("''{name}'' is empty or could not be read.", { name })));
325 if (persistedFileUri) {
326 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
327 }
328 continue;
329 }
330 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
331 warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_FILE_BYTES, m));
332 if (persistedFileUri) {
333 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
334 }
335 continue;
336 }
337 if (persistedFileUri === undefined && input.fileReader.persistFile) {
338 persistedFileUri = await input.fileReader.persistFile(uri, name);
339 // Android content sources can misreport size; record the stored copy's measured size.
340 const storedSize = (await input.fileReader.readSize?.(persistedFileUri)) ?? null;
341 if (storedSize !== null) {
342 sizeBytes = storedSize;
343 }
344 if (sizeBytes <= 0) {
345 warnings.push(m(msg("''{name}'' is empty or could not be read.", { name })));
346 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
347 continue;
348 }
349 if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) {
350 warnings.push(
351 fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_FILE_BYTES, m),
352 );
353 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
354 continue;
355 }
356 }
357 attachments.push({
358 id: `${input.id}-file-${index}`,
359 type: "file",
360 name,
361 mimeType,
362 sizeBytes,
363 fileUri: persistedFileUri ?? uri,
364 });
365 retainedFileUri = persistedFileUri ?? uri;
366 } catch (error) {
367 warnings.push(
368 error instanceof Error
369 ? (errorDisplayMessage(error, m) ?? error.message)
370 : m(msg("Could not read ''{name}''.", { name })),
371 );
372 if (persistedFileUri !== undefined) {
373 await releaseOwnedFiles(input.fileReader, [persistedFileUri]);
374 }
375 } finally {
376 await releaseOwnedFiles(
377 input.fileReader,
378 [uri, payload.value].filter((candidate) => candidate !== retainedFileUri),
379 );
380 }
381 continue;
382 }
383 if (!uri || !mimeType.startsWith("image/")) {
384 warnings.push(m(msg("One shared item was not a supported image.")));
385 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
386 continue;
387 }
388 if (!isProviderSendTurnSupportedImageMimeType(mimeType)) {
389 warnings.push(
390 m(
391 msg("''{name}'' is not a supported image type.", {
392 name: resolved?.originalName ?? fallbackName(uri, index, mimeType),
393 }),
394 ),
395 );
396 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
397 continue;
398 }
399 if (
400 resolved?.contentSize !== null &&
401 resolved?.contentSize !== undefined &&
402 resolved.contentSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
403 ) {
404 warnings.push(
405 m(
406 msg("''{name}'' exceeds the 10 MB attachment limit.", {
407 name: resolved.originalName ?? fallbackName(uri, index, mimeType),
408 }),
409 ),
410 );
411 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
412 continue;
413 }
414
415 try {
416 const sharedBase64 = await input.fileReader.readBase64(uri);
417 // Use already-read bytes because native image loaders may not read the provider's file.
418 const fitted = await fitComposerImage({
419 uri: `data:${mimeType};base64,${sharedBase64}`,
420 mimeType,
421 base64: sharedBase64,
422 });
423 const base64 = fitted?.base64 ?? sharedBase64;
424 const sizeBytes = fitted
425 ? estimateBase64ByteSize(base64)
426 : (resolved?.contentSize ?? estimateBase64ByteSize(base64));
427 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
428 warnings.push(
429 m(
430 msg("''{name}'' exceeds the 10 MB attachment limit.", {
431 name: resolved?.originalName ?? fallbackName(uri, index, mimeType),
432 }),
433 ),
434 );
435 continue;
436 }
437 const dataUrl = `data:${mimeType};base64,${base64}`;
438 attachments.push({
439 id: `${input.id}-image-${index}`,
440 type: "image",
441 name: resolved?.originalName ?? fallbackName(uri, index, mimeType),
442 mimeType,
443 sizeBytes,
444 dataUrl,
445 // Data-backed previews outlive temporary share files and App Group entries.
446 previewUri: dataUrl,
447 });
448 } catch {
449 warnings.push(
450 m(msg("Could not read ''{name}''.", { name: fallbackName(uri, index, mimeType) })),
451 );
452 } finally {
453 await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
454 }
455 }
456
457 return {
458 schemaVersion: 1,
459 id: input.id,
460 createdAt: input.createdAt,
461 text: sharedText(input.payloads),
462 attachments,
463 warnings,
464 };
465 }
466
467 export function hasIncomingShareContent(draft: IncomingShareDraft): boolean {
468 return draft.text.trim().length > 0 || draft.attachments.length > 0;
469 }