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