Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Conversation control bar: surface local git remote/branch + diff against HEAD (#166)

Robert Brennan22aa64f4822b
diff --git a/AGENTS.md b/AGENTS.md
index 33a8f03d03..e6ebc48f7d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -23,7 +23,7 @@
- `vitest.setup.ts` must guard DOM-specific globals (`HTMLCanvasElement`, `HTMLElement`, `window`) because some suites run in the Node environment instead of jsdom.
- `__tests__/components/providers/posthog-wrapper.test.tsx` must wrap `PostHogWrapper` in a `QueryClientProvider`; the wrapper now reads its client from React Query context instead of importing the global singleton.
-- `@openhands/typescript-client` is consumed directly from `github:OpenHands/typescript-client#4716d2e`; that package ships the needed subpath exports for `client/http-client`, `events/remote-events-list`, and `workspace/remote-workspace`.
+- `@openhands/typescript-client` is consumed directly from `github:OpenHands/typescript-client#6b9603f`; that package ships the needed subpath exports for `client/http-client`, `events/remote-events-list`, and `workspace/remote-workspace`. `RemoteWorkspace.gitChanges`/`gitDiff` accept an optional `{ ref }` option; agent-canvas passes `'HEAD'` so the changes panel reflects working-tree + index versus the latest commit (i.e. staged + unstaged) instead of a diff against the upstream/default branch.
- Shared TypeScript-client adapters live in `src/api/typescript-client.ts`; prefer those helpers for agent-server-backed REST/workspace/event/VS Code calls before falling back to `open-hands-axios`.
- Local verification/build gotchas:
- `npm run typecheck` assumes generated translation types exist; run `npm run make-i18n` first if `src/i18n/declaration.ts` is missing.
diff --git a/__tests__/api/v1-git-service.test.ts b/__tests__/api/v1-git-service.test.ts
index 603f4b3406..80ea76c0a6 100644
--- a/__tests__/api/v1-git-service.test.ts
+++ b/__tests__/api/v1-git-service.test.ts
@@ -48,7 +48,7 @@ describe("V1GitService", () => {
conversationUrl: "http://localhost:3000/api/conversations/123",
sessionApiKey: "my-session-key",
});
- expect(mockGitChanges).toHaveBeenCalledWith("/workspace/project");
+ expect(mockGitChanges).toHaveBeenCalledWith("/workspace/project", { ref: "HEAD" });
});
test("preserves slashes in path when using workspace helper", async () => {
@@ -61,7 +61,7 @@ describe("V1GitService", () => {
pathWithSlashes,
);
- expect(mockGitChanges).toHaveBeenCalledWith(pathWithSlashes);
+ expect(mockGitChanges).toHaveBeenCalledWith(pathWithSlashes, { ref: "HEAD" });
});
test("maps V1 git statuses to V0 format", async () => {
@@ -101,7 +101,7 @@ describe("V1GitService", () => {
conversationUrl: "http://localhost:3000/api/conversations/123",
sessionApiKey: "test-api-key",
});
- expect(mockGitDiff).toHaveBeenCalledWith("/workspace/project/file.ts");
+ expect(mockGitDiff).toHaveBeenCalledWith("/workspace/project/file.ts", { ref: "HEAD" });
});
test("preserves slashes in file path when using workspace helper", async () => {
@@ -114,7 +114,7 @@ describe("V1GitService", () => {
filePath,
);
- expect(mockGitDiff).toHaveBeenCalledWith(filePath);
+ expect(mockGitDiff).toHaveBeenCalledWith(filePath, { ref: "HEAD" });
});
test("returns the diff data from the response", async () => {
diff --git a/__tests__/utils/parse-git-remote-url.test.ts b/__tests__/utils/parse-git-remote-url.test.ts
new file mode 100644
index 0000000000..cbe73cde0d
--- /dev/null
+++ b/__tests__/utils/parse-git-remote-url.test.ts
@@ -0,0 +1,81 @@
+import { describe, it, expect } from "vitest";
+
+import { parseGitRemoteUrl } from "#/utils/parse-git-remote-url";
+
+describe("parseGitRemoteUrl", () => {
+ it("returns null for empty/whitespace input", () => {
+ expect(parseGitRemoteUrl(undefined)).toBeNull();
+ expect(parseGitRemoteUrl(null)).toBeNull();
+ expect(parseGitRemoteUrl("")).toBeNull();
+ expect(parseGitRemoteUrl(" ")).toBeNull();
+ });
+
+ it("parses HTTPS GitHub URLs and strips the .git suffix", () => {
+ const result = parseGitRemoteUrl("https://github.com/owner/repo.git");
+ expect(result).toEqual({
+ url: "https://github.com/owner/repo.git",
+ host: "github.com",
+ repository: "owner/repo",
+ provider: "github",
+ });
+ });
+
+ it("parses HTTPS GitHub URLs without a .git suffix", () => {
+ const result = parseGitRemoteUrl("https://github.com/owner/repo");
+ expect(result?.repository).toBe("owner/repo");
+ expect(result?.provider).toBe("github");
+ });
+
+ it("parses SSH-style git@host:owner/repo URLs", () => {
+ const result = parseGitRemoteUrl("[email protected]:owner/repo.git");
+ expect(result).toEqual({
+ url: "[email protected]:owner/repo.git",
+ host: "github.com",
+ repository: "owner/repo",
+ provider: "github",
+ });
+ });
+
+ it("parses ssh:// URLs", () => {
+ const result = parseGitRemoteUrl("ssh://[email protected]/owner/repo.git");
+ expect(result?.host).toBe("gitlab.com");
+ expect(result?.repository).toBe("owner/repo");
+ expect(result?.provider).toBe("gitlab");
+ });
+
+ it("parses Bitbucket Cloud URLs", () => {
+ const result = parseGitRemoteUrl(
+ "https://bitbucket.org/owner/repo.git",
+ );
+ expect(result?.provider).toBe("bitbucket");
+ expect(result?.repository).toBe("owner/repo");
+ });
+
+ it("normalizes Azure DevOps paths by removing the _git segment", () => {
+ const result = parseGitRemoteUrl(
+ "https://dev.azure.com/org/project/_git/repo",
+ );
+ expect(result?.provider).toBe("azure_devops");
+ expect(result?.repository).toBe("org/project/repo");
+ });
+
+ it("preserves nested paths for unknown self-hosted hosts", () => {
+ const result = parseGitRemoteUrl(
+ "https://git.example.com/group/subgroup/repo.git",
+ );
+ expect(result?.host).toBe("git.example.com");
+ expect(result?.repository).toBe("group/subgroup/repo");
+ expect(result?.provider).toBeNull();
+ });
+
+ it("handles SSH-style URLs against unknown hosts", () => {
+ const result = parseGitRemoteUrl("[email protected]:team/repo.git");
+ expect(result?.host).toBe("git.example.com");
+ expect(result?.repository).toBe("team/repo");
+ expect(result?.provider).toBeNull();
+ });
+
+ it("returns null for unparseable strings", () => {
+ expect(parseGitRemoteUrl("not a url")).toBeNull();
+ });
+});
diff --git a/package-lock.json b/package-lock.json
index e4f70dd1ff..9a1d7df650 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -12,7 +12,7 @@
"@heroui/react": "2.8.10",
"@microlink/react-json-view": "1.31.19",
"@monaco-editor/react": "4.7.0",
- "@openhands/typescript-client": "github:OpenHands/typescript-client#7d20f119d68893903c3eab7070416e6317f72716",
+ "@openhands/typescript-client": "github:OpenHands/typescript-client#6b9603f06ea0ecc9bc715bf2192e274c23cd3be6",
"@react-router/node": "7.14.2",
"@react-router/serve": "7.14.2",
"@tailwindcss/vite": "4.2.4",
@@ -3400,11 +3400,11 @@
},
"node_modules/@openhands/typescript-client": {
"version": "0.1.1",
- "resolved": "git+ssh://[email protected]/OpenHands/typescript-client.git#7d20f119d68893903c3eab7070416e6317f72716",
- "integrity": "sha512-WPm20BYImlFilbjKBXkHSa1EBT486Rc3vbJFSAMY/LHm7/78rMuKF8GO0uq0FhscM+q+vocJ62bYA5vC8Y2Zpw==",
+ "resolved": "git+ssh://[email protected]/OpenHands/typescript-client.git#6b9603f06ea0ecc9bc715bf2192e274c23cd3be6",
+ "integrity": "sha512-nna6lSh557v+ovhGESlCHz1X6rMmnFKrJF9n2L1Q8YeHb911Vmmxyk7bNKJQNqDsP/jVajzO8DLhNlgYX0nTvA==",
"license": "MIT",
"dependencies": {
- "@openrouter/sdk": "^0.12.21",
+ "@openrouter/sdk": "^0.12.25",
"ws": "^8.20.0"
}
},
diff --git a/package.json b/package.json
index f3ce5532e1..d8ae6fef63 100644
--- a/package.json
+++ b/package.json
@@ -11,7 +11,7 @@
"@heroui/react": "2.8.10",
"@microlink/react-json-view": "1.31.19",
"@monaco-editor/react": "4.7.0",
- "@openhands/typescript-client": "github:OpenHands/typescript-client#7d20f119d68893903c3eab7070416e6317f72716",
+ "@openhands/typescript-client": "github:OpenHands/typescript-client#6b9603f06ea0ecc9bc715bf2192e274c23cd3be6",
"@react-router/node": "7.14.2",
"@react-router/serve": "7.14.2",
"@tailwindcss/vite": "4.2.4",
diff --git a/src/api/git-service/git-service.api.ts b/src/api/git-service/git-service.api.ts
index 5bb7b70408..68a3c55ad7 100644
--- a/src/api/git-service/git-service.api.ts
+++ b/src/api/git-service/git-service.api.ts
@@ -157,6 +157,7 @@ class GitService {
await V1ConversationService.resolveConversationWorkingDir(conversationId);
const changes = await createRemoteWorkspace({ workingDir }).gitChanges(
workingDir,
+ { ref: "HEAD" },
);
return changes.map((change) => ({
@@ -173,7 +174,7 @@ class GitService {
_conversationId: string,
path: string,
): Promise<GitChangeDiff> {
- const diff = await createRemoteWorkspace().gitDiff(path);
+ const diff = await createRemoteWorkspace().gitDiff(path, { ref: "HEAD" });
return {
modified: diff.modified ?? "",
diff --git a/src/api/git-service/v1-git-service.api.ts b/src/api/git-service/v1-git-service.api.ts
index c6b1cb1bfe..709bb6e44d 100644
--- a/src/api/git-service/v1-git-service.api.ts
+++ b/src/api/git-service/v1-git-service.api.ts
@@ -45,6 +45,7 @@ class V1GitService {
if (active.kind === "cloud" && conversationUrl) {
const params = new URLSearchParams();
params.set("path", toAbsoluteRuntimePath(path));
+ params.set("ref", "HEAD");
const data = await callCloudProxy<V1GitChange[]>({
backend: active,
method: "GET",
@@ -71,7 +72,7 @@ class V1GitService {
const changes = await createRemoteWorkspace({
conversationUrl,
sessionApiKey,
- }).gitChanges(path);
+ }).gitChanges(path, { ref: "HEAD" });
if (!Array.isArray(changes)) {
throw new Error(
@@ -99,6 +100,7 @@ class V1GitService {
if (active.kind === "cloud" && conversationUrl) {
const params = new URLSearchParams();
params.set("path", toAbsoluteRuntimePath(path));
+ params.set("ref", "HEAD");
const diff = await callCloudProxy<GitChangeDiff & { diff?: string }>({
backend: active,
method: "GET",
@@ -117,7 +119,7 @@ class V1GitService {
const diff = (await createRemoteWorkspace({
conversationUrl,
sessionApiKey,
- }).gitDiff(path)) as GitChangeDiff & { diff?: string };
+ }).gitDiff(path, { ref: "HEAD" })) as GitChangeDiff & { diff?: string };
return {
modified: diff.modified ?? "",
diff --git a/src/components/features/chat/git-control-bar-branch-button.tsx b/src/components/features/chat/git-control-bar-branch-button.tsx
index 4c843729f2..8a3e931e97 100644
--- a/src/components/features/chat/git-control-bar-branch-button.tsx
+++ b/src/components/features/chat/git-control-bar-branch-button.tsx
@@ -24,8 +24,12 @@ export function GitControlBarBranchButton({
? settings?.provider_tokens_set[gitProvider]
: null;
- const hasBranch = selectedBranch && selectedRepository && gitProvider;
- const branchUrl = hasBranch
+ // Render the linked styling only when we have enough info to build a URL.
+ // Local-workspace fallbacks may give us a branch name without a known
+ // provider β€” show the branch text in that case but skip the external link.
+ const hasLinkableBranch =
+ !!selectedBranch && !!selectedRepository && !!gitProvider;
+ const branchUrl = hasLinkableBranch
? constructBranchUrl(
gitProvider,
selectedRepository,
@@ -34,16 +38,16 @@ export function GitControlBarBranchButton({
)
: undefined;
- const buttonText = hasBranch ? selectedBranch : t(I18nKey.COMMON$NO_BRANCH);
+ const buttonText = selectedBranch || t(I18nKey.COMMON$NO_BRANCH);
return (
<a
- href={hasBranch ? branchUrl : undefined}
+ href={hasLinkableBranch ? branchUrl : undefined}
target="_blank"
rel="noopener noreferrer"
className={cn(
"group flex flex-row items-center justify-between gap-2 pl-2.5 pr-2.5 py-1 rounded-[100px] w-fit flex-shrink-0 max-w-[200px] truncate relative",
- hasBranch
+ hasLinkableBranch
? "border border-[#525252] bg-transparent hover:border-[#454545] cursor-pointer"
: "border border-[rgba(71,74,84,0.50)] bg-transparent cursor-not-allowed min-w-[108px]",
)}
@@ -57,7 +61,7 @@ export function GitControlBarBranchButton({
>
{buttonText}
</div>
- {hasBranch && <GitExternalLinkIcon />}
+ {hasLinkableBranch && <GitExternalLinkIcon />}
</a>
);
}
diff --git a/src/components/features/chat/git-control-bar-repo-button.tsx b/src/components/features/chat/git-control-bar-repo-button.tsx
index 7e889d22a9..81a0343b2b 100644
--- a/src/components/features/chat/git-control-bar-repo-button.tsx
+++ b/src/components/features/chat/git-control-bar-repo-button.tsx
@@ -23,22 +23,24 @@ export function GitControlBarRepoButton({
const { t } = useTranslation("openhands");
const { data: settings } = useSettings();
- const hasRepository = selectedRepository && gitProvider;
+ // Render as an external link only when we know both the repo and the
+ // provider (so the URL is well-defined). Local-workspace fallbacks may
+ // populate `selectedRepository` without a provider; in that case we still
+ // show the repo name but keep the button non-link styling.
+ const hasLinkableRepo = !!selectedRepository && !!gitProvider;
// Get the host for the current provider from settings
const providerHost = gitProvider
? settings?.provider_tokens_set[gitProvider]
: null;
- const repositoryUrl = hasRepository
+ const repositoryUrl = hasLinkableRepo
? constructRepositoryUrl(gitProvider, selectedRepository, providerHost)
: undefined;
- const buttonText = hasRepository
- ? selectedRepository
- : t(I18nKey.COMMON$NO_REPO_CONNECTED);
+ const buttonText = selectedRepository || t(I18nKey.COMMON$NO_REPO_CONNECTED);
- if (hasRepository) {
+ if (hasLinkableRepo) {
return (
<a
href={repositoryUrl}
diff --git a/src/components/features/chat/git-control-bar.tsx b/src/components/features/chat/git-control-bar.tsx
index 10078fd74d..764f2203e3 100644
--- a/src/components/features/chat/git-control-bar.tsx
+++ b/src/components/features/chat/git-control-bar.tsx
@@ -6,6 +6,7 @@ import { GitControlBarPullButton } from "./git-control-bar-pull-button";
import { GitControlBarPushButton } from "./git-control-bar-push-button";
import { GitControlBarPrButton } from "./git-control-bar-pr-button";
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
+import { useLocalGitInfo } from "#/hooks/query/use-local-git-info";
import { useTaskPolling } from "#/hooks/query/use-task-polling";
import { useUnifiedWebSocketStatus } from "#/hooks/use-unified-websocket-status";
import { useSendMessage } from "#/hooks/use-send-message";
@@ -33,6 +34,7 @@ export function GitControlBar({ onSuggestionsClick }: GitControlBarProps) {
const { data: conversation } = useActiveConversation();
const { repositoryInfo } = useTaskPolling();
+ const { data: localGitInfo } = useLocalGitInfo();
const webSocketStatus = useUnifiedWebSocketStatus();
const webSocketStatusRef = useRef(webSocketStatus);
useEffect(() => {
@@ -45,16 +47,28 @@ export function GitControlBar({ onSuggestionsClick }: GitControlBarProps) {
}, [send]);
const { mutate: updateRepository } = useUpdateConversationRepository();
- // Priority: conversation data > task data
- // This ensures we show repository info immediately from task, then transition to conversation data
- const selectedRepository =
+ // Priority: conversation data > task data > locally-detected git info.
+ // The local fallback runs `git remote get-url origin` / `git rev-parse --abbrev-ref HEAD`
+ // in the conversation's working dir so local-workspace conversations can
+ // still display a repo and branch in the control bar.
+ const conversationRepository =
conversation?.selected_repository || repositoryInfo?.selectedRepository;
- const gitProvider = (conversation?.git_provider ||
- repositoryInfo?.gitProvider) as Provider;
- const selectedBranch =
+ const conversationProvider = (conversation?.git_provider ||
+ repositoryInfo?.gitProvider) as Provider | undefined;
+ const conversationBranch =
conversation?.selected_branch || repositoryInfo?.selectedBranch;
- const hasRepository = !!selectedRepository;
+ const selectedRepository =
+ conversationRepository || localGitInfo?.repository || undefined;
+ const gitProvider = (conversationProvider ||
+ localGitInfo?.provider) as Provider;
+ const selectedBranch =
+ conversationBranch || localGitInfo?.branch || undefined;
+
+ // Keep git actions (pull/push/PR) gated on the conversation actually being
+ // associated with a known git provider β€” local-only repos shouldn't enable
+ // those flows, so we only flip `hasRepository` for conversation/task data.
+ const hasRepository = !!conversationRepository;
// Enable buttons only when conversation exists and WS is connected
const isConversationReady = !!conversation && webSocketStatus === "OPEN";
@@ -124,7 +138,7 @@ export function GitControlBar({ onSuggestionsClick }: GitControlBarProps) {
<GitControlBarTooltipWrapper
tooltipMessage={t(I18nKey.COMMON$GIT_TOOLS_DISABLED_CONTENT)}
testId="git-control-bar-branch-button-tooltip"
- shouldShowTooltip={!hasRepository}
+ shouldShowTooltip={!selectedBranch}
>
<GitControlBarBranchButton
selectedBranch={selectedBranch}
diff --git a/src/hooks/query/use-local-git-info.ts b/src/hooks/query/use-local-git-info.ts
new file mode 100644
index 0000000000..59d55f6f1b
--- /dev/null
+++ b/src/hooks/query/use-local-git-info.ts
@@ -0,0 +1,91 @@
+import { useQuery } from "@tanstack/react-query";
+
+import { createRemoteWorkspace } from "#/api/typescript-client";
+import { useActiveConversation } from "#/hooks/query/use-active-conversation";
+import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";
+import { Provider } from "#/types/settings";
+import { parseGitRemoteUrl } from "#/utils/parse-git-remote-url";
+
+export interface LocalGitInfo {
+ repository: string | null;
+ branch: string | null;
+ provider: Provider | null;
+ remoteUrl: string | null;
+}
+
+const EMPTY_LOCAL_GIT_INFO: LocalGitInfo = {
+ repository: null,
+ branch: null,
+ provider: null,
+ remoteUrl: null,
+};
+
+/**
+ * For local-workspace conversations (no `selected_repository` recorded on the
+ * conversation), shell out via the agent server's bash-execute endpoint to
+ * read `git remote get-url origin` and the current branch from the
+ * conversation's working directory.
+ *
+ * Returns `null` fields when the working dir is not a git checkout β€” callers
+ * should treat that the same as "no repo detected".
+ */
+export const useLocalGitInfo = () => {
+ const { data: conversation } = useActiveConversation();
+ const runtimeIsReady = useRuntimeIsReady();
+
+ const conversationId = conversation?.id;
+ const conversationUrl = conversation?.conversation_url;
+ const sessionApiKey = conversation?.session_api_key;
+ const workingDir = conversation?.workspace?.working_dir?.trim();
+ const hasConversationRepo = !!conversation?.selected_repository;
+
+ return useQuery<LocalGitInfo>({
+ queryKey: [
+ "local-git-info",
+ conversationId,
+ conversationUrl,
+ sessionApiKey,
+ workingDir,
+ ],
+ queryFn: async () => {
+ const workspace = createRemoteWorkspace({
+ conversationUrl,
+ sessionApiKey,
+ });
+
+ const [remoteResult, branchResult] = await Promise.all([
+ workspace.executeCommand("git remote get-url origin", workingDir, 10),
+ workspace.executeCommand(
+ "git rev-parse --abbrev-ref HEAD",
+ workingDir,
+ 10,
+ ),
+ ]);
+
+ const remoteUrl =
+ remoteResult.exit_code === 0 ? remoteResult.stdout.trim() : "";
+ const rawBranch =
+ branchResult.exit_code === 0 ? branchResult.stdout.trim() : "";
+ const branch = rawBranch && rawBranch !== "HEAD" ? rawBranch : null;
+
+ if (!remoteUrl && !branch) return EMPTY_LOCAL_GIT_INFO;
+
+ const parsedRemote = parseGitRemoteUrl(remoteUrl);
+ return {
+ repository: parsedRemote?.repository ?? null,
+ provider: parsedRemote?.provider ?? null,
+ remoteUrl: remoteUrl || null,
+ branch,
+ };
+ },
+ enabled:
+ runtimeIsReady &&
+ !!conversationId &&
+ !!workingDir &&
+ !hasConversationRepo,
+ retry: false,
+ staleTime: 1000 * 60,
+ gcTime: 1000 * 60 * 5,
+ meta: { disableToast: true },
+ });
+};
diff --git a/src/utils/parse-git-remote-url.ts b/src/utils/parse-git-remote-url.ts
new file mode 100644
index 0000000000..12f0e5c3c5
--- /dev/null
+++ b/src/utils/parse-git-remote-url.ts
@@ -0,0 +1,87 @@
+import { Provider } from "#/types/settings";
+
+export interface ParsedGitRemoteUrl {
+ /** Original URL, trimmed. */
+ url: string;
+ /** Hostname of the remote (e.g. `github.com`, `git.example.com`). */
+ host: string | null;
+ /** Path-style identifier, normalized to `owner/repo` (no leading slash, no `.git` suffix). */
+ repository: string | null;
+ /** Best-effort provider detection from the host. `null` for unrecognized/self-hosted hosts. */
+ provider: Provider | null;
+}
+
+const KNOWN_HOSTS: Record<string, Provider> = {
+ "github.com": "github",
+ "gitlab.com": "gitlab",
+ "bitbucket.org": "bitbucket",
+ "dev.azure.com": "azure_devops",
+};
+
+function stripGitSuffix(path: string): string {
+ return path.replace(/\.git$/, "");
+}
+
+function detectProvider(host: string | null): Provider | null {
+ if (!host) return null;
+ return KNOWN_HOSTS[host.toLowerCase()] ?? null;
+}
+
+function normalizeAzureDevOpsPath(path: string): string {
+ // Azure paths look like `org/project/_git/repo` or `org/_git/repo`.
+ // Normalize to `org/project/repo` (or `org/repo`) so it lines up with
+ // constructBranchUrl's expectations.
+ const segments = path.split("/").filter(Boolean);
+ const gitIndex = segments.indexOf("_git");
+ if (gitIndex === -1) return segments.join("/");
+ return [...segments.slice(0, gitIndex), ...segments.slice(gitIndex + 1)].join(
+ "/",
+ );
+}
+
+function buildParsedGitRemoteUrl(
+ url: string,
+ host: string | null,
+ rawPath: string,
+): ParsedGitRemoteUrl {
+ const path = stripGitSuffix(rawPath.replace(/^\/+/, ""));
+ const provider = detectProvider(host);
+ const repository =
+ provider === "azure_devops" ? normalizeAzureDevOpsPath(path) : path;
+
+ return {
+ url,
+ host,
+ repository: repository || null,
+ provider,
+ };
+}
+
+/**
+ * Parse a git remote URL (HTTPS, SSH, or `git@host:path` shorthand) into its
+ * host, repository (`owner/repo`), and best-effort provider.
+ *
+ * Returns `null` if the URL is empty or unparseable. Unknown hosts still
+ * resolve `host` and `repository`; only `provider` is left `null`.
+ */
+export function parseGitRemoteUrl(
+ remoteUrl: string | null | undefined,
+): ParsedGitRemoteUrl | null {
+ const url = remoteUrl?.trim();
+ if (!url) return null;
+
+ // git@host:owner/repo(.git)
+ const scpMatch = url.match(/^[^@\s]+@([^:\s]+):(.+)$/);
+ if (scpMatch) {
+ const host = scpMatch[1];
+ return buildParsedGitRemoteUrl(url, host, scpMatch[2]);
+ }
+
+ // ssh://, https://, http://, git://
+ try {
+ const parsed = new URL(url);
+ return buildParsedGitRemoteUrl(url, parsed.hostname || null, parsed.pathname);
+ } catch {
+ return null;
+ }
+}