The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; |
| 3 | import { msg } from "gt-react"; |
| 4 | import { |
| 5 | type EnvironmentId, |
| 6 | type ProjectListEntriesResult, |
| 7 | ProjectReadFileError, |
| 8 | type ProjectReadFileResult, |
| 9 | T3_PROJECT_FILE_NAME, |
| 10 | } from "@t3tools/contracts"; |
| 11 | import * as Cause from "effect/Cause"; |
| 12 | import * as Option from "effect/Option"; |
| 13 | import * as Schema from "effect/Schema"; |
| 14 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 15 | |
| 16 | import { m, type MessageResolver } from "~/i18n/messages"; |
| 17 | import { appAtomRegistry } from "~/rpc/atomRegistry"; |
| 18 | import { useFilesystemReadAccess } from "~/state/filesystem"; |
| 19 | import { projectEnvironment } from "~/state/projects"; |
| 20 | import { useProjectPathSearch } from "~/state/queries"; |
| 21 | import { revisionedQuery } from "~/state/revisionedQuery"; |
| 22 | |
| 23 | const EMPTY_PROJECT_FILE_PATH = ""; |
| 24 | const EMPTY_PROJECT_ENTRIES_QUERY_ATOM = Atom.make( |
| 25 | AsyncResult.initial<ProjectListEntriesResult, never>(false), |
| 26 | ); |
| 27 | const EMPTY_PROJECT_FILE_QUERY_ATOM = Atom.make( |
| 28 | AsyncResult.initial<ProjectReadFileResult, never>(false), |
| 29 | ).pipe(Atom.withLabel("project-file-query:empty")); |
| 30 | export function optimisticFileAtom( |
| 31 | environmentId: EnvironmentId, |
| 32 | cwd: string, |
| 33 | relativePath: string, |
| 34 | ) { |
| 35 | return projectEnvironment.optimisticFile({ environmentId, cwd, relativePath }); |
| 36 | } |
| 37 | |
| 38 | // Dirty contents must survive a closed preview, including failed or unauthorized saves. |
| 39 | const unsavedFileMounts = new Map<ReturnType<typeof optimisticFileAtom>, () => void>(); |
| 40 | |
| 41 | function releaseUnsavedFile(atom: ReturnType<typeof optimisticFileAtom>): void { |
| 42 | const unmount = unsavedFileMounts.get(atom); |
| 43 | unsavedFileMounts.delete(atom); |
| 44 | unmount?.(); |
| 45 | } |
| 46 | |
| 47 | interface ProjectQueryState<A> { |
| 48 | readonly data: A | null; |
| 49 | readonly error: string | null; |
| 50 | readonly isPending: boolean; |
| 51 | readonly refresh: () => void; |
| 52 | } |
| 53 | |
| 54 | interface ProjectFileQueryState extends ProjectQueryState<ProjectReadFileResult> { |
| 55 | readonly readError: ProjectReadFileError | null; |
| 56 | readonly isNotFile: boolean; |
| 57 | readonly isFile: boolean; |
| 58 | } |
| 59 | |
| 60 | function getProjectEntriesQueryAtom( |
| 61 | environmentId: EnvironmentId, |
| 62 | cwd: string, |
| 63 | directoryPath?: string, |
| 64 | ) { |
| 65 | return projectEnvironment.listEntries({ |
| 66 | environmentId, |
| 67 | input: { cwd, ...(directoryPath !== undefined ? { directoryPath } : {}) }, |
| 68 | }); |
| 69 | } |
| 70 | |
| 71 | export function getProjectFileQueryAtom( |
| 72 | environmentId: EnvironmentId, |
| 73 | cwd: string, |
| 74 | relativePath: string | null, |
| 75 | ) { |
| 76 | return projectEnvironment.readFile({ |
| 77 | environmentId, |
| 78 | input: { |
| 79 | cwd, |
| 80 | relativePath: relativePath ?? EMPTY_PROJECT_FILE_PATH, |
| 81 | ...(relativePath === T3_PROJECT_FILE_NAME ? { allowMissing: true } : {}), |
| 82 | }, |
| 83 | }); |
| 84 | } |
| 85 | |
| 86 | export function setProjectFileQueryData( |
| 87 | environmentId: EnvironmentId, |
| 88 | cwd: string, |
| 89 | relativePath: string, |
| 90 | contents: string, |
| 91 | ): void { |
| 92 | const atom = optimisticFileAtom(environmentId, cwd, relativePath); |
| 93 | if (!unsavedFileMounts.has(atom)) { |
| 94 | unsavedFileMounts.set(atom, appAtomRegistry.mount(atom)); |
| 95 | } |
| 96 | appAtomRegistry.set(atom, { |
| 97 | saved: false, |
| 98 | data: { |
| 99 | relativePath, |
| 100 | contents, |
| 101 | byteLength: new TextEncoder().encode(contents).byteLength, |
| 102 | truncated: false, |
| 103 | }, |
| 104 | }); |
| 105 | } |
| 106 | |
| 107 | export function getOptimisticProjectFileQueryData( |
| 108 | environmentId: EnvironmentId, |
| 109 | cwd: string, |
| 110 | relativePath: string, |
| 111 | ): ProjectReadFileResult | null { |
| 112 | return appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath))?.data ?? null; |
| 113 | } |
| 114 | |
| 115 | export function getProjectFileContents( |
| 116 | environmentId: EnvironmentId, |
| 117 | cwd: string, |
| 118 | relativePath: string, |
| 119 | ): string | undefined { |
| 120 | const optimistic = getOptimisticProjectFileQueryData(environmentId, cwd, relativePath); |
| 121 | if (optimistic) return optimistic.contents; |
| 122 | const result = appAtomRegistry.get(getProjectFileQueryAtom(environmentId, cwd, relativePath)); |
| 123 | const data = Option.getOrUndefined(AsyncResult.value(result)); |
| 124 | return data?.exists === false ? undefined : data?.contents; |
| 125 | } |
| 126 | |
| 127 | export function getUnsavedProjectFileQueryData( |
| 128 | environmentId: EnvironmentId, |
| 129 | cwd: string, |
| 130 | relativePath: string, |
| 131 | ): ProjectReadFileResult | null { |
| 132 | const optimistic = appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath)); |
| 133 | return !optimistic?.saved ? (optimistic?.data ?? null) : null; |
| 134 | } |
| 135 | |
| 136 | export function confirmProjectFileQueryData( |
| 137 | environmentId: EnvironmentId, |
| 138 | cwd: string, |
| 139 | relativePath: string, |
| 140 | contents: string, |
| 141 | ): boolean { |
| 142 | const atom = optimisticFileAtom(environmentId, cwd, relativePath); |
| 143 | const optimisticFile = appAtomRegistry.get(atom); |
| 144 | if (optimisticFile?.data.contents !== contents) return false; |
| 145 | |
| 146 | const queryAtom = getProjectFileQueryAtom(environmentId, cwd, relativePath); |
| 147 | appAtomRegistry.set(atom, { |
| 148 | ...optimisticFile, |
| 149 | saved: true, |
| 150 | confirmingQuery: queryAtom, |
| 151 | }); |
| 152 | releaseUnsavedFile(atom); |
| 153 | appAtomRegistry.refresh(queryAtom); |
| 154 | return true; |
| 155 | } |
| 156 | |
| 157 | export function resolveProjectFileQueryData( |
| 158 | environmentId: EnvironmentId, |
| 159 | cwd: string, |
| 160 | relativePath: string | null, |
| 161 | data: ProjectReadFileResult | null, |
| 162 | ): ProjectReadFileResult | null { |
| 163 | if (relativePath === null) return data; |
| 164 | return appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath))?.data ?? data; |
| 165 | } |
| 166 | |
| 167 | export function clearProjectFileQueryData( |
| 168 | environmentId: EnvironmentId, |
| 169 | cwd: string, |
| 170 | relativePath: string, |
| 171 | ): void { |
| 172 | const atom = optimisticFileAtom(environmentId, cwd, relativePath); |
| 173 | appAtomRegistry.set(atom, null); |
| 174 | releaseUnsavedFile(atom); |
| 175 | } |
| 176 | |
| 177 | function failureCause<A>(result: AsyncResult.AsyncResult<A, unknown>): unknown { |
| 178 | return result._tag === "Failure" ? Cause.squash(result.cause) : null; |
| 179 | } |
| 180 | |
| 181 | function errorMessage(cause: unknown, resolve: MessageResolver): string | null { |
| 182 | if (cause === null) return null; |
| 183 | return thrownErrorMessage(cause, resolve) ?? resolve(msg("Workspace query failed.")); |
| 184 | } |
| 185 | |
| 186 | const isProjectReadFileError = Schema.is(ProjectReadFileError); |
| 187 | |
| 188 | /** `revision` is the workspace mutation id; a new one refetches the listing. */ |
| 189 | export function useProjectEntriesQuery( |
| 190 | environmentId: EnvironmentId, |
| 191 | cwd: string, |
| 192 | directoryPath?: string, |
| 193 | revision?: string | null, |
| 194 | resolve: MessageResolver = m, |
| 195 | ): ProjectQueryState<ProjectListEntriesResult> { |
| 196 | const fileAccess = useFilesystemReadAccess(environmentId, resolve); |
| 197 | const { canReadFiles } = fileAccess; |
| 198 | const atom = canReadFiles |
| 199 | ? getProjectEntriesQueryAtom(environmentId, cwd, directoryPath) |
| 200 | : EMPTY_PROJECT_ENTRIES_QUERY_ATOM; |
| 201 | const result = useAtomValue(revisionedQuery(atom, canReadFiles ? revision : undefined)); |
| 202 | const refreshAtom = useAtomRefresh(atom); |
| 203 | const refresh = () => refreshAtom(); |
| 204 | return { |
| 205 | data: AsyncResult.getOrElse(result, () => null), |
| 206 | error: fileAccess.isPending |
| 207 | ? null |
| 208 | : canReadFiles |
| 209 | ? errorMessage(failureCause(result), resolve) |
| 210 | : (fileAccess.error ?? resolve(msg("This connection cannot read host files."))), |
| 211 | isPending: fileAccess.isPending || result.waiting, |
| 212 | refresh, |
| 213 | }; |
| 214 | } |
| 215 | |
| 216 | /** Empty queries return frecency-ranked files without transferring the full workspace listing. */ |
| 217 | export function useProjectFilePickerQuery( |
| 218 | environmentId: EnvironmentId, |
| 219 | cwd: string, |
| 220 | query: string, |
| 221 | limit: number, |
| 222 | options?: { readonly imageOnly?: boolean }, |
| 223 | resolve: MessageResolver = m, |
| 224 | ) { |
| 225 | const search = useProjectPathSearch( |
| 226 | { |
| 227 | environmentId, |
| 228 | cwd, |
| 229 | query, |
| 230 | kind: "file", |
| 231 | ...(options?.imageOnly ? { imageOnly: true } : {}), |
| 232 | }, |
| 233 | limit, |
| 234 | { allowEmptyQuery: true }, |
| 235 | resolve, |
| 236 | ); |
| 237 | |
| 238 | return { |
| 239 | entries: search.isPending ? [] : search.entries, |
| 240 | error: search.error, |
| 241 | isPending: search.isPending, |
| 242 | matchedQuery: search.searchedQuery, |
| 243 | }; |
| 244 | } |
| 245 | |
| 246 | export function useProjectFileQuery( |
| 247 | environmentId: EnvironmentId, |
| 248 | cwd: string, |
| 249 | relativePath: string | null, |
| 250 | enabled = true, |
| 251 | resolve: MessageResolver = m, |
| 252 | ): ProjectFileQueryState { |
| 253 | // Read media-like paths too; a failed read is how folders with those names are detected. |
| 254 | const fileAccess = useFilesystemReadAccess(environmentId, resolve); |
| 255 | const { canReadFiles } = fileAccess; |
| 256 | const isQueryEnabled = enabled; |
| 257 | const atom = |
| 258 | enabled && canReadFiles |
| 259 | ? getProjectFileQueryAtom(environmentId, cwd, relativePath) |
| 260 | : EMPTY_PROJECT_FILE_QUERY_ATOM; |
| 261 | const result = useAtomValue(atom); |
| 262 | const refreshAtom = useAtomRefresh(atom); |
| 263 | const refresh = () => refreshAtom(); |
| 264 | const readData = AsyncResult.getOrElse(result, () => null); |
| 265 | const isMissing = readData?.exists === false; |
| 266 | const optimisticResult = useAtomValue( |
| 267 | optimisticFileAtom(environmentId, cwd, relativePath ?? EMPTY_PROJECT_FILE_PATH), |
| 268 | ); |
| 269 | const optimisticFile = relativePath === null ? null : optimisticResult; |
| 270 | const cause = failureCause(result); |
| 271 | const readError = isProjectReadFileError(cause) ? cause : null; |
| 272 | const data = canReadFiles ? (optimisticFile?.data ?? (isMissing ? null : readData)) : null; |
| 273 | const isNotFile = readError?.failure === "path_not_file"; |
| 274 | |
| 275 | return { |
| 276 | data, |
| 277 | error: |
| 278 | !isQueryEnabled || fileAccess.isPending |
| 279 | ? null |
| 280 | : canReadFiles |
| 281 | ? isMissing && !optimisticFile |
| 282 | ? resolve(msg("''{path}'' does not exist.", { path: relativePath })) |
| 283 | : errorMessage(cause, resolve) |
| 284 | : (fileAccess.error ?? resolve(msg("This connection cannot read host files."))), |
| 285 | isPending: isQueryEnabled && (fileAccess.isPending || result.waiting), |
| 286 | readError, |
| 287 | isNotFile, |
| 288 | // A folder error overrides cached contents retained across failed refreshes. |
| 289 | isFile: !isNotFile && (data !== null || readError?.failure === "binary_file"), |
| 290 | refresh, |
| 291 | }; |
| 292 | } |