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

main
ts 231 lines 8.92 KB
Raw
1 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
2 import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3 import * as Dialog from "../components/ui/Dialog";
4 import type { MediaActionsSource } from "../lib/mediaActionsSource";
5 import { useNavigation } from "@react-navigation/native";
6 import { msg, useGT } from "gt-react-native";
7 import { m } from "../i18n/messages";
8 import {
9 formatFilePathForClipboard,
10 type MediaActionId,
11 } from "@t3tools/client-runtime/media-actions";
12 import {
13 AuthFilesystemReadScope,
14 type EnvironmentId,
15 sessionGrantsScope,
16 type SessionGrantInput,
17 } from "@t3tools/contracts";
18 import { normalizeNativeMarkdownUrl } from "../lib/markdownLinks";
19 import { AsyncResult } from "effect/reactivity";
20 import * as Haptics from "expo-haptics";
21 import { useEffect, useRef, useState } from "react";
22
23 import { useRefreshAssetUrl } from "./assets";
24 import { appAtomRegistry } from "./atom-registry";
25 import { useEnvironmentQuery } from "./query";
26 import { environmentSession } from "./session";
27 import {
28 downloadAndShareAttachment,
29 downloadAttachmentForPreview,
30 shareLocalAttachment,
31 } from "../lib/attachmentDownload";
32 import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
33 import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
34 import { canSaveImageToLibrary, saveImageToLibrary } from "../lib/saveImageToLibrary";
35
36 function allowsHostMedia(session: SessionGrantInput | null) {
37 return session === null || sessionGrantsScope(session, AuthFilesystemReadScope);
38 }
39
40 function canReadHostMedia(environmentId: EnvironmentId | null): boolean {
41 if (environmentId === null) return true;
42 const result = appAtomRegistry.get(environmentSession.sessionStateAtom(environmentId));
43 return result._tag !== "Failure" && allowsHostMedia(AsyncResult.getOrElse(result, () => null));
44 }
45
46 export function useMediaActions(source: MediaActionsSource | undefined, onOpenFile?: () => void) {
47 const navigation = useNavigation();
48 const gt = useGT();
49 const hostEnvironmentId =
50 source &&
51 "resource" in source &&
52 (source.resource._tag === "workspace-file" || source.resource._tag === "media-file")
53 ? source.environmentId
54 : null;
55 const fileSession = useEnvironmentQuery(
56 hostEnvironmentId === null ? null : environmentSession.sessionStateAtom(hostEnvironmentId),
57 );
58 const canReadMedia =
59 hostEnvironmentId === null ||
60 (fileSession.error === null && fileSession.data !== null && allowsHostMedia(fileSession.data));
61 const refresh = useRefreshAssetUrl(
62 source && "environmentId" in source ? source.environmentId : null,
63 source && "resource" in source ? source.resource : null,
64 );
65 const controller = useRef<AbortController | null>(null);
66 const [busy, setBusy] = useState<"share" | "save-image" | null>(null);
67 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- aborts the in-flight media task when the component unmounts
68 useEffect(() => () => controller.current?.abort(), []);
69
70 const run = (
71 kind: "share" | "save-image",
72 task: (source: MediaActionsSource, signal: AbortSignal) => Promise<void>,
73 ) => {
74 if (!source || controller.current || !canReadHostMedia(hostEnvironmentId)) return;
75 const request = new AbortController();
76 controller.current = request;
77 setBusy(kind);
78 return task(source, request.signal)
79 .catch((error: unknown) => {
80 if (!request.signal.aborted) {
81 Dialog.alert(
82 kind === "share" ? m(msg("Could not share file")) : m(msg("Could not save image")),
83 errorDisplayMessage(error, m) ?? m(msg("Try again.")),
84 );
85 }
86 })
87 .finally(() => {
88 if (controller.current === request) {
89 controller.current = null;
90 if (!request.signal.aborted) setBusy(null);
91 }
92 });
93 };
94
95 const hostUri = async (source: MediaActionsSource, signal: AbortSignal) => {
96 const uri = "uri" in source ? normalizeNativeMarkdownUrl(source.uri) : await refresh();
97 if (signal.aborted || !canReadHostMedia(hostEnvironmentId)) return null;
98 if (uri === null) {
99 throw new Error(m(msg("The file could not be loaded. Reconnect and try again.")));
100 }
101 return uri;
102 };
103
104 const share = () =>
105 run("share", async (source, signal) => {
106 if ("attachment" in source) {
107 const preview = await loadLocalAttachmentPreview(source.attachment, signal);
108 if (!preview) return;
109 const shared = await settlePromise(() => preview.share(signal, source.sourceIdentifier));
110 preview.dispose();
111 if (AsyncResult.isFailure(shared)) throw squashAtomCommandFailure(shared);
112 return;
113 }
114 const uri = await hostUri(source, signal);
115 if (uri === null) return;
116 const input = {
117 attachment: { name: source.name, mimeType: source.mimeType },
118 signal,
119 sourceIdentifier: source.sourceIdentifier,
120 };
121 if (/^(file|content):/i.test(uri)) await shareLocalAttachment({ ...input, uri });
122 else await downloadAndShareAttachment({ ...input, url: uri });
123 });
124
125 const localImageFile = async (source: MediaActionsSource, signal: AbortSignal) => {
126 if ("attachment" in source) return loadLocalAttachmentPreview(source.attachment, signal);
127 const uri = await hostUri(source, signal);
128 if (uri === null) return null;
129 if (/^(file|content):/i.test(uri)) return { uri, dispose: () => {} };
130 return downloadAttachmentForPreview({
131 url: uri,
132 attachment: { name: source.name, mimeType: source.mimeType },
133 signal,
134 });
135 };
136
137 const saveImage = () =>
138 run("save-image", async (source, signal) => {
139 const file = await localImageFile(source, signal);
140 if (!file) return;
141 const saved = signal.aborted
142 ? null
143 : await settlePromise(() => saveImageToLibrary(file.uri, source.mimeType, source.name));
144 file.dispose();
145 if (saved === null) return;
146 if (AsyncResult.isFailure(saved)) throw squashAtomCommandFailure(saved);
147 void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {});
148 });
149
150 const reference = source?.reference;
151 const relativePath = reference?.kind === "file" ? reference.relativePath : undefined;
152 const threadId = source && "threadId" in source ? source.threadId : undefined;
153 const actions: { id: MediaActionId; title: string; run: () => void; disabled?: boolean }[] =
154 source
155 ? [
156 ...(reference?.kind === "file"
157 ? [
158 {
159 id: "copy-full-path" as const,
160 title: gt("Copy full path"),
161 run: () => copyTextWithHaptic(formatFilePathForClipboard(reference.path)),
162 },
163 ]
164 : []),
165 ...(relativePath && reference?.kind === "file"
166 ? [
167 {
168 id: "copy-relative-path" as const,
169 title: gt("Copy relative path"),
170 run: () =>
171 copyTextWithHaptic(formatFilePathForClipboard(relativePath, reference.path)),
172 },
173 ]
174 : []),
175 ...(reference?.kind === "url"
176 ? [
177 {
178 id: "copy-url" as const,
179 title: gt("Copy URL"),
180 run: () => copyTextWithHaptic(reference.url),
181 },
182 ]
183 : []),
184 ...(relativePath && "environmentId" in source && threadId !== undefined
185 ? [
186 {
187 id: "open-file" as const,
188 title: gt("Open in file viewer"),
189 disabled: !canReadMedia,
190 run: () => {
191 if (!canReadHostMedia(hostEnvironmentId)) return;
192 onOpenFile?.();
193 navigation.navigate("ThreadFile", {
194 environmentId: String(source.environmentId),
195 threadId: String(threadId),
196 path: relativePath.split("/"),
197 });
198 },
199 },
200 ]
201 : []),
202 ...(canSaveImageToLibrary(source.mimeType)
203 ? [
204 {
205 id: "save-image" as const,
206 title: busy === "save-image" ? gt("Saving image…") : gt("Save image"),
207 run: saveImage,
208 disabled: busy !== null || !canReadMedia,
209 },
210 ]
211 : []),
212 {
213 id: "save" as const,
214 title:
215 busy === "share"
216 ? gt("Opening share sheet…")
217 : canSaveImageToLibrary(source.mimeType)
218 ? gt("Share", { $context: "verb, opens the system share sheet" })
219 : gt("Save or share"),
220 run: share,
221 disabled: busy !== null || !canReadMedia,
222 },
223 ]
224 : [];
225 return {
226 title: reference?.kind === "file" ? reference.path : reference?.url,
227 actions,
228 sharing: busy === "share",
229 share,
230 };
231 }