@devries-cameron20 / t3code-1 / commits / effb4337e5
Fork 0

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

feat(web,server): add a project to another machine from Run on, .env files included (#22180)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 20, 2026 at 00:33 UTC effb4337e58b1db215e8293f48bc110e6b2176a4
18 files changed +903 -10
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -141,6 +141,7 @@ export const RPC_REQUIRED_SCOPES = {
141 [WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
142 [WS_METHODS.subscribeProjectClones]: AuthOrchestrationReadScope,
143 [WS_METHODS.projectsListEntries]: AuthFilesystemReadScope,
144 + [WS_METHODS.projectsListIgnoredFiles]: AuthFilesystemReadScope,
145 [WS_METHODS.projectsReadFile]: AuthFilesystemReadScope,
146 [WS_METHODS.projectsSearchContents]: AuthFilesystemReadScope,
147 [WS_METHODS.projectsSearchEntries]: AuthFilesystemReadScope,
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -258,6 +258,7 @@ export const make = Effect.gen(function* () {
258 threadStop: true,
259 environmentIcon: true,
260 projectCloneTracking: true,
261 + ignoredFileListing: true,
262 ...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
263 ...(serverInstallation === null ? {} : { serverInstallation }),
264 ...(serverSelfUpdate === "boot-service" || desktopAppUpdate
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -137,6 +137,7 @@ const RPC_AGGREGATES = {
137 [WS_METHODS.projectCloneRetry]: "source-control",
138 [WS_METHODS.subscribeProjectClones]: "source-control",
139 [WS_METHODS.projectsListEntries]: "workspace",
140 + [WS_METHODS.projectsListIgnoredFiles]: "workspace",
141 [WS_METHODS.projectsReadFile]: "workspace",
142 [WS_METHODS.projectsSearchContents]: "workspace",
143 [WS_METHODS.projectsSearchEntries]: "workspace",
apps/server/src/workspace/WorkspaceEntries.test.ts
+35
@@ -349,6 +349,41 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {
349 );
350 });
351
352 + describe("listIgnoredFiles", () => {
353 + it.effect("lists ignored files with sizes and skips wholly ignored folders", () =>
354 + Effect.gen(function* () {
355 + const cwd = yield* makeTempDir({ git: true });
356 + yield* writeTextFile(cwd, ".gitignore", "node_modules/\n.env*\n");
357 + yield* writeTextFile(cwd, ".env", "A=1");
358 + yield* writeTextFile(cwd, "apps/web/index.ts", "y");
359 + yield* git(cwd, ["add", "apps/web/index.ts"]);
360 + yield* writeTextFile(cwd, "apps/web/.env.local", "B=22");
361 + yield* writeTextFile(cwd, "node_modules/pkg/index.js", "x");
362 +
363 + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
364 + expect(yield* workspaceEntries.listIgnoredFiles({ cwd })).toEqual({
365 + files: [
366 + { path: ".env", byteLength: 3 },
367 + { path: "apps/web/.env.local", byteLength: 4 },
368 + ],
369 + truncated: false,
370 + });
371 + }),
372 + );
373 +
374 + it.effect("returns nothing outside a git repository", () =>
375 + Effect.gen(function* () {
376 + const cwd = yield* makeTempDir();
377 + yield* writeTextFile(cwd, ".env", "A=1");
378 + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
379 + expect(yield* workspaceEntries.listIgnoredFiles({ cwd })).toEqual({
380 + files: [],
381 + truncated: false,
382 + });
383 + }),
384 + );
385 + });
386 +
387 describe("search", () => {
388 it.effect("returns files and directories relative to cwd", () =>
389 Effect.gen(function* () {
apps/server/src/workspace/WorkspaceEntries.ts
+58 -1
@@ -14,6 +14,8 @@ import type {
14 ProjectEntry,
15 ProjectListEntriesInput,
16 ProjectListEntriesResult,
17 + ProjectListIgnoredFilesInput,
18 + ProjectListIgnoredFilesResult,
19 ProjectSearchContentsInput,
20 ProjectSearchContentsResult,
21 ProjectSearchEntriesInput,
@@ -99,6 +101,9 @@ export class WorkspaceEntries extends Context.Service<
101 readonly search: (
102 input: ProjectSearchEntriesInput,
103 ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
104 + readonly listIgnoredFiles: (
105 + input: ProjectListIgnoredFilesInput,
106 + ) => Effect.Effect<ProjectListIgnoredFilesResult, WorkspaceEntriesError>;
107 readonly searchContents: (
108 input: ProjectSearchContentsInput,
109 ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;
@@ -106,6 +111,9 @@ export class WorkspaceEntries extends Context.Service<
111 }
112 >()("t3/workspace/WorkspaceEntries") {}
113
114 +/** Ignored files offered for copying; more than this is a build folder, not config. */
115 +const IGNORED_FILES_LIMIT = 200;
116 +
117 /** Paths sent to one `git check-ignore` call when labelling a folder's children. */
118 const IGNORE_CHECK_CHUNK_SIZE = 1000;
119
@@ -388,7 +396,56 @@ export const make = Effect.gen(function* () {
396 },
397 );
398
391 - return WorkspaceEntries.of({ browse, list, refresh, search, searchContents });
399 + const listIgnoredFiles: WorkspaceEntries["Service"]["listIgnoredFiles"] = Effect.fn(
400 + "WorkspaceEntries.listIgnoredFiles",
401 + )(function* (input) {
402 + const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
403 + // `--directory` reports a folder holding nothing but ignored files as one
404 + // `name/` entry, which is how `node_modules` and build output drop out.
405 + const result = yield* vcsProcess
406 + .run({
407 + operation: "WorkspaceEntries.listIgnoredFiles",
408 + command: "git",
409 + args: [
410 + "-c",
411 + "core.fsmonitor=false",
412 + "ls-files",
413 + "--others",
414 + "--ignored",
415 + "--exclude-standard",
416 + "--directory",
417 + "--no-empty-directory",
418 + "-z",
419 + ],
420 + cwd: normalizedCwd,
421 + allowNonZeroExit: true,
422 + timeoutMs: 10_000,
423 + maxOutputBytes: 4 * 1024 * 1024,
424 + })
425 + .pipe(Effect.orElseSucceed(() => undefined));
426 + if (!result || result.exitCode !== 0) return { files: [], truncated: false };
427 + const paths = result.stdout
428 + .split("\0")
429 + .filter((entry) => entry.length > 0 && !entry.endsWith("/"))
430 + .toSorted();
431 + const files = yield* Effect.promise(() =>
432 + Promise.all(
433 + paths.slice(0, IGNORED_FILES_LIMIT).map(async (relativePath) => {
434 + // lstat: a symlink usually points outside the workspace, where reads refuse to go.
435 + const stat = await NodeFSP.lstat(path.join(normalizedCwd, relativePath)).catch(
436 + () => null,
437 + );
438 + return stat?.isFile() ? { path: relativePath, byteLength: stat.size } : null;
439 + }),
440 + ),
441 + );
442 + return {
443 + files: files.filter((file) => file !== null),
444 + truncated: paths.length > IGNORED_FILES_LIMIT,
445 + };
446 + });
447 +
448 + return WorkspaceEntries.of({ browse, list, listIgnoredFiles, refresh, search, searchContents });
449 });
450
451 export const layer = Layer.effect(WorkspaceEntries, make).pipe(
apps/server/src/ws.ts
+16
@@ -1249,6 +1249,7 @@ export const layerWsRpc = (
1249 const projectCloneTracker = yield* ProjectCloneTracker.ProjectCloneTracker;
1250 const repositoryIdentityResolver =
1251 yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
1252 + const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService;
1253 const agentSessionScanner = yield* AgentSessionScanner.AgentSessionScanner;
1254 const agentSessionImporter = yield* AgentSessionImporter.AgentSessionImporter;
1255 const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery;
@@ -2571,6 +2572,10 @@ export const layerWsRpc = (
2572 }),
2573 ),
2574 Effect.andThen(refreshGitStatus(project.workspaceRoot)),
2575 + // The folder was empty when the project was created, so the cached
2576 + // enrichment says "no repository" and clients cannot group it yet.
2577 + Effect.andThen(projectEnrichment.invalidate([project.workspaceRoot])),
2578 + Effect.andThen(projectEnrichment.request(project.workspaceRoot)),
2579 Effect.ignoreCause({ log: true }),
2580 ),
2581 }),
@@ -2635,6 +2640,17 @@ export const layerWsRpc = (
2640 }),
2641 ),
2642 ),
2643 + [WS_METHODS.projectsListIgnoredFiles]: (input) =>
2644 + workspaceEntries.listIgnoredFiles(input).pipe(
2645 + Effect.mapError(
2646 + (cause) =>
2647 + new ProjectListEntriesError({
2648 + ...input,
2649 + ...projectEntriesFailureContext(cause),
2650 + cause,
2651 + }),
2652 + ),
2653 + ),
2654 [WS_METHODS.projectsReadFile]: (input) =>
2655 workspaceFileSystem.readFile(input).pipe(
2656 Effect.mapError(
apps/web/src/components/AddProjectToMachineDialog.tsx new
+394
@@ -0,0 +1,394 @@
1 +import {
2 + getAddProjectInitialQuery,
3 + getCloneDestinationPath,
4 + getCloneDirectoryName,
5 +} from "@t3tools/client-runtime/operations/projects";
6 +import {
7 + type EnvironmentId,
8 + type ProjectIgnoredFile,
9 + type ScopedProjectRef,
10 + resolveEnvironmentMachineKind,
11 +} from "@t3tools/contracts";
12 +import { ArrowRightIcon } from "lucide-react";
13 +import { useEffect, useId, useState } from "react";
14 +import { create } from "zustand";
15 +
16 +import { useAddProjectTargets } from "../hooks/useAddProjectTargets";
17 +import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments";
18 +import {
19 + COPYABLE_FILE_MAX_BYTES,
20 + type CloneProtocol,
21 + addProjectToMachine,
22 + cloneUrlForProtocol,
23 + cloneUrlProtocol,
24 + isDefaultCopiedFile,
25 +} from "../lib/addProjectToMachine";
26 +import { formatBytes } from "../lib/formatBytes";
27 +import { newProjectId } from "../lib/utils";
28 +import { useProject } from "../state/entities";
29 +import { useEnvironments } from "../state/environments";
30 +import { projectEnvironment } from "../state/projects";
31 +import { useEnvironmentQuery } from "../state/query";
32 +import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
33 +import { Button } from "./ui/button";
34 +import { Checkbox } from "./ui/checkbox";
35 +import {
36 + Dialog,
37 + DialogDescription,
38 + DialogFooter,
39 + DialogHeader,
40 + DialogPanel,
41 + DialogPopup,
42 + DialogTitle,
43 +} from "./ui/dialog";
44 +import { Input } from "./ui/input";
45 +import { Label } from "./ui/label";
46 +import { MiddleTruncate } from "./ui/middle-truncate";
47 +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
48 +import { Toggle, ToggleGroup } from "./ui/toggle-group";
49 +
50 +interface AddProjectToMachineRequest {
51 + readonly projectRef: ScopedProjectRef;
52 + readonly targetEnvironmentId: EnvironmentId | null;
53 +}
54 +
55 +const useRequest = create<{ request: AddProjectToMachineRequest | null }>(() => ({
56 + request: null,
57 +}));
58 +
59 +/** Opens the dialog that clones a project onto another connected machine. */
60 +export function openAddProjectToMachine(request: AddProjectToMachineRequest) {
61 + useRequest.setState({ request });
62 +}
63 +
64 +const close = () => useRequest.setState({ request: null });
65 +
66 +export function AddProjectToMachineDialogHost() {
67 + const request = useRequest((state) => state.request);
68 + return request ? <AddProjectToMachineDialog request={request} /> : null;
69 +}
70 +
71 +function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRequest }) {
72 + const id = useId();
73 + const project = useProject(request.projectRef);
74 + const { environments } = useEnvironments();
75 + const targets = useAddProjectTargets(project, useLogicalProjectEnvironments(project, false));
76 + const [targetId, setTargetId] = useState(request.targetEnvironmentId);
77 + const target = targets.find((t) => t.environmentId === targetId) ?? targets[0] ?? null;
78 + const source = environments.find((env) => env.environmentId === request.projectRef.environmentId);
79 + const sourceUrl = project?.repositoryIdentity?.locator.remoteUrl ?? "";
80 + const [protocol, setProtocol] = useState<CloneProtocol | null>(() => cloneUrlProtocol(sourceUrl));
81 + const sshUrl = cloneUrlForProtocol(sourceUrl, "ssh");
82 + const httpsUrl = cloneUrlForProtocol(sourceUrl, "https");
83 + const remoteUrl =
84 + (protocol === "ssh" ? sshUrl : protocol === "https" ? httpsUrl : null) ?? sourceUrl;
85 +
86 + const targetEnvironment = environments.find((env) => env.environmentId === target?.environmentId);
87 + const defaultPath = getCloneDestinationPath(
88 + getAddProjectInitialQuery(targetEnvironment?.serverConfig?.settings.addProjectBaseDirectory),
89 + getCloneDirectoryName(sourceUrl),
90 + );
91 + const [pathOverride, setPathOverride] = useState<string | null>(null);
92 + const destinationPath = pathOverride ?? defaultPath;
93 +
94 + const canListFiles = source?.serverConfig?.environment.capabilities.ignoredFileListing === true;
95 + const ignoredFiles = useEnvironmentQuery(
96 + project && canListFiles
97 + ? projectEnvironment.listIgnoredFiles({
98 + environmentId: project.environmentId,
99 + input: { cwd: project.workspaceRoot },
100 + })
101 + : null,
102 + );
103 + const files = ignoredFiles.data?.files ?? [];
104 + const [selected, setSelected] = useState<ReadonlySet<string> | null>(null);
105 + const selectedFiles = selected ?? defaultSelection(files);
106 + const copyable = files.filter((file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES);
107 + const selectedBytes = files
108 + .filter((file) => selectedFiles.has(file.path))
109 + .reduce((total, file) => total + file.byteLength, 0);
110 +
111 + const [submitting, setSubmitting] = useState(false);
112 + const [error, setError] = useState<string | null>(null);
113 +
114 + // The project or every target can vanish while the dialog is open. Submitting
115 + // before the file list loads would silently skip the default .env copies.
116 + const unavailable =
117 + project === null ||
118 + target === null ||
119 + (canListFiles && ignoredFiles.data === null && ignoredFiles.error === null);
120 + useEffect(() => {
121 + if (project === null) close();
122 + }, [project]);
123 +
124 + const toggleFile = (path: string, checked: boolean) => {
125 + const next = new Set(selectedFiles);
126 + if (checked) next.add(path);
127 + else next.delete(path);
128 + setSelected(next);
129 + };
130 +
131 + const submit = async () => {
132 + if (!project || !target || submitting) return;
133 + if (destinationPath.trim().length === 0) {
134 + setError("Choose a folder on the other machine.");
135 + return;
136 + }
137 + setSubmitting(true);
138 + setError(null);
139 + try {
140 + await addProjectToMachine({
141 + source: { environmentId: project.environmentId, cwd: project.workspaceRoot },
142 + subdirectory: projectSubdirectory(
143 + project.repositoryIdentity?.rootPath,
144 + project.workspaceRoot,
145 + ),
146 + target: { environmentId: target.environmentId, label: target.label },
147 + projectId: newProjectId(),
148 + title: project.title,
149 + remoteUrl,
150 + destinationPath: destinationPath.trim(),
151 + files: files.filter((file) => selectedFiles.has(file.path)).map((file) => file.path),
152 + });
153 + close();
154 + } catch (cause) {
155 + setError(cause instanceof Error ? cause.message : "Could not start the clone.");
156 + setSubmitting(false);
157 + }
158 + };
159 +
160 + return (
161 + <Dialog
162 + open
163 + onOpenChange={(open) => {
164 + if (!open) close();
165 + }}
166 + >
167 + <DialogPopup className="sm:max-w-xl">
168 + <form
169 + className="flex min-h-0 flex-col"
170 + onSubmit={(event) => {
171 + event.preventDefault();
172 + void submit();
173 + }}
174 + >
175 + <DialogHeader>
176 + <DialogTitle>Add to another machine</DialogTitle>
177 + <DialogDescription>
178 + Clone {project?.repositoryIdentity?.displayName ?? project?.title} and bring the local
179 + files git does not track.
180 + </DialogDescription>
181 + </DialogHeader>
182 + <DialogPanel>
183 + <div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-3">
184 + <div className="flex min-w-0 flex-col gap-1">
185 + <span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
186 + <EnvironmentMachineIcon
187 + kind={resolveEnvironmentMachineKind(source?.serverConfig ?? null)}
188 + className="size-3.5 shrink-0"
189 + />
190 + <span className="truncate">{source?.label ?? "This machine"}</span>
191 + </span>
192 + <span className="flex min-w-0 font-mono text-muted-foreground text-xs">
193 + <MiddleTruncate value={project?.workspaceRoot ?? ""} />
194 + </span>
195 + </div>
196 + <div className="flex w-28 flex-col items-center gap-0.5 text-muted-foreground text-xs">
197 + <span>git clone</span>
198 + <span className="flex w-full items-center">
199 + <span className="h-px flex-1 bg-border" />
200 + <ArrowRightIcon className="-ms-1 size-3.5" aria-hidden />
201 + </span>
202 + <span>
203 + {selectedFiles.size === 0
204 + ? "no files"
205 + : `+ ${selectedFiles.size} ${selectedFiles.size === 1 ? "file" : "files"}`}
206 + </span>
207 + </div>
208 + <div className="flex min-w-0 flex-col gap-1">
209 + {targets.length > 1 ? (
210 + <Select
211 + value={target?.environmentId ?? null}
212 + onValueChange={(value) => {
213 + if (value) setTargetId(value);
214 + }}
215 + items={targets.map((t) => ({ value: t.environmentId, label: t.label }))}
216 + >
217 + <SelectTrigger size="sm" aria-label="Machine to add the project to">
218 + {target ? (
219 + <EnvironmentMachineIcon kind={target.machine} className="size-3.5" />
220 + ) : null}
221 + <SelectValue />
222 + </SelectTrigger>
223 + <SelectPopup>
224 + {targets.map((t) => (
225 + <SelectItem key={t.environmentId} value={t.environmentId}>
226 + <span className="inline-flex items-center gap-1.5">
227 + <EnvironmentMachineIcon kind={t.machine} className="size-3" />
228 + {t.label}
229 + </span>
230 + </SelectItem>
231 + ))}
232 + </SelectPopup>
233 + </Select>
234 + ) : (
235 + <span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
236 + {target ? (
237 + <EnvironmentMachineIcon kind={target.machine} className="size-3.5 shrink-0" />
238 + ) : null}
239 + <span className="truncate">{target?.label ?? "No machine available"}</span>
240 + </span>
241 + )}
242 + <span className="flex min-w-0 font-mono text-muted-foreground text-xs">
243 + <MiddleTruncate value={destinationPath} />
244 + </span>
245 + </div>
246 + </div>
247 +
248 + <div className="flex flex-col gap-1.5">
249 + <Label>Clone over</Label>
250 + {sshUrl && httpsUrl ? (
251 + <ToggleGroup
252 + aria-label="Clone protocol"
253 + value={protocol ? [protocol] : []}
254 + onValueChange={(next) => {
255 + const value = next[0];
256 + if (value === "ssh" || value === "https") setProtocol(value);
257 + }}
258 + >
259 + <Toggle value="ssh">SSH</Toggle>
260 + <Toggle value="https">HTTPS</Toggle>
261 + </ToggleGroup>
262 + ) : null}
263 + <span className="truncate font-mono text-muted-foreground text-xs">{remoteUrl}</span>
264 + </div>
265 +
266 + <div className="flex flex-col gap-1.5">
267 + <Label htmlFor={`${id}-path`}>Folder on {target?.label ?? "the other machine"}</Label>
268 + <Input
269 + id={`${id}-path`}
270 + value={destinationPath}
271 + onChange={(event) => setPathOverride(event.target.value)}
272 + spellCheck={false}
273 + autoComplete="off"
274 + />
275 + </div>
276 +
277 + {canListFiles ? (
278 + <div className="flex flex-col gap-1.5">
279 + <div className="flex items-center gap-2">
280 + <Label className="flex-1">Copy ignored files</Label>
281 + {copyable.length > 0 ? (
282 + <>
283 + <span className="text-muted-foreground text-xs">
284 + {selectedFiles.size} of {files.length}
285 + {selectedBytes > 0 ? ` · ${formatBytes(selectedBytes)}` : ""}
286 + </span>
287 + <Button
288 + type="button"
289 + variant="ghost"
290 + size="xs"
291 + onClick={() =>
292 + setSelected(
293 + selectedFiles.size === copyable.length
294 + ? new Set()
295 + : new Set(copyable.map((file) => file.path)),
296 + )
297 + }
298 + >
299 + {selectedFiles.size === copyable.length ? "None" : "All"}
300 + </Button>
301 + </>
302 + ) : null}
303 + </div>
304 + {ignoredFiles.error ? (
305 + <p className="text-destructive-foreground text-xs">{ignoredFiles.error}</p>
306 + ) : files.length === 0 ? (
307 + <p className="text-muted-foreground text-xs">
308 + {ignoredFiles.isSuccess
309 + ? "No ignored files to copy."
310 + : "Finding ignored files…"}
311 + </p>
312 + ) : (
313 + <div className="max-h-52 overflow-y-auto rounded-md border">
314 + {files.map((file) => (
315 + <IgnoredFileRow
316 + key={file.path}
317 + file={file}
318 + checked={selectedFiles.has(file.path)}
319 + onCheckedChange={(checked) => toggleFile(file.path, checked)}
320 + />
321 + ))}
322 + </div>
323 + )}
324 + {ignoredFiles.data?.truncated ? (
325 + <p className="text-muted-foreground text-xs">
326 + Showing the first {files.length} files.
327 + </p>
328 + ) : null}
329 + <p className="text-muted-foreground text-xs">
330 + Files are copied after the clone finishes. Folders git ignores whole, like
331 + node_modules, are left out.
332 + </p>
333 + </div>
334 + ) : null}
335 +
336 + {error ? <p className="text-destructive-foreground text-sm">{error}</p> : null}
337 + </DialogPanel>
338 + <DialogFooter>
339 + <Button type="button" variant="outline" onClick={close}>
340 + Cancel
341 + </Button>
342 + <Button type="submit" disabled={unavailable || submitting}>
343 + {submitting ? "Starting…" : `Clone to ${target?.label ?? "machine"}`}
344 + </Button>
345 + </DialogFooter>
346 + </form>
347 + </DialogPopup>
348 + </Dialog>
349 + );
350 +}
351 +
352 +/**
353 + * A project can be rooted below its repository's top folder. The clone lands
354 + * at the top, so copied files keep the same path below it.
355 + */
356 +function projectSubdirectory(repositoryRoot: string | undefined, workspaceRoot: string) {
357 + if (!repositoryRoot) return "";
358 + const prefix = repositoryRoot.replace(/[\\/]+$/, "");
359 + const rest = workspaceRoot.slice(prefix.length);
360 + return workspaceRoot.startsWith(prefix) && /^[\\/]/.test(rest)
361 + ? rest.slice(1).replaceAll("\\", "/")
362 + : "";
363 +}
364 +
365 +function defaultSelection(files: readonly ProjectIgnoredFile[]): ReadonlySet<string> {
366 + return new Set(
367 + files
368 + .filter(
369 + (file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES && isDefaultCopiedFile(file.path),
370 + )
371 + .map((file) => file.path),
372 + );
373 +}
374 +
375 +function IgnoredFileRow({
376 + file,
377 + checked,
378 + onCheckedChange,
379 +}: {
380 + file: ProjectIgnoredFile;
381 + checked: boolean;
382 + onCheckedChange: (checked: boolean) => void;
383 +}) {
384 + const tooLarge = file.byteLength > COPYABLE_FILE_MAX_BYTES;
385 + return (
386 + <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">
387 + <Checkbox checked={checked} disabled={tooLarge} onCheckedChange={onCheckedChange} />
388 + <span className="min-w-0 flex-1 truncate font-mono text-xs">{file.path}</span>
389 + <span className="shrink-0 text-muted-foreground text-xs tabular-nums">
390 + {tooLarge ? "Over 1 MB" : formatBytes(file.byteLength)}
391 + </span>
392 + </label>
393 + );
394 +}
apps/web/src/components/BranchToolbar.logic.ts
+4
@@ -22,6 +22,10 @@ export interface EnvironmentOption {
22 machine: EnvironmentMachineKind;
23 }
24
25 +/** "Add to another machine" stays muted until hovered: easy to find, quieter than the machines. */
26 +export const ADD_TO_MACHINE_LABEL_CLASS =
27 + "flex min-w-0 items-center gap-1.5 opacity-55 in-data-highlighted:opacity-100 in-data-popup-open:opacity-100";
28 +
29 export const EnvMode = Schema.Literals(["local", "worktree"]);
30 export type EnvMode = typeof EnvMode.Type;
31
apps/web/src/components/BranchToolbar.tsx
+52 -4
@@ -10,6 +10,7 @@ import {
10 FolderGit2Icon,
11 FolderGitIcon,
12 FolderIcon,
13 + PlusIcon,
14 ScaleIcon,
15 } from "lucide-react";
16 import {
@@ -28,6 +29,7 @@ import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
29 import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
30 import { useProject, useThreadShellsForProjectRefs } from "../state/entities";
31 import {
32 + ADD_TO_MACHINE_LABEL_CLASS,
33 type EnvMode,
34 type EnvironmentOption,
35 resolveContextStripLabelsCompact,
@@ -43,6 +45,8 @@ import {
45 type BranchToolbarBranchSelectorHandle,
46 } from "./BranchToolbarBranchSelector";
47 import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
48 +import { openAddProjectToMachine } from "./AddProjectToMachineDialog";
49 +import { type AddProjectTarget, useAddProjectTargets } from "../hooks/useAddProjectTargets";
50 import type { PendingServerUpdate } from "./ServerUpdateAction";
51 import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector";
52 import { PreviousWorktreeItemContent } from "./PreviousWorktreeItemContent";
@@ -56,10 +60,14 @@ import {
60 Menu,
61 MenuGroup,
62 MenuGroupLabel,
63 + MenuItem,
64 MenuPopup,
65 MenuRadioGroup,
66 MenuRadioItem,
67 MenuSeparator,
68 + MenuSub,
69 + MenuSubPopup,
70 + MenuSubTrigger,
71 MenuTrigger,
72 } from "./ui/menu";
73 import { Separator } from "./ui/separator";
@@ -162,6 +170,8 @@ interface RunContextSelectorProps {
170 previousWorktreeLabel: string | null;
171 previousWorktreeBranch: string | null;
172 onUsePreviousWorktree: () => void;
173 + addTargets: readonly AddProjectTarget[];
174 + onAddToMachine: (environmentId: EnvironmentId) => void;
175 }
176
177 const RunContextSelector = memo(function RunContextSelector({
@@ -183,6 +193,8 @@ const RunContextSelector = memo(function RunContextSelector({
193 previousWorktreeLabel,
194 previousWorktreeBranch,
195 onUsePreviousWorktree,
196 + addTargets,
197 + onAddToMachine,
198 }: RunContextSelectorProps) {
199 const composerFloatingLayerProps = useComposerMenuProps();
200 const activeEnvironment =
@@ -318,7 +330,8 @@ const RunContextSelector = memo(function RunContextSelector({
330 }
331 {...(!isPanel ? composerFloatingLayerProps : {})}
332 >
321 - {showEnvironmentPicker && availableEnvironments && onEnvironmentChange ? (
333 + {availableEnvironments &&
334 + ((showEnvironmentPicker && onEnvironmentChange) || addTargets.length > 0) ? (
335 <>
336 <MenuGroup>
337 <MenuGroupLabel>Run on</MenuGroupLabel>
@@ -327,7 +340,7 @@ const RunContextSelector = memo(function RunContextSelector({
340 onValueChange={(value) =>
341 value === "auto"
342 ? onAutoEnvironment?.()
330 - : onEnvironmentChange(value as EnvironmentId)
343 + : onEnvironmentChange?.(value as EnvironmentId)
344 }
345 >
346 {onAutoEnvironment && (
@@ -350,7 +363,9 @@ const RunContextSelector = memo(function RunContextSelector({
363 {availableEnvironments.map((env) => (
364 <MenuRadioItem
365 key={env.environmentId}
353 - disabled={envLocked}
366 + disabled={
367 + envLocked || (!onEnvironmentChange && env.environmentId !== environmentId)
368 + }
369 value={env.environmentId}
370 closeOnClick
371 >
@@ -361,6 +376,29 @@ const RunContextSelector = memo(function RunContextSelector({
376 </MenuRadioItem>
377 ))}
378 </MenuRadioGroup>
379 + {addTargets.length > 0 ? (
380 + <MenuSub>
381 + <MenuSubTrigger>
382 + <span className={ADD_TO_MACHINE_LABEL_CLASS}>
383 + <PlusIcon className="size-3" />
384 + <span className="min-w-0 truncate">Add to another machine</span>
385 + </span>
386 + </MenuSubTrigger>
387 + <MenuSubPopup {...(!isPanel ? composerFloatingLayerProps : {})}>
388 + {addTargets.map((target) => (
389 + <MenuItem
390 + key={target.environmentId}
391 + onClick={() => onAddToMachine(target.environmentId)}
392 + >
393 + <span className="flex min-w-0 items-center gap-1.5">
394 + <EnvironmentMachineIcon kind={target.machine} className="size-3" />
395 + <span className="min-w-0 truncate">{target.label}</span>
396 + </span>
397 + </MenuItem>
398 + ))}
399 + </MenuSubPopup>
400 + </MenuSub>
401 + ) : null}
402 </MenuGroup>
403 <MenuSeparator />
404 </>
@@ -649,7 +687,11 @@ export const BranchToolbar = memo(function BranchToolbar({
687 ],
688 );
689
652 - const hasMultipleEnvironments = (availableEnvironments?.length ?? 0) > 1;
690 + const addTargets = useAddProjectTargets(activeProject, availableEnvironments);
691 + const onAddToMachine = (targetEnvironmentId: EnvironmentId | null) =>
692 + openAddProjectToMachine({ projectRef: activeProjectRef, targetEnvironmentId });
693 + // A project on one machine still gets the picker when it can be added to another.
694 + const hasMultipleEnvironments = (availableEnvironments?.length ?? 0) > 1 || addTargets.length > 0;
695 const showEnvironmentPicker = hasMultipleEnvironments && onEnvironmentChange !== undefined;
696 const activeEnvironmentOption =
697 availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
@@ -688,6 +730,8 @@ export const BranchToolbar = memo(function BranchToolbar({
730 previousWorktreeLabel={previousWorktreeLabel}
731 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
732 onUsePreviousWorktree={onUsePreviousWorktree}
733 + addTargets={addTargets}
734 + onAddToMachine={onAddToMachine}
735 />
736 ) : null}
737 {panelSection !== "workspace" ? (
@@ -731,6 +775,7 @@ export const BranchToolbar = memo(function BranchToolbar({
775 environmentId={environmentId}
776 availableEnvironments={availableEnvironments}
777 {...(showEnvironmentPicker ? { onEnvironmentChange } : {})}
778 + {...(addTargets.length > 0 ? { onAddToMachine: () => onAddToMachine(null) } : {})}
779 serverUpdate={serverUpdate}
780 />
781 ) : null}
@@ -753,6 +798,8 @@ export const BranchToolbar = memo(function BranchToolbar({
798 previousWorktreeLabel={previousWorktreeLabel}
799 previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
800 onUsePreviousWorktree={onUsePreviousWorktree}
801 + addTargets={addTargets}
802 + onAddToMachine={onAddToMachine}
803 />
804 </div>
805 ) : null}
@@ -774,6 +821,7 @@ export const BranchToolbar = memo(function BranchToolbar({
821 environmentId={environmentId}
822 availableEnvironments={availableEnvironments}
823 {...(showEnvironmentPicker ? { onEnvironmentChange } : {})}
824 + {...(addTargets.length > 0 ? { onAddToMachine: () => onAddToMachine(null) } : {})}
825 />
826 ) : null}
827 {showGitControls ? (
apps/web/src/components/BranchToolbarEnvironmentSelector.tsx
+23 -5
@@ -5,10 +5,10 @@ import { useAtomValue } from "@effect/atom-react";
5 import { shortcutLabelForCommand } from "../keybindings";
6 import { primaryServerKeybindingsAtom } from "../state/server";
7 import type { EnvironmentId } from "@t3tools/contracts";
8 -import { CircleArrowUpIcon, ScaleIcon } from "lucide-react";
8 +import { CircleArrowUpIcon, PlusIcon, ScaleIcon } from "lucide-react";
9 import { memo } from "react";
10
11 -import type { EnvironmentOption } from "./BranchToolbar.logic";
11 +import { ADD_TO_MACHINE_LABEL_CLASS, type EnvironmentOption } from "./BranchToolbar.logic";
12 import {
13 ServerUpdateAction,
14 type PendingServerUpdate,
@@ -32,12 +32,14 @@ interface BranchToolbarEnvironmentSelectorProps {
32 environmentId: EnvironmentId;
33 availableEnvironments: readonly EnvironmentOption[];
34 onEnvironmentChange?: (environmentId: EnvironmentId) => void;
35 + onAddToMachine?: (() => void) | undefined;
36 serverUpdate?: PendingServerUpdate | null;
37 }
38
39 // Action values cannot collide with server-minted environment IDs.
40 const AUTO_VALUE = "action:auto";
41 const UPDATE_VALUE = "action:update";
42 +const ADD_MACHINE_VALUE = "action:add-machine";
43 const environmentValue = (id: EnvironmentId) => `env:${id}`;
44
45 export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector(
@@ -60,6 +62,7 @@ function EnvironmentSelector({
62 environmentId,
63 availableEnvironments,
64 onEnvironmentChange,
65 + onAddToMachine,
66 serverUpdate,
67 updateControl,
68 }: BranchToolbarEnvironmentSelectorProps & {
@@ -84,6 +87,7 @@ function EnvironmentSelector({
87 ...(serverUpdate && updateControl
88 ? [{ value: UPDATE_VALUE, label: `${updateControl.label} ${serverUpdate.serverLabel}` }]
89 : []),
90 + ...(onAddToMachine ? [{ value: ADD_MACHINE_VALUE, label: "Add to another machine" }] : []),
91 ];
92 const updateTooltip = serverUpdate
93 ? `${serverUpdate.serverLabel} ${serverUpdate.serverVersion} → ${serverUpdate.targetVersion}. ${
@@ -114,7 +118,7 @@ function EnvironmentSelector({
118 // the glass seam joining it to the composer assumes a fixed strip height, so
119 // a shorter label would drag the seam out of line whenever this label is the
120 // only thing in the strip.
117 - if (envLocked || onEnvironmentChange === undefined) {
121 + if (envLocked || (onEnvironmentChange === undefined && onAddToMachine === undefined)) {
122 const lockedRow = updateControl ? (
123 <ComposerControl
124 size="xs"
@@ -161,10 +165,12 @@ function EnvironmentSelector({
165 onValueChange={(value) => {
166 if (value === UPDATE_VALUE) {
167 updateControl?.onClick();
168 + } else if (value === ADD_MACHINE_VALUE) {
169 + onAddToMachine?.();
170 } else if (value === AUTO_VALUE) {
171 onAutoEnvironment?.();
172 } else if (value?.startsWith("env:")) {
167 - onEnvironmentChange(value.slice(4) as EnvironmentId);
173 + onEnvironmentChange?.(value.slice(4) as EnvironmentId);
174 }
175 }}
176 items={environmentItems}
@@ -212,7 +218,11 @@ function EnvironmentSelector({
218 </SelectItem>
219 )}
220 {availableEnvironments.map((env) => (
215 - <SelectItem key={env.environmentId} value={environmentValue(env.environmentId)}>
221 + <SelectItem
222 + key={env.environmentId}
223 + value={environmentValue(env.environmentId)}
224 + disabled={onEnvironmentChange === undefined && env.environmentId !== environmentId}
225 + >
226 <span className="inline-flex items-center gap-1.5">
227 {serverUpdate?.environmentId === env.environmentId ? (
228 <CircleArrowUpIcon aria-hidden="true" className="size-3" />
@@ -223,6 +233,14 @@ function EnvironmentSelector({
233 </span>
234 </SelectItem>
235 ))}
236 + {onAddToMachine ? (
237 + <SelectItem value={ADD_MACHINE_VALUE}>
238 + <span className={ADD_TO_MACHINE_LABEL_CLASS}>
239 + <PlusIcon aria-hidden="true" className="size-3" />
240 + Add to another machine
241 + </span>
242 + </SelectItem>
243 + ) : null}
244 </SelectGroup>
245 {serverUpdate && updateControl ? (
246 <SelectGroup>
apps/web/src/hooks/useAddProjectTargets.ts new
+41
@@ -0,0 +1,41 @@
1 +import { canCreateProjectInEnvironment } from "@t3tools/client-runtime/operations/projects";
2 +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
3 +import { AuthSourceControlWriteScope, resolveEnvironmentMachineKind } from "@t3tools/contracts";
4 +
5 +import type { EnvironmentOption } from "../components/BranchToolbar.logic";
6 +import { useEnvironments } from "../state/environments";
7 +import { useEnvironmentsWithScope } from "../state/session";
8 +
9 +export type AddProjectTarget = Pick<EnvironmentOption, "environmentId" | "label" | "machine">;
10 +
11 +/**
12 + * Connected machines that do not have the project yet and can clone it.
13 + * `projectEnvironments` is the project's current machine list, from
14 + * `useLogicalProjectEnvironments`. Projects without a git remote get none.
15 + */
16 +export function useAddProjectTargets(
17 + project: EnvironmentProject | null,
18 + projectEnvironments: readonly Pick<EnvironmentOption, "environmentId">[] | undefined,
19 +): readonly AddProjectTarget[] {
20 + const { environments } = useEnvironments();
21 + const canClone = useEnvironmentsWithScope(environments, AuthSourceControlWriteScope);
22 + if (!project?.repositoryIdentity?.locator.remoteUrl) return [];
23 + const hasProject = new Set([
24 + project.environmentId,
25 + ...(projectEnvironments ?? []).map((env) => env.environmentId),
26 + ]);
27 + return environments
28 + .filter(
29 + (environment) =>
30 + !hasProject.has(environment.environmentId) &&
31 + canClone.has(environment.environmentId) &&
32 + canCreateProjectInEnvironment(environment.connection.phase) &&
33 + environment.serverConfig?.environment.capabilities.projectCloneTracking === true,
34 + )
35 + .map((environment) => ({
36 + environmentId: environment.environmentId,
37 + label: environment.label,
38 + machine: resolveEnvironmentMachineKind(environment.serverConfig),
39 + }))
40 + .toSorted((a, b) => a.label.localeCompare(b.label));
41 +}
apps/web/src/lib/addProjectToMachine.test.ts new
+46
@@ -0,0 +1,46 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { cloneUrlForProtocol, cloneUrlProtocol, isDefaultCopiedFile } from "./addProjectToMachine";
4 +
5 +describe("cloneUrlForProtocol", () => {
6 + it("switches between scp-style SSH and HTTPS", () => {
7 + expect(cloneUrlForProtocol("git@github.com:pingdotgg/t3code.git", "https")).toBe(
8 + "https://github.com/pingdotgg/t3code.git",
9 + );
10 + expect(cloneUrlForProtocol("https://github.com/pingdotgg/t3code.git", "ssh")).toBe(
11 + "git@github.com:pingdotgg/t3code.git",
12 + );
13 + expect(cloneUrlForProtocol("ssh://git@gitlab.com/group/sub/repo.git", "https")).toBe(
14 + "https://gitlab.com/group/sub/repo.git",
15 + );
16 + });
17 +
18 + it("keeps the URL as is for its own protocol and drops HTTPS credentials on switch", () => {
19 + expect(cloneUrlForProtocol("https://token@github.com/a/b.git", "https")).toBe(
20 + "https://token@github.com/a/b.git",
21 + );
22 + expect(cloneUrlForProtocol("https://token@github.com/a/b.git", "ssh")).toBe(
23 + "git@github.com:a/b.git",
24 + );
25 + });
26 +
27 + it("refuses rewrites that would guess wrong", () => {
28 + expect(cloneUrlForProtocol("ssh://git@host.example:2222/a/b.git", "https")).toBeNull();
29 + expect(cloneUrlForProtocol("https://host.example:8443/a/b.git", "ssh")).toBeNull();
30 + expect(cloneUrlForProtocol("https://host.example:8443/a/b.git", "https")).toBe(
31 + "https://host.example:8443/a/b.git",
32 + );
33 + expect(cloneUrlForProtocol("/srv/git/repo.git", "https")).toBeNull();
34 + expect(cloneUrlProtocol("file:///srv/git/repo.git")).toBeNull();
35 + });
36 +});
37 +
38 +describe("isDefaultCopiedFile", () => {
39 + it("selects env files anywhere in the tree", () => {
40 + expect(
41 + [".env", "apps/web/.env.local", ".envrc", ".dev.vars", "dist.log", ".environment"].filter(
42 + isDefaultCopiedFile,
43 + ),
44 + ).toEqual([".env", "apps/web/.env.local", ".envrc", ".dev.vars"]);
45 + });
46 +});
apps/web/src/lib/addProjectToMachine.ts new
+193
@@ -0,0 +1,193 @@
1 +import {
2 + executeAtomQuery,
3 + runAtomCommand,
4 + squashAtomCommandFailure,
5 +} from "@t3tools/client-runtime/state/runtime";
6 +import type { EnvironmentId, ProjectCloneSnapshot, ProjectId } from "@t3tools/contracts";
7 +
8 +import { stackedThreadToast, toastManager } from "../components/ui/toast";
9 +import { appAtomRegistry } from "../rpc/atomRegistry";
10 +import { environmentProjectClonesAtom } from "../state/projectClones";
11 +import { projectEnvironment } from "../state/projects";
12 +import { sourceControlEnvironment } from "../state/sourceControl";
13 +
14 +export type CloneProtocol = "ssh" | "https";
15 +
16 +/** Matches the server's read cap: a larger file would arrive truncated. */
17 +export const COPYABLE_FILE_MAX_BYTES = 1024 * 1024;
18 +
19 +const SCP_LIKE_URL = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/;
20 +const SSH_URL = /^ssh:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
21 +const HTTPS_URL = /^https?:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
22 +
23 +function parseCloneUrl(
24 + url: string,
25 +): { protocol: CloneProtocol; host: string; path: string; customPort: boolean } | null {
26 + const trimmed = url.trim();
27 + const ssh = SSH_URL.exec(trimmed);
28 + if (ssh) return { protocol: "ssh", host: ssh[1]!, path: ssh[3]!, customPort: !!ssh[2] };
29 + const https = HTTPS_URL.exec(trimmed);
30 + if (https) return { protocol: "https", host: https[1]!, path: https[3]!, customPort: !!https[2] };
31 + const scp = SCP_LIKE_URL.exec(trimmed);
32 + if (scp) return { protocol: "ssh", host: scp[1]!, path: scp[2]!, customPort: false };
33 + return null;
34 +}
35 +
36 +export function cloneUrlProtocol(url: string): CloneProtocol | null {
37 + return parseCloneUrl(url)?.protocol ?? null;
38 +}
39 +
40 +/**
41 + * Rewrites a clone URL to the other protocol, because the target machine may
42 + * only have SSH keys or only an HTTPS credential helper. Returns null when the
43 + * URL cannot be rewritten safely, such as a custom port.
44 + */
45 +export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): string | null {
46 + const parsed = parseCloneUrl(url);
47 + if (!parsed) return null;
48 + if (parsed.protocol === protocol) return url.trim();
49 + if (parsed.customPort) return null;
50 + return protocol === "ssh"
51 + ? `git@${parsed.host}:${parsed.path}`
52 + : `https://${parsed.host}/${parsed.path}`;
53 +}
54 +
55 +const DEFAULT_COPIED_FILE_NAME = /^(?:\.env(?:\..+)?|\.envrc|\.dev\.vars)$/;
56 +
57 +/** Env files are the ignored files people almost always want on a new machine. */
58 +export function isDefaultCopiedFile(path: string): boolean {
59 + const name = path.split("/").at(-1) ?? path;
60 + return DEFAULT_COPIED_FILE_NAME.test(name);
61 +}
62 +
63 +export interface AddProjectToMachineInput {
64 + readonly source: { readonly environmentId: EnvironmentId; readonly cwd: string };
65 + /** Where the source project sits below its repository root, or "". */
66 + readonly subdirectory: string;
67 + readonly target: { readonly environmentId: EnvironmentId; readonly label: string };
68 + readonly projectId: ProjectId;
69 + readonly title: string;
70 + readonly remoteUrl: string;
71 + readonly destinationPath: string;
72 + readonly files: ReadonlyArray<string>;
73 +}
74 +
75 +function failureMessage(result: Parameters<typeof squashAtomCommandFailure>[0]): string {
76 + const error = squashAtomCommandFailure(result);
77 + return error instanceof Error ? error.message : "An error occurred.";
78 +}
79 +
80 +/**
81 + * Resolves when the clone finishes, or null once it is removed. A failed or
82 + * cancelled clone keeps waiting, since its toast offers a retry.
83 + */
84 +function waitForClone(environmentId: EnvironmentId, projectId: ProjectId) {
85 + return new Promise<ProjectCloneSnapshot | null>((resolve) => {
86 + const atom = environmentProjectClonesAtom(environmentId);
87 + let seen = false;
88 + let settled = false;
89 + let unsubscribe: (() => void) | null = null;
90 + const check = (clones: ReadonlyArray<ProjectCloneSnapshot>) => {
91 + if (settled) return;
92 + const clone = clones.find((candidate) => candidate.projectId === projectId);
93 + if (clone) seen = true;
94 + const result = clone?.phase === "done" ? clone : !clone && seen ? null : undefined;
95 + if (result === undefined) return;
96 + settled = true;
97 + unsubscribe?.();
98 + resolve(result);
99 + };
100 + unsubscribe = appAtomRegistry.subscribe(atom, check);
101 + check(appAtomRegistry.get(atom));
102 + });
103 +}
104 +
105 +/**
106 + * Clones a project onto another machine, then copies the chosen ignored files
107 + * from the source. The client relays the files because the two servers never
108 + * talk to each other. Resolves once the clone starts; the clone toast shows
109 + * progress and a second toast reports the copied files.
110 + */
111 +export async function addProjectToMachine(input: AddProjectToMachineInput): Promise<void> {
112 + // Read first, so the copy reflects the files as they were when the user asked.
113 + const reads = await Promise.all(
114 + input.files.map(async (relativePath) => {
115 + const result = await executeAtomQuery(
116 + appAtomRegistry,
117 + projectEnvironment.readFile({
118 + environmentId: input.source.environmentId,
119 + input: { cwd: input.source.cwd, relativePath },
120 + }),
121 + { label: "Read file to copy", reportFailure: false, refresh: true },
122 + );
123 + if (result._tag === "Failure") return { relativePath, error: failureMessage(result) };
124 + if (result.value.truncated) return { relativePath, error: "Too large to copy." };
125 + return { relativePath, contents: result.value.contents };
126 + }),
127 + );
128 +
129 + const started = await runAtomCommand(
130 + appAtomRegistry,
131 + sourceControlEnvironment.startProjectClone,
132 + {
133 + environmentId: input.target.environmentId,
134 + input: {
135 + projectId: input.projectId,
136 + title: input.title,
137 + createdAt: new Date().toISOString(),
138 + remoteUrl: input.remoteUrl,
139 + destinationPath: input.destinationPath,
140 + },
141 + },
142 + { label: "Add project to machine", reportFailure: false },
143 + );
144 + if (started._tag === "Failure") throw new Error(failureMessage(started));
145 + if (input.files.length === 0) return;
146 +
147 + void (async () => {
148 + const clone = await waitForClone(input.target.environmentId, input.projectId);
149 + if (!clone) return;
150 + const failed: Array<string> = [];
151 + let copied = 0;
152 + for (const read of reads) {
153 + if (!("contents" in read)) {
154 + failed.push(`${read.relativePath}: ${read.error}`);
155 + continue;
156 + }
157 + const written = await runAtomCommand(
158 + appAtomRegistry,
159 + projectEnvironment.writeFile,
160 + {
161 + environmentId: input.target.environmentId,
162 + input: {
163 + cwd: started.value.cwd,
164 + relativePath: input.subdirectory
165 + ? `${input.subdirectory}/${read.relativePath}`
166 + : read.relativePath,
167 + contents: read.contents,
168 + },
169 + },
170 + { label: "Copy file to machine", reportFailure: false },
171 + );
172 + if (written._tag === "Failure")
173 + failed.push(`${read.relativePath}: ${failureMessage(written)}`);
174 + else copied += 1;
175 + }
176 + const noun = (count: number) => (count === 1 ? "file" : "files");
177 + toastManager.add(
178 + stackedThreadToast(
179 + failed.length === 0
180 + ? {
181 + type: "success",
182 + title: `Copied ${copied} ${noun(copied)} to ${input.target.label}`,
183 + description: reads.map((read) => read.relativePath).join(", "),
184 + }
185 + : {
186 + type: "error",
187 + title: `Could not copy ${failed.length} ${noun(failed.length)} to ${input.target.label}`,
188 + description: failed.join("\n"),
189 + },
190 + ),
191 + );
192 + })();
193 +}
apps/web/src/routes/__root.tsx
+2
@@ -19,6 +19,7 @@ import { resolveServerBackedAppDisplayName } from "../branding.logic";
19 import { AppSidebarLayout } from "../components/AppSidebarLayout";
20 import { CommandPalette } from "../components/CommandPalette";
21 import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";
22 +import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog";
23 import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
24 import { KeybindingsConfigWarning } from "../components/KeybindingsConfigWarning";
25 import { FirstRunGate } from "../components/onboarding/FirstRunGate";
@@ -245,6 +246,7 @@ function RootRouteView() {
246 <PermissionUpdateNotice />
247 {primaryEnvironmentAuthenticated ? <LegacyThreadMigrationToast /> : null}
248 <ProjectCloneToastCoordinator />
249 + <AddProjectToMachineDialogHost />
250 <PullRequestGuideRunCoordinator />
251 <HostedStaticEnvironmentBootstrap />
252 {primaryEnvironmentAuthenticated ? (
packages/client-runtime/src/state/projectCommands.ts
+5
@@ -135,6 +135,11 @@ export function createProjectEnvironmentAtoms<R, E>(
135 (result, isCurrent) => fileMetadata.rememberEntries(input.cwd, result.entries, isCurrent),
136 ),
137 }),
138 + listIgnoredFiles: createEnvironmentRpcQueryAtomFamily(runtime, {
139 + label: "environment-data:projects:list-ignored-files",
140 + tag: WS_METHODS.projectsListIgnoredFiles,
141 + staleTimeMs: 15_000,
142 + }),
143 readFile: createEnvironmentRpcQueryAtomFamily(runtime, {
144 label: "environment-data:projects:read-file",
145 tag: WS_METHODS.projectsReadFile,
packages/contracts/src/environment.ts
+2
@@ -141,6 +141,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
141 */
142 agentActivityPublishing: Schema.optionalKey(Schema.Boolean),
143 projectCloneTracking: Schema.optionalKey(Schema.Boolean),
144 + /** Server answers projects.listIgnoredFiles. */
145 + ignoredFileListing: Schema.optionalKey(Schema.Boolean),
146 environmentIcon: Schema.optionalKey(Schema.Boolean),
147 desktopAppUpdate: Schema.optionalKey(Schema.Boolean),
148 /** Server answers orchestration.subscribeCommandOutput. Absent on older servers,
packages/contracts/src/project.ts
+19
@@ -304,6 +304,25 @@ export const ProjectListEntriesResult = Schema.Struct({
304 });
305 export type ProjectListEntriesResult = typeof ProjectListEntriesResult.Type;
306
307 +// Untracked files git ignores. Wholly ignored folders such as `node_modules`
308 +// are left out, so the list stays small enough to pick from.
309 +export const ProjectListIgnoredFilesInput = Schema.Struct({
310 + cwd: TrimmedNonEmptyString,
311 +});
312 +export type ProjectListIgnoredFilesInput = typeof ProjectListIgnoredFilesInput.Type;
313 +
314 +export const ProjectIgnoredFile = Schema.Struct({
315 + path: TrimmedNonEmptyString,
316 + byteLength: NonNegativeInt,
317 +});
318 +export type ProjectIgnoredFile = typeof ProjectIgnoredFile.Type;
319 +
320 +export const ProjectListIgnoredFilesResult = Schema.Struct({
321 + files: Schema.Array(ProjectIgnoredFile),
322 + truncated: Schema.Boolean,
323 +});
324 +export type ProjectListIgnoredFilesResult = typeof ProjectListIgnoredFilesResult.Type;
325 +
326 export const ProjectEntriesFailure = Schema.Literals([
327 "workspace_root_not_found",
328 "workspace_root_create_failed",
packages/contracts/src/rpc.ts
+10
@@ -224,6 +224,8 @@ import {
224 ProjectListEntriesError,
225 ProjectListEntriesInput,
226 ProjectListEntriesResult,
227 + ProjectListIgnoredFilesInput,
228 + ProjectListIgnoredFilesResult,
229 ProjectReadFileError,
230 ProjectReadFileInput,
231 ProjectReadFileResult,
@@ -376,6 +378,7 @@ export const WS_METHODS = {
378 projectsAdd: "projects.add",
379 projectsRemove: "projects.remove",
380 projectsListEntries: "projects.listEntries",
381 + projectsListIgnoredFiles: "projects.listIgnoredFiles",
382 projectsReadFile: "projects.readFile",
383 projectsSearchContents: "projects.searchContents",
384 projectsSearchEntries: "projects.searchEntries",
@@ -1207,6 +1210,12 @@ const WsProjectsListEntriesRpc = Rpc.make(WS_METHODS.projectsListEntries, {
1210 error: Schema.Union([ProjectListEntriesError, EnvironmentAuthorizationError]),
1211 });
1212
1213 +const WsProjectsListIgnoredFilesRpc = Rpc.make(WS_METHODS.projectsListIgnoredFiles, {
1214 + payload: ProjectListIgnoredFilesInput,
1215 + success: ProjectListIgnoredFilesResult,
1216 + error: Schema.Union([ProjectListEntriesError, EnvironmentAuthorizationError]),
1217 +});
1218 +
1219 const WsProjectsReadFileRpc = Rpc.make(WS_METHODS.projectsReadFile, {
1220 payload: ProjectReadFileInput,
1221 success: ProjectReadFileResult,
@@ -1959,6 +1968,7 @@ export const WsRpcGroup = RpcGroup.make(
1968 WsProjectCloneRetryRpc,
1969 WsSubscribeProjectClonesRpc,
1970 WsProjectsListEntriesRpc,
1971 + WsProjectsListIgnoredFilesRpc,
1972 WsProjectsReadFileRpc,
1973 WsProjectsSearchContentsRpc,
1974 WsProjectsSearchEntriesRpc,