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): pick a workspace with the system folder window

Ruben Lütke78540398471e
diff --git a/jarvis/agentic_ide/native_picker.py b/jarvis/agentic_ide/native_picker.py
new file mode 100644
index 0000000000..f39cab964e
--- /dev/null
+++ b/jarvis/agentic_ide/native_picker.py
@@ -0,0 +1,445 @@
+"""The operating system's own folder dialog, for picking a workspace.
+
+Browsing folders over REST works everywhere and stays the only option on a
+headless box, but on a real desktop it is the wrong tool for one specific job:
+finding a folder you know by sight rather than by name. The system dialog
+already has the sidebar, the search, the recent places and the muscle memory —
+rebuilding a worse copy of it inside a web page helps nobody.
+
+So both exist. The REST browser is the floor; this is the shortcut when the
+machine can actually show a window.
+
+**Every dialog runs in its own short-lived process.** Not an optimisation — a
+requirement, three times over:
+
+1. A window toolkit demands a thread state the web server does not have: a
+ single-threaded apartment on Windows, the main thread on macOS. A subprocess
+ gets to be both.
+2. A modal dialog blocks until someone answers it. In-process that would pin a
+ worker for as long as the user leaves it open.
+3. A wedged dialog must be *recoverable*, not merely bounded. A hung thread
+ cannot be cancelled in Python — killing a child process can (AP-24).
+
+**Availability is probed, never assumed from the platform.** ``sys.platform ==
+"linux"`` says nothing about whether a screen exists; a container, an SSH
+session and a VPS all report the same platform as a desktop. The probe asks for
+the two things that actually matter — a display and a program that can draw the
+dialog — and every OS without both degrades to an honest "not available here",
+which is what keeps the REST browser the advertised path.
+"""
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+
+from loguru import logger
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+# A dialog is a human interaction, so the ceiling is generous — it exists to
+# reap a dialog nobody is looking at any more, not to rush the user.
+DEFAULT_TIMEOUT_S = 300.0
+
+# The chosen path is printed between these, so a helper's own chatter (a shell
+# profile banner, a GTK warning on stdout, a PowerShell progress record) can
+# never be mistaken for an answer.
+_BEGIN = "<<<JARVIS-FOLDER>>>"
+_END = "<<<END-JARVIS-FOLDER>>>"
+
+
+@dataclass(frozen=True, slots=True)
+class PickerSupport:
+ """Whether this machine can show a folder dialog, and why not when it cannot."""
+
+ available: bool
+ backend: str | None = None
+ reason: str | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class PickResult:
+ """The outcome of one dialog. ``path`` is set only when a folder was chosen."""
+
+ path: str | None = None
+ cancelled: bool = False
+ error: str | None = None
+
+
+# --------------------------------------------------------------------------- #
+# Availability #
+# --------------------------------------------------------------------------- #
+def _has_display() -> bool:
+ """True when this session can put a window on a screen.
+
+ Windows and macOS carry their window server with the session, so the
+ question only has a meaningful answer on Linux and the other X11/Wayland
+ systems, where a headless server is the normal case rather than the
+ exception.
+ """
+ if sys.platform in {"win32", "darwin"}:
+ return True
+ return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))
+
+
+def _linux_helper() -> str | None:
+ """The dialog program to use, in order of how well it fits the desktop."""
+ for candidate in ("zenity", "kdialog", "qarma", "matedialog"):
+ if shutil.which(candidate):
+ return candidate
+ return None
+
+
+def _windows_shell() -> str | None:
+ """Windows PowerShell first: it is always present and always has WinForms."""
+ for candidate in ("powershell", "pwsh"):
+ if shutil.which(candidate):
+ return candidate
+ return None
+
+
+def support() -> PickerSupport:
+ """Can this machine show a native folder dialog right now?
+
+ Answered about the running session, not the platform — the same build of
+ Jarvis is expected to say "yes" on a desktop and "no" over SSH.
+ """
+ if not _has_display():
+ return PickerSupport(
+ available=False,
+ reason="This machine has no desktop session, so it cannot open a folder window.",
+ )
+ if sys.platform == "win32":
+ shell = _windows_shell()
+ if shell is None:
+ return PickerSupport(
+ available=False,
+ reason="PowerShell was not found, so no folder window can be opened.",
+ )
+ return PickerSupport(available=True, backend=shell)
+ if sys.platform == "darwin":
+ if shutil.which("osascript") is None:
+ return PickerSupport(
+ available=False,
+ reason="osascript was not found, so no folder window can be opened.",
+ )
+ return PickerSupport(available=True, backend="osascript")
+ helper = _linux_helper()
+ if helper is None:
+ return PickerSupport(
+ available=False,
+ reason=(
+ "No folder-dialog program is installed. Install zenity (GNOME) or "
+ "kdialog (KDE) to enable it — browsing here works either way."
+ ),
+ )
+ return PickerSupport(available=True, backend=helper)
+
+
+# --------------------------------------------------------------------------- #
+# The dialog itself #
+# --------------------------------------------------------------------------- #
+_PROMPT = "Choose the folder the agents should work in"
+
+# Written with placeholders rather than f-strings: these scripts are dense with
+# braces of their own, and doubling every one of them to survive `str.format`
+# would make them unreadable and easy to break.
+def _fill(script: str, **values: str) -> str:
+ out = script.replace("__BEGIN__", _BEGIN).replace("__END__", _END)
+ out = out.replace("__PROMPT__", _PROMPT)
+ for key, value in values.items():
+ out = out.replace(f"__{key.upper()}__", value)
+ return out
+
+
+# Windows has TWO folder dialogs and the difference matters here.
+#
+# `FolderBrowserDialog` — the one every PowerShell snippet reaches for — is the
+# small tree from Windows XP: no address bar, no search, no way to type or paste
+# a path, and no Quick Access. Windows PowerShell 5.1 runs on .NET Framework,
+# where that is the ONLY thing it can be; the modern version of that class ships
+# with .NET Core and never reached the Framework.
+#
+# The dialog people mean when they say "the Explorer window" is the Common Item
+# Dialog (`IFileOpenDialog` with the pick-folders option) — the same one Explorer
+# and every modern app use, with the sidebar, the address bar, search, and typed
+# paths. It is a COM interface, not a .NET class, so it is declared here and used
+# directly. That declaration is the fragile part (the method order IS the binary
+# contract), which is why the whole thing sits in a try/catch that falls back to
+# the old tree rather than failing: an outdated dialog still picks a folder.
+#
+# `-STA` is mandatory either way — the shell dialogs refuse to run in a
+# multi-threaded apartment — and the invisible topmost owner form exists only to
+# lend its z-order, because a dialog opened by a background process otherwise
+# appears behind every other window and looks like nothing happened.
+_WINDOWS_SCRIPT = r"""
+$ErrorActionPreference = 'Stop'
+[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
+Add-Type -AssemblyName System.Windows.Forms
+
+$owner = New-Object System.Windows.Forms.Form
+$owner.TopMost = $true
+$owner.ShowInTaskbar = $false
+$owner.Opacity = 0
+$owner.Show()
+$owner.Activate()
+$ownerHandle = $owner.Handle
+
+$start = $env:JARVIS_PICKER_START
+$picked = $null
+
+try {
+ Add-Type -TypeDefinition @'
+using System;
+using System.Runtime.InteropServices;
+
+public static class JarvisFolderPicker {
+ [ComImport, ClassInterface(ClassInterfaceType.None)]
+ [Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")]
+ private class FileOpenDialogRCW { }
+
+ [ComImport, Guid("42f85136-db7e-439c-85f1-e4075d135fc8")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IFileDialog {
+ [PreserveSig] int Show(IntPtr parent);
+ void SetFileTypes(uint cFileTypes, IntPtr rgFilterSpec);
+ void SetFileTypeIndex(uint iFileType);
+ void GetFileTypeIndex(out uint piFileType);
+ void Advise(IntPtr pfde, out uint pdwCookie);
+ void Unadvise(uint dwCookie);
+ void SetOptions(uint fos);
+ void GetOptions(out uint fos);
+ void SetDefaultFolder(IShellItem psi);
+ void SetFolder(IShellItem psi);
+ void GetFolder(out IShellItem ppsi);
+ void GetCurrentSelection(out IShellItem ppsi);
+ void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string pszName);
+ void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
+ void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
+ void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string pszText);
+ void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
+ void GetResult(out IShellItem ppsi);
+ void AddPlace(IShellItem psi, int alignment);
+ void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
+ void Close([MarshalAs(UnmanagedType.Error)] int hr);
+ void SetClientGuid(ref Guid guid);
+ void ClearClientData();
+ void SetFilter(IntPtr pFilter);
+ }
+
+ [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
+ private interface IShellItem {
+ void BindToHandler(IntPtr pbc, ref Guid bhid, ref Guid riid, out IntPtr ppv);
+ void GetParent(out IShellItem ppsi);
+ void GetDisplayName(uint sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
+ void GetAttributes(uint sfgaoMask, out uint psfgaoAttribs);
+ void Compare(IShellItem psi, uint hint, out int piOrder);
+ }
+
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
+ private static extern IShellItem SHCreateItemFromParsingName(
+ [MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid);
+
+ private const uint FOS_PICKFOLDERS = 0x00000020;
+ private const uint FOS_FORCEFILESYSTEM = 0x00000040;
+ private const uint FOS_PATHMUSTEXIST = 0x00000800;
+ private const uint SIGDN_FILESYSPATH = 0x80058000;
+
+ public static string Show(IntPtr owner, string startPath) {
+ IFileDialog dialog = (IFileDialog)new FileOpenDialogRCW();
+ dialog.SetOptions(FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
+ dialog.SetTitle("__PROMPT__");
+ dialog.SetOkButtonLabel("Use this folder");
+ if (!string.IsNullOrEmpty(startPath)) {
+ try {
+ Guid iid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE");
+ dialog.SetFolder(SHCreateItemFromParsingName(startPath, IntPtr.Zero, ref iid));
+ } catch { /* a start folder is a nicety, never a reason to fail */ }
+ }
+ if (dialog.Show(owner) != 0) return null; // cancelled
+ IShellItem result;
+ dialog.GetResult(out result);
+ string path;
+ result.GetDisplayName(SIGDN_FILESYSPATH, out path);
+ return path;
+ }
+}
+'@ -ErrorAction Stop
+ $picked = [JarvisFolderPicker]::Show($ownerHandle, $start)
+} catch {
+ # No Common Item Dialog available (very old Windows, blocked compiler):
+ # the XP-era tree still picks a folder, which beats no window at all.
+ $dialog = New-Object System.Windows.Forms.FolderBrowserDialog
+ $dialog.Description = '__PROMPT__'
+ $dialog.ShowNewFolderButton = $true
+ if ($start) { $dialog.SelectedPath = $start }
+ if ($dialog.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) {
+ $picked = $dialog.SelectedPath
+ }
+}
+
+$owner.Dispose()
+if ($picked) {
+ Write-Output '__BEGIN__'
+ Write-Output $picked
+ Write-Output '__END__'
+}
+"""
+
+# `choose folder` returns an alias; `POSIX path of` turns it into a real path.
+# Cancelling raises error -128, which is a normal answer here, not a failure.
+# `activate` brings the dialog forward — without it a dialog asked for by a
+# background process opens behind whatever the user is looking at.
+_MACOS_SCRIPT = r"""
+on run argv
+ set startPath to item 1 of argv
+ tell me to activate
+ try
+ if startPath is not "" then
+ set here to POSIX file startPath
+ set chosen to choose folder with prompt "__PROMPT__" default location here
+ else
+ set chosen to choose folder with prompt "__PROMPT__"
+ end if
+ on error number -128
+ return ""
+ end try
+ return "__BEGIN__" & linefeed & POSIX path of chosen & linefeed & "__END__"
+end run
+"""
+
+
+def _command(start: str | None, backend: str) -> tuple[list[str], dict[str, str]] | None:
+ """The argv (and any extra environment) that shows the dialog."""
+ env_extra: dict[str, str] = {}
+ if sys.platform == "win32":
+ if start:
+ env_extra["JARVIS_PICKER_START"] = start
+ return (
+ [
+ backend,
+ "-STA",
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ _fill(_WINDOWS_SCRIPT),
+ ],
+ env_extra,
+ )
+ if sys.platform == "darwin":
+ return ["osascript", "-e", _fill(_MACOS_SCRIPT), start or ""], env_extra
+ if backend in {"zenity", "qarma", "matedialog"}:
+ argv = [
+ backend,
+ "--file-selection",
+ "--directory",
+ f"--title={_PROMPT}",
+ ]
+ if start:
+ # zenity wants a trailing separator to treat the value as the folder
+ # to open rather than the entry to preselect inside its parent.
+ argv.append(f"--filename={start.rstrip('/')}/")
+ return argv, env_extra
+ if backend == "kdialog":
+ return [backend, "--getexistingdirectory", start or str(Path.home())], env_extra
+ return None
+
+
+def _extract(stdout: str) -> str | None:
+ """The path between the markers, or None when the dialog produced no answer."""
+ if _BEGIN not in stdout:
+ # kdialog and zenity have no scripting layer to add markers; they print
+ # the bare path and nothing else, so the whole output IS the answer.
+ cleaned = stdout.strip()
+ return cleaned or None
+ body = stdout.split(_BEGIN, 1)[1]
+ body = body.split(_END, 1)[0] if _END in body else body
+ cleaned = body.strip()
+ return cleaned or None
+
+
+def choose_folder(
+ *, start: str | None = None, timeout: float = DEFAULT_TIMEOUT_S
+) -> PickResult:
+ """Show the system folder dialog and return what the user picked.
+
+ Blocking — call it off the event loop. Cancelling is an ordinary outcome
+ (``cancelled=True``), not an error: the user changing their mind is the most
+ common way this ends.
+ """
+ probe = support()
+ if not probe.available or probe.backend is None:
+ return PickResult(error=probe.reason or "No folder window can be opened here.")
+
+ resolved_start: str | None = None
+ if start:
+ try:
+ candidate = Path(start).expanduser()
+ if candidate.is_dir():
+ resolved_start = str(candidate)
+ except OSError:
+ resolved_start = None
+
+ built = _command(resolved_start, probe.backend)
+ if built is None:
+ return PickResult(error="No folder window can be opened here.")
+ argv, env_extra = built
+
+ env = {**os.environ, **env_extra}
+ try:
+ completed = subprocess.run( # noqa: S603 - fixed argv, no shell
+ argv,
+ capture_output=True,
+ text=True,
+ # Explicit, because the answer is a PATH: Python would otherwise
+ # decode with the console codepage (cp1252/cp850 on Windows) and
+ # every folder with an umlaut in its name would come back mangled —
+ # or, as it did here, take the reader thread down with a decode
+ # error and look exactly like a cancelled dialog. Each helper is
+ # told to write UTF-8; `replace` keeps a stray byte from any of
+ # them a cosmetic problem rather than a crash.
+ encoding="utf-8",
+ errors="replace",
+ timeout=timeout,
+ env=env,
+ creationflags=NO_WINDOW_CREATIONFLAGS, # AP-1: no console flash
+ )
+ except subprocess.TimeoutExpired:
+ logger.info("Agentic IDE: the folder dialog was left open and timed out")
+ return PickResult(
+ error="The folder window was left open too long and was closed. Try again."
+ )
+ except OSError as exc:
+ logger.warning("Agentic IDE: could not open the folder dialog: {}", exc)
+ return PickResult(error=f"Could not open a folder window: {exc}")
+
+ chosen = _extract(completed.stdout or "")
+ if not chosen:
+ # Every helper signals "cancelled" with a non-zero exit and no path, so
+ # an empty answer is a cancellation unless the helper also complained.
+ stderr = (completed.stderr or "").strip()
+ if completed.returncode not in (0, 1) and stderr:
+ logger.warning("Agentic IDE: folder dialog failed: {}", stderr)
+ return PickResult(error="The folder window could not be opened.")
+ return PickResult(cancelled=True)
+
+ try:
+ picked = Path(chosen).expanduser()
+ if not picked.is_dir():
+ return PickResult(error=f"That is not a folder any more: {picked}")
+ except OSError as exc:
+ return PickResult(error=f"Could not read that folder: {exc}")
+ return PickResult(path=str(picked))
+
+
+__all__ = [
+ "DEFAULT_TIMEOUT_S",
+ "PickResult",
+ "PickerSupport",
+ "choose_folder",
+ "support",
+]
diff --git a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx
index 5810ced3bb..7a876d8e41 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx
@@ -7,9 +7,17 @@ vi.mock("@/lib/agenticIdeApi", () => ({
fetchRecents: vi.fn(),
forgetRecent: vi.fn(),
resolveDroppedFolder: vi.fn(),
+ fetchNativePickerSupport: vi.fn(),
+ openNativePicker: vi.fn(),
}));
-import { FolderPicker, extractDropPayload } from "./FolderPicker";
+import {
+ FolderPicker,
+ extractDropPayload,
+ joinPath,
+ separatorOf,
+ splitTypedPath,
+} from "./FolderPicker";
import * as api from "@/lib/agenticIdeApi";
const LISTING = {
@@ -33,6 +41,10 @@ beforeEach(() => {
entries: [],
truncated: false,
});
+ // The default is "this machine cannot show a folder window", which is what a
+ // headless install and a remote browser both report — so every existing test
+ // keeps asserting against the path that must work everywhere.
+ vi.mocked(api.fetchNativePickerSupport).mockResolvedValue({ available: false });
});
afterEach(() => {
@@ -222,3 +234,159 @@ describe("FolderPicker", () => {
expect(api.resolveDroppedFolder).not.toHaveBeenCalled();
});
});
+
+describe("the system folder window", () => {
+ it("is not offered where the machine cannot show one", async () => {
+ // The default from the shared setup: a headless server, or a browser on a
+ // different machine than the backend. Offering a button that cannot work
+ // is worse than not offering one.
+ render(<FolderPicker selected={null} onSelect={vi.fn()} />);
+ await screen.findByText("webshop");
+ expect(screen.queryByTestId("native-browse")).toBeNull();
+ });
+
+ it("hands the chosen folder straight to the wizard", async () => {
+ vi.mocked(api.fetchNativePickerSupport).mockResolvedValue({
+ available: true,
+ backend: "powershell",
+ });
+ vi.mocked(api.openNativePicker).mockResolvedValue({ path: "C:\\work\\shop" });
+ const onSelect = vi.fn();
+ render(<FolderPicker selected={null} onSelect={onSelect} />);
+
+ fireEvent.click(await screen.findByTestId("native-browse"));
+
+ await waitFor(() => expect(onSelect).toHaveBeenCalledWith("C:\\work\\shop"));
+ // And the in-page browser follows it there, so both views agree.
+ expect(api.fetchFolders).toHaveBeenCalledWith("C:\\work\\shop");
+ });
+
+ it("says a window is waiting, because it can open behind the app", async () => {
+ vi.mocked(api.fetchNativePickerSupport).mockResolvedValue({ available: true });
+ let release: (value: { path: string }) => void = () => {};
+ vi.mocked(api.openNativePicker).mockReturnValue(
+ new Promise((resolve) => {
+ release = resolve;
+ }),
+ );
+ render(<FolderPicker selected={null} onSelect={vi.fn()} />);
+
+ fireEvent.click(await screen.findByTestId("native-browse"));
+
+ expect(await screen.findByText(/folder window is open/i)).toBeTruthy();
+ release({ path: "/home/ruben/webshop" });
+ });
+
+ it("changes nothing when the window is closed without choosing", async () => {
+ vi.mocked(api.fetchNativePickerSupport).mockResolvedValue({ available: true });
+ vi.mocked(api.openNativePicker).mockResolvedValue({ cancelled: true });
+ const onSelect = vi.fn();
+ render(<FolderPicker selected="/already/here" onSelect={onSelect} />);
+
+ fireEvent.click(await screen.findByTestId("native-browse"));
+
+ await waitFor(() => expect(api.openNativePicker).toHaveBeenCalled());
+ expect(onSelect).not.toHaveBeenCalled();
+ // Cancelling is a decision, not a failure — nothing is reported.
+ expect(screen.queryByRole("alert")).toBeNull();
+ });
+
+ it("opens the window at the folder already in view", async () => {
+ vi.mocked(api.fetchNativePickerSupport).mockResolvedValue({ available: true });
+ vi.mocked(api.openNativePicker).mockResolvedValue({ cancelled: true });
+ render(<FolderPicker selected="/home/ruben/webshop" onSelect={vi.fn()} />);
+
+ fireEvent.click(await screen.findByTestId("native-browse"));
+
+ await waitFor(() =>
+ expect(api.openNativePicker).toHaveBeenCalledWith("/home/ruben/webshop"),
+ );
+ });
+});
+
+describe("typing a path", () => {
+ it("splits what was typed into a folder and what to match", () => {
+ expect(splitTypedPath("/home/ruben/web")).toEqual({
+ dir: "/home/ruben/",
+ leaf: "web",
+ });
+ expect(splitTypedPath("C:\\work\\sh")).toEqual({ dir: "C:\\work\\", leaf: "sh" });
+ // A bare name has no folder part — that is what makes `cd notes` work.
+ expect(splitTypedPath("notes")).toEqual({ dir: "", leaf: "notes" });
+ });
+
+ it("reads the separator off a real path instead of guessing", () => {
+ // The UI may well be open on a different machine than the backend, so
+ // asking the browser which OS this is would answer about the wrong one.
+ expect(separatorOf("C:\\work\\shop")).toBe("\\");
+ expect(separatorOf("/home/ruben")).toBe("/");
+ expect(joinPath("C:\\work", "shop")).toBe("C:\\work\\shop");
+ expect(joinPath("/home/ruben/", "webshop")).toBe("/home/ruben/webshop");
+ });
+
+ it("completes against the folder on screen, the way cd does", async () => {
+ vi.mocked(api.fetchFolders).mockResolvedValue({
+ ...LISTING,
+ path: "/home/ruben",
+ parent: "/home",
+ });
+ render(<FolderPicker selected={null} onSelect={vi.fn()} />);
+ await screen.findByText("webshop");
+
+ fireEvent.change(screen.getByTestId("folder-path-input"), {
+ target: { value: "web" },
+ });
+
+ const list = await screen.findByTestId("path-suggestions");
+ await waitFor(() => expect(list.textContent).toContain("webshop"));
+ // Only what matches: `notes` does not start with "web".
+ expect(list.textContent).not.toContain("notes");
+ });
+
+ it("Tab completes and leaves the next segment ready to type", async () => {
+ vi.mocked(api.fetchFolders).mockResolvedValue({
+ ...LISTING,
+ path: "/home/ruben",
+ parent: "/home",
+ });
+ render(<FolderPicker selected={null} onSelect={vi.fn()} />);
+ await screen.findByText("webshop");
+
+ const input = screen.getByTestId("folder-path-input") as HTMLInputElement;
+ fireEvent.change(input, { target: { value: "web" } });
+ await screen.findByTestId("path-suggestions");
+ fireEvent.keyDown(input, { key: "Tab" });
+
+ // The trailing separator is the point: typing continues into the folder.
+ await waitFor(() => expect(input.value).toBe("/home/ruben/webshop/"));
+ });
+
+ it("treats a bare name as relative to the folder on screen", async () => {
+ vi.mocked(api.fetchFolders).mockResolvedValue({
+ ...LISTING,
+ path: "/home/ruben",
+ parent: "/home",
+ });
+ const onSelect = vi.fn();
+ render(<FolderPicker selected={null} onSelect={onSelect} />);
+ await screen.findByText("webshop");
+
+ const input = screen.getByTestId("folder-path-input");
+ fireEvent.change(input, { target: { value: "notes" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ await waitFor(() => expect(onSelect).toHaveBeenCalledWith("/home/ruben/notes"));
+ });
+
+ it("uses a full path exactly as typed", async () => {
+ const onSelect = vi.fn();
+ render(<FolderPicker selected={null} onSelect={onSelect} />);
+ await screen.findByText("webshop");
+
+ const input = screen.getByTestId("folder-path-input");
+ fireEvent.change(input, { target: { value: "/srv/deploy" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ await waitFor(() => expect(onSelect).toHaveBeenCalledWith("/srv/deploy"));
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx
index 4b174ac95e..97936ecebf 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx
@@ -1,21 +1,25 @@
/**
* Folder picker for step 1 of the Agentic-IDE wizard.
*
- * 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, which
- * behaves identically on Windows, macOS, Linux and a remote box.
+ * Five ways to arrive at a folder, because people arrive differently:
*
- * Four ways to arrive at a folder, because people arrive differently:
- *
- * 1. **Recents** — the workspaces opened before, with their previous layout.
+ * 1. **The system folder window** — Explorer on Windows, Finder on macOS, the
+ * desktop's own dialog on Linux. The one people already know. Offered only
+ * when the backend confirms this machine can actually show it (see below).
+ * 2. **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
+ * 3. **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
+ * 4. **Browsing** — the list, projects and repositories sorted first.
+ * 5. **Typing a path** — with completion, the way `cd` works in a terminal.
+ * 6. **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 in-page browser is not a fallback for the system window, it is the floor:
+ * the system window opens on the machine the BACKEND runs on, so it is useless
+ * over a network and absent on a headless server. Everything here therefore
+ * works without it, and the button appears only where it can deliver.
+ *
* 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.
@@ -37,11 +41,14 @@ import {
import { cn } from "@/lib/utils";
import {
fetchFolders,
+ fetchNativePickerSupport,
fetchRecents,
forgetRecent,
+ openNativePicker,
resolveDroppedFolder,
searchFolders,
type FolderItem,
+ type NativePickerSupport,
type RecentWorkspace,
} from "@/lib/agenticIdeApi";
@@ -121,6 +128,10 @@ export function FolderPicker({ selected, onSelect, onSelectRecent }: FolderPicke
const [dropChoices, setDropChoices] = useState<FolderItem[]>([]);
const dragDepth = useRef(0);
+ const [nativePicker, setNativePicker] = useState<NativePickerSupport | null>(null);
+ const [nativeOpen, setNativeOpen] = useState(false);
+ const [nativeNote, setNativeNote] = useState<string | null>(null);
+
const load = useCallback(async (target: string | null) => {
setLoading(true);
setError(null);
@@ -148,8 +159,44 @@ export function FolderPicker({ selected, onSelect, onSelectRecent }: FolderPicke
.catch(() => {
/* no recents yet — the section just stays hidden */
});
+ void fetchNativePickerSupport()
+ .then(setNativePicker)
+ .catch(() => {
+ // An older backend has no such route. Treat that as "not available"
+ // rather than showing a button that would 404 on click.
+ setNativePicker({ available: false });
+ });
}, [load]);
+ /**
+ * Hand over to the operating system's own folder window.
+ *
+ * The request stays open for as long as the window does — a person deciding
+ * where their project lives is not a slow response — so the button reports
+ * that a window is waiting for them. Without it a dialog that opened behind
+ * the app window looks exactly like a button that did nothing.
+ */
+ const browseNatively = () => {
+ if (nativeOpen) return;
+ setNativeOpen(true);
+ setNativeNote(null);
+ void openNativePicker(selected ?? path)
+ .then((res) => {
+ if (res.path) {
+ onSelect(res.path);
+ setQuery("");
+ setSearchHits(null);
+ void load(res.path);
+ } else if (res.error) {
+ setNativeNote(res.error);
+ }
+ // A cancelled dialog says nothing: the user closed it on purpose and
+ // whatever was selected before is still selected.
+ })
+ .catch((e) => setNativeNote((e as Error).message))
+ .finally(() => setNativeOpen(false));
+ };
+
// Server-side search once the query is long enough; shorter input just filters
// the folder list already on screen, which feels instant.
useEffect(() => {
@@ -339,6 +386,23 @@ export function FolderPicker({ selected, onSelect, onSelectRecent }: FolderPicke
</button>
)}
</div>
+ {nativePicker?.available && (
+ <button
+ type="button"
+ className="btn-primary"
+ onClick={browseNatively}
+ disabled={nativeOpen}
+ data-testid="native-browse"
+ title="Open the folder window this computer normally uses"
+ >
+ {nativeOpen ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <FolderOpen className="h-4 w-4" />
+ )}
+ {nativeOpen ? "Waiting for the window…" : "Browse…"}
+ </button>
+ )}
<button
type="button"
className="btn-ghost"
@@ -364,6 +428,21 @@ export function FolderPicker({ selected, onSelect, onSelectRecent }: FolderPicke
</button>
</div>
+ {/* The window can still end up behind the app despite being opened
+ topmost — a user who does not know it is there just sees a button
+ that hung. Saying so costs one line and saves the confusion. */}
+ {nativeOpen && (
+ <p className="text-xs text-primary" role="status">
+ A folder window is open — pick a folder there. If you cannot see it,
+ check behind this window or on your taskbar.
+ </p>
+ )}
+ {nativeNote && !nativeOpen && (
+ <p className="text-xs text-muted-foreground" role="alert">
+ {nativeNote}
+ </p>
+ )}
+
{/* ---------------------------------------------------------- breadcrumb */}
<div className="flex items-center gap-2 text-xs text-muted-foreground">
{searchHits !== null ? (
@@ -469,7 +548,7 @@ export function FolderPicker({ selected, onSelect, onSelectRecent }: FolderPicke
)}
{/* ----------------------------------------------------------- raw path */}
- <PathInput onUse={usePath} />
+ <PathInput base={path} 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">
@@ -484,28 +563,185 @@ export function FolderPicker({ selected, onSelect, onSelectRecent }: FolderPicke
);
}
-function PathInput({ onUse }: { onUse: (value: string) => void }) {
+/** Where the typed text stops being a folder and starts being what to match. */
+export function splitTypedPath(value: string): { dir: string; leaf: string } {
+ const cut = Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"));
+ if (cut < 0) return { dir: "", leaf: value };
+ return { dir: value.slice(0, cut + 1), leaf: value.slice(cut + 1) };
+}
+
+/**
+ * The separator this machine uses, read off a real path instead of guessed.
+ *
+ * A web page cannot know whether the backend is Windows or not, and guessing
+ * from `navigator` would describe the wrong computer entirely when the UI is
+ * open on a different one. Every path the backend hands out already contains
+ * the answer.
+ */
+export function separatorOf(fullPath: string): string {
+ return fullPath.includes("\\") ? "\\" : "/";
+}
+
+export function joinPath(base: string, name: string): string {
+ const sep = separatorOf(base);
+ return base.endsWith(sep) ? `${base}${name}` : `${base}${sep}${name}`;
+}
+
+/**
+ * A path field that completes as you type, the way `cd` does in a terminal.
+ *
+ * Typing a bare name completes against the folder currently on screen, so
+ * `cd`-style navigation works without ever writing an absolute path; Tab takes
+ * the highlighted suggestion and appends a separator so the next segment can be
+ * typed straight away. Arrow keys move through the list, Enter opens what is
+ * highlighted — or, with nothing highlighted, whatever was typed.
+ *
+ * Completion is deliberately a plain folder listing rather than the name search
+ * above it: `cd` shows what is in THIS folder, and a field that answered with
+ * matches from across the disk would be a different tool wearing the same shape.
+ */
+function PathInput({ base, onUse }: { base: string | null; onUse: (value: string) => void }) {
const [value, setValue] = useState("");
+ const [options, setOptions] = useState<FolderItem[]>([]);
+ const [active, setActive] = useState(-1);
+ const [open, setOpen] = useState(false);
+
+ const { dir, leaf } = splitTypedPath(value);
+ // An empty `dir` means a bare name was typed: complete inside the folder the
+ // list is showing, which is what makes `cd projects` work.
+ const lookupDir = dir || base || "";
+
+ useEffect(() => {
+ if (!value.trim() && !base) {
+ setOptions([]);
+ return;
+ }
+ let cancelled = false;
+ const handle = window.setTimeout(() => {
+ fetchFolders(lookupDir || null)
+ .then((res) => {
+ if (cancelled) return;
+ const needle = leaf.toLowerCase();
+ setOptions(
+ res.entries.filter((e) => !needle || e.name.toLowerCase().startsWith(needle)),
+ );
+ setActive(-1);
+ })
+ .catch(() => {
+ if (!cancelled) setOptions([]);
+ });
+ }, 160);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(handle);
+ };
+ }, [lookupDir, leaf, value, base]);
+
+ /** Take a suggestion and leave the cursor ready for the next segment. */
+ const complete = (item: FolderItem) => {
+ setValue(`${item.path}${separatorOf(item.path)}`);
+ setActive(-1);
+ setOpen(true);
+ };
+
+ const submit = () => {
+ if (active >= 0 && options[active]) {
+ onUse(options[active].path);
+ } else if (value.trim()) {
+ // A bare name is relative to what is on screen, exactly as typed.
+ const typed = value.trim();
+ const absolute = dir || !base ? typed : joinPath(base, typed);
+ onUse(absolute);
+ }
+ setOpen(false);
+ };
+
+ const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === "Tab" && options.length > 0) {
+ e.preventDefault();
+ complete(options[active >= 0 ? active : 0]);
+ return;
+ }
+ if (e.key === "ArrowDown" && options.length > 0) {
+ e.preventDefault();
+ setOpen(true);
+ setActive((prev) => (prev + 1) % options.length);
+ return;
+ }
+ if (e.key === "ArrowUp" && options.length > 0) {
+ e.preventDefault();
+ setOpen(true);
+ setActive((prev) => (prev <= 0 ? options.length - 1 : prev - 1));
+ return;
+ }
+ if (e.key === "Enter") {
+ e.preventDefault();
+ submit();
+ return;
+ }
+ if (e.key === "Escape") setOpen(false);
+ };
+
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 className="space-y-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="relative min-w-0 flex-1">
+ <input
+ value={value}
+ onChange={(e) => {
+ setValue(e.target.value);
+ setOpen(true);
+ }}
+ onKeyDown={onKeyDown}
+ onFocus={() => setOpen(true)}
+ // Closing on blur is delayed: a click on a suggestion blurs the
+ // input first, and an immediate close would remove the element
+ // under the pointer before the click lands on it.
+ onBlur={() => window.setTimeout(() => setOpen(false), 150)}
+ placeholder="…or type a path — Tab completes, like cd"
+ aria-label="Folder path"
+ data-testid="folder-path-input"
+ className="w-full rounded-lg border border-border bg-background/60 px-3 py-2 font-mono text-xs outline-none focus:border-primary/50"
+ spellCheck={false}
+ autoComplete="off"
+ />
+ {open && options.length > 0 && (
+ <ul
+ data-testid="path-suggestions"
+ className="absolute bottom-full z-20 mb-1 max-h-48 w-full overflow-y-auto scrollbar-jarvis rounded-lg border border-border bg-card shadow-lg"
+ >
+ {options.slice(0, 40).map((item, index) => (
+ <li key={item.path}>
+ <button
+ type="button"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => complete(item)}
+ className={cn(
+ "flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs",
+ index === active ? "bg-primary/15" : "hover:bg-background/60",
+ )}
+ >
+ {item.is_repo ? (
+ <FolderGit2 className="h-3.5 w-3.5 shrink-0 text-primary" />
+ ) : (
+ <Folder className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ )}
+ <span className="truncate font-mono">{item.name}</span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ <button
+ type="button"
+ className="btn-ghost"
+ disabled={!value.trim()}
+ onClick={submit}
+ >
+ Use this path
+ </button>
+ </div>
</div>
);
}
diff --git a/tests/unit/agentic_ide/test_native_picker.py b/tests/unit/agentic_ide/test_native_picker.py
new file mode 100644
index 0000000000..fb32b319aa
--- /dev/null
+++ b/tests/unit/agentic_ide/test_native_picker.py
@@ -0,0 +1,255 @@
+"""The system folder window: offered where it works, silent where it does not.
+
+Two things must hold on every machine, and the second one is the reason this
+feature is allowed to exist at all:
+
+* Where a desktop is present, the window opens and the chosen folder comes back
+ intact — including folders whose names carry accents, which is where the
+ first version broke.
+* Where one is not (a headless VPS, an SSH session, a container), the feature
+ reports itself unavailable in plain language and the REST browser stays the
+ whole story. It never raises, never blocks, and never offers a button that
+ cannot deliver.
+"""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import native_picker
+
+
+class _Completed:
+ """Stand-in for a finished helper process."""
+
+ def __init__(self, stdout: str = "", stderr: str = "", returncode: int = 0) -> None:
+ self.stdout = stdout
+ self.stderr = stderr
+ self.returncode = returncode
+
+
+def _marked(path: str) -> str:
+ return f"noise before\n{native_picker._BEGIN}\n{path}\n{native_picker._END}\ntrailing\n"
+
+
+# --------------------------------------------------------------------------- #
+# Availability #
+# --------------------------------------------------------------------------- #
+def test_a_headless_linux_box_says_so_in_plain_language(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.delenv("DISPLAY", raising=False)
+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)
+
+ probe = native_picker.support()
+
+ assert probe.available is False
+ assert probe.backend is None
+ assert probe.reason and "desktop session" in probe.reason
+
+
+def test_a_linux_desktop_without_a_dialog_program_names_the_fix(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setenv("DISPLAY", ":0")
+ monkeypatch.setattr(native_picker.shutil, "which", lambda _name: None)
+
+ probe = native_picker.support()
+
+ assert probe.available is False
+ # A dead end is not an answer: the message says what to install.
+ assert probe.reason and "zenity" in probe.reason
+
+
+def test_a_linux_desktop_with_zenity_is_available(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-0")
+ monkeypatch.setattr(
+ native_picker.shutil, "which", lambda name: "/usr/bin/zenity" if name == "zenity" else None
+ )
+
+ assert native_picker.support() == native_picker.PickerSupport(available=True, backend="zenity")
+
+
+def test_choosing_on_a_headless_box_fails_without_running_anything(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.delenv("DISPLAY", raising=False)
+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)
+
+ def _explode(*_args: object, **_kwargs: object) -> None:
+ raise AssertionError("no helper process may be started without a display")
+
+ monkeypatch.setattr(native_picker.subprocess, "run", _explode)
+
+ result = native_picker.choose_folder()
+
+ assert result.path is None
+ assert result.error
+
+
+# --------------------------------------------------------------------------- #
+# The answer #
+# --------------------------------------------------------------------------- #
+def test_the_chosen_folder_comes_back(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ native_picker, "support", lambda: native_picker.PickerSupport(True, "zenity")
+ )
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(
+ native_picker.subprocess, "run", lambda *_a, **_k: _Completed(stdout=str(tmp_path))
+ )
+
+ assert native_picker.choose_folder().path == str(tmp_path)
+
+
+def test_a_folder_name_with_accents_survives(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The first version decoded the helper's output with the console codepage
+ and took its own reader thread down on the first accented character. Most of
+ the world names folders in something other than plain ASCII, so this is an
+ ordinary folder, not an edge case.
+
+ Written as escapes so the assertion is about ENCODING rather than about any
+ one language, and so this file stays plain ASCII on disk.
+ """
+ folder = tmp_path / "\u00c5ngstr\u00f6m caf\u00e9 \u00f1o\u00f1o"
+ folder.mkdir()
+ monkeypatch.setattr(
+ native_picker, "support", lambda: native_picker.PickerSupport(True, "powershell")
+ )
+ monkeypatch.setattr(sys, "platform", "win32")
+
+ seen: dict[str, object] = {}
+
+ def _run(*_args: object, **kwargs: object) -> _Completed:
+ seen.update(kwargs)
+ return _Completed(stdout=_marked(str(folder)))
+
+ monkeypatch.setattr(native_picker.subprocess, "run", _run)
+
+ assert native_picker.choose_folder().path == str(folder)
+ # The decoding is pinned, not inherited from whatever locale the app booted in.
+ assert seen["encoding"] == "utf-8"
+
+
+def test_the_helpers_own_chatter_is_not_mistaken_for_an_answer(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ native_picker, "support", lambda: native_picker.PickerSupport(True, "powershell")
+ )
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(
+ native_picker.subprocess,
+ "run",
+ lambda *_a, **_k: _Completed(stdout=f"Gtk-WARNING: something\n{_marked(str(tmp_path))}"),
+ )
+
+ assert native_picker.choose_folder().path == str(tmp_path)
+
+
+def test_cancelling_is_an_outcome_not_an_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ native_picker, "support", lambda: native_picker.PickerSupport(True, "zenity")
+ )
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(native_picker.subprocess, "run", lambda *_a, **_k: _Completed(returncode=1))
+
+ result = native_picker.choose_folder()
+
+ assert result.cancelled is True
+ assert result.error is None
+ assert result.path is None
+
+
+def test_a_window_left_open_is_closed_and_reported(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A dialog nobody answers must be recoverable, not merely bounded — which
+ is the whole reason it runs as a separate process (AP-24)."""
+ monkeypatch.setattr(
+ native_picker, "support", lambda: native_picker.PickerSupport(True, "zenity")
+ )
+ monkeypatch.setattr(sys, "platform", "linux")
+
+ def _timeout(*_a: object, **_k: object) -> None:
+ raise subprocess.TimeoutExpired(cmd="zenity", timeout=1)
+
+ monkeypatch.setattr(native_picker.subprocess, "run", _timeout)
+
+ result = native_picker.choose_folder(timeout=1)
+
+ assert result.path is None
+ assert result.error and "too long" in result.error
+
+
+def test_a_folder_deleted_while_the_window_was_open_is_reported(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ native_picker, "support", lambda: native_picker.PickerSupport(True, "zenity")
+ )
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(
+ native_picker.subprocess,
+ "run",
+ lambda *_a, **_k: _Completed(stdout=str(tmp_path / "gone")),
+ )
+
+ result = native_picker.choose_folder()
+
+ assert result.path is None
+ assert result.error and "not a folder" in result.error
+
+
+def test_a_missing_helper_never_raises(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ native_picker, "support", lambda: native_picker.PickerSupport(True, "zenity")
+ )
+ monkeypatch.setattr(sys, "platform", "linux")
+
+ def _missing(*_a: object, **_k: object) -> None:
+ raise OSError("zenity vanished")
+
+ monkeypatch.setattr(native_picker.subprocess, "run", _missing)
+
+ assert native_picker.choose_folder().error
+
+
+# --------------------------------------------------------------------------- #
+# The command #
+# --------------------------------------------------------------------------- #
+def test_the_start_folder_is_dropped_when_it_no_longer_exists(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A stale start folder must not stop the window from opening."""
+ monkeypatch.setattr(
+ native_picker, "support", lambda: native_picker.PickerSupport(True, "kdialog")
+ )
+ monkeypatch.setattr(sys, "platform", "linux")
+ seen: list[list[str]] = []
+
+ def _run(argv: list[str], **_k: object) -> _Completed:
+ seen.append(argv)
+ return _Completed(stdout=str(tmp_path))
+
+ monkeypatch.setattr(native_picker.subprocess, "run", _run)
+ native_picker.choose_folder(start=str(tmp_path / "deleted-yesterday"))
+
+ assert seen and str(tmp_path / "deleted-yesterday") not in seen[0]
+
+
+def test_the_windows_command_runs_in_a_single_threaded_apartment() -> None:
+ """`-STA` is not optional: the shell dialogs refuse to run without it."""
+ if sys.platform != "win32":
+ pytest.skip("the Windows command is only built on Windows")
+ argv, _env = native_picker._command(None, "powershell")
+ assert "-STA" in argv
+ assert "-NoProfile" in argv
diff --git a/tests/unit/web/test_agentic_ide_native_picker_routes.py b/tests/unit/web/test_agentic_ide_native_picker_routes.py
new file mode 100644
index 0000000000..50147f55fa
--- /dev/null
+++ b/tests/unit/web/test_agentic_ide_native_picker_routes.py
@@ -0,0 +1,111 @@
+"""The system folder window opens where the SERVER runs — so only locally.
+
+Anyone reaching the UI from a phone, a second laptop, or a tunnelled URL would
+otherwise pop a modal window onto a screen nobody is watching, where it would sit
+and wait. Worse, they could not see or answer it, so the request would hang until
+its timeout while the desktop's owner found a dialog they never asked for.
+
+The route therefore answers the question twice: the capability probe says "not
+available, and here is why" so no button ever appears, and the action itself
+refuses outright in case one does.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException
+
+from jarvis.agentic_ide import native_picker
+from jarvis.ui.web import agentic_ide_routes as routes
+
+
+def _request() -> SimpleNamespace:
+ return SimpleNamespace(scope={})
+
+
+async def test_a_remote_browser_is_told_the_window_would_open_elsewhere(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(routes, "is_loopback_request", lambda _scope: False)
+
+ probe = await routes.native_picker_support(_request())
+
+ assert probe.available is False
+ assert probe.reason and "computer running Jarvis" in probe.reason
+
+
+async def test_a_remote_browser_cannot_open_the_window(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(routes, "is_loopback_request", lambda _scope: False)
+
+ def _explode(**_kwargs: object) -> None:
+ raise AssertionError("no window may be opened for a remote caller")
+
+ monkeypatch.setattr(native_picker, "choose_folder", _explode)
+
+ with pytest.raises(HTTPException) as excinfo:
+ await routes.open_native_picker(_request(), routes.NativePickRequest())
+
+ assert excinfo.value.status_code == 403
+
+
+async def test_locally_the_probe_reports_what_the_machine_can_do(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(routes, "is_loopback_request", lambda _scope: True)
+ monkeypatch.setattr(
+ native_picker, "support", lambda: native_picker.PickerSupport(True, "osascript")
+ )
+
+ probe = await routes.native_picker_support(_request())
+
+ assert probe.available is True
+ assert probe.backend == "osascript"
+
+
+async def test_the_chosen_folder_is_returned(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(routes, "is_loopback_request", lambda _scope: True)
+ monkeypatch.setattr(
+ native_picker,
+ "choose_folder",
+ lambda *, start: native_picker.PickResult(path=f"/picked/{start}"),
+ )
+
+ result = await routes.open_native_picker(
+ _request(), routes.NativePickRequest(start="/home/ruben")
+ )
+
+ assert result.path == "/picked//home/ruben"
+ assert result.cancelled is False
+
+
+async def test_cancelling_is_a_normal_answer(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(routes, "is_loopback_request", lambda _scope: True)
+ monkeypatch.setattr(
+ native_picker, "choose_folder", lambda **_k: native_picker.PickResult(cancelled=True)
+ )
+
+ result = await routes.open_native_picker(_request(), routes.NativePickRequest())
+
+ assert result.cancelled is True
+ assert result.path is None
+ assert result.error is None
+
+
+async def test_a_second_window_is_refused_while_one_is_open(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Stacked invisible dialogs are worse than a refusal: the user ends up
+ clicking through windows they never asked for."""
+ monkeypatch.setattr(routes, "is_loopback_request", lambda _scope: True)
+ await routes._native_picker_lock.acquire()
+ try:
+ with pytest.raises(HTTPException) as excinfo:
+ await routes.open_native_picker(_request(), routes.NativePickRequest())
+ finally:
+ routes._native_picker_lock.release()
+
+ assert excinfo.value.status_code == 409