The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { msg } from "gt-i18n"; |
| 2 | import { type MarkedText, markedTextEnglish } from "../errors/translatable.ts"; |
| 3 | import { |
| 4 | type EnvironmentId, |
| 5 | ProjectId, |
| 6 | type ProjectReadFileResult, |
| 7 | type ScopedProjectRef, |
| 8 | WS_METHODS, |
| 9 | } from "@t3tools/contracts"; |
| 10 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as Option from "effect/Option"; |
| 13 | import * as Predicate from "effect/Predicate"; |
| 14 | import * as Schema from "effect/Schema"; |
| 15 | import * as Stream from "effect/Stream"; |
| 16 | import { Atom, AtomRegistry } from "effect/reactivity"; |
| 17 | |
| 18 | import { |
| 19 | type EnvironmentRpcInput, |
| 20 | type EnvironmentRpcSuccess, |
| 21 | request, |
| 22 | requestGuarded, |
| 23 | } from "../rpc/client.ts"; |
| 24 | import type { EnvironmentProject } from "./models.ts"; |
| 25 | import { |
| 26 | createAtomCommandScheduler, |
| 27 | createEnvironmentCommand, |
| 28 | createEnvironmentRpcCommand, |
| 29 | createEnvironmentRpcQueryAtomFamily, |
| 30 | } from "./runtime.ts"; |
| 31 | import { createProject, deleteProject, updateProject } from "../operations/commands.ts"; |
| 32 | import type { EnvironmentRegistry } from "../connection/registry.ts"; |
| 33 | import { createFileMetadataAtoms } from "./fileMetadata.ts"; |
| 34 | import { resolveWorkspaceFilePath } from "@t3tools/shared/path"; |
| 35 | |
| 36 | export type { |
| 37 | CreateProjectInput, |
| 38 | DeleteProjectInput, |
| 39 | UpdateProjectInput, |
| 40 | } from "../operations/commands.ts"; |
| 41 | |
| 42 | export type OptimisticProjectFile = { |
| 43 | readonly data: ProjectReadFileResult; |
| 44 | } & ( |
| 45 | | { readonly saved: false } |
| 46 | | { |
| 47 | readonly saved: true; |
| 48 | /** Only this query's next successful answer can replace the saved contents. */ |
| 49 | readonly confirmingQuery: Atom.Atom<unknown>; |
| 50 | } |
| 51 | ); |
| 52 | |
| 53 | export interface OptimisticProjectFileTarget { |
| 54 | readonly environmentId: EnvironmentId; |
| 55 | readonly cwd: string; |
| 56 | readonly relativePath: string; |
| 57 | } |
| 58 | |
| 59 | function optimisticProjectFileKey(target: OptimisticProjectFileTarget): string { |
| 60 | return JSON.stringify([target.environmentId, target.cwd, target.relativePath]); |
| 61 | } |
| 62 | |
| 63 | function writtenFilePaths( |
| 64 | input: EnvironmentRpcInput<typeof WS_METHODS.projectsWriteFile>, |
| 65 | result: EnvironmentRpcSuccess<typeof WS_METHODS.projectsWriteFile>, |
| 66 | ) { |
| 67 | return new Set( |
| 68 | [result.relativePath, input.relativePath].map((path) => |
| 69 | resolveWorkspaceFilePath(path, input.cwd), |
| 70 | ), |
| 71 | ); |
| 72 | } |
| 73 | |
| 74 | export class ScratchProjectNotLoadedError extends Schema.TaggedError<ScratchProjectNotLoadedError>()( |
| 75 | "ScratchProjectNotLoadedError", |
| 76 | { projectId: ProjectId }, |
| 77 | ) { |
| 78 | override get message(): string { |
| 79 | return markedTextEnglish(this.i18nMessage); |
| 80 | } |
| 81 | |
| 82 | get i18nMessage(): MarkedText { |
| 83 | return [ |
| 84 | msg("The folder for threads without a project has not reached this device yet. Try again."), |
| 85 | ]; |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | export function createProjectEnvironmentAtoms<R, E>( |
| 90 | runtime: Atom.AtomRuntime<EnvironmentRegistry | SecureRandom.SecureRandom | R, E>, |
| 91 | options: { |
| 92 | readonly projectAtom: (ref: ScopedProjectRef) => Atom.Atom<EnvironmentProject | null>; |
| 93 | }, |
| 94 | ) { |
| 95 | const fileMetadata = createFileMetadataAtoms(runtime); |
| 96 | const projectScheduler = createAtomCommandScheduler(); |
| 97 | const fileScheduler = createAtomCommandScheduler(); |
| 98 | const optimisticFileFamily = Atom.family((key: string) => |
| 99 | Atom.make<OptimisticProjectFile | null>(null).pipe( |
| 100 | Atom.withLabel(`environment-data:projects:optimistic-file:${key}`), |
| 101 | ), |
| 102 | ); |
| 103 | const readFile = createEnvironmentRpcQueryAtomFamily(runtime, { |
| 104 | label: "environment-data:projects:read-file", |
| 105 | tag: WS_METHODS.projectsReadFile, |
| 106 | staleTimeMs: 30_000, |
| 107 | idleTtlMs: 5 * 60_000, |
| 108 | onAnswer: (target, _value, registry): Effect.Effect<void> => |
| 109 | Effect.sync(() => { |
| 110 | const atom = optimisticFileFamily( |
| 111 | optimisticProjectFileKey({ environmentId: target.environmentId, ...target.input }), |
| 112 | ); |
| 113 | const overlay = registry.get(atom); |
| 114 | if (overlay?.saved && overlay.confirmingQuery === readFile(target)) |
| 115 | registry.set(atom, null); |
| 116 | }), |
| 117 | execute: (input) => |
| 118 | fileMetadata.seedAfterRead( |
| 119 | request(WS_METHODS.projectsReadFile, input), |
| 120 | (result, isCurrent) => |
| 121 | result.exists === false |
| 122 | ? Effect.void |
| 123 | : fileMetadata.rememberFile(input.cwd, result, isCurrent), |
| 124 | ), |
| 125 | }); |
| 126 | const projectConcurrency = { |
| 127 | mode: "serial" as const, |
| 128 | key: ({ environmentId, input }: { environmentId: string; input: { projectId: string } }) => |
| 129 | JSON.stringify([environmentId, input.projectId]), |
| 130 | }; |
| 131 | return { |
| 132 | fileMetadata: fileMetadata.metadata, |
| 133 | fileMetadataThread: fileMetadata.retainThread, |
| 134 | invalidateFileMetadata: createEnvironmentCommand(runtime, { |
| 135 | label: "environment-data:filesystem:invalidate-metadata", |
| 136 | execute: (input: { paths: ReadonlyArray<string> }, registry, environmentId) => |
| 137 | Effect.forEach([...new Set(input.paths)], (path) => |
| 138 | fileMetadata |
| 139 | .invalidate(path) |
| 140 | .pipe( |
| 141 | Effect.tap(() => |
| 142 | Effect.sync(() => fileMetadata.refreshPath(environmentId, path, registry)), |
| 143 | ), |
| 144 | ), |
| 145 | ), |
| 146 | }), |
| 147 | searchEntries: createEnvironmentRpcQueryAtomFamily(runtime, { |
| 148 | label: "environment-data:projects:search-entries", |
| 149 | tag: WS_METHODS.projectsSearchEntries, |
| 150 | staleTimeMs: 15_000, |
| 151 | execute: (input) => |
| 152 | fileMetadata.seedAfterRead( |
| 153 | request(WS_METHODS.projectsSearchEntries, input), |
| 154 | (result, isCurrent) => fileMetadata.rememberEntries(input.cwd, result.entries, isCurrent), |
| 155 | ), |
| 156 | }), |
| 157 | listEntries: createEnvironmentRpcQueryAtomFamily(runtime, { |
| 158 | label: "environment-data:projects:list-entries", |
| 159 | tag: WS_METHODS.projectsListEntries, |
| 160 | staleTimeMs: 30_000, |
| 161 | idleTtlMs: 5 * 60_000, |
| 162 | execute: (input) => |
| 163 | fileMetadata.seedAfterRead( |
| 164 | request(WS_METHODS.projectsListEntries, input), |
| 165 | (result, isCurrent) => fileMetadata.rememberEntries(input.cwd, result.entries, isCurrent), |
| 166 | ), |
| 167 | }), |
| 168 | listIgnoredFiles: createEnvironmentRpcQueryAtomFamily(runtime, { |
| 169 | label: "environment-data:projects:list-ignored-files", |
| 170 | tag: WS_METHODS.projectsListIgnoredFiles, |
| 171 | staleTimeMs: 15_000, |
| 172 | }), |
| 173 | readFile, |
| 174 | optimisticFile: (target: OptimisticProjectFileTarget) => |
| 175 | optimisticFileFamily(optimisticProjectFileKey(target)), |
| 176 | create: createEnvironmentCommand(runtime, { |
| 177 | label: "environment-data:commands:project:create", |
| 178 | execute: createProject, |
| 179 | scheduler: projectScheduler, |
| 180 | concurrency: projectConcurrency, |
| 181 | }), |
| 182 | update: createEnvironmentCommand(runtime, { |
| 183 | label: "environment-data:commands:project:update", |
| 184 | execute: updateProject, |
| 185 | scheduler: projectScheduler, |
| 186 | concurrency: projectConcurrency, |
| 187 | }), |
| 188 | delete: createEnvironmentCommand(runtime, { |
| 189 | label: "environment-data:commands:project:delete", |
| 190 | execute: deleteProject, |
| 191 | scheduler: projectScheduler, |
| 192 | concurrency: projectConcurrency, |
| 193 | }), |
| 194 | // Finds or creates the environment's Scratch project and resolves once the |
| 195 | // project is in the client store, since drafts key off its stored path. |
| 196 | openScratch: createEnvironmentCommand(runtime, { |
| 197 | label: "environment-data:projects:open-scratch", |
| 198 | execute: ( |
| 199 | input: EnvironmentRpcInput<typeof WS_METHODS.projectsEnsureScratch>, |
| 200 | registry, |
| 201 | environmentId, |
| 202 | ) => |
| 203 | request(WS_METHODS.projectsEnsureScratch, input).pipe( |
| 204 | Effect.flatMap(({ projectId }) => |
| 205 | AtomRegistry.toStream(registry, options.projectAtom({ environmentId, projectId })).pipe( |
| 206 | Stream.filter(Predicate.isNotNull), |
| 207 | Stream.runHead, |
| 208 | Effect.timeoutOption("10 seconds"), |
| 209 | Effect.map(Option.flatten), |
| 210 | Effect.flatMap( |
| 211 | Option.match({ |
| 212 | onSome: Effect.succeed, |
| 213 | onNone: () => Effect.fail(new ScratchProjectNotLoadedError({ projectId })), |
| 214 | }), |
| 215 | ), |
| 216 | ), |
| 217 | ), |
| 218 | ), |
| 219 | scheduler: projectScheduler, |
| 220 | concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, |
| 221 | }), |
| 222 | createNew: createEnvironmentRpcCommand(runtime, { |
| 223 | label: "environment-data:projects:create-new", |
| 224 | tag: WS_METHODS.projectsCreateNew, |
| 225 | scheduler: projectScheduler, |
| 226 | concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, |
| 227 | }), |
| 228 | createFromThread: createEnvironmentRpcCommand(runtime, { |
| 229 | label: "environment-data:projects:create-from-thread", |
| 230 | tag: WS_METHODS.projectsCreateFromThread, |
| 231 | scheduler: projectScheduler, |
| 232 | concurrency: { mode: "serial", key: ({ environmentId }) => environmentId }, |
| 233 | }), |
| 234 | writeFile: createEnvironmentRpcCommand(runtime, { |
| 235 | label: "environment-data:projects:write-file", |
| 236 | tag: WS_METHODS.projectsWriteFile, |
| 237 | scheduler: fileScheduler, |
| 238 | concurrency: { |
| 239 | mode: "serial", |
| 240 | key: ({ environmentId, input }) => |
| 241 | JSON.stringify([environmentId, input.cwd, input.relativePath]), |
| 242 | }, |
| 243 | execute: (input) => |
| 244 | requestGuarded(WS_METHODS.projectsWriteFile, input).pipe( |
| 245 | Effect.tap((result) => |
| 246 | Effect.forEach(writtenFilePaths(input, result), fileMetadata.invalidate), |
| 247 | ), |
| 248 | ), |
| 249 | onSuccess: ({ environmentId, input }, registry, result) => |
| 250 | Effect.sync(() => { |
| 251 | for (const path of writtenFilePaths(input, result)) |
| 252 | fileMetadata.refreshPath(environmentId, path, registry); |
| 253 | }), |
| 254 | }), |
| 255 | }; |
| 256 | } |