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(chat): open local file links instead of reloading the window

rubenluetke10-beep75e8d7978e2c
diff --git a/jarvis/platform/open_path.py b/jarvis/platform/open_path.py
index bf60a548c0..8291fdfee5 100644
--- a/jarvis/platform/open_path.py
+++ b/jarvis/platform/open_path.py
@@ -5,14 +5,16 @@ thin per-OS dispatch with a graceful no-op fallback when no display is present
(headless VPS), mirroring jarvis/plugins/tool/app_resolver.py. Import-cleanliness
(HN-7): only stdlib at module scope; no platform-only package imported here.
"""
+
from __future__ import annotations
import logging
import os
+import re
import shutil
import subprocess
from pathlib import Path
-from urllib.parse import urlparse
+from urllib.parse import unquote, urlparse
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
from jarvis.platform import detect_platform
@@ -284,7 +286,7 @@ def _open_url_windows(url: str) -> bool:
os.startfile(url) # type: ignore[attr-defined] # noqa: S606
log.warning(
"open_url: no browser exe found; handed off to ShellExecute "
- "(cannot verify it opened) for %s", host
+ "(cannot verify it opened) for %s", host,
)
return True # best-effort; ShellExecute may open nothing for a dead handler
except OSError as exc:
@@ -422,9 +424,156 @@ def open_url(url: str) -> bool:
return _open_url_linux(url)
+# A chat link must never launch a program. Media, documents and folders open
+# with the default app; these suffixes are programs, installers or scripts.
+_REFUSED_CHAT_SUFFIXES = frozenset(
+ {
+ ".exe",
+ ".bat",
+ ".cmd",
+ ".com",
+ ".scr",
+ ".pif",
+ ".ps1",
+ ".psc1",
+ ".psm1",
+ ".psd1",
+ ".vbs",
+ ".vbe",
+ ".js",
+ ".jse",
+ ".wsf",
+ ".wsh",
+ ".wsc",
+ ".msi",
+ ".msp",
+ ".mst",
+ ".dll",
+ ".cpl",
+ ".jar",
+ ".sh",
+ ".bash",
+ ".command",
+ ".zsh",
+ ".ksh",
+ ".dmg",
+ ".pkg",
+ ".deb",
+ ".rpm",
+ ".appimage",
+ ".lnk",
+ ".scf",
+ ".url",
+ ".hta",
+ ".reg",
+ ".inf",
+ ".app",
+ ".apk",
+ ".ipa",
+ ".py",
+ ".pyw",
+ ".rb",
+ ".pl",
+ ".php",
+ }
+)
+
+
+class ChatOpenRejected(ValueError):
+ """The chat link is not a file or folder this computer should open."""
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+ super().__init__(reason)
+
+
+def _path_from_file_uri(value: str) -> str | None:
+ """``file:///C:/x`` / ``file:///home/x`` → a native path, else None.
+
+ A host other than empty or ``localhost`` is a network location and is
+ refused. ``file://C:/x`` (the drive letter parsed as the host) is repaired.
+ """
+ parsed = urlparse(value)
+ host = parsed.netloc
+ path = unquote(parsed.path or "")
+ if re.fullmatch(r"[A-Za-z]:", host):
+ path = host + path
+ elif host and host.lower() != "localhost":
+ return None
+ if re.match(r"^/[A-Za-z]:[\\/]", path):
+ path = path[1:]
+ return path or None
+
+
+def chat_link_path(raw: str) -> str | None:
+ """Absolute local path inside a chat link, or None when it is not one.
+
+ Accepts a Windows drive path, a POSIX absolute path, a ``~/`` path, and a
+ ``file:`` URI with no remote host. Relative paths, UNC shares and web URLs
+ are not local opens. Does not check that the path exists.
+ """
+ text = raw.strip()
+ if len(text) >= 2 and text[0] == "<" and text[-1] == ">":
+ text = text[1:-1].strip()
+ if not text or any(ch in text for ch in "\x00\r\n"):
+ return None
+ lowered = text.lower()
+ if lowered.startswith(("http://", "https://", "javascript:", "data:", "mailto:")):
+ return None
+ if lowered.startswith("file:"):
+ converted = _path_from_file_uri(text)
+ if not converted:
+ return None
+ text = converted
+ if text.startswith("\\\\") or text.startswith("//"):
+ return None
+ if text.startswith("~/") or text.startswith("~\\"):
+ return text
+ if re.match(r"^[A-Za-z]:[\\/]", text):
+ return text
+ if text.startswith("/") and text != "/api" and not text.startswith("/api/"):
+ return text
+ return None
+
+
+def prepare_chat_open(raw: str) -> Path:
+ """Existing local file or folder a chat link may open.
+
+ Raises :class:`ChatOpenRejected`. A Windows drive path is only accepted
+ on Windows, so resolving it cannot land inside another operating system's
+ working directory.
+ """
+ native = chat_link_path(raw)
+ if native is None:
+ raise ChatOpenRejected("not-a-local-path")
+ if native.startswith("~"):
+ native = str(Path(native).expanduser())
+ drive = re.match(r"^[A-Za-z]:[\\/]", native) is not None
+ if drive and os.name != "nt":
+ raise ChatOpenRejected("not-found")
+ path = Path(native)
+ if not path.is_absolute():
+ raise ChatOpenRejected("not-a-local-path")
+ try:
+ target = path.resolve()
+ except OSError as exc:
+ raise ChatOpenRejected("invalid-path") from exc
+ if not target.exists() or not (target.is_file() or target.is_dir()):
+ raise ChatOpenRejected("not-found")
+ suffix = target.suffix.lower()
+ if (target.is_file() and suffix in _REFUSED_CHAT_SUFFIXES) or (
+ target.is_dir() and suffix == ".app"
+ ):
+ raise ChatOpenRejected("refused-program")
+ return target
+
+
__all__ = [
+ "ChatOpenRejected",
+ "chat_link_path",
"open_file",
"open_file_with",
"open_url",
+ "prepare_chat_open",
"reveal_in_folder",
]
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx
index 105cfa9b88..455e09c2e0 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx
@@ -1,5 +1,5 @@
import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { ChatMarkdown, mediaKind, normalizeMediaMarkup, safeMediaUrl } from "./ChatMarkdown";
afterEach(cleanup);
@@ -124,4 +124,42 @@ describe("shared chat media", () => {
expect(safeMediaUrl(url)).toBeNull();
expect(mediaKind(url)).toBeNull();
});
+
+ it("opens a local file link on this computer instead of navigating", () => {
+ const fetchMock = vi.fn(async () => ({ ok: true, json: async () => ({ opened: true }) }));
+ vi.stubGlobal("fetch", fetchMock);
+ render(<ChatMarkdown text="[Clip](C:/Users/me/Downloads/Clip.mp4)" />);
+ const link = screen.getByRole("link", { name: "Clip" });
+ expect(link.getAttribute("href")).toBe("#jarvis-local=" + encodeURIComponent("C:/Users/me/Downloads/Clip.mp4"));
+ fireEvent.click(link);
+ expect(fetchMock).toHaveBeenCalledWith("/api/settings/open-path", expect.objectContaining({
+ method: "POST",
+ body: JSON.stringify({ path: "C:/Users/me/Downloads/Clip.mp4" }),
+ }));
+ vi.unstubAllGlobals();
+ });
+
+ it("does not let a bare filename navigate the window", () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ render(<ChatMarkdown text="[Clip](Clip.mp4)" />);
+ const link = screen.getByRole("link", { name: "Clip" });
+ const event = new MouseEvent("click", { bubbles: true, cancelable: true });
+ link.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(true);
+ expect(fetchMock).not.toHaveBeenCalled();
+ vi.unstubAllGlobals();
+ });
+
+ it("still opens a web link outside the window", () => {
+ const fetchMock = vi.fn(async () => ({ ok: true, json: async () => ({ opened: true }) }));
+ vi.stubGlobal("fetch", fetchMock);
+ render(<ChatMarkdown text="[Notes](https://example.test/notes)" />);
+ fireEvent.click(screen.getByRole("link", { name: "Notes" }));
+ expect(fetchMock).toHaveBeenCalledWith("/api/settings/open-external", expect.objectContaining({
+ method: "POST",
+ body: JSON.stringify({ url: "https://example.test/notes" }),
+ }));
+ vi.unstubAllGlobals();
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx
index fedadc5e3b..434fd2c6c6 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx
@@ -1,11 +1,13 @@
import { Children, createContext, lazy, Suspense, useContext, useEffect, useMemo, useRef, useState } from "react";
-import ReactMarkdown, { defaultUrlTransform, type Components } from "react-markdown";
+import ReactMarkdown, { type Components } from "react-markdown";
import remarkGfm from "remark-gfm";
import { AlertCircle, Download, Maximize2, X } from "lucide-react";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { openExternalUrl } from "@/lib/openExternal";
+import { openLocalPath } from "@/lib/openLocalPath";
import { readFence, visualFenceLanguage } from "@/lib/visualFence";
+import { chatLinkAction, chatUrlTransform, localPathFromChatHref } from "./chatLinks";
import { parseToolResult, ToolResultCard } from "./ToolResultCard";
import * as Dialog from "@radix-ui/react-dialog";
@@ -144,18 +146,31 @@ export function MediaPreview({ src, label, kind }: { src: string; label: string;
const ImageKeysContext = createContext<ReadonlySet<string>>(new Set());
+// A file or folder address must not be loaded in this window: an empty href
+// reloads the page, and a relative name is served back as the app itself.
+function onChatLinkClick(event: { preventDefault(): void }, href: string) {
+ const action = chatLinkAction(href);
+ if (action.type === "allow") return;
+ event.preventDefault();
+ if (action.type === "local") void openLocalPath(action.path);
+ else if (action.type === "external") void openExternalUrl(action.url);
+}
+
// Stable component identities are essential: changing these on each streamed
// token would unmount videos, reset playback and discard image error state.
const MARKDOWN_COMPONENTS: Components = {
- img: ({ src = "", alt = "image" }) => <MediaPreview src={src} label={alt || "image"} kind={mediaKind(src) ?? "image"} />,
+ img: ({ src = "", alt = "image" }) => {
+ const local = localPathFromChatHref(src);
+ if (local) return <a href={src} title={local} onClick={event => onChatLinkClick(event, src)}>{alt || local}</a>;
+ return <MediaPreview src={src} label={alt || "image"} kind={mediaKind(src) ?? "image"} />;
+ },
a: function MediaLink({ href = "", children }) {
const imageKeys = useContext(ImageKeysContext);
const kind = mediaKind(href);
const label = Children.toArray(children).filter(child => typeof child === "string").join("") || kind || "media";
if (kind && !imageKeys.has(assetKey(href))) return <MediaPreview src={href} label={label} kind={kind} />;
- return <a href={href} onClick={event => {
- if (/^https?:\/\//i.test(href)) { event.preventDefault(); void openExternalUrl(href); }
- }}>{children}</a>;
+ const local = localPathFromChatHref(href);
+ return <a href={href} title={local || undefined} onClick={event => onChatLinkClick(event, href)}>{children}</a>;
},
pre: ({ children, node: _node, ...props }) => {
const fence = readFence(children);
@@ -176,7 +191,7 @@ export function ChatMarkdown({ text, className }: { text: string; className?: st
const imageKeys = useMemo(() => new Set(Array.from(body.matchAll(/!\[[^\]]*\]\(<?([^)>]+)>?\)/g), match => assetKey(match[1]))), [body]);
return <div className={cn("min-w-0 [overflow-wrap:anywhere]", className)}>
<ImageKeysContext.Provider value={imageKeys}>
- <ReactMarkdown remarkPlugins={[remarkGfm]} urlTransform={url => url.startsWith("data:") ? safeMediaUrl(url) ?? "" : defaultUrlTransform(url)} components={MARKDOWN_COMPONENTS}>{body}</ReactMarkdown>
+ <ReactMarkdown remarkPlugins={[remarkGfm]} urlTransform={url => url.startsWith("data:") ? safeMediaUrl(url) ?? "" : chatUrlTransform(url)} components={MARKDOWN_COMPONENTS}>{body}</ReactMarkdown>
</ImageKeysContext.Provider>
</div>;
}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.test.ts
new file mode 100644
index 0000000000..22223c72a8
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+import { chatLinkAction, chatUrlTransform, nativePathFromMarkdownUrl } from "./chatLinks";
+
+describe("chat file links", () => {
+ it.each([
+ ["C:/Users/me/Clip.mp4", "C:/Users/me/Clip.mp4"],
+ ["C:\\Users\\me\\Clip.mp4", "C:\\Users\\me\\Clip.mp4"],
+ ["file:///C:/Users/me/My%20Clip.mp4", "C:/Users/me/My Clip.mp4"],
+ ["file://C:/Users/me/Clip.mp4", "C:/Users/me/Clip.mp4"],
+ ["file://localhost/home/me/clip.mp4", "/home/me/clip.mp4"],
+ ["~/Downloads/clip.mp4", "~/Downloads/clip.mp4"],
+ ["/home/me/Videos/clip.mp4", "/home/me/Videos/clip.mp4"],
+ ])("keeps %s as a local path", (raw, expected) => {
+ expect(nativePathFromMarkdownUrl(raw)).toBe(expected);
+ expect(chatUrlTransform(raw)).toBe("#jarvis-local=" + encodeURIComponent(expected));
+ });
+
+ it.each([
+ "clip.mp4",
+ "https://example.test/clip.mp4",
+ "javascript:alert(1)",
+ "file://server/share/clip.mp4",
+ "/api/outputs/run/files/clip.mp4/download",
+ ])("does not treat %s as a local file", raw => {
+ expect(nativePathFromMarkdownUrl(raw)).toBeNull();
+ });
+
+ it("opens a preserved local path and still sends web links out", () => {
+ const href = chatUrlTransform("C:/Users/me/Clip.mp4");
+ expect(chatLinkAction(href)).toEqual({ type: "local", path: "C:/Users/me/Clip.mp4" });
+ expect(chatLinkAction("https://example.test/clip.mp4")).toEqual({
+ type: "external",
+ url: "https://example.test/clip.mp4",
+ });
+ });
+
+ it("refuses to navigate the window for an empty or relative link", () => {
+ expect(chatLinkAction("")).toEqual({ type: "stay" });
+ expect(chatLinkAction("Clip.mp4")).toEqual({ type: "stay" });
+ expect(chatLinkAction("javascript:alert(1)")).toEqual({ type: "stay" });
+ expect(chatLinkAction("/api/outputs/run/download")).toEqual({ type: "allow" });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.ts b/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.ts
new file mode 100644
index 0000000000..eebc4a3c7a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.ts
@@ -0,0 +1,89 @@
+import { defaultUrlTransform } from "react-markdown";
+
+const LOCAL_PREFIX = "#jarvis-local=";
+
+export type ChatLinkAction =
+ | { type: "local"; path: string }
+ | { type: "external"; url: string }
+ | { type: "stay" }
+ | { type: "allow" };
+
+function decodePath(value: string): string {
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ return value;
+ }
+}
+
+/** `file:///C:/x` and `file:///home/x` become a native path. Network hosts do not. */
+function pathFromFileUri(value: string): string | null {
+ const rest = value.replace(/^file:/i, "");
+ if (!rest.startsWith("//")) return decodePath(rest) || null;
+ const hostAndPath = rest.slice(2);
+ const slash = hostAndPath.indexOf("/");
+ const host = slash === -1 ? hostAndPath : hostAndPath.slice(0, slash);
+ const path = slash === -1 ? "" : hostAndPath.slice(slash);
+ if (/^[A-Za-z]:$/.test(host)) return decodePath(host + path) || null;
+ if (host && host.toLowerCase() !== "localhost") return null;
+ const decoded = decodePath(path);
+ return /^\/[A-Za-z]:\//.test(decoded) ? decoded.slice(1) : decoded || null;
+}
+
+/**
+ * Absolute local path written in a chat link, or null when the address is
+ * something else (a web URL, a relative name, an app download).
+ */
+export function nativePathFromMarkdownUrl(raw: string): string | null {
+ let text = raw.trim();
+ if (text.length >= 2 && text.startsWith("<") && text.endsWith(">")) text = text.slice(1, -1).trim();
+ if (!text || /[\u0000\r\n]/.test(text)) return null;
+ const lower = text.toLowerCase();
+ if (
+ lower.startsWith("http://") ||
+ lower.startsWith("https://") ||
+ lower.startsWith("javascript:") ||
+ lower.startsWith("data:") ||
+ lower.startsWith("mailto:")
+ ) {
+ return null;
+ }
+ if (lower.startsWith("file:")) {
+ const converted = pathFromFileUri(text);
+ if (!converted) return null;
+ text = converted;
+ }
+ if (text.startsWith("\\\\") || text.startsWith("//")) return null;
+ if (text.startsWith("~/") || text.startsWith("~\\")) return text;
+ if (/^[A-Za-z]:[\\/]/.test(text)) return text;
+ if (text.startsWith("/") && text !== "/api" && !text.startsWith("/api/")) return text;
+ return null;
+}
+
+/** Keep a local path on a hash so the desktop window cannot navigate to it. */
+export function chatUrlTransform(url: string): string {
+ const local = nativePathFromMarkdownUrl(url);
+ if (local) return LOCAL_PREFIX + encodeURIComponent(local);
+ return defaultUrlTransform(url);
+}
+
+export function localPathFromChatHref(href: string): string | null {
+ if (!href.startsWith(LOCAL_PREFIX)) return null;
+ const path = decodePath(href.slice(LOCAL_PREFIX.length));
+ return path || null;
+}
+
+/**
+ * What a click on a chat link should do.
+ *
+ * `stay` means: do not load this address in the window. An empty href reloads
+ * the current page, and a relative file name is served back as the app itself.
+ */
+export function chatLinkAction(href: string): ChatLinkAction {
+ const local = localPathFromChatHref(href);
+ if (local) return { type: "local", path: local };
+ if (/^https?:\/\//i.test(href)) return { type: "external", url: href };
+ if (href.startsWith("//")) return { type: "external", url: `https:${href}` };
+ if (href.startsWith("mailto:") || href.startsWith("/api/")) return { type: "allow" };
+ return { type: "stay" };
+}
diff --git a/jarvis/ui/web/frontend/src/lib/openLocalPath.ts b/jarvis/ui/web/frontend/src/lib/openLocalPath.ts
new file mode 100644
index 0000000000..1b305273cf
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/openLocalPath.ts
@@ -0,0 +1,23 @@
+/**
+ * Open a file or folder on this computer.
+ *
+ * The desktop app is a web view. Sending the path to `window.open` or letting
+ * a link navigate would load it inside that window and reload the app. This
+ * asks the backend to hand the path to the operating system instead.
+ */
+export async function openLocalPath(path: string): Promise<boolean> {
+ if (!path) return false;
+ try {
+ const res = await fetch("/api/settings/open-path", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ path }),
+ });
+ if (!res.ok) return false;
+ const data = (await res.json().catch(() => null)) as { opened?: boolean } | null;
+ return data?.opened === true;
+ } catch {
+ // The bridge can be absent. A failed open must not navigate this window.
+ return false;
+ }
+}
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index b2ae241278..21d1890972 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -2616,6 +2616,33 @@ async def open_external(body: OpenExternalBody) -> dict[str, object]:
return {"opened": bool(opened)}
+class OpenPathBody(BaseModel):
+ path: str = Field(min_length=1, max_length=4096)
+
+
[email protected]("/open-path")
+async def open_local_path(body: OpenPathBody, request: Request) -> dict[str, object]:
+ """Open a local file or folder from a chat link with the OS default app.
+
+ The desktop window is a web view. Following a file or folder address there
+ reloads the app, so chat asks this route to open it instead. Only an
+ existing file or folder on this computer is opened. Programs and scripts
+ are refused. A headless host has no native file actions and returns 404.
+ """
+ if not bool(getattr(request.app.state, "native_file_actions", False)):
+ raise HTTPException(status_code=404, detail="native-file-actions-disabled")
+ from jarvis.platform.open_path import ChatOpenRejected, open_file, prepare_chat_open
+
+ try:
+ target = prepare_chat_open(body.path)
+ except ChatOpenRejected as exc:
+ status = 404 if exc.reason == "not-found" else 400
+ raise HTTPException(status_code=status, detail=exc.reason) from exc
+ opened = await asyncio.to_thread(open_file, target)
+ log.info("open-path: opened=%s path=%s", opened, target)
+ return {"opened": bool(opened)}
+
+
# ---------------------------------------------------------------------------
# Taskbar section toggles: "Show bar at all times" (bar_persistent, live) and
# "Mute music while dictating" (ducking.enabled, live). Both persist to
diff --git a/tests/unit/platform/test_chat_link_path.py b/tests/unit/platform/test_chat_link_path.py
new file mode 100644
index 0000000000..7d24b3f33f
--- /dev/null
+++ b/tests/unit/platform/test_chat_link_path.py
@@ -0,0 +1,76 @@
+"""Chat links to a file or folder must resolve to that path, and nothing else."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.platform.open_path import ChatOpenRejected, chat_link_path, prepare_chat_open
+
+
+ ("raw", "expected"),
+ [
+ (r"C:\Users\me\Clip.mp4", r"C:\Users\me\Clip.mp4"),
+ ("C:/Users/me/Clip.mp4", "C:/Users/me/Clip.mp4"),
+ ("file:///C:/Users/me/My%20Clip.mp4", "C:/Users/me/My Clip.mp4"),
+ ("file://C:/Users/me/Clip.mp4", "C:/Users/me/Clip.mp4"),
+ ("file://localhost/C:/Users/me/Clip.mp4", "C:/Users/me/Clip.mp4"),
+ ("file:///home/me/clip.mp4", "/home/me/clip.mp4"),
+ ("<C:/Users/me/Clip.mp4>", "C:/Users/me/Clip.mp4"),
+ ("~/Downloads/clip.mp4", "~/Downloads/clip.mp4"),
+ ("/home/me/Videos/clip.mp4", "/home/me/Videos/clip.mp4"),
+ ],
+)
+def test_local_paths_are_recognized(raw: str, expected: str) -> None:
+ assert chat_link_path(raw) == expected
+
+
+ "raw",
+ [
+ "clip.mp4",
+ "./clip.mp4",
+ r"\\server\share\clip.mp4",
+ "file://server/share/clip.mp4",
+ "https://example.test/clip.mp4",
+ "javascript:alert(1)",
+ "/api/outputs/run/files/clip.mp4/download",
+ "",
+ ],
+)
+def test_web_relative_and_network_paths_are_not_local_opens(raw: str) -> None:
+ assert chat_link_path(raw) is None
+
+
+def test_prepare_opens_an_existing_file_or_folder(tmp_path: Path) -> None:
+ clip = tmp_path / "clip.mp4"
+ clip.write_bytes(b"video")
+ folder = tmp_path / "exports"
+ folder.mkdir()
+ assert prepare_chat_open(str(clip)) == clip.resolve()
+ assert prepare_chat_open(clip.as_uri()) == clip.resolve()
+ assert prepare_chat_open(str(folder)) == folder.resolve()
+
+
+def test_prepare_refuses_a_program(tmp_path: Path) -> None:
+ program = tmp_path / "run.exe"
+ program.write_bytes(b"nope")
+ with pytest.raises(ChatOpenRejected) as caught:
+ prepare_chat_open(str(program))
+ assert caught.value.reason == "refused-program"
+
+
+def test_prepare_misses_a_path_that_is_not_there(tmp_path: Path) -> None:
+ missing = tmp_path / "gone.mp4"
+ with pytest.raises(ChatOpenRejected) as caught:
+ prepare_chat_open(str(missing))
+ assert caught.value.reason == "not-found"
+
+
+def test_prepare_rejects_a_relative_name(tmp_path: Path) -> None:
+ del tmp_path
+ with pytest.raises(ChatOpenRejected) as caught:
+ prepare_chat_open("clip.mp4")
+ assert caught.value.reason == "not-a-local-path"
diff --git a/tests/unit/ui/web/test_open_path_route.py b/tests/unit/ui/web/test_open_path_route.py
new file mode 100644
index 0000000000..b95e585b57
--- /dev/null
+++ b/tests/unit/ui/web/test_open_path_route.py
@@ -0,0 +1,55 @@
+"""POST /api/settings/open-path opens a chat file link on the desktop."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import patch
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.ui.web.settings_routes import router
+
+
+def _client(native: bool) -> TestClient:
+ app = FastAPI()
+ app.include_router(router)
+ app.state.native_file_actions = native
+ return TestClient(app)
+
+
+def test_open_path_calls_open_file(tmp_path: Path) -> None:
+ target = tmp_path / "clip.mp4"
+ target.write_bytes(b"video")
+ with patch("jarvis.platform.open_path.open_file", return_value=True) as opened:
+ response = _client(True).post("/api/settings/open-path", json={"path": str(target)})
+ assert response.status_code == 200
+ assert response.json() == {"opened": True}
+ opened.assert_called_once_with(target.resolve())
+
+
+def test_open_path_is_absent_without_native_file_actions(tmp_path: Path) -> None:
+ target = tmp_path / "clip.mp4"
+ target.write_bytes(b"video")
+ with patch("jarvis.platform.open_path.open_file") as opened:
+ response = _client(False).post("/api/settings/open-path", json={"path": str(target)})
+ assert response.status_code == 404
+ opened.assert_not_called()
+
+
+def test_open_path_refuses_a_program(tmp_path: Path) -> None:
+ target = tmp_path / "run.exe"
+ target.write_bytes(b"nope")
+ with patch("jarvis.platform.open_path.open_file") as opened:
+ response = _client(True).post("/api/settings/open-path", json={"path": str(target)})
+ assert response.status_code == 400
+ assert response.json()["detail"] == "refused-program"
+ opened.assert_not_called()
+
+
+def test_open_path_reports_a_missing_file(tmp_path: Path) -> None:
+ response = _client(True).post(
+ "/api/settings/open-path", json={"path": str(tmp_path / "gone.mp4")}
+ )
+ assert response.status_code == 404
+ assert response.json()["detail"] == "not-found"