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