Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions apps/server/src/git/Layers/GitCore.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { realpathSync } from "node:fs";

import {
Cache,
Data,
Expand Down Expand Up @@ -34,6 +36,14 @@ import { decodeJsonResult } from "@okcode/shared/schemaJson";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { resolveRuntimeEnvironment } from "../../runtimeEnvironment.ts";

function safeRealpath(value: string): string {
try {
return realpathSync(value);
} catch {
return value;
}
}

const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
Expand Down Expand Up @@ -1850,6 +1860,37 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
),
);

const cloneRepository: GitCoreShape["cloneRepository"] = (input) =>
Effect.gen(function* () {
// Extract repo name from URL for the target directory name
const urlPath = input.url.replace(/\.git$/, "");
const repoName = urlPath.split("/").pop() ?? "repo";
const clonePath = path.join(input.targetDir, repoName);

const args = ["clone", input.url, clonePath];
if (input.branch) {
args.push("--branch", input.branch);
}

yield* executeGit("GitCore.cloneRepository", input.targetDir, args, {
timeoutMs: 5 * 60_000, // 5 minutes for large repos
fallbackErrorMessage: "git clone failed",
});

// Read the current branch from the cloned repo
const branchOutput = yield* runGitStdout("GitCore.cloneRepository.branch", clonePath, [
"rev-parse",
"--abbrev-ref",
"HEAD",
]);
const branch = branchOutput.trim() || "main";

// Resolve to real path in case of symlinks
const resolvedPath = safeRealpath(clonePath);

return { path: resolvedPath, branch };
});

return {
execute,
status,
Expand All @@ -1872,6 +1913,7 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
checkoutBranch,
initRepo,
listLocalBranchNames,
cloneRepository,
} satisfies GitCoreShape;
});

Expand Down
9 changes: 9 additions & 0 deletions apps/server/src/git/Services/GitCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { ServiceMap } from "effect";
import type { Effect, Scope } from "effect";
import type {
GitCheckoutInput,
GitCloneRepositoryInput,
GitCloneRepositoryResult,
GitCreateBranchInput,
GitCreateWorktreeInput,
GitCreateWorktreeResult,
Expand Down Expand Up @@ -267,6 +269,13 @@ export interface GitCoreShape {
* List local branch names (short format).
*/
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;

/**
* Clone a remote repository into a target directory.
*/
readonly cloneRepository: (
input: GitCloneRepositoryInput,
) => Effect.Effect<GitCloneRepositoryResult, GitCommandError>;
}

/**
Expand Down
5 changes: 5 additions & 0 deletions apps/server/src/wsServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1082,6 +1082,11 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
return yield* git.initRepo(body);
}

case WS_METHODS.gitCloneRepository: {
const body = stripRequestTag(request.body);
return yield* git.cloneRepository(body);
}

case WS_METHODS.terminalOpen: {
const body = stripRequestTag(request.body);
const snapshot = yield* projectionReadModelQuery.getSnapshot();
Expand Down
58 changes: 58 additions & 0 deletions apps/web/src/components/ChatHomeEmptyState.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useNavigate } from "@tanstack/react-router";
import {
FolderOpenIcon,
FolderIcon,
GitBranchIcon,
GitMergeIcon,
GitPullRequestIcon,
SettingsIcon,
Expand All @@ -18,6 +19,7 @@ import { serverConfigQueryOptions } from "../lib/serverReactQuery";
import { newCommandId, newProjectId } from "../lib/utils";
import { readNativeApi } from "../nativeApi";
import { useStore } from "../store";
import { CloneRepositoryDialog } from "./CloneRepositoryDialog";
import { sortProjectsForSidebar } from "./Sidebar.logic";
import { ProviderSetupCard } from "./chat/ProviderSetupCard";
import { Button } from "./ui/button";
Expand All @@ -34,6 +36,7 @@ export function ChatHomeEmptyState() {
const threads = useStore((store) => store.threads);
const { handleNewThread } = useHandleNewThread();
const [isOpeningProject, setIsOpeningProject] = useState(false);
const [cloneDialogOpen, setCloneDialogOpen] = useState(false);

const recentProjects = useMemo(
() =>
Expand Down Expand Up @@ -113,6 +116,47 @@ export function ChatHomeEmptyState() {
setIsOpeningProject(false);
}, [appSettings.defaultThreadEnvMode, handleNewThread, isOpeningProject, projects]);

const handleCloned = useCallback(
async (result: { path: string; branch: string; repoName: string }) => {
const api = readNativeApi();
if (!api) return;

const existingProject = projects.find((project) => project.cwd === result.path);
if (existingProject) {
await handleNewThread(existingProject.id, {
envMode: appSettings.defaultThreadEnvMode,
}).catch(() => undefined);
return;
}

try {
const projectId = newProjectId();
await api.orchestration.dispatchCommand({
type: "project.create",
commandId: newCommandId(),
projectId,
title: result.repoName,
workspaceRoot: result.path,
defaultModel: DEFAULT_MODEL_BY_PROVIDER.codex,
createdAt: new Date().toISOString(),
});
await handleNewThread(projectId, {
envMode: appSettings.defaultThreadEnvMode,
}).catch(() => undefined);
} catch (error) {
toastManager.add({
type: "error",
title: "Failed to add project",
description:
error instanceof Error
? error.message
: "An unexpected error occurred while adding the project.",
});
}
},
[appSettings.defaultThreadEnvMode, handleNewThread, projects],
);

const startLatestThread = useCallback(async () => {
if (!latestProject) {
await openProjectFolder();
Expand Down Expand Up @@ -178,6 +222,14 @@ export function ChatHomeEmptyState() {
<FolderOpenIcon className="size-4" />
{isOpeningProject ? "Opening…" : "Open project folder"}
</Button>
<Button
variant="outline"
className="justify-start gap-2"
onClick={() => setCloneDialogOpen(true)}
>
<GitBranchIcon className="size-4" />
Clone from GitHub
</Button>
<Button
variant="outline"
className="justify-start gap-2"
Expand Down Expand Up @@ -253,6 +305,12 @@ export function ChatHomeEmptyState() {
)}
</div>
</div>

<CloneRepositoryDialog
open={cloneDialogOpen}
onOpenChange={setCloneDialogOpen}
onCloned={handleCloned}
/>
</div>
);
}
Loading
Loading