The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; |
| 2 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 3 | import { Atom, AsyncResult } from "effect/reactivity"; |
| 4 | import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 5 | import * as Dialog from "../components/ui/Dialog"; |
| 6 | import { msg, useMessages } from "gt-react-native"; |
| 7 | import { m } from "../i18n/messages"; |
| 8 | import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview"; |
| 9 | import type { AssetResource, EnvironmentId } from "@t3tools/contracts"; |
| 10 | import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview"; |
| 11 | import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview"; |
| 12 | import { fetch } from "expo/fetch"; |
| 13 | import { File } from "expo-file-system"; |
| 14 | import * as Effect from "effect/Effect"; |
| 15 | import * as Option from "effect/Option"; |
| 16 | import * as Schema from "effect/Schema"; |
| 17 | import { useEffect, useRef, useState } from "react"; |
| 18 | |
| 19 | import type { FileBackedComposerAttachment } from "./composerImages"; |
| 20 | import { localAttachmentPreviewAtom, localAttachmentPreviewState } from "./localAttachmentPreview"; |
| 21 | import { downloadAndShareAttachment, shareLocalAttachment } from "./attachmentDownload"; |
| 22 | import { refreshAssetUrl, useFreshAssetUrl, useRefreshAssetUrl } from "../state/assets"; |
| 23 | import { attachmentDocumentPresentation } from "./attachmentDocumentPresentation"; |
| 24 | |
| 25 | const isLocalUri = (uri: string) => /^(file|content):/.test(uri); |
| 26 | |
| 27 | /** Signed asset URLs live for an hour; treat anything older than this as worth re-minting. */ |
| 28 | const STALE_URL_MS = 5 * 60_000; |
| 29 | |
| 30 | interface AttachmentTextKey { |
| 31 | readonly uri: string; |
| 32 | /** When a remote `uri` was signed; null for local files. */ |
| 33 | readonly authorizedAt: number | null; |
| 34 | readonly environmentId: EnvironmentId | null; |
| 35 | readonly resource: AssetResource; |
| 36 | readonly sizeBytes: number; |
| 37 | readonly revision: number; |
| 38 | } |
| 39 | |
| 40 | async function readAttachmentText(key: AttachmentTextKey, signal: AbortSignal) { |
| 41 | if (isLocalUri(key.uri)) { |
| 42 | return readFilePreviewResponse({ ok: true, body: new File(key.uri).readableStream() }, signal); |
| 43 | } |
| 44 | // Reauthorize before source reads; the opening URL may have expired. |
| 45 | let target = key.uri; |
| 46 | if (key.authorizedAt === null || Date.now() - key.authorizedAt > STALE_URL_MS) { |
| 47 | const refreshed = |
| 48 | key.environmentId === null |
| 49 | ? null |
| 50 | : await refreshAssetUrl(key.environmentId, key.resource, signal).catch(() => null); |
| 51 | if (!refreshed) throw new Error(m(msg("Reconnect to this environment and try again."))); |
| 52 | target = refreshed; |
| 53 | } |
| 54 | const response = await fetch(target, { |
| 55 | signal, |
| 56 | headers: { |
| 57 | ...(key.sizeBytes > 0 ? { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } : {}), |
| 58 | ...(key.revision > 0 ? { "Cache-Control": "no-cache" } : {}), |
| 59 | }, |
| 60 | }); |
| 61 | return readFilePreviewResponse(response, signal); |
| 62 | } |
| 63 | |
| 64 | class AttachmentTextReadError extends Schema.TaggedError<AttachmentTextReadError>()( |
| 65 | "AttachmentTextReadError", |
| 66 | { |
| 67 | message: Schema.String, |
| 68 | cause: Schema.Defect(), |
| 69 | }, |
| 70 | ) {} |
| 71 | |
| 72 | // Plain-object keys compare structurally (Effect `Equal`/`Hash`). Unmounting the |
| 73 | // last reader interrupts the read, which aborts the fetch. |
| 74 | const attachmentTextAtom = Atom.family((key: AttachmentTextKey) => |
| 75 | Atom.make( |
| 76 | Effect.tryPromise({ |
| 77 | try: (signal) => readAttachmentText(key, signal), |
| 78 | catch: (cause) => |
| 79 | new AttachmentTextReadError({ |
| 80 | message: errorDisplayMessage(cause, m) ?? m(msg("Could not read this file.")), |
| 81 | cause, |
| 82 | }), |
| 83 | }), |
| 84 | ).pipe(Atom.withLabel("attachment-text")), |
| 85 | ); |
| 86 | |
| 87 | const noAttachmentText = Atom.make( |
| 88 | AsyncResult.initial<{ text: string; truncated: boolean }, AttachmentTextReadError>(), |
| 89 | ).pipe(Atom.withLabel("attachment-text:none")); |
| 90 | |
| 91 | /** Captured bytes never resolve against the workspace. */ |
| 92 | export function useAttachmentDocument(input: { |
| 93 | readonly name: string; |
| 94 | readonly mimeType: string; |
| 95 | readonly sizeBytes: number; |
| 96 | readonly attachmentId: string; |
| 97 | readonly environmentId: EnvironmentId | null; |
| 98 | readonly attachment: FileBackedComposerAttachment | null; |
| 99 | }) { |
| 100 | const resolve = useMessages(); |
| 101 | const kind = filePreviewKind(input, { richDocuments: false }); |
| 102 | const delimiter = filePreviewDelimiter(input); |
| 103 | const shareController = useRef<AbortController | null>(null); |
| 104 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- aborts the in-flight attachment share download when the component unmounts |
| 105 | useEffect(() => () => shareController.current?.abort(), []); |
| 106 | const resource = { |
| 107 | _tag: "attachment" as const, |
| 108 | attachmentId: input.attachmentId, |
| 109 | fileName: input.name, |
| 110 | mimeType: input.mimeType, |
| 111 | disposition: "inline" as const, |
| 112 | }; |
| 113 | const environmentId = input.attachment ? null : input.environmentId; |
| 114 | const refresh = useRefreshAssetUrl(environmentId, resource); |
| 115 | const [rendered, setRendered] = useState(true); |
| 116 | const [revision, setRevision] = useState(0); |
| 117 | const [sharing, setSharing] = useState(false); |
| 118 | const attachment = input.attachment; |
| 119 | const localPreviewAtom = localAttachmentPreviewAtom(attachment); |
| 120 | const localPreview = localAttachmentPreviewState(useAtomValue(localPreviewAtom)); |
| 121 | const refreshLocalPreview = useAtomRefresh(localPreviewAtom); |
| 122 | const remote = useFreshAssetUrl(environmentId, attachment ? null : resource, revision); |
| 123 | const remoteUrl = AsyncResult.isSuccess(remote) && !remote.waiting ? remote.value : null; |
| 124 | const uri = attachment ? localPreview.uri : (remoteUrl?.url ?? null); |
| 125 | const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered); |
| 126 | const text = useAtomValue( |
| 127 | uri && needsText |
| 128 | ? attachmentTextAtom({ |
| 129 | uri, |
| 130 | authorizedAt: remoteUrl?.authorizedAt ?? null, |
| 131 | environmentId, |
| 132 | resource, |
| 133 | sizeBytes: input.sizeBytes, |
| 134 | revision, |
| 135 | }) |
| 136 | : noAttachmentText, |
| 137 | ); |
| 138 | const content = AsyncResult.isSuccess(text) ? text.value : null; |
| 139 | const contentError = AsyncResult.isFailure(text) |
| 140 | ? (Option.getOrNull(AsyncResult.error(text))?.message ?? |
| 141 | resolve(msg("Could not read this file."))) |
| 142 | : null; |
| 143 | const table = content && delimiter ? parseDelimitedPreview(content.text, delimiter) : null; |
| 144 | const presentation = attachmentDocumentPresentation({ |
| 145 | kind, |
| 146 | hasTable: table !== null, |
| 147 | hasEnvironment: input.environmentId !== null, |
| 148 | rendered, |
| 149 | }); |
| 150 | const error = attachment |
| 151 | ? localPreview.error && |
| 152 | (localPreview.error.message || resolve(msg("The local file is unavailable."))) |
| 153 | : AsyncResult.isFailure(remote) |
| 154 | ? (Option.getOrNull(AsyncResult.error(remote))?.message ?? |
| 155 | resolve(msg("The attachment is unavailable."))) |
| 156 | : null; |
| 157 | const share = async () => { |
| 158 | if (!uri || sharing) return; |
| 159 | setSharing(true); |
| 160 | const controller = new AbortController(); |
| 161 | shareController.current = controller; |
| 162 | const request = { |
| 163 | attachment: { name: input.name, mimeType: input.mimeType }, |
| 164 | signal: controller.signal, |
| 165 | }; |
| 166 | const result = await settlePromise(async () => { |
| 167 | if (isLocalUri(uri)) await shareLocalAttachment({ ...request, uri }); |
| 168 | else await downloadAndShareAttachment({ ...request, url: (await refresh()) ?? uri }); |
| 169 | }); |
| 170 | if (shareController.current === controller) shareController.current = null; |
| 171 | if (controller.signal.aborted) return; |
| 172 | setSharing(false); |
| 173 | if (AsyncResult.isFailure(result)) { |
| 174 | const cause = squashAtomCommandFailure(result); |
| 175 | Dialog.alert( |
| 176 | m(msg("Could not share file")), |
| 177 | errorDisplayMessage(cause, m) ?? m(msg("Please try again.")), |
| 178 | ); |
| 179 | } |
| 180 | }; |
| 181 | return { |
| 182 | kind, |
| 183 | ...presentation, |
| 184 | uri, |
| 185 | /** Native viewers resolve their own fresh URL from this instead of reusing `uri`. */ |
| 186 | resource, |
| 187 | content, |
| 188 | table, |
| 189 | error: error ?? contentError, |
| 190 | needsText, |
| 191 | rendered, |
| 192 | setRendered, |
| 193 | revision, |
| 194 | retry: () => { |
| 195 | setRevision((value) => value + 1); |
| 196 | if (attachment) refreshLocalPreview(); |
| 197 | }, |
| 198 | share, |
| 199 | sharing, |
| 200 | }; |
| 201 | } |