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