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