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(agentic-ide): add workspace file explorer

rubenluetke10-beepcec2c6930c1f
diff --git a/jarvis/agentic_ide/folders.py b/jarvis/agentic_ide/folders.py
index b3cf212dcd..4351209185 100644
--- a/jarvis/agentic_ide/folders.py
+++ b/jarvis/agentic_ide/folders.py
@@ -18,6 +18,7 @@ recursive walk — because this runs when a session starts and its result is wha
gets folded into the voice turn's context (AP-9: awareness work stays off the
hot path; here it is computed once and cached in the session).
"""
+
from __future__ import annotations
import os
@@ -80,6 +81,7 @@ _INSTRUCTION_FILES: tuple[str, ...] = (
)
_MAX_ENTRIES = 400
+_MAX_WORKSPACE_ENTRIES = 2_000
_MAX_SKILLS = 60
@@ -93,6 +95,27 @@ class FolderEntry:
is_repo: bool
+@dataclass(frozen=True, slots=True)
+class WorkspaceEntry:
+ """One direct child of a directory inside an open workspace."""
+
+ name: str
+ path: str
+ is_directory: bool
+ is_symlink: bool
+ size: int | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class WorkspaceListing:
+ """A bounded, workspace-relative directory listing for the file explorer."""
+
+ path: str
+ entries: tuple[WorkspaceEntry, ...]
+ truncated: bool = False
+ error: str | None = None
+
+
@dataclass(slots=True)
class ProjectProfile:
"""Compact, cheap description of a chosen folder."""
@@ -251,6 +274,85 @@ def list_dir(
return entries, None
+def list_workspace_dir(
+ root: str | Path,
+ relative: str | Path = "",
+ *,
+ limit: int = _MAX_WORKSPACE_ENTRIES,
+) -> WorkspaceListing:
+ """List one directory without ever escaping the open workspace.
+
+ The explorer loads one level at a time, so even a large repository stays
+ cheap to open. Hidden entries are intentionally included: source control,
+ agent instructions, and environment examples are normal project files.
+ Symlinks are shown but never reported as expandable directories, which
+ prevents a link inside the workspace from becoming a browser for another
+ part of the machine.
+ """
+ root_path = Path(root).expanduser().resolve(strict=True)
+ relative_path = Path(relative or ".")
+ if relative_path.is_absolute():
+ raise ValueError("Workspace paths must be relative.")
+
+ try:
+ target = (root_path / relative_path).resolve(strict=True)
+ target.relative_to(root_path)
+ except (OSError, ValueError) as exc:
+ raise ValueError("That folder is outside the open workspace.") from exc
+ if not target.is_dir():
+ raise NotADirectoryError("That workspace path is not a folder.")
+
+ normalized_path = "" if target == root_path else target.relative_to(root_path).as_posix()
+ entries: list[WorkspaceEntry] = []
+ truncated = False
+ try:
+ with os.scandir(target) as it:
+ for item in it:
+ if len(entries) >= max(1, limit):
+ truncated = True
+ break
+ try:
+ is_symlink = item.is_symlink()
+ is_directory = item.is_dir(follow_symlinks=False)
+ size = None
+ if not is_directory and not is_symlink:
+ size = item.stat(follow_symlinks=False).st_size
+ except OSError:
+ # A file can disappear between scandir and stat. The next
+ # refresh will reflect it; one racing entry must not blank
+ # the rest of the folder.
+ continue
+ child = Path(item.path).relative_to(root_path).as_posix()
+ entries.append(
+ WorkspaceEntry(
+ name=item.name,
+ path=child,
+ is_directory=is_directory,
+ is_symlink=is_symlink,
+ size=size,
+ )
+ )
+ except PermissionError:
+ return WorkspaceListing(
+ path=normalized_path,
+ entries=(),
+ error="This folder cannot be read with the current permissions.",
+ )
+ except OSError:
+ return WorkspaceListing(
+ path=normalized_path,
+ entries=(),
+ error="This folder could not be read.",
+ )
+
+ entries.sort(key=lambda entry: (not entry.is_directory, entry.name.casefold()))
+ return WorkspaceListing(
+ path=normalized_path,
+ entries=tuple(entries),
+ truncated=truncated,
+ )
+
+
def search_folders(
query: str,
*,
@@ -458,7 +560,10 @@ def probe_project(path: str | Path) -> ProjectProfile:
__all__ = [
"FolderEntry",
"ProjectProfile",
+ "WorkspaceEntry",
+ "WorkspaceListing",
"list_dir",
+ "list_workspace_dir",
"probe_project",
"search_folders",
"start_points",
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index e49bb49cb5..94188fb170 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -13,6 +13,7 @@ Endpoints (prefix ``/api/agentic-ide``):
* ``POST /folders/native`` → open it and return what was picked
* ``POST /terminal-target/open`` → open a path printed by one terminal
* ``GET /workspaces`` → every open workspace, in tab order
+* ``GET /workspaces/{id}/files`` → browse that workspace's file tree
* ``PUT /workspaces/active`` → bring one to the front (null = wizard)
* ``PATCH /workspaces/{workspace_id}`` → rename one workspace tab
* ``DELETE /workspaces/{workspace_id}`` → close that one and stop its agents
@@ -91,7 +92,12 @@ from jarvis.agentic_ide.fleet_actions import (
terminals_closed_event,
wait_for_prompt_ready,
)
-from jarvis.agentic_ide.folders import list_dir, search_folders, start_points
+from jarvis.agentic_ide.folders import (
+ list_dir,
+ list_workspace_dir,
+ search_folders,
+ start_points,
+)
from jarvis.agentic_ide.names import default_names
from jarvis.agentic_ide.session import (
AGENT_DISPLAY,
@@ -624,6 +630,25 @@ class FoldersResponse(BaseModel):
device_name: str | None = None
+class WorkspaceFileItem(BaseModel):
+ """One workspace-relative entry in the IDE file explorer."""
+
+ name: str
+ path: str = Field(description="POSIX-style path relative to the workspace root.")
+ is_directory: bool
+ is_symlink: bool = False
+ size: int | None = None
+
+
+class WorkspaceFilesResponse(BaseModel):
+ workspace_id: str
+ root_name: str
+ path: str
+ entries: list[WorkspaceFileItem]
+ truncated: bool = False
+ error: str | None = None
+
+
class SearchResponse(BaseModel):
query: str
entries: list[FolderItem]
@@ -1210,6 +1235,36 @@ async def get_folders(path: str | None = None, include_hidden: bool = False) ->
)
+ "/workspaces/{workspace_id}/files",
+ response_model=WorkspaceFilesResponse,
+ summary="Browse files in an open workspace",
+)
+async def get_workspace_files(workspace_id: str, path: str = "") -> WorkspaceFilesResponse:
+ """One lazy-loaded level of the workspace's file tree.
+
+ Paths on the wire are relative to the selected workspace. The filesystem
+ helper resolves them again and rejects traversal and symlink escapes before
+ touching a directory, so this endpoint cannot become a general host browser.
+ """
+ session = get_registry().get(workspace_id)
+ if session is None:
+ raise HTTPException(status_code=404, detail="Workspace not found.")
+ try:
+ listing = await asyncio.to_thread(list_workspace_dir, session.folder, path)
+ except (OSError, ValueError):
+ raise HTTPException(status_code=404, detail="Workspace folder not found.") from None
+
+ return WorkspaceFilesResponse(
+ workspace_id=workspace_id,
+ root_name=Path(session.folder).name or str(session.folder),
+ path=listing.path,
+ entries=[WorkspaceFileItem(**asdict(entry)) for entry in listing.entries],
+ truncated=listing.truncated,
+ error=listing.error,
+ )
+
+
@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.
@@ -1907,7 +1962,7 @@ async def get_deck_queue() -> dict:
@router.post("/deck/hold/{name}", summary="Take a pane over from the Command Deck")
async def set_deck_hold(name: str, req: DeckHoldRequest) -> dict:
- """"I'll take this one" — and handing it back.
+ """ "I'll take this one" — and handing it back.
The honest limit on the deck's promise. A pane can hold a question only the
user can settle, and while they are dealing with it the deck must stop
@@ -1924,7 +1979,7 @@ async def set_deck_hold(name: str, req: DeckHoldRequest) -> dict:
@router.post("/deck/ack", summary="Answer a Command Deck report")
async def ack_deck_report(req: DeckAckRequest) -> dict:
- """"Tell me that one" / "later" / "drop it", from voice or from the lane.
+ """ "Tell me that one" / "later" / "drop it", from voice or from the lane.
Not a 404 for an unknown id: a report goes away when its pane does, and a
click that lands a moment after that got the outcome it wanted. `found`
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
index d17ee0e06b..3396961ba0 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx
@@ -54,6 +54,14 @@ vi.mock("@/lib/agenticIdeApi", () => ({
workspace_id: "ide_test",
terminals: [],
})),
+ fetchWorkspaceFiles: vi.fn(async () => ({
+ workspace_id: "ide_test",
+ root_name: "project",
+ path: "",
+ entries: [],
+ truncated: false,
+ })),
+ openTerminalTarget: vi.fn(),
promptTerminal: vi.fn(),
// Reached from the toolbar's settings panel, which the grid always renders.
setIdeActiveAccount: vi.fn(),
@@ -2414,6 +2422,22 @@ describe("the workspace header row", () => {
expect(screen.getByTestId("agentic-toolbar").textContent).toContain("project");
});
+
+ it("expands the file explorer without remounting any live agent pane", async () => {
+ renderGrid();
+
+ const pane = screen.getByTestId("pane-Mika");
+ const toggle = screen.getByTestId("workspace-explorer-toggle");
+ fireEvent.click(toggle);
+
+ expect(await screen.findByTestId("workspace-explorer")).toBeTruthy();
+ expect(toggle.getAttribute("aria-expanded")).toBe("true");
+ expect(screen.getByTestId("pane-Mika")).toBe(pane);
+
+ fireEvent.click(screen.getByRole("button", { name: "Close the explorer" }));
+ expect(screen.queryByTestId("workspace-explorer")).toBeNull();
+ expect(screen.getByTestId("pane-Mika")).toBe(pane);
+ });
});
/**
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
index 838d00b1ab..3c78377e12 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx
@@ -18,6 +18,7 @@ import {
Check,
ChevronUp,
FileText,
+ Files,
FolderGit2,
FolderPlus,
GripVertical,
@@ -76,6 +77,7 @@ import { isVoiceActive } from "./VoiceBubble";
import { PromptPreview } from "./PromptPreview";
import { PromptEditor } from "./PromptEditor";
import { WorkspaceSettings } from "./WorkspaceSettings";
+import { WorkspaceExplorer } from "./WorkspaceExplorer";
import { usePaneFileDrag } from "./paneFileDrag";
import {
chatTerminalIdentity,
@@ -833,6 +835,7 @@ export function AgenticGrid({
* screen, not workspace state worth a round-trip.
*/
const [viewMode, setViewModeState] = useState<WorkspaceView>(() => storedViewMode() ?? "grid");
+ const [explorerOpen, setExplorerOpen] = useState(false);
/**
* Which agent's terminal is unfolded on the deck, if any.
*
@@ -2325,6 +2328,23 @@ export function AgenticGrid({
</button>
))}
+ {/* The current workspace's files, in the familiar editor-explorer
+ position. It is an independent panel rather than a fourth reading
+ mode: opening it must not hide or remount a live terminal. */}
+ <button
+ type="button"
+ data-testid="workspace-explorer-toggle"
+ aria-pressed={explorerOpen}
+ aria-expanded={explorerOpen}
+ aria-controls="workspace-explorer"
+ onClick={() => setExplorerOpen((open) => !open)}
+ title={t("agentic_grid.explorer.toggle")}
+ aria-label={t("agentic_grid.explorer.toggle")}
+ className={cn(TOOLBAR_BTN, explorerOpen && TOOLBAR_BTN_ON)}
+ >
+ <Files className="h-4 w-4 shrink-0" aria-hidden />
+ </button>
+
{/* Even out the sizes. Beside the grid/chat toggle because both are
about the SHAPE of the workspace rather than what is in it, and
before the appearance controls because it changes the panes
@@ -2523,6 +2543,26 @@ export function AgenticGrid({
change of clothes.
*/}
<div className="flex min-h-0 flex-1">
+ {/* This zero-width host is ALWAYS present. Only its child mounts when
+ the explorer is open, so toggling the panel never shifts the live
+ terminal children in React's sibling order (and therefore never
+ tears down their PTY sockets). */}
+ <div
+ className={cn(
+ "h-full shrink-0 overflow-hidden transition-[width] duration-200 motion-reduce:transition-none",
+ explorerOpen ? "w-[280px]" : "w-0",
+ )}
+ aria-hidden={!explorerOpen}
+ >
+ {explorerOpen && (
+ <WorkspaceExplorer
+ workspaceId={session.id}
+ rootName={project.name}
+ onClose={() => setExplorerOpen(false)}
+ />
+ )}
+ </div>
+
{/* ------------------------------------------------------ chat rail */}
<aside
data-testid="agentic-chat-rail"
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.test.tsx
new file mode 100644
index 0000000000..1a07e62b5d
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.test.tsx
@@ -0,0 +1,151 @@
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const pushToast = vi.fn();
+
+vi.mock("@/store/events", () => ({
+ useEventStore: (selector: (state: { pushToast: typeof pushToast }) => unknown) =>
+ selector({ pushToast }),
+}));
+
+vi.mock("@/i18n", () => ({
+ useT: () => (key: string) =>
+ ({
+ "agentic_grid.explorer.title": "Explorer",
+ "agentic_grid.explorer.toggle": "Show or hide the workspace explorer",
+ "agentic_grid.explorer.refresh": "Refresh the file tree",
+ "agentic_grid.explorer.close": "Close the explorer",
+ "agentic_grid.explorer.loading": "Loading…",
+ "agentic_grid.explorer.empty": "Empty folder",
+ "agentic_grid.explorer.load_failed": "The folder could not be loaded.",
+ "agentic_grid.explorer.open_failed": "The file could not be opened.",
+ "agentic_grid.explorer.open_hint":
+ "Double-click a file to open it in your system editor.",
+ "agentic_grid.explorer.truncated":
+ "This folder has more entries than can be shown at once.",
+ })[key] ?? key,
+}));
+
+vi.mock("@/lib/agenticIdeApi", () => ({
+ fetchWorkspaceFiles: vi.fn(),
+ openTerminalTarget: vi.fn(),
+}));
+
+import * as api from "@/lib/agenticIdeApi";
+import { WorkspaceExplorer } from "./WorkspaceExplorer";
+
+describe("WorkspaceExplorer", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(api.fetchWorkspaceFiles).mockImplementation(async (_workspace, path = "") => {
+ if (path === "src") {
+ return {
+ workspace_id: "workspace-1",
+ root_name: "project",
+ path: "src",
+ truncated: false,
+ entries: [
+ {
+ name: "main.ts",
+ path: "src/main.ts",
+ is_directory: false,
+ is_symlink: false,
+ size: 12,
+ },
+ ],
+ };
+ }
+ return {
+ workspace_id: "workspace-1",
+ root_name: "project",
+ path: "",
+ truncated: false,
+ entries: [
+ {
+ name: "src",
+ path: "src",
+ is_directory: true,
+ is_symlink: false,
+ },
+ {
+ name: ".gitignore",
+ path: ".gitignore",
+ is_directory: false,
+ is_symlink: false,
+ size: 8,
+ },
+ ],
+ };
+ });
+ vi.mocked(api.openTerminalTarget).mockResolvedValue({
+ opened: true,
+ kind: "file",
+ path: "src/main.ts",
+ });
+ });
+
+ it("lazy-loads the complete tree and opens files from their relative paths", async () => {
+ render(
+ <WorkspaceExplorer
+ workspaceId="workspace-1"
+ rootName="fallback"
+ onClose={vi.fn()}
+ />,
+ );
+
+ expect(await screen.findByText(".gitignore")).toBeTruthy();
+ expect(screen.getByTestId("workspace-explorer").className).toContain(
+ "jarvis-panel-surface",
+ );
+ expect(screen.getByText("project")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("treeitem", { name: /src/i }));
+ expect(await screen.findByText("main.ts")).toBeTruthy();
+ expect(api.fetchWorkspaceFiles).toHaveBeenCalledWith("workspace-1", "src");
+
+ fireEvent.doubleClick(screen.getByRole("treeitem", { name: /main\.ts/i }));
+ await waitFor(() =>
+ expect(api.openTerminalTarget).toHaveBeenCalledWith(
+ "workspace-1",
+ "src/main.ts",
+ ),
+ );
+ });
+
+ it("keeps open failures visible and lets the close button collapse the panel", async () => {
+ const onClose = vi.fn();
+ vi.mocked(api.openTerminalTarget).mockRejectedValue(new Error("No editor is available."));
+ render(
+ <WorkspaceExplorer
+ workspaceId="workspace-1"
+ rootName="project"
+ onClose={onClose}
+ />,
+ );
+
+ const file = await screen.findByRole("treeitem", { name: /\.gitignore/i });
+ fireEvent.doubleClick(file);
+ await waitFor(() =>
+ expect(pushToast).toHaveBeenCalledWith("error", "No editor is available."),
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Close the explorer" }));
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+
+ it("shows a localized message when a directory cannot be loaded", async () => {
+ vi.mocked(api.fetchWorkspaceFiles).mockRejectedValue(new Error("Not Found"));
+
+ render(
+ <WorkspaceExplorer
+ workspaceId="workspace-1"
+ rootName="project"
+ onClose={vi.fn()}
+ />,
+ );
+
+ expect((await screen.findByRole("alert")).textContent).toBe(
+ "The folder could not be loaded.",
+ );
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.tsx
new file mode 100644
index 0000000000..c42f574e06
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.tsx
@@ -0,0 +1,389 @@
+/**
+ * A lazy, workspace-scoped file tree for the running Agentic IDE.
+ *
+ * It follows the familiar editor explorer shape without importing another
+ * product's chrome: compact rows, folders first, one gold selection mark, and
+ * the app's own translucent panel token over the shared wallpaper.
+ */
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ ChevronRight,
+ File,
+ FileCode2,
+ FileText,
+ Folder,
+ FolderOpen,
+ Image as ImageIcon,
+ Link2,
+ Loader2,
+ RefreshCw,
+ X,
+} from "lucide-react";
+
+import { useT } from "@/i18n";
+import {
+ fetchWorkspaceFiles,
+ openTerminalTarget,
+ type WorkspaceFileItem,
+} from "@/lib/agenticIdeApi";
+import { cn } from "@/lib/utils";
+import { useEventStore } from "@/store/events";
+
+interface DirectoryState {
+ entries: WorkspaceFileItem[];
+ loading: boolean;
+ truncated: boolean;
+ error: string | null;
+}
+
+interface WorkspaceExplorerProps {
+ workspaceId: string;
+ rootName: string;
+ onClose: () => void;
+}
+
+export function WorkspaceExplorer({
+ workspaceId,
+ rootName,
+ onClose,
+}: WorkspaceExplorerProps) {
+ const t = useT();
+ const tRef = useRef(t);
+ tRef.current = t;
+ const pushToast = useEventStore((state) => state.pushToast);
+ const [directories, setDirectories] = useState<Record<string, DirectoryState>>({});
+ const [openPaths, setOpenPaths] = useState<Set<string>>(() => new Set([""]));
+ const [selectedPath, setSelectedPath] = useState<string | null>(null);
+ const [resolvedRootName, setResolvedRootName] = useState(rootName);
+
+ const loadDirectory = useCallback(
+ async (path: string) => {
+ setDirectories((current) => ({
+ ...current,
+ [path]: {
+ entries: current[path]?.entries ?? [],
+ loading: true,
+ truncated: false,
+ error: null,
+ },
+ }));
+ try {
+ const response = await fetchWorkspaceFiles(workspaceId, path);
+ if (path === "") setResolvedRootName(response.root_name || rootName);
+ setDirectories((current) => ({
+ ...current,
+ [path]: {
+ entries: response.entries,
+ loading: false,
+ truncated: response.truncated,
+ error: response.error
+ ? tRef.current("agentic_grid.explorer.load_failed")
+ : null,
+ },
+ }));
+ } catch {
+ setDirectories((current) => ({
+ ...current,
+ [path]: {
+ entries: current[path]?.entries ?? [],
+ loading: false,
+ truncated: false,
+ error: tRef.current("agentic_grid.explorer.load_failed"),
+ },
+ }));
+ }
+ },
+ [rootName, workspaceId],
+ );
+
+ useEffect(() => {
+ setDirectories({});
+ setOpenPaths(new Set([""]));
+ setSelectedPath(null);
+ setResolvedRootName(rootName);
+ void loadDirectory("");
+ }, [loadDirectory, rootName]);
+
+ const toggleDirectory = useCallback(
+ (path: string) => {
+ setOpenPaths((current) => {
+ const next = new Set(current);
+ if (next.has(path)) {
+ next.delete(path);
+ } else {
+ next.add(path);
+ if (!directories[path]) void loadDirectory(path);
+ }
+ return next;
+ });
+ },
+ [directories, loadDirectory],
+ );
+
+ const openFile = useCallback(
+ async (path: string) => {
+ try {
+ await openTerminalTarget(workspaceId, path);
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : "";
+ pushToast(
+ "error",
+ detail || t("agentic_grid.explorer.open_failed"),
+ );
+ }
+ },
+ [pushToast, t, workspaceId],
+ );
+
+ const refresh = () => {
+ setDirectories({});
+ setOpenPaths(new Set([""]));
+ setSelectedPath(null);
+ void loadDirectory("");
+ };
+
+ const rootOpen = openPaths.has("");
+
+ return (
+ <aside
+ id="workspace-explorer"
+ data-testid="workspace-explorer"
+ className="jarvis-panel-surface flex h-full w-[280px] shrink-0 flex-col border-r border-border/70 backdrop-blur-xl"
+ aria-label={t("agentic_grid.explorer.title")}
+ >
+ <header className="flex h-10 shrink-0 items-center gap-2 border-b border-border/60 px-3">
+ <span className="min-w-0 flex-1 truncate text-[10px] font-semibold uppercase tracking-[0.16em] text-muted-foreground">
+ {t("agentic_grid.explorer.title")}
+ </span>
+ <button
+ type="button"
+ onClick={refresh}
+ aria-label={t("agentic_grid.explorer.refresh")}
+ title={t("agentic_grid.explorer.refresh")}
+ className="flex h-7 w-7 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60"
+ >
+ <RefreshCw className="h-3.5 w-3.5" aria-hidden />
+ </button>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label={t("agentic_grid.explorer.close")}
+ title={t("agentic_grid.explorer.close")}
+ className="flex h-7 w-7 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60"
+ >
+ <X className="h-3.5 w-3.5" aria-hidden />
+ </button>
+ </header>
+
+ <div className="min-h-0 flex-1 overflow-auto px-1.5 py-2 scrollbar-jarvis">
+ <div role="tree" aria-label={resolvedRootName}>
+ <button
+ type="button"
+ role="treeitem"
+ aria-expanded={rootOpen}
+ onClick={() => toggleDirectory("")}
+ className="flex h-7 w-full items-center gap-1.5 rounded-control px-1.5 text-left text-xs font-semibold uppercase tracking-[0.08em] text-foreground transition-colors hover:bg-secondary/70 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring/60"
+ >
+ <ChevronRight
+ className={cn(
+ "h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform",
+ rootOpen && "rotate-90",
+ )}
+ aria-hidden
+ />
+ {rootOpen ? (
+ <FolderOpen className="h-4 w-4 shrink-0 text-primary" aria-hidden />
+ ) : (
+ <Folder className="h-4 w-4 shrink-0 text-primary" aria-hidden />
+ )}
+ <span className="truncate">{resolvedRootName}</span>
+ </button>
+
+ {rootOpen && (
+ <TreeLevel
+ parentPath=""
+ depth={1}
+ directories={directories}
+ openPaths={openPaths}
+ selectedPath={selectedPath}
+ onToggle={toggleDirectory}
+ onSelect={setSelectedPath}
+ onOpenFile={(path) => void openFile(path)}
+ />
+ )}
+ </div>
+ </div>
+
+ <footer className="shrink-0 border-t border-border/60 px-3 py-2 text-[10px] leading-relaxed text-muted-foreground">
+ {t("agentic_grid.explorer.open_hint")}
+ </footer>
+ </aside>
+ );
+}
+
+function TreeLevel({
+ parentPath,
+ depth,
+ directories,
+ openPaths,
+ selectedPath,
+ onToggle,
+ onSelect,
+ onOpenFile,
+}: {
+ parentPath: string;
+ depth: number;
+ directories: Record<string, DirectoryState>;
+ openPaths: Set<string>;
+ selectedPath: string | null;
+ onToggle: (path: string) => void;
+ onSelect: (path: string) => void;
+ onOpenFile: (path: string) => void;
+}) {
+ const t = useT();
+ const directory = directories[parentPath];
+
+ if (!directory || directory.loading) {
+ return (
+ <div
+ role="status"
+ className="flex h-7 items-center gap-2 text-[11px] text-muted-foreground"
+ style={{ paddingLeft: `${depth * 12 + 9}px` }}
+ >
+ <Loader2 className="h-3 w-3 animate-spin motion-reduce:animate-none" aria-hidden />
+ {t("agentic_grid.explorer.loading")}
+ </div>
+ );
+ }
+
+ if (directory.error) {
+ return (
+ <div
+ role="alert"
+ className="my-1 border-l-2 border-destructive/70 py-1 pr-2 text-[11px] leading-relaxed text-destructive"
+ style={{ marginLeft: `${depth * 12 + 9}px`, paddingLeft: "8px" }}
+ >
+ {directory.error}
+ </div>
+ );
+ }
+
+ return (
+ <div role="group">
+ {directory.entries.map((entry) => {
+ const expandable = entry.is_directory && !entry.is_symlink;
+ const isOpen = expandable && openPaths.has(entry.path);
+ const selected = selectedPath === entry.path;
+ const EntryIcon = iconFor(entry, isOpen);
+ return (
+ <div key={entry.path}>
+ <button
+ type="button"
+ role="treeitem"
+ aria-expanded={expandable ? isOpen : undefined}
+ aria-selected={selected}
+ title={entry.path}
+ onClick={() => {
+ onSelect(entry.path);
+ if (expandable) onToggle(entry.path);
+ }}
+ onDoubleClick={() => {
+ if (!entry.is_directory && !entry.is_symlink) onOpenFile(entry.path);
+ }}
+ onKeyDown={(event) => {
+ if (
+ event.key === "Enter" &&
+ !entry.is_directory &&
+ !entry.is_symlink
+ ) {
+ event.preventDefault();
+ onOpenFile(entry.path);
+ }
+ }}
+ className={cn(
+ "group flex h-6 w-full items-center gap-1.5 rounded-control pr-2 text-left text-[12px] transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring/60",
+ selected
+ ? "bg-primary/10 text-foreground shadow-[inset_2px_0_0_hsl(var(--primary))]"
+ : "text-muted-foreground hover:bg-secondary/65 hover:text-foreground",
+ )}
+ style={{ paddingLeft: `${depth * 12}px` }}
+ >
+ {expandable ? (
+ <ChevronRight
+ className={cn(
+ "h-3 w-3 shrink-0 transition-transform",
+ isOpen && "rotate-90",
+ )}
+ aria-hidden
+ />
+ ) : (
+ <span className="w-3 shrink-0" aria-hidden />
+ )}
+ <EntryIcon
+ className={cn(
+ "h-3.5 w-3.5 shrink-0",
+ expandable
+ ? "text-primary/80"
+ : entry.is_symlink
+ ? "text-muted-foreground/70"
+ : selected
+ ? "text-primary"
+ : "text-muted-foreground group-hover:text-foreground/80",
+ )}
+ aria-hidden
+ />
+ <span className="min-w-0 flex-1 truncate">{entry.name}</span>
+ </button>
+
+ {isOpen && (
+ <TreeLevel
+ parentPath={entry.path}
+ depth={depth + 1}
+ directories={directories}
+ openPaths={openPaths}
+ selectedPath={selectedPath}
+ onToggle={onToggle}
+ onSelect={onSelect}
+ onOpenFile={onOpenFile}
+ />
+ )}
+ </div>
+ );
+ })}
+
+ {directory.entries.length === 0 && (
+ <div
+ className="h-6 truncate text-[11px] italic leading-6 text-muted-foreground/70"
+ style={{ paddingLeft: `${depth * 12 + 21}px` }}
+ >
+ {t("agentic_grid.explorer.empty")}
+ </div>
+ )}
+ {directory.truncated && (
+ <div
+ role="note"
+ className="py-1 pr-2 text-[10px] leading-relaxed text-amber-500"
+ style={{ paddingLeft: `${depth * 12 + 21}px` }}
+ >
+ {t("agentic_grid.explorer.truncated")}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function iconFor(entry: WorkspaceFileItem, open: boolean) {
+ if (entry.is_symlink) return Link2;
+ if (entry.is_directory) return open ? FolderOpen : Folder;
+ const name = entry.name.toLowerCase();
+ if (/\.(png|jpe?g|gif|webp|svg|ico|bmp)$/.test(name)) return ImageIcon;
+ if (/\.(md|mdx|txt|rst|log)$/.test(name)) return FileText;
+ if (
+ /\.(py|js|jsx|ts|tsx|css|scss|html|rs|go|java|c|cc|cpp|h|hpp|sh|ps1|toml|ya?ml|json)$/.test(
+ name,
+ )
+ ) {
+ return FileCode2;
+ }
+ return File;
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 1e56c42ac7..890ebdaeb0 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -3922,6 +3922,18 @@
"already": "Alle Terminals haben bereits dieselbe Größe.",
"grid_only": "Größen gleichen sich im Terminal-Raster an — hier gibt es keine Grenzen zum Angleichen."
},
+ "explorer": {
+ "title": "Explorer",
+ "toggle": "Workspace-Explorer ein- oder ausblenden",
+ "refresh": "Dateibaum aktualisieren",
+ "close": "Explorer schließen",
+ "loading": "Wird geladen…",
+ "empty": "Leerer Ordner",
+ "load_failed": "Der Ordner konnte nicht geladen werden.",
+ "open_failed": "Die Datei konnte nicht geöffnet werden.",
+ "open_hint": "Doppelklick öffnet eine Datei im System-Editor.",
+ "truncated": "Dieser Ordner enthält mehr Einträge, als gleichzeitig angezeigt werden können."
+ },
"arrange": {
"carrying": "auf ein Terminal ziehen",
"swap": "Mit {0} tauschen",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index ec4b544349..913af3f05d 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -3922,6 +3922,18 @@
"already": "Every terminal already has the same size.",
"grid_only": "Sizes even out in the terminal grid — there are no boundaries to even here."
},
+ "explorer": {
+ "title": "Explorer",
+ "toggle": "Show or hide the workspace explorer",
+ "refresh": "Refresh the file tree",
+ "close": "Close the explorer",
+ "loading": "Loading…",
+ "empty": "Empty folder",
+ "load_failed": "The folder could not be loaded.",
+ "open_failed": "The file could not be opened.",
+ "open_hint": "Double-click a file to open it in your system editor.",
+ "truncated": "This folder has more entries than can be shown at once."
+ },
"arrange": {
"carrying": "drop it on a terminal",
"swap": "Swap with {0}",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 43ebfdab66..4f4c0b3553 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -3922,6 +3922,18 @@
"already": "Todos los terminales ya tienen el mismo tamaño.",
"grid_only": "Los tamaños se igualan en la cuadrícula de terminales: aquí no hay bordes que igualar."
},
+ "explorer": {
+ "title": "Explorador",
+ "toggle": "Mostrar u ocultar el explorador del espacio de trabajo",
+ "refresh": "Actualizar el árbol de archivos",
+ "close": "Cerrar el explorador",
+ "loading": "Cargando…",
+ "empty": "Carpeta vacía",
+ "load_failed": "No se pudo cargar la carpeta.",
+ "open_failed": "No se pudo abrir el archivo.",
+ "open_hint": "Haz doble clic en un archivo para abrirlo en el editor del sistema.",
+ "truncated": "Esta carpeta tiene más entradas de las que se pueden mostrar a la vez."
+ },
"arrange": {
"carrying": "suéltalo sobre un terminal",
"swap": "Intercambiar con {0}",
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index 77cfb32465..401718f084 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -41,6 +41,24 @@ export interface FoldersResponse {
device_name?: string | null;
}
+export interface WorkspaceFileItem {
+ name: string;
+ /** POSIX-style path relative to the workspace root. */
+ path: string;
+ is_directory: boolean;
+ is_symlink: boolean;
+ size?: number | null;
+}
+
+export interface WorkspaceFilesResponse {
+ workspace_id: string;
+ root_name: string;
+ path: string;
+ entries: WorkspaceFileItem[];
+ truncated: boolean;
+ error?: string | null;
+}
+
export interface SearchResponse {
query: string;
entries: FolderItem[];
@@ -700,6 +718,17 @@ export function fetchFolders(path?: string | null): Promise<FoldersResponse> {
return getJson<FoldersResponse>(`/api/agentic-ide/folders${query}`);
}
+/** Load one level of an open workspace's file tree. */
+export function fetchWorkspaceFiles(
+ workspaceId: string,
+ path = "",
+): Promise<WorkspaceFilesResponse> {
+ const query = path ? `?path=${encodeURIComponent(path)}` : "";
+ return getJson<WorkspaceFilesResponse>(
+ `/api/agentic-ide/workspaces/${encodeURIComponent(workspaceId)}/files${query}`,
+ );
+}
+
export function searchFolders(
query: string,
limit = 40,
diff --git a/tests/unit/agentic_ide/test_workspace_explorer.py b/tests/unit/agentic_ide/test_workspace_explorer.py
new file mode 100644
index 0000000000..5dbcef3fa5
--- /dev/null
+++ b/tests/unit/agentic_ide/test_workspace_explorer.py
@@ -0,0 +1,108 @@
+"""The Agentic-IDE explorer exposes one safe, complete workspace level at a time."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException
+
+from jarvis.agentic_ide.folders import list_workspace_dir
+from jarvis.ui.web import agentic_ide_routes as routes
+
+
+def test_listing_includes_hidden_and_dependency_directories(tmp_path: Path) -> None:
+ (tmp_path / "src").mkdir()
+ (tmp_path / "node_modules").mkdir()
+ (tmp_path / ".github").mkdir()
+ (tmp_path / ".env.example").write_text("TOKEN=\n", encoding="utf-8")
+ (tmp_path / "README.md").write_text("hello\n", encoding="utf-8")
+
+ listing = list_workspace_dir(tmp_path)
+
+ assert listing.path == ""
+ assert [entry.name for entry in listing.entries] == [
+ ".github",
+ "node_modules",
+ "src",
+ ".env.example",
+ "README.md",
+ ]
+ assert [entry.is_directory for entry in listing.entries[:3]] == [True, True, True]
+ assert listing.entries[-1].size == 7
+
+
+def test_nested_listing_keeps_every_path_workspace_relative(tmp_path: Path) -> None:
+ nested = tmp_path / "src" / "feature"
+ nested.mkdir(parents=True)
+ (nested / "panel.tsx").write_text("export {};\n", encoding="utf-8")
+
+ listing = list_workspace_dir(tmp_path, "src/feature")
+
+ assert listing.path == "src/feature"
+ assert [entry.path for entry in listing.entries] == ["src/feature/panel.tsx"]
+ assert str(tmp_path) not in repr(listing)
+
+
[email protected]("path", ["..", "../outside", "src/../../outside"])
+def test_listing_rejects_workspace_traversal(tmp_path: Path, path: str) -> None:
+ (tmp_path / "src").mkdir()
+ (tmp_path.parent / "outside").mkdir(exist_ok=True)
+
+ with pytest.raises(ValueError, match="outside the open workspace"):
+ list_workspace_dir(tmp_path, path)
+
+
+def test_symlinked_directories_are_visible_but_not_expandable(tmp_path: Path) -> None:
+ outside = tmp_path.parent / "outside-link-target"
+ outside.mkdir(exist_ok=True)
+ link = tmp_path / "linked"
+ try:
+ os.symlink(outside, link, target_is_directory=True)
+ except (NotImplementedError, OSError):
+ pytest.skip("Directory symlinks are unavailable on this host")
+
+ listing = list_workspace_dir(tmp_path)
+
+ entry = next(item for item in listing.entries if item.name == "linked")
+ assert entry.is_symlink is True
+ assert entry.is_directory is False
+ with pytest.raises(ValueError, match="outside the open workspace"):
+ list_workspace_dir(tmp_path, "linked")
+
+
+def workspace(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ root = tmp_path / "project"
+ root.mkdir()
+ session = SimpleNamespace(folder=str(root))
+ registry = SimpleNamespace(
+ get=lambda workspace_id: session if workspace_id == "workspace-1" else None
+ )
+ monkeypatch.setattr(routes, "get_registry", lambda: registry)
+ return root
+
+
+async def test_workspace_route_returns_only_relative_paths(workspace: Path) -> None:
+ (workspace / "src").mkdir()
+ (workspace / "src" / "main.py").write_text("print('ready')\n", encoding="utf-8")
+
+ response = await routes.get_workspace_files("workspace-1", "src")
+
+ assert response.workspace_id == "workspace-1"
+ assert response.root_name == "project"
+ assert response.path == "src"
+ assert [entry.path for entry in response.entries] == ["src/main.py"]
+ assert str(workspace) not in response.model_dump_json()
+
+
+async def test_workspace_route_hides_unknown_and_escaping_paths(workspace: Path) -> None:
+ with pytest.raises(HTTPException) as unknown:
+ await routes.get_workspace_files("gone")
+ assert unknown.value.status_code == 404
+
+ with pytest.raises(HTTPException) as traversal:
+ await routes.get_workspace_files("workspace-1", "..")
+ assert traversal.value.status_code == 404