Open History to see the last commit
1import type { AssetResource, EnvironmentId, ThreadId } from "@t3tools/contracts";
2import { useAtomValue } from "@effect/atom-react";
3import * as Effect from "effect/Effect";
4import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
5import { AsyncResult, Atom } from "effect/reactivity";
6import { useMemo } from "react";
7
8import { connectionAtomRuntime } from "../../connection/runtime";
9import { useAssetUrlState } from "../../state/assets";
10
11// Whole-file reads past this stay on the 1 MB RPC preview; a phone lays out every source row.
12export const MOBILE_FULL_FILE_MAX_BYTES = 8 * 1024 * 1024;
13
14/**
15 * A refresh can keep the URL, so the key also carries the revision it downloads for. No idle TTL:
16 * the revision cannot see a same-size edit, so a reopened file downloads its text again.
17 */
18const fullFileTextAtom = Atom.family((key: string) => {
19 const [uri] = JSON.parse(key) as [string, string];
20 return connectionAtomRuntime
21 .atom(
22 HttpClient.get(uri).pipe(
23 Effect.flatMap(HttpClientResponse.filterStatusOk),
24 Effect.flatMap((response) => {
25 // The file can grow after the preview read; never buffer past the cap. React Native's
26 // fetch buffers the whole body, so a response without a length is refused, not trusted.
27 const length = Number(response.headers["content-length"] ?? Number.NaN);
28 return Number.isFinite(length) && length <= MOBILE_FULL_FILE_MAX_BYTES
29 ? response.text
30 : Effect.succeed(null);
31 }),
32 Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }),
33 ),
34 )
35 .pipe(Atom.withLabel(`full-file-text:${key}`));
36});
37
38const noFullFileTextAtom = Atom.make(AsyncResult.success(null));
39
40/**
41 * Downloads a thread file's full text past the 1 MB RPC preview; null while loading, after a
42 * failure, or when disabled. A new `revision` downloads it again.
43 */
44export function useFullFileText(input: {
45 readonly environmentId: EnvironmentId | null;
46 readonly threadId: ThreadId | null;
47 readonly absolutePath: string | null;
48 readonly revision: string;
49}): string | null {
50 const { threadId, absolutePath } = input;
51 // Workspace-file URLs serve only previewable types; an attachment download serves any file.
52 const resource = useMemo<AssetResource | null>(
53 () =>
54 threadId === null || absolutePath === null
55 ? null
56 : { _tag: "media-file", threadId, path: absolutePath, disposition: "attachment" },
57 [threadId, absolutePath],
58 );
59 const assetUrl = useAssetUrlState(input.environmentId, resource, input.revision);
60 const uri = resource !== null && assetUrl._tag === "Success" ? assetUrl.url : null;
61 const result = useAtomValue(
62 uri === null ? noFullFileTextAtom : fullFileTextAtom(JSON.stringify([uri, input.revision])),
63 );
64 // The caller keeps showing the 1 MB preview and its partial-file notice.
65 return AsyncResult.isSuccess(result) ? result.value : null;
66}