Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(agentic-ide): the folder window opens in front, and a dropped folder keeps its real path
Haraldeb1c037d9db0
diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 1a7e47d318..c53235edce 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -9941,3 +9941,59 @@ transcript, after local microphone voice, after the window, a late resultJarvis injected itself; the capability gate; every disarm reason; the dropceiling). `tests/unit/diagnostics/test_realtime_forensics.py` carries thenew finding.++## BUG-144: "Browse" in the Agentic IDE folder step does nothing — the system folder window opens BEHIND the maximised app because its invisible owner is not topmost, and a dropped folder is only searched for by name (HIGH, FIXED 2026-08-18)++**Symptom.** Clicking "Browse" in "Choose the project folder" showed+"Waiting… A folder window is open — pick a folder there" and nothing else;+five minutes later the log said `the folder dialog was left open and timed+out`. Dropping a folder from Explorer onto the step answered "Several folders+are called “shop” — pick the right one" and listed the real folder next+to two cache directories whose NAMES merely contained it.++**Root.** Two, plus a ranking bug. (1) `native_picker._WINDOWS_SCRIPT` opened+the Common Item Dialog owned by a WinForms form with `TopMost = $true` and+`Opacity = 0`. Windows silently drops `WS_EX_TOPMOST` from a layered window+that is completely transparent (measured: ex-style `0x90100`, no `0x8`; with+opacity 0.01 the flag stays), so the owner was NOT topmost, the dialog it owns+was not either, and it opened behind the maximised app window — the process+was alive and the dialog "visible" to `IsWindowVisible`, just covered. Nothing+in the log said so because nothing was wrong from the helper's point of view.+(2) A browser hands a page only the NAME of a dropped folder; the picker sent+that name to `/folders/resolve`, which searched for it. Inside the desktop+shell the host knows the real path (pywebview delivers it as+`pywebviewFullPath` to a Python `drop` handler on every OS) but nobody asked.+(3) `resolve_folder` treated every substring hit of `search_folders` as a+rival of the exact-name hit.++**Fix.** (1) The owner is a one-pixel borderless form at opacity 0.01,+topmost, parked in the middle of the screen the mouse is on (the dialog+centres itself over its owner) — and `choose_folder` hands the app's+foreground right to the helper first (`AllowSetForegroundWindow(ASFW_ANY)`,+Windows only, best effort) so the dialog opens focused, not merely visible.+(2) `jarvis/ui/native_drop.py` registers a pywebview DOM `drop` handler on+`window` (not `body`, whose serialisation would be the whole document) from+the `loaded` hook of the main and every detached window, and dispatches a+`jarvis-native-drop` DOM event carrying the resolved paths; the frontend's+`waitForNativeDrop()` (src/lib/nativeDrop.ts), armed synchronously in the+picker's drop handler, uses that path and falls back to the name search after+2 s or at once outside the shell. Verified end-to-end for a dropped FOLDER on+WebView2 (`CoreWebView2File.Path` returns the directory path); macOS/Linux+ride pywebview's own implementation, unverified from this machine+(`docs/os-parity.md` P-34). (3) One exact-name match resolves outright;+several exact matches are offered without the look-alikes.++**Class.** A window opened by a background helper is invisible unless it is+topmost AND the topmost flag actually took (fully transparent layered windows+lose it); a fully transparent owner is a bug that reads as "the button does+nothing". Browser drops carry names, not paths — inside the shell, ask the+host. A search hit that merely CONTAINS the wanted name is not a rival for the+exact one.++**Regression tests.** `tests/unit/agentic_ide/test_native_picker.py`+(`test_the_windows_owner_window_is_never_fully_transparent`, foreground+hand-off is a no-op elsewhere); `tests/unit/ui/test_native_drop.py`;+`tests/unit/ui/test_desktop_detached_windows.py::test_every_window_load_rewires_the_drop_path_bridge`;+`tests/unit/web/test_agentic_ide_resolve_folder.py`; frontend+`src/lib/nativeDrop.test.ts` and `FolderPicker.test.tsx` ("uses the real path+the desktop shell reports").diff --git a/docs/os-parity.md b/docs/os-parity.mdindex 8bd4d4c75f..ee4079e7b8 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -248,6 +248,7 @@ experiences today.| P-32 | Low | Local models | The in-app Ollama runtime install (the plug-and-go path for local models: detect → install → start → pull, no terminal) has one silent path per OS and an honest refusal elsewhere: Windows uses winget or the official per-user OllamaSetup.exe (built, not yet live-run on a machine WITHOUT Ollama); macOS automates only Homebrew — a dmg drag cannot be scripted honestly, so brew-less Macs get the download pointer; Linux runs the official install.sh only when non-interactive sudo exists (the script escalates internally; without it the refusal names the one terminal command instead of hanging on an invisible password prompt). Detection and start are cross-platform | `jarvis/brain/ollama_runtime.py`, `jarvis/ui/web/provider_routes.py` (ollama-runtime routes), `jarvis/realtime/local_server/install.py::_setup_local_brain` | Every OS gets the same three-state truth (not installed / stopped / running) and the same buttons; only the INSTALL leg differs. Refusals are one honest sentence with the exact fixing action. All install legs are unit-tested with fakes; no leg has been live-run on a machine without Ollama yet — the cold-machine drill is the recorded release gate || P-31 | Low | Detached views | The "own window" detach (Agentic IDE / Voice into a second pywebview window) creates the window at RUNTIME, after `webview.start()`. pywebview documents runtime multi-window, and the code path is OS-neutral (worker-thread create, distinct title, shared backend), but it has only been RUN against the Windows/WebView2 backend; whether the cocoa and GTK backends accept a runtime `create_window` is unverified from this machine. Browser-lock auth in the second window additionally relies on a shared cookie jar, which is verified for WebView2 only | `jarvis/ui/desktop_app.py::open_detached_window`, `jarvis/platform/probes.py::webview_backend_available`, `jarvis/ui/web/desktop_routes.py` | Every failure is honest and keeps the feature usable: a shell whose backend refuses the runtime create answers `ok: false` with the solo URL and the frontend opens it in the user's real browser tab (via open-external); plain-browser clients open the tab directly; headless answers `no_desktop_shell` the same way. macOS/Linux desktop live check pending: detach, close main, reattach, tray-reopen — on success this row shrinks to the cookie-jar note or disappears |+| P-34 | Low | Drop-path bridge | The desktop shell reports the REAL path of a file or folder dropped onto the UI (`jarvis-native-drop` DOM event from `jarvis/ui/native_drop.py`, consumed by `src/lib/nativeDrop.ts` in the Agentic IDE folder picker). Built on pywebview's own cross-platform drop handling (`pywebviewFullPath` — WebView2 on Windows, WKWebView on macOS, WebKitGTK on Linux); live-verified for a dropped FOLDER on Windows/WebView2 only | `jarvis/ui/native_drop.py::register_native_drop`, `jarvis/ui/desktop_app.py::_register_native_drop`, `jarvis/ui/web/frontend/src/lib/nativeDrop.ts` | Honest degradation everywhere: without the announcement (plain browser, headless, a shell whose backend does not resolve paths) the picker falls back to searching for the dropped NAME after 2 s, exactly as before. macOS/Linux live check pending: drop a folder onto the folder step and confirm the exact path is used without a candidate list |## Maintenancediff --git a/jarvis/agentic_ide/native_picker.py b/jarvis/agentic_ide/native_picker.pyindex f39cab964e..f205a943d0 100644--- a/jarvis/agentic_ide/native_picker.py+++ b/jarvis/agentic_ide/native_picker.py@@ -27,6 +27,7 @@ the two things that actually matter — a display and a program that can draw thdialog — 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 annotationsimport os@@ -144,6 +145,7 @@ def support() -> PickerSupport:# --------------------------------------------------------------------------- #_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.@@ -175,15 +177,34 @@ def _fill(script: str, **values: str) -> str:# 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.+#+# The owner is a one-pixel borderless form, NOT a full-size form with+# `Opacity = 0`: Windows silently drops WS_EX_TOPMOST from a layered window that+# is completely transparent, so an opacity-0 owner is not topmost at all, the+# dialog it owns is not either, and behind a maximised app window the picker is+# invisible — exactly the "Browse does nothing" report. A faint 1x1 window keeps+# the flag (measured: 0.01 keeps it, 0 loses it). It sits in the middle of the+# screen the mouse is on, because the dialog centres itself over its owner and+# the mouse is where the person just clicked "Browse"._WINDOWS_SCRIPT = r"""$ErrorActionPreference = 'Stop'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8Add-Type -AssemblyName System.Windows.Forms+Add-Type -AssemblyName System.Drawing$owner = New-Object System.Windows.Forms.Form-$owner.TopMost = $true+$owner.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None$owner.ShowInTaskbar = $false-$owner.Opacity = 0+$owner.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual+$owner.MinimumSize = New-Object System.Drawing.Size(1, 1)+$owner.Size = New-Object System.Drawing.Size(1, 1)+$mouse = [System.Windows.Forms.Cursor]::Position+$area = [System.Windows.Forms.Screen]::FromPoint($mouse).WorkingArea+$owner.Location = New-Object System.Drawing.Point(+ ($area.Left + [int]($area.Width / 2)),+ ($area.Top + [int]($area.Height / 2)))+$owner.Opacity = 0.01+$owner.TopMost = $true$owner.Show()$owner.Activate()$ownerHandle = $owner.Handle@@ -362,9 +383,28 @@ def _extract(stdout: str) -> str | None:return cleaned or None-def choose_folder(- *, start: str | None = None, timeout: float = DEFAULT_TIMEOUT_S-) -> PickResult:+def _let_the_dialog_take_the_foreground() -> None:+ """Hand our foreground right to the helper about to be started (Windows).++ Windows lets a process activate a window only while it holds the foreground+ right; the app has it because the user just clicked "Browse", the helper+ process does not. ``AllowSetForegroundWindow(ASFW_ANY)`` passes it on for the+ next activation, so the dialog opens focused instead of merely visible.+ Best effort: when the app is not in the foreground the call fails, and the+ topmost owner window still makes the dialog visible.+ """+ if sys.platform != "win32":+ return+ try:+ import ctypes++ asfw_any = ctypes.c_uint32(0xFFFFFFFF).value # -1 as DWORD+ ctypes.windll.user32.AllowSetForegroundWindow(asfw_any)+ except Exception as exc: # noqa: BLE001 - a nicety, never a reason to fail+ logger.debug("Agentic IDE: could not pass the foreground right on: {}", exc)+++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@@ -390,6 +430,7 @@ def choose_folder(argv, env_extra = builtenv = {**os.environ, **env_extra}+ _let_the_dialog_take_the_foreground()try:completed = subprocess.run( # noqa: S603 - fixed argv, no shellargv,diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 4a95acdbe1..4cb24700f3 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -4415,6 +4415,7 @@ class DesktopApp:# Not fatal: the window still authenticates via open access / the# shared cookie jar; only the embedded-shell niceties are lost.pass+ self._register_native_drop(window)try:from jarvis.ui.icon_utils import ( # noqa: PLC0415project_icon_path,@@ -4500,6 +4501,20 @@ class DesktopApp:"""Attach the closing/closed contract to the current main window."""self._window.events.closing += self._on_window_closingself._window.events.closed += self._on_main_window_closed+ # Real paths for dropped files/folders (see jarvis/ui/native_drop.py).+ # A `loaded` hook, not `func`: pywebview forgets DOM handlers on every+ # page load, and the UI reloads itself after each frontend build.+ self._window.events.loaded += lambda w=self._window: self._register_native_drop(w)++ @staticmethod+ def _register_native_drop(window: Any) -> None:+ """Wire the drop-path bridge into a freshly loaded page — never raises."""+ try:+ from jarvis.ui.native_drop import register_native_drop # noqa: PLC0415++ register_native_drop(window)+ except Exception: # noqa: BLE001, S110 - the drop bridge is never load-bearing+ passdef _on_main_window_closed(self) -> None:"""pywebview ``closed`` hook of the MAIN window.diff --git a/jarvis/ui/native_drop.py b/jarvis/ui/native_drop.pynew file mode 100644index 0000000000..b818070373--- /dev/null+++ b/jarvis/ui/native_drop.py@@ -0,0 +1,98 @@+"""Real paths for files and folders dropped ONTO the desktop WebView.++A web page never learns where a dropped folder lives: the browser hands it a+``File`` with a name and nothing else, by design. In a plain browser tab that is+the end of it and the UI falls back to searching for the name. Inside the+desktop shell we can do better, because the host process sees the native drop+and knows the full path — pywebview exposes it as ``pywebviewFullPath`` on every+file of a ``drop`` event delivered to a Python handler, on Windows (WebView2),+macOS (WKWebView) and Linux (WebKitGTK) alike.++So this module registers exactly such a handler on each window's ``window``+object and, whenever it fires, tells the page: it dispatches a+``jarvis-native-drop`` DOM event whose ``detail`` carries the resolved paths+(and the names they belong to). Any component that handles drops can wait a+moment for that event and use the exact path instead of guessing — the folder+picker in the Agentic IDE does. Outside the shell the event never comes and the+component simply keeps its browser fallback.++Registered on ``window``, not ``body``: pywebview serialises the whole event+including ``currentTarget``, and for ``window`` that is one short string where+``body`` would be the entire document.+"""++from __future__ import annotations++import json+import logging+from collections.abc import Mapping+from typing import Any++log = logging.getLogger(__name__)++# The DOM event the page listens for. Kept in sync with the frontend helper+# (src/lib/nativeDrop.ts).+EVENT_NAME = "jarvis-native-drop"+++def dropped_paths(event: Mapping[str, Any]) -> tuple[list[str], list[str]]:+ """The full paths and names of the files in a serialised ``drop`` event.++ Pure, so it can be tested without a window. Files pywebview could not+ resolve (no ``pywebviewFullPath``) are skipped rather than reported as an+ empty path — an empty path is not a hint the page can act on.+ """+ data_transfer = event.get("dataTransfer")+ files = data_transfer.get("files") if isinstance(data_transfer, Mapping) else None+ paths: list[str] = []+ names: list[str] = []+ for item in files or []:+ if not isinstance(item, Mapping):+ continue+ path = item.get("pywebviewFullPath")+ if not isinstance(path, str) or not path:+ continue+ paths.append(path)+ name = item.get("name")+ names.append(name if isinstance(name, str) else "")+ return paths, names+++def announce_script(paths: list[str], names: list[str]) -> str:+ """The JavaScript that tells the page what was dropped."""+ detail = json.dumps({"paths": paths, "names": names})+ return f"window.dispatchEvent(new CustomEvent({json.dumps(EVENT_NAME)}, {{detail: {detail}}}));"+++def register_native_drop(window: Any) -> bool:+ """Wire the drop handler into ``window``'s CURRENT page.++ Call from the window's ``loaded`` hook — pywebview forgets DOM handlers on+ every load, so this must run again each time the page (re)loads. Never+ raises: a shell without the DOM API (or a stub window in tests) just does+ not get the feature, and the browser fallback still stands.+ """+ dom = getattr(window, "dom", None)+ if dom is None:+ log.debug("native_drop: this window has no DOM bridge — browser fallback stays")+ return False++ def _on_drop(event: Mapping[str, Any]) -> None:+ try:+ paths, names = dropped_paths(event)+ if not paths:+ return+ window.evaluate_js(announce_script(paths, names))+ except Exception: # noqa: BLE001 — a drop must never take the shell down+ log.exception("native_drop: could not hand the dropped paths to the page")++ try:+ dom.window.on("drop", _on_drop)+ except Exception as exc: # noqa: BLE001 — pywebview internals vary by backend+ log.warning("native_drop: drop bridge unavailable in this window (%s)", exc)+ return False+ log.debug("native_drop: drop bridge registered")+ return True+++__all__ = ["EVENT_NAME", "announce_script", "dropped_paths", "register_native_drop"]diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 60b7c8bdf4..88010333f4 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -1647,6 +1647,15 @@ async def resolve_folder(req: ResolveRequest) -> ResolveResponse:hits = await asyncio.to_thread(search_folders, wanted, limit=12)items = [FolderItem(**asdict(e)) for e in hits]+ # A dropped folder is CALLED exactly that, so a folder that merely contains+ # the name (a "C--Users-x-Desktop-shop" cache dir next to a real "shop")+ # is not a rival for it: one exact match wins outright, and only several+ # exact matches are a real ambiguity.+ exact = [item for item in items if item.name.lower() == wanted.lower()]+ if len(exact) == 1:+ return ResolveResponse(resolved=exact[0].path, candidates=items)+ if len(exact) > 1:+ items = exactif len(items) == 1:return ResolveResponse(resolved=items[0].path, candidates=items)if not items:@@ -4107,7 +4116,7 @@ def _writer_options() -> list[PromptWriterOption]:options = [PromptWriterOption(id="auto",- label="Automatic (a connected subscription, else the API model)",+ label="Automatic (your Tool Model, else the API model, else a connected subscription)",connected=True,),_tool_model_option(),diff --git a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsxindex 7a876d8e41..6ba8a19d8d 100644--- a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.test.tsx@@ -222,6 +222,45 @@ describe("FolderPicker", () => {expect(await screen.findByText("/a/webshop")).toBeTruthy();});+ it("uses the real path the desktop shell reports instead of searching by name", async () => {+ // Inside the shell the host knows where the dropped folder lives and says+ // so a moment after the drop; the picker waits for that instead of asking+ // the backend to guess from the name.+ (window as unknown as { __JARVIS_EMBEDDED_DESKTOP?: boolean }).__JARVIS_EMBEDDED_DESKTOP =+ true;+ try {+ vi.mocked(api.resolveDroppedFolder).mockResolvedValue({+ resolved: "/home/x/Desktop/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({ directoryName: "webshop" }),+ });+ window.dispatchEvent(+ new CustomEvent("jarvis-native-drop", {+ detail: { paths: ["/home/x/Desktop/webshop"], names: ["webshop"] },+ }),+ );++ await waitFor(() =>+ expect(api.resolveDroppedFolder).toHaveBeenCalledWith({+ path: "/home/x/Desktop/webshop",+ }),+ );+ await waitFor(() =>+ expect(onSelect).toHaveBeenCalledWith("/home/x/Desktop/webshop"),+ );+ } finally {+ delete (window as unknown as { __JARVIS_EMBEDDED_DESKTOP?: boolean })+ .__JARVIS_EMBEDDED_DESKTOP;+ }+ });+it("says so plainly when a drop carried nothing usable", async () => {render(<FolderPicker selected={null} onSelect={vi.fn()} />);await screen.findByText("webshop");diff --git a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsxindex dbdba24339..a7f0b2ace2 100644--- a/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/FolderPicker.tsx@@ -13,7 +13,9 @@* 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.+ * panel. Inside the desktop shell the host reports the real path+ * (`waitForNativeDrop`); in a browser only the NAME is known, and the+ * backend searches for it — see `extractDropPayload`.** 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@@ -53,6 +55,7 @@ import {X,} from "lucide-react";import { cn } from "@/lib/utils";+import { waitForNativeDrop } from "@/lib/nativeDrop";import { Button, Field, IconButton, SectionLabel } from "./controls";import {fetchFolders,@@ -283,7 +286,19 @@ export function FolderPicker({return;}setDropNote("Resolving the dropped folder…");- void resolveDroppedFolder(payload)+ // The desktop shell knows the real path of what was dropped and says so a+ // moment after the drop; with only a name, that beats searching for it.+ // The wait itself is armed here, synchronously, so no announcement is+ // missed — outside the shell it answers null at once.+ const nativePaths = payload.path+ ? Promise.resolve(null)+ : waitForNativeDrop({ name: payload.name });+ void nativePaths+ .then((native) =>+ resolveDroppedFolder(+ native?.paths[0] ? { path: native.paths[0] } : payload,+ ),+ ).then((res) => {if (res.resolved) {setDropNote(res.detail || null);diff --git a/jarvis/ui/web/frontend/src/lib/nativeDrop.test.ts b/jarvis/ui/web/frontend/src/lib/nativeDrop.test.tsnew file mode 100644index 0000000000..8a5a522f0d--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/nativeDrop.test.ts@@ -0,0 +1,56 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ NATIVE_DROP_EVENT,+ inDesktopShell,+ waitForNativeDrop,+} from "./nativeDrop";++type Host = { __JARVIS_EMBEDDED_DESKTOP?: boolean; pywebview?: unknown };++afterEach(() => {+ const host = window as unknown as Host;+ delete host.__JARVIS_EMBEDDED_DESKTOP;+ delete host.pywebview;+ vi.useRealTimers();+});++function announce(paths: string[], names: string[]) {+ window.dispatchEvent(+ new CustomEvent(NATIVE_DROP_EVENT, { detail: { paths, names } }),+ );+}++describe("waitForNativeDrop", () => {+ it("answers null at once outside the desktop shell", async () => {+ expect(inDesktopShell()).toBe(false);+ await expect(waitForNativeDrop({ name: "shop" })).resolves.toBeNull();+ });++ it("returns the paths the shell announces for the dropped name", async () => {+ (window as unknown as Host).__JARVIS_EMBEDDED_DESKTOP = true;+ const pending = waitForNativeDrop({ name: "shop" });+ announce(["C:\\Users\\x\\Desktop\\shop"], ["shop"]);+ await expect(pending).resolves.toEqual({+ paths: ["C:\\Users\\x\\Desktop\\shop"],+ names: ["shop"],+ });+ });++ it("ignores an announcement for a different drop", async () => {+ vi.useFakeTimers();+ (window as unknown as Host).pywebview = {};+ const pending = waitForNativeDrop({ name: "shop", timeoutMs: 50 });+ announce(["/elsewhere/notes"], ["notes"]);+ vi.advanceTimersByTime(60);+ await expect(pending).resolves.toBeNull();+ });++ it("gives up after the timeout when the shell stays silent", async () => {+ vi.useFakeTimers();+ (window as unknown as Host).__JARVIS_EMBEDDED_DESKTOP = true;+ const pending = waitForNativeDrop({ timeoutMs: 100 });+ vi.advanceTimersByTime(101);+ await expect(pending).resolves.toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/nativeDrop.ts b/jarvis/ui/web/frontend/src/lib/nativeDrop.tsnew file mode 100644index 0000000000..ea72741024--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/nativeDrop.ts@@ -0,0 +1,71 @@+/**+ * Real paths for files and folders dropped onto the desktop shell.+ *+ * A browser hands a page only the NAME of a dropped folder — never its path.+ * Inside the desktop shell the host process sees the native drop and knows the+ * path; `jarvis/ui/native_drop.py` dispatches it to the page as a+ * `jarvis-native-drop` event right after the DOM `drop`. A drop handler that+ * wants the exact path calls `waitForNativeDrop()` synchronously from its drop+ * handler and gets the paths a moment later — or `null`, promptly, in a plain+ * browser tab or when the shell could not resolve them, and then keeps its own+ * fallback (searching by name).+ */++/** Event name — MUST match `EVENT_NAME` in jarvis/ui/native_drop.py. */+export const NATIVE_DROP_EVENT = "jarvis-native-drop";++/** How long a page waits for the shell before falling back. The round trip is+ * usually well under 200 ms; the ceiling only matters when the bridge is not+ * there at all. */+const NATIVE_DROP_TIMEOUT_MS = 2000;++export interface NativeDropDetail {+ /** Full native paths, one per dropped file or folder that could be resolved. */+ paths: string[];+ /** The browser-side names the paths belong to, in the same order. */+ names: string[];+}++/** True inside the pywebview desktop shell (any OS), where the host can answer. */+export function inDesktopShell(): boolean {+ const host = window as unknown as {+ __JARVIS_EMBEDDED_DESKTOP?: boolean;+ pywebview?: unknown;+ };+ return Boolean(host.__JARVIS_EMBEDDED_DESKTOP || host.pywebview);+}++/**+ * Wait for the shell to report the paths of the drop that just happened.+ *+ * Call it synchronously inside the `drop` handler, so the listener is in place+ * before the shell answers. Resolves `null` immediately outside the shell, and+ * after the timeout when no matching announcement arrives. When `name` is+ * given, an announcement is accepted only if it carries that name — a stray+ * event from another drop is never mistaken for this one.+ */+export function waitForNativeDrop(opts: {+ name?: string;+ timeoutMs?: number;+} = {}): Promise<NativeDropDetail | null> {+ if (!inDesktopShell()) return Promise.resolve(null);+ const timeoutMs = opts.timeoutMs ?? NATIVE_DROP_TIMEOUT_MS;+ return new Promise((resolve) => {+ let timer: number | undefined;+ const onEvent = (event: Event) => {+ const detail = (event as CustomEvent<Partial<NativeDropDetail>>).detail;+ const paths = Array.isArray(detail?.paths) ? detail.paths : [];+ const names = Array.isArray(detail?.names) ? detail.names : [];+ if (paths.length === 0) return;+ if (opts.name && names.length > 0 && !names.includes(opts.name)) return;+ window.removeEventListener(NATIVE_DROP_EVENT, onEvent);+ if (timer !== undefined) window.clearTimeout(timer);+ resolve({ paths, names });+ };+ window.addEventListener(NATIVE_DROP_EVENT, onEvent);+ timer = window.setTimeout(() => {+ window.removeEventListener(NATIVE_DROP_EVENT, onEvent);+ resolve(null);+ }, timeoutMs);+ });+}diff --git a/tests/unit/agentic_ide/test_native_picker.py b/tests/unit/agentic_ide/test_native_picker.pyindex fb32b319aa..ea42a90a6f 100644--- a/tests/unit/agentic_ide/test_native_picker.py+++ b/tests/unit/agentic_ide/test_native_picker.py@@ -253,3 +253,28 @@ def test_the_windows_command_runs_in_a_single_threaded_apartment() -> None:argv, _env = native_picker._command(None, "powershell")assert "-STA" in argvassert "-NoProfile" in argv+++def test_the_windows_owner_window_is_never_fully_transparent() -> None:+ """Regression guard for the "Browse does nothing" report.++ The dialog is made visible above a maximised app window by a topmost owner.+ Windows drops the topmost flag from a layered window whose opacity is 0, so+ an ``Opacity = 0`` owner is not topmost, the dialog it owns opens BEHIND the+ app, and the button looks dead. The owner must therefore be faint, never+ invisible — and topmost.+ """+ script = native_picker._fill(native_picker._WINDOWS_SCRIPT)+ assert "$owner.Opacity = 0\n" not in script+ assert "$owner.Opacity = 0.01" in script+ assert "$owner.TopMost = $true" in script+ # The dialog centres itself over its owner: park the owner where the person+ # is looking, i.e. on the screen the mouse is on.+ assert "Screen]::FromPoint($mouse).WorkingArea" in script+++def test_handing_over_the_foreground_right_is_a_no_op_elsewhere(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(sys, "platform", "linux")+ native_picker._let_the_dialog_take_the_foreground() # must not raisediff --git a/tests/unit/ui/test_desktop_detached_windows.py b/tests/unit/ui/test_desktop_detached_windows.pyindex f8425663a7..2baaeb7fd9 100644--- a/tests/unit/ui/test_desktop_detached_windows.py+++ b/tests/unit/ui/test_desktop_detached_windows.py@@ -327,6 +327,35 @@ def test_ensure_main_window_recreates_and_rehooks(monkeypatch) -> None:assert app._window_visible is Trueassert len(created[0].events.closing) == 1 # quit contract re-attachedassert len(created[0].events.closed) == 1 # null-out re-attached+ assert len(created[0].events.loaded) == 1 # drop-path bridge re-attached+++# --- native drop bridge --------------------------------------------------------+++def test_every_window_load_rewires_the_drop_path_bridge(monkeypatch) -> None:+ """pywebview forgets DOM handlers on each page load, and the UI reloads+ itself after a frontend build — so the bridge is (re)registered from the+ ``loaded`` hook of the main window and of every detached window."""+ import sys++ registered: list[Any] = []+ monkeypatch.setattr(+ "jarvis.ui.native_drop.register_native_drop",+ lambda window: registered.append(window) or True,+ )+ app = _app(monkeypatch)+ app._hook_main_window_lifecycle()+ for hook in app._window.events.loaded:+ hook()+ assert registered == [app._window]++ created: list[_FakeWindow] = []+ monkeypatch.setitem(sys.modules, "webview", _fake_webview(created))+ app.open_detached_window("agentic-ide")+ for hook in created[0].events.loaded:+ hook()+ assert registered == [app._window, created[0]]def test_ensure_main_window_shows_existing_window(monkeypatch) -> None:diff --git a/tests/unit/ui/test_native_drop.py b/tests/unit/ui/test_native_drop.pynew file mode 100644index 0000000000..24f6e22c5e--- /dev/null+++ b/tests/unit/ui/test_native_drop.py@@ -0,0 +1,99 @@+"""The drop-path bridge: what the shell knows about a drop reaches the page.++The desktop WebView is told the real path of a dropped file or folder by+pywebview (``pywebviewFullPath``); this bridge forwards it to the page as one+DOM event. It must never raise — a window without the DOM API (or a stub in+tests) simply keeps the browser fallback — and it must not report files whose+path the shell could not resolve.+"""++from __future__ import annotations++import json+from types import SimpleNamespace+from typing import Any++from jarvis.ui import native_drop+++def test_paths_and_names_come_from_the_resolved_files_only() -> None:+ event = {+ "type": "drop",+ "dataTransfer": {+ "files": [+ {"name": "shop", "size": 0, "pywebviewFullPath": "C:\\Users\\x\\Desktop\\shop"},+ {"name": "unresolved.txt", "size": 3},+ "not-a-file",+ {"name": "notes", "pywebviewFullPath": "/home/x/notes"},+ ]+ },+ }++ paths, names = native_drop.dropped_paths(event)++ assert paths == ["C:\\Users\\x\\Desktop\\shop", "/home/x/notes"]+ assert names == ["shop", "notes"]+++def test_an_event_without_files_yields_nothing() -> None:+ assert native_drop.dropped_paths({"type": "drop"}) == ([], [])+ assert native_drop.dropped_paths({"dataTransfer": "??"}) == ([], [])+++def test_the_announcement_is_one_dom_event_with_the_paths_as_detail() -> None:+ script = native_drop.announce_script(["C:\\a b\\shop"], ["shop"])++ assert script.startswith("window.dispatchEvent(new CustomEvent(")+ assert json.dumps(native_drop.EVENT_NAME) in script+ # Backslashes and spaces survive because the detail is JSON, never string glue.+ assert json.dumps({"paths": ["C:\\a b\\shop"], "names": ["shop"]}) in script+++class _FakeDomWindow:+ def __init__(self) -> None:+ self.handlers: dict[str, Any] = {}++ def on(self, event: str, handler: Any) -> None:+ self.handlers[event] = handler+++class _FakeWindow:+ def __init__(self) -> None:+ self.dom = SimpleNamespace(window=_FakeDomWindow())+ self.evaluated: list[str] = []++ def evaluate_js(self, script: str) -> None:+ self.evaluated.append(script)+++def test_registering_wires_a_drop_handler_that_tells_the_page() -> None:+ window = _FakeWindow()++ assert native_drop.register_native_drop(window) is True+ handler = window.dom.window.handlers["drop"]+ handler({"dataTransfer": {"files": [{"name": "shop", "pywebviewFullPath": "/p/shop"}]}})++ assert len(window.evaluated) == 1+ assert "/p/shop" in window.evaluated[0]+++def test_a_drop_the_shell_could_not_resolve_stays_silent() -> None:+ """No paths, no event: the page's browser fallback (searching by name)+ must not be pre-empted by an announcement that says nothing."""+ window = _FakeWindow()+ native_drop.register_native_drop(window)++ window.dom.window.handlers["drop"]({"dataTransfer": {"files": [{"name": "shop"}]}})++ assert window.evaluated == []+++def test_a_window_without_a_dom_bridge_is_a_quiet_no() -> None:+ assert native_drop.register_native_drop(SimpleNamespace()) is False+++def test_a_failing_registration_never_raises() -> None:+ class _Broken:+ window = SimpleNamespace(on=lambda *_a, **_k: (_ for _ in ()).throw(RuntimeError("no js")))++ assert native_drop.register_native_drop(SimpleNamespace(dom=_Broken())) is Falsediff --git a/tests/unit/web/test_agentic_ide_resolve_folder.py b/tests/unit/web/test_agentic_ide_resolve_folder.pynew file mode 100644index 0000000000..e477bb9763--- /dev/null+++ b/tests/unit/web/test_agentic_ide_resolve_folder.py@@ -0,0 +1,80 @@+"""Turning a dropped folder into a path — a name is a name, not a substring.++A browser tells the page only what a dropped folder is CALLED. The route then+searches for that name, and the search also returns folders that merely contain+it — a cache directory named after a project path, say. Those are not rivals:+a folder called exactly what was dropped wins outright, and only several exact+matches are a real ambiguity worth asking about.+"""++from __future__ import annotations++import pytest++from jarvis.agentic_ide.folders import FolderEntry+from jarvis.ui.web import agentic_ide_routes as routes+++def _entry(name: str, path: str) -> FolderEntry:+ return FolderEntry(name=name, path=path, is_project=True, is_repo=False)+++async def test_one_exact_name_match_wins_over_folders_that_merely_contain_it(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ hits = [+ _entry("shop", "/home/x/Desktop/shop"),+ _entry("C--Users-x-Desktop-shop", "/home/x/.cache/tool/C--Users-x-Desktop-shop"),+ _entry("shop-backup", "/home/x/old/shop-backup"),+ ]+ monkeypatch.setattr(routes, "search_folders", lambda *_a, **_k: hits)++ res = await routes.resolve_folder(routes.ResolveRequest(name="shop"))++ assert res.resolved == "/home/x/Desktop/shop"+++async def test_several_exact_matches_are_offered_without_the_lookalikes(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ hits = [+ _entry("shop", "/home/x/a/shop"),+ _entry("Shop", "/home/x/b/Shop"),+ _entry("shop-old", "/home/x/c/shop-old"),+ ]+ monkeypatch.setattr(routes, "search_folders", lambda *_a, **_k: hits)++ res = await routes.resolve_folder(routes.ResolveRequest(name="shop"))++ assert res.resolved is None+ assert [c.path for c in res.candidates] == ["/home/x/a/shop", "/home/x/b/Shop"]+ assert "pick the right one" in res.detail+++async def test_only_lookalikes_are_still_offered_as_a_choice(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ hits = [+ _entry("webshop", "/home/x/webshop"),+ _entry("shop-old", "/home/x/shop-old"),+ ]+ monkeypatch.setattr(routes, "search_folders", lambda *_a, **_k: hits)++ res = await routes.resolve_folder(routes.ResolveRequest(name="shop"))++ assert res.resolved is None+ assert len(res.candidates) == 2+++async def test_a_real_path_needs_no_search(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ """The desktop shell reports the dropped folder's real path — that is used as+ is, and the name search never runs."""++ def _explode(*_a: object, **_k: object) -> None:+ raise AssertionError("a known path must not be searched for")++ monkeypatch.setattr(routes, "search_folders", _explode)++ res = await routes.resolve_folder(routes.ResolveRequest(path=str(tmp_path), name="x"))++ assert res.resolved == str(tmp_path)