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 try {
190 const projectId = 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: newProjectId(),
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) =>
323 setPathOverride(resolvePastedPath(destinationPath, event.target.value))
324 }
325 spellCheck={false}
326 autoComplete="off"
327 />
328 </div>
329
330 {canListFiles ? (
331 <div className="flex flex-col gap-1.5">
332 <div className="flex items-center gap-2">
333 <Label className="flex-1">Copy ignored files</Label>
334 {copyable.length > 0 ? (
335 <>
336 <span className="text-muted-foreground text-xs">
337 {selectedFiles.size} of {files.length}
338 {selectedBytes > 0 ? ` · ${formatBytes(selectedBytes)}` : ""}
339 </span>
340 <Button
341 type="button"
342 variant="ghost"
343 size="xs"
344 onClick={() =>
345 setSelected(
346 selectedFiles.size === copyable.length
347 ? new Set()
348 : new Set(copyable.map((file) => file.path)),
349 )
350 }
351 >
352 {selectedFiles.size === copyable.length ? "None" : "All"}
353 </Button>
354 </>
355 ) : null}
356 </div>
357 {ignoredFiles.error ? (
358 <p className="text-destructive-foreground text-xs">{ignoredFiles.error}</p>
359 ) : files.length === 0 ? (
360 <p className="text-muted-foreground text-xs">
361 {ignoredFiles.isSuccess
362 ? "No ignored files to copy."
363 : "Finding ignored files…"}
364 </p>
365 ) : (
366 <div className="max-h-52 overflow-y-auto rounded-md border">
367 {files.map((file) => (
368 <IgnoredFileRow
369 key={file.path}
370 file={file}
371 checked={selectedFiles.has(file.path)}
372 onCheckedChange={(checked) => toggleFile(file.path, checked)}
373 />
374 ))}
375 </div>
376 )}
377 {ignoredFiles.data?.truncated ? (
378 <p className="text-muted-foreground text-xs">
379 Showing the first {files.length} files.
380 </p>
381 ) : null}
382 <p className="text-muted-foreground text-xs">
383 Files are copied after the clone finishes. Folders git ignores whole, like
384 node_modules, are left out.
385 </p>
386 </div>
387 ) : null}
388
389 {error ? <p className="text-destructive-foreground text-sm">{error}</p> : null}
390 </DialogPanel>
391 <DialogFooter>
392 <Button type="button" variant="outline" onClick={close}>
393 Cancel
394 </Button>
395 <Button type="submit" disabled={unavailable || submitting}>
396 {submitting ? "Starting…" : `Clone to ${target?.label ?? "machine"}`}
397 </Button>
398 </DialogFooter>
399 </form>
400 </DialogPopup>
401 </Dialog>
402 );
403}
404
405/**
406 * A project can be rooted below its repository's top folder. The clone lands
407 * at the top, so copied files keep the same path below it.
408 */
409function projectSubdirectory(repositoryRoot: string | undefined, workspaceRoot: string) {
410 if (!repositoryRoot) return "";
411 const prefix = repositoryRoot.replace(/[\\/]+$/, "");
412 const rest = workspaceRoot.slice(prefix.length);
413 return workspaceRoot.startsWith(prefix) && /^[\\/]/.test(rest)
414 ? rest.slice(1).replaceAll("\\", "/")
415 : "";
416}
417
418function defaultSelection(files: readonly ProjectIgnoredFile[]): ReadonlySet<string> {
419 return new Set(
420 files
421 .filter(
422 (file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES && isDefaultCopiedFile(file.path),
423 )
424 .map((file) => file.path),
425 );
426}
427
428function IgnoredFileRow({
429 file,
430 checked,
431 onCheckedChange,
432}: {
433 file: ProjectIgnoredFile;
434 checked: boolean;
435 onCheckedChange: (checked: boolean) => void;
436}) {
437 const tooLarge = file.byteLength > COPYABLE_FILE_MAX_BYTES;
438 return (
439 <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">
440 <Checkbox checked={checked} disabled={tooLarge} onCheckedChange={onCheckedChange} />
441 <span className="min-w-0 flex-1 truncate font-mono text-xs">{file.path}</span>
442 <span className="shrink-0 text-muted-foreground text-xs tabular-nums">
443 {tooLarge ? "Over 1 MB" : formatBytes(file.byteLength)}
444 </span>
445 </label>
446 );
447}