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

main
ts 155 lines 5.27 KB
Raw
1 import { useAtomValue } from "@effect/atom-react";
2 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3 import { videoMimeType } from "@t3tools/shared/video";
4 import * as Effect from "effect/Effect";
5 import { msg } from "gt-react-native";
6 import { m } from "../i18n/messages";
7 import * as Equal from "effect/Equal";
8 import * as Hash from "effect/Hash";
9 import * as Option from "effect/Option";
10 import * as Schema from "effect/Schema";
11 import { Atom, AsyncResult } from "effect/reactivity";
12
13 import type { FileBackedComposerAttachment } from "./composerImages";
14 import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
15 import { shareLocalAttachment, type AttachmentPreviewFile } from "./attachmentDownload";
16 import { retainComposerAttachmentFileForPreview } from "./composerAttachmentPreviewRetention";
17
18 export async function loadLocalAttachmentPreview(
19 attachment: FileBackedComposerAttachment,
20 signal: AbortSignal,
21 ): Promise<AttachmentPreviewFile | null> {
22 if (signal.aborted) return null;
23 const release = retainComposerAttachmentFileForPreview(attachment);
24 try {
25 const { File, Paths } = await import("expo-file-system");
26 if (signal.aborted) {
27 release();
28 return null;
29 }
30 const uri =
31 resolveOwnedComposerAttachmentFileUri(attachment.fileUri, Paths.document.uri) ??
32 attachment.fileUri;
33 const file = new File(uri);
34 if (!file.exists) {
35 throw new Error("The local attachment file is missing.");
36 }
37 let disposed = false;
38 return {
39 uri: file.uri,
40 dispose: () => {
41 if (disposed) return;
42 disposed = true;
43 release();
44 },
45 share: async (shareSignal, sourceIdentifier) => {
46 if (disposed || shareSignal.aborted) return;
47 const releaseShare = retainComposerAttachmentFileForPreview(attachment);
48 try {
49 await shareLocalAttachment({
50 uri: file.uri,
51 attachment: {
52 name: attachment.name,
53 mimeType:
54 attachment.type === "file"
55 ? (videoMimeType(attachment) ?? attachment.mimeType)
56 : attachment.mimeType,
57 },
58 signal: shareSignal,
59 sourceIdentifier,
60 });
61 } finally {
62 releaseShare();
63 }
64 },
65 };
66 } catch (cause) {
67 release();
68 if (signal.aborted) return null;
69 throw new Error(m(msg("This attachment is no longer available. Attach the file again.")), {
70 cause,
71 });
72 }
73 }
74
75 /**
76 * Keyed by file identity only: a metadata update on the same draft must not
77 * dispose the lease of a file a viewer is still showing.
78 */
79 class LocalAttachmentPreviewKey implements Equal.Equal {
80 constructor(readonly attachment: FileBackedComposerAttachment) {}
81 [Equal.symbol](that: unknown): boolean {
82 return (
83 that instanceof LocalAttachmentPreviewKey &&
84 that.attachment.id === this.attachment.id &&
85 that.attachment.fileUri === this.attachment.fileUri
86 );
87 }
88 [Hash.symbol](): number {
89 return Hash.string(`${this.attachment.id}\u0000${this.attachment.fileUri}`);
90 }
91 }
92
93 class LocalAttachmentPreviewLoadError extends Schema.TaggedError<LocalAttachmentPreviewLoadError>()(
94 "LocalAttachmentPreviewLoadError",
95 {
96 message: Schema.String,
97 cause: Schema.Defect(),
98 },
99 ) {}
100
101 const localAttachmentPreviewFamily = Atom.family((key: LocalAttachmentPreviewKey) =>
102 Atom.make(
103 // The lease lives as long as the atom: unmounting the last reader (or a
104 // refresh) closes the scope and releases the file.
105 Effect.acquireRelease(
106 Effect.tryPromise({
107 try: (signal) => loadLocalAttachmentPreview(key.attachment, signal),
108 catch: (cause) =>
109 new LocalAttachmentPreviewLoadError({
110 message: errorDisplayMessage(cause, m) ?? m(msg("The local file is unavailable.")),
111 cause,
112 }),
113 }).pipe(
114 Effect.filterOrElse(
115 (file) => file !== null,
116 () => Effect.interrupt,
117 ),
118 ),
119 (file) => Effect.sync(file.dispose),
120 ),
121 ).pipe(Atom.withLabel(`local-attachment-preview:${key.attachment.id}`)),
122 );
123
124 const noLocalAttachmentPreview = Atom.make(
125 AsyncResult.initial<AttachmentPreviewFile, Error>(),
126 ).pipe(Atom.withLabel("local-attachment-preview:none"));
127
128 export function localAttachmentPreviewAtom(
129 attachment: FileBackedComposerAttachment | null,
130 ): Atom.Atom<AsyncResult.AsyncResult<AttachmentPreviewFile, Error>> {
131 return attachment === null
132 ? noLocalAttachmentPreview
133 : localAttachmentPreviewFamily(new LocalAttachmentPreviewKey(attachment));
134 }
135
136 export interface LocalAttachmentPreviewState {
137 readonly uri: string | null;
138 readonly error: Error | null;
139 }
140
141 export function localAttachmentPreviewState(
142 result: AsyncResult.AsyncResult<AttachmentPreviewFile, Error>,
143 ): LocalAttachmentPreviewState {
144 return {
145 // A refresh has already released the previous lease while it reacquires.
146 uri: result._tag === "Success" && !result.waiting ? result.value.uri : null,
147 error: result._tag === "Failure" ? Option.getOrNull(AsyncResult.error(result)) : null,
148 };
149 }
150
151 export function useLocalAttachmentPreview(
152 attachment: FileBackedComposerAttachment | null,
153 ): LocalAttachmentPreviewState {
154 return localAttachmentPreviewState(useAtomValue(localAttachmentPreviewAtom(attachment)));
155 }