Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import {
3 executeAtomQuery,
4 runAtomCommand,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import { scopedProjectKey } from "@t3tools/client-runtime/environment";
8import type {
9 EnvironmentId,
10 ProjectCloneSnapshot,
11 ProjectId,
12 ScopedProjectRef,
13} from "@t3tools/contracts";
14import { msg } from "gt-react";
15import { create } from "zustand";
16
17import { m } from "../i18n/messages";
18import { appAtomRegistry } from "../rpc/atomRegistry";
19import { suggestAppAccessForRemote } from "../components/sourceControlAppAccessToast";
20import { environmentProjectClonesAtom } from "../state/projectClones";
21import { projectEnvironment } from "../state/projects";
22import { sourceControlEnvironment } from "../state/sourceControl";
23
24/** Matches the server's read cap: a larger file would arrive truncated. */
25export const COPYABLE_FILE_MAX_BYTES = 1024 * 1024;
26
27/** The server lists at most this many ignored files, so one pick never exceeded it. */
28export const COPIED_FILES_MAX_COUNT = 200;
29
30const DEFAULT_COPIED_FILE_NAME = /^(?:\.env(?:\..+)?|\.envrc|\.dev\.vars)$/;
31
32/** Env files are the ignored files people almost always want on a new machine. */
33export function isDefaultCopiedFile(path: string): boolean {
34 const name = path.split("/").at(-1) ?? path;
35 return DEFAULT_COPIED_FILE_NAME.test(name);
36}
37
38export 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
50function 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 */
59function 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
80export 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. */
90const useFileCopies = create<{ copies: Readonly<Record<string, ProjectFileCopy>> }>(() => ({
91 copies: {},
92}));
93
94function 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. */
102export function useProjectFileCopy(ref: ScopedProjectRef | null): ProjectFileCopy | null {
103 return useFileCopies((state) => (ref ? (state.copies[scopedProjectKey(ref)] ?? null) : null));
104}
105
106export 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 decides whether to open it and show progress in the composer.
114 */
115export 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 if (reads.length > 0) setFileCopy(requestedKey, { phase: "copying" });
136 const started = await runAtomCommand(
137 appAtomRegistry,
138 sourceControlEnvironment.startProjectClone,
139 {
140 environmentId: input.target.environmentId,
141 input: {
142 projectId: input.projectId,
143 title: input.title,
144 createdAt: new Date().toISOString(),
145 remoteUrl: input.remoteUrl,
146 destinationPath: input.destinationPath,
147 },
148 },
149 { label: "Add project to machine", reportFailure: false },
150 );
151 if (started._tag === "Failure") {
152 setFileCopy(requestedKey, null);
153 throw new Error(failureMessage(started));
154 }
155 // The server clones for the existing project when one already owns the empty destination.
156 const { projectId } = started.value;
157 const targetRef = { environmentId: input.target.environmentId, projectId };
158 const copyKey = scopedProjectKey(targetRef);
159 if (projectId !== input.projectId) {
160 if (reads.length > 0) {
161 setFileCopy(copyKey, { phase: "copying" });
162 setFileCopy(requestedKey, null);
163 }
164 }
165 void suggestAppAccessForRemote(input.target.environmentId, input.remoteUrl);
166 if (reads.length === 0) return projectId;
167
168 void (async () => {
169 const clone = await waitForClone(input.target.environmentId, projectId);
170 if (!clone) {
171 setFileCopy(copyKey, null);
172 return;
173 }
174 const failed: Array<string> = [];
175 for (const read of reads) {
176 if (!("contents" in read)) {
177 failed.push(`${read.relativePath}: ${read.error}`);
178 continue;
179 }
180 const written = await runAtomCommand(
181 appAtomRegistry,
182 projectEnvironment.writeFile,
183 {
184 environmentId: input.target.environmentId,
185 input: {
186 cwd: started.value.cwd,
187 relativePath: input.subdirectory
188 ? `${input.subdirectory}/${read.relativePath}`
189 : read.relativePath,
190 contents: read.contents,
191 },
192 },
193 { label: "Copy file to machine", reportFailure: false },
194 );
195 if (written._tag === "Failure")
196 failed.push(`${read.relativePath}: ${failureMessage(written)}`);
197 }
198 setFileCopy(
199 copyKey,
200 failed.length === 0
201 ? null
202 : {
203 phase: "failed",
204 title: msg(
205 "Could not copy {count, plural, one {{count} file} other {{count} files}} to {target}",
206 { count: failed.length, target: input.target.label },
207 ),
208 failures: failed,
209 },
210 );
211 })();
212 return projectId;
213}