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 any linked filename, not only a full path

rubenluetke10-beep3ac513de2db8
diff --git a/jarvis/platform/open_path.py b/jarvis/platform/open_path.py
index 8291fdfee5..72ab19fcaa 100644
--- a/jarvis/platform/open_path.py
+++ b/jarvis/platform/open_path.py
@@ -536,35 +536,115 @@ def chat_link_path(raw: str) -> str | None:
return None
-def prepare_chat_open(raw: str) -> Path:
- """Existing local file or folder a chat link may open.
+def _user_file_roots() -> list[Path]:
+ """Folders a bare filename from chat may be found in."""
+ home = Path.home()
+ roots: list[Path] = []
+ for name in ("Downloads", "Desktop", "Documents"):
+ folder = home / name
+ if folder.is_dir():
+ roots.append(folder)
+ return roots
+
+
+def _relative_file_name(raw: str) -> Path | None:
+ """``notes.md`` or ``shots/photo.png``, never a path that climbs upward."""
+ 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:", "file:")):
+ return None
+ if text.startswith(("\\\\", "//", "~/")) or re.match(r"^[A-Za-z]:[\\/]", text):
+ return None
+ parts = [part for part in text.replace("\\", "/").split("/") if part not in ("", ".")]
+ if not parts or any(part == ".." for part in parts):
+ return None
+ suffix = Path(parts[-1]).suffix
+ if not re.fullmatch(r"\.[A-Za-z0-9]{1,12}", suffix):
+ return None
+ return Path(*parts)
- 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")
+
+def _inside(root: Path, candidate: Path) -> bool:
+ try:
+ resolved_root = root.resolve()
+ resolved = candidate.resolve()
+ except OSError:
+ return False
+ return resolved == resolved_root or resolved_root in resolved.parents
+
+
+def _find_named_file(raw: str) -> Path | None:
+ """Newest file of this name under Downloads, Desktop or Documents."""
+ relative = _relative_file_name(raw)
+ if relative is None:
+ return None
+ names = [relative]
+ if len(relative.parts) > 1:
+ names.append(Path(relative.name))
+ found: list[Path] = []
+ for root in _user_file_roots():
+ for name in names:
+ candidate = root / name
+ if _inside(root, candidate) and candidate.is_file():
+ found.append(candidate)
+ if not found:
+ return None
+ found.sort(key=lambda path: path.stat().st_mtime, reverse=True)
+ return found[0]
+
+
+def _refuse_program(target: Path) -> None:
+ 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")
+
+
+def _existing_absolute(native: str) -> Path | None:
+ """Resolve an absolute local path, or None when it is not on this computer."""
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")
+ return None
path = Path(native)
if not path.is_absolute():
- raise ChatOpenRejected("not-a-local-path")
+ return None
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()):
+ except OSError:
+ return None
+ if target.exists() and (target.is_file() or target.is_dir()):
+ return target
+ return None
+
+
+def prepare_chat_open(raw: str) -> Path:
+ """Existing local file or folder a chat link may open.
+
+ A full path opens that exact file, whatever its type: video, picture,
+ markdown or anything else the system can open. A bare filename is looked
+ up in Downloads, Desktop and Documents. Programs and scripts are refused.
+
+ 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)
+ target = _existing_absolute(native) if native is not None else None
+ if target is None:
+ named = Path(native).name if native else raw
+ target = _find_named_file(named)
+ if target is None:
+ if native is None and _relative_file_name(raw) is None:
+ raise ChatOpenRejected("not-a-local-path")
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")
+ _refuse_program(target)
return target
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 455e09c2e0..cc60d903d5 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx
@@ -139,15 +139,21 @@ describe("shared chat media", () => {
vi.unstubAllGlobals();
});
- it("does not let a bare filename navigate the window", () => {
- const fetchMock = vi.fn();
+ it.each([
+ ["[Clip](file:///C:/Users/Administrator/Downloads/Clip.mp4)", "C:/Users/Administrator/Downloads/Clip.mp4"],
+ ["[notes.md](notes.md)", "notes.md"],
+ ["[shot.png](shot.png)", "shot.png"],
+ ])("opens %s on this computer", (markdown, path) => {
+ const fetchMock = vi.fn(async () => ({ ok: true, json: async () => ({ opened: true }) }));
vi.stubGlobal("fetch", fetchMock);
- render(<ChatMarkdown text="[Clip](Clip.mp4)" />);
- const link = screen.getByRole("link", { name: "Clip" });
+ render(<ChatMarkdown text={markdown} />);
const event = new MouseEvent("click", { bubbles: true, cancelable: true });
- link.dispatchEvent(event);
+ screen.getByRole("link").dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
- expect(fetchMock).not.toHaveBeenCalled();
+ expect(fetchMock).toHaveBeenCalledWith("/api/settings/open-path", expect.objectContaining({
+ method: "POST",
+ body: JSON.stringify({ path }),
+ }));
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 434fd2c6c6..0eefe23c81 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx
@@ -148,8 +148,8 @@ 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);
+function onChatLinkClick(event: { preventDefault(): void }, href: string, label = "") {
+ const action = chatLinkAction(href, label);
if (action.type === "allow") return;
event.preventDefault();
if (action.type === "local") void openLocalPath(action.path);
@@ -161,7 +161,7 @@ function onChatLinkClick(event: { preventDefault(): void }, href: string) {
const MARKDOWN_COMPONENTS: Components = {
img: ({ src = "", alt = "image" }) => {
const local = localPathFromChatHref(src);
- if (local) return <a href={src} title={local} onClick={event => onChatLinkClick(event, src)}>{alt || local}</a>;
+ if (local) return <a href={src} title={local} onClick={event => onChatLinkClick(event, src, alt || local)}>{alt || local}</a>;
return <MediaPreview src={src} label={alt || "image"} kind={mediaKind(src) ?? "image"} />;
},
a: function MediaLink({ href = "", children }) {
@@ -170,7 +170,7 @@ const MARKDOWN_COMPONENTS: Components = {
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} />;
const local = localPathFromChatHref(href);
- return <a href={href} title={local || undefined} onClick={event => onChatLinkClick(event, href)}>{children}</a>;
+ return <a href={href} title={local || undefined} onClick={event => onChatLinkClick(event, href, label)}>{children}</a>;
},
pre: ({ children, node: _node, ...props }) => {
const fence = readFence(children);
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.test.ts
index 22223c72a8..1cdfcd9899 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.test.ts
@@ -16,7 +16,6 @@ describe("chat file links", () => {
});
it.each([
- "clip.mp4",
"https://example.test/clip.mp4",
"javascript:alert(1)",
"file://server/share/clip.mp4",
@@ -25,6 +24,11 @@ describe("chat file links", () => {
expect(nativePathFromMarkdownUrl(raw)).toBeNull();
});
+ it.each(["notes.md", "shot.png", "folder/clip.mp4"])("opens a linked filename %s", name => {
+ expect(chatUrlTransform(name)).toBe("#jarvis-local=" + encodeURIComponent(name));
+ expect(chatLinkAction(chatUrlTransform(name))).toEqual({ type: "local", path: name });
+ });
+
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" });
@@ -34,9 +38,9 @@ describe("chat file links", () => {
});
});
- it("refuses to navigate the window for an empty or relative link", () => {
+ it("uses the visible filename when the address itself was emptied", () => {
+ expect(chatLinkAction("", "photo.png")).toEqual({ type: "local", path: "photo.png" });
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
index eebc4a3c7a..9f345a29d6 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.ts
@@ -30,13 +30,33 @@ function pathFromFileUri(value: string): string | null {
return /^\/[A-Za-z]:\//.test(decoded) ? decoded.slice(1) : decoded || null;
}
+function stripAngles(raw: string): string {
+ const text = raw.trim();
+ if (text.length >= 2 && text.startsWith("<") && text.endsWith(">")) return text.slice(1, -1).trim();
+ return text;
+}
+
+/**
+ * A linked name such as `notes.md`, `photo.png` or `folder/clip.mp4`.
+ * Web addresses and app downloads are not files on this computer.
+ */
+export function looksLikeLocalFile(raw: string): boolean {
+ const text = stripAngles(raw);
+ if (!text || text.length > 240 || /[\u0000\r\n]/.test(text)) return false;
+ if (/^[a-z][a-z0-9+.-]*:/i.test(text)) return false;
+ if (text.startsWith("/api/") || text === "/api" || text.startsWith("//")) return false;
+ const parts = text.replace(/\\/g, "/").split("/");
+ if (parts.some(part => part === ".." || part === "")) return false;
+ const name = parts[parts.length - 1] ?? "";
+ return /^[^\\/:*?"<>|]+\.[A-Za-z0-9]{1,12}$/.test(name);
+}
+
/**
* 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();
+ let text = stripAngles(raw);
if (!text || /[\u0000\r\n]/.test(text)) return null;
const lower = text.toLowerCase();
if (
@@ -60,9 +80,14 @@ export function nativePathFromMarkdownUrl(raw: string): string | null {
return null;
}
+/** Full path when the link has one, otherwise a bare filename worth opening. */
+export function openableLinkTarget(raw: string): string | null {
+ return nativePathFromMarkdownUrl(raw) || (looksLikeLocalFile(raw) ? stripAngles(raw) : 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);
+ const local = openableLinkTarget(url);
if (local) return LOCAL_PREFIX + encodeURIComponent(local);
return defaultUrlTransform(url);
}
@@ -79,11 +104,13 @@ export function localPathFromChatHref(href: string): string | null {
* `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);
+export function chatLinkAction(href: string, label = ""): ChatLinkAction {
+ const local = localPathFromChatHref(href) || openableLinkTarget(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" };
+ const named = openableLinkTarget(label);
+ if (named) return { type: "local", path: named };
return { type: "stay" };
}
diff --git a/tests/unit/platform/test_chat_link_path.py b/tests/unit/platform/test_chat_link_path.py
index 7d24b3f33f..69589fc7dc 100644
--- a/tests/unit/platform/test_chat_link_path.py
+++ b/tests/unit/platform/test_chat_link_path.py
@@ -69,8 +69,34 @@ def test_prepare_misses_a_path_that_is_not_there(tmp_path: Path) -> None:
assert caught.value.reason == "not-found"
-def test_prepare_rejects_a_relative_name(tmp_path: Path) -> None:
- del tmp_path
+def test_prepare_rejects_a_word_that_is_not_a_file() -> None:
with pytest.raises(ChatOpenRejected) as caught:
- prepare_chat_open("clip.mp4")
+ prepare_chat_open("just a sentence")
assert caught.value.reason == "not-a-local-path"
+
+
+def test_a_filename_opens_from_downloads_whatever_the_type(tmp_path: Path, monkeypatch) -> None:
+ downloads = tmp_path / "Downloads"
+ downloads.mkdir()
+ notes = downloads / "notes.md"
+ notes.write_text("hello", encoding="utf-8")
+ picture = downloads / "shot.png"
+ picture.write_bytes(b"png")
+ monkeypatch.setattr(
+ "jarvis.platform.open_path._user_file_roots", lambda: [downloads]
+ )
+ assert prepare_chat_open("notes.md") == notes.resolve()
+ assert prepare_chat_open("shot.png") == picture.resolve()
+
+
+def test_a_full_path_wins_over_another_file_with_the_same_name(tmp_path: Path, monkeypatch) -> None:
+ downloads = tmp_path / "Downloads"
+ downloads.mkdir()
+ other = downloads / "clip.mp4"
+ other.write_bytes(b"other")
+ exact = tmp_path / "clip.mp4"
+ exact.write_bytes(b"exact")
+ monkeypatch.setattr(
+ "jarvis.platform.open_path._user_file_roots", lambda: [downloads]
+ )
+ assert prepare_chat_open(str(exact)) == exact.resolve()