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): search, device name, recents and drag-and-drop in the folder step

Ruben Lütke43449cc517dc
diff --git a/jarvis/agentic_ide/device.py b/jarvis/agentic_ide/device.py
new file mode 100644
index 0000000000..611eb16add
--- /dev/null
+++ b/jarvis/agentic_ide/device.py
@@ -0,0 +1,102 @@
+"""The name of THIS machine, the way its owner named it.
+
+Why this needs its own module: the obvious sources are all wrong for a label a
+human reads. ``Path.home().name`` gives the account name ("Administrator"),
+which says nothing about the device. ``platform.node()`` gives the network
+hostname, which on macOS is a mangled derivative ("rubens-macbook.local", or
+worse "Rubens-MacBook-Pro-2.fritz.box"). What the owner actually set — "Ruben's
+MacBook" — lives in a per-OS place:
+
+* **macOS** ``scutil --get ComputerName`` (the Sharing pane's "Computer Name")
+* **Linux** ``hostnamectl --pretty`` ("Pretty hostname"), else /etc/hostname
+* **Windows** the computer name, which IS what the user typed when renaming the
+ PC, available without a subprocess via the ``COMPUTERNAME`` environment
+
+Every lookup degrades: an unreachable command, a missing tool, or a container
+without hostnamectl falls back to ``platform.node()`` and finally to a plain
+"This machine". The result is cached for the process, because it cannot change
+without a restart of the OS-level identity and because nothing user-facing
+should pay for a subprocess twice (AP-26).
+
+Subprocess discipline: every spawn passes ``NO_WINDOW_CREATIONFLAGS`` (AP-1) and
+a short timeout — a hung `scutil` must never hold a REST request open.
+"""
+from __future__ import annotations
+
+import os
+import platform
+import subprocess
+import sys
+from functools import lru_cache
+
+from loguru import logger
+
+_TIMEOUT_S = 2.0
+_FALLBACK = "This machine"
+
+
+def _run(argv: list[str]) -> str | None:
+ """Run a short identity command, returning its trimmed stdout or None."""
+ try:
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+ proc = subprocess.run( # noqa: S603 - fixed argv, no shell
+ argv,
+ capture_output=True,
+ text=True,
+ timeout=_TIMEOUT_S,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ logger.debug("device name: {} failed: {}", argv[0], exc)
+ return None
+ out = (proc.stdout or "").strip()
+ return out or None
+
+
+def _strip_hostname_noise(name: str) -> str:
+ """Drop the network suffix and separators a hostname carries.
+
+ "Rubens-MacBook-Pro.local" -> "Rubens MacBook Pro". Only applied to a
+ hostname fallback; a real ComputerName is used verbatim.
+ """
+ base = name.split(".", 1)[0]
+ return base.replace("-", " ").replace("_", " ").strip() or name
+
+
+@lru_cache(maxsize=1)
+def device_name() -> str:
+ """Human-facing name of this machine ("Ruben's MacBook", "STUDIO-PC")."""
+ if sys.platform == "darwin":
+ friendly = _run(["scutil", "--get", "ComputerName"])
+ if friendly:
+ return friendly
+ elif sys.platform.startswith("linux"):
+ pretty = _run(["hostnamectl", "--pretty"])
+ if pretty:
+ return pretty
+ try:
+ from pathlib import Path
+
+ text = Path("/etc/hostname").read_text(encoding="utf-8").strip()
+ if text:
+ return _strip_hostname_noise(text)
+ except OSError:
+ pass
+ else:
+ # Windows: COMPUTERNAME *is* the name shown in Settings > About.
+ env = (os.environ.get("COMPUTERNAME") or "").strip()
+ if env:
+ return env
+
+ node = (platform.node() or "").strip()
+ return _strip_hostname_noise(node) if node else _FALLBACK
+
+
+def reset_cache() -> None:
+ """Forget the cached name — tests only."""
+ device_name.cache_clear()
+
+
+__all__ = ["device_name", "reset_cache"]
diff --git a/jarvis/agentic_ide/folders.py b/jarvis/agentic_ide/folders.py
index 3d50726e79..b25a34579f 100644
--- a/jarvis/agentic_ide/folders.py
+++ b/jarvis/agentic_ide/folders.py
@@ -21,6 +21,7 @@ hot path; here it is computed once and cached in the session).
from __future__ import annotations
import os
+from collections import deque
from dataclasses import asdict, dataclass, field
from pathlib import Path
@@ -237,6 +238,95 @@ def list_dir(
return entries, None
+def search_folders(
+ query: str,
+ *,
+ roots: list[Path] | None = None,
+ limit: int = 40,
+ max_depth: int = 5,
+) -> list[FolderEntry]:
+ """Folders whose name matches ``query``, searched breadth-first.
+
+ Breadth-first on purpose: the folder a person is looking for is almost always
+ a few levels down from home or from a code directory, so widening before
+ deepening finds it sooner and lets the walk stop early. The traversal is
+ bounded three ways — depth, a hard visit budget, and the shared skip list —
+ because an unbounded walk of a home directory on a spinning disk or a network
+ share would block for minutes.
+
+ Ranking puts exact name matches first, then prefix matches, then substring
+ matches; within each tier projects and repositories come before plain
+ folders, because that is what someone opening a coding workspace wants.
+ """
+ needle = query.strip().lower()
+ if not needle:
+ return []
+
+ if roots is None:
+ home = Path.home()
+ roots = [home]
+ for extra in ("Desktop", "Documents", "Projects", "Code", "dev", "src", "repos"):
+ candidate = home / extra
+ if candidate.is_dir():
+ roots.append(candidate)
+
+ # Visit budget: generous enough to cover a real code tree, small enough that
+ # the worst case stays well inside a request timeout.
+ budget = 20_000
+ seen: set[str] = set()
+ hits: list[tuple[int, int, str, FolderEntry]] = []
+
+ queue: deque[tuple[Path, int]] = deque((root, 0) for root in roots)
+ while queue and budget > 0 and len(hits) < limit * 4:
+ current, depth = queue.popleft()
+ key = str(current).lower()
+ if key in seen:
+ continue
+ seen.add(key)
+ if depth > max_depth:
+ continue
+ try:
+ with os.scandir(current) as it:
+ for item in it:
+ budget -= 1
+ if budget <= 0:
+ break
+ name = item.name
+ if name in _SKIP_DIRS or _is_hidden(name):
+ continue
+ try:
+ if not item.is_dir(follow_symlinks=False):
+ continue
+ except OSError:
+ continue
+ child = Path(item.path)
+ lowered = name.lower()
+ if needle in lowered:
+ tier = 0 if lowered == needle else 1 if lowered.startswith(needle) else 2
+ is_project, is_repo = _looks_like_project(child)
+ kind = 0 if is_repo else 1 if is_project else 2
+ hits.append(
+ (
+ tier,
+ kind,
+ lowered,
+ FolderEntry(
+ name=name,
+ path=str(child),
+ is_project=is_project,
+ is_repo=is_repo,
+ ),
+ )
+ )
+ if depth < max_depth:
+ queue.append((child, depth + 1))
+ except (PermissionError, OSError):
+ continue
+
+ hits.sort(key=lambda h: (h[0], h[1], h[2]))
+ return [entry for _t, _k, _n, entry in hits[:limit]]
+
+
def _git_branch(root: Path) -> str | None:
"""Current branch from ``.git/HEAD`` — no subprocess, no git required."""
head = root / ".git" / "HEAD"
@@ -326,5 +416,6 @@ __all__ = [
"ProjectProfile",
"list_dir",
"probe_project",
+ "search_folders",
"start_points",
]
diff --git a/jarvis/agentic_ide/recents.py b/jarvis/agentic_ide/recents.py
new file mode 100644
index 0000000000..94685c0014
--- /dev/null
+++ b/jarvis/agentic_ide/recents.py
@@ -0,0 +1,140 @@
+"""Recently opened Agentic-IDE workspaces.
+
+Opening the same project twice should not mean browsing to it twice. Each started
+session records where it ran and how it was laid out, so the next visit is one
+click — and the recorded terminal count and agent split are replayed, because
+someone who opened a repo with "3 × Claude Code" almost always wants that again.
+
+Storage is a single small JSON file under the per-user data directory (never in
+the repo, never in ``jarvis.toml``). Writes are atomic (temp file + ``os.replace``)
+and every read is defensive: a truncated or hand-edited file degrades to "no
+recents" instead of breaking the wizard. Entries that no longer exist on disk are
+dropped on read, so a deleted or unplugged folder disappears by itself rather
+than failing at launch.
+"""
+from __future__ import annotations
+
+import json
+import os
+import time
+from dataclasses import asdict, dataclass, field
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+MAX_RECENTS = 8
+
+
+@dataclass(slots=True)
+class RecentWorkspace:
+ """One previously opened workspace."""
+
+ path: str
+ name: str
+ terminals: int = 1
+ # agent name -> how many terminals ran it, e.g. {"claude": 2, "codex": 1}
+ agents: dict[str, int] = field(default_factory=dict)
+ last_used: float = 0.0
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+def _store_path() -> Path:
+ from jarvis.core.paths import user_data_dir
+
+ return user_data_dir() / "agentic_ide" / "recents.json"
+
+
+def _load_raw() -> list[dict[str, Any]]:
+ path = _store_path()
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ return []
+ except (OSError, ValueError) as exc:
+ logger.warning("Agentic IDE: unreadable recents file, ignoring it: {}", exc)
+ return []
+ if not isinstance(data, list):
+ return []
+ return [item for item in data if isinstance(item, dict)]
+
+
+def load(*, verify_exists: bool = True) -> list[RecentWorkspace]:
+ """Recent workspaces, newest first. Vanished folders are filtered out."""
+ out: list[RecentWorkspace] = []
+ for item in _load_raw():
+ path = str(item.get("path") or "").strip()
+ if not path:
+ continue
+ if verify_exists:
+ try:
+ if not Path(path).is_dir():
+ continue
+ except OSError:
+ continue
+ agents = item.get("agents")
+ out.append(
+ RecentWorkspace(
+ path=path,
+ name=str(item.get("name") or Path(path).name or path),
+ terminals=max(1, int(item.get("terminals") or 1)),
+ agents={
+ str(k): int(v)
+ for k, v in (agents.items() if isinstance(agents, dict) else [])
+ },
+ last_used=float(item.get("last_used") or 0.0),
+ )
+ )
+ out.sort(key=lambda r: r.last_used, reverse=True)
+ return out[:MAX_RECENTS]
+
+
+def remember(path: str, *, terminals: int, agents: dict[str, int]) -> None:
+ """Record (or refresh) one workspace as the most recent.
+
+ Best-effort: a failure to persist must never stop a session from opening, so
+ problems are logged and swallowed.
+ """
+ resolved = str(Path(path).expanduser())
+ entry = RecentWorkspace(
+ path=resolved,
+ name=Path(resolved).name or resolved,
+ terminals=max(1, terminals),
+ agents=dict(agents),
+ last_used=time.time(),
+ )
+ kept = [r for r in load(verify_exists=False) if r.path.lower() != resolved.lower()]
+ payload = [entry.to_dict(), *(r.to_dict() for r in kept)][:MAX_RECENTS]
+
+ target = _store_path()
+ try:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ tmp = target.with_suffix(".json.tmp")
+ tmp.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+ os.replace(tmp, target)
+ except OSError as exc:
+ logger.warning("Agentic IDE: could not persist recents: {}", exc)
+
+
+def forget(path: str) -> bool:
+ """Remove one entry. Returns True when something was removed."""
+ resolved = str(Path(path).expanduser()).lower()
+ current = load(verify_exists=False)
+ kept = [r for r in current if r.path.lower() != resolved]
+ if len(kept) == len(current):
+ return False
+ target = _store_path()
+ try:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ tmp = target.with_suffix(".json.tmp")
+ tmp.write_text(json.dumps([r.to_dict() for r in kept], indent=2), encoding="utf-8")
+ os.replace(tmp, target)
+ return True
+ except OSError as exc:
+ logger.warning("Agentic IDE: could not update recents: {}", exc)
+ return False
+
+
+__all__ = ["MAX_RECENTS", "RecentWorkspace", "forget", "load", "remember"]
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index dbac6b34ef..ada18cf861 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -323,6 +323,22 @@ class Registry:
created_at=time.time(),
)
self._session = session
+ # Remember the workspace so the next visit is one click, replaying
+ # the same terminal count and agent split (see recents.py).
+ split: dict[str, int] = {}
+ for term in terminals:
+ split[term.agent] = split.get(term.agent, 0) + 1
+ try:
+ from . import recents
+
+ await asyncio.to_thread(
+ recents.remember,
+ str(root),
+ terminals=len(terminals),
+ agents=split,
+ )
+ except Exception as exc: # noqa: BLE001 - convenience, never fatal
+ logger.warning("Agentic IDE: recents not updated: {}", exc)
logger.info(
"Agentic IDE session started: {} terminals in {}",
len(terminals),
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index 56e1462b77..11bfc7cf6d 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -29,7 +29,9 @@ from pathlib import Path
from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
from pydantic import BaseModel, Field
-from jarvis.agentic_ide.folders import list_dir, start_points
+from jarvis.agentic_ide import recents
+from jarvis.agentic_ide.device import device_name
+from jarvis.agentic_ide.folders import list_dir, search_folders, start_points
from jarvis.agentic_ide.names import default_names
from jarvis.agentic_ide.session import (
AGENT_DISPLAY,
@@ -106,6 +108,47 @@ class FoldersResponse(BaseModel):
parent: str | None
entries: list[FolderItem]
error: str | None = None
+ # Human-facing name of this machine ("Ruben's MacBook"), so the picker can
+ # label the start points with the device rather than the account folder
+ # ("Administrator" tells the user nothing about which computer this is).
+ device_name: str | None = None
+
+
+class SearchResponse(BaseModel):
+ query: str
+ entries: list[FolderItem]
+ truncated: bool = False
+
+
+class RecentItem(BaseModel):
+ path: str
+ name: str
+ terminals: int
+ agents: dict[str, int]
+ last_used: float
+ exists: bool = True
+
+
+class RecentsResponse(BaseModel):
+ device_name: str
+ recents: list[RecentItem]
+
+
+class ResolveRequest(BaseModel):
+ path: str | None = Field(
+ default=None,
+ description="A full path from a drop (folder, file, or file:// URI).",
+ )
+ name: str | None = Field(
+ default=None,
+ description="Folder name only — used when the drop carried no path.",
+ )
+
+
+class ResolveResponse(BaseModel):
+ resolved: str | None = None
+ candidates: list[FolderItem] = Field(default_factory=list)
+ detail: str = ""
# --------------------------------------------------------------------------- #
@@ -156,6 +199,7 @@ async def get_folders(path: str | None = None, include_hidden: bool = False) ->
path=None,
parent=None,
entries=[FolderItem(**asdict(e)) for e in entries],
+ device_name=device_name(),
)
found, error = await asyncio.to_thread(list_dir, path, include_hidden=include_hidden)
@@ -166,9 +210,116 @@ async def get_folders(path: str | None = None, include_hidden: bool = False) ->
parent=parent,
entries=[FolderItem(**asdict(e)) for e in found],
error=error,
+ device_name=device_name(),
+ )
+
+
[email protected]("/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.
+
+ Bounded by depth and a visit budget, so this stays a fast interactive search
+ rather than a full-disk crawl (see ``folders.search_folders``).
+ """
+ capped = max(1, min(limit, 100))
+ hits = await asyncio.to_thread(search_folders, q, limit=capped)
+ return SearchResponse(
+ query=q,
+ entries=[FolderItem(**asdict(e)) for e in hits],
+ truncated=len(hits) >= capped,
+ )
+
+
[email protected]("/recents", response_model=RecentsResponse, summary="Recently opened workspaces")
+async def get_recents() -> RecentsResponse:
+ """Workspaces opened before, newest first, with their previous layout."""
+ entries = await asyncio.to_thread(recents.load)
+ return RecentsResponse(
+ device_name=device_name(),
+ recents=[
+ RecentItem(
+ path=r.path,
+ name=r.name,
+ terminals=r.terminals,
+ agents=r.agents,
+ last_used=r.last_used,
+ exists=True,
+ )
+ for r in entries
+ ],
)
[email protected]("/recents", summary="Forget a recent workspace")
+async def delete_recent(path: str) -> dict:
+ """Remove one entry from the recents list (the folder itself is untouched)."""
+ removed = await asyncio.to_thread(recents.forget, path)
+ return {"ok": True, "removed": removed}
+
+
[email protected]("/folders/resolve", response_model=ResolveResponse, summary="Resolve a dropped folder")
+async def resolve_folder(req: ResolveRequest) -> ResolveResponse:
+ """Turn a drag-and-drop payload into a usable folder path.
+
+ Browsers do not hand a web page the real path of a dropped folder, so the
+ frontend sends whatever it managed to extract and this route does the rest:
+
+ * a ``file://`` URI or a plain path is unwrapped and used directly,
+ * a path pointing at a FILE resolves to the folder containing it (dropping a
+ file from inside a project is a normal way to mean "that project"),
+ * with only a folder NAME available, the name is searched for — one hit is
+ taken, several are returned for the user to pick from.
+ """
+ raw = (req.path or "").strip()
+ if raw:
+ candidate = _unwrap_file_uri(raw)
+ try:
+ # expanduser() is string/env work; the stats below run in threads.
+ resolved_path = Path(candidate).expanduser() # noqa: ASYNC240
+ if await asyncio.to_thread(resolved_path.is_dir):
+ return ResolveResponse(resolved=str(resolved_path))
+ if await asyncio.to_thread(resolved_path.is_file):
+ return ResolveResponse(
+ resolved=str(resolved_path.parent),
+ detail=f"Used the folder containing {resolved_path.name}.",
+ )
+ except OSError as exc:
+ return ResolveResponse(detail=f"Could not read that path: {exc}")
+
+ wanted = (req.name or "").strip()
+ if not wanted:
+ return ResolveResponse(
+ detail="That drop carried no folder path — browse to the folder or paste its path."
+ )
+
+ hits = await asyncio.to_thread(search_folders, wanted, limit=12)
+ items = [FolderItem(**asdict(e)) for e in hits]
+ if len(items) == 1:
+ return ResolveResponse(resolved=items[0].path, candidates=items)
+ if not items:
+ return ResolveResponse(
+ detail=f'No folder called "{wanted}" was found on this machine.'
+ )
+ return ResolveResponse(
+ candidates=items,
+ detail=f'Several folders are called "{wanted}" — pick the right one.',
+ )
+
+
+def _unwrap_file_uri(value: str) -> str:
+ """``file:///C:/x`` / ``file:///home/x`` -> a native path; anything else as-is."""
+ if not value.lower().startswith("file:"):
+ return value
+ from urllib.parse import unquote, urlparse
+
+ parsed = urlparse(value)
+ path = unquote(parsed.path)
+ # Windows URIs carry a leading slash before the drive letter.
+ if len(path) > 2 and path[0] == "/" and path[2] == ":":
+ path = path[1:]
+ return path
+
+
@router.post("/session", summary="Open an Agentic-IDE workspace")
async def start_session(req: StartSessionRequest) -> dict:
"""Open ``folder`` with one named terminal per requested agent."""
diff --git a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx
new file mode 100644
index 0000000000..023a4957e0
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx
@@ -0,0 +1,222 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/lib/agenticIdeApi", () => ({
+ fetchFolders: vi.fn(),
+ searchFolders: vi.fn(),
+ fetchRecents: vi.fn(),
+ forgetRecent: vi.fn(),
+ resolveDroppedFolder: vi.fn(),
+}));
+
+import { FolderPicker, extractDropPayload } from "./FolderPicker";
+import * as api from "@/lib/agenticIdeApi";
+
+const LISTING = {
+ path: null,
+ parent: null,
+ entries: [
+ { name: "webshop", path: "/home/ruben/webshop", is_project: true, is_repo: true },
+ { name: "notes", path: "/home/ruben/notes", is_project: false, is_repo: false },
+ ],
+ device_name: "Rubens MacBook",
+};
+
+beforeEach(() => {
+ vi.mocked(api.fetchFolders).mockResolvedValue(LISTING);
+ vi.mocked(api.fetchRecents).mockResolvedValue({
+ device_name: "Rubens MacBook",
+ recents: [],
+ });
+ vi.mocked(api.searchFolders).mockResolvedValue({
+ query: "",
+ entries: [],
+ truncated: false,
+ });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+/** Minimal DataTransfer stand-in — jsdom has no real one. */
+function dataTransfer(opts: {
+ text?: string;
+ uriList?: string;
+ directoryName?: string;
+ relativePath?: string;
+}): DataTransfer {
+ const items: unknown[] = [];
+ if (opts.directoryName) {
+ items.push({
+ kind: "file",
+ type: "",
+ webkitGetAsEntry: () => ({ isDirectory: true, name: opts.directoryName }),
+ });
+ }
+ const files = opts.relativePath
+ ? [Object.assign(new File(["x"], "file.txt"), { webkitRelativePath: opts.relativePath })]
+ : [];
+ return {
+ dropEffect: "none",
+ getData: (type: string) =>
+ type === "text/uri-list" ? (opts.uriList ?? "") : (opts.text ?? ""),
+ items,
+ files,
+ types: ["Files"],
+ } as unknown as DataTransfer;
+}
+
+describe("extractDropPayload", () => {
+ it("prefers a real path from the URI list", () => {
+ const payload = extractDropPayload(
+ dataTransfer({ uriList: "file:///home/ruben/webshop\r\n" }),
+ );
+ expect(payload.path).toBe("file:///home/ruben/webshop");
+ });
+
+ it("falls back to plain text", () => {
+ expect(extractDropPayload(dataTransfer({ text: "C:\\work\\shop" })).path).toBe(
+ "C:\\work\\shop",
+ );
+ });
+
+ it("takes the folder name when no path is offered", () => {
+ // This is the normal browser case: a dropped directory exposes its NAME but
+ // never its path, so the backend has to search for it.
+ const payload = extractDropPayload(dataTransfer({ directoryName: "webshop" }));
+ expect(payload.name).toBe("webshop");
+ expect(payload.path).toBeUndefined();
+ });
+
+ it("derives the folder name from a dropped file inside it", () => {
+ const payload = extractDropPayload(
+ dataTransfer({ relativePath: "webshop/src/main.ts" }),
+ );
+ expect(payload.name).toBe("webshop");
+ });
+
+ it("returns nothing for an empty drop", () => {
+ expect(extractDropPayload(dataTransfer({}))).toEqual({});
+ expect(extractDropPayload(null)).toEqual({});
+ });
+});
+
+describe("FolderPicker", () => {
+ it("labels the machine by its own name, not the account folder", async () => {
+ render(<FolderPicker selected={null} onSelect={vi.fn()} />);
+ expect(await screen.findByText("Rubens MacBook")).toBeTruthy();
+ });
+
+ it("filters the open list locally on a single character", async () => {
+ render(<FolderPicker selected={null} onSelect={vi.fn()} />);
+ await screen.findByText("webshop");
+ fireEvent.change(screen.getByTestId("folder-search"), { target: { value: "n" } });
+ expect(screen.queryByText("webshop")).toBeNull();
+ expect(screen.getByText("notes")).toBeTruthy();
+ // Too short to bother the backend.
+ expect(api.searchFolders).not.toHaveBeenCalled();
+ });
+
+ it("searches the machine once the query is long enough", async () => {
+ vi.mocked(api.searchFolders).mockResolvedValue({
+ query: "shop",
+ entries: [
+ { name: "old-webshop", path: "/archive/old-webshop", is_project: true, is_repo: false },
+ ],
+ truncated: false,
+ });
+ render(<FolderPicker selected={null} onSelect={vi.fn()} />);
+ await screen.findByText("webshop");
+
+ fireEvent.change(screen.getByTestId("folder-search"), { target: { value: "shop" } });
+ await waitFor(() => expect(api.searchFolders).toHaveBeenCalledWith("shop"), {
+ timeout: 2000,
+ });
+ // Results show their full path, since they can be anywhere on the machine.
+ expect(await screen.findByText("/archive/old-webshop")).toBeTruthy();
+ });
+
+ it("offers recent workspaces and replays their layout", async () => {
+ vi.mocked(api.fetchRecents).mockResolvedValue({
+ device_name: "Rubens MacBook",
+ recents: [
+ {
+ path: "/home/ruben/webshop",
+ name: "webshop",
+ terminals: 3,
+ agents: { claude: 2, codex: 1 },
+ last_used: 1,
+ exists: true,
+ },
+ ],
+ });
+ const onSelect = vi.fn();
+ const onSelectRecent = vi.fn();
+ render(
+ <FolderPicker selected={null} onSelect={onSelect} onSelectRecent={onSelectRecent} />,
+ );
+
+ const card = await screen.findByText("/home/ruben/webshop");
+ fireEvent.click(card);
+ expect(onSelect).toHaveBeenCalledWith("/home/ruben/webshop");
+ expect(onSelectRecent).toHaveBeenCalledWith(
+ expect.objectContaining({ terminals: 3, agents: { claude: 2, codex: 1 } }),
+ );
+ });
+
+ it("resolves a dropped folder through the backend", async () => {
+ vi.mocked(api.resolveDroppedFolder).mockResolvedValue({
+ resolved: "/home/ruben/webshop",
+ candidates: [],
+ detail: "",
+ });
+ const onSelect = vi.fn();
+ render(<FolderPicker selected={null} onSelect={onSelect} />);
+ await screen.findByText("webshop");
+
+ fireEvent.drop(screen.getByTestId("folder-drop-zone"), {
+ dataTransfer: dataTransfer({ uriList: "file:///home/ruben/webshop" }),
+ });
+
+ await waitFor(() =>
+ expect(api.resolveDroppedFolder).toHaveBeenCalledWith({
+ path: "file:///home/ruben/webshop",
+ }),
+ );
+ await waitFor(() => expect(onSelect).toHaveBeenCalledWith("/home/ruben/webshop"));
+ });
+
+ it("offers a choice when a dropped name matches several folders", async () => {
+ vi.mocked(api.resolveDroppedFolder).mockResolvedValue({
+ resolved: null,
+ candidates: [
+ { name: "webshop", path: "/a/webshop", is_project: true, is_repo: true },
+ { name: "webshop", path: "/b/webshop", is_project: true, is_repo: false },
+ ],
+ detail: 'Several folders are called "webshop" — pick the right one.',
+ });
+ render(<FolderPicker selected={null} onSelect={vi.fn()} />);
+ await screen.findByText("webshop");
+
+ fireEvent.drop(screen.getByTestId("folder-drop-zone"), {
+ dataTransfer: dataTransfer({ directoryName: "webshop" }),
+ });
+
+ expect(await screen.findByText(/pick the right one/i)).toBeTruthy();
+ expect(await screen.findByText("/a/webshop")).toBeTruthy();
+ });
+
+ it("says so plainly when a drop carried nothing usable", async () => {
+ render(<FolderPicker selected={null} onSelect={vi.fn()} />);
+ await screen.findByText("webshop");
+
+ fireEvent.drop(screen.getByTestId("folder-drop-zone"), {
+ dataTransfer: dataTransfer({}),
+ });
+
+ expect(await screen.findByText(/carried no folder/i)).toBeTruthy();
+ expect(api.resolveDroppedFolder).not.toHaveBeenCalled();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx
index 3151e3babc..cdb71cf5cf 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx
@@ -3,36 +3,123 @@
*
* A native folder dialog was not an option: the desktop app is a web UI, so a
* native picker would exist on one OS and be missing on the others — and on a
- * headless server there is no dialog at all. This browses over REST instead,
- * which behaves identically on Windows, macOS, Linux and a remote box, and it
- * keeps a plain path field for the case where the user already knows where they
- * are going (or is working on a machine with no start points worth listing).
+ * headless server there is no dialog at all. This browses over REST, which
+ * behaves identically on Windows, macOS, Linux and a remote box.
+ *
+ * Four ways to arrive at a folder, because people arrive differently:
+ *
+ * 1. **Recents** — the workspaces opened before, with their previous layout.
+ * One click and the wizard already knows how many terminals to open.
+ * 2. **Search** — type a name, get matches from anywhere under home and the
+ * usual code directories. Faster than clicking down five levels.
+ * 3. **Browsing** — the list, projects and repositories sorted first.
+ * 4. **Drag and drop** — drop a folder (or a file inside it) anywhere on the
+ * panel. See `extractDropPayload` for why this needs a backend round-trip.
+ *
+ * The start view is labelled with the machine's own name rather than the account
+ * folder: "Administrator" says nothing about which computer you are looking at,
+ * "Ruben's MacBook" does.
*/
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
- ChevronRight,
+ Clock,
CornerLeftUp,
Folder,
FolderGit2,
FolderOpen,
+ Laptop,
Loader2,
RefreshCw,
+ Search,
+ Terminal,
+ X,
} from "lucide-react";
import { cn } from "@/lib/utils";
-import { fetchFolders, type FolderItem } from "@/lib/agenticIdeApi";
+import {
+ fetchFolders,
+ fetchRecents,
+ forgetRecent,
+ resolveDroppedFolder,
+ searchFolders,
+ type FolderItem,
+ type RecentWorkspace,
+} from "@/lib/agenticIdeApi";
interface FolderPickerProps {
selected: string | null;
onSelect: (path: string) => void;
+ /** A recent workspace was picked — its previous layout can be replayed. */
+ onSelectRecent?: (recent: RecentWorkspace) => void;
}
-export function FolderPicker({ selected, onSelect }: FolderPickerProps) {
+/** Below this many characters the search stays a local filter of the open list. */
+const SEARCH_MIN = 2;
+const SEARCH_DEBOUNCE_MS = 250;
+
+/**
+ * Pull whatever identifies the dropped folder out of a DataTransfer.
+ *
+ * This MUST run synchronously inside the drop handler: a DataTransfer is
+ * emptied as soon as the event returns, so reading it after an `await` yields
+ * nothing. Three sources, in order of how much they tell us:
+ *
+ * 1. `text/uri-list` / `text/plain` — Explorer and Finder usually put the real
+ * path here, which resolves exactly.
+ * 2. `webkitGetAsEntry()` — gives the folder's NAME (never its path; that is a
+ * deliberate browser restriction), which the backend can search for.
+ * 3. `webkitRelativePath` of a dropped file — its first segment is the folder
+ * name, which covers dropping a file from inside the project.
+ */
+export function extractDropPayload(dt: DataTransfer | null): {
+ path?: string;
+ name?: string;
+} {
+ if (!dt) return {};
+ const out: { path?: string; name?: string } = {};
+
+ const uri = dt.getData("text/uri-list") || dt.getData("text/plain");
+ if (uri) {
+ const first = uri.split(/[\r\n]+/).find((line) => line.trim().length > 0);
+ if (first) out.path = first.trim();
+ }
+
+ const items = dt.items ? Array.from(dt.items) : [];
+ for (const item of items) {
+ const getAsEntry = (
+ item as DataTransferItem & { webkitGetAsEntry?: () => { isDirectory?: boolean; name?: string } | null }
+ ).webkitGetAsEntry;
+ const entry = typeof getAsEntry === "function" ? getAsEntry.call(item) : null;
+ if (entry?.isDirectory && entry.name) {
+ out.name = entry.name;
+ break;
+ }
+ }
+
+ if (!out.name && dt.files && dt.files.length > 0) {
+ const rel = (dt.files[0] as File & { webkitRelativePath?: string }).webkitRelativePath;
+ if (rel && rel.includes("/")) out.name = rel.split("/")[0];
+ }
+
+ return out;
+}
+
+export function FolderPicker({ selected, onSelect, onSelectRecent }: FolderPickerProps) {
const [path, setPath] = useState<string | null>(null);
const [parent, setParent] = useState<string | null>(null);
const [entries, setEntries] = useState<FolderItem[]>([]);
+ const [deviceName, setDeviceName] = useState<string>("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
- const [manual, setManual] = useState("");
+
+ const [query, setQuery] = useState("");
+ const [searchHits, setSearchHits] = useState<FolderItem[] | null>(null);
+ const [searching, setSearching] = useState(false);
+
+ const [recents, setRecents] = useState<RecentWorkspace[]>([]);
+ const [dragOver, setDragOver] = useState(false);
+ const [dropNote, setDropNote] = useState<string | null>(null);
+ const [dropChoices, setDropChoices] = useState<FolderItem[]>([]);
+ const dragDepth = useRef(0);
const load = useCallback(async (target: string | null) => {
setLoading(true);
@@ -42,6 +129,7 @@ export function FolderPicker({ selected, onSelect }: FolderPickerProps) {
setPath(res.path);
setParent(res.parent);
setEntries(res.entries);
+ if (res.device_name) setDeviceName(res.device_name);
if (res.error) setError(res.error);
} catch (e) {
setError((e as Error).message);
@@ -52,21 +140,207 @@ export function FolderPicker({ selected, onSelect }: FolderPickerProps) {
useEffect(() => {
void load(null);
+ void fetchRecents()
+ .then((res) => {
+ setRecents(res.recents);
+ if (res.device_name) setDeviceName(res.device_name);
+ })
+ .catch(() => {
+ /* no recents yet — the section just stays hidden */
+ });
}, [load]);
+ // Server-side search once the query is long enough; shorter input just filters
+ // the folder list already on screen, which feels instant.
+ useEffect(() => {
+ const trimmed = query.trim();
+ if (trimmed.length < SEARCH_MIN) {
+ setSearchHits(null);
+ setSearching(false);
+ return;
+ }
+ setSearching(true);
+ const handle = window.setTimeout(() => {
+ searchFolders(trimmed)
+ .then((res) => setSearchHits(res.entries))
+ .catch(() => setSearchHits([]))
+ .finally(() => setSearching(false));
+ }, SEARCH_DEBOUNCE_MS);
+ return () => window.clearTimeout(handle);
+ }, [query]);
+
+ const visible = useMemo(() => {
+ if (searchHits !== null) return searchHits;
+ const needle = query.trim().toLowerCase();
+ if (!needle) return entries;
+ return entries.filter((e) => e.name.toLowerCase().includes(needle));
+ }, [entries, query, searchHits]);
+
const open = (item: FolderItem) => {
onSelect(item.path);
+ setQuery("");
+ setSearchHits(null);
void load(item.path);
};
+ const usePath = (raw: string) => {
+ const value = raw.trim();
+ if (!value) return;
+ onSelect(value);
+ void load(value);
+ };
+
+ const pickRecent = (recent: RecentWorkspace) => {
+ onSelect(recent.path);
+ onSelectRecent?.(recent);
+ void load(recent.path);
+ };
+
+ // ------------------------------------------------------------ drag & drop
+ const onDrop = (event: React.DragEvent) => {
+ event.preventDefault();
+ dragDepth.current = 0;
+ setDragOver(false);
+ setDropChoices([]);
+ // Read the DataTransfer BEFORE awaiting anything (see extractDropPayload).
+ const payload = extractDropPayload(event.dataTransfer);
+ if (!payload.path && !payload.name) {
+ setDropNote("That drop carried no folder — browse to it or paste its path.");
+ return;
+ }
+ setDropNote("Resolving the dropped folder…");
+ void resolveDroppedFolder(payload)
+ .then((res) => {
+ if (res.resolved) {
+ setDropNote(res.detail || null);
+ onSelect(res.resolved);
+ void load(res.resolved);
+ } else {
+ setDropChoices(res.candidates);
+ setDropNote(res.detail || "Could not resolve that folder.");
+ }
+ })
+ .catch((e) => setDropNote((e as Error).message));
+ };
+
return (
- <div className="space-y-3">
+ <div
+ onDragEnter={(e) => {
+ e.preventDefault();
+ dragDepth.current += 1;
+ setDragOver(true);
+ }}
+ onDragOver={(e) => {
+ e.preventDefault();
+ e.dataTransfer.dropEffect = "copy";
+ }}
+ onDragLeave={(e) => {
+ e.preventDefault();
+ dragDepth.current = Math.max(0, dragDepth.current - 1);
+ if (dragDepth.current === 0) setDragOver(false);
+ }}
+ onDrop={onDrop}
+ data-testid="folder-drop-zone"
+ className={cn(
+ "relative space-y-4 rounded-xl transition-colors",
+ dragOver && "ring-2 ring-primary/60 ring-offset-2 ring-offset-background",
+ )}
+ >
+ {dragOver && (
+ <div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-xl bg-background/80">
+ <div className="flex items-center gap-2 rounded-lg border border-primary/50 bg-card px-4 py-3 text-sm font-medium text-primary">
+ <FolderOpen className="h-4 w-4" />
+ Drop a folder to open it here
+ </div>
+ </div>
+ )}
+
+ {/* ------------------------------------------------------------ recents */}
+ {recents.length > 0 && searchHits === null && (
+ <section className="space-y-2">
+ <h4 className="flex items-center gap-2 text-[11px] uppercase tracking-wider text-muted-foreground">
+ <Clock className="h-3.5 w-3.5" />
+ Recent workspaces
+ </h4>
+ <ul className="grid gap-2 sm:grid-cols-2">
+ {recents.map((recent) => (
+ <li key={recent.path} className="group relative">
+ <button
+ type="button"
+ onClick={() => pickRecent(recent)}
+ className={cn(
+ "flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left transition-colors",
+ selected === recent.path
+ ? "border-primary/50 bg-primary/5"
+ : "border-border bg-card/60 hover:border-primary/40",
+ )}
+ >
+ <FolderOpen className="h-4 w-4 shrink-0 text-primary/80" />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-sm font-medium">{recent.name}</span>
+ <span className="block truncate font-mono text-[10px] text-muted-foreground">
+ {recent.path}
+ </span>
+ </span>
+ <span className="flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground">
+ <Terminal className="h-3 w-3" />
+ {recent.terminals}
+ </span>
+ </button>
+ <button
+ type="button"
+ aria-label={`Forget ${recent.name}`}
+ title="Remove from this list (the folder itself stays)"
+ onClick={(e) => {
+ e.stopPropagation();
+ setRecents((prev) => prev.filter((r) => r.path !== recent.path));
+ void forgetRecent(recent.path).catch(() => {
+ /* list refreshes on next visit */
+ });
+ }}
+ className="absolute right-1 top-1 hidden rounded p-1 text-muted-foreground hover:text-foreground group-hover:block"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+
+ {/* ------------------------------------------------------------- search */}
<div className="flex flex-wrap items-center gap-2">
+ <div className="relative min-w-0 flex-1">
+ {searching ? (
+ <Loader2 className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 animate-spin text-muted-foreground" />
+ ) : (
+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
+ )}
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search folders by name…"
+ aria-label="Search folders by name"
+ data-testid="folder-search"
+ className="w-full rounded-lg border border-border bg-background/60 py-2 pl-9 pr-8 text-sm outline-none focus:border-primary/50"
+ spellCheck={false}
+ />
+ {query && (
+ <button
+ type="button"
+ aria-label="Clear search"
+ onClick={() => setQuery("")}
+ className="absolute right-2 top-1/2 -translate-y-1/2 rounded p-1 text-muted-foreground hover:text-foreground"
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ )}
+ </div>
<button
type="button"
className="btn-ghost"
onClick={() => void load(parent)}
- disabled={loading || (!parent && path === null)}
+ disabled={loading || searchHits !== null || (!parent && path === null)}
title="Go up one folder"
>
<CornerLeftUp className="h-4 w-4" />
@@ -85,19 +359,42 @@ export function FolderPicker({ selected, onSelect }: FolderPickerProps) {
<RefreshCw className="h-4 w-4" />
)}
</button>
- <code className="min-w-0 flex-1 truncate rounded-md bg-background/60 px-3 py-1.5 font-mono text-xs text-muted-foreground">
- {path ?? "This machine"}
- </code>
</div>
- <div className="max-h-[320px] overflow-y-auto scrollbar-jarvis rounded-xl border border-border bg-card/40">
- {entries.length === 0 && !loading ? (
+ {/* ---------------------------------------------------------- breadcrumb */}
+ <div className="flex items-center gap-2 text-xs text-muted-foreground">
+ {searchHits !== null ? (
+ <span>
+ {visible.length === 0 && !searching
+ ? `Nothing matches “${query.trim()}”`
+ : `Matches for “${query.trim()}”`}
+ </span>
+ ) : (
+ <>
+ <Laptop className="h-3.5 w-3.5 shrink-0 text-primary/70" />
+ <span className="shrink-0 font-medium text-foreground">
+ {deviceName || "This machine"}
+ </span>
+ {path && (
+ <code className="min-w-0 truncate rounded bg-background/60 px-2 py-0.5 font-mono">
+ {path}
+ </code>
+ )}
+ </>
+ )}
+ </div>
+
+ {/* --------------------------------------------------------------- list */}
+ <div className="max-h-[300px] overflow-y-auto scrollbar-jarvis rounded-xl border border-border bg-card/40">
+ {visible.length === 0 && !loading && !searching ? (
<p className="p-4 text-sm text-muted-foreground">
- Nothing to list here — type a path below instead.
+ {searchHits !== null
+ ? "No folder with that name was found."
+ : "Nothing to list here — search above, drop a folder, or paste a path below."}
</p>
) : (
<ul className="divide-y divide-border/50">
- {entries.map((item) => {
+ {visible.map((item) => {
const isSelected = selected === item.path;
return (
<li key={item.path}>
@@ -106,9 +403,7 @@ export function FolderPicker({ selected, onSelect }: FolderPickerProps) {
onClick={() => open(item)}
className={cn(
"flex w-full items-center gap-3 px-3 py-2 text-left text-sm transition-colors",
- isSelected
- ? "bg-primary/10 text-foreground"
- : "hover:bg-background/60",
+ isSelected ? "bg-primary/10 text-foreground" : "hover:bg-background/60",
)}
>
{item.is_repo ? (
@@ -118,13 +413,17 @@ export function FolderPicker({ selected, onSelect }: FolderPickerProps) {
) : (
<Folder className="h-4 w-4 shrink-0 text-muted-foreground" />
)}
- <span className="min-w-0 flex-1 truncate">{item.name}</span>
+ <span className="min-w-0 flex-1">
+ <span className="block truncate">{item.name}</span>
+ {searchHits !== null && (
+ <span className="block truncate font-mono text-[10px] text-muted-foreground">
+ {item.path}
+ </span>
+ )}
+ </span>
{item.is_repo && (
- <span className="chip shrink-0 text-[10px] uppercase tracking-wide">
- git
- </span>
+ <span className="chip shrink-0 text-[10px] uppercase tracking-wide">git</span>
)}
- <ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground/60" />
</button>
</li>
);
@@ -139,32 +438,35 @@ export function FolderPicker({ selected, onSelect }: FolderPickerProps) {
</p>
)}
- <div className="flex flex-wrap items-center gap-2">
- <input
- value={manual}
- onChange={(e) => setManual(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter" && manual.trim()) {
- onSelect(manual.trim());
- void load(manual.trim());
- }
- }}
- placeholder="…or paste a full folder path"
- className="min-w-0 flex-1 rounded-lg border border-border bg-background/60 px-3 py-2 font-mono text-xs outline-none focus:border-primary/50"
- spellCheck={false}
- />
- <button
- type="button"
- className="btn-ghost"
- disabled={!manual.trim()}
- onClick={() => {
- onSelect(manual.trim());
- void load(manual.trim());
- }}
- >
- Use this path
- </button>
- </div>
+ {/* --------------------------------------------------------- drop result */}
+ {dropNote && (
+ <div className="space-y-2 rounded-lg border border-border bg-card/60 px-3 py-2">
+ <p className="text-xs text-muted-foreground">{dropNote}</p>
+ {dropChoices.length > 0 && (
+ <ul className="space-y-1">
+ {dropChoices.map((choice) => (
+ <li key={choice.path}>
+ <button
+ type="button"
+ onClick={() => {
+ setDropNote(null);
+ setDropChoices([]);
+ open(choice);
+ }}
+ className="flex w-full items-center gap-2 rounded px-2 py-1 text-left text-xs hover:bg-background/60"
+ >
+ <FolderOpen className="h-3.5 w-3.5 shrink-0 text-primary/70" />
+ <code className="min-w-0 truncate font-mono">{choice.path}</code>
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+
+ {/* ----------------------------------------------------------- raw path */}
+ <PathInput onUse={usePath} />
{selected && (
<div className="flex items-center gap-2 rounded-lg border border-primary/40 bg-primary/5 px-3 py-2 text-sm">
@@ -178,3 +480,29 @@ export function FolderPicker({ selected, onSelect }: FolderPickerProps) {
</div>
);
}
+
+function PathInput({ onUse }: { onUse: (value: string) => void }) {
+ const [value, setValue] = useState("");
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && value.trim()) onUse(value);
+ }}
+ placeholder="…or paste a full folder path"
+ className="min-w-0 flex-1 rounded-lg border border-border bg-background/60 px-3 py-2 font-mono text-xs outline-none focus:border-primary/50"
+ spellCheck={false}
+ />
+ <button
+ type="button"
+ className="btn-ghost"
+ disabled={!value.trim()}
+ onClick={() => onUse(value)}
+ >
+ Use this path
+ </button>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index 3c6c3e444d..1bc55e90f0 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -29,6 +29,34 @@ export interface FoldersResponse {
parent: string | null;
entries: FolderItem[];
error?: string | null;
+ /** Human-facing name of this machine ("Ruben's MacBook"). */
+ device_name?: string | null;
+}
+
+export interface SearchResponse {
+ query: string;
+ entries: FolderItem[];
+ truncated: boolean;
+}
+
+export interface RecentWorkspace {
+ path: string;
+ name: string;
+ terminals: number;
+ agents: Record<string, number>;
+ last_used: number;
+ exists: boolean;
+}
+
+export interface RecentsResponse {
+ device_name: string;
+ recents: RecentWorkspace[];
+}
+
+export interface ResolveResponse {
+ resolved: string | null;
+ candidates: FolderItem[];
+ detail: string;
}
export interface ProjectProfile {
@@ -110,6 +138,44 @@ export function fetchFolders(path?: string | null): Promise<FoldersResponse> {
return getJson<FoldersResponse>(`/api/agentic-ide/folders${query}`);
}
+export function searchFolders(query: string, limit = 40): Promise<SearchResponse> {
+ const qs = new URLSearchParams({ q: query, limit: String(limit) });
+ return getJson<SearchResponse>(`/api/agentic-ide/folders/search?${qs.toString()}`);
+}
+
+export function fetchRecents(): Promise<RecentsResponse> {
+ return getJson<RecentsResponse>("/api/agentic-ide/recents");
+}
+
+export async function forgetRecent(path: string): Promise<void> {
+ const res = await fetch(
+ `/api/agentic-ide/recents?path=${encodeURIComponent(path)}`,
+ { method: "DELETE" },
+ );
+ if (!res.ok) throw new Error(await detail(res));
+}
+
+/**
+ * Turn a drag-and-drop payload into a folder path.
+ *
+ * The browser refuses to tell a web page where a dropped folder lives, so the
+ * caller sends whatever it could extract — a `file://` URI, a plain path, or
+ * just the folder name — and the backend resolves it (searching by name when
+ * that is all there is).
+ */
+export async function resolveDroppedFolder(payload: {
+ path?: string;
+ name?: string;
+}): Promise<ResolveResponse> {
+ const res = await fetch("/api/agentic-ide/folders/resolve", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ });
+ if (!res.ok) throw new Error(await detail(res));
+ return (await res.json()) as ResolveResponse;
+}
+
export async function startIdeSession(
folder: string,
terminals: TerminalPlan[],
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
index 707345776b..a1c352ba53 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.test.tsx
@@ -28,6 +28,10 @@ vi.mock("@/lib/agenticIdeApi", () => ({
fetchIdeState: vi.fn(),
fetchIdeAgents: vi.fn(),
fetchFolders: vi.fn(),
+ searchFolders: vi.fn(),
+ fetchRecents: vi.fn(),
+ forgetRecent: vi.fn(),
+ resolveDroppedFolder: vi.fn(),
startIdeSession: vi.fn(),
endIdeSession: vi.fn(),
setFocusMode: vi.fn(),
@@ -107,6 +111,16 @@ beforeEach(() => {
entries: [
{ name: "project", path: "/work/project", is_project: true, is_repo: true },
],
+ device_name: "Rubens MacBook",
+ });
+ vi.mocked(api.fetchRecents).mockResolvedValue({
+ device_name: "Rubens MacBook",
+ recents: [],
+ });
+ vi.mocked(api.searchFolders).mockResolvedValue({
+ query: "",
+ entries: [],
+ truncated: false,
});
});
diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
index be5c5a312f..b9500b1dea 100644
--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx
@@ -124,6 +124,33 @@ export function AgenticIdeView() {
setPlanned((prev) => buildPlan(n, prev, defaultAgent, suggested));
};
+ const replayRecent = (recent: {
+ path: string;
+ terminals: number;
+ agents: Record<string, number>;
+ }) => {
+ const total = Math.max(1, Math.min(recent.terminals, meta?.max_terminals ?? 12));
+ setCount(total);
+ const entries = Object.entries(recent.agents ?? {}).filter(([, n]) => n > 0);
+ if (entries.length === 0) {
+ setPlanned(buildPlan(total, [], defaultAgent, suggested));
+ return;
+ }
+ // Expand the remembered split back into one pane per terminal, grouped the
+ // way it was, then re-apply the call-sign pool in grid order.
+ const expanded: string[] = [];
+ for (const [agent, n] of entries) {
+ for (let i = 0; i < n && expanded.length < total; i += 1) expanded.push(agent);
+ }
+ while (expanded.length < total) expanded.push(defaultAgent);
+ setPlanned(
+ expanded.map((agent, index) => ({
+ agent,
+ name: suggested[index] ?? `T${index + 1}`,
+ })),
+ );
+ };
+
const goToStep = (next: Step) => {
// Entering the agent step is the moment the plan has to exist and the
// suggested call-signs have certainly arrived.
@@ -240,7 +267,11 @@ export function AgenticIdeView() {
title="Which folder should the agents work in?"
hint="Pick the project root. Everything the agents do happens inside it."
>
- <FolderPicker selected={folder} onSelect={setFolder} />
+ <FolderPicker
+ selected={folder}
+ onSelect={setFolder}
+ onSelectRecent={replayRecent}
+ />
</Section>
)}
diff --git a/tests/unit/agentic_ide/test_folders_search.py b/tests/unit/agentic_ide/test_folders_search.py
new file mode 100644
index 0000000000..79af3395c7
--- /dev/null
+++ b/tests/unit/agentic_ide/test_folders_search.py
@@ -0,0 +1,181 @@
+"""Folder search, device naming, and the recents store.
+
+These three make the wizard's first step usable: finding a folder by name
+instead of clicking down five levels, labelling the machine the way its owner
+named it, and getting back to yesterday's workspace in one click.
+"""
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import device, recents
+from jarvis.agentic_ide.folders import search_folders
+
+
+def tree(tmp_path: Path) -> Path:
+ """A small folder tree with a repo, a project, and noise to skip."""
+ (tmp_path / "work" / "webshop").mkdir(parents=True)
+ (tmp_path / "work" / "webshop" / ".git").mkdir()
+ (tmp_path / "work" / "webshop-docs").mkdir()
+ (tmp_path / "work" / "notes").mkdir()
+ (tmp_path / "archive" / "old-webshop").mkdir(parents=True)
+ (tmp_path / "archive" / "old-webshop" / "pyproject.toml").write_text("", encoding="utf-8")
+ # Must never be walked into or offered.
+ (tmp_path / "work" / "node_modules" / "webshop").mkdir(parents=True)
+ (tmp_path / "work" / ".hidden-webshop").mkdir()
+ return tmp_path
+
+
+# ------------------------------------------------------------------- search
+def test_search_finds_a_folder_by_partial_name(tree: Path) -> None:
+ names = [e.name for e in search_folders("webshop", roots=[tree])]
+ assert "webshop" in names
+ assert "webshop-docs" in names
+ assert "old-webshop" in names
+
+
+def test_exact_match_ranks_first(tree: Path) -> None:
+ hits = search_folders("webshop", roots=[tree])
+ assert hits[0].name == "webshop", [h.name for h in hits]
+
+
+def test_repos_rank_above_plain_folders_within_a_tier(tree: Path) -> None:
+ """Two folders both starting with the query: the repo should come first."""
+ hits = [h for h in search_folders("webshop", roots=[tree]) if h.name.startswith("webshop")]
+ assert hits[0].is_repo is True
+
+
+def test_search_skips_dependency_and_hidden_directories(tree: Path) -> None:
+ paths = [e.path for e in search_folders("webshop", roots=[tree])]
+ assert not any("node_modules" in p for p in paths)
+ assert not any(".hidden-webshop" in p for p in paths)
+
+
+def test_empty_query_returns_nothing(tree: Path) -> None:
+ assert search_folders(" ", roots=[tree]) == []
+
+
+def test_search_respects_the_limit(tree: Path) -> None:
+ assert len(search_folders("webshop", roots=[tree], limit=1)) == 1
+
+
+def test_depth_limit_stops_the_walk(tmp_path: Path) -> None:
+ # NB: not named "target" — that is a Rust build directory and therefore on
+ # the shared skip list, which would make this pass for the wrong reason.
+ deep = tmp_path / "a" / "b" / "c" / "d" / "e" / "f" / "buried"
+ deep.mkdir(parents=True)
+ assert search_folders("buried", roots=[tmp_path], max_depth=2) == []
+ assert [h.name for h in search_folders("buried", roots=[tmp_path], max_depth=8)] == ["buried"]
+
+
+def test_build_directories_are_never_offered(tmp_path: Path) -> None:
+ """A folder called "target" / "dist" / "build" is an artefact, not a project."""
+ for artefact in ("target", "dist", "build", "node_modules"):
+ (tmp_path / artefact).mkdir()
+ for artefact in ("target", "dist", "build", "node_modules"):
+ assert search_folders(artefact, roots=[tmp_path]) == [], artefact
+
+
+def test_unreadable_root_does_not_raise(tmp_path: Path) -> None:
+ assert search_folders("anything", roots=[tmp_path / "missing"]) == []
+
+
+# ------------------------------------------------------------- device name
+def test_device_name_is_never_empty() -> None:
+ device.reset_cache()
+ assert device.device_name().strip()
+
+
+def test_device_name_falls_back_to_the_hostname(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Every per-OS lookup failing must still yield something readable."""
+ device.reset_cache()
+ monkeypatch.setattr(device, "_run", lambda argv: None)
+ monkeypatch.setattr(device.platform, "node", lambda: "Rubens-MacBook-Pro.local")
+ monkeypatch.delenv("COMPUTERNAME", raising=False)
+ assert device.device_name() == "Rubens MacBook Pro"
+ device.reset_cache()
+
+
+def test_device_name_prefers_the_friendly_macos_name(monkeypatch: pytest.MonkeyPatch) -> None:
+ device.reset_cache()
+ monkeypatch.setattr(device.sys, "platform", "darwin")
+ monkeypatch.setattr(device, "_run", lambda argv: "Ruben’s MacBook")
+ assert device.device_name() == "Ruben’s MacBook"
+ device.reset_cache()
+
+
+# ----------------------------------------------------------------- recents
+def recents_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ store = tmp_path / "store" / "agentic_ide" / "recents.json"
+ monkeypatch.setattr(recents, "_store_path", lambda: store)
+ return store
+
+
+def test_remember_then_load_round_trips(recents_store: Path, tmp_path: Path) -> None:
+ project = tmp_path / "proj"
+ project.mkdir()
+ recents.remember(str(project), terminals=3, agents={"claude": 2, "codex": 1})
+ loaded = recents.load()
+ assert len(loaded) == 1
+ assert loaded[0].name == "proj"
+ assert loaded[0].terminals == 3
+ assert loaded[0].agents == {"claude": 2, "codex": 1}
+
+
+def test_reopening_moves_a_workspace_to_the_front(recents_store: Path, tmp_path: Path) -> None:
+ first, second = tmp_path / "one", tmp_path / "two"
+ first.mkdir()
+ second.mkdir()
+ recents.remember(str(first), terminals=1, agents={"claude": 1})
+ recents.remember(str(second), terminals=2, agents={"claude": 2})
+ recents.remember(str(first), terminals=4, agents={"codex": 4})
+ loaded = recents.load()
+ assert [r.name for r in loaded] == ["one", "two"]
+ assert loaded[0].terminals == 4, "the newest layout wins"
+
+
+def test_vanished_folders_disappear_from_the_list(recents_store: Path, tmp_path: Path) -> None:
+ gone = tmp_path / "deleted"
+ gone.mkdir()
+ recents.remember(str(gone), terminals=1, agents={"claude": 1})
+ gone.rmdir()
+ assert recents.load() == []
+
+
+def test_the_list_is_capped(recents_store: Path, tmp_path: Path) -> None:
+ for i in range(recents.MAX_RECENTS + 5):
+ folder = tmp_path / f"p{i}"
+ folder.mkdir()
+ recents.remember(str(folder), terminals=1, agents={"claude": 1})
+ assert len(recents.load()) == recents.MAX_RECENTS
+
+
+def test_a_corrupt_store_degrades_to_empty(recents_store: Path) -> None:
+ """A truncated or hand-edited file must not break the wizard."""
+ recents_store.parent.mkdir(parents=True, exist_ok=True)
+ recents_store.write_text("{not json at all", encoding="utf-8")
+ assert recents.load() == []
+
+
+def test_forget_removes_one_entry(recents_store: Path, tmp_path: Path) -> None:
+ keep, drop = tmp_path / "keep", tmp_path / "drop"
+ keep.mkdir()
+ drop.mkdir()
+ recents.remember(str(keep), terminals=1, agents={"claude": 1})
+ recents.remember(str(drop), terminals=1, agents={"claude": 1})
+ assert recents.forget(str(drop)) is True
+ assert [r.name for r in recents.load()] == ["keep"]
+ assert recents.forget(str(drop)) is False
+
+
+def test_the_store_is_valid_json_on_disk(recents_store: Path, tmp_path: Path) -> None:
+ project = tmp_path / "proj"
+ project.mkdir()
+ recents.remember(str(project), terminals=1, agents={"claude": 1})
+ payload = json.loads(recents_store.read_text(encoding="utf-8"))
+ assert isinstance(payload, list) and payload[0]["path"].endswith("proj")