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 { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { |
| 3 | executeAtomQuery, |
| 4 | runAtomCommand, |
| 5 | squashAtomCommandFailure, |
| 6 | } from "@t3tools/client-runtime/state/runtime"; |
| 7 | import { scopedProjectKey } from "@t3tools/client-runtime/environment"; |
| 8 | import type { |
| 9 | EnvironmentId, |
| 10 | ProjectCloneSnapshot, |
| 11 | ProjectId, |
| 12 | ScopedProjectRef, |
| 13 | } from "@t3tools/contracts"; |
| 14 | import { msg } from "gt-react"; |
| 15 | import { create } from "zustand"; |
| 16 | |
| 17 | import { m } from "../i18n/messages"; |
| 18 | import { appAtomRegistry } from "../rpc/atomRegistry"; |
| 19 | import { suggestAppAccessForRemote } from "../components/sourceControlAppAccessToast"; |
| 20 | import { environmentProjectClonesAtom, silenceProjectCloneToasts } from "../state/projectClones"; |
| 21 | import { projectEnvironment } from "../state/projects"; |
| 22 | import { sourceControlEnvironment } from "../state/sourceControl"; |
| 23 | |
| 24 | /** Matches the server's read cap: a larger file would arrive truncated. */ |
| 25 | export const COPYABLE_FILE_MAX_BYTES = 1024 * 1024; |
| 26 | |
| 27 | /** The server lists at most this many ignored files, so one pick never exceeded it. */ |
| 28 | export const COPIED_FILES_MAX_COUNT = 200; |
| 29 | |
| 30 | const DEFAULT_COPIED_FILE_NAME = /^(?:\.env(?:\..+)?|\.envrc|\.dev\.vars)$/; |
| 31 | |
| 32 | /** Env files are the ignored files people almost always want on a new machine. */ |
| 33 | export function isDefaultCopiedFile(path: string): boolean { |
| 34 | const name = path.split("/").at(-1) ?? path; |
| 35 | return DEFAULT_COPIED_FILE_NAME.test(name); |
| 36 | } |
| 37 | |
| 38 | export interface AddProjectToMachineInput { |
| 39 | readonly source: { readonly environmentId: EnvironmentId; readonly cwd: string }; |
| 40 | /** Where the source project sits below its repository root, or "". */ |
| 41 | readonly subdirectory: string; |
| 42 | readonly target: { readonly environmentId: EnvironmentId; readonly label: string }; |
| 43 | readonly projectId: ProjectId; |
| 44 | readonly title: string; |
| 45 | readonly remoteUrl: string; |
| 46 | readonly destinationPath: string; |
| 47 | readonly files: ReadonlyArray<string>; |
| 48 | } |
| 49 | |
| 50 | function failureMessage(result: Parameters<typeof squashAtomCommandFailure>[0]): string { |
| 51 | const error = squashAtomCommandFailure(result); |
| 52 | return thrownErrorMessage(error, m) ?? m(msg("An error occurred.")); |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * Resolves when the clone finishes, or null once it is removed. A failed or |
| 57 | * cancelled clone keeps waiting, since the composer offers a retry. |
| 58 | */ |
| 59 | function waitForClone(environmentId: EnvironmentId, projectId: ProjectId) { |
| 60 | return new Promise<ProjectCloneSnapshot | null>((resolve) => { |
| 61 | const atom = environmentProjectClonesAtom(environmentId); |
| 62 | let seen = false; |
| 63 | let settled = false; |
| 64 | let unsubscribe: (() => void) | null = null; |
| 65 | const check = (clones: ReadonlyArray<ProjectCloneSnapshot>) => { |
| 66 | if (settled) return; |
| 67 | const clone = clones.find((candidate) => candidate.projectId === projectId); |
| 68 | if (clone) seen = true; |
| 69 | const result = clone?.phase === "done" ? clone : !clone && seen ? null : undefined; |
| 70 | if (result === undefined) return; |
| 71 | settled = true; |
| 72 | unsubscribe?.(); |
| 73 | resolve(result); |
| 74 | }; |
| 75 | unsubscribe = appAtomRegistry.subscribe(atom, check); |
| 76 | check(appAtomRegistry.get(atom)); |
| 77 | }); |
| 78 | } |
| 79 | |
| 80 | export type ProjectFileCopy = |
| 81 | | { readonly phase: "copying" } |
| 82 | | { |
| 83 | readonly phase: "failed"; |
| 84 | /** A `msg()`, resolved where it is shown so it follows the UI language. */ |
| 85 | readonly title: string; |
| 86 | readonly failures: ReadonlyArray<string>; |
| 87 | }; |
| 88 | |
| 89 | /** Ignored-file copies still owed to a cloned project, keyed by its scoped project key. */ |
| 90 | const useFileCopies = create<{ copies: Readonly<Record<string, ProjectFileCopy>> }>(() => ({ |
| 91 | copies: {}, |
| 92 | })); |
| 93 | |
| 94 | function setFileCopy(key: string, copy: ProjectFileCopy | null) { |
| 95 | useFileCopies.setState(({ copies }) => { |
| 96 | const { [key]: _previous, ...rest } = copies; |
| 97 | return { copies: copy === null ? rest : { ...rest, [key]: copy } }; |
| 98 | }); |
| 99 | } |
| 100 | |
| 101 | /** The composer holds sends until the copy lands, and shows a failed copy until dismissed. */ |
| 102 | export function useProjectFileCopy(ref: ScopedProjectRef | null): ProjectFileCopy | null { |
| 103 | return useFileCopies((state) => (ref ? (state.copies[scopedProjectKey(ref)] ?? null) : null)); |
| 104 | } |
| 105 | |
| 106 | export function dismissProjectFileCopy(ref: ScopedProjectRef) { |
| 107 | setFileCopy(scopedProjectKey(ref), null); |
| 108 | } |
| 109 | |
| 110 | /** |
| 111 | * Clones onto another machine, then relays the chosen ignored files, since the |
| 112 | * two servers never talk. Resolves with the cloning project once it starts; the |
| 113 | * caller opens it, and its composer shows progress, so nothing toasts. |
| 114 | */ |
| 115 | export async function addProjectToMachine(input: AddProjectToMachineInput): Promise<ProjectId> { |
| 116 | // Read first, so the copy reflects the files as they were when the user asked. |
| 117 | const reads = await Promise.all( |
| 118 | input.files.map(async (relativePath) => { |
| 119 | const result = await executeAtomQuery( |
| 120 | appAtomRegistry, |
| 121 | projectEnvironment.readFile({ |
| 122 | environmentId: input.source.environmentId, |
| 123 | input: { cwd: input.source.cwd, relativePath }, |
| 124 | }), |
| 125 | { label: "Read file to copy", reportFailure: false, refresh: true }, |
| 126 | ); |
| 127 | if (result._tag === "Failure") return { relativePath, error: failureMessage(result) }; |
| 128 | if (result.value.truncated) return { relativePath, error: m(msg("Too large to copy.")) }; |
| 129 | return { relativePath, contents: result.value.contents }; |
| 130 | }), |
| 131 | ); |
| 132 | |
| 133 | const requestedRef = { environmentId: input.target.environmentId, projectId: input.projectId }; |
| 134 | const requestedKey = scopedProjectKey(requestedRef); |
| 135 | // Marked before the start request, since the clone list can arrive before its reply. |
| 136 | silenceProjectCloneToasts(requestedRef); |
| 137 | if (reads.length > 0) setFileCopy(requestedKey, { phase: "copying" }); |
| 138 | const started = await runAtomCommand( |
| 139 | appAtomRegistry, |
| 140 | sourceControlEnvironment.startProjectClone, |
| 141 | { |
| 142 | environmentId: input.target.environmentId, |
| 143 | input: { |
| 144 | projectId: input.projectId, |
| 145 | title: input.title, |
| 146 | createdAt: new Date().toISOString(), |
| 147 | remoteUrl: input.remoteUrl, |
| 148 | destinationPath: input.destinationPath, |
| 149 | }, |
| 150 | }, |
| 151 | { label: "Add project to machine", reportFailure: false }, |
| 152 | ); |
| 153 | if (started._tag === "Failure") { |
| 154 | setFileCopy(requestedKey, null); |
| 155 | throw new Error(failureMessage(started)); |
| 156 | } |
| 157 | // The server clones for the existing project when one already owns the empty destination. |
| 158 | const { projectId } = started.value; |
| 159 | const targetRef = { environmentId: input.target.environmentId, projectId }; |
| 160 | const copyKey = scopedProjectKey(targetRef); |
| 161 | if (projectId !== input.projectId) { |
| 162 | silenceProjectCloneToasts(targetRef); |
| 163 | if (reads.length > 0) { |
| 164 | setFileCopy(copyKey, { phase: "copying" }); |
| 165 | setFileCopy(requestedKey, null); |
| 166 | } |
| 167 | } |
| 168 | void suggestAppAccessForRemote(input.target.environmentId, input.remoteUrl); |
| 169 | if (reads.length === 0) return projectId; |
| 170 | |
| 171 | void (async () => { |
| 172 | const clone = await waitForClone(input.target.environmentId, projectId); |
| 173 | if (!clone) { |
| 174 | setFileCopy(copyKey, null); |
| 175 | return; |
| 176 | } |
| 177 | const failed: Array<string> = []; |
| 178 | for (const read of reads) { |
| 179 | if (!("contents" in read)) { |
| 180 | failed.push(`${read.relativePath}: ${read.error}`); |
| 181 | continue; |
| 182 | } |
| 183 | const written = await runAtomCommand( |
| 184 | appAtomRegistry, |
| 185 | projectEnvironment.writeFile, |
| 186 | { |
| 187 | environmentId: input.target.environmentId, |
| 188 | input: { |
| 189 | cwd: started.value.cwd, |
| 190 | relativePath: input.subdirectory |
| 191 | ? `${input.subdirectory}/${read.relativePath}` |
| 192 | : read.relativePath, |
| 193 | contents: read.contents, |
| 194 | }, |
| 195 | }, |
| 196 | { label: "Copy file to machine", reportFailure: false }, |
| 197 | ); |
| 198 | if (written._tag === "Failure") |
| 199 | failed.push(`${read.relativePath}: ${failureMessage(written)}`); |
| 200 | } |
| 201 | setFileCopy( |
| 202 | copyKey, |
| 203 | failed.length === 0 |
| 204 | ? null |
| 205 | : { |
| 206 | phase: "failed", |
| 207 | title: msg( |
| 208 | "Could not copy {count, plural, one {{count} file} other {{count} files}} to {target}", |
| 209 | { count: failed.length, target: input.target.label }, |
| 210 | ), |
| 211 | failures: failed, |
| 212 | }, |
| 213 | ); |
| 214 | })(); |
| 215 | return projectId; |
| 216 | } |