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(wiki): recognize nested Obsidian vaults
Ruben Lütkef9a8717b3a69
diff --git a/jarvis/setup/obsidian.py b/jarvis/setup/obsidian.pyindex a31f61d5a9..bdfdcbc3e0 100644--- a/jarvis/setup/obsidian.py+++ b/jarvis/setup/obsidian.py@@ -317,17 +317,43 @@ def _normalize_for_compare(path: Path) -> str:def is_vault_registered(vaults: list[VaultEntry], expected_vault_path: Path) -> bool:- """Return True iff ``expected_vault_path`` is among the registered vaults.+ """Return True when Obsidian can reach ``expected_vault_path``.- Comparison is case-insensitive (Windows) and trailing-separator- tolerant. Both sides are passed through ``Path.resolve()`` so- relative-vs-absolute inputs match correctly.+ An exact match is reachable, but so is a Jarvis-owned subdirectory inside+ an already-registered user vault. The latter is the shape created by the+ setup wizard's ``mode="existing"`` flow: Obsidian registers+ ``<user-vault>`` while Jarvis writes under ``<user-vault>/Jarvis``.+ """+ return find_registered_vault(vaults, expected_vault_path) is not None+++def find_registered_vault(+ vaults: list[VaultEntry], expected_vault_path: Path,+) -> VaultEntry | None:+ """Return the most specific registered vault containing ``expected``.++ This mirrors Obsidian's URI ``path`` resolution rule and keeps status+ detection aligned with deep links when nested vault candidates exist."""expected_norm = _normalize_for_compare(expected_vault_path)+ matches: list[tuple[int, VaultEntry]] = []for entry in vaults:- if _normalize_for_compare(entry.path) == expected_norm:- return True- return False+ registered_norm = _normalize_for_compare(entry.path)+ try:+ contains = (+ registered_norm == expected_norm+ or os.path.commonpath((registered_norm, expected_norm)) == registered_norm+ )+ except ValueError:+ # Different Windows drives (or otherwise incompatible roots) cannot+ # contain one another.+ contains = False+ if contains:+ matches.append((len(registered_norm), entry))+ if not matches:+ return None+ matches.sort(key=lambda item: item[0], reverse=True)+ return matches[0][1]# ---------------------------------------------------------------------------diff --git a/jarvis/ui/web/frontend/src/__tests__/obsidian.test.ts b/jarvis/ui/web/frontend/src/__tests__/obsidian.test.tsindex 7f443e2e27..abcb17a805 100644--- a/jarvis/ui/web/frontend/src/__tests__/obsidian.test.ts+++ b/jarvis/ui/web/frontend/src/__tests__/obsidian.test.ts@@ -1,31 +1,29 @@import { describe, expect, it } from "vitest";-import { buildObsidianUrl, VAULT_NAME } from "@/lib/obsidian";+import { buildObsidianUrl } from "@/lib/obsidian";describe("buildObsidianUrl", () => {it("builds the expected URL for a simple vault-relative path", () => {- const url = buildObsidianUrl("entities/harald.md");+ const url = buildObsidianUrl("C:\\Notes\\Jarvis", "entities/harald.md");expect(url).toBe(- `obsidian://open?vault=${encodeURIComponent(VAULT_NAME)}&file=${encodeURIComponent(- "entities/harald.md",- )}`,+ `obsidian://open?path=${encodeURIComponent("C:\\Notes\\Jarvis\\entities\\harald.md")}`,);});it("omits the file param when the path is empty (opens vault root)", () => {- const url = buildObsidianUrl("");- expect(url).toBe(`obsidian://open?vault=${encodeURIComponent(VAULT_NAME)}`);- expect(url).not.toContain("&file=");+ const url = buildObsidianUrl("/home/user/Notes/Jarvis/");+ expect(url).toBe(+ `obsidian://open?path=${encodeURIComponent("/home/user/Notes/Jarvis")}`,+ );});it("encodes spaces as %20 (real Obsidian round-trip)", () => {- const url = buildObsidianUrl("entities/my note.md");+ const url = buildObsidianUrl("/home/user/My Vault/Jarvis", "entities/my note.md");expect(url).toContain("my%20note.md");- // sanity-check the vault portion is also encoded- expect(url.startsWith("obsidian://open?vault=")).toBe(true);+ expect(url.startsWith("obsidian://open?path=")).toBe(true);});it("encodes German umlauts in the file path", () => {- const url = buildObsidianUrl("entities/küche.md"); // i18n-allow: German umlaut is the content under test+ const url = buildObsidianUrl("/notes/Jarvis", "entities/küche.md"); // i18n-allow: German umlaut is the content under test// U+00FC -> %C3%BC under encodeURIComponentexpect(url).toContain("k%C3%BCche.md");});diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsxindex 4202c4ba0e..35b1f87bff 100644--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianButton.tsx@@ -9,7 +9,7 @@ import { useT } from "@/i18n";* Per-page "Open in Obsidian" button.** Hands editing off to the real Obsidian desktop app via the- * `obsidian://open?vault=…&file=…` URL scheme. There is no reliable way+ * `obsidian://open?path=…` URL scheme. There is no reliable way* to detect from the browser whether the URL handler is registered, so* we fire a fallback toast 800 ms after the click to inform the user* what was attempted — if Obsidian launched, they'll see the file open;@@ -19,6 +19,8 @@ import { useT } from "@/i18n";* "Open vault in Obsidian" button in the wiki tab header).*/export interface ObsidianButtonProps {+ /** Absolute configured Jarvis vault root. */+ vaultRoot: string;/** Vault-relative POSIX path, e.g. `"entities/harald.md"`. Empty opens the root. */vaultRelPath: string;/** Use the compact "sm" button size — useful inside dense panels. */@@ -31,6 +33,7 @@ export interface ObsidianButtonProps {export const FALLBACK_TOAST_DELAY_MS = 800;export function ObsidianButton({+ vaultRoot,vaultRelPath,size = "sm",label,@@ -39,7 +42,7 @@ export function ObsidianButton({const pushToast = useEventStore((s) => s.pushToast);const handleClick = useCallback(() => {- const url = buildObsidianUrl(vaultRelPath);+ const url = buildObsidianUrl(vaultRoot, vaultRelPath);// Trigger the URL handler. We use `window.location.assign` rather// than `window.open` because the latter is blocked by popup blockers// and pywebview's window-open hook; `assign` invokes the protocol@@ -73,7 +76,7 @@ export function ObsidianButton({);}}, FALLBACK_TOAST_DELAY_MS);- }, [pushToast, vaultRelPath]);+ }, [pushToast, t, vaultRelPath, vaultRoot]);const buttonLabel =label ?? (vaultRelPath ? t("obsidian_button.open_in_obsidian") : t("obsidian_button.open_vault_in_obsidian"));@@ -85,7 +88,7 @@ export function ObsidianButton({size={size}onClick={handleClick}className="gap-1.5"- title={vaultRelPath || "obsidian-vault"}+ title={vaultRelPath || vaultRoot}><ExternalLink className="h-3.5 w-3.5" aria-hidden /><span>{buttonLabel}</span>diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.test.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.test.tsxindex bdfb4bb429..a84c3f429f 100644--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.test.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.test.tsx@@ -259,10 +259,9 @@ describe("ObsidianSetupDialog", () => {);fireEvent.click(screen.getByTestId("obsidian-setup-launch"));expect(lastHref).not.toBeNull();- expect(lastHref!.startsWith("obsidian://open?vault=")).toBe(true);- // The vault path ends in "obsidian-vault" — that final segment must- // appear (URL-encoded) in the href.- expect(lastHref!).toContain(encodeURIComponent("obsidian-vault"));+ expect(lastHref!).toBe(+ `obsidian://open?path=${encodeURIComponent(STATUS_OK.vault_path)}`,+ );} finally {Object.defineProperty(window, "location", {configurable: true,@@ -465,8 +464,9 @@ describe("ObsidianSetupDialog", () => {});fireEvent.click(screen.getByTestId("obsidian-setup-launch"));expect(lastHref).not.toBeNull();- expect(lastHref!).toContain(encodeURIComponent(VAULTS[1].name));- expect(lastHref!).not.toContain(encodeURIComponent("obsidian-vault"));+ expect(lastHref!).toBe(+ `obsidian://open?path=${encodeURIComponent("C:/Users/Administrator/Work/Jarvis")}`,+ );} finally {Object.defineProperty(window, "location", {configurable: true,diff --git a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsxindex 4bbaceba2a..4ffa77b8bf 100644--- a/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/ObsidianSetupDialog.tsx@@ -11,7 +11,7 @@* Jarvis vault" (default) or "use my existing vault", the latter fed* by ``GET /api/setup/obsidian/vaults`` and enabled only once that* list is non-empty.- * 3. Live-test the ``obsidian://open?vault=…`` URL scheme. Also shows the+ * 3. Live-test the ``obsidian://open?path=…`` URL scheme. Also shows the* ``active_vault_root`` returned by step 2 and, when the backend* reports ``restart_required`` (always true for the "existing" vault* choice — the running wiki index still targets the old vault root@@ -26,7 +26,7 @@* Sub-Agent 6 will wire `onComplete` into the first-run flag; we expose* the slot but do not act on it here.*/-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { Check, ExternalLink, Loader2, X } from "lucide-react";import { Button } from "@/components/ui/button";@@ -34,6 +34,7 @@ import { cn } from "@/lib/utils";import { useT } from "@/i18n";import type { ObsidianStatus } from "@/types/setup";import {+ buildObsidianUrl,fetchObsidianVaults,registerObsidianVault,type ObsidianVaultInfo,@@ -76,26 +77,6 @@ interface RegisterResponse {const RESTART_URL = "/api/settings/restart-app";-/**- * Extract the final segment of the vault path so the- * ``obsidian://open?vault=`` URL scheme can target it by name.- *- * Handles both POSIX and Windows separators. Decodes percent-encoding- * once because the path comes through ``str(Path)`` on the backend and- * is otherwise opaque.- */-function deriveVaultName(vaultPath: string): string {- if (!vaultPath) return "";- const trimmed = vaultPath.replace(/[\\/]+$/, "");- const segments = trimmed.split(/[\\/]/);- const last = segments[segments.length - 1] ?? "";- try {- return decodeURIComponent(last);- } catch {- return last;- }-}-/** Decide which step should be the initial active step. */function decideInitialStep(status: ObsidianStatus): StepId {if (!status.installed) return 1;@@ -410,10 +391,8 @@ export function ObsidianSetupDialog({}}, []);- const vaultName = useMemo(() => deriveVaultName(vaultPath), [vaultPath]);-const handleLaunchObsidian = useCallback(() => {- const url = `obsidian://open?vault=${encodeURIComponent(vaultName)}`;+ const url = buildObsidianUrl(activeVaultRoot ?? vaultPath);// Use ``location.href`` rather than ``window.open`` — Chrome and// pywebview both block popups for custom URI schemes.try {@@ -422,7 +401,7 @@ export function ObsidianSetupDialog({// jsdom or sandboxed embed: nothing we can do, the failure message// shows up on the "It didn't work" branch anyway.}- }, [vaultName]);+ }, [activeVaultRoot, vaultPath]);const handleComplete = useCallback(() => {onComplete?.();diff --git a/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsx b/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsxindex 755b34f7d2..94be3cb2ef 100644--- a/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/PageHeader.tsx@@ -25,6 +25,7 @@ interface PageHeaderProps {kind: WikiKind;title: string;frontmatter: Record<string, string | string[]>;+ vaultRoot: string;vaultRelPath: string;}@@ -52,6 +53,7 @@ export function PageHeader({kind,title,frontmatter,+ vaultRoot,vaultRelPath,}: PageHeaderProps) {const pills = buildPills(frontmatter);@@ -97,7 +99,7 @@ export function PageHeader({<ObsidianButtonPlaceholder vaultRelPath={vaultRelPath} />}>- <ObsidianButton vaultRelPath={vaultRelPath} />+ <ObsidianButton vaultRoot={vaultRoot} vaultRelPath={vaultRelPath} /></Suspense></header>);diff --git a/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx b/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsxindex 5d4177c969..171c6c8075 100644--- a/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx+++ b/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx@@ -117,6 +117,7 @@ export function PageRenderer({ slug, onWikilinkClick }: PageRendererProps) {kind={kind}title={title}frontmatter={frontmatter}+ vaultRoot={treeQuery.data?.vault_root ?? ""}vaultRelPath={vaultRelPath}/>diff --git a/jarvis/ui/web/frontend/src/lib/obsidian.ts b/jarvis/ui/web/frontend/src/lib/obsidian.tsindex a634920ef3..cb4b183b34 100644--- a/jarvis/ui/web/frontend/src/lib/obsidian.ts+++ b/jarvis/ui/web/frontend/src/lib/obsidian.ts@@ -3,19 +3,11 @@* scheme plus the setup-wizard API (`GET /api/setup/obsidian/vaults`,* `POST /api/setup/obsidian/register`).*- * The `obsidian://open?vault=<vault>&file=<path>` URL handler is installed- * by Obsidian on the user's machine and opens the named file inside the- * matching vault. We cannot detect from the browser whether the handler- * is registered — the per-page button in `ObsidianButton.tsx` shows a- * fallback toast 800 ms after click as a defensive UX measure.- *- * The vault name is hard-coded to match the on-disk folder name- * `wiki/obsidian-vault/`. If the user renames the vault inside Obsidian,- * they must also rename the folder; we don't try to introspect.+ * `obsidian://open?path=<absolute-path>` asks Obsidian to find the most+ * specific registered vault containing the path. This works for both a+ * separate Jarvis vault and a `Jarvis/` directory inside an existing vault.*/-/** Vault name in Obsidian — matches the on-disk folder `wiki/obsidian-vault/`. */-export const VAULT_NAME = "obsidian-vault";/** One entry in the "use my existing vault" picker (spec A6). */export interface ObsidianVaultInfo {@@ -90,20 +82,25 @@ export async function registerObsidianVault(}/**- * Build an `obsidian://open` URL for a vault-relative file path.+ * Build an `obsidian://open` URL for an absolute vault or page path.*- * - When `vaultRelPath` is empty, the URL opens to the vault root.- * - The vault name and the file path are both URI-component-encoded so- * spaces, German umlauts, and other special characters round-trip- * correctly through Obsidian's URL handler.+ * - When `vaultRelPath` is empty, the URL targets the configured vault root.+ * - Windows and POSIX separators stay consistent.+ * - The absolute path is URI-component-encoded for a reliable round trip.*+ * @param vaultRoot - Absolute configured Jarvis vault root.* @param vaultRelPath - Vault-relative POSIX path such as* `"entities/harald.md"`. May be the empty string to open the root.*/-export function buildObsidianUrl(vaultRelPath: string): string {- const base = `obsidian://open?vault=${encodeURIComponent(VAULT_NAME)}`;- if (!vaultRelPath) {- return base;- }- return `${base}&file=${encodeURIComponent(vaultRelPath)}`;+export function buildObsidianUrl(+ vaultRoot: string,+ vaultRelPath = "",+): string {+ const root = vaultRoot.replace(/[\\/]+$/, "");+ const separator = root.includes("\\") ? "\\" : "/";+ const relative = vaultRelPath+ .replace(/^[\\/]+/, "")+ .replace(/[\\/]+/g, separator);+ const absolutePath = relative ? `${root}${separator}${relative}` : root;+ return `obsidian://open?path=${encodeURIComponent(absolutePath)}`;}diff --git a/jarvis/ui/web/frontend/src/views/WikiView.test.tsx b/jarvis/ui/web/frontend/src/views/WikiView.test.tsxindex 6f007aab36..77c39b8324 100644--- a/jarvis/ui/web/frontend/src/views/WikiView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/WikiView.test.tsx@@ -351,6 +351,7 @@ describe("PageHeader — frontmatter pills", () => {created: "2026-05-13",updated: "2026-05-13",}}+ vaultRoot="C:/vault/Jarvis"vaultRelPath="entities/harald.md"/>,);diff --git a/jarvis/ui/web/setup_routes.py b/jarvis/ui/web/setup_routes.pyindex 60bdd76df6..9a5754cf53 100644--- a/jarvis/ui/web/setup_routes.py+++ b/jarvis/ui/web/setup_routes.py@@ -39,6 +39,7 @@ from pydantic import BaseModelfrom jarvis.memory.wiki.vault_root import resolve_vault_rootfrom jarvis.setup.obsidian import (detect_obsidian,+ find_registered_vault,is_vault_registered,read_obsidian_vaults,register_vault,@@ -155,6 +156,14 @@ def _resolve_vault_path(request: Request) -> Path:return resolve_vault_root(raw).path+def _read_vaults_for_request(request: Request):+ """Read the request-scoped Obsidian index without touching real test state."""+ override = getattr(request.app.state, "obsidian_config_path", None)+ if override is None:+ return read_obsidian_vaults()+ return read_obsidian_vaults(Path(override))++def _write_vault_root_config(values: dict) -> None:"""Persist ``[wiki_integration].vault_root`` atomically (AP-7).@@ -228,7 +237,7 @@ def obsidian_status(request: Request) -> ObsidianStatusResponse:try:detection = detect_obsidian()- vaults_state = read_obsidian_vaults()+ vaults_state = _read_vaults_for_request(request)registered = is_vault_registered(vaults_state.vaults, vault_path)except Exception as exc: # noqa: BLE001 — UI must keep workinglog.warning("setup_route_status_failed: %s", exc, exc_info=True)@@ -332,6 +341,23 @@ def obsidian_register(active_vault_root=str(_resolve_vault_path(request)),restart_required=False,)+ try:+ vaults_state = _read_vaults_for_request(request)+ registered_parent = find_registered_vault(vaults_state.vaults, target_vault)+ except ValueError as exc:+ return ObsidianRegisterResponse(+ status="config_missing",+ error=str(exc),+ active_vault_root=str(_resolve_vault_path(request)),+ restart_required=False,+ )+ if registered_parent is None:+ return ObsidianRegisterResponse(+ status="config_missing",+ error="existing vault is not registered in Obsidian",+ active_vault_root=str(_resolve_vault_path(request)),+ restart_required=False,+ )jarvis_root = target_vault / "Jarvis"# ``dry_run`` previews the would-be vault root without touching disk# or config — same contract the ``separate`` branch gives the flag.@@ -353,7 +379,15 @@ def obsidian_register(vault_path = _resolve_vault_path(request)try:- result = register_vault(vault_path, dry_run=dry_run)+ override = getattr(request.app.state, "obsidian_config_path", None)+ if override is None:+ result = register_vault(vault_path, dry_run=dry_run)+ else:+ result = register_vault(+ vault_path,+ config_path=Path(override),+ dry_run=dry_run,+ )except Exception as exc: # noqa: BLE001 — translate to 500 with envelopelog.warning("setup_route_register_failed: %s", exc, exc_info=True)raise HTTPException(diff --git a/tests/unit/setup/test_obsidian_detector.py b/tests/unit/setup/test_obsidian_detector.pyindex e8d0405262..7c65c35461 100644--- a/tests/unit/setup/test_obsidian_detector.py+++ b/tests/unit/setup/test_obsidian_detector.py@@ -14,12 +14,12 @@ from pathlib import Pathimport pytest-from jarvis.setup import obsidian as modfrom jarvis.setup.obsidian import (ObsidianDetection,ObsidianVaultsState,VaultEntry,detect_obsidian,+ find_registered_vault,is_vault_registered,read_obsidian_vaults,)@@ -317,6 +317,30 @@ def test_is_vault_registered_empty_vault_list() -> None:assert is_vault_registered([], Path(r"C:\anything")) is False+def test_is_vault_registered_for_subdirectory_of_registered_vault(+ tmp_path: Path,+) -> None:+ """Existing-vault mode keeps Jarvis in a reachable child directory."""+ parent = tmp_path / "Notes"+ expected = parent / "Jarvis"+ vaults = [VaultEntry(id="parent", path=parent)]++ assert is_vault_registered(vaults, expected) is True+ assert find_registered_vault(vaults, expected) == vaults[0]+++def test_find_registered_vault_prefers_most_specific_container(tmp_path: Path) -> None:+ root = tmp_path / "Notes"+ nested = root / "Team"+ expected = nested / "Jarvis"+ vaults = [+ VaultEntry(id="root", path=root),+ VaultEntry(id="nested", path=nested),+ ]++ assert find_registered_vault(vaults, expected) == vaults[1]++# ---------------------------------------------------------------------------# _default_obsidian_config_path()# ---------------------------------------------------------------------------diff --git a/tests/unit/ui/web/test_setup_routes_vault_choice.py b/tests/unit/ui/web/test_setup_routes_vault_choice.pyindex 704a33830a..d54814c72e 100644--- a/tests/unit/ui/web/test_setup_routes_vault_choice.py+++ b/tests/unit/ui/web/test_setup_routes_vault_choice.py@@ -13,6 +13,7 @@ from pathlib import Pathfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from jarvis.setup.obsidian import ObsidianDetectionfrom jarvis.ui.web import setup_routes@@ -46,6 +47,41 @@ def test_vault_list_returns_registered_vaults(tmp_path):assert body["vaults"][0]["path"] == str(user_vault)+def test_status_accepts_jarvis_subdirectory_inside_registered_vault(+ tmp_path, monkeypatch,+):+ user_vault = tmp_path / "MyVault"+ user_vault.mkdir()+ app = _app(tmp_path, {"vaults": {"abc123": {"path": str(user_vault)}}})+ app.state.config.wiki_integration.vault_root = user_vault / "Jarvis"+ monkeypatch.setattr(+ setup_routes,+ "detect_obsidian",+ lambda: ObsidianDetection(installed=True, version="1.0"),+ )++ body = TestClient(app).get("/api/setup/obsidian/status").json()++ assert body["vault_registered"] is True+ assert body["recommended_action"] == "ok"+++def test_separate_register_uses_injected_obsidian_config(tmp_path, monkeypatch):+ app = _app(tmp_path, {"vaults": {}})+ monkeypatch.setattr(+ setup_routes,+ "detect_obsidian",+ lambda: ObsidianDetection(installed=True, version="1.0"),+ )++ response = TestClient(app).post("/api/setup/obsidian/register")++ assert response.status_code == 200+ state = json.loads(app.state.obsidian_config_path.read_text(encoding="utf-8"))+ registered_paths = {entry["path"] for entry in state["vaults"].values()}+ assert str((tmp_path / "jarvis-vault").resolve()) in registered_paths++def test_register_existing_mode_points_vault_root_into_jarvis_subfolder(tmp_path, monkeypatch,):