The best way to control Claude Code, Codex and more from any computer or phone

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