Skip to content
TypeScript

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

Theo Browneeffb4337e58b
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index 30e0ca31a59..24ccc3beae1 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -141,6 +141,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
[WS_METHODS.subscribeProjectClones]: AuthOrchestrationReadScope,
[WS_METHODS.projectsListEntries]: AuthFilesystemReadScope,
+ [WS_METHODS.projectsListIgnoredFiles]: AuthFilesystemReadScope,
[WS_METHODS.projectsReadFile]: AuthFilesystemReadScope,
[WS_METHODS.projectsSearchContents]: AuthFilesystemReadScope,
[WS_METHODS.projectsSearchEntries]: AuthFilesystemReadScope,
diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts
index d53d5420c3f..fbb5970560b 100644
--- a/apps/server/src/environment/ServerEnvironment.ts
+++ b/apps/server/src/environment/ServerEnvironment.ts
@@ -258,6 +258,7 @@ export const make = Effect.gen(function* () {
threadStop: true,
environmentIcon: true,
projectCloneTracking: true,
+ ignoredFileListing: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverInstallation === null ? {} : { serverInstallation }),
...(serverSelfUpdate === "boot-service" || desktopAppUpdate
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index 161694d55cb..6cc3bdb18b3 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -137,6 +137,7 @@ const RPC_AGGREGATES = {
[WS_METHODS.projectCloneRetry]: "source-control",
[WS_METHODS.subscribeProjectClones]: "source-control",
[WS_METHODS.projectsListEntries]: "workspace",
+ [WS_METHODS.projectsListIgnoredFiles]: "workspace",
[WS_METHODS.projectsReadFile]: "workspace",
[WS_METHODS.projectsSearchContents]: "workspace",
[WS_METHODS.projectsSearchEntries]: "workspace",
diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts
index d700ca9547e..2a592139014 100644
--- a/apps/server/src/workspace/WorkspaceEntries.test.ts
+++ b/apps/server/src/workspace/WorkspaceEntries.test.ts
@@ -349,6 +349,41 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => {
);
});
+ describe("listIgnoredFiles", () => {
+ it.effect("lists ignored files with sizes and skips wholly ignored folders", () =>
+ Effect.gen(function* () {
+ const cwd = yield* makeTempDir({ git: true });
+ yield* writeTextFile(cwd, ".gitignore", "node_modules/\n.env*\n");
+ yield* writeTextFile(cwd, ".env", "A=1");
+ yield* writeTextFile(cwd, "apps/web/index.ts", "y");
+ yield* git(cwd, ["add", "apps/web/index.ts"]);
+ yield* writeTextFile(cwd, "apps/web/.env.local", "B=22");
+ yield* writeTextFile(cwd, "node_modules/pkg/index.js", "x");
+
+ const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
+ expect(yield* workspaceEntries.listIgnoredFiles({ cwd })).toEqual({
+ files: [
+ { path: ".env", byteLength: 3 },
+ { path: "apps/web/.env.local", byteLength: 4 },
+ ],
+ truncated: false,
+ });
+ }),
+ );
+
+ it.effect("returns nothing outside a git repository", () =>
+ Effect.gen(function* () {
+ const cwd = yield* makeTempDir();
+ yield* writeTextFile(cwd, ".env", "A=1");
+ const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
+ expect(yield* workspaceEntries.listIgnoredFiles({ cwd })).toEqual({
+ files: [],
+ truncated: false,
+ });
+ }),
+ );
+ });
+
describe("search", () => {
it.effect("returns files and directories relative to cwd", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/workspace/WorkspaceEntries.ts b/apps/server/src/workspace/WorkspaceEntries.ts
index e40a1a25c12..a0d35202c21 100644
--- a/apps/server/src/workspace/WorkspaceEntries.ts
+++ b/apps/server/src/workspace/WorkspaceEntries.ts
@@ -14,6 +14,8 @@ import type {
ProjectEntry,
ProjectListEntriesInput,
ProjectListEntriesResult,
+ ProjectListIgnoredFilesInput,
+ ProjectListIgnoredFilesResult,
ProjectSearchContentsInput,
ProjectSearchContentsResult,
ProjectSearchEntriesInput,
@@ -99,6 +101,9 @@ export class WorkspaceEntries extends Context.Service<
readonly search: (
input: ProjectSearchEntriesInput,
) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;
+ readonly listIgnoredFiles: (
+ input: ProjectListIgnoredFilesInput,
+ ) => Effect.Effect<ProjectListIgnoredFilesResult, WorkspaceEntriesError>;
readonly searchContents: (
input: ProjectSearchContentsInput,
) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;
@@ -106,6 +111,9 @@ export class WorkspaceEntries extends Context.Service<
}
>()("t3/workspace/WorkspaceEntries") {}
+/** Ignored files offered for copying; more than this is a build folder, not config. */
+const IGNORED_FILES_LIMIT = 200;
+
/** Paths sent to one `git check-ignore` call when labelling a folder's children. */
const IGNORE_CHECK_CHUNK_SIZE = 1000;
@@ -388,7 +396,56 @@ export const make = Effect.gen(function* () {
},
);
- return WorkspaceEntries.of({ browse, list, refresh, search, searchContents });
+ const listIgnoredFiles: WorkspaceEntries["Service"]["listIgnoredFiles"] = Effect.fn(
+ "WorkspaceEntries.listIgnoredFiles",
+ )(function* (input) {
+ const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);
+ // `--directory` reports a folder holding nothing but ignored files as one
+ // `name/` entry, which is how `node_modules` and build output drop out.
+ const result = yield* vcsProcess
+ .run({
+ operation: "WorkspaceEntries.listIgnoredFiles",
+ command: "git",
+ args: [
+ "-c",
+ "core.fsmonitor=false",
+ "ls-files",
+ "--others",
+ "--ignored",
+ "--exclude-standard",
+ "--directory",
+ "--no-empty-directory",
+ "-z",
+ ],
+ cwd: normalizedCwd,
+ allowNonZeroExit: true,
+ timeoutMs: 10_000,
+ maxOutputBytes: 4 * 1024 * 1024,
+ })
+ .pipe(Effect.orElseSucceed(() => undefined));
+ if (!result || result.exitCode !== 0) return { files: [], truncated: false };
+ const paths = result.stdout
+ .split("\0")
+ .filter((entry) => entry.length > 0 && !entry.endsWith("/"))
+ .toSorted();
+ const files = yield* Effect.promise(() =>
+ Promise.all(
+ paths.slice(0, IGNORED_FILES_LIMIT).map(async (relativePath) => {
+ // lstat: a symlink usually points outside the workspace, where reads refuse to go.
+ const stat = await NodeFSP.lstat(path.join(normalizedCwd, relativePath)).catch(
+ () => null,
+ );
+ return stat?.isFile() ? { path: relativePath, byteLength: stat.size } : null;
+ }),
+ ),
+ );
+ return {
+ files: files.filter((file) => file !== null),
+ truncated: paths.length > IGNORED_FILES_LIMIT,
+ };
+ });
+
+ return WorkspaceEntries.of({ browse, list, listIgnoredFiles, refresh, search, searchContents });
});
export const layer = Layer.effect(WorkspaceEntries, make).pipe(
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 88b0be99046..83deec74ca8 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -1249,6 +1249,7 @@ export const layerWsRpc = (
const projectCloneTracker = yield* ProjectCloneTracker.ProjectCloneTracker;
const repositoryIdentityResolver =
yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
+ const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService;
const agentSessionScanner = yield* AgentSessionScanner.AgentSessionScanner;
const agentSessionImporter = yield* AgentSessionImporter.AgentSessionImporter;
const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery;
@@ -2571,6 +2572,10 @@ export const layerWsRpc = (
}),
),
Effect.andThen(refreshGitStatus(project.workspaceRoot)),
+ // The folder was empty when the project was created, so the cached
+ // enrichment says "no repository" and clients cannot group it yet.
+ Effect.andThen(projectEnrichment.invalidate([project.workspaceRoot])),
+ Effect.andThen(projectEnrichment.request(project.workspaceRoot)),
Effect.ignoreCause({ log: true }),
),
}),
@@ -2635,6 +2640,17 @@ export const layerWsRpc = (
}),
),
),
+ [WS_METHODS.projectsListIgnoredFiles]: (input) =>
+ workspaceEntries.listIgnoredFiles(input).pipe(
+ Effect.mapError(
+ (cause) =>
+ new ProjectListEntriesError({
+ ...input,
+ ...projectEntriesFailureContext(cause),
+ cause,
+ }),
+ ),
+ ),
[WS_METHODS.projectsReadFile]: (input) =>
workspaceFileSystem.readFile(input).pipe(
Effect.mapError(
diff --git a/apps/web/src/components/AddProjectToMachineDialog.tsx b/apps/web/src/components/AddProjectToMachineDialog.tsx
new file mode 100644
index 00000000000..0007c079ad7
--- /dev/null
+++ b/apps/web/src/components/AddProjectToMachineDialog.tsx
@@ -0,0 +1,394 @@
+import {
+ getAddProjectInitialQuery,
+ getCloneDestinationPath,
+ getCloneDirectoryName,
+} from "@t3tools/client-runtime/operations/projects";
+import {
+ type EnvironmentId,
+ type ProjectIgnoredFile,
+ type ScopedProjectRef,
+ resolveEnvironmentMachineKind,
+} from "@t3tools/contracts";
+import { ArrowRightIcon } from "lucide-react";
+import { useEffect, useId, useState } from "react";
+import { create } from "zustand";
+
+import { useAddProjectTargets } from "../hooks/useAddProjectTargets";
+import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments";
+import {
+ COPYABLE_FILE_MAX_BYTES,
+ type CloneProtocol,
+ addProjectToMachine,
+ cloneUrlForProtocol,
+ cloneUrlProtocol,
+ isDefaultCopiedFile,
+} from "../lib/addProjectToMachine";
+import { formatBytes } from "../lib/formatBytes";
+import { newProjectId } from "../lib/utils";
+import { useProject } from "../state/entities";
+import { useEnvironments } from "../state/environments";
+import { projectEnvironment } from "../state/projects";
+import { useEnvironmentQuery } from "../state/query";
+import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
+import { Button } from "./ui/button";
+import { Checkbox } from "./ui/checkbox";
+import {
+ Dialog,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogPanel,
+ DialogPopup,
+ DialogTitle,
+} from "./ui/dialog";
+import { Input } from "./ui/input";
+import { Label } from "./ui/label";
+import { MiddleTruncate } from "./ui/middle-truncate";
+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
+import { Toggle, ToggleGroup } from "./ui/toggle-group";
+
+interface AddProjectToMachineRequest {
+ readonly projectRef: ScopedProjectRef;
+ readonly targetEnvironmentId: EnvironmentId | null;
+}
+
+const useRequest = create<{ request: AddProjectToMachineRequest | null }>(() => ({
+ request: null,
+}));
+
+/** Opens the dialog that clones a project onto another connected machine. */
+export function openAddProjectToMachine(request: AddProjectToMachineRequest) {
+ useRequest.setState({ request });
+}
+
+const close = () => useRequest.setState({ request: null });
+
+export function AddProjectToMachineDialogHost() {
+ const request = useRequest((state) => state.request);
+ return request ? <AddProjectToMachineDialog request={request} /> : null;
+}
+
+function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRequest }) {
+ const id = useId();
+ const project = useProject(request.projectRef);
+ const { environments } = useEnvironments();
+ const targets = useAddProjectTargets(project, useLogicalProjectEnvironments(project, false));
+ const [targetId, setTargetId] = useState(request.targetEnvironmentId);
+ const target = targets.find((t) => t.environmentId === targetId) ?? targets[0] ?? null;
+ const source = environments.find((env) => env.environmentId === request.projectRef.environmentId);
+ const sourceUrl = project?.repositoryIdentity?.locator.remoteUrl ?? "";
+ const [protocol, setProtocol] = useState<CloneProtocol | null>(() => cloneUrlProtocol(sourceUrl));
+ const sshUrl = cloneUrlForProtocol(sourceUrl, "ssh");
+ const httpsUrl = cloneUrlForProtocol(sourceUrl, "https");
+ const remoteUrl =
+ (protocol === "ssh" ? sshUrl : protocol === "https" ? httpsUrl : null) ?? sourceUrl;
+
+ const targetEnvironment = environments.find((env) => env.environmentId === target?.environmentId);
+ const defaultPath = getCloneDestinationPath(
+ getAddProjectInitialQuery(targetEnvironment?.serverConfig?.settings.addProjectBaseDirectory),
+ getCloneDirectoryName(sourceUrl),
+ );
+ const [pathOverride, setPathOverride] = useState<string | null>(null);
+ const destinationPath = pathOverride ?? defaultPath;
+
+ const canListFiles = source?.serverConfig?.environment.capabilities.ignoredFileListing === true;
+ const ignoredFiles = useEnvironmentQuery(
+ project && canListFiles
+ ? projectEnvironment.listIgnoredFiles({
+ environmentId: project.environmentId,
+ input: { cwd: project.workspaceRoot },
+ })
+ : null,
+ );
+ const files = ignoredFiles.data?.files ?? [];
+ const [selected, setSelected] = useState<ReadonlySet<string> | null>(null);
+ const selectedFiles = selected ?? defaultSelection(files);
+ const copyable = files.filter((file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES);
+ const selectedBytes = files
+ .filter((file) => selectedFiles.has(file.path))
+ .reduce((total, file) => total + file.byteLength, 0);
+
+ const [submitting, setSubmitting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // The project or every target can vanish while the dialog is open. Submitting
+ // before the file list loads would silently skip the default .env copies.
+ const unavailable =
+ project === null ||
+ target === null ||
+ (canListFiles && ignoredFiles.data === null && ignoredFiles.error === null);
+ useEffect(() => {
+ if (project === null) close();
+ }, [project]);
+
+ const toggleFile = (path: string, checked: boolean) => {
+ const next = new Set(selectedFiles);
+ if (checked) next.add(path);
+ else next.delete(path);
+ setSelected(next);
+ };
+
+ const submit = async () => {
+ if (!project || !target || submitting) return;
+ if (destinationPath.trim().length === 0) {
+ setError("Choose a folder on the other machine.");
+ return;
+ }
+ setSubmitting(true);
+ setError(null);
+ try {
+ await addProjectToMachine({
+ source: { environmentId: project.environmentId, cwd: project.workspaceRoot },
+ subdirectory: projectSubdirectory(
+ project.repositoryIdentity?.rootPath,
+ project.workspaceRoot,
+ ),
+ target: { environmentId: target.environmentId, label: target.label },
+ projectId: newProjectId(),
+ title: project.title,
+ remoteUrl,
+ destinationPath: destinationPath.trim(),
+ files: files.filter((file) => selectedFiles.has(file.path)).map((file) => file.path),
+ });
+ close();
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : "Could not start the clone.");
+ setSubmitting(false);
+ }
+ };
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open) close();
+ }}
+ >
+ <DialogPopup className="sm:max-w-xl">
+ <form
+ className="flex min-h-0 flex-col"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+ <DialogHeader>
+ <DialogTitle>Add to another machine</DialogTitle>
+ <DialogDescription>
+ Clone {project?.repositoryIdentity?.displayName ?? project?.title} and bring the local
+ files git does not track.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogPanel>
+ <div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-3">
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
+ <EnvironmentMachineIcon
+ kind={resolveEnvironmentMachineKind(source?.serverConfig ?? null)}
+ className="size-3.5 shrink-0"
+ />
+ <span className="truncate">{source?.label ?? "This machine"}</span>
+ </span>
+ <span className="flex min-w-0 font-mono text-muted-foreground text-xs">
+ <MiddleTruncate value={project?.workspaceRoot ?? ""} />
+ </span>
+ </div>
+ <div className="flex w-28 flex-col items-center gap-0.5 text-muted-foreground text-xs">
+ <span>git clone</span>
+ <span className="flex w-full items-center">
+ <span className="h-px flex-1 bg-border" />
+ <ArrowRightIcon className="-ms-1 size-3.5" aria-hidden />
+ </span>
+ <span>
+ {selectedFiles.size === 0
+ ? "no files"
+ : `+ ${selectedFiles.size} ${selectedFiles.size === 1 ? "file" : "files"}`}
+ </span>
+ </div>
+ <div className="flex min-w-0 flex-col gap-1">
+ {targets.length > 1 ? (
+ <Select
+ value={target?.environmentId ?? null}
+ onValueChange={(value) => {
+ if (value) setTargetId(value);
+ }}
+ items={targets.map((t) => ({ value: t.environmentId, label: t.label }))}
+ >
+ <SelectTrigger size="sm" aria-label="Machine to add the project to">
+ {target ? (
+ <EnvironmentMachineIcon kind={target.machine} className="size-3.5" />
+ ) : null}
+ <SelectValue />
+ </SelectTrigger>
+ <SelectPopup>
+ {targets.map((t) => (
+ <SelectItem key={t.environmentId} value={t.environmentId}>
+ <span className="inline-flex items-center gap-1.5">
+ <EnvironmentMachineIcon kind={t.machine} className="size-3" />
+ {t.label}
+ </span>
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ ) : (
+ <span className="flex min-w-0 items-center gap-1.5 font-medium text-sm">
+ {target ? (
+ <EnvironmentMachineIcon kind={target.machine} className="size-3.5 shrink-0" />
+ ) : null}
+ <span className="truncate">{target?.label ?? "No machine available"}</span>
+ </span>
+ )}
+ <span className="flex min-w-0 font-mono text-muted-foreground text-xs">
+ <MiddleTruncate value={destinationPath} />
+ </span>
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-1.5">
+ <Label>Clone over</Label>
+ {sshUrl && httpsUrl ? (
+ <ToggleGroup
+ aria-label="Clone protocol"
+ value={protocol ? [protocol] : []}
+ onValueChange={(next) => {
+ const value = next[0];
+ if (value === "ssh" || value === "https") setProtocol(value);
+ }}
+ >
+ <Toggle value="ssh">SSH</Toggle>
+ <Toggle value="https">HTTPS</Toggle>
+ </ToggleGroup>
+ ) : null}
+ <span className="truncate font-mono text-muted-foreground text-xs">{remoteUrl}</span>
+ </div>
+
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor={`${id}-path`}>Folder on {target?.label ?? "the other machine"}</Label>
+ <Input
+ id={`${id}-path`}
+ value={destinationPath}
+ onChange={(event) => setPathOverride(event.target.value)}
+ spellCheck={false}
+ autoComplete="off"
+ />
+ </div>
+
+ {canListFiles ? (
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center gap-2">
+ <Label className="flex-1">Copy ignored files</Label>
+ {copyable.length > 0 ? (
+ <>
+ <span className="text-muted-foreground text-xs">
+ {selectedFiles.size} of {files.length}
+ {selectedBytes > 0 ? ` · ${formatBytes(selectedBytes)}` : ""}
+ </span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ onClick={() =>
+ setSelected(
+ selectedFiles.size === copyable.length
+ ? new Set()
+ : new Set(copyable.map((file) => file.path)),
+ )
+ }
+ >
+ {selectedFiles.size === copyable.length ? "None" : "All"}
+ </Button>
+ </>
+ ) : null}
+ </div>
+ {ignoredFiles.error ? (
+ <p className="text-destructive-foreground text-xs">{ignoredFiles.error}</p>
+ ) : files.length === 0 ? (
+ <p className="text-muted-foreground text-xs">
+ {ignoredFiles.isSuccess
+ ? "No ignored files to copy."
+ : "Finding ignored files…"}
+ </p>
+ ) : (
+ <div className="max-h-52 overflow-y-auto rounded-md border">
+ {files.map((file) => (
+ <IgnoredFileRow
+ key={file.path}
+ file={file}
+ checked={selectedFiles.has(file.path)}
+ onCheckedChange={(checked) => toggleFile(file.path, checked)}
+ />
+ ))}
+ </div>
+ )}
+ {ignoredFiles.data?.truncated ? (
+ <p className="text-muted-foreground text-xs">
+ Showing the first {files.length} files.
+ </p>
+ ) : null}
+ <p className="text-muted-foreground text-xs">
+ Files are copied after the clone finishes. Folders git ignores whole, like
+ node_modules, are left out.
+ </p>
+ </div>
+ ) : null}
+
+ {error ? <p className="text-destructive-foreground text-sm">{error}</p> : null}
+ </DialogPanel>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={close}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={unavailable || submitting}>
+ {submitting ? "Starting…" : `Clone to ${target?.label ?? "machine"}`}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogPopup>
+ </Dialog>
+ );
+}
+
+/**
+ * A project can be rooted below its repository's top folder. The clone lands
+ * at the top, so copied files keep the same path below it.
+ */
+function projectSubdirectory(repositoryRoot: string | undefined, workspaceRoot: string) {
+ if (!repositoryRoot) return "";
+ const prefix = repositoryRoot.replace(/[\\/]+$/, "");
+ const rest = workspaceRoot.slice(prefix.length);
+ return workspaceRoot.startsWith(prefix) && /^[\\/]/.test(rest)
+ ? rest.slice(1).replaceAll("\\", "/")
+ : "";
+}
+
+function defaultSelection(files: readonly ProjectIgnoredFile[]): ReadonlySet<string> {
+ return new Set(
+ files
+ .filter(
+ (file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES && isDefaultCopiedFile(file.path),
+ )
+ .map((file) => file.path),
+ );
+}
+
+function IgnoredFileRow({
+ file,
+ checked,
+ onCheckedChange,
+}: {
+ file: ProjectIgnoredFile;
+ checked: boolean;
+ onCheckedChange: (checked: boolean) => void;
+}) {
+ const tooLarge = file.byteLength > COPYABLE_FILE_MAX_BYTES;
+ return (
+ <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">
+ <Checkbox checked={checked} disabled={tooLarge} onCheckedChange={onCheckedChange} />
+ <span className="min-w-0 flex-1 truncate font-mono text-xs">{file.path}</span>
+ <span className="shrink-0 text-muted-foreground text-xs tabular-nums">
+ {tooLarge ? "Over 1 MB" : formatBytes(file.byteLength)}
+ </span>
+ </label>
+ );
+}
diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts
index ee1c891f24d..13775843b64 100644
--- a/apps/web/src/components/BranchToolbar.logic.ts
+++ b/apps/web/src/components/BranchToolbar.logic.ts
@@ -22,6 +22,10 @@ export interface EnvironmentOption {
machine: EnvironmentMachineKind;
}
+/** "Add to another machine" stays muted until hovered: easy to find, quieter than the machines. */
+export const ADD_TO_MACHINE_LABEL_CLASS =
+ "flex min-w-0 items-center gap-1.5 opacity-55 in-data-highlighted:opacity-100 in-data-popup-open:opacity-100";
+
export const EnvMode = Schema.Literals(["local", "worktree"]);
export type EnvMode = typeof EnvMode.Type;
diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx
index d27dc428ac3..2447ae3e1eb 100644
--- a/apps/web/src/components/BranchToolbar.tsx
+++ b/apps/web/src/components/BranchToolbar.tsx
@@ -10,6 +10,7 @@ import {
FolderGit2Icon,
FolderGitIcon,
FolderIcon,
+ PlusIcon,
ScaleIcon,
} from "lucide-react";
import {
@@ -28,6 +29,7 @@ import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
import { useProject, useThreadShellsForProjectRefs } from "../state/entities";
import {
+ ADD_TO_MACHINE_LABEL_CLASS,
type EnvMode,
type EnvironmentOption,
resolveContextStripLabelsCompact,
@@ -43,6 +45,8 @@ import {
type BranchToolbarBranchSelectorHandle,
} from "./BranchToolbarBranchSelector";
import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
+import { openAddProjectToMachine } from "./AddProjectToMachineDialog";
+import { type AddProjectTarget, useAddProjectTargets } from "../hooks/useAddProjectTargets";
import type { PendingServerUpdate } from "./ServerUpdateAction";
import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector";
import { PreviousWorktreeItemContent } from "./PreviousWorktreeItemContent";
@@ -56,10 +60,14 @@ import {
Menu,
MenuGroup,
MenuGroupLabel,
+ MenuItem,
MenuPopup,
MenuRadioGroup,
MenuRadioItem,
MenuSeparator,
+ MenuSub,
+ MenuSubPopup,
+ MenuSubTrigger,
MenuTrigger,
} from "./ui/menu";
import { Separator } from "./ui/separator";
@@ -162,6 +170,8 @@ interface RunContextSelectorProps {
previousWorktreeLabel: string | null;
previousWorktreeBranch: string | null;
onUsePreviousWorktree: () => void;
+ addTargets: readonly AddProjectTarget[];
+ onAddToMachine: (environmentId: EnvironmentId) => void;
}
const RunContextSelector = memo(function RunContextSelector({
@@ -183,6 +193,8 @@ const RunContextSelector = memo(function RunContextSelector({
previousWorktreeLabel,
previousWorktreeBranch,
onUsePreviousWorktree,
+ addTargets,
+ onAddToMachine,
}: RunContextSelectorProps) {
const composerFloatingLayerProps = useComposerMenuProps();
const activeEnvironment =
@@ -318,7 +330,8 @@ const RunContextSelector = memo(function RunContextSelector({
}
{...(!isPanel ? composerFloatingLayerProps : {})}
>
- {showEnvironmentPicker && availableEnvironments && onEnvironmentChange ? (
+ {availableEnvironments &&
+ ((showEnvironmentPicker && onEnvironmentChange) || addTargets.length > 0) ? (
<>
<MenuGroup>
<MenuGroupLabel>Run on</MenuGroupLabel>
@@ -327,7 +340,7 @@ const RunContextSelector = memo(function RunContextSelector({
onValueChange={(value) =>
value === "auto"
? onAutoEnvironment?.()
- : onEnvironmentChange(value as EnvironmentId)
+ : onEnvironmentChange?.(value as EnvironmentId)
}
>
{onAutoEnvironment && (
@@ -350,7 +363,9 @@ const RunContextSelector = memo(function RunContextSelector({
{availableEnvironments.map((env) => (
<MenuRadioItem
key={env.environmentId}
- disabled={envLocked}
+ disabled={
+ envLocked || (!onEnvironmentChange && env.environmentId !== environmentId)
+ }
value={env.environmentId}
closeOnClick
>
@@ -361,6 +376,29 @@ const RunContextSelector = memo(function RunContextSelector({
</MenuRadioItem>
))}
</MenuRadioGroup>
+ {addTargets.length > 0 ? (
+ <MenuSub>
+ <MenuSubTrigger>
+ <span className={ADD_TO_MACHINE_LABEL_CLASS}>
+ <PlusIcon className="size-3" />
+ <span className="min-w-0 truncate">Add to another machine</span>
+ </span>
+ </MenuSubTrigger>
+ <MenuSubPopup {...(!isPanel ? composerFloatingLayerProps : {})}>
+ {addTargets.map((target) => (
+ <MenuItem
+ key={target.environmentId}
+ onClick={() => onAddToMachine(target.environmentId)}
+ >
+ <span className="flex min-w-0 items-center gap-1.5">
+ <EnvironmentMachineIcon kind={target.machine} className="size-3" />
+ <span className="min-w-0 truncate">{target.label}</span>
+ </span>
+ </MenuItem>
+ ))}
+ </MenuSubPopup>
+ </MenuSub>
+ ) : null}
</MenuGroup>
<MenuSeparator />
</>
@@ -649,7 +687,11 @@ export const BranchToolbar = memo(function BranchToolbar({
],
);
- const hasMultipleEnvironments = (availableEnvironments?.length ?? 0) > 1;
+ const addTargets = useAddProjectTargets(activeProject, availableEnvironments);
+ const onAddToMachine = (targetEnvironmentId: EnvironmentId | null) =>
+ openAddProjectToMachine({ projectRef: activeProjectRef, targetEnvironmentId });
+ // A project on one machine still gets the picker when it can be added to another.
+ const hasMultipleEnvironments = (availableEnvironments?.length ?? 0) > 1 || addTargets.length > 0;
const showEnvironmentPicker = hasMultipleEnvironments && onEnvironmentChange !== undefined;
const activeEnvironmentOption =
availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
@@ -688,6 +730,8 @@ export const BranchToolbar = memo(function BranchToolbar({
previousWorktreeLabel={previousWorktreeLabel}
previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
onUsePreviousWorktree={onUsePreviousWorktree}
+ addTargets={addTargets}
+ onAddToMachine={onAddToMachine}
/>
) : null}
{panelSection !== "workspace" ? (
@@ -731,6 +775,7 @@ export const BranchToolbar = memo(function BranchToolbar({
environmentId={environmentId}
availableEnvironments={availableEnvironments}
{...(showEnvironmentPicker ? { onEnvironmentChange } : {})}
+ {...(addTargets.length > 0 ? { onAddToMachine: () => onAddToMachine(null) } : {})}
serverUpdate={serverUpdate}
/>
) : null}
@@ -753,6 +798,8 @@ export const BranchToolbar = memo(function BranchToolbar({
previousWorktreeLabel={previousWorktreeLabel}
previousWorktreeBranch={previousWorktreeSeed?.branch ?? null}
onUsePreviousWorktree={onUsePreviousWorktree}
+ addTargets={addTargets}
+ onAddToMachine={onAddToMachine}
/>
</div>
) : null}
@@ -774,6 +821,7 @@ export const BranchToolbar = memo(function BranchToolbar({
environmentId={environmentId}
availableEnvironments={availableEnvironments}
{...(showEnvironmentPicker ? { onEnvironmentChange } : {})}
+ {...(addTargets.length > 0 ? { onAddToMachine: () => onAddToMachine(null) } : {})}
/>
) : null}
{showGitControls ? (
diff --git a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx
index e93094d7c32..d505cdecae7 100644
--- a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx
+++ b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx
@@ -5,10 +5,10 @@ import { useAtomValue } from "@effect/atom-react";
import { shortcutLabelForCommand } from "../keybindings";
import { primaryServerKeybindingsAtom } from "../state/server";
import type { EnvironmentId } from "@t3tools/contracts";
-import { CircleArrowUpIcon, ScaleIcon } from "lucide-react";
+import { CircleArrowUpIcon, PlusIcon, ScaleIcon } from "lucide-react";
import { memo } from "react";
-import type { EnvironmentOption } from "./BranchToolbar.logic";
+import { ADD_TO_MACHINE_LABEL_CLASS, type EnvironmentOption } from "./BranchToolbar.logic";
import {
ServerUpdateAction,
type PendingServerUpdate,
@@ -32,12 +32,14 @@ interface BranchToolbarEnvironmentSelectorProps {
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[];
onEnvironmentChange?: (environmentId: EnvironmentId) => void;
+ onAddToMachine?: (() => void) | undefined;
serverUpdate?: PendingServerUpdate | null;
}
// Action values cannot collide with server-minted environment IDs.
const AUTO_VALUE = "action:auto";
const UPDATE_VALUE = "action:update";
+const ADD_MACHINE_VALUE = "action:add-machine";
const environmentValue = (id: EnvironmentId) => `env:${id}`;
export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector(
@@ -60,6 +62,7 @@ function EnvironmentSelector({
environmentId,
availableEnvironments,
onEnvironmentChange,
+ onAddToMachine,
serverUpdate,
updateControl,
}: BranchToolbarEnvironmentSelectorProps & {
@@ -84,6 +87,7 @@ function EnvironmentSelector({
...(serverUpdate && updateControl
? [{ value: UPDATE_VALUE, label: `${updateControl.label} ${serverUpdate.serverLabel}` }]
: []),
+ ...(onAddToMachine ? [{ value: ADD_MACHINE_VALUE, label: "Add to another machine" }] : []),
];
const updateTooltip = serverUpdate
? `${serverUpdate.serverLabel} ${serverUpdate.serverVersion} → ${serverUpdate.targetVersion}. ${
@@ -114,7 +118,7 @@ function EnvironmentSelector({
// the glass seam joining it to the composer assumes a fixed strip height, so
// a shorter label would drag the seam out of line whenever this label is the
// only thing in the strip.
- if (envLocked || onEnvironmentChange === undefined) {
+ if (envLocked || (onEnvironmentChange === undefined && onAddToMachine === undefined)) {
const lockedRow = updateControl ? (
<ComposerControl
size="xs"
@@ -161,10 +165,12 @@ function EnvironmentSelector({
onValueChange={(value) => {
if (value === UPDATE_VALUE) {
updateControl?.onClick();
+ } else if (value === ADD_MACHINE_VALUE) {
+ onAddToMachine?.();
} else if (value === AUTO_VALUE) {
onAutoEnvironment?.();
} else if (value?.startsWith("env:")) {
- onEnvironmentChange(value.slice(4) as EnvironmentId);
+ onEnvironmentChange?.(value.slice(4) as EnvironmentId);
}
}}
items={environmentItems}
@@ -212,7 +218,11 @@ function EnvironmentSelector({
</SelectItem>
)}
{availableEnvironments.map((env) => (
- <SelectItem key={env.environmentId} value={environmentValue(env.environmentId)}>
+ <SelectItem
+ key={env.environmentId}
+ value={environmentValue(env.environmentId)}
+ disabled={onEnvironmentChange === undefined && env.environmentId !== environmentId}
+ >
<span className="inline-flex items-center gap-1.5">
{serverUpdate?.environmentId === env.environmentId ? (
<CircleArrowUpIcon aria-hidden="true" className="size-3" />
@@ -223,6 +233,14 @@ function EnvironmentSelector({
</span>
</SelectItem>
))}
+ {onAddToMachine ? (
+ <SelectItem value={ADD_MACHINE_VALUE}>
+ <span className={ADD_TO_MACHINE_LABEL_CLASS}>
+ <PlusIcon aria-hidden="true" className="size-3" />
+ Add to another machine
+ </span>
+ </SelectItem>
+ ) : null}
</SelectGroup>
{serverUpdate && updateControl ? (
<SelectGroup>
diff --git a/apps/web/src/hooks/useAddProjectTargets.ts b/apps/web/src/hooks/useAddProjectTargets.ts
new file mode 100644
index 00000000000..d5962dd48d3
--- /dev/null
+++ b/apps/web/src/hooks/useAddProjectTargets.ts
@@ -0,0 +1,41 @@
+import { canCreateProjectInEnvironment } from "@t3tools/client-runtime/operations/projects";
+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
+import { AuthSourceControlWriteScope, resolveEnvironmentMachineKind } from "@t3tools/contracts";
+
+import type { EnvironmentOption } from "../components/BranchToolbar.logic";
+import { useEnvironments } from "../state/environments";
+import { useEnvironmentsWithScope } from "../state/session";
+
+export type AddProjectTarget = Pick<EnvironmentOption, "environmentId" | "label" | "machine">;
+
+/**
+ * Connected machines that do not have the project yet and can clone it.
+ * `projectEnvironments` is the project's current machine list, from
+ * `useLogicalProjectEnvironments`. Projects without a git remote get none.
+ */
+export function useAddProjectTargets(
+ project: EnvironmentProject | null,
+ projectEnvironments: readonly Pick<EnvironmentOption, "environmentId">[] | undefined,
+): readonly AddProjectTarget[] {
+ const { environments } = useEnvironments();
+ const canClone = useEnvironmentsWithScope(environments, AuthSourceControlWriteScope);
+ if (!project?.repositoryIdentity?.locator.remoteUrl) return [];
+ const hasProject = new Set([
+ project.environmentId,
+ ...(projectEnvironments ?? []).map((env) => env.environmentId),
+ ]);
+ return environments
+ .filter(
+ (environment) =>
+ !hasProject.has(environment.environmentId) &&
+ canClone.has(environment.environmentId) &&
+ canCreateProjectInEnvironment(environment.connection.phase) &&
+ environment.serverConfig?.environment.capabilities.projectCloneTracking === true,
+ )
+ .map((environment) => ({
+ environmentId: environment.environmentId,
+ label: environment.label,
+ machine: resolveEnvironmentMachineKind(environment.serverConfig),
+ }))
+ .toSorted((a, b) => a.label.localeCompare(b.label));
+}
diff --git a/apps/web/src/lib/addProjectToMachine.test.ts b/apps/web/src/lib/addProjectToMachine.test.ts
new file mode 100644
index 00000000000..b501b921707
--- /dev/null
+++ b/apps/web/src/lib/addProjectToMachine.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { cloneUrlForProtocol, cloneUrlProtocol, isDefaultCopiedFile } from "./addProjectToMachine";
+
+describe("cloneUrlForProtocol", () => {
+ it("switches between scp-style SSH and HTTPS", () => {
+ expect(cloneUrlForProtocol("[email protected]:pingdotgg/t3code.git", "https")).toBe(
+ "https://github.com/pingdotgg/t3code.git",
+ );
+ expect(cloneUrlForProtocol("https://github.com/pingdotgg/t3code.git", "ssh")).toBe(
+ "[email protected]:pingdotgg/t3code.git",
+ );
+ expect(cloneUrlForProtocol("ssh://[email protected]/group/sub/repo.git", "https")).toBe(
+ "https://gitlab.com/group/sub/repo.git",
+ );
+ });
+
+ it("keeps the URL as is for its own protocol and drops HTTPS credentials on switch", () => {
+ expect(cloneUrlForProtocol("https://[email protected]/a/b.git", "https")).toBe(
+ "https://[email protected]/a/b.git",
+ );
+ expect(cloneUrlForProtocol("https://[email protected]/a/b.git", "ssh")).toBe(
+ "[email protected]:a/b.git",
+ );
+ });
+
+ it("refuses rewrites that would guess wrong", () => {
+ expect(cloneUrlForProtocol("ssh://[email protected]:2222/a/b.git", "https")).toBeNull();
+ expect(cloneUrlForProtocol("https://host.example:8443/a/b.git", "ssh")).toBeNull();
+ expect(cloneUrlForProtocol("https://host.example:8443/a/b.git", "https")).toBe(
+ "https://host.example:8443/a/b.git",
+ );
+ expect(cloneUrlForProtocol("/srv/git/repo.git", "https")).toBeNull();
+ expect(cloneUrlProtocol("file:///srv/git/repo.git")).toBeNull();
+ });
+});
+
+describe("isDefaultCopiedFile", () => {
+ it("selects env files anywhere in the tree", () => {
+ expect(
+ [".env", "apps/web/.env.local", ".envrc", ".dev.vars", "dist.log", ".environment"].filter(
+ isDefaultCopiedFile,
+ ),
+ ).toEqual([".env", "apps/web/.env.local", ".envrc", ".dev.vars"]);
+ });
+});
diff --git a/apps/web/src/lib/addProjectToMachine.ts b/apps/web/src/lib/addProjectToMachine.ts
new file mode 100644
index 00000000000..53c37f37298
--- /dev/null
+++ b/apps/web/src/lib/addProjectToMachine.ts
@@ -0,0 +1,193 @@
+import {
+ executeAtomQuery,
+ runAtomCommand,
+ squashAtomCommandFailure,
+} from "@t3tools/client-runtime/state/runtime";
+import type { EnvironmentId, ProjectCloneSnapshot, ProjectId } from "@t3tools/contracts";
+
+import { stackedThreadToast, toastManager } from "../components/ui/toast";
+import { appAtomRegistry } from "../rpc/atomRegistry";
+import { environmentProjectClonesAtom } from "../state/projectClones";
+import { projectEnvironment } from "../state/projects";
+import { sourceControlEnvironment } from "../state/sourceControl";
+
+export type CloneProtocol = "ssh" | "https";
+
+/** Matches the server's read cap: a larger file would arrive truncated. */
+export const COPYABLE_FILE_MAX_BYTES = 1024 * 1024;
+
+const SCP_LIKE_URL = /^(?:[^@/\s]+@)?([^:/\s]+):(?!\/)(.+)$/;
+const SSH_URL = /^ssh:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
+const HTTPS_URL = /^https?:\/\/(?:[^@/\s]+@)?([^:/\s]+)(:\d+)?\/(.+)$/;
+
+function parseCloneUrl(
+ url: string,
+): { protocol: CloneProtocol; host: string; path: string; customPort: boolean } | null {
+ const trimmed = url.trim();
+ const ssh = SSH_URL.exec(trimmed);
+ if (ssh) return { protocol: "ssh", host: ssh[1]!, path: ssh[3]!, customPort: !!ssh[2] };
+ const https = HTTPS_URL.exec(trimmed);
+ if (https) return { protocol: "https", host: https[1]!, path: https[3]!, customPort: !!https[2] };
+ const scp = SCP_LIKE_URL.exec(trimmed);
+ if (scp) return { protocol: "ssh", host: scp[1]!, path: scp[2]!, customPort: false };
+ return null;
+}
+
+export function cloneUrlProtocol(url: string): CloneProtocol | null {
+ return parseCloneUrl(url)?.protocol ?? null;
+}
+
+/**
+ * Rewrites a clone URL to the other protocol, because the target machine may
+ * only have SSH keys or only an HTTPS credential helper. Returns null when the
+ * URL cannot be rewritten safely, such as a custom port.
+ */
+export function cloneUrlForProtocol(url: string, protocol: CloneProtocol): string | null {
+ const parsed = parseCloneUrl(url);
+ if (!parsed) return null;
+ if (parsed.protocol === protocol) return url.trim();
+ if (parsed.customPort) return null;
+ return protocol === "ssh"
+ ? `git@${parsed.host}:${parsed.path}`
+ : `https://${parsed.host}/${parsed.path}`;
+}
+
+const DEFAULT_COPIED_FILE_NAME = /^(?:\.env(?:\..+)?|\.envrc|\.dev\.vars)$/;
+
+/** Env files are the ignored files people almost always want on a new machine. */
+export function isDefaultCopiedFile(path: string): boolean {
+ const name = path.split("/").at(-1) ?? path;
+ return DEFAULT_COPIED_FILE_NAME.test(name);
+}
+
+export interface AddProjectToMachineInput {
+ readonly source: { readonly environmentId: EnvironmentId; readonly cwd: string };
+ /** Where the source project sits below its repository root, or "". */
+ readonly subdirectory: string;
+ readonly target: { readonly environmentId: EnvironmentId; readonly label: string };
+ readonly projectId: ProjectId;
+ readonly title: string;
+ readonly remoteUrl: string;
+ readonly destinationPath: string;
+ readonly files: ReadonlyArray<string>;
+}
+
+function failureMessage(result: Parameters<typeof squashAtomCommandFailure>[0]): string {
+ const error = squashAtomCommandFailure(result);
+ return error instanceof Error ? error.message : "An error occurred.";
+}
+
+/**
+ * Resolves when the clone finishes, or null once it is removed. A failed or
+ * cancelled clone keeps waiting, since its toast offers a retry.
+ */
+function waitForClone(environmentId: EnvironmentId, projectId: ProjectId) {
+ return new Promise<ProjectCloneSnapshot | null>((resolve) => {
+ const atom = environmentProjectClonesAtom(environmentId);
+ let seen = false;
+ let settled = false;
+ let unsubscribe: (() => void) | null = null;
+ const check = (clones: ReadonlyArray<ProjectCloneSnapshot>) => {
+ if (settled) return;
+ const clone = clones.find((candidate) => candidate.projectId === projectId);
+ if (clone) seen = true;
+ const result = clone?.phase === "done" ? clone : !clone && seen ? null : undefined;
+ if (result === undefined) return;
+ settled = true;
+ unsubscribe?.();
+ resolve(result);
+ };
+ unsubscribe = appAtomRegistry.subscribe(atom, check);
+ check(appAtomRegistry.get(atom));
+ });
+}
+
+/**
+ * Clones a project onto another machine, then copies the chosen ignored files
+ * from the source. The client relays the files because the two servers never
+ * talk to each other. Resolves once the clone starts; the clone toast shows
+ * progress and a second toast reports the copied files.
+ */
+export async function addProjectToMachine(input: AddProjectToMachineInput): Promise<void> {
+ // Read first, so the copy reflects the files as they were when the user asked.
+ const reads = await Promise.all(
+ input.files.map(async (relativePath) => {
+ const result = await executeAtomQuery(
+ appAtomRegistry,
+ projectEnvironment.readFile({
+ environmentId: input.source.environmentId,
+ input: { cwd: input.source.cwd, relativePath },
+ }),
+ { label: "Read file to copy", reportFailure: false, refresh: true },
+ );
+ if (result._tag === "Failure") return { relativePath, error: failureMessage(result) };
+ if (result.value.truncated) return { relativePath, error: "Too large to copy." };
+ return { relativePath, contents: result.value.contents };
+ }),
+ );
+
+ const started = await runAtomCommand(
+ appAtomRegistry,
+ sourceControlEnvironment.startProjectClone,
+ {
+ environmentId: input.target.environmentId,
+ input: {
+ projectId: input.projectId,
+ title: input.title,
+ createdAt: new Date().toISOString(),
+ remoteUrl: input.remoteUrl,
+ destinationPath: input.destinationPath,
+ },
+ },
+ { label: "Add project to machine", reportFailure: false },
+ );
+ if (started._tag === "Failure") throw new Error(failureMessage(started));
+ if (input.files.length === 0) return;
+
+ void (async () => {
+ const clone = await waitForClone(input.target.environmentId, input.projectId);
+ if (!clone) return;
+ const failed: Array<string> = [];
+ let copied = 0;
+ for (const read of reads) {
+ if (!("contents" in read)) {
+ failed.push(`${read.relativePath}: ${read.error}`);
+ continue;
+ }
+ const written = await runAtomCommand(
+ appAtomRegistry,
+ projectEnvironment.writeFile,
+ {
+ environmentId: input.target.environmentId,
+ input: {
+ cwd: started.value.cwd,
+ relativePath: input.subdirectory
+ ? `${input.subdirectory}/${read.relativePath}`
+ : read.relativePath,
+ contents: read.contents,
+ },
+ },
+ { label: "Copy file to machine", reportFailure: false },
+ );
+ if (written._tag === "Failure")
+ failed.push(`${read.relativePath}: ${failureMessage(written)}`);
+ else copied += 1;
+ }
+ const noun = (count: number) => (count === 1 ? "file" : "files");
+ toastManager.add(
+ stackedThreadToast(
+ failed.length === 0
+ ? {
+ type: "success",
+ title: `Copied ${copied} ${noun(copied)} to ${input.target.label}`,
+ description: reads.map((read) => read.relativePath).join(", "),
+ }
+ : {
+ type: "error",
+ title: `Could not copy ${failed.length} ${noun(failed.length)} to ${input.target.label}`,
+ description: failed.join("\n"),
+ },
+ ),
+ );
+ })();
+}
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index ece2903be3d..a2dc82d03c4 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -19,6 +19,7 @@ import { resolveServerBackedAppDisplayName } from "../branding.logic";
import { AppSidebarLayout } from "../components/AppSidebarLayout";
import { CommandPalette } from "../components/CommandPalette";
import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";
+import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog";
import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
import { KeybindingsConfigWarning } from "../components/KeybindingsConfigWarning";
import { FirstRunGate } from "../components/onboarding/FirstRunGate";
@@ -245,6 +246,7 @@ function RootRouteView() {
<PermissionUpdateNotice />
{primaryEnvironmentAuthenticated ? <LegacyThreadMigrationToast /> : null}
<ProjectCloneToastCoordinator />
+ <AddProjectToMachineDialogHost />
<PullRequestGuideRunCoordinator />
<HostedStaticEnvironmentBootstrap />
{primaryEnvironmentAuthenticated ? (
diff --git a/packages/client-runtime/src/state/projectCommands.ts b/packages/client-runtime/src/state/projectCommands.ts
index ca9b8c7d024..645e3ed6308 100644
--- a/packages/client-runtime/src/state/projectCommands.ts
+++ b/packages/client-runtime/src/state/projectCommands.ts
@@ -135,6 +135,11 @@ export function createProjectEnvironmentAtoms<R, E>(
(result, isCurrent) => fileMetadata.rememberEntries(input.cwd, result.entries, isCurrent),
),
}),
+ listIgnoredFiles: createEnvironmentRpcQueryAtomFamily(runtime, {
+ label: "environment-data:projects:list-ignored-files",
+ tag: WS_METHODS.projectsListIgnoredFiles,
+ staleTimeMs: 15_000,
+ }),
readFile: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:projects:read-file",
tag: WS_METHODS.projectsReadFile,
diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts
index 98205f1f3cb..4272c9d12d9 100644
--- a/packages/contracts/src/environment.ts
+++ b/packages/contracts/src/environment.ts
@@ -141,6 +141,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
*/
agentActivityPublishing: Schema.optionalKey(Schema.Boolean),
projectCloneTracking: Schema.optionalKey(Schema.Boolean),
+ /** Server answers projects.listIgnoredFiles. */
+ ignoredFileListing: Schema.optionalKey(Schema.Boolean),
environmentIcon: Schema.optionalKey(Schema.Boolean),
desktopAppUpdate: Schema.optionalKey(Schema.Boolean),
/** Server answers orchestration.subscribeCommandOutput. Absent on older servers,
diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts
index ef4477575ff..5f71c47f71f 100644
--- a/packages/contracts/src/project.ts
+++ b/packages/contracts/src/project.ts
@@ -304,6 +304,25 @@ export const ProjectListEntriesResult = Schema.Struct({
});
export type ProjectListEntriesResult = typeof ProjectListEntriesResult.Type;
+// Untracked files git ignores. Wholly ignored folders such as `node_modules`
+// are left out, so the list stays small enough to pick from.
+export const ProjectListIgnoredFilesInput = Schema.Struct({
+ cwd: TrimmedNonEmptyString,
+});
+export type ProjectListIgnoredFilesInput = typeof ProjectListIgnoredFilesInput.Type;
+
+export const ProjectIgnoredFile = Schema.Struct({
+ path: TrimmedNonEmptyString,
+ byteLength: NonNegativeInt,
+});
+export type ProjectIgnoredFile = typeof ProjectIgnoredFile.Type;
+
+export const ProjectListIgnoredFilesResult = Schema.Struct({
+ files: Schema.Array(ProjectIgnoredFile),
+ truncated: Schema.Boolean,
+});
+export type ProjectListIgnoredFilesResult = typeof ProjectListIgnoredFilesResult.Type;
+
export const ProjectEntriesFailure = Schema.Literals([
"workspace_root_not_found",
"workspace_root_create_failed",
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index b74175d23c6..796e7af7164 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -224,6 +224,8 @@ import {
ProjectListEntriesError,
ProjectListEntriesInput,
ProjectListEntriesResult,
+ ProjectListIgnoredFilesInput,
+ ProjectListIgnoredFilesResult,
ProjectReadFileError,
ProjectReadFileInput,
ProjectReadFileResult,
@@ -376,6 +378,7 @@ export const WS_METHODS = {
projectsAdd: "projects.add",
projectsRemove: "projects.remove",
projectsListEntries: "projects.listEntries",
+ projectsListIgnoredFiles: "projects.listIgnoredFiles",
projectsReadFile: "projects.readFile",
projectsSearchContents: "projects.searchContents",
projectsSearchEntries: "projects.searchEntries",
@@ -1207,6 +1210,12 @@ const WsProjectsListEntriesRpc = Rpc.make(WS_METHODS.projectsListEntries, {
error: Schema.Union([ProjectListEntriesError, EnvironmentAuthorizationError]),
});
+const WsProjectsListIgnoredFilesRpc = Rpc.make(WS_METHODS.projectsListIgnoredFiles, {
+ payload: ProjectListIgnoredFilesInput,
+ success: ProjectListIgnoredFilesResult,
+ error: Schema.Union([ProjectListEntriesError, EnvironmentAuthorizationError]),
+});
+
const WsProjectsReadFileRpc = Rpc.make(WS_METHODS.projectsReadFile, {
payload: ProjectReadFileInput,
success: ProjectReadFileResult,
@@ -1959,6 +1968,7 @@ export const WsRpcGroup = RpcGroup.make(
WsProjectCloneRetryRpc,
WsSubscribeProjectClonesRpc,
WsProjectsListEntriesRpc,
+ WsProjectsListIgnoredFilesRpc,
WsProjectsReadFileRpc,
WsProjectsSearchContentsRpc,
WsProjectsSearchEntriesRpc,