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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(ide): explorer tab with git changes, diffs and drag-to-terminal
rubenluetke10-beep7766e8b5d357
diff --git a/jarvis/agentic_ide/git_changes.py b/jarvis/agentic_ide/git_changes.pynew file mode 100644index 0000000000..b3d88c453c--- /dev/null+++ b/jarvis/agentic_ide/git_changes.py@@ -0,0 +1,368 @@+"""What the agents changed in a workspace: git status and per-file diffs.++The IDE's Explorer tab shows which files an agent touched and, on a click,+exactly how — removed lines red, added lines green. Everything here is read+through the ``git`` CLI, the one git implementation that is on every machine+that has git at all, and every call is bounded:++* **Workspace-scoped.** A workspace may be a sub-folder of a repository; only+ changes under that folder are reported, with paths relative to it — the same+ paths the file tree uses.+* **Degrades, never raises.** No git, not a repository, a repository without+ commits, a timeout: each comes back as an honest ``available=False`` or an+ empty list, never an exception into a route.+* **Capped.** A repository with thousands of generated files must not turn one+ poll into a multi-megabyte answer; untracked folders stay collapsed the way+ ``git status`` shows them, and lists and diffs are cut with ``truncated``.+"""++from __future__ import annotations++import subprocess+from dataclasses import dataclass, field+from pathlib import Path, PurePosixPath++from loguru import logger++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++_GIT_TIMEOUT_S = 8.0+#: Most changed files reported in one answer.+MAX_CHANGED_FILES = 500+#: Most diff lines returned for one file; the rest is summarised by ``truncated``.+MAX_DIFF_LINES = 4000+#: Untracked text files up to this size have their lines counted and shown.+MAX_UNTRACKED_BYTES = 512 * 1024+++@dataclass(slots=True)+class ChangedFile:+ """One changed path, relative to the workspace root."""++ path: str+ #: ``modified`` | ``added`` | ``deleted`` | ``untracked`` | ``conflicted``+ status: str+ added: int | None = None+ removed: int | None = None+ is_directory: bool = False+++@dataclass(slots=True)+class WorkspaceChanges:+ available: bool+ branch: str = ""+ files: list[ChangedFile] = field(default_factory=list)+ truncated: bool = False+ #: Why ``available`` is false, in one plain sentence.+ reason: str = ""+++@dataclass(slots=True)+class DiffLine:+ #: ``add`` | ``del`` | ``ctx``+ kind: str+ text: str+ old_no: int | None = None+ new_no: int | None = None+++@dataclass(slots=True)+class DiffHunk:+ header: str+ lines: list[DiffLine] = field(default_factory=list)+++@dataclass(slots=True)+class FileDiff:+ path: str+ status: str+ binary: bool = False+ hunks: list[DiffHunk] = field(default_factory=list)+ added: int = 0+ removed: int = 0+ truncated: bool = False+++def _git(args: list[str], cwd: Path) -> subprocess.CompletedProcess[str] | None:+ """Run git; None when git is missing or does not answer in time."""+ try:+ return subprocess.run(+ ["git", "-c", "core.quotePath=false", *args],+ cwd=str(cwd),+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=_GIT_TIMEOUT_S,+ check=False,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except FileNotFoundError:+ return None+ except subprocess.TimeoutExpired:+ logger.info("Agentic IDE git changes: git timed out in {}", cwd)+ return None+++def _repo_prefix(folder: Path) -> tuple[bool, str, str]:+ """(is a repo, the folder's path inside the repo with a trailing /, reason)."""+ result = _git(["rev-parse", "--show-prefix"], folder)+ if result is None:+ return False, "", "Git is not installed or did not answer."+ if result.returncode != 0:+ return False, "", "This folder is not a git repository."+ return True, result.stdout.strip(), ""+++def _strip_prefix(repo_path: str, prefix: str) -> str | None:+ """A repo-relative path as a workspace-relative one, or None if outside."""+ if not prefix:+ return repo_path+ return repo_path[len(prefix) :] if repo_path.startswith(prefix) else None+++def _status_word(xy: str) -> str:+ if xy == "??":+ return "untracked"+ if "U" in xy or xy in {"AA", "DD"}:+ return "conflicted"+ if "D" in xy:+ return "deleted"+ if "A" in xy:+ return "added"+ return "modified"+++def _has_head(folder: Path) -> bool:+ result = _git(["rev-parse", "--verify", "--quiet", "HEAD"], folder)+ return result is not None and result.returncode == 0+++def _count_lines(path: Path) -> int | None:+ try:+ if path.stat().st_size > MAX_UNTRACKED_BYTES:+ return None+ data = path.read_bytes()+ except OSError:+ return None+ if b"\0" in data[:8000]:+ return None+ if not data:+ return 0+ return data.count(b"\n") + (0 if data.endswith(b"\n") else 1)+++def workspace_changes(folder: str | Path) -> WorkspaceChanges:+ """Every changed path under ``folder``, with line counts where cheap."""+ root = Path(folder).expanduser()+ if not root.is_dir():+ return WorkspaceChanges(available=False, reason="The workspace folder is missing.")+ is_repo, prefix, reason = _repo_prefix(root)+ if not is_repo:+ return WorkspaceChanges(available=False, reason=reason)++ branch_result = _git(["rev-parse", "--abbrev-ref", "HEAD"], root)+ branch = branch_result.stdout.strip() if branch_result and branch_result.returncode == 0 else ""++ status = _git(+ ["status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=normal", "--", "."],+ root,+ )+ if status is None or status.returncode != 0:+ return WorkspaceChanges(+ available=False, branch=branch, reason="Git could not read the changes."+ )++ counts: dict[str, tuple[int | None, int | None]] = {}+ numstat_args = ["diff", "--numstat", "-z", "--no-renames"]+ if _has_head(root):+ numstat_args.append("HEAD")+ numstat = _git([*numstat_args, "--", "."], root)+ if numstat is not None and numstat.returncode == 0:+ for record in numstat.stdout.split("\0"):+ parts = record.split("\t")+ if len(parts) != 3:+ continue+ added, removed, repo_path = parts+ counts[repo_path] = (+ int(added) if added.isdigit() else None,+ int(removed) if removed.isdigit() else None,+ )++ files: list[ChangedFile] = []+ truncated = False+ for record in status.stdout.split("\0"):+ if len(record) < 4:+ continue+ xy, repo_path = record[:2], record[3:]+ rel = _strip_prefix(repo_path, prefix)+ if rel is None or not rel:+ continue+ if len(files) >= MAX_CHANGED_FILES:+ truncated = True+ break+ word = _status_word(xy)+ is_dir = rel.endswith("/")+ added, removed = counts.get(repo_path, (None, None))+ if word == "untracked" and not is_dir:+ added, removed = _count_lines(root / rel), 0+ files.append(+ ChangedFile(+ path=rel.rstrip("/"),+ status=word,+ added=added,+ removed=removed,+ is_directory=is_dir,+ )+ )+ files.sort(key=lambda item: item.path.lower())+ return WorkspaceChanges(available=True, branch=branch, files=files, truncated=truncated)+++def normalize_workspace_path(folder: str | Path, path: str) -> str:+ """A path printed or picked in the IDE as a workspace-relative POSIX path.++ Accepts a workspace-relative path or an absolute one inside the workspace.+ The file need not exist — a deleted file still has a diff. Raises+ ``ValueError`` for anything that would leave the workspace.+ """+ value = path.strip().replace("\\", "/")+ if not value:+ raise ValueError("No path given.")+ root = Path(folder).expanduser().resolve()+ candidate = Path(value).expanduser()+ if candidate.is_absolute():+ try:+ rel = candidate.resolve().relative_to(root).as_posix()+ except (OSError, ValueError) as exc:+ raise ValueError("That path is outside the open workspace.") from exc+ else:+ posix = PurePosixPath(value[2:] if value.startswith("./") else value)+ if ".." in posix.parts:+ raise ValueError("That path is outside the open workspace.")+ rel = posix.as_posix()+ try:+ (root / rel).resolve().relative_to(root)+ except (OSError, ValueError) as exc:+ raise ValueError("That path is outside the open workspace.") from exc+ if rel in {"", "."}:+ raise ValueError("That is the workspace folder itself.")+ return rel+++def _parse_unified(text: str) -> tuple[list[DiffHunk], int, int, bool, bool]:+ """Hunks, added, removed, binary, truncated from ``git diff`` output."""+ hunks: list[DiffHunk] = []+ added = removed = shown = 0+ old_no = new_no = 0+ truncated = False+ for line in text.splitlines():+ if line.startswith("Binary files ") and line.endswith(" differ"):+ return [], 0, 0, True, False+ if line.startswith("@@"):+ header = line+ try:+ spans = line.split("@@")[1].strip().split(" ")+ old_no = int(spans[0][1:].split(",")[0])+ new_no = int(spans[1][1:].split(",")[0])+ except (IndexError, ValueError):+ old_no = new_no = 0+ hunks.append(DiffHunk(header=header))+ continue+ if not hunks:+ continue # the file header before the first hunk+ if line.startswith("\\"):+ continue # "\ No newline at end of file"+ kind = {"+": "add", "-": "del"}.get(line[:1], "ctx")+ if kind == "add":+ added += 1+ elif kind == "del":+ removed += 1+ if shown >= MAX_DIFF_LINES:+ truncated = True+ continue+ shown += 1+ hunks[-1].lines.append(+ DiffLine(+ kind=kind,+ text=line[1:],+ old_no=None if kind == "add" else old_no,+ new_no=None if kind == "del" else new_no,+ )+ )+ if kind != "add":+ old_no += 1+ if kind != "del":+ new_no += 1+ return hunks, added, removed, False, truncated+++def file_diff(folder: str | Path, path: str) -> FileDiff:+ """How one file differs from the last commit; an untracked file is all new."""+ rel = normalize_workspace_path(folder, path)+ root = Path(folder).expanduser()+ is_repo, prefix, _reason = _repo_prefix(root)+ if not is_repo:+ return FileDiff(path=rel, status="unchanged")++ status = _git(+ ["status", "--porcelain=v1", "-z", "--no-renames", "--untracked-files=all", "--", rel], root+ )+ record = next(+ (item for item in (status.stdout.split("\0") if status else []) if len(item) >= 4), ""+ )+ word = _status_word(record[:2]) if record else "unchanged"++ if word == "untracked":+ target = root / rel+ count = _count_lines(target)+ if count is None:+ return FileDiff(path=rel, status=word, binary=target.is_file())+ text = target.read_text(encoding="utf-8", errors="replace")+ lines = text.splitlines()+ shown = lines[:MAX_DIFF_LINES]+ hunk = DiffHunk(+ header=f"@@ -0,0 +1,{len(lines)} @@",+ lines=[+ DiffLine(kind="add", text=line, new_no=index + 1)+ for index, line in enumerate(shown)+ ],+ )+ return FileDiff(+ path=rel,+ status=word,+ hunks=[hunk],+ added=len(lines),+ truncated=len(lines) > len(shown),+ )++ args = ["diff", "--no-color", "--no-ext-diff", "--no-renames", "-U3"]+ if _has_head(root):+ args.append("HEAD")+ diff = _git([*args, "--", rel], root)+ if diff is None or diff.returncode != 0:+ return FileDiff(path=rel, status=word)+ hunks, added, removed, binary, truncated = _parse_unified(diff.stdout)+ return FileDiff(+ path=rel,+ status=word,+ binary=binary,+ hunks=hunks,+ added=added,+ removed=removed,+ truncated=truncated,+ )+++__all__ = [+ "MAX_CHANGED_FILES",+ "MAX_DIFF_LINES",+ "ChangedFile",+ "DiffHunk",+ "DiffLine",+ "FileDiff",+ "WorkspaceChanges",+ "file_diff",+ "normalize_workspace_path",+ "workspace_changes",+]diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 9461db0c0f..faf91703a4 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -83,6 +83,7 @@ from jarvis.agentic_ide import (agent_transcript,drop_analysis,drops,+ git_changes,interrupted,native_picker,notifications,@@ -828,6 +829,52 @@ class WorkspaceFilesResponse(BaseModel):error: str | None = None+class ChangedFileItem(BaseModel):+ """One path an agent changed, relative to the workspace root."""++ path: str+ status: str = Field(description="'modified', 'added', 'deleted', 'untracked' or 'conflicted'.")+ added: int | None = Field(default=None, description="Lines added; null when unknown.")+ removed: int | None = Field(default=None, description="Lines removed; null when unknown.")+ is_directory: bool = False+++class WorkspaceChangesResponse(BaseModel):+ """What git reports as changed under the workspace folder."""++ workspace_id: str+ available: bool = Field(description="False when git or the repository is not usable.")+ branch: str = ""+ files: list[ChangedFileItem] = Field(default_factory=list)+ truncated: bool = False+ reason: str = ""+++class DiffLineItem(BaseModel):+ kind: str = Field(description="'add', 'del' or 'ctx'.")+ text: str+ old_no: int | None = None+ new_no: int | None = None+++class DiffHunkItem(BaseModel):+ header: str+ lines: list[DiffLineItem] = Field(default_factory=list)+++class WorkspaceFileDiffResponse(BaseModel):+ """One file's difference from the last commit; an untracked file is all new."""++ workspace_id: str+ path: str+ status: str+ binary: bool = False+ added: int = 0+ removed: int = 0+ hunks: list[DiffHunkItem] = Field(default_factory=list)+ truncated: bool = False++class WorkspaceFilePreviewResponse(BaseModel):"""A bounded in-app preview without exposing an absolute host path."""@@ -1572,6 +1619,53 @@ async def get_workspace_files(workspace_id: str, path: str = "") -> WorkspaceFil)+ "/workspaces/{workspace_id}/changes",+ response_model=WorkspaceChangesResponse,+ summary="Files the agents changed in an open workspace",+)+async def get_workspace_changes(workspace_id: str) -> WorkspaceChangesResponse:+ """Git's view of what changed under the workspace folder.++ Paths are relative to the workspace, like the file tree's. A folder that is+ not a repository, or a machine without git, answers ``available=false`` with+ the reason rather than an error: the explorer still works without it.+ """+ session = get_registry().get(workspace_id)+ if session is None:+ raise HTTPException(status_code=404, detail="Workspace not found.")+ changes = await asyncio.to_thread(git_changes.workspace_changes, session.folder)+ return WorkspaceChangesResponse(+ workspace_id=workspace_id,+ available=changes.available,+ branch=changes.branch,+ files=[ChangedFileItem(**asdict(item)) for item in changes.files],+ truncated=changes.truncated,+ reason=changes.reason,+ )+++ "/workspaces/{workspace_id}/diff",+ response_model=WorkspaceFileDiffResponse,+ summary="How one workspace file differs from the last commit",+)+async def get_workspace_file_diff(workspace_id: str, path: str) -> WorkspaceFileDiffResponse:+ """Removed and added lines of one file, for the explorer's diff view.++ ``path`` may be workspace-relative or an absolute path inside the workspace+ (what a terminal printed). Anything outside the workspace is refused.+ """+ session = get_registry().get(workspace_id)+ if session is None:+ raise HTTPException(status_code=404, detail="Workspace not found.")+ try:+ diff = await asyncio.to_thread(git_changes.file_diff, session.folder, path)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from None+ return WorkspaceFileDiffResponse(workspace_id=workspace_id, **asdict(diff))++@router.get("/folders/search", response_model=SearchResponse, summary="Search folders by name")async def search(q: str, limit: int = 40) -> SearchResponse:"""Find folders by name across the home and conventional code directories.diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/IdeSidePanel.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/IdeSidePanel.test.tsxindex f49cf01f7d..e271dc3e90 100644--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/IdeSidePanel.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/IdeSidePanel.test.tsx@@ -65,7 +65,7 @@ describe("IdeSidePanel", () => {});it("disables + while every tab is already open", () => {- act(() => useIdeSidePanelStore.getState().setOpen(true));+ act(() => useIdeSidePanelStore.setState({ open: true, tabs: ["agents", "files"], active: "agents" }));render(<Harness />);expect((screen.getByTestId("ide-side-panel-add") as HTMLButtonElement).disabled).toBe(true);});@@ -86,4 +86,14 @@ describe("IdeSidePanel", () => {render(<IdeSidePanelToggle />);expect(screen.queryByTestId("ide-side-panel-toggle")).toBeNull();});++ it("leaves a labelled rail on the right edge while closed, and opens at the tab picked there", () => {+ render(<Harness />);+ const rail = screen.getByTestId("ide-side-panel-rail");+ expect(rail.textContent).toContain("Agents");+ expect(rail.textContent).toContain("Explorer");+ fireEvent.click(screen.getByTestId("ide-side-panel-rail-files"));+ expect(useIdeSidePanelStore.getState()).toMatchObject({ open: true, active: "files" });+ expect(screen.queryByTestId("ide-side-panel-rail")).toBeNull();+ });});diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/IdeSidePanel.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/IdeSidePanel.tsxindex 375cb9a64e..cb03ad15b4 100644--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/IdeSidePanel.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/IdeSidePanel.tsx@@ -1,10 +1,14 @@import { useEffect, useRef, useState, type ReactNode } from "react";import { MoveHorizontal, PanelRightClose, Plus, X } from "lucide-react";-import { useT } from "@/i18n";+import { fill, useT } from "@/i18n";import { cn } from "@/lib/utils";import { useResizablePane } from "@/hooks/useResizablePane";import { PaneResizer } from "@/components/layout/PaneResizer";import { useIdeSidePanelStore } from "@/store/ideSidePanel";+import { useExplorerPathRouting } from "@/store/ideExplorer";+import { useIdeProjectsStore } from "@/store/ideProjects";+import { useWorkspacePanes } from "@/store/workspacePanes";+import { dotKindFor, workspaceAgents } from "./agentStatus";import { SIDE_PANEL_TABS, sidePanelTab } from "./sidePanelTabs";const WIDTH_KEY = "jarvis.agenticIde.sidePanelWidth.v1";@@ -32,6 +36,8 @@ const HEADER_BTN =export function IdeSidePanelFrame({ children }: { children: ReactNode }) {const t = useT();const open = useIdeSidePanelStore((state) => state.open);+ // Ctrl+click on a path in any terminal opens it in the Explorer tab.+ useExplorerPathRouting();const frame = useRef<HTMLDivElement>(null);const [frameWidth, setFrameWidth] = useState(0);@@ -99,10 +105,60 @@ export function IdeSidePanelFrame({ children }: { children: ReactNode }) {</>)}</div>+ {!open && <IdeSidePanelRail />}</div>);}+/**+ * The closed panel's edge: one labelled button per tab, always in view.+ *+ * The caption toggle alone was easy to miss (maintainer, 2026-09-28), so a+ * closed panel leaves this narrow rail on the right edge — the way an editor's+ * activity bar does — and an agent waiting for the user shows up here as a+ * count even while the panel is shut.+ */+function IdeSidePanelRail() {+ const t = useT();+ const openTab = useIdeSidePanelStore((state) => state.openTab);+ const activeWorkspaceId = useIdeProjectsStore((state) => state.activeWorkspaceId);+ const panes = useWorkspacePanes();+ const waiting = workspaceAgents(panes, activeWorkspaceId).filter((pane) => dotKindFor(pane) === "waiting").length;+ return (+ <nav+ data-testid="ide-side-panel-rail"+ aria-label={t("ide_side_panel.rail_aria")}+ className="flex h-full w-12 shrink-0 flex-col items-center gap-1.5 border-l border-border/60 bg-card/40 py-2"+ >+ {SIDE_PANEL_TABS.map((tab) => {+ const label = t(tab.labelKey);+ const badge = tab.id === "agents" && waiting > 0 ? waiting : 0;+ return (+ <button+ key={tab.id}+ type="button"+ data-testid={`ide-side-panel-rail-${tab.id}`}+ onClick={() => openTab(tab.id)}+ title={label}+ aria-label={badge ? `${label} (${fill(t("ide_side_panel.rail_waiting"), { n: badge })})` : label}+ aria-controls={SIDE_PANEL_ID}+ aria-expanded={false}+ className="relative flex w-10 flex-col items-center gap-0.5 rounded-lg py-1.5 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <tab.icon className="h-[18px] w-[18px]" aria-hidden />+ <span className="max-w-full truncate text-[9.5px] font-medium leading-none">{label}</span>+ {badge > 0 && (+ <span className="absolute right-0.5 top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-warning px-1 text-[10px] font-semibold tabular-nums text-background">+ {badge}+ </span>+ )}+ </button>+ );+ })}+ </nav>+ );+}+/** The panel itself: tab header ("+" and collapse) over the active tab's content. */export function IdeSidePanel() {const t = useT();diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/DiffView.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/DiffView.tsxnew file mode 100644index 0000000000..d83c2aac7b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/DiffView.tsx@@ -0,0 +1,58 @@+import { cn } from "@/lib/utils";+import type { DiffHunk } from "./explorerApi";++/**+ * A unified diff, read top to bottom: removed lines red, added lines green,+ * unchanged context in the body ink, with both line numbers in the gutter.+ */+export function DiffView({ hunks }: { hunks: DiffHunk[] }) {+ return (+ <div data-testid="explorer-diff" className="min-w-max font-mono text-[12px] leading-[1.55]">+ {hunks.map((hunk, index) => (+ <div key={`${hunk.header}-${index}`}>+ <div className="sticky top-0 z-[1] border-y border-border/60 bg-muted/80 px-3 py-1 text-[11px] text-muted-foreground backdrop-blur-sm">+ {hunk.header}+ </div>+ {hunk.lines.map((line, row) => (+ <div+ key={row}+ data-kind={line.kind}+ className={cn(+ "flex",+ line.kind === "add" && "bg-success/10",+ line.kind === "del" && "bg-destructive/10",+ )}+ >+ <span className="w-10 shrink-0 select-none pr-2 text-right tabular-nums text-muted-foreground/70">+ {line.old_no ?? ""}+ </span>+ <span className="w-10 shrink-0 select-none pr-2 text-right tabular-nums text-muted-foreground/70">+ {line.new_no ?? ""}+ </span>+ <span+ aria-hidden="true"+ className={cn(+ "w-4 shrink-0 select-none text-center",+ line.kind === "add" && "text-success",+ line.kind === "del" && "text-destructive",+ )}+ >+ {line.kind === "add" ? "+" : line.kind === "del" ? "−" : ""}+ </span>+ <span+ className={cn(+ "whitespace-pre pr-4",+ line.kind === "add" && "text-success",+ line.kind === "del" && "text-destructive",+ line.kind === "ctx" && "text-foreground/80",+ )}+ >+ {line.text || " "}+ </span>+ </div>+ ))}+ </div>+ ))}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsxnew file mode 100644index 0000000000..396576eb9a--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.test.tsx@@ -0,0 +1,136 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { renderHook } from "@testing-library/react";+import { ExplorerPanel } from "./ExplorerPanel";+import { WORKSPACE_PATH_TYPE } from "@/components/agentic/paneDrop";+import { activateTerminalLink } from "@/lib/terminalLinks";+import { useEventStore } from "@/store/events";+import { useIdeChatStore } from "@/store/ideChat";+import { useExplorerPathRouting, useIdeExplorerStore } from "@/store/ideExplorer";+import { useIdeSidePanelStore } from "@/store/ideSidePanel";++const CHANGES = {+ workspace_id: "w1",+ available: true,+ branch: "main",+ truncated: false,+ reason: "",+ files: [+ { path: "src/app.ts", status: "modified", added: 3, removed: 1, is_directory: false },+ { path: "old.md", status: "deleted", added: 0, removed: 4, is_directory: false },+ ],+};++const DIFF = {+ workspace_id: "w1",+ path: "src/app.ts",+ status: "modified",+ binary: false,+ added: 1,+ removed: 1,+ truncated: false,+ hunks: [+ {+ header: "@@ -1,2 +1,2 @@",+ lines: [+ { kind: "ctx", text: "keep", old_no: 1, new_no: 1 },+ { kind: "del", text: "before", old_no: 2, new_no: null },+ { kind: "add", text: "after", old_no: null, new_no: 2 },+ ],+ },+ ],+};++const calls: string[] = [];++function respond(url: string): unknown {+ if (url.includes("/changes")) return CHANGES;+ if (url.includes("/diff?")) return DIFF;+ if (url.includes("/files")) {+ return { workspace_id: "w1", root_name: "app", path: "", truncated: false, entries: [+ { name: "src", path: "src", is_directory: true, is_symlink: false },+ { name: "README.md", path: "README.md", is_directory: false, is_symlink: false },+ ] };+ }+ return {};+}++beforeEach(() => {+ calls.length = 0;+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {+ const url = String(input);+ calls.push(url);+ return new Response(JSON.stringify(respond(url)), { status: 200, headers: { "Content-Type": "application/json" } });+ }));+ useEventStore.setState({ activeSection: "agentic-ide" });+ useIdeChatStore.setState({ workspace: { id: "w1", name: "App", path: "/code/app" }, stagedPane: null });+ useIdeExplorerStore.setState({ view: "changes", opened: null });+ useIdeSidePanelStore.setState({ open: false, tabs: ["agents", "files"], active: "agents" });+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("ExplorerPanel", () => {+ it("lists what changed — deleted red, edited green — with line counts and the branch", async () => {+ render(<ExplorerPanel />);+ const rows = await screen.findAllByTestId("explorer-change-row");+ expect(rows.map((row) => row.dataset.path)).toEqual(["src/app.ts", "old.md"]);+ expect(rows[0].textContent).toContain("+3");+ expect(rows[0].textContent).toContain("−1");+ expect(rows[0].querySelector("[data-status]")?.className).toContain("text-success");+ expect(rows[1].querySelector("[data-status]")?.className).toContain("text-destructive");+ expect(screen.getByTestId("explorer-branch").textContent).toBe("main");+ });++ it("hands a terminal the absolute path when a row is dragged", async () => {+ render(<ExplorerPanel />);+ const [row] = await screen.findAllByTestId("explorer-change-row");+ const data: Record<string, string> = {};+ const dataTransfer = { setData: (type: string, value: string) => { data[type] = value; }, effectAllowed: "" };+ fireEvent.dragStart(row, { dataTransfer });+ expect(data[WORKSPACE_PATH_TYPE]).toBe("/code/app/src/app.ts");+ });++ it("opens a changed file as a diff with removed and added lines", async () => {+ render(<ExplorerPanel />);+ const [row] = await screen.findAllByTestId("explorer-change-row");+ fireEvent.click(row);+ const diff = await screen.findByTestId("explorer-diff");+ expect(diff.querySelector('[data-kind="del"]')?.textContent).toContain("before");+ expect(diff.querySelector('[data-kind="add"]')?.textContent).toContain("after");+ expect(diff.querySelector('[data-kind="del"]')?.className).toContain("bg-destructive/10");+ expect(diff.querySelector('[data-kind="add"]')?.className).toContain("bg-success/10");+ });++ it("shows the folder as a lazy tree in the Files view", async () => {+ useIdeExplorerStore.setState({ view: "files" });+ render(<ExplorerPanel />);+ await waitFor(() => expect(screen.getAllByTestId("explorer-tree-row")).toHaveLength(2));+ const rows = screen.getAllByTestId("explorer-tree-row");+ expect(rows.map((row) => row.dataset.path)).toEqual(["src", "README.md"]);+ // The folder holds a change, so it carries the marker while collapsed.+ await waitFor(() => expect(rows[0].querySelector(".bg-success\\/80")).not.toBeNull());+ });+});++describe("terminal path clicks", () => {+ it("open the file in the Explorer instead of the OS when the IDE is mounted", async () => {+ renderHook(() => useExplorerPathRouting());+ act(() =>+ activateTerminalLink(new MouseEvent("click", { button: 0, ctrlKey: true }), "src/app.ts", { workspaceId: "w1" }),+ );+ expect(useIdeExplorerStore.getState().opened).toEqual({ workspaceId: "w1", path: "src/app.ts" });+ expect(useIdeSidePanelStore.getState()).toMatchObject({ open: true, active: "files" });+ expect(calls.some((url) => url.includes("terminal-target"))).toBe(false);+ });++ it("fall back to the OS for another workspace's pane", () => {+ renderHook(() => useExplorerPathRouting());+ activateTerminalLink(new MouseEvent("click", { button: 0, ctrlKey: true }), "src/app.ts", { workspaceId: "w9" });+ expect(useIdeExplorerStore.getState().opened).toBeNull();+ expect(calls.some((url) => url.includes("terminal-target"))).toBe(true);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.tsxnew file mode 100644index 0000000000..7fb81ed624--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/ExplorerPanel.tsx@@ -0,0 +1,614 @@+import { useCallback, useEffect, useMemo, useRef, useState, type DragEvent } from "react";+import {+ ArrowLeft,+ ChevronRight,+ ExternalLink,+ Folder,+ FolderOpen,+ GitBranch,+ Loader2,+ RefreshCw,+ Search,+ SquareArrowOutUpRight,+ X,+} from "lucide-react";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import {+ attachToTerminal,+ fetchWorkspaceFilePreview,+ fetchWorkspaceFiles,+ openTerminalTarget,+ workspaceFileUrl,+ type WorkspaceFileItem,+ type WorkspaceFilePreviewResponse,+} from "@/lib/agenticIdeApi";+import { WORKSPACE_PATH_TYPE } from "@/components/agentic/paneDrop";+import { useEventStore } from "@/store/events";+import { useIdeChatStore } from "@/store/ideChat";+import { useIdeExplorerStore } from "@/store/ideExplorer";+import { DiffView } from "./DiffView";+import {+ absoluteWorkspacePath,+ fetchFileDiff,+ fetchWorkspaceChanges,+ type ChangeStatus,+ type ChangedFile,+ type FileDiff,+ type WorkspaceChanges,+} from "./explorerApi";+import { fileIcon } from "./fileIcon";++/** How often git is asked what changed while the Explorer is on screen. */+const CHANGES_POLL_MS = 6000;+const CHANGES_JITTER_MS = 1200;++/** Deleted is red; everything an agent added or edited is green. */+const STATUS_TONE: Record<ChangeStatus, string> = {+ modified: "text-success",+ added: "text-success",+ untracked: "text-success",+ deleted: "text-destructive",+ conflicted: "text-warning",+};+const STATUS_LETTER: Record<ChangeStatus, string> = {+ modified: "M",+ added: "A",+ untracked: "U",+ deleted: "D",+ conflicted: "!",+};++const baseName = (path: string) => path.split("/").filter(Boolean).pop() ?? path;+const parentPath = (path: string) => path.split("/").slice(0, -1).join("/");++/** Start a drag that a terminal pane turns into a file reference. */+function startFileDrag(event: DragEvent, absolute: string): void {+ event.dataTransfer.setData(WORKSPACE_PATH_TYPE, absolute);+ event.dataTransfer.setData("text/plain", absolute);+ event.dataTransfer.effectAllowed = "copy";+}++function useWorkspaceChanges(workspaceId: string | null) {+ const [changes, setChanges] = useState<WorkspaceChanges | null>(null);+ const [error, setError] = useState("");+ const [nonce, setNonce] = useState(0);+ useEffect(() => {+ if (!workspaceId) {+ setChanges(null);+ return;+ }+ let alive = true;+ let timer: number | undefined;+ const tick = async () => {+ if (useEventStore.getState().activeSection === "agentic-ide") {+ try {+ const next = await fetchWorkspaceChanges(workspaceId);+ if (alive) {+ setChanges(next);+ setError("");+ }+ } catch (err) {+ // Keep the last answer; the next tick tries again.+ if (alive) setError((err as Error).message);+ }+ }+ if (alive) timer = window.setTimeout(tick, CHANGES_POLL_MS + Math.random() * CHANGES_JITTER_MS);+ };+ void tick();+ return () => {+ alive = false;+ window.clearTimeout(timer);+ };+ }, [workspaceId, nonce]);+ return { changes, error, refresh: () => setNonce((value) => value + 1) };+}++function ChangeCounts({ file }: { file: Pick<ChangedFile, "added" | "removed"> }) {+ if (file.added == null && file.removed == null) return null;+ return (+ <span className="shrink-0 font-mono text-[11px] tabular-nums">+ {file.added ? <span className="text-success">+{file.added}</span> : null}+ {file.added && file.removed ? " " : null}+ {file.removed ? <span className="text-destructive">−{file.removed}</span> : null}+ </span>+ );+}++function StatusLetter({ status }: { status: ChangeStatus }) {+ return (+ <span+ data-status={status}+ className={cn("w-3 shrink-0 text-center font-mono text-[11px] font-semibold", STATUS_TONE[status])}+ >+ {STATUS_LETTER[status]}+ </span>+ );+}++/**+ * The Explorer tab: the workspace's folder as a tree, what the agents changed,+ * and any file's diff — drag a row onto a terminal to reference that file.+ */+export function ExplorerPanel() {+ const t = useT();+ const workspace = useIdeChatStore((state) => state.workspace);+ const stagedPane = useIdeChatStore((state) => state.stagedPane);+ const view = useIdeExplorerStore((state) => state.view);+ const setView = useIdeExplorerStore((state) => state.setView);+ const opened = useIdeExplorerStore((state) => state.opened);+ const open = useIdeExplorerStore((state) => state.open);+ const close = useIdeExplorerStore((state) => state.close);+ const pushToast = useEventStore((state) => state.pushToast);+ const [filter, setFilter] = useState("");+ const workspaceId = workspace?.id ?? null;+ const { changes, error: changesError, refresh } = useWorkspaceChanges(workspaceId);++ const changeMap = useMemo(() => {+ const map = new Map<string, ChangedFile>();+ for (const file of changes?.files ?? []) map.set(file.path, file);+ return map;+ }, [changes]);+ // Every folder that holds a change, so a collapsed tree still shows where to look.+ const changedFolders = useMemo(() => {+ const folders = new Set<string>();+ for (const file of changes?.files ?? []) {+ const parts = file.path.split("/");+ for (let index = 1; index < parts.length; index += 1) folders.add(parts.slice(0, index).join("/"));+ if (file.is_directory) folders.add(file.path);+ }+ return folders;+ }, [changes]);++ if (!workspace || !workspaceId) {+ return <p className="px-4 py-3 text-sm text-muted-foreground">{t("ide_side_panel.explorer.no_workspace")}</p>;+ }++ const absolute = (relative: string) => absoluteWorkspacePath(workspace.path, relative);+ const referenceInPane = async (relative: string) => {+ if (!stagedPane) return;+ try {+ await attachToTerminal(stagedPane, { paths: [absolute(relative)] });+ } catch (error) {+ pushToast("error", (error as Error).message);+ }+ };++ if (opened && opened.workspaceId === workspaceId) {+ return (+ <FileViewer+ workspaceId={workspaceId}+ path={opened.path}+ change={changeMap}+ onBack={close}+ onReference={stagedPane ? referenceInPane : undefined}+ referenceLabel={stagedPane ? fill(t("ide_side_panel.explorer.reference_in"), { pane: stagedPane }) : ""}+ onOpenExternally={(path) =>+ void openTerminalTarget(workspaceId, path).catch((error: unknown) =>+ pushToast("error", (error as Error).message),+ )+ }+ absolute={absolute}+ />+ );+ }++ const needle = filter.trim().toLowerCase();+ const changedFiles = (changes?.files ?? []).filter((file) => !needle || file.path.toLowerCase().includes(needle));+ const openFile = (path: string) => open({ workspaceId, path });++ return (+ <section data-testid="ide-explorer" aria-label={t("ide_side_panel.explorer.aria")} className="flex h-full min-h-0 flex-col">+ <div className="shrink-0 space-y-2 border-b border-border/60 px-3 pb-2.5 pt-3">+ <div className="flex items-center gap-2">+ <FolderOpen className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />+ <span className="min-w-0 truncate text-sm font-semibold text-foreground" title={workspace.path}>+ {baseName(workspace.path.replace(/\\/g, "/")) || workspace.name}+ </span>+ {changes?.branch && (+ <span+ data-testid="explorer-branch"+ className="flex min-w-0 shrink items-center gap-1 rounded-md bg-muted px-1.5 py-0.5 text-[11px] text-muted-foreground"+ >+ <GitBranch className="h-3 w-3 shrink-0" aria-hidden />+ <span className="truncate">{changes.branch}</span>+ </span>+ )}+ <button+ type="button"+ onClick={refresh}+ aria-label={t("ide_side_panel.explorer.refresh")}+ title={t("ide_side_panel.explorer.refresh")}+ className="ml-auto inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <RefreshCw className="h-3.5 w-3.5" aria-hidden />+ </button>+ </div>+ <div role="tablist" aria-label={t("ide_side_panel.explorer.views")} className="grid grid-cols-2 gap-1 rounded-lg bg-muted/60 p-0.5">+ {(["changes", "files"] as const).map((id) => (+ <button+ key={id}+ type="button"+ role="tab"+ aria-selected={view === id}+ data-testid={`explorer-view-${id}`}+ onClick={() => setView(id)}+ className={cn(+ "flex h-7 items-center justify-center gap-1.5 rounded-md text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ view === id ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground",+ )}+ >+ {t(`ide_side_panel.explorer.view_${id}`)}+ {id === "changes" && (changes?.files.length ?? 0) > 0 && (+ <span className="rounded bg-success/15 px-1 text-[10px] tabular-nums text-success">{changes?.files.length}</span>+ )}+ </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+ value={filter}+ onChange={(event) => setFilter(event.target.value)}+ placeholder={t("ide_side_panel.explorer.filter")}+ aria-label={t("ide_side_panel.explorer.filter")}+ className="min-w-0 flex-1 bg-transparent text-xs text-foreground outline-none placeholder:text-muted-foreground"+ />+ {filter && (+ <button type="button" aria-label={t("ide_side_panel.explorer.clear_filter")} onClick={() => setFilter("")} className="text-muted-foreground hover:text-foreground">+ <X className="h-3.5 w-3.5" aria-hidden />+ </button>+ )}+ </label>+ </div>++ <div className="scrollbar-jarvis min-h-0 flex-1 overflow-y-auto py-1.5">+ {view === "changes" ? (+ !changes && changesError ? (+ <p className="px-4 py-3 text-xs text-muted-foreground">+ {fill(t("ide_side_panel.explorer.changes_error"), { error: changesError })}+ </p>+ ) : !changes ? (+ <p className="flex items-center gap-2 px-4 py-3 text-xs text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ {t("ide_side_panel.explorer.loading")}+ </p>+ ) : !changes.available ? (+ <p className="px-4 py-3 text-xs text-muted-foreground">{changes.reason || t("ide_side_panel.explorer.no_git")}</p>+ ) : changedFiles.length === 0 ? (+ <p className="px-4 py-3 text-xs text-muted-foreground">+ {needle ? t("ide_side_panel.explorer.no_match") : t("ide_side_panel.explorer.clean")}+ </p>+ ) : (+ <ul data-testid="explorer-changes">+ {changedFiles.map((file) => {+ const Icon = file.is_directory ? Folder : fileIcon(file.path);+ return (+ <li key={file.path}>+ <button+ type="button"+ draggable+ onDragStart={(event) => startFileDrag(event, absolute(file.path))}+ onClick={() => !file.is_directory && openFile(file.path)}+ data-testid="explorer-change-row"+ data-path={file.path}+ title={`${file.path} — ${t("ide_side_panel.explorer.drag_hint")}`}+ className="group flex h-9 w-full items-center gap-2 px-3 text-left hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none"+ >+ <Icon className={cn("h-4 w-4 shrink-0", STATUS_TONE[file.status])} aria-hidden />+ <span className="flex min-w-0 flex-1 flex-col leading-tight">+ <span className={cn("truncate text-[13px] text-foreground", file.status === "deleted" && "line-through decoration-destructive/60")}>+ {baseName(file.path)}+ </span>+ {parentPath(file.path) && (+ <span className="truncate text-[10.5px] text-muted-foreground">{parentPath(file.path)}</span>+ )}+ </span>+ <ChangeCounts file={file} />+ <StatusLetter status={file.status} />+ </button>+ </li>+ );+ })}+ {changes.truncated && <li className="px-3 py-2 text-[11px] text-muted-foreground">{t("ide_side_panel.explorer.truncated")}</li>}+ </ul>+ )+ ) : (+ <FileTree+ workspaceId={workspaceId}+ filter={needle}+ changeMap={changeMap}+ changedFolders={changedFolders}+ onOpen={openFile}+ absolute={absolute}+ />+ )}+ </div>+ </section>+ );+}++interface TreeProps {+ workspaceId: string;+ filter: string;+ changeMap: Map<string, ChangedFile>;+ changedFolders: Set<string>;+ onOpen: (path: string) => void;+ absolute: (relative: string) => string;+}++/** The folder, one lazily loaded level at a time. */+function FileTree({ workspaceId, filter, changeMap, changedFolders, onOpen, absolute }: TreeProps) {+ const t = useT();+ const [children, setChildren] = useState<Record<string, WorkspaceFileItem[]>>({});+ const [expanded, setExpanded] = useState<Set<string>>(() => new Set([""]));+ const [loading, setLoading] = useState<Set<string>>(() => new Set());+ const [error, setError] = useState("");+ const loaded = useRef<Set<string>>(new Set());++ const load = useCallback(+ async (path: string) => {+ setLoading((current) => new Set(current).add(path));+ try {+ const answer = await fetchWorkspaceFiles(workspaceId, path);+ loaded.current.add(path);+ setChildren((current) => ({ ...current, [path]: answer.entries }));+ if (answer.error) setError(answer.error);+ } catch (err) {+ setError((err as Error).message);+ } finally {+ setLoading((current) => {+ const next = new Set(current);+ next.delete(path);+ return next;+ });+ }+ },+ [workspaceId],+ );++ useEffect(() => {+ loaded.current = new Set();+ setChildren({});+ setExpanded(new Set([""]));+ void load("");+ }, [load]);++ const toggle = (path: string) => {+ setExpanded((current) => {+ const next = new Set(current);+ if (next.has(path)) next.delete(path);+ else {+ next.add(path);+ if (!loaded.current.has(path)) void load(path);+ }+ return next;+ });+ };++ const rows: { item: WorkspaceFileItem; depth: number }[] = [];+ const walk = (path: string, depth: number) => {+ for (const item of sortEntries(children[path] ?? [])) {+ const matches = !filter || item.name.toLowerCase().includes(filter);+ if (matches || item.is_directory) {+ if (matches) rows.push({ item, depth });+ if (item.is_directory && expanded.has(item.path)) walk(item.path, matches ? depth + 1 : depth);+ }+ }+ };+ walk("", 0);++ if (!children[""] && loading.has("")) {+ return (+ <p className="flex items-center gap-2 px-4 py-3 text-xs text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ {t("ide_side_panel.explorer.loading")}+ </p>+ );+ }++ return (+ <ul data-testid="explorer-tree" role="tree" aria-label={t("ide_side_panel.explorer.view_files")}>+ {error && <li className="px-3 py-2 text-[11px] text-destructive">{error}</li>}+ {rows.map(({ item, depth }) => {+ const change = changeMap.get(item.path);+ const open = expanded.has(item.path);+ const Icon = item.is_directory ? (open ? FolderOpen : Folder) : fileIcon(item.name);+ const hasChangeInside = item.is_directory && changedFolders.has(item.path);+ return (+ <li key={item.path} role="treeitem" aria-expanded={item.is_directory ? open : undefined}>+ <button+ type="button"+ draggable+ onDragStart={(event) => startFileDrag(event, absolute(item.path))}+ onClick={() => (item.is_directory ? toggle(item.path) : onOpen(item.path))}+ data-testid="explorer-tree-row"+ data-path={item.path}+ title={item.path}+ style={{ paddingLeft: 10 + depth * 14 }}+ className="flex h-7 w-full items-center gap-1.5 pr-3 text-left text-[13px] hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none"+ >+ <ChevronRight+ aria-hidden+ className={cn(+ "h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform duration-150 motion-reduce:transition-none",+ !item.is_directory && "invisible",+ open && "rotate-90",+ )}+ />+ <Icon+ aria-hidden+ className={cn(+ "h-4 w-4 shrink-0",+ change ? STATUS_TONE[change.status] : item.is_directory ? "text-muted-foreground" : "text-muted-foreground/80",+ )}+ />+ <span className={cn("min-w-0 flex-1 truncate", change ? STATUS_TONE[change.status] : "text-foreground/90")}>+ {item.name}+ </span>+ {loading.has(item.path) && <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted-foreground" aria-hidden />}+ {hasChangeInside && !change && <span className="h-1.5 w-1.5 shrink-0 rounded-full bg-success/80" aria-hidden />}+ {change && <StatusLetter status={change.status} />}+ </button>+ </li>+ );+ })}+ </ul>+ );+}++/** Tool-owned folders nobody browses; the agents' own config folders stay visible. */+const HIDDEN_ENTRIES = new Set([".git", "__pycache__", ".DS_Store", "Thumbs.db", ".pytest_cache", ".mypy_cache", ".ruff_cache"]);++function sortEntries(entries: WorkspaceFileItem[]): WorkspaceFileItem[] {+ return entries+ .filter((entry) => !HIDDEN_ENTRIES.has(entry.name))+ .sort((a, b) =>+ a.is_directory === b.is_directory+ ? a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" })+ : a.is_directory+ ? -1+ : 1,+ );+}++const IMAGE_EXTENSIONS = /\.(png|jpe?g|gif|webp|svg|bmp|ico|avif)$/i;++interface ViewerProps {+ workspaceId: string;+ path: string;+ change: Map<string, ChangedFile>;+ onBack: () => void;+ onReference?: (relative: string) => void;+ referenceLabel: string;+ onOpenExternally: (path: string) => void;+ absolute: (relative: string) => string;+}++/** One file: its diff when it changed, else its contents. */+function FileViewer({ workspaceId, path, change, onBack, onReference, referenceLabel, onOpenExternally, absolute }: ViewerProps) {+ const t = useT();+ const [diff, setDiff] = useState<FileDiff | null>(null);+ const [preview, setPreview] = useState<WorkspaceFilePreviewResponse | null>(null);+ const [error, setError] = useState("");++ useEffect(() => {+ let alive = true;+ setDiff(null);+ setPreview(null);+ setError("");+ void (async () => {+ try {+ const answer = await fetchFileDiff(workspaceId, path);+ if (!alive) return;+ setDiff(answer);+ if (answer.hunks.length === 0 && !answer.binary && answer.status !== "deleted") {+ const body = await fetchWorkspaceFilePreview(workspaceId, answer.path);+ if (alive) setPreview(body);+ }+ } catch (err) {+ if (alive) setError((err as Error).message);+ }+ })();+ return () => {+ alive = false;+ };+ }, [workspaceId, path]);++ const relative = diff?.path ?? path;+ const Icon = fileIcon(baseName(relative));+ const known = change.get(relative);+ const status = diff && diff.status !== "unchanged" ? diff.status : known?.status;++ return (+ <section data-testid="explorer-viewer" data-path={relative} className="flex h-full min-h-0 flex-col">+ <div className="shrink-0 border-b border-border/60 px-2 py-2">+ <div className="flex items-center gap-1.5">+ <button+ type="button"+ onClick={onBack}+ aria-label={t("ide_side_panel.explorer.back")}+ title={t("ide_side_panel.explorer.back")}+ className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <ArrowLeft className="h-4 w-4" aria-hidden />+ </button>+ <span+ draggable+ onDragStart={(event) => startFileDrag(event, absolute(relative))}+ title={t("ide_side_panel.explorer.drag_hint")}+ className="flex min-w-0 flex-1 cursor-grab items-center gap-2"+ >+ <Icon className={cn("h-4 w-4 shrink-0", status ? STATUS_TONE[status as ChangeStatus] : "text-muted-foreground")} aria-hidden />+ <span className="flex min-w-0 flex-col leading-tight">+ <span className="truncate text-[13px] font-semibold text-foreground">{baseName(relative)}</span>+ {parentPath(relative) && <span className="truncate text-[10.5px] text-muted-foreground">{parentPath(relative)}</span>}+ </span>+ </span>+ {diff && (diff.added > 0 || diff.removed > 0) && <ChangeCounts file={diff} />}+ </div>+ <div className="mt-2 flex flex-wrap gap-1.5 pl-8">+ {onReference && (+ <button+ type="button"+ data-testid="explorer-reference"+ onClick={() => onReference(relative)}+ className="inline-flex h-7 items-center gap-1.5 rounded-md border border-border/70 px-2 text-xs text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <SquareArrowOutUpRight className="h-3.5 w-3.5" aria-hidden />+ {referenceLabel}+ </button>+ )}+ <button+ type="button"+ onClick={() => onOpenExternally(relative)}+ className="inline-flex h-7 items-center gap-1.5 rounded-md border border-border/70 px-2 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <ExternalLink className="h-3.5 w-3.5" aria-hidden />+ {t("ide_side_panel.explorer.open_externally")}+ </button>+ </div>+ </div>+ <div className="scrollbar-jarvis min-h-0 flex-1 overflow-auto">+ {error ? (+ <p className="px-4 py-3 text-xs text-destructive">{error}</p>+ ) : !diff ? (+ <p className="flex items-center gap-2 px-4 py-3 text-xs text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ {t("ide_side_panel.explorer.loading")}+ </p>+ ) : diff.binary ? (+ IMAGE_EXTENSIONS.test(relative) && diff.status !== "deleted" ? (+ <img src={workspaceFileUrl(workspaceId, relative)} alt={baseName(relative)} className="m-3 max-w-[calc(100%-24px)] rounded-md border border-border/60" />+ ) : (+ <p className="px-4 py-3 text-xs text-muted-foreground">{t("ide_side_panel.explorer.binary")}</p>+ )+ ) : diff.hunks.length > 0 ? (+ <>+ <DiffView hunks={diff.hunks} />+ {diff.truncated && <p className="px-4 py-2 text-[11px] text-muted-foreground">{t("ide_side_panel.explorer.truncated")}</p>}+ </>+ ) : IMAGE_EXTENSIONS.test(relative) ? (+ <img src={workspaceFileUrl(workspaceId, relative)} alt={baseName(relative)} className="m-3 max-w-[calc(100%-24px)] rounded-md border border-border/60" />+ ) : preview?.text != null ? (+ <div className="min-w-max py-1 font-mono text-[12px] leading-[1.55]">+ <p className="px-3 pb-1 font-sans text-[11px] text-muted-foreground">{t("ide_side_panel.explorer.unchanged")}</p>+ {preview.text.split("\n").map((line, index) => (+ <div key={index} className="flex">+ <span className="w-10 shrink-0 select-none pr-3 text-right tabular-nums text-muted-foreground/70">{index + 1}</span>+ <span className="whitespace-pre pr-4 text-foreground/85">{line || " "}</span>+ </div>+ ))}+ </div>+ ) : preview ? (+ <p className="px-4 py-3 text-xs text-muted-foreground">{t("ide_side_panel.explorer.binary")}</p>+ ) : (+ <p className="flex items-center gap-2 px-4 py-3 text-xs text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />+ {t("ide_side_panel.explorer.loading")}+ </p>+ )}+ </div>+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/explorerApi.ts b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/explorerApi.tsnew file mode 100644index 0000000000..5f0a5926d8--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/explorerApi.ts@@ -0,0 +1,76 @@+/** The explorer's git reads: what changed in a workspace, and one file's diff. */++export type ChangeStatus = "modified" | "added" | "deleted" | "untracked" | "conflicted";++export interface ChangedFile {+ /** POSIX path relative to the workspace root. */+ path: string;+ status: ChangeStatus;+ added: number | null;+ removed: number | null;+ is_directory: boolean;+}++export interface WorkspaceChanges {+ workspace_id: string;+ available: boolean;+ branch: string;+ files: ChangedFile[];+ truncated: boolean;+ reason: string;+}++export interface DiffLine {+ kind: "add" | "del" | "ctx";+ text: string;+ old_no: number | null;+ new_no: number | null;+}++export interface DiffHunk {+ header: string;+ lines: DiffLine[];+}++export interface FileDiff {+ workspace_id: string;+ path: string;+ status: ChangeStatus | "unchanged";+ binary: boolean;+ added: number;+ removed: number;+ hunks: DiffHunk[];+ truncated: boolean;+}++async function read<T>(url: string): Promise<T> {+ const res = await fetch(url);+ if (!res.ok) {+ let message = `Request failed (${res.status}).`;+ try {+ const body = (await res.json()) as { detail?: unknown };+ if (typeof body.detail === "string") message = body.detail;+ } catch {+ /* keep the status-code message */+ }+ throw new Error(message);+ }+ return (await res.json()) as T;+}++const base = (workspaceId: string) => `/api/agentic-ide/workspaces/${encodeURIComponent(workspaceId)}`;++export function fetchWorkspaceChanges(workspaceId: string): Promise<WorkspaceChanges> {+ return read<WorkspaceChanges>(`${base(workspaceId)}/changes`);+}++export function fetchFileDiff(workspaceId: string, path: string): Promise<FileDiff> {+ return read<FileDiff>(`${base(workspaceId)}/diff?${new URLSearchParams({ path }).toString()}`);+}++/** The absolute path a terminal drop needs, from the workspace root and a relative path. */+export function absoluteWorkspacePath(root: string, relative: string): string {+ const separator = root.includes("\\") && !root.includes("/") ? "\\" : "/";+ const trimmed = root.replace(/[\\/]+$/, "");+ return `${trimmed}${separator}${relative.split("/").join(separator)}`;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/fileIcon.ts b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/fileIcon.tsnew file mode 100644index 0000000000..e7f780072f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/explorer/fileIcon.ts@@ -0,0 +1,42 @@+import {+ File,+ FileArchive,+ FileCode,+ FileCog,+ FileImage,+ FileJson,+ FileLock,+ FileSpreadsheet,+ FileTerminal,+ FileText,+ FileType,+ type LucideIcon,+} from "lucide-react";++const BY_EXTENSION: Record<string, LucideIcon> = {};+const register = (icon: LucideIcon, extensions: string[]) => {+ for (const extension of extensions) BY_EXTENSION[extension] = icon;+};+register(FileCode, [+ "ts", "tsx", "js", "jsx", "mjs", "cjs", "py", "pyi", "rs", "go", "java", "kt", "swift", "c", "cc",+ "cpp", "h", "hpp", "cs", "rb", "php", "vue", "svelte", "html", "htm", "css", "scss", "sass", "less",+ "sql", "astro",+]);+register(FileJson, ["json", "jsonl", "jsonc"]);+register(FileCog, ["toml", "yaml", "yml", "ini", "cfg", "conf", "env", "editorconfig"]);+register(FileText, ["md", "mdx", "txt", "rst", "log"]);+register(FileImage, ["png", "jpg", "jpeg", "gif", "svg", "webp", "ico", "bmp", "avif"]);+register(FileTerminal, ["sh", "bash", "zsh", "fish", "ps1", "bat", "cmd"]);+register(FileArchive, ["zip", "tar", "gz", "tgz", "7z", "rar", "whl"]);+register(FileSpreadsheet, ["csv", "tsv", "xlsx", "xls"]);+register(FileLock, ["lock"]);+register(FileType, ["ttf", "otf", "woff", "woff2"]);++/** A generic, brand-free glyph for a file, chosen by its extension. */+export function fileIcon(name: string): LucideIcon {+ const lower = name.toLowerCase();+ if (lower.startsWith(".env")) return FileCog;+ const dot = lower.lastIndexOf(".");+ if (dot <= 0) return File;+ return BY_EXTENSION[lower.slice(dot + 1)] ?? File;+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsxindex c58881f615..3dac728aef 100644--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsx@@ -1,7 +1,8 @@import type { ReactNode } from "react";-import { Bot, type LucideIcon } from "lucide-react";+import { Bot, FolderTree, type LucideIcon } from "lucide-react";import type { SidePanelTabId } from "@/store/ideSidePanel";import { AgentsOverview } from "./AgentsOverview";+import { ExplorerPanel } from "./explorer/ExplorerPanel";/** One function the side panel can show. */export interface SidePanelTabDef {@@ -26,6 +27,12 @@ export const SIDE_PANEL_TABS: readonly SidePanelTabDef[] = [icon: Bot,render: () => <AgentsOverview />,},+ {+ id: "files",+ labelKey: "ide_side_panel.tabs.files",+ icon: FolderTree,+ render: () => <ExplorerPanel />,+ },];export function sidePanelTab(id: SidePanelTabId): SidePanelTabDef | undefined {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex c865518ac8..986398ff9f 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -5772,8 +5772,33 @@"add_tab": "Tab hinzufügen","all_open": "Alle Tabs sind bereits offen","close_tab": "Tab schließen",+ "rail_aria": "Tabs der Seitenleiste",+ "rail_waiting": "{n} warten auf dich",+ "explorer": {+ "aria": "Dateien und Änderungen im Workspace",+ "no_workspace": "Wähle einen Workspace, um seine Dateien zu sehen.",+ "refresh": "Aktualisieren",+ "views": "Explorer-Ansichten",+ "view_changes": "Änderungen",+ "view_files": "Dateien",+ "filter": "Dateien filtern",+ "clear_filter": "Filter leeren",+ "loading": "Lädt…",+ "no_git": "Dieser Ordner ist kein Git-Repository, daher gibt es keine Änderungsansicht.",+ "no_match": "Keine Datei passt zum Filter.",+ "clean": "Keine Änderungen seit dem letzten Commit.",+ "changes_error": "Änderungen konnten nicht geladen werden ({error}). Nach einem Update ist eventuell ein Neustart der App nötig.",+ "drag_hint": "Auf ein Terminal ziehen, um die Datei dort zu referenzieren",+ "truncated": "Die Liste wurde gekürzt; öffne den Ordner für den Rest.",+ "reference_in": "In {pane} referenzieren",+ "open_externally": "Auf diesem Computer öffnen",+ "back": "Zurück",+ "binary": "Diese Datei lässt sich nicht als Text anzeigen.",+ "unchanged": "Seit dem letzten Commit unverändert."+ },"tabs": {- "agents": "Agents"+ "agents": "Agents",+ "files": "Explorer"},"agents": {"aria": "Agents in diesem Workspace",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 7eca7ddb75..ffc6e3fea4 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -5805,8 +5805,33 @@"add_tab": "Add a tab","all_open": "Every tab is already open","close_tab": "Close tab",+ "rail_aria": "Side panel tabs",+ "rail_waiting": "{n} waiting for you",+ "explorer": {+ "aria": "Workspace files and changes",+ "no_workspace": "Select a workspace to see its files.",+ "refresh": "Refresh",+ "views": "Explorer views",+ "view_changes": "Changes",+ "view_files": "Files",+ "filter": "Filter files",+ "clear_filter": "Clear filter",+ "loading": "Loading…",+ "no_git": "This folder is not a git repository, so changes cannot be shown.",+ "no_match": "No file matches the filter.",+ "clean": "No changes since the last commit.",+ "changes_error": "Changes could not be loaded ({error}). Restarting the app may be needed after an update.",+ "drag_hint": "Drag onto a terminal to reference it",+ "truncated": "The list was shortened; open the folder for the rest.",+ "reference_in": "Reference in {pane}",+ "open_externally": "Open on this computer",+ "back": "Back",+ "binary": "This file cannot be shown as text.",+ "unchanged": "Unchanged since the last commit."+ },"tabs": {- "agents": "Agents"+ "agents": "Agents",+ "files": "Explorer"},"agents": {"aria": "Agents in this workspace",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex ba2630bb67..d5f392cc75 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -5772,8 +5772,33 @@"add_tab": "Añadir una pestaña","all_open": "Todas las pestañas ya están abiertas","close_tab": "Cerrar pestaña",+ "rail_aria": "Pestañas del panel lateral",+ "rail_waiting": "{n} esperan tu respuesta",+ "explorer": {+ "aria": "Archivos y cambios del espacio de trabajo",+ "no_workspace": "Selecciona un espacio de trabajo para ver sus archivos.",+ "refresh": "Actualizar",+ "views": "Vistas del explorador",+ "view_changes": "Cambios",+ "view_files": "Archivos",+ "filter": "Filtrar archivos",+ "clear_filter": "Borrar filtro",+ "loading": "Cargando…",+ "no_git": "Esta carpeta no es un repositorio git, así que no hay vista de cambios.",+ "no_match": "Ningún archivo coincide con el filtro.",+ "clean": "Sin cambios desde el último commit.",+ "changes_error": "No se pudieron cargar los cambios ({error}). Tras una actualización puede hacer falta reiniciar la app.",+ "drag_hint": "Arrástralo a una terminal para referenciarlo",+ "truncated": "La lista se acortó; abre la carpeta para ver el resto.",+ "reference_in": "Referenciar en {pane}",+ "open_externally": "Abrir en este equipo",+ "back": "Volver",+ "binary": "Este archivo no se puede mostrar como texto.",+ "unchanged": "Sin cambios desde el último commit."+ },"tabs": {- "agents": "Agentes"+ "agents": "Agentes",+ "files": "Explorador"},"agents": {"aria": "Agentes de este espacio de trabajo",diff --git a/jarvis/ui/web/frontend/src/lib/terminalLinks.ts b/jarvis/ui/web/frontend/src/lib/terminalLinks.tsindex d818cfeddc..16fb781239 100644--- a/jarvis/ui/web/frontend/src/lib/terminalLinks.ts+++ b/jarvis/ui/web/frontend/src/lib/terminalLinks.ts@@ -11,6 +11,13 @@ import type {import { openTerminalTarget } from "@/lib/agenticIdeApi";import { openExternalUrl } from "@/lib/openExternal";+/**+ * Raised for a Ctrl/Cmd-clicked local path before the OS opener runs. A+ * listener that shows the file in the app (the IDE's Explorer) calls+ * `preventDefault()`, and the OS opener is skipped.+ */+export const OPEN_PATH_EVENT = "jarvis:ide-open-path";+const MAX_LOGICAL_LINE_CHARS = 4096;const BARE_FILE = /^(?:(?:readme|license|makefile|dockerfile|containerfile)|[^/\\]+\.(?:c|cc|cpp|h|hpp|cs|go|rs|java|kt|kts|swift|php|rb|py|pyi|js|mjs|cjs|jsx|ts|mts|cts|tsx|vue|svelte|html?|css|scss|sass|less|json|jsonl|ya?ml|toml|xml|md|mdx|txt|log|csv|tsv|sql|sh|bash|zsh|fish|ps1|bat|cmd|ini|cfg|conf|env|lock|diff|patch|pdf|png|jpe?g|gif|svg|webp))(?::[1-9]\d*(?::[1-9]\d*)?|#L[1-9]\d*(?::[1-9]\d*)?|\([1-9]\d*(?:,[1-9]\d*)?\))?$/i;@@ -80,6 +87,13 @@ export function activateTerminalLink(return;}if (!options.workspaceId || !isTerminalPath(uri)) return;+ // The IDE's Explorer shows the file — with its diff — when it is mounted; it+ // answers by cancelling the event. Otherwise the OS opens it as before.+ const routed = new CustomEvent(OPEN_PATH_EVENT, {+ cancelable: true,+ detail: { workspaceId: options.workspaceId, path: uri },+ });+ if (!window.dispatchEvent(routed)) return;void openTerminalTarget(options.workspaceId, uri).catch((error: unknown) => {const message = errorMessage(error);if (options.onError) options.onError(message);diff --git a/jarvis/ui/web/frontend/src/store/ideExplorer.ts b/jarvis/ui/web/frontend/src/store/ideExplorer.tsnew file mode 100644index 0000000000..f3d3587cc2--- /dev/null+++ b/jarvis/ui/web/frontend/src/store/ideExplorer.ts@@ -0,0 +1,69 @@+import { useEffect } from "react";+import { create } from "zustand";++import { OPEN_PATH_EVENT } from "@/lib/terminalLinks";+import { useIdeChatStore } from "@/store/ideChat";+import { useIdeSidePanelStore } from "@/store/ideSidePanel";++/**+ * The Explorer tab's state: which list it shows and which file is open.+ *+ * Kept outside the component because a file can be opened from elsewhere: a+ * Ctrl+click on a path a coding agent printed in its terminal lands here (see+ * `OPEN_PATH_EVENT`), opens the side panel on the Explorer, and shows that+ * file's diff.+ */+export type ExplorerView = "files" | "changes";++export interface OpenedFile {+ workspaceId: string;+ /** Workspace-relative, or an absolute path inside the workspace as printed. */+ path: string;+}++interface IdeExplorerState {+ view: ExplorerView;+ opened: OpenedFile | null;+ setView: (view: ExplorerView) => void;+ open: (file: OpenedFile) => void;+ close: () => void;+}++export const useIdeExplorerStore = create<IdeExplorerState>((set) => ({+ view: "changes",+ opened: null,+ setView: (view) => set({ view }),+ open: (file) => set({ opened: file }),+ close: () => set({ opened: null }),+}));++export interface OpenPathDetail {+ workspaceId: string;+ path: string;+}++/** Open a file in the side panel's Explorer, bringing the panel up if needed. */+export function openInExplorer(file: OpenedFile): void {+ useIdeExplorerStore.getState().open(file);+ useIdeSidePanelStore.getState().openTab("files");+}++/**+ * Route terminal path clicks into the Explorer while the Agentic IDE is mounted.+ *+ * Only for the workspace on screen: a path from another workspace's pane has+ * no tree here to show it in, so it keeps the old behaviour.+ */+export function useExplorerPathRouting(): void {+ useEffect(() => {+ const onOpen = (event: Event) => {+ const detail = (event as CustomEvent<OpenPathDetail>).detail;+ if (!detail?.workspaceId || !detail.path) return;+ if (useIdeChatStore.getState().workspace?.id !== detail.workspaceId) return;+ event.preventDefault();+ openInExplorer({ workspaceId: detail.workspaceId, path: detail.path });+ };+ window.addEventListener(OPEN_PATH_EVENT, onOpen);+ return () => window.removeEventListener(OPEN_PATH_EVENT, onOpen);+ }, []);+}diff --git a/jarvis/ui/web/frontend/src/store/ideSidePanel.ts b/jarvis/ui/web/frontend/src/store/ideSidePanel.tsindex a1592f1968..cf9d2cb035 100644--- a/jarvis/ui/web/frontend/src/store/ideSidePanel.ts+++ b/jarvis/ui/web/frontend/src/store/ideSidePanel.ts@@ -11,14 +11,15 @@ import { create } from "zustand";*//** Every function the panel can show. A new one is a new id plus a registry entry. */-export type SidePanelTabId = "agents";+export type SidePanelTabId = "agents" | "files";-export const SIDE_PANEL_TAB_IDS: readonly SidePanelTabId[] = ["agents"];+export const SIDE_PANEL_TAB_IDS: readonly SidePanelTabId[] = ["agents", "files"];const OPEN_KEY = "jarvis.agenticIde.sidePanelOpen";-const TABS_KEY = "jarvis.agenticIde.sidePanelTabs.v1";+// v2: the Explorer joined the default tabs; a v1 list would have hidden it.+const TABS_KEY = "jarvis.agenticIde.sidePanelTabs.v2";-const DEFAULT_TABS: SidePanelTabId[] = ["agents"];+const DEFAULT_TABS: SidePanelTabId[] = ["agents", "files"];const isTabId = (value: unknown): value is SidePanelTabId =>typeof value === "string" && (SIDE_PANEL_TAB_IDS as readonly string[]).includes(value);diff --git a/tests/unit/agentic_ide/test_git_changes.py b/tests/unit/agentic_ide/test_git_changes.pynew file mode 100644index 0000000000..af11a4627a--- /dev/null+++ b/tests/unit/agentic_ide/test_git_changes.py@@ -0,0 +1,107 @@+"""The explorer's git view: which files changed, and how, inside one workspace."""++from __future__ import annotations++import shutil+import subprocess+from pathlib import Path++import pytest++from jarvis.agentic_ide import git_changes++pytestmark = pytest.mark.skipif(shutil.which("git") is None, reason="git is not installed")+++def _git(cwd: Path, *args: str) -> None:+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True)+++def repo(tmp_path: Path) -> Path:+ _git(tmp_path, "init", "-q")+ _git(tmp_path, "config", "user.email", "[email protected]")+ _git(tmp_path, "config", "user.name", "Test")+ _git(tmp_path, "config", "core.autocrlf", "false")+ (tmp_path / "app").mkdir()+ (tmp_path / "app" / "main.py").write_text("one\ntwo\nthree\n", encoding="utf-8")+ (tmp_path / "app" / "gone.py").write_text("bye\n", encoding="utf-8")+ (tmp_path / "top.txt").write_text("root\n", encoding="utf-8")+ _git(tmp_path, "add", "-A")+ _git(tmp_path, "commit", "-q", "-m", "init")+ return tmp_path+++def test_reports_modified_deleted_and_untracked_with_line_counts(repo: Path) -> None:+ (repo / "app" / "main.py").write_text("one\nTWO\nthree\nfour\n", encoding="utf-8")+ (repo / "app" / "gone.py").unlink()+ (repo / "app" / "new.py").write_text("a\nb\n", encoding="utf-8")++ changes = git_changes.workspace_changes(repo)++ assert changes.available+ by_path = {item.path: item for item in changes.files}+ assert by_path["app/main.py"].status == "modified"+ assert (by_path["app/main.py"].added, by_path["app/main.py"].removed) == (2, 1)+ assert by_path["app/gone.py"].status == "deleted"+ assert by_path["app/new.py"].status == "untracked"+ assert by_path["app/new.py"].added == 2+++def test_a_sub_folder_workspace_sees_only_its_own_changes_relative_to_itself(repo: Path) -> None:+ (repo / "app" / "main.py").write_text("changed\n", encoding="utf-8")+ (repo / "top.txt").write_text("changed\n", encoding="utf-8")++ changes = git_changes.workspace_changes(repo / "app")++ assert [item.path for item in changes.files] == ["main.py"]+++def test_the_diff_marks_removed_and_added_lines_with_line_numbers(repo: Path) -> None:+ (repo / "app" / "main.py").write_text("one\nTWO\nthree\n", encoding="utf-8")++ diff = git_changes.file_diff(repo, "app/main.py")++ assert diff.status == "modified"+ assert (diff.added, diff.removed) == (1, 1)+ lines = [(line.kind, line.old_no, line.new_no, line.text) for line in diff.hunks[0].lines]+ assert ("del", 2, None, "two") in lines+ assert ("add", None, 2, "TWO") in lines+ assert ("ctx", 1, 1, "one") in lines+++def test_an_untracked_file_is_all_new_and_an_absolute_path_is_accepted(repo: Path) -> None:+ (repo / "fresh.md").write_text("# Title\nbody\n", encoding="utf-8")++ diff = git_changes.file_diff(repo, str(repo / "fresh.md"))++ assert diff.status == "untracked"+ assert diff.added == 2+ assert [line.kind for line in diff.hunks[0].lines] == ["add", "add"]+++def test_a_deleted_file_still_has_a_diff(repo: Path) -> None:+ (repo / "app" / "gone.py").unlink()++ diff = git_changes.file_diff(repo, "app/gone.py")++ assert diff.status == "deleted"+ assert diff.removed == 1+++def test_paths_outside_the_workspace_are_refused(repo: Path) -> None:+ with pytest.raises(ValueError):+ git_changes.file_diff(repo / "app", "../top.txt")+ with pytest.raises(ValueError):+ git_changes.normalize_workspace_path(repo / "app", str(repo / "top.txt"))+++def test_a_dotfile_keeps_its_leading_dot(repo: Path) -> None:+ assert git_changes.normalize_workspace_path(repo, "./.env.example") == ".env.example"+++def test_a_plain_folder_is_reported_unavailable_not_raised(tmp_path: Path) -> None:+ changes = git_changes.workspace_changes(tmp_path)++ assert not changes.available+ assert changes.reason