Open History to see the last commit
1import { useParams } from "@tanstack/react-router";
2import { scopeProjectRef } from "@t3tools/client-runtime/environment";
3import {
4 getAddProjectInitialQuery,
5 getCloneDestinationPath,
6 getCloneDirectoryName,
7} from "@t3tools/client-runtime/operations/projects";
8import {
9 type EnvironmentId,
10 type ProjectIgnoredFile,
11 type ScopedProjectRef,
12 resolveEnvironmentMachineKind,
13} from "@t3tools/contracts";
14import { ArrowRightIcon } from "lucide-react";
15import { useEffect, useId, useState } from "react";
16import { create } from "zustand";
17
18import { type DraftId, useComposerDraftStore } from "../composerDraftStore";
19import { useAddProjectTargets } from "../hooks/useAddProjectTargets";
20import { useNewThreadHandler } from "../hooks/useHandleNewThread";
21import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments";
22import {
23 COPYABLE_FILE_MAX_BYTES,
24 type CloneProtocol,
25 addProjectToMachine,
26 cloneUrlForProtocol,
27 cloneUrlProtocol,
28 isDefaultCopiedFile,
29} from "../lib/addProjectToMachine";
30import { formatBytes } from "../lib/formatBytes";
31import { newProjectId } from "../lib/utils";
32import { useProject } from "../state/entities";
33import { useEnvironments } from "../state/environments";
34import { projectEnvironment } from "../state/projects";
35import { useEnvironmentQuery } from "../state/query";
36import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
37import { Button } from "./ui/button";
38import { Checkbox } from "./ui/checkbox";
39import {
40 Dialog,
41 DialogDescription,
42 DialogFooter,
43 DialogHeader,
44 DialogPanel,
45 DialogPopup,
46 DialogTitle,
47} from "./ui/dialog";
48import { Input } from "./ui/input";
49import { Label } from "./ui/label";
50import { MiddleTruncate } from "./ui/middle-truncate";
51import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
52import { Toggle, ToggleGroup } from "./ui/toggle-group";
53
54interface AddProjectToMachineRequest {
55 readonly projectRef: ScopedProjectRef;
56 readonly targetEnvironmentId: EnvironmentId | null;
57}
58
59const useRequest = create<{ request: AddProjectToMachineRequest | null }>(() => ({
60 request: null,
61}));
62
63/** Opens the dialog that clones a project onto another connected machine. */
64export function openAddProjectToMachine(request: AddProjectToMachineRequest) {
65 useRequest.setState({ request });
66}
67
68const close = () => useRequest.setState({ request: null });
69
70export function AddProjectToMachineDialogHost() {
71 const request = useRequest((state) => state.request);
72 return request ? <AddProjectToMachineDialog request={request} /> : null;
73}
74
75function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRequest }) {
76 const id = useId();
77 const project = useProject(request.projectRef);
78 const handleNewThread = useNewThreadHandler();
79 const { draftId: routeDraftId } = useParams({ strict: false });
80 const { environments } = useEnvironments();
81 const targets = useAddProjectTargets(project, useLogicalProjectEnvironments(project, false));
82 const [targetId, setTargetId] = useState(request.targetEnvironmentId);
83 const target = targets.find((t) => t.environmentId === targetId) ?? targets[0] ?? null;
84 const source = environments.find((env) => env.environmentId === request.projectRef.environmentId);
85 const sourceUrl = project?.repositoryIdentity?.locator.remoteUrl ?? "";
86 const [protocol, setProtocol] = useState<CloneProtocol | null>(() => cloneUrlProtocol(sourceUrl));
87 const sshUrl = cloneUrlForProtocol(sourceUrl, "ssh");
88 const httpsUrl = cloneUrlForProtocol(sourceUrl, "https");
89 const remoteUrl =
90 (protocol === "ssh" ? sshUrl : protocol === "https" ? httpsUrl : null) ?? sourceUrl;
91
92 const targetEnvironment = environments.find((env) => env.environmentId === target?.environmentId);
93 const defaultPath = getCloneDestinationPath(
94 getAddProjectInitialQuery(targetEnvironment?.serverConfig?.settings.addProjectBaseDirectory),
95 getCloneDirectoryName(sourceUrl),
96 );
97 const [pathOverride, setPathOverride] = useState<string | null>(null);
98 const destinationPath = pathOverride ?? defaultPath;
99
100 const canListFiles = source?.serverConfig?.environment.capabilities.ignoredFileListing === true;
101 const ignoredFiles = useEnvironmentQuery(
102 project && canListFiles
103 ? projectEnvironment.listIgnoredFiles({
104 environmentId: project.environmentId,
105 input: { cwd: project.workspaceRoot },
106 })
107 : null,
108 );
109 const files = ignoredFiles.data?.files ?? [];
110 const [selected, setSelected] = useState<ReadonlySet<string> | null>(null);
111 const selectedFiles = selected ?? defaultSelection(files);
112 const copyable = files.filter((file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES);
113 const selectedBytes = files
114 .filter((file) => selectedFiles.has(file.path))
115 .reduce((total, file) => total + file.byteLength, 0);
116
117 const [submitting, setSubmitting] = useState(false);
118 const [error, setError] = useState<string | null>(null);
119
120 // The project or every target can vanish while the dialog is open. Submitting
121 // before the file list loads would silently skip the default .env copies.
122 const unavailable =
123 project === null ||
124 target === null ||
125 (canListFiles && ignoredFiles.data === null && ignoredFiles.error === null);
126 useEffect(() => {
127 if (project === null) close();
128 }, [project]);
129
130 const toggleFile = (path: string, checked: boolean) => {
131 const next = new Set(selectedFiles);
132 if (checked) next.add(path);
133 else next.delete(path);
134 setSelected(next);
135 };
136
137 // Lands the user on the new machine right away; its composer shows the clone
138 // and holds sends until it finishes. A draft open on the source project moves
139 // over with whatever was typed in it.
140 const openClonedProject = (targetRef: ScopedProjectRef) => {
141 const drafts = useComposerDraftStore.getState();
142 const draftId = routeDraftId as DraftId | undefined;
143 const draft = draftId ? drafts.getDraftSession(draftId) : null;
144 if (
145 draftId &&
146 draft &&
147 !draft.promotedTo &&
148 draft.environmentId === request.projectRef.environmentId &&
149 draft.projectId === request.projectRef.projectId
150 ) {
151 drafts.setDraftThreadContext(draftId, {
152 projectRef: targetRef,
153 environmentSelection: "manual",
154 loadBalancedEnvironmentId: null,
155 });
156 return;
157 }
158 void handleNewThread(targetRef);
159 };
160
161 const submit = async () => {
162 if (!project || !target || submitting) return;
163 if (destinationPath.trim().length === 0) {
164 setError("Choose a folder on the other machine.");
165 return;
166 }
167 setSubmitting(true);
168 setError(null);
169 const projectId = newProjectId();
170 try {
171 await addProjectToMachine({
172 source: { environmentId: project.environmentId, cwd: project.workspaceRoot },
173 subdirectory: projectSubdirectory(
174 project.repositoryIdentity?.rootPath,
175 project.workspaceRoot,
176 ),
177 target: { environmentId: target.environmentId, label: target.label },
178 projectId,
179 title: project.title,
180 remoteUrl,
181 destinationPath: destinationPath.trim(),
182 files: files.filter((file) => selectedFiles.has(file.path)).map((file) => file.path),
183 });
184 close();
185 openClonedProject(scopeProjectRef(target.environmentId, projectId));
186 } catch (cause) {
187 setError(cause instanceof Error ? cause.message : "Could not start the clone.");
188 setSubmitting(false);
189 }
190 };
191
192 return (
193 <Dialog
194 open
195 onOpenChange={(open) => {
196 if (!open) close();
197 }}
198 >
199 <DialogPopup className="sm:max-w-xl">
200 <form
201 className="flex min-h-0 flex-col"
202 onSubmit={(event) => {
203 event.preventDefault();
204 void submit();
205 }}
206 >
207 <DialogHeader>
208 <DialogTitle>Add to another machine</DialogTitle>
209 <DialogDescription>
210 Clone {project?.repositoryIdentity?.displayName ?? project?.title} and bring the local
211 files git does not track.
212 </DialogDescription>
213 </DialogHeader>
214 <DialogPanel>
215 <div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-3">
216 <div className="flex min-w-0 flex-col gap-1">
217 <span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
218 <EnvironmentMachineIcon
219 kind={resolveEnvironmentMachineKind(source?.serverConfig ?? null)}
220 className="size-3.5 shrink-0"
221 />
222 <span className="truncate">{source?.label ?? "This machine"}</span>
223 </span>
224 <span className="flex min-w-0 font-mono text-muted-foreground text-xs">
225 <MiddleTruncate value={project?.workspaceRoot ?? ""} />
226 </span>
227 </div>
228 <div className="flex w-28 flex-col items-center gap-0.5 text-muted-foreground text-xs">
229 <span>git clone</span>
230 <span className="flex w-full items-center">
231 <span className="h-px flex-1 bg-border" />
232 <ArrowRightIcon className="-ms-1 size-3.5" aria-hidden />
233 </span>
234 <span>
235 {selectedFiles.size === 0
236 ? "no files"
237 : `+ ${selectedFiles.size} ${selectedFiles.size === 1 ? "file" : "files"}`}
238 </span>
239 </div>
240 <div className="flex min-w-0 flex-col gap-1">
241 {targets.length > 1 ? (
242 <Select
243 value={target?.environmentId ?? null}
244 onValueChange={(value) => {
245 if (value) setTargetId(value);
246 }}
247 items={targets.map((t) => ({ value: t.environmentId, label: t.label }))}
248 >
249 <SelectTrigger size="sm" aria-label="Machine to add the project to">
250 {target ? (
251 <EnvironmentMachineIcon kind={target.machine} className="size-3.5" />
252 ) : null}
253 <SelectValue />
254 </SelectTrigger>
255 <SelectPopup>
256 {targets.map((t) => (
257 <SelectItem key={t.environmentId} value={t.environmentId}>
258 <span className="inline-flex items-center gap-1.5">
259 <EnvironmentMachineIcon kind={t.machine} className="size-3" />
260 {t.label}
261 </span>
262 </SelectItem>
263 ))}
264 </SelectPopup>
265 </Select>
266 ) : (
267 <span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
268 {target ? (
269 <EnvironmentMachineIcon kind={target.machine} className="size-3.5 shrink-0" />
270 ) : null}
271 <span className="truncate">{target?.label ?? "No machine available"}</span>
272 </span>
273 )}
274 <span className="flex min-w-0 font-mono text-muted-foreground text-xs">
275 <MiddleTruncate value={destinationPath} />
276 </span>
277 </div>
278 </div>
279
280 <div className="flex flex-col gap-1.5">
281 <Label>Clone over</Label>
282 {sshUrl && httpsUrl ? (
283 <ToggleGroup
284 aria-label="Clone protocol"
285 value={protocol ? [protocol] : []}
286 onValueChange={(next) => {
287 const value = next[0];
288 if (value === "ssh" || value === "https") setProtocol(value);
289 }}
290 >
291 <Toggle value="ssh">SSH</Toggle>
292 <Toggle value="https">HTTPS</Toggle>
293 </ToggleGroup>
294 ) : null}
295 <span className="truncate font-mono text-muted-foreground text-xs">{remoteUrl}</span>
296 </div>
297
298 <div className="flex flex-col gap-1.5">
299 <Label htmlFor={`${id}-path`}>Folder on {target?.label ?? "the other machine"}</Label>
300 <Input
301 id={`${id}-path`}
302 value={destinationPath}
303 onChange={(event) => setPathOverride(event.target.value)}
304 spellCheck={false}
305 autoComplete="off"
306 />
307 </div>
308
309 {canListFiles ? (
310 <div className="flex flex-col gap-1.5">
311 <div className="flex items-center gap-2">
312 <Label className="flex-1">Copy ignored files</Label>
313 {copyable.length > 0 ? (
314 <>
315 <span className="text-muted-foreground text-xs">
316 {selectedFiles.size} of {files.length}
317 {selectedBytes > 0 ? ` · ${formatBytes(selectedBytes)}` : ""}
318 </span>
319 <Button
320 type="button"
321 variant="ghost"
322 size="xs"
323 onClick={() =>
324 setSelected(
325 selectedFiles.size === copyable.length
326 ? new Set()
327 : new Set(copyable.map((file) => file.path)),
328 )
329 }
330 >
331 {selectedFiles.size === copyable.length ? "None" : "All"}
332 </Button>
333 </>
334 ) : null}
335 </div>
336 {ignoredFiles.error ? (
337 <p className="text-destructive-foreground text-xs">{ignoredFiles.error}</p>
338 ) : files.length === 0 ? (
339 <p className="text-muted-foreground text-xs">
340 {ignoredFiles.isSuccess
341 ? "No ignored files to copy."
342 : "Finding ignored files…"}
343 </p>
344 ) : (
345 <div className="max-h-52 overflow-y-auto rounded-md border">
346 {files.map((file) => (
347 <IgnoredFileRow
348 key={file.path}
349 file={file}
350 checked={selectedFiles.has(file.path)}
351 onCheckedChange={(checked) => toggleFile(file.path, checked)}
352 />
353 ))}
354 </div>
355 )}
356 {ignoredFiles.data?.truncated ? (
357 <p className="text-muted-foreground text-xs">
358 Showing the first {files.length} files.
359 </p>
360 ) : null}
361 <p className="text-muted-foreground text-xs">
362 Files are copied after the clone finishes. Folders git ignores whole, like
363 node_modules, are left out.
364 </p>
365 </div>
366 ) : null}
367
368 {error ? <p className="text-destructive-foreground text-sm">{error}</p> : null}
369 </DialogPanel>
370 <DialogFooter>
371 <Button type="button" variant="outline" onClick={close}>
372 Cancel
373 </Button>
374 <Button type="submit" disabled={unavailable || submitting}>
375 {submitting ? "Starting…" : `Clone to ${target?.label ?? "machine"}`}
376 </Button>
377 </DialogFooter>
378 </form>
379 </DialogPopup>
380 </Dialog>
381 );
382}
383
384/**
385 * A project can be rooted below its repository's top folder. The clone lands
386 * at the top, so copied files keep the same path below it.
387 */
388function projectSubdirectory(repositoryRoot: string | undefined, workspaceRoot: string) {
389 if (!repositoryRoot) return "";
390 const prefix = repositoryRoot.replace(/[\\/]+$/, "");
391 const rest = workspaceRoot.slice(prefix.length);
392 return workspaceRoot.startsWith(prefix) && /^[\\/]/.test(rest)
393 ? rest.slice(1).replaceAll("\\", "/")
394 : "";
395}
396
397function defaultSelection(files: readonly ProjectIgnoredFile[]): ReadonlySet<string> {
398 return new Set(
399 files
400 .filter(
401 (file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES && isDefaultCopiedFile(file.path),
402 )
403 .map((file) => file.path),
404 );
405}
406
407function IgnoredFileRow({
408 file,
409 checked,
410 onCheckedChange,
411}: {
412 file: ProjectIgnoredFile;
413 checked: boolean;
414 onCheckedChange: (checked: boolean) => void;
415}) {
416 const tooLarge = file.byteLength > COPYABLE_FILE_MAX_BYTES;
417 return (
418 <label className="flex cursor-pointer items-center gap-2 px-2.5 py-1.5 text-sm not-last:border-b has-disabled:cursor-not-allowed has-disabled:opacity-64">
419 <Checkbox checked={checked} disabled={tooLarge} onCheckedChange={onCheckedChange} />
420 <span className="min-w-0 flex-1 truncate font-mono text-xs">{file.path}</span>
421 <span className="shrink-0 text-muted-foreground text-xs tabular-nums">
422 {tooLarge ? "Over 1 MB" : formatBytes(file.byteLength)}
423 </span>
424 </label>
425 );
426}