The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react"; |
| 2 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 3 | import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem"; |
| 4 | import { |
| 5 | assetUrlStateFromResult, |
| 6 | blockedAssetUrlState, |
| 7 | createAssetEnvironmentAtoms, |
| 8 | createProjectFaviconUrlAtomFamily, |
| 9 | EMPTY_ASSET_URL_ATOM, |
| 10 | makeRevisionedAssetUrlFamily, |
| 11 | } from "@t3tools/client-runtime/state/assets"; |
| 12 | import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 13 | import { msg, useMessages } from "gt-react-native"; |
| 14 | import { m } from "../i18n/messages"; |
| 15 | import type { AssetResource, EnvironmentId } from "@t3tools/contracts"; |
| 16 | import * as Clock from "effect/Clock"; |
| 17 | import * as Effect from "effect/Effect"; |
| 18 | import * as Schema from "effect/Schema"; |
| 19 | import { Atom, AsyncResult } from "effect/reactivity"; |
| 20 | |
| 21 | import { environmentCatalog } from "../connection/catalog"; |
| 22 | import { connectionAtomRuntime } from "../connection/runtime"; |
| 23 | import { projectFaviconDatabaseCache } from "../lib/projectFaviconDatabaseCache"; |
| 24 | import { type AssetUrlState, deriveAssetUrlState } from "./asset-url-state"; |
| 25 | import { appAtomRegistry } from "./atom-registry"; |
| 26 | import { environmentProjectCloneListAtom } from "./projectClones"; |
| 27 | import { environmentSession, usePreparedConnection } from "./session"; |
| 28 | import { useEnvironmentPresentation } from "./presentation"; |
| 29 | import { useEnvironmentQuery } from "./query"; |
| 30 | import { useAtomQueryRunner } from "./use-atom-query-runner"; |
| 31 | |
| 32 | export type { AssetUrlFailureReason, AssetUrlState } from "./asset-url-state"; |
| 33 | |
| 34 | export const assetEnvironment = createAssetEnvironmentAtoms(connectionAtomRuntime); |
| 35 | |
| 36 | export const projectFaviconUrlAtom = createProjectFaviconUrlAtomFamily({ |
| 37 | imageCache: projectFaviconDatabaseCache, |
| 38 | createUrl: assetEnvironment.createUrl, |
| 39 | preparedConnection: environmentSession.preparedConnectionValueAtom, |
| 40 | projectClones: environmentProjectCloneListAtom, |
| 41 | }); |
| 42 | |
| 43 | const revisionedAssetUrl = makeRevisionedAssetUrlFamily(assetEnvironment.createUrl); |
| 44 | |
| 45 | /** |
| 46 | * Pass `revision` for a host file whose bytes can change under the same path; each new |
| 47 | * revision re-mints the URL so the image reloads. |
| 48 | */ |
| 49 | export function useAssetUrlState( |
| 50 | environmentId: EnvironmentId | null, |
| 51 | resource: AssetResource | null, |
| 52 | revision?: string | null, |
| 53 | ): AssetUrlState { |
| 54 | const fileAccessSession = useEnvironmentQuery( |
| 55 | environmentId === null ? null : environmentSession.sessionStateAtom(environmentId), |
| 56 | ); |
| 57 | const messages = useMessages(); |
| 58 | const fileEnvironment = useEnvironmentPresentation(environmentId); |
| 59 | const fileAccess = resolveFilesystemReadAccess( |
| 60 | { |
| 61 | isCatalogReady: fileEnvironment.isReady, |
| 62 | connection: fileEnvironment.presentation?.connection ?? null, |
| 63 | session: fileAccessSession.data, |
| 64 | sessionError: fileAccessSession.error, |
| 65 | }, |
| 66 | messages, |
| 67 | ); |
| 68 | const blocked = blockedAssetUrlState(resource, fileAccess); |
| 69 | const preparedConnection = usePreparedConnection(environmentId); |
| 70 | const connectionPhase = fileEnvironment.presentation?.connection.phase ?? "available"; |
| 71 | const result = useAtomValue( |
| 72 | blocked !== null || environmentId === null || resource === null |
| 73 | ? EMPTY_ASSET_URL_ATOM |
| 74 | : revision === undefined |
| 75 | ? assetEnvironment.createUrl({ environmentId, input: { resource } }) |
| 76 | : revisionedAssetUrl({ environmentId, input: { resource }, revision }), |
| 77 | ); |
| 78 | const shared = |
| 79 | blocked ?? |
| 80 | assetUrlStateFromResult( |
| 81 | result, |
| 82 | preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null, |
| 83 | ); |
| 84 | return deriveAssetUrlState({ |
| 85 | connectionPhase, |
| 86 | shared: shared._tag === "Failure" && result.waiting ? { _tag: "Loading" } : shared, |
| 87 | }); |
| 88 | } |
| 89 | |
| 90 | export function useAssetUrl( |
| 91 | environmentId: EnvironmentId | null, |
| 92 | resource: AssetResource | null, |
| 93 | ): string | null { |
| 94 | const state = useAssetUrlState(environmentId, resource); |
| 95 | return state._tag === "Success" ? state.url : null; |
| 96 | } |
| 97 | |
| 98 | /** Explicit playback and sharing must reauthorize files that may have been replaced on disk. */ |
| 99 | export function useRefreshAssetUrl( |
| 100 | environmentId: EnvironmentId | null, |
| 101 | resource: AssetResource | null, |
| 102 | ): () => Promise<string | null> { |
| 103 | const connection = usePreparedConnection(environmentId); |
| 104 | const httpBaseUrl = connection._tag === "Some" ? connection.value.httpBaseUrl : null; |
| 105 | const createUrl = useAtomQueryRunner(assetEnvironment.createUrl, { |
| 106 | refresh: true, |
| 107 | reportFailure: false, |
| 108 | }); |
| 109 | return async () => { |
| 110 | if (environmentId === null || resource === null || httpBaseUrl === null) return null; |
| 111 | const state = assetUrlStateFromResult( |
| 112 | await createUrl({ environmentId, input: { resource } }), |
| 113 | httpBaseUrl, |
| 114 | ); |
| 115 | return state._tag === "Success" ? state.url : null; |
| 116 | }; |
| 117 | } |
| 118 | |
| 119 | /** |
| 120 | * {@link useRefreshAssetUrl} for async tasks that resolve several resources at once. Resolves |
| 121 | * null without a connection and rejects with the server's error when it refuses the URL. |
| 122 | */ |
| 123 | export async function refreshAssetUrl( |
| 124 | environmentId: EnvironmentId, |
| 125 | resource: AssetResource, |
| 126 | signal?: AbortSignal, |
| 127 | ): Promise<string | null> { |
| 128 | const connectionAtom = environmentSession.preparedConnectionValueAtom(environmentId); |
| 129 | if (appAtomRegistry.get(connectionAtom)._tag === "None") return null; |
| 130 | const atom = assetEnvironment.createUrl({ environmentId, input: { resource } }); |
| 131 | const result = await executeAtomQuery(appAtomRegistry, atom, { |
| 132 | label: atom.label?.[0] ?? "asset url", |
| 133 | refresh: true, |
| 134 | reportFailure: false, |
| 135 | ...(signal ? { signal } : {}), |
| 136 | }); |
| 137 | if (result._tag === "Failure") throw squashAtomCommandFailure(result); |
| 138 | // A route can change while the query runs; resolve against the connection now current. |
| 139 | const connection = appAtomRegistry.get(connectionAtom); |
| 140 | if (connection._tag === "None") return null; |
| 141 | const state = assetUrlStateFromResult(result, connection.value.httpBaseUrl); |
| 142 | return state._tag === "Success" ? state.url : null; |
| 143 | } |
| 144 | |
| 145 | export interface AuthorizedAssetUrl { |
| 146 | readonly url: string; |
| 147 | readonly authorizedAt: number; |
| 148 | } |
| 149 | |
| 150 | interface FreshAssetUrlKey { |
| 151 | readonly environmentId: EnvironmentId | null; |
| 152 | readonly resource: AssetResource; |
| 153 | /** A reconnect changes the base URL, and any URL minted against the old one is unusable. */ |
| 154 | readonly httpBaseUrl: string | null; |
| 155 | /** Bumped by Retry so a file replaced on disk is reauthorized. */ |
| 156 | readonly revision: number; |
| 157 | } |
| 158 | |
| 159 | class AssetUrlUnavailableError extends Schema.TaggedError<AssetUrlUnavailableError>()( |
| 160 | "AssetUrlUnavailableError", |
| 161 | { |
| 162 | message: Schema.String, |
| 163 | cause: Schema.optional(Schema.Defect()), |
| 164 | }, |
| 165 | ) {} |
| 166 | |
| 167 | // Plain-object keys compare structurally (Effect `Equal`/`Hash`). |
| 168 | const freshAssetUrlFamily = Atom.family((key: FreshAssetUrlKey) => |
| 169 | Atom.make( |
| 170 | Effect.tryPromise({ |
| 171 | try: async (signal) => |
| 172 | key.environmentId === null |
| 173 | ? null |
| 174 | : await refreshAssetUrl(key.environmentId, key.resource, signal).catch(() => null), |
| 175 | catch: (cause) => |
| 176 | new AssetUrlUnavailableError({ |
| 177 | message: errorDisplayMessage(cause, m) ?? m(msg("The attachment is unavailable.")), |
| 178 | cause, |
| 179 | }), |
| 180 | }).pipe( |
| 181 | Effect.flatMap((url) => |
| 182 | url |
| 183 | ? Effect.map(Clock.currentTimeMillis, (authorizedAt): AuthorizedAssetUrl => ({ |
| 184 | url, |
| 185 | authorizedAt, |
| 186 | })) |
| 187 | : Effect.fail( |
| 188 | new AssetUrlUnavailableError({ |
| 189 | message: m(msg("Reconnect to this environment and try again.")), |
| 190 | }), |
| 191 | ), |
| 192 | ), |
| 193 | ), |
| 194 | ).pipe(Atom.withLabel("fresh-asset-url")), |
| 195 | ); |
| 196 | |
| 197 | const noFreshAssetUrl = Atom.make( |
| 198 | AsyncResult.initial<AuthorizedAssetUrl, AssetUrlUnavailableError>(), |
| 199 | ).pipe(Atom.withLabel("fresh-asset-url:none")); |
| 200 | const noSessionGeneration = Atom.make(0); |
| 201 | |
| 202 | /** |
| 203 | * A signed URL minted when the reader mounts, not a cached one: cached links can |
| 204 | * expire while the client is suspended. |
| 205 | */ |
| 206 | export function useFreshAssetUrl( |
| 207 | environmentId: EnvironmentId | null, |
| 208 | resource: AssetResource | null, |
| 209 | revision: number, |
| 210 | ): AsyncResult.AsyncResult<AuthorizedAssetUrl, Error> { |
| 211 | const connection = usePreparedConnection(environmentId); |
| 212 | const httpBaseUrl = connection._tag === "Some" ? connection.value.httpBaseUrl : null; |
| 213 | const atom = |
| 214 | resource === null |
| 215 | ? noFreshAssetUrl |
| 216 | : freshAssetUrlFamily({ environmentId, resource, httpBaseUrl, revision }); |
| 217 | // Minting fails at once while the environment is unreachable; mint again once a new session is |
| 218 | // up instead of keeping the error until Retry. |
| 219 | const sessionGeneration = |
| 220 | environmentId === null |
| 221 | ? noSessionGeneration |
| 222 | : environmentCatalog.sessionGenerationAtom(environmentId); |
| 223 | // A listener alone does not compute the atom, so nothing would follow the connection. |
| 224 | useAtomMount(sessionGeneration); |
| 225 | useAtomSubscribe(sessionGeneration, () => { |
| 226 | if (AsyncResult.isFailure(appAtomRegistry.get(atom))) appAtomRegistry.refresh(atom); |
| 227 | }); |
| 228 | return useAtomValue(atom); |
| 229 | } |