Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(ide): pick a folder's GitHub repository once, use the app's GitHub login

rubenluetke10-beep5e4dba62e23c
diff --git a/jarvis/agentic_ide/git_overview.py b/jarvis/agentic_ide/git_overview.py
index 6572b1aba4..41af8eb05c 100644
--- a/jarvis/agentic_ide/git_overview.py
+++ b/jarvis/agentic_ide/git_overview.py
@@ -13,20 +13,20 @@ separate facts that are easy to mix up:
apart on purpose.
Local git is read on every call (a handful of fast plumbing commands). GitHub
-is read through the ``gh`` CLI with ONE GraphQL query per repository and
-cached per repository, so N open panes polling one project cost one network
-call per minute — shorter while a check is still running, because that is
-exactly when the user is waiting for the answer.
-
-Degrades, never raises: no git, not a repository, no ``gh``, ``gh`` not signed
-in, no GitHub remote — each comes back as ``available=False`` or
-``github.available=False`` with one plain sentence. Raw ``gh`` error text is
-logged, never returned: it may carry account or host details.
+is read for the repository the person picked for this folder ONCE
+(:mod:`jarvis.agentic_ide.github_link`), with their existing GitHub
+connection, in ONE GraphQL query per repository, cached per repository: N open
+panes polling one project cost one network call per minute — shorter while a
+check is still running, because that is exactly when the user is waiting.
+
+Degrades, never raises: no git, not a repository, GitHub not connected, no
+repository picked yet — each comes back as ``available=False`` or
+``github.available=False`` with a ``code`` the tab turns into the one next
+step (connect GitHub, pick the repository) and one plain sentence.
"""
from __future__ import annotations
-import json
import os
import shutil
import subprocess
@@ -38,10 +38,10 @@ from typing import Any
from loguru import logger
+from jarvis.agentic_ide import github_link
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
_GIT_TIMEOUT_S = 8.0
-_GH_TIMEOUT_S = 25.0
#: Most local branches listed; the newest by commit date win.
MAX_BRANCHES = 60
#: Most GitHub-only branches listed beside the local ones.
@@ -177,6 +177,15 @@ class BranchRow:
class GitHubState:
available: bool = False
reason: str = ""
+ #: What the tab offers next: ``not_connected`` (connect GitHub),
+ #: ``needs_repo`` (pick this folder's repository), another failure code, or "".
+ code: str = ""
+ #: The ``owner/name`` picked for this folder.
+ repo: str = ""
+ #: What the folder's git remote points at — the picker's recommendation.
+ suggested_repo: str = ""
+ #: ``app`` or ``gh``: which GitHub credential is in use.
+ source: str = ""
repo_url: str = ""
#: Epoch seconds of the GitHub answer in use.
fetched_at: float = 0.0
@@ -326,6 +335,7 @@ _PR_RANK = {"queued": 0, "open": 1, "draft": 2, "merged": 3, "closed": 4}
class _GitHubSnapshot:
ok: bool
reason: str = ""
+ code: str = ""
repo_url: str = ""
fetched_at: float = 0.0
prs: list[PullRequest] = field(default_factory=list)
@@ -380,54 +390,13 @@ def parse_github(payload: dict[str, Any], fetched_at: float = 0.0) -> _GitHubSna
return snap
-def _gh_failure_reason(stderr: str) -> str:
- text = stderr.lower()
- if "auth login" in text or "not logged" in text or "authentication" in text:
- return "The GitHub CLI (gh) is not signed in."
- if "known github host" in text or "no git remotes" in text or "set-default" in text:
- return "This repository has no GitHub remote gh can use."
- if "could not resolve to a repository" in text:
- return "GitHub does not know this repository, or this account cannot see it."
- if "rate limit" in text:
- return "GitHub's rate limit is reached; it resets within the hour."
- return "GitHub could not be reached."
-
-
-def _fetch_github(root: Path) -> _GitHubSnapshot:
+def _fetch_github(repo: str, token: str) -> _GitHubSnapshot:
now = time.time()
- if shutil.which("gh") is None:
- return _GitHubSnapshot(
- ok=False, reason="The GitHub CLI (gh) is not installed.", fetched_at=now
- )
- result = _run(
- [
- "api",
- "graphql",
- "-F",
- "owner={owner}",
- "-F",
- "name={repo}",
- "-f",
- f"query={_QUERY}",
- ],
- root,
- timeout=_GH_TIMEOUT_S,
- program="gh",
- )
- if result is None:
- return _GitHubSnapshot(ok=False, reason="GitHub did not answer in time.", fetched_at=now)
- if result.returncode != 0:
- # Logged for the maintainer, never shown: it may name the account or host.
- logger.debug("Git overview: gh graphql failed: {}", (result.stderr or "").strip()[:500])
- return _GitHubSnapshot(
- ok=False, reason=_gh_failure_reason(result.stderr or ""), fetched_at=now
- )
+ owner, _, name = repo.partition("/")
try:
- payload = json.loads(result.stdout or "{}")
- except json.JSONDecodeError: # answered as github.available=False with a reason
- return _GitHubSnapshot(
- ok=False, reason="GitHub sent an answer that could not be read.", fetched_at=now
- )
+ payload = github_link.graphql(token, _QUERY, {"owner": owner, "name": name})
+ except github_link.GitHubError as exc: # shown in the tab as github.reason/code
+ return _GitHubSnapshot(ok=False, reason=str(exc), code=exc.code, fetched_at=now)
return parse_github(payload, fetched_at=now)
@@ -447,29 +416,30 @@ class _GitHubCache:
return age < GITHUB_MIN_REFRESH_S
return age < (GITHUB_BUSY_TTL_S if snap.busy else GITHUB_TTL_S)
- def _load(self, key: str, root: Path, lock: threading.Lock, force: bool) -> _GitHubSnapshot:
+ def _load(self, key: str, token: str, lock: threading.Lock, force: bool) -> _GitHubSnapshot:
# One fetch per repository at a time; everyone else waits for its answer.
with lock:
snap = self._entries.get(key)
if self._fresh(snap, time.time(), force):
assert snap is not None
return snap
- snap = _fetch_github(root)
+ snap = _fetch_github(key, token)
self._entries[key] = snap
return snap
- def get(self, key: str, root: Path, *, force: bool = False) -> _GitHubSnapshot:
+ def get(self, key: str, token: str, *, force: bool = False) -> _GitHubSnapshot:
+ """``key`` is the repository (``owner/name``)."""
with self._guard:
lock = self._locks.setdefault(key, threading.Lock())
snap = self._entries.get(key)
if snap is None or force:
- return self._load(key, root, lock, force)
+ return self._load(key, token, lock, force)
if not self._fresh(snap, time.time(), False) and not lock.locked():
# Stale-while-revalidate: a poll never waits seconds for GitHub;
# it gets the last answer now and the new one on its next tick.
threading.Thread(
target=self._load,
- args=(key, root, lock, False),
+ args=(key, token, lock, False),
name="git-overview-github",
daemon=True,
).start()
@@ -606,6 +576,31 @@ def _attach_github(row: BranchRow, remote: str, snap: _GitHubSnapshot) -> None:
)
+def _github_for(root: Path, info: RepoOverview, refresh: bool) -> _GitHubSnapshot | None:
+ """GitHub's answer for the repository picked for ``root``, or None with
+ ``info.github`` saying what is missing (a connection, or the choice)."""
+ state = info.github
+ state.repo = github_link.bound_repository(root)
+ cred = github_link.credential()
+ if cred is None:
+ state.code = "not_connected"
+ state.reason = "GitHub is not connected yet."
+ return None
+ state.source = cred.source
+ if not state.repo:
+ state.code = "needs_repo"
+ state.reason = "Pick which GitHub repository this folder is."
+ state.suggested_repo = github_link.remote_repository(root)
+ return None
+ snap = _CACHE.get(state.repo, cred.token, force=refresh)
+ state.available = snap.ok
+ state.reason = snap.reason
+ state.code = snap.code
+ state.repo_url = snap.repo_url or f"https://github.com/{state.repo}"
+ state.fetched_at = snap.fetched_at
+ return snap if snap.ok else None
+
+
def overview(folder: str | Path, *, refresh: bool = False, github: bool = True) -> RepoOverview:
"""Branches of the repository ``folder`` is in, with merge, PR and CI state."""
path = Path(folder).expanduser()
@@ -630,16 +625,7 @@ def overview(folder: str | Path, *, refresh: bool = False, github: bool = True)
snap: _GitHubSnapshot | None = None
if github:
- common = (
- _out(["rev-parse", "--path-format=absolute", "--git-common-dir"], root) or ""
- ).strip()
- snap = _CACHE.get(os.path.normcase(common or str(root)), root, force=refresh)
- info.github = GitHubState(
- available=snap.ok,
- reason=snap.reason,
- repo_url=snap.repo_url,
- fetched_at=snap.fetched_at,
- )
+ snap = _github_for(root, info, refresh)
# Current and default branch always make the list, however old they are.
keep = {head, info.default_branch}
diff --git a/jarvis/agentic_ide/github_link.py b/jarvis/agentic_ide/github_link.py
new file mode 100644
index 0000000000..0966ac57b1
--- /dev/null
+++ b/jarvis/agentic_ide/github_link.py
@@ -0,0 +1,344 @@
+"""Which GitHub repository a workspace folder belongs to, and how to reach GitHub.
+
+The IDE's Git tab asks the person ONCE per folder: "which of your GitHub
+repositories is this?" — picked from a list of their own repositories. The
+answer is remembered per folder (per repository checkout, so every worktree of
+one repository shares it) in a small JSON file under the per-user data
+directory, never in the repo and never in ``jarvis.toml``.
+
+GitHub itself is reached over HTTPS with the credential the person already
+has, in this order:
+
+1. The app's own GitHub connection (Plugins → GitHub, one browser approval).
+2. The GitHub CLI's login (``gh auth token``), for people who use ``gh``.
+
+Nothing here ever asks for a pasted token. Error bodies from GitHub are logged
+at debug level and never returned: every failure maps to one fixed sentence.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import shutil
+import subprocess
+import threading
+import time
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+from jarvis.core.http_pool import SyncHttpClientPool
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+GRAPHQL_URL = "https://api.github.com/graphql"
+#: ``owner/name`` as GitHub allows it.
+REPO_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}$")
+#: How long the repository list is reused (it changes rarely).
+REPOS_TTL_S = 300.0
+#: Most repositories listed (three pages of 100).
+MAX_REPOS = 300
+
+_POOL = SyncHttpClientPool(timeout_s=20.0)
+
+
+class GitHubError(RuntimeError):
+ """A GitHub call that failed, worded for the person; ``code`` for the UI."""
+
+ def __init__(self, message: str, *, code: str = "error") -> None:
+ super().__init__(message)
+ self.code = code
+
+
+# ------------------------------------------------------------------ credential
+
+
+@dataclass(slots=True)
+class Credential:
+ token: str
+ #: ``app`` (the Plugins → GitHub connection) or ``gh`` (the GitHub CLI).
+ source: str
+
+
+def _app_token() -> str | None:
+ try:
+ from jarvis.marketplace.token_store import TokenStore
+
+ tokens = TokenStore().load("github")
+ except Exception as exc: # keyring unavailable (headless box): try gh next
+ logger.debug("GitHub link: app connection unreadable: {}", type(exc).__name__)
+ return None
+ if tokens is None or tokens.needs_reauth or not tokens.access:
+ return None
+ return tokens.access
+
+
+def _gh_token() -> str | None:
+ if shutil.which("gh") is None:
+ return None
+ env = dict(os.environ, GH_PROMPT_DISABLED="1", GH_NO_UPDATE_NOTIFIER="1")
+ try:
+ result = subprocess.run(
+ ["gh", "auth", "token"],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=8,
+ check=False,
+ env=env,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ logger.debug("GitHub link: gh auth token failed: {}", type(exc).__name__)
+ return None
+ token = result.stdout.strip()
+ return token if result.returncode == 0 and token else None
+
+
+def credential() -> Credential | None:
+ """The person's GitHub credential, or None when GitHub is not connected."""
+ token = _app_token()
+ if token:
+ return Credential(token=token, source="app")
+ token = _gh_token()
+ if token:
+ return Credential(token=token, source="gh")
+ return None
+
+
+# ------------------------------------------------------------------ GraphQL
+
+
+def graphql(token: str, query: str, variables: dict[str, Any] | None = None) -> dict[str, Any]:
+ """One GraphQL call; raises :class:`GitHubError` with a fixed sentence."""
+ try:
+ response = _POOL.client().post(
+ GRAPHQL_URL,
+ json={"query": query, "variables": variables or {}},
+ headers={
+ "Authorization": f"Bearer {token}",
+ "Accept": "application/vnd.github+json",
+ "User-Agent": "PersonalJarvis",
+ },
+ )
+ except Exception as exc: # network down, DNS, TLS: one sentence for all
+ logger.debug("GitHub link: request failed: {}", type(exc).__name__)
+ raise GitHubError("GitHub could not be reached.", code="unreachable") from exc
+ if response.status_code == 401:
+ raise GitHubError(
+ "The GitHub connection has expired. Connect GitHub again.", code="not_connected"
+ )
+ if response.status_code in (403, 429):
+ raise GitHubError(
+ "GitHub's rate limit is reached; it resets within the hour.", code="rate_limited"
+ )
+ if response.status_code >= 400:
+ logger.debug("GitHub link: HTTP {}", response.status_code)
+ raise GitHubError("GitHub could not be reached.", code="unreachable")
+ try:
+ payload = response.json()
+ except ValueError as exc:
+ raise GitHubError("GitHub sent an answer that could not be read.") from exc
+ if not isinstance(payload, dict):
+ raise GitHubError("GitHub sent an answer that could not be read.")
+ errors = payload.get("errors")
+ if errors and not payload.get("data"):
+ logger.debug("GitHub link: GraphQL errors: {}", str(errors)[:300])
+ text = str(errors).lower()
+ if "could not resolve to a repository" in text:
+ raise GitHubError(
+ "GitHub does not know this repository, or this account cannot see it.",
+ code="repo_missing",
+ )
+ raise GitHubError("GitHub could not answer this request.")
+ return payload
+
+
+# ------------------------------------------------------------------ repositories
+
+_REPOS_QUERY = """
+query($after: String) {
+ viewer {
+ login
+ repositories(first: 100, after: $after,
+ ownerAffiliations: [OWNER, COLLABORATOR, ORGANIZATION_MEMBER],
+ orderBy: {field: PUSHED_AT, direction: DESC}) {
+ pageInfo { hasNextPage endCursor }
+ nodes { nameWithOwner description isPrivate isFork url pushedAt }
+ }
+ }
+}
+"""
+
+
+@dataclass(slots=True)
+class RepoChoice:
+ name: str
+ description: str = ""
+ private: bool = False
+ fork: bool = False
+ url: str = ""
+ pushed_at: str = ""
+
+
+_repos_lock = threading.Lock()
+_repos_cache: dict[str, tuple[float, str, list[RepoChoice]]] = {}
+
+
+def list_repositories(cred: Credential, *, refresh: bool = False) -> tuple[str, list[RepoChoice]]:
+ """(login, the person's repositories newest-push first), cached for minutes."""
+ key = f"{cred.source}:{hash(cred.token)}"
+ with _repos_lock:
+ cached = _repos_cache.get(key)
+ if cached and not refresh and time.time() - cached[0] < REPOS_TTL_S:
+ return cached[1], list(cached[2])
+ login = ""
+ repos: list[RepoChoice] = []
+ after: str | None = None
+ while len(repos) < MAX_REPOS:
+ data = graphql(cred.token, _REPOS_QUERY, {"after": after}).get("data") or {}
+ viewer = data.get("viewer") or {}
+ login = str(viewer.get("login") or login)
+ page = viewer.get("repositories") or {}
+ for node in page.get("nodes") or []:
+ if isinstance(node, dict) and node.get("nameWithOwner"):
+ repos.append(
+ RepoChoice(
+ name=str(node["nameWithOwner"]),
+ description=str(node.get("description") or "")[:200],
+ private=bool(node.get("isPrivate")),
+ fork=bool(node.get("isFork")),
+ url=str(node.get("url") or ""),
+ pushed_at=str(node.get("pushedAt") or ""),
+ )
+ )
+ info = page.get("pageInfo") or {}
+ if not info.get("hasNextPage"):
+ break
+ after = info.get("endCursor")
+ with _repos_lock:
+ _repos_cache[key] = (time.time(), login, repos)
+ return login, list(repos)
+
+
+# ------------------------------------------------------------------ folder → repo
+
+
+def _store_path() -> Path:
+ from jarvis.core.paths import user_data_dir
+
+ return user_data_dir() / "agentic_ide" / "github_repos.json"
+
+
+_store_lock = threading.Lock()
+
+
+def folder_key(folder: str | Path) -> str:
+ """The key a folder's choice is stored under: its main checkout when it is
+ a git repository (so every worktree shares one answer), else the folder."""
+ path = Path(folder).expanduser()
+ try:
+ result = subprocess.run(
+ ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"],
+ cwd=str(path),
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=8,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ common = result.stdout.strip() if result.returncode == 0 else ""
+ except (OSError, subprocess.TimeoutExpired): # no git: the folder itself is the key
+ common = ""
+ base = Path(common).parent if common and Path(common).name == ".git" else path
+ try:
+ base = base.resolve()
+ except OSError: # unresolvable (network drive gone): keep the path as given
+ pass
+ return os.path.normcase(str(base))
+
+
+def _load() -> dict[str, str]:
+ try:
+ raw = json.loads(_store_path().read_text(encoding="utf-8"))
+ except FileNotFoundError: # nothing picked yet on this machine
+ return {}
+ except (OSError, ValueError) as exc:
+ logger.warning("GitHub link: repository choices unreadable, starting empty: {}", exc)
+ return {}
+ if not isinstance(raw, dict):
+ return {}
+ return {str(k): str(v) for k, v in raw.items() if isinstance(v, str) and REPO_RE.match(v)}
+
+
+def bound_repository(folder: str | Path) -> str:
+ """The ``owner/name`` chosen for this folder, or ``""``."""
+ with _store_lock:
+ return _load().get(folder_key(folder), "")
+
+
+def bind_repository(folder: str | Path, repo: str) -> str:
+ """Remember ``repo`` for this folder (``""`` forgets it). Returns the key."""
+ repo = repo.strip()
+ if repo and not REPO_RE.match(repo):
+ raise ValueError("A repository is written as owner/name.")
+ key = folder_key(folder)
+ with _store_lock:
+ choices = _load()
+ if repo:
+ choices[key] = repo
+ else:
+ choices.pop(key, None)
+ target = _store_path()
+ target.parent.mkdir(parents=True, exist_ok=True)
+ tmp = target.with_suffix(".json.tmp")
+ tmp.write_text(json.dumps(choices, indent=2, sort_keys=True), encoding="utf-8")
+ os.replace(tmp, target)
+ return key
+
+
+_REMOTE_RE = re.compile(
+ r"github\.com[:/]+(?P<owner>[A-Za-z0-9-]+)/(?P<name>[A-Za-z0-9._-]+?)(?:\.git)?/?$"
+)
+
+
+def remote_repository(folder: str | Path) -> str:
+ """The GitHub repository this folder's git remote points at, or ``""``.
+
+ Only a suggestion for the picker — ``origin`` first, then any other remote.
+ """
+ path = Path(folder).expanduser()
+ try:
+ result = subprocess.run(
+ ["git", "remote", "-v"],
+ cwd=str(path),
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=8,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except (OSError, subprocess.TimeoutExpired): # no git: nothing to suggest
+ return ""
+ found: list[tuple[int, str]] = []
+ for line in result.stdout.splitlines() if result.returncode == 0 else []:
+ parts = line.split()
+ if len(parts) < 2:
+ continue
+ match = _REMOTE_RE.search(parts[1])
+ if match:
+ found.append((0 if parts[0] == "origin" else 1, f"{match['owner']}/{match['name']}"))
+ found.sort(key=lambda item: item[0])
+ return found[0][1] if found else ""
+
+
+def repo_dicts(repos: list[RepoChoice]) -> list[dict[str, Any]]:
+ return [asdict(repo) for repo in repos]
diff --git a/jarvis/ui/web/agentic_ide_git_routes.py b/jarvis/ui/web/agentic_ide_git_routes.py
index 1e4067796c..f221bee7ad 100644
--- a/jarvis/ui/web/agentic_ide_git_routes.py
+++ b/jarvis/ui/web/agentic_ide_git_routes.py
@@ -4,6 +4,8 @@ Endpoints (all under ``/api/agentic-ide/git``)::
GET /inspect Branch, changes, ahead/behind, branches, worktrees
GET /overview A workspace's branches with merged-into, PR and CI state
+ GET /github/repos The person's GitHub repositories, for the one-time pick
+ PUT /github/binding Remember which GitHub repository a workspace folder is
POST /prepare Git half of opening a workspace or an agent
POST /commit Stage everything and commit
POST /push Push the current branch (sets upstream once)
@@ -26,7 +28,7 @@ from __future__ import annotations
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, Field
-from jarvis.agentic_ide import git_ops, git_overview
+from jarvis.agentic_ide import git_ops, git_overview, github_link
from jarvis.agentic_ide.git_ops import GitError, PrepareMode
from jarvis.agentic_ide.session import get_registry
@@ -92,6 +94,57 @@ def workspace_overview(
return git_overview.overview(session.folder, refresh=refresh).to_dict()
+class BindingRequest(BaseModel):
+ workspace_id: str = Field(..., min_length=1)
+ repo: str = Field("", max_length=200, description="owner/name; empty forgets the choice")
+
+
[email protected]("/github/repos", summary="The person's GitHub repositories")
+def github_repositories(refresh: bool = Query(False)) -> dict:
+ """What the Git tab's one-time "which repository is this folder?" list shows.
+
+ Uses the existing GitHub connection (Plugins → GitHub, else the GitHub
+ CLI's login). ``connected=false`` when there is none — the tab then offers
+ to connect instead of an empty list.
+ """
+ cred = github_link.credential()
+ if cred is None:
+ return {"connected": False, "source": "", "login": "", "repos": [], "reason": ""}
+ try:
+ login, repos = github_link.list_repositories(cred, refresh=refresh)
+ except github_link.GitHubError as exc:
+ return {
+ "connected": exc.code != "not_connected",
+ "source": cred.source,
+ "login": "",
+ "repos": [],
+ "reason": str(exc),
+ }
+ return {
+ "connected": True,
+ "source": cred.source,
+ "login": login,
+ "repos": github_link.repo_dicts(repos),
+ "reason": "",
+ }
+
+
[email protected]("/github/binding", summary="Remember a workspace folder's GitHub repository")
+def bind_github_repository(req: BindingRequest) -> dict:
+ """Asked once per folder; every worktree of the same repository shares it."""
+ session = get_registry().get(req.workspace_id)
+ if session is None:
+ raise HTTPException(status_code=404, detail="Workspace not found.")
+ try:
+ github_link.bind_repository(session.folder, req.repo)
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from None
+ except OSError as exc:
+ raise HTTPException(status_code=500, detail="The choice could not be saved.") from exc
+ git_overview.clear_cache()
+ return {"ok": True, "repo": req.repo.strip()}
+
+
@router.post("/prepare", summary="Prepare a checkout for a new workspace or agent")
def prepare_checkout(req: PrepareRequest) -> dict:
try:
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitHubRepoPicker.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitHubRepoPicker.tsx
new file mode 100644
index 0000000000..45d1b213ff
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitHubRepoPicker.tsx
@@ -0,0 +1,187 @@
+import { useEffect, useMemo, useState } from "react";
+import { Check, Github, Loader2, Lock, Search, X } from "lucide-react";
+import { fill, useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { useEventStore } from "@/store/events";
+import { bindGitHubRepo, fetchGitHubRepos, type GitHubRepoChoice, type GitHubRepoList } from "./gitOverviewApi";
+
+/** No GitHub credential at all: one button to the GitHub connection. */
+export function ConnectGitHubCard() {
+ const t = useT();
+ const setActiveSection = useEventStore((state) => state.setActiveSection);
+ return (
+ <div data-testid="git-connect-github" className="mx-3 my-3 space-y-2 rounded-lg border border-border/60 bg-muted/30 p-3">
+ <p className="text-[12.5px] font-medium text-foreground">{t("ide_side_panel.git.connect_title")}</p>
+ <p className="text-[11.5px] text-muted-foreground">{t("ide_side_panel.git.connect_body")}</p>
+ <button
+ type="button"
+ onClick={() => setActiveSection("plugins")}
+ className="inline-flex h-8 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <Github className="h-3.5 w-3.5" aria-hidden />
+ {t("ide_side_panel.git.connect_button")}
+ </button>
+ </div>
+ );
+}
+
+/**
+ * "Which of your GitHub repositories is this folder?" — asked once per
+ * folder. The repository the folder's git remote points at comes first,
+ * marked as the recommendation; one click remembers the choice.
+ */
+export function GitHubRepoPicker({
+ workspaceId,
+ current,
+ suggested,
+ onPicked,
+ onCancel,
+}: {
+ workspaceId: string;
+ /** The repository picked before, when the picker is reopened to change it. */
+ current: string;
+ suggested: string;
+ onPicked: () => void;
+ /** Present when there is already a choice to go back to. */
+ onCancel?: () => void;
+}) {
+ const t = useT();
+ const [list, setList] = useState<GitHubRepoList | null>(null);
+ const [error, setError] = useState("");
+ const [filter, setFilter] = useState("");
+ const [saving, setSaving] = useState("");
+
+ useEffect(() => {
+ let alive = true;
+ fetchGitHubRepos()
+ .then((next) => alive && setList(next))
+ .catch((err: Error) => alive && setError(err.message));
+ return () => {
+ alive = false;
+ };
+ }, []);
+
+ const repos = useMemo(() => {
+ const all = list?.repos ?? [];
+ // The folder's own remote leads, even when the list does not carry it
+ // (an organisation repository the account can read but is not a member of).
+ const lead: GitHubRepoChoice[] =
+ suggested && !all.some((repo) => repo.name.toLowerCase() === suggested.toLowerCase())
+ ? [{ name: suggested, description: "", private: false, fork: false, url: "", pushed_at: "" }]
+ : [];
+ const ordered = [...lead, ...all].sort(
+ (a, b) => Number(b.name.toLowerCase() === suggested.toLowerCase()) - Number(a.name.toLowerCase() === suggested.toLowerCase()),
+ );
+ const needle = filter.trim().toLowerCase();
+ return needle ? ordered.filter((repo) => repo.name.toLowerCase().includes(needle)) : ordered;
+ }, [list, suggested, filter]);
+
+ const pick = async (name: string) => {
+ setSaving(name);
+ setError("");
+ try {
+ await bindGitHubRepo(workspaceId, name);
+ onPicked();
+ } catch (err) {
+ setError((err as Error).message);
+ } finally {
+ setSaving("");
+ }
+ };
+
+ if (list && !list.connected) return <ConnectGitHubCard />;
+
+ return (
+ <div data-testid="git-repo-picker" className="flex min-h-0 flex-1 flex-col">
+ <div className="shrink-0 space-y-2 px-3 pb-2 pt-3">
+ <div className="flex items-start gap-2">
+ <div className="min-w-0 flex-1">
+ <p className="text-[12.5px] font-medium text-foreground">{t("ide_side_panel.git.pick_title")}</p>
+ <p className="text-[11.5px] text-muted-foreground">
+ {list?.login
+ ? fill(t("ide_side_panel.git.pick_body_login"), { login: list.login })
+ : t("ide_side_panel.git.pick_body")}
+ </p>
+ </div>
+ {onCancel && (
+ <button
+ type="button"
+ onClick={onCancel}
+ aria-label={t("ide_side_panel.git.pick_cancel")}
+ className="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground"
+ >
+ <X className="h-3.5 w-3.5" aria-hidden />
+ </button>
+ )}
+ </div>
+ <label className="flex h-8 items-center gap-2 rounded-lg border border-border/60 bg-background/50 px-2.5 focus-within:border-ring">
+ <Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
+ <input
+ autoFocus
+ value={filter}
+ onChange={(event) => setFilter(event.target.value)}
+ placeholder={t("ide_side_panel.git.pick_search")}
+ aria-label={t("ide_side_panel.git.pick_search")}
+ className="min-w-0 flex-1 bg-transparent text-xs text-foreground outline-none placeholder:text-muted-foreground"
+ />
+ </label>
+ {error && <p className="text-[11px] text-destructive">{error}</p>}
+ {list?.reason && <p className="text-[11px] text-destructive">{list.reason}</p>}
+ </div>
+ <ul className="min-h-0 flex-1 overflow-y-auto pb-2" aria-label={t("ide_side_panel.git.pick_title")}>
+ {!list && !error && (
+ <li className="flex items-center justify-center gap-2 px-4 py-6 text-xs text-muted-foreground">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
+ {t("ide_side_panel.git.pick_loading")}
+ </li>
+ )}
+ {list && repos.length === 0 && (
+ <li className="px-4 py-6 text-center text-xs text-muted-foreground">{t("ide_side_panel.git.pick_empty")}</li>
+ )}
+ {repos.map((repo) => {
+ const recommended = suggested !== "" && repo.name.toLowerCase() === suggested.toLowerCase();
+ const chosen = current !== "" && repo.name.toLowerCase() === current.toLowerCase();
+ return (
+ <li key={repo.name}>
+ <button
+ type="button"
+ data-testid="git-repo-choice"
+ data-repo={repo.name}
+ disabled={saving !== ""}
+ onClick={() => void pick(repo.name)}
+ className={cn(
+ "flex w-full items-start gap-2 px-3 py-1.5 text-left hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none disabled:opacity-60",
+ recommended && "bg-accent/10",
+ )}
+ >
+ {saving === repo.name ? (
+ <Loader2 className="mt-0.5 h-3.5 w-3.5 shrink-0 animate-spin text-muted-foreground" aria-hidden />
+ ) : chosen ? (
+ <Check className="mt-0.5 h-3.5 w-3.5 shrink-0 text-accent" aria-hidden />
+ ) : (
+ <Github className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
+ )}
+ <span className="flex min-w-0 flex-1 flex-col leading-tight">
+ <span className="flex min-w-0 items-center gap-1.5">
+ <span className="truncate font-mono text-[12px] text-foreground">{repo.name}</span>
+ {repo.private && <Lock className="h-3 w-3 shrink-0 text-muted-foreground" aria-label={t("ide_side_panel.git.pick_private")} />}
+ {recommended && (
+ <span className="shrink-0 rounded bg-accent/15 px-1 text-[9.5px] font-medium uppercase tracking-wide text-accent">
+ {t("ide_side_panel.git.pick_recommended")}
+ </span>
+ )}
+ </span>
+ {recommended ? (
+ <span className="text-[10.5px] text-muted-foreground">{t("ide_side_panel.git.pick_recommended_why")}</span>
+ ) : (
+ repo.description && <span className="truncate text-[10.5px] text-muted-foreground">{repo.description}</span>
+ )}
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx
index c5dafec9b9..f160da0829 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.test.tsx
@@ -53,7 +53,16 @@ const OVERVIEW: RepoOverview = {
head: "abc123def456",
default_branch: "main",
truncated: false,
- github: { available: true, reason: "", repo_url: "https://github.com/o/r", fetched_at: Date.now() / 1000 },
+ github: {
+ available: true,
+ reason: "",
+ code: "",
+ repo: "o/r",
+ suggested_repo: "o/r",
+ source: "app",
+ repo_url: "https://github.com/o/r",
+ fetched_at: Date.now() / 1000,
+ },
branches: [
branch("feature/wip", {
current: true,
@@ -78,16 +87,39 @@ const OVERVIEW: RepoOverview = {
};
let answer: unknown = OVERVIEW;
+let status = 200;
const calls: string[] = [];
+const puts: string[] = [];
+const REPOS = {
+ connected: true,
+ source: "app",
+ login: "octo",
+ reason: "",
+ repos: [
+ { name: "octo/other", description: "Something else", private: true, fork: false, url: "", pushed_at: "" },
+ { name: "o/r", description: "", private: false, fork: false, url: "", pushed_at: "" },
+ ],
+};
beforeEach(() => {
answer = OVERVIEW;
+ status = 200;
calls.length = 0;
+ puts.length = 0;
vi.stubGlobal(
"fetch",
- vi.fn(async (input: RequestInfo | URL) => {
- calls.push(String(input));
- return new Response(JSON.stringify(answer), { status: 200, headers: { "Content-Type": "application/json" } });
+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ calls.push(url);
+ const json = (body: unknown, code = 200) =>
+ new Response(JSON.stringify(body), { status: code, headers: { "Content-Type": "application/json" } });
+ if (url.includes("/github/repos")) return json(REPOS);
+ if (url.includes("/github/binding")) {
+ puts.push(String(init?.body));
+ answer = OVERVIEW;
+ return json({ ok: true, repo: "o/r" });
+ }
+ return json(answer, status);
}),
);
useEventStore.setState({ activeSection: "agentic-ide" });
@@ -178,4 +210,42 @@ describe("GitOverviewTab", () => {
render(<GitOverviewTab />);
expect((await screen.findByTestId("git-unavailable")).textContent).toContain("not a git repository");
});
+
+ it("asks once which GitHub repository the folder is, recommending its remote", async () => {
+ answer = { ...OVERVIEW, github: { ...OVERVIEW.github, available: false, code: "needs_repo", repo: "", repo_url: "" } };
+ render(<GitOverviewTab />);
+ // The recommendation is clickable at once; the rest of the list follows.
+ await vi.waitFor(() => expect(screen.getAllByTestId("git-repo-choice")).toHaveLength(2));
+ const choices = screen.getAllByTestId("git-repo-choice");
+ expect(choices.map((el) => el.dataset.repo)).toEqual(["o/r", "octo/other"]);
+ expect(choices[0].textContent).toContain("Recommended");
+ fireEvent.click(choices[0]);
+ await vi.waitFor(() => expect(puts).toEqual([JSON.stringify({ workspace_id: "w1", repo: "o/r" })]));
+ expect(await screen.findAllByTestId("git-branch-row")).toHaveLength(6);
+ expect(screen.queryByTestId("git-repo-picker")).toBeNull();
+ });
+
+ it("reopens the pick from the repository name to change it", async () => {
+ render(<GitOverviewTab />);
+ fireEvent.click(await screen.findByTestId("git-bound-repo"));
+ await vi.waitFor(() => expect(screen.getAllByTestId("git-repo-choice")).toHaveLength(2));
+ fireEvent.click(screen.getByLabelText("Keep the current repository"));
+ expect(await screen.findAllByTestId("git-branch-row")).toHaveLength(6);
+ });
+
+ it("offers to connect GitHub and still lists the local branches", async () => {
+ answer = { ...OVERVIEW, github: { ...OVERVIEW.github, available: false, code: "not_connected", repo: "" } };
+ render(<GitOverviewTab />);
+ expect(await screen.findByTestId("git-connect-github")).toBeTruthy();
+ expect(screen.getAllByTestId("git-branch-row")).toHaveLength(6);
+ fireEvent.click(screen.getByText("Connect GitHub"));
+ expect(useEventStore.getState().activeSection).toBe("plugins");
+ });
+
+ it("asks for one restart when the running backend does not know the route yet", async () => {
+ answer = { detail: "Not Found" };
+ status = 404;
+ render(<GitOverviewTab />);
+ expect((await screen.findByTestId("git-error")).textContent).toContain("Restart Jarvis once");
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx
index cabcef9f3b..d2f25a8138 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/GitOverviewTab.tsx
@@ -22,8 +22,10 @@ import { cn } from "@/lib/utils";
import { QuickTooltip } from "@/components/ui/tooltip";
import { useEventStore } from "@/store/events";
import { useIdeChatStore } from "@/store/ideChat";
+import { ConnectGitHubCard, GitHubRepoPicker } from "./GitHubRepoPicker";
import {
fetchGitOverview,
+ GitOverviewError,
type BranchRow,
type CiState,
type CiStatus,
@@ -101,6 +103,7 @@ function CiIcon({ state, className }: { state: CiState; className?: string }) {
function useGitOverview(workspaceId: string | null) {
const [data, setData] = useState<RepoOverview | null>(null);
const [error, setError] = useState("");
+ const [routeMissing, setRouteMissing] = useState(false);
const [loading, setLoading] = useState(false);
const [force, setForce] = useState(0);
useEffect(() => {
@@ -121,10 +124,14 @@ function useGitOverview(workspaceId: string | null) {
if (alive) {
setData(next);
setError("");
+ setRouteMissing(false);
}
} catch (err) {
// Keep the last answer on screen; the next tick tries again.
- if (alive) setError((err as Error).message);
+ if (alive) {
+ setError((err as Error).message);
+ setRouteMissing(err instanceof GitOverviewError && err.routeMissing);
+ }
} finally {
if (alive) setLoading(false);
}
@@ -137,7 +144,7 @@ function useGitOverview(workspaceId: string | null) {
window.clearTimeout(timer);
};
}, [workspaceId, force]);
- return { data, error, loading, refresh: () => setForce((value) => value + 1) };
+ return { data, error, routeMissing, loading, refresh: () => setForce((value) => value + 1) };
}
/** An icon that opens a GitHub page; a plain span when there is nowhere to go. */
@@ -355,14 +362,18 @@ export function GitOverviewTab() {
const t = useT();
const workspace = useIdeChatStore((state) => state.workspace);
const workspaceId = workspace?.id ?? null;
- const { data, error, loading, refresh } = useGitOverview(workspaceId);
+ const { data, error, routeMissing, loading, refresh } = useGitOverview(workspaceId);
const [showRemote, setShowRemote] = useState(false);
const [showLegend, setShowLegend] = useState(false);
+ // Reopened from the repository chip to change an earlier choice.
+ const [changing, setChanging] = useState(false);
+ useEffect(() => setChanging(false), [workspaceId]);
if (!workspace) {
return <p className="px-4 py-6 text-center text-xs text-muted-foreground">{t("ide_side_panel.git.no_workspace")}</p>;
}
const github = data?.github;
+ const picking = Boolean(data && workspaceId && (github?.code === "needs_repo" || (changing && github?.code !== "not_connected")));
const repoName = (data?.root || workspace.path).replace(/\\/g, "/").split("/").filter(Boolean).pop() ?? workspace.name;
return (
@@ -413,11 +424,24 @@ export function GitOverviewTab() {
</QuickTooltip>
</span>
</div>
- {github && (
- <p data-testid="git-github-state" className="truncate text-[10.5px] text-muted-foreground">
- {github.available
- ? fill(t("ide_side_panel.git.github_updated"), { when: sinceLabel(t, github.fetched_at) })
- : fill(t("ide_side_panel.git.github_off"), { reason: github.reason })}
+ {github?.repo && (
+ <p data-testid="git-github-state" className="flex min-w-0 items-center gap-1.5 text-[10.5px] text-muted-foreground">
+ <QuickTooltip content={t("ide_side_panel.git.change_repo")} side="bottom" className="inline-flex min-w-0">
+ <button
+ type="button"
+ data-testid="git-bound-repo"
+ onClick={() => setChanging(true)}
+ className="inline-flex min-w-0 items-center gap-1 rounded px-0.5 font-mono text-foreground/80 hover:bg-secondary hover:text-foreground"
+ >
+ <span className="truncate">{github.repo}</span>
+ </button>
+ </QuickTooltip>
+ <span aria-hidden>·</span>
+ <span className="min-w-0 truncate">
+ {github.available
+ ? fill(t("ide_side_panel.git.github_updated"), { when: sinceLabel(t, github.fetched_at) })
+ : github.reason}
+ </span>
</p>
)}
</div>
@@ -426,10 +450,26 @@ export function GitOverviewTab() {
<Legend />
</div>
)}
+ {picking && data && workspaceId ? (
+ <GitHubRepoPicker
+ key={workspaceId}
+ workspaceId={workspaceId}
+ current={github?.repo ?? ""}
+ suggested={github?.suggested_repo ?? ""}
+ onPicked={() => {
+ setChanging(false);
+ refresh();
+ }}
+ onCancel={github?.repo ? () => setChanging(false) : undefined}
+ />
+ ) : (
<div className="min-h-0 flex-1 overflow-y-auto py-1">
+ {github?.code === "not_connected" && <ConnectGitHubCard />}
{!data ? (
error ? (
- <p className="px-4 py-6 text-center text-xs text-destructive">{error}</p>
+ <p data-testid="git-error" className="px-4 py-6 text-center text-xs text-muted-foreground">
+ {routeMissing ? t("ide_side_panel.git.needs_restart") : error}
+ </p>
) : (
<p className="flex items-center justify-center gap-2 px-4 py-6 text-xs text-muted-foreground">
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
@@ -477,6 +517,7 @@ export function GitOverviewTab() {
</>
)}
</div>
+ )}
</section>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitOverviewApi.ts b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitOverviewApi.ts
index 8f8ac688ca..96b6e9924f 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitOverviewApi.ts
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/git/gitOverviewApi.ts
@@ -69,6 +69,14 @@ export interface BranchRow {
export interface GitHubState {
available: boolean;
reason: string;
+ /** The next step the tab offers: connect GitHub, pick the folder's repository, or a failure code. */
+ code: "" | "not_connected" | "needs_repo" | string;
+ /** The `owner/name` picked for this folder. */
+ repo: string;
+ /** What the folder's git remote points at — the picker's recommendation. */
+ suggested_repo: string;
+ /** `app` (Plugins → GitHub) or `gh` (the GitHub CLI). */
+ source: string;
repo_url: string;
/** Epoch seconds of the GitHub answer in use. */
fetched_at: number;
@@ -88,19 +96,67 @@ export interface RepoOverview {
github: GitHubState;
}
-export async function fetchGitOverview(workspaceId: string, refresh = false): Promise<RepoOverview> {
- const query = new URLSearchParams({ workspace_id: workspaceId });
- if (refresh) query.set("refresh", "true");
- const res = await fetch(`/api/agentic-ide/git/overview?${query.toString()}`);
+/** A failed call; `routeMissing` means the running backend predates this tab (restart once). */
+export class GitOverviewError extends Error {
+ readonly routeMissing: boolean;
+
+ constructor(message: string, routeMissing = false) {
+ super(message);
+ this.routeMissing = routeMissing;
+ }
+}
+
+async function call<T>(url: string, init?: RequestInit): Promise<T> {
+ const res = await fetch(url, init);
if (!res.ok) {
let message = `Request failed (${res.status}).`;
+ let detail: unknown;
try {
- const body = (await res.json()) as { detail?: unknown };
- if (typeof body.detail === "string") message = body.detail;
+ detail = ((await res.json()) as { detail?: unknown }).detail;
+ if (typeof detail === "string") message = detail;
} catch {
/* keep the status-code message */
}
- throw new Error(message);
+ // FastAPI's own 404 for an unknown path says exactly "Not Found"; this
+ // API's 404s always explain themselves ("Workspace not found.").
+ throw new GitOverviewError(message, res.status === 404 && detail === "Not Found");
}
- return (await res.json()) as RepoOverview;
+ return (await res.json()) as T;
+}
+
+export function fetchGitOverview(workspaceId: string, refresh = false): Promise<RepoOverview> {
+ const query = new URLSearchParams({ workspace_id: workspaceId });
+ if (refresh) query.set("refresh", "true");
+ return call<RepoOverview>(`/api/agentic-ide/git/overview?${query.toString()}`);
+}
+
+export interface GitHubRepoChoice {
+ /** `owner/name`. */
+ name: string;
+ description: string;
+ private: boolean;
+ fork: boolean;
+ url: string;
+ pushed_at: string;
+}
+
+export interface GitHubRepoList {
+ connected: boolean;
+ source: string;
+ login: string;
+ repos: GitHubRepoChoice[];
+ reason: string;
+}
+
+export function fetchGitHubRepos(refresh = false): Promise<GitHubRepoList> {
+ return call<GitHubRepoList>(`/api/agentic-ide/git/github/repos${refresh ? "?refresh=true" : ""}`);
+}
+
+/** Remember which repository this workspace's folder is; `""` forgets it. */
+export function bindGitHubRepo(workspaceId: string, repo: string): Promise<{ ok: boolean; repo: string }> {
+ return call(`/api/agentic-ide/git/github/binding`, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ workspace_id: workspaceId, repo }),
+ });
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 217308ca4e..105db74462 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -5816,6 +5816,21 @@
},
"git": {
"aria": "Branches, Pull Requests und CI",
+ "needs_restart": "Starte Jarvis einmal neu, damit der Git-Tab geladen wird.",
+ "connect_title": "Verbinde GitHub, um Pull Requests und CI zu sehen",
+ "connect_body": "Die Branches dieses Ordners erscheinen auch ohne. Das Verbinden ist eine Bestätigung im Browser.",
+ "connect_button": "GitHub verbinden",
+ "pick_title": "Welches GitHub-Repository ist dieser Ordner?",
+ "pick_body": "Das wählst du einmal pro Ordner.",
+ "pick_body_login": "Deine Repositories als {login}. Das wählst du einmal pro Ordner.",
+ "pick_search": "Repositories durchsuchen …",
+ "pick_loading": "Lade deine Repositories …",
+ "pick_empty": "Kein Repository passt.",
+ "pick_private": "Privat",
+ "pick_recommended": "Empfohlen",
+ "pick_recommended_why": "Das Git-Remote dieses Ordners zeigt hierhin.",
+ "pick_cancel": "Aktuelles Repository behalten",
+ "change_repo": "Anderes GitHub-Repository für diesen Ordner wählen",
"no_workspace": "Wähle einen Workspace, um seine Branches zu sehen.",
"loading": "Lese Branches aus Git und GitHub …",
"refresh": "Jetzt aus Git und GitHub aktualisieren",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 6b20accd8b..da2a97655f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -5849,6 +5849,21 @@
},
"git": {
"aria": "Branches, pull requests and CI",
+ "needs_restart": "Restart Jarvis once to load the Git tab.",
+ "connect_title": "Connect GitHub to see pull requests and CI",
+ "connect_body": "Branches from this folder show without it. Connecting takes one approval in the browser.",
+ "connect_button": "Connect GitHub",
+ "pick_title": "Which GitHub repository is this folder?",
+ "pick_body": "You pick this once per folder.",
+ "pick_body_login": "Your repositories as {login}. You pick this once per folder.",
+ "pick_search": "Search repositories…",
+ "pick_loading": "Loading your repositories…",
+ "pick_empty": "No repository matches.",
+ "pick_private": "Private",
+ "pick_recommended": "Recommended",
+ "pick_recommended_why": "This folder's git remote points here.",
+ "pick_cancel": "Keep the current repository",
+ "change_repo": "Pick a different GitHub repository for this folder",
"no_workspace": "Select a workspace to see its branches.",
"loading": "Reading branches from git and GitHub…",
"refresh": "Refresh from git and GitHub now",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 7e646917ad..0b7b0c93cb 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -5816,6 +5816,21 @@
},
"git": {
"aria": "Ramas, pull requests y CI",
+ "needs_restart": "Reinicia Jarvis una vez para cargar la pestaña Git.",
+ "connect_title": "Conecta GitHub para ver pull requests y CI",
+ "connect_body": "Las ramas de esta carpeta se ven igualmente. Conectar es una sola aprobación en el navegador.",
+ "connect_button": "Conectar GitHub",
+ "pick_title": "¿Qué repositorio de GitHub es esta carpeta?",
+ "pick_body": "Lo eliges una sola vez por carpeta.",
+ "pick_body_login": "Tus repositorios como {login}. Lo eliges una sola vez por carpeta.",
+ "pick_search": "Buscar repositorios…",
+ "pick_loading": "Cargando tus repositorios…",
+ "pick_empty": "Ningún repositorio coincide.",
+ "pick_private": "Privado",
+ "pick_recommended": "Recomendado",
+ "pick_recommended_why": "El remoto git de esta carpeta apunta aquí.",
+ "pick_cancel": "Mantener el repositorio actual",
+ "change_repo": "Elegir otro repositorio de GitHub para esta carpeta",
"no_workspace": "Selecciona un espacio de trabajo para ver sus ramas.",
"loading": "Leyendo ramas de git y GitHub…",
"refresh": "Actualizar ahora desde git y GitHub",
diff --git a/tests/unit/agentic_ide/test_git_overview.py b/tests/unit/agentic_ide/test_git_overview.py
index 7c5033cc94..48873018fa 100644
--- a/tests/unit/agentic_ide/test_git_overview.py
+++ b/tests/unit/agentic_ide/test_git_overview.py
@@ -8,7 +8,7 @@ from pathlib import Path
import pytest
-from jarvis.agentic_ide import git_overview
+from jarvis.agentic_ide import git_overview, github_link
from jarvis.agentic_ide.git_overview import ci_from_rollup, parse_github
needs_git = pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed")
@@ -190,10 +190,17 @@ def test_unreadable_payload_is_unavailable() -> None:
assert parse_github({"data": {"repository": None}}).ok is False
-def test_gh_failure_reasons_are_fixed_sentences() -> None:
- reason = git_overview._gh_failure_reason("To get started with GitHub CLI, run: gh auth login")
- assert reason == "The GitHub CLI (gh) is not signed in."
- assert git_overview._gh_failure_reason("secret host detail") == "GitHub could not be reached."
+def test_a_github_failure_becomes_a_coded_sentence(monkeypatch: pytest.MonkeyPatch) -> None:
+ def boom(token: str, query: str, variables: dict | None = None) -> dict:
+ raise github_link.GitHubError("GitHub could not be reached.", code="unreachable")
+
+ monkeypatch.setattr(github_link, "graphql", boom)
+ snap = git_overview._fetch_github("o/r", "t")
+ assert (snap.ok, snap.code, snap.reason) == (
+ False,
+ "unreachable",
+ "GitHub could not be reached.",
+ )
# ------------------------------------------------------------------ local git
@@ -227,10 +234,10 @@ def test_overview_joins_pull_requests_ci_and_squash_merges(
) -> None:
wip_head = _git(repo, "rev-parse", "feature/wip")
fresh_head = _git(repo, "rev-parse", "feature/fresh")
- calls: list[Path] = []
+ calls: list[str] = []
- def fake_fetch(root: Path) -> git_overview._GitHubSnapshot:
- calls.append(root)
+ def fake_fetch(repo_name: str, token: str) -> git_overview._GitHubSnapshot:
+ calls.append(repo_name)
snap = parse_github(
_payload(
[
@@ -265,7 +272,11 @@ def test_overview_joins_pull_requests_ci_and_squash_merges(
return snap
monkeypatch.setattr(git_overview, "_fetch_github", fake_fetch)
+ monkeypatch.setattr(github_link, "credential", lambda: github_link.Credential("t", "app"))
+ monkeypatch.setattr(github_link, "bound_repository", lambda folder: "o/r")
info = git_overview.overview(repo)
+ assert calls == ["o/r"]
+ assert (info.github.repo, info.github.source) == ("o/r", "app")
by_name = {row.name: row for row in info.branches}
wip = by_name["feature/wip"]
@@ -283,3 +294,64 @@ def test_overview_joins_pull_requests_ci_and_squash_merges(
# A second read inside the TTL reuses the answer instead of calling GitHub again.
git_overview.overview(repo)
assert len(calls) == 1
+
+
+# ------------------------------------------------------------------ the one-time pick
+
+
+def store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ target = tmp_path / "data" / "github_repos.json"
+ monkeypatch.setattr(github_link, "_store_path", lambda: target)
+ return target
+
+
+@needs_git
+def test_without_a_connection_the_tab_offers_to_connect(
+ repo: Path, monkeypatch: pytest.MonkeyPatch, store: Path
+) -> None:
+ monkeypatch.setattr(github_link, "credential", lambda: None)
+ info = git_overview.overview(repo)
+ assert info.available and info.branches # local git still works
+ assert (info.github.available, info.github.code) == (False, "not_connected")
+
+
+@needs_git
+def test_an_unpicked_folder_asks_once_and_suggests_its_remote(
+ repo: Path, monkeypatch: pytest.MonkeyPatch, store: Path
+) -> None:
+ monkeypatch.setattr(github_link, "credential", lambda: github_link.Credential("t", "gh"))
+ _git(repo, "remote", "add", "origin", "[email protected]:Octo-Org/my.app.git")
+ info = git_overview.overview(repo)
+ assert info.github.code == "needs_repo"
+ assert info.github.suggested_repo == "Octo-Org/my.app"
+
+ github_link.bind_repository(repo, "Octo-Org/my.app")
+ # A worktree of the same repository shares the answer.
+ tree = repo.parent / "tree"
+ _git(repo, "worktree", "add", "-q", str(tree), "feature/fresh")
+ assert github_link.bound_repository(tree) == "Octo-Org/my.app"
+ assert github_link.bound_repository(repo / ".") == "Octo-Org/my.app"
+
+ github_link.bind_repository(repo, "")
+ assert github_link.bound_repository(repo) == ""
+
+
+def test_a_malformed_choice_is_refused(tmp_path: Path, store: Path) -> None:
+ with pytest.raises(ValueError):
+ github_link.bind_repository(tmp_path, "not a repo")
+ store.parent.mkdir(parents=True)
+ store.write_text("{broken", encoding="utf-8")
+ assert github_link.bound_repository(tmp_path) == "" # unreadable file = no choice
+
+
+def test_remote_parsing_accepts_https_and_ssh(tmp_path: Path) -> None:
+ for url in (
+ "https://github.com/o/r.git",
+ "https://github.com/o/r",
+ "[email protected]:o/r.git",
+ "ssh://[email protected]/o/r.git",
+ ):
+ match = github_link._REMOTE_RE.search(url)
+ assert match is not None and f"{match['owner']}/{match['name']}" == "o/r", url
+ assert github_link._REMOTE_RE.search("https://gitlab.com/o/r.git") is None