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