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.

fix(downloads): save into the folder the OS calls Downloads

rubenluetke10-beep388df596c3de
diff --git a/jarvis/appshot/card_actions.py b/jarvis/appshot/card_actions.py
index a8e7dabf61..a872689663 100644
--- a/jarvis/appshot/card_actions.py
+++ b/jarvis/appshot/card_actions.py
@@ -108,7 +108,9 @@ def as_png(image: bytes) -> bytes:
def save_to_downloads(png: bytes, *, folder: Path | None = None, now: float | None = None) -> Path:
"""Write ``png`` into Downloads under a fresh name and return the path."""
- target = folder or (Path.home() / "Downloads")
+ from jarvis.platform import user_dirs # noqa: PLC0415
+
+ target = folder or user_dirs.downloads_dir()
target.mkdir(parents=True, exist_ok=True)
moment = time.time() if now is None else now
stem = time.strftime("appshot-%Y%m%d-%H%M%S", time.localtime(moment))
diff --git a/jarvis/jarvisx/paths.py b/jarvis/jarvisx/paths.py
index 03e4430f17..15afe89d8b 100644
--- a/jarvis/jarvisx/paths.py
+++ b/jarvis/jarvisx/paths.py
@@ -11,15 +11,14 @@ Two locations:
- the **library folder** in the Jarvis data directory, holding the index and
the small preview thumbnails.
-Only stdlib at module scope; the Windows path uses ctypes lazily.
+Only stdlib at module scope; the OS folder lookup lives in
+:mod:`jarvis.platform.user_dirs`.
"""
from __future__ import annotations
import logging
import os
-import re
-import sys
from datetime import datetime
from pathlib import Path
@@ -69,13 +68,10 @@ def resolve_save_dir(configured: str) -> Path:
def pictures_dir() -> Path | None:
"""The user's Pictures folder, or ``None`` when this machine has none."""
+ from jarvis.platform.user_dirs import pictures_dir as user_pictures # noqa: PLC0415
+
try:
- if sys.platform == "win32":
- found = _windows_pictures()
- elif sys.platform == "darwin":
- found = Path.home() / "Pictures"
- else:
- found = _xdg_pictures()
+ found = user_pictures()
except Exception: # noqa: BLE001 - a probe failure means "use the fallback"
log.debug("jarvisx: Pictures folder probe failed", exc_info=True)
return None
@@ -84,65 +80,6 @@ def pictures_dir() -> Path | None:
return None
-def _windows_pictures() -> Path | None:
- """``FOLDERID_Pictures`` through ``SHGetKnownFolderPath`` (OneDrive-aware)."""
- import ctypes # noqa: PLC0415
- from ctypes import wintypes # noqa: PLC0415
-
- class _GUID(ctypes.Structure):
- _fields_ = [
- ("Data1", wintypes.DWORD),
- ("Data2", wintypes.WORD),
- ("Data3", wintypes.WORD),
- ("Data4", ctypes.c_ubyte * 8),
- ]
-
- # {33E28130-4E1E-4676-835A-98395C3BC3BB}
- folder_id = _GUID(
- 0x33E28130,
- 0x4E1E,
- 0x4676,
- (ctypes.c_ubyte * 8)(0x83, 0x5A, 0x98, 0x39, 0x5C, 0x3B, 0xC3, 0xBB),
- )
- shell32 = ctypes.WinDLL("shell32", use_last_error=True)
- ole32 = ctypes.WinDLL("ole32", use_last_error=True)
- shell32.SHGetKnownFolderPath.argtypes = [
- ctypes.POINTER(_GUID),
- wintypes.DWORD,
- wintypes.HANDLE,
- ctypes.POINTER(ctypes.c_wchar_p),
- ]
- shell32.SHGetKnownFolderPath.restype = ctypes.c_long
- ole32.CoTaskMemFree.argtypes = [ctypes.c_void_p]
- ole32.CoTaskMemFree.restype = None
- out = ctypes.c_wchar_p()
- if shell32.SHGetKnownFolderPath(ctypes.byref(folder_id), 0, None, ctypes.byref(out)) != 0:
- return Path.home() / "Pictures"
- try:
- return Path(out.value) if out.value else Path.home() / "Pictures"
- finally:
- ole32.CoTaskMemFree(out)
-
-
-def _xdg_pictures() -> Path | None:
- """``XDG_PICTURES_DIR`` from ``user-dirs.dirs``, else ``~/Pictures``."""
- home = Path.home()
- config_home = Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config")
- dirs_file = config_home / "user-dirs.dirs"
- try:
- text = dirs_file.read_text(encoding="utf-8")
- except OSError:
- return home / "Pictures"
- match = re.search(r'^XDG_PICTURES_DIR="([^"]*)"', text, re.MULTILINE)
- if not match:
- return home / "Pictures"
- value = match.group(1).replace("$HOME", str(home))
- path = Path(value)
- # user-dirs.dirs points Pictures at $HOME itself when the folder was
- # removed; saving loose files into the home folder is not what anyone wants.
- return None if path == home else path
-
-
def capture_filename(kind: str, when: datetime, ext: str) -> str:
"""``Jarvis X 2026-09-29 at 14.03.22.png`` (``Recording`` for videos)."""
label = "Recording" if kind == "video" else FOLDER_NAME
diff --git a/jarvis/platform/user_dirs.py b/jarvis/platform/user_dirs.py
new file mode 100644
index 0000000000..d2976e6a8d
--- /dev/null
+++ b/jarvis/platform/user_dirs.py
@@ -0,0 +1,123 @@
+"""The user's own folders — Downloads and Pictures — the way each OS names them.
+
+- **Windows** asks the known-folder API (``SHGetKnownFolderPath``), so a
+ Downloads or Pictures folder moved to another drive or into OneDrive is the
+ one used.
+- **macOS** uses ``~/Downloads`` and ``~/Pictures``.
+- **Linux** reads ``XDG_DOWNLOAD_DIR`` / ``XDG_PICTURES_DIR`` from
+ ``user-dirs.dirs``: on a Spanish desktop Downloads is ``~/Descargas``, on a
+ French one ``~/Téléchargements``. Writing to a hard-coded ``~/Downloads``
+ there created a stray folder nobody looks in.
+
+Only stdlib at module scope; the Windows path uses ctypes lazily.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+import sys
+from pathlib import Path
+
+log = logging.getLogger(__name__)
+
+#: FOLDERID_Downloads {374DE290-123F-4565-9164-39C4925E467B}.
+_DOWNLOADS_ID = (0x374DE290, 0x123F, 0x4565, (0x91, 0x64, 0x39, 0xC4, 0x92, 0x5E, 0x46, 0x7B))
+#: FOLDERID_Pictures {33E28130-4E1E-4676-835A-98395C3BC3BB}.
+_PICTURES_ID = (0x33E28130, 0x4E1E, 0x4676, (0x83, 0x5A, 0x98, 0x39, 0x5C, 0x3B, 0xC3, 0xBB))
+
+
+def downloads_dir() -> Path:
+ """The user's Downloads folder. Never ``None``: ``~/Downloads`` is the floor."""
+ fallback = Path.home() / "Downloads"
+ try:
+ if sys.platform == "win32":
+ return windows_known_folder(_DOWNLOADS_ID) or fallback
+ if sys.platform == "darwin":
+ return fallback
+ return xdg_user_dir("DOWNLOAD") or fallback
+ except Exception: # noqa: BLE001 - a probe failure means "use the plain folder"
+ log.debug("user-dirs: Downloads folder probe failed", exc_info=True)
+ return fallback
+
+
+def pictures_dir() -> Path | None:
+ """The user's Pictures folder path, or ``None`` when Linux points it at home."""
+ if sys.platform == "win32":
+ return windows_known_folder(_PICTURES_ID) or Path.home() / "Pictures"
+ if sys.platform == "darwin":
+ return Path.home() / "Pictures"
+ found = xdg_user_dir("PICTURES")
+ if found is None and not _xdg_names_home("PICTURES"):
+ return Path.home() / "Pictures"
+ return found
+
+
+def xdg_user_dir(name: str) -> Path | None:
+ """``XDG_<name>_DIR`` from ``user-dirs.dirs``; ``None`` when unset or ``$HOME``.
+
+ xdg-user-dirs points an entry at ``$HOME`` itself when its folder was
+ removed; loose files in the home folder are not what anyone wants.
+ """
+ value = _xdg_entry(name)
+ if value is None:
+ return None
+ path = Path(value)
+ return None if path == Path.home() else path
+
+
+def _xdg_names_home(name: str) -> bool:
+ value = _xdg_entry(name)
+ return value is not None and Path(value) == Path.home()
+
+
+def _xdg_entry(name: str) -> str | None:
+ home = Path.home()
+ config_home = Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config")
+ try:
+ text = (config_home / "user-dirs.dirs").read_text(encoding="utf-8")
+ except OSError:
+ return None
+ match = re.search(rf'^XDG_{re.escape(name)}_DIR="([^"]*)"', text, re.MULTILINE)
+ if not match:
+ return None
+ return match.group(1).replace("$HOME", str(home))
+
+
+def windows_known_folder(folder: tuple[int, int, int, tuple[int, ...]]) -> Path | None:
+ """A Windows known folder through ``SHGetKnownFolderPath``, or ``None``."""
+ import ctypes # noqa: PLC0415
+ from ctypes import wintypes # noqa: PLC0415
+
+ class _GUID(ctypes.Structure):
+ _fields_ = [
+ ("Data1", wintypes.DWORD),
+ ("Data2", wintypes.WORD),
+ ("Data3", wintypes.WORD),
+ ("Data4", ctypes.c_ubyte * 8),
+ ]
+
+ data1, data2, data3, data4 = folder
+ folder_id = _GUID(data1, data2, data3, (ctypes.c_ubyte * 8)(*data4))
+ shell32 = ctypes.WinDLL("shell32", use_last_error=True)
+ ole32 = ctypes.WinDLL("ole32", use_last_error=True)
+ shell32.SHGetKnownFolderPath.argtypes = [
+ ctypes.POINTER(_GUID),
+ wintypes.DWORD,
+ wintypes.HANDLE,
+ ctypes.POINTER(ctypes.c_wchar_p),
+ ]
+ shell32.SHGetKnownFolderPath.restype = ctypes.c_long
+ ole32.CoTaskMemFree.argtypes = [ctypes.c_void_p]
+ ole32.CoTaskMemFree.restype = None
+ out = ctypes.c_wchar_p()
+ if shell32.SHGetKnownFolderPath(ctypes.byref(folder_id), 0, None, ctypes.byref(out)) != 0:
+ return None
+ try:
+ return Path(out.value) if out.value else None
+ finally:
+ ole32.CoTaskMemFree(out)
+
+
+__all__ = ["downloads_dir", "pictures_dir", "windows_known_folder", "xdg_user_dir"]
diff --git a/jarvis/ui/web/downloads_routes.py b/jarvis/ui/web/downloads_routes.py
index 2670d443c4..1637e70bf5 100644
--- a/jarvis/ui/web/downloads_routes.py
+++ b/jarvis/ui/web/downloads_routes.py
@@ -6,8 +6,9 @@ defaulting to ``False`` — its EdgeChromium handler then *silently cancels* eve
browser download (blob ``<a download>``, ``Content-Disposition: attachment``).
So the client-side download that works in a plain browser produces a "success"
toast but no file on the desktop. To put a file where the user expects it, the
-backend writes it directly to ``~/Downloads`` (cross-platform via
-``Path.home()``) and reports the absolute path back for the toast.
+backend writes it directly to the user's Downloads folder
+(:func:`jarvis.platform.user_dirs.downloads_dir`: the Windows known folder, the
+XDG download folder on Linux) and reports the absolute path back for the toast.
This mirrors the Outputs view, which already takes the native path on the
desktop (``open_path.reveal_in_folder`` / ``open_file``) instead of a browser
@@ -44,7 +45,7 @@ from typing import Any
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel, Field
-from jarvis.platform import detect_platform
+from jarvis.platform import detect_platform, user_dirs
# Reuse the proven collision-avoidance helper from the sessions save path
# instead of duplicating it (the two save flows share the same ~/Downloads
@@ -133,7 +134,7 @@ async def save_to_downloads(
raise HTTPException(status_code=413, detail="file-too-large")
filename = _safe_basename(body.filename)
- downloads = Path.home() / "Downloads"
+ downloads = user_dirs.downloads_dir()
downloads.mkdir(parents=True, exist_ok=True)
target = _avoid_collision(downloads / filename)
@@ -176,7 +177,7 @@ def _resolve_saved_file(path_str: str) -> Path:
p = Path(path_str).resolve()
except OSError as exc:
raise HTTPException(status_code=400, detail="invalid-path") from exc
- downloads = (Path.home() / "Downloads").resolve()
+ downloads = user_dirs.downloads_dir().resolve()
if p != downloads and downloads not in p.parents:
raise HTTPException(status_code=403, detail="path-outside-downloads")
if not p.is_file():
diff --git a/tests/integration/test_downloads_routes.py b/tests/integration/test_downloads_routes.py
index e4ed59ed0d..66349b3028 100644
--- a/tests/integration/test_downloads_routes.py
+++ b/tests/integration/test_downloads_routes.py
@@ -22,13 +22,17 @@ def _client(native: bool, home: Path) -> TestClient:
app.state.native_file_actions = native
app.include_router(downloads_router)
client = TestClient(app)
- # Both Path.home() (in the route) resolve to the temp home.
+ # The route's Downloads folder resolves into the temp home.
return client
@pytest.fixture
def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ # Windows asks the known-folder API, which ignores Path.home().
+ monkeypatch.setattr(
+ "jarvis.platform.user_dirs.downloads_dir", lambda: tmp_path / "Downloads"
+ )
return tmp_path
diff --git a/tests/unit/platform/test_user_dirs.py b/tests/unit/platform/test_user_dirs.py
new file mode 100644
index 0000000000..c287a92656
--- /dev/null
+++ b/tests/unit/platform/test_user_dirs.py
@@ -0,0 +1,62 @@
+"""Downloads and Pictures resolve to the folder the OS names, on every OS."""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+from jarvis.platform import user_dirs
+
+
+def linux_home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ home = tmp_path / "home"
+ (home / ".config").mkdir(parents=True)
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(Path, "home", lambda: home)
+ monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)
+
+ def write(lines: str) -> Path:
+ (home / ".config" / "user-dirs.dirs").write_text(lines, encoding="utf-8")
+ return home
+
+ return write
+
+
+def test_a_spanish_linux_desktop_saves_into_descargas(linux_home) -> None:
+ home = linux_home('XDG_DOWNLOAD_DIR="$HOME/Descargas"\nXDG_PICTURES_DIR="$HOME/Imágenes"\n')
+ assert user_dirs.downloads_dir() == home / "Descargas"
+ assert user_dirs.pictures_dir() == home / "Imágenes"
+
+
+def test_a_folder_pointed_at_home_falls_back(linux_home) -> None:
+ home = linux_home('XDG_DOWNLOAD_DIR="$HOME/"\nXDG_PICTURES_DIR="$HOME"\n')
+ assert user_dirs.downloads_dir() == home / "Downloads"
+ # Pictures keeps its old meaning: a removed folder means "none".
+ assert user_dirs.pictures_dir() is None
+
+
+def test_without_user_dirs_the_plain_folders_are_used(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "nowhere"))
+ assert user_dirs.downloads_dir() == tmp_path / "Downloads"
+ assert user_dirs.pictures_dir() == tmp_path / "Pictures"
+
+
+def test_macos_uses_the_home_folders(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ assert user_dirs.downloads_dir() == tmp_path / "Downloads"
+ assert user_dirs.pictures_dir() == tmp_path / "Pictures"
+
+
[email protected](sys.platform != "win32", reason="Windows known-folder API")
+def test_windows_asks_the_known_folder_api() -> None:
+ downloads = user_dirs.downloads_dir()
+ assert downloads.is_absolute()
+ assert user_dirs.windows_known_folder(user_dirs._DOWNLOADS_ID) == downloads # noqa: SLF001