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 {
9 type EnvironmentId,
10 type ProjectIgnoredFile,
11 type ScopedProjectRef,
12 resolveEnvironmentMachineKind,
13} from "@t3tools/contracts";
14import {
15 type CloneProtocol,
16 cloneUrlForProtocol,
17 cloneUrlProtocol,
18} from "@t3tools/shared/cloneUrl";
19import { ArrowRightIcon } from "lucide-react";
20import { useId, useState } from "react";
21import { create } from "zustand";
22
23import { type DraftId, useComposerDraftStore } from "../composerDraftStore";
24import { useAddProjectTargets } from "../hooks/useAddProjectTargets";
25import { useNewThreadHandler } from "../hooks/useHandleNewThread";
26import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments";
27import {
28 COPYABLE_FILE_MAX_BYTES,
29 addProjectToMachine,
30 isDefaultCopiedFile,
31} from "../lib/addProjectToMachine";
32import { formatBytes } from "../lib/formatBytes";
33import { newProjectId } from "../lib/utils";
34import { readProject, subscribeProject, useProject } from "../state/entities";
35import { useEnvironments } from "../state/environments";
36import { projectEnvironment } from "../state/projects";
37import { useEnvironmentQuery } from "../state/query";
38import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
39import { Button } from "./ui/button";
40import { Checkbox } from "./ui/checkbox";
41import {
42 Dialog,
43 DialogDescription,
44 DialogFooter,
45 DialogHeader,
46 DialogPanel,
47 DialogPopup,
48 DialogTitle,
49} from "./ui/dialog";
50import { Input } from "./ui/input";
51import { Label } from "./ui/label";
52import { MiddleTruncate } from "./ui/middle-truncate";
53import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
54import { Toggle, ToggleGroup } from "./ui/toggle-group";
55
56interface AddProjectToMachineRequest {
57 readonly projectRef: ScopedProjectRef;
58 readonly targetEnvironmentId: EnvironmentId | null;
59}
60
61const useRequest = create<{ request: AddProjectToMachineRequest | null; session: number }>(() => ({
62 request: null,
63 session: 0,
64}));
65
66let endRequestWithProject: (() => void) | null = null;
67
68/** Opens the dialog that clones a project onto another connected machine. */
69export function openAddProjectToMachine(request: AddProjectToMachineRequest) {
70 if (readProject(request.projectRef) === null) return;
71 endRequestWithProject?.();
72 // The request ends when its project goes away, so a project that comes back
73 // later cannot reopen a dialog nobody asked for.
74 endRequestWithProject = subscribeProject(request.projectRef, (project) => {
75 if (project === null) close();
76 });
77 useRequest.setState((state) => ({ request, session: state.session + 1 }));
78}
79
80function close() {
81 endRequestWithProject?.();
82 endRequestWithProject = null;
83 useRequest.setState({ request: null });
84}
85
86export function AddProjectToMachineDialogHost() {
87 const request = useRequest((state) => state.request);
88 const session = useRequest((state) => state.session);
89 return request ? <AddProjectToMachineDialog key={session} request={request} /> : null;
90}
91
92function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRequest }) {
93 const id = useId();
94 const project = useProject(request.projectRef);
95 const handleNewThread = useNewThreadHandler();
96 const { draftId: routeDraftId } = useParams({ strict: false });
97 const { environments } = useEnvironments();
98 const targets = useAddProjectTargets(project, useLogicalProjectEnvironments(project, false));
99 const [targetId, setTargetId] = useState(request.targetEnvironmentId);
100 const target = targets.find((t) => t.environmentId === targetId) ?? targets[0] ?? null;
101 const source = environments.find((env) => env.environmentId === request.projectRef.environmentId);
102 const sourceUrl =
103 project?.repositoryIdentity?.origin?.remoteUrl ??
104 project?.repositoryIdentity?.locator.remoteUrl ??
105 "";
106 const [protocol, setProtocol] = useState<CloneProtocol | null>(() => cloneUrlProtocol(sourceUrl));
107 const sshUrl = cloneUrlForProtocol(sourceUrl, "ssh");
108 const httpsUrl = cloneUrlForProtocol(sourceUrl, "https");
109 const remoteUrl =
110 (protocol === "ssh" ? sshUrl : protocol === "https" ? httpsUrl : null) ?? sourceUrl;
111
112 const targetEnvironment = environments.find((env) => env.environmentId === target?.environmentId);
113 const defaultPath = getCloneDestinationPath(
114 getAddProjectInitialQuery(targetEnvironment?.serverConfig?.settings.addProjectBaseDirectory),
115 getCloneDirectoryPath(
116 sourceUrl,
117 targetEnvironment?.serverConfig?.settings.ghqCloneLayout === true,
118 ),
119 );
120 const [pathOverride, setPathOverride] = useState<string | null>(null);
121 const destinationPath = pathOverride ?? defaultPath;
122
123 const canListFiles = source?.serverConfig?.environment.capabilities.ignoredFileListing === true;
124 const ignoredFiles = useEnvironmentQuery(
125 project && canListFiles
126 ? projectEnvironment.listIgnoredFiles({
127 environmentId: project.environmentId,
128 input: { cwd: project.workspaceRoot },
129 })
130 : null,
131 );
132 const files = ignoredFiles.data?.files ?? [];
133 const [selected, setSelected] = useState<ReadonlySet<string> | null>(null);
134 const selectedFiles = selected ?? defaultSelection(files);
135 const copyable = files.filter((file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES);
136 const selectedBytes = files
137 .filter((file) => selectedFiles.has(file.path))
138 .reduce((total, file) => total + file.byteLength, 0);
139
140 const [submitting, setSubmitting] = useState(false);
141 const [error, setError] = useState<string | null>(null);
142
143 // The project or every target can vanish while the dialog is open. Submitting
144 // before the file list loads would silently skip the default .env copies.
145 const unavailable =
146 project === null ||
147 target === null ||
148 (canListFiles && ignoredFiles.data === null && ignoredFiles.error === null);
149 const toggleFile = (path: string, checked: boolean) => {
150 const next = new Set(selectedFiles);
151 if (checked) next.add(path);
152 else next.delete(path);
153 setSelected(next);
154 };
155
156 // Lands the user on the new machine right away; its composer shows the clone
157 // and holds sends until it finishes. A draft open on the source project moves
158 // over with whatever was typed in it.
159 const openClonedProject = (targetRef: ScopedProjectRef) => {
160 const drafts = useComposerDraftStore.getState();
161 const draftId = routeDraftId as DraftId | undefined;
162 const draft = draftId ? drafts.getDraftSession(draftId) : null;
163 if (
164 draftId &&
165 draft &&
166 !draft.promotedTo &&
167 draft.environmentId === request.projectRef.environmentId &&
168 draft.projectId === request.projectRef.projectId
169 ) {
170 drafts.setDraftThreadContext(draftId, {
171 projectRef: targetRef,
172 environmentSelection: "manual",
173 loadBalancedEnvironmentId: null,
174 });
175 return;
176 }
177 void handleNewThread(targetRef);
178 };
179
180 const submit = async () => {
181 if (!project || !target || submitting) return;
182 if (destinationPath.trim().length === 0) {
183 setError("Choose a folder on the other machine.");
184 return;
185 }
186 setSubmitting(true);
187 setError(null);
188 const projectId = newProjectId();
189 try {
190 await addProjectToMachine({
191 source: { environmentId: project.environmentId, cwd: project.workspaceRoot },
192 subdirectory: projectSubdirectory(
193 project.repositoryIdentity?.rootPath,
194 project.workspaceRoot,
195 ),
196 target: { environmentId: target.environmentId, label: target.label },
197 projectId,
198 title: project.title,
199 remoteUrl,
200 destinationPath: destinationPath.trim(),
201 files: files.filter((file) => selectedFiles.has(file.path)).map((file) => file.path),
202 });
203 close();
204 openClonedProject(scopeProjectRef(target.environmentId, projectId));
205 } catch (cause) {
206 setError(cause instanceof Error ? cause.message : "Could not start the clone.");
207 setSubmitting(false);
208 }
209 };
210
211 return (
212 <Dialog
213 open
214 onOpenChange={(open) => {
215 if (!open) close();
216 }}
217 >
218 <DialogPopup className="sm:max-w-xl">
219 <form
220 className="flex min-h-0 flex-col"
221 onSubmit={(event) => {
222 event.preventDefault();
223 void submit();
224 }}
225 >
226 <DialogHeader>
227 <DialogTitle>Add to another machine</DialogTitle>
228 <DialogDescription>
229 Clone {project?.repositoryIdentity?.displayName ?? project?.title} and bring the local
230 files git does not track.
231 </DialogDescription>
232 </DialogHeader>
233 <DialogPanel>
234 <div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-3">
235 <div className="flex min-w-0 flex-col gap-1">
236 <span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
237 <EnvironmentMachineIcon
238 kind={resolveEnvironmentMachineKind(source?.serverConfig ?? null)}
239 className="size-3.5 shrink-0"
240 />
241 <span className="truncate">{source?.label ?? "This machine"}</span>
242 </span>
243 <span className="flex min-w-0 font-mono text-muted-foreground text-xs">
244 <MiddleTruncate value={project?.workspaceRoot ?? ""} />
245 </span>
246 </div>
247 <div className="flex w-28 flex-col items-center gap-0.5 text-muted-foreground text-xs">
248 <span>git clone</span>
249 <span className="flex w-full items-center">
250 <span className="h-px flex-1 bg-border" />
251 <ArrowRightIcon className="-ms-1 size-3.5" aria-hidden />
252 </span>
253 <span>
254 {selectedFiles.size === 0
255 ? "no files"
256 : `+ ${selectedFiles.size} ${selectedFiles.size === 1 ? "file" : "files"}`}
257 </span>
258 </div>
259 <div className="flex min-w-0 flex-col gap-1">
260 {targets.length > 1 ? (
261 <Select
262 value={target?.environmentId ?? null}
263 onValueChange={(value) => {
264 if (value) setTargetId(value);
265 }}
266 items={targets.map((t) => ({ value: t.environmentId, label: t.label }))}
267 >
268 <SelectTrigger size="sm" aria-label="Machine to add the project to">
269 {target ? (
270 <EnvironmentMachineIcon kind={target.machine} className="size-3.5" />
271 ) : null}
272 <SelectValue />
273 </SelectTrigger>
274 <SelectPopup>
275 {targets.map((t) => (
276 <SelectItem key={t.environmentId} value={t.environmentId}>
277 <span className="inline-flex items-center gap-1.5">
278 <EnvironmentMachineIcon kind={t.machine} className="size-3" />
279 {t.label}
280 </span>
281 </SelectItem>
282 ))}
283 </SelectPopup>
284 </Select>
285 ) : (
286 <span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
287 {target ? (
288 <EnvironmentMachineIcon kind={target.machine} className="size-3.5 shrink-0" />
289 ) : null}
290 <span className="truncate">{target?.label ?? "No machine available"}</span>
291 </span>
292 )}
293 <span className="flex min-w-0 font-mono text-muted-foreground text-xs">
294 <MiddleTruncate value={destinationPath} />
295 </span>
296 </div>
297 </div>
298
299 <div className="flex flex-col gap-1.5">
300 <Label>Clone over</Label>
301 {sshUrl && httpsUrl ? (
302 <ToggleGroup
303 aria-label="Clone protocol"
304 value={protocol ? [protocol] : []}
305 onValueChange={(next) => {
306 const value = next[0];
307 if (value === "ssh" || value === "https") setProtocol(value);
308 }}
309 >
310 <Toggle value="ssh">SSH</Toggle>
311 <Toggle value="https">HTTPS</Toggle>
312 </ToggleGroup>
313 ) : null}
314 <span className="truncate font-mono text-muted-foreground text-xs">{remoteUrl}</span>
315 </div>
316
317 <div className="flex flex-col gap-1.5">
318 <Label htmlFor={`${id}-path`}>Folder on {target?.label ?? "the other machine"}</Label>
319 <Input
320 id={`${id}-path`}
321 value={destinationPath}
322 onChange={(event) => setPathOverride(event.target.value)}
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}