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
feat(outputs): open artifacts in a chosen editor via an "open with" chooser
Ruben Lütkef54d6069d744
diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 5774e6e4ea..c00d0c3e32 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -1013,6 +1013,10 @@ class UIConfig(BaseModel):bar_persistent: bool = True# Hex accent the bar lights up with during activity (gold on-brand).bar_accent: str = "#e7c46e"+ # Remembered "open with" choice for Outputs artifacts: an opener id+ # ("default" = OS default app, "browser", or an editor key like "code").+ # Empty = ask via the chooser dialog on first open. Desktop-only.+ preferred_opener: str = ""class DuckingConfig(BaseModel):diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex 5bcdfd5822..611ecc0599 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -256,6 +256,16 @@ def set_ui_language(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:_patch_table(path, "ui", "language", name)+def set_preferred_opener(opener: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:+ """Persist the remembered "open with" choice in ``[ui] preferred_opener``.++ ``opener`` is an opener id (``default`` | ``browser`` | an editor key like+ ``code``) validated by the caller. Used by the Outputs view so a file opens+ straight in the chosen app without re-prompting. Desktop-only setting.+ """+ _patch_table(path, "ui", "preferred_opener", opener)++def set_wake_word(phrase: str,*,diff --git a/jarvis/platform/open_path.py b/jarvis/platform/open_path.pyindex d50594004b..04b01e11a8 100644--- a/jarvis/platform/open_path.py+++ b/jarvis/platform/open_path.py@@ -82,4 +82,66 @@ def reveal_in_folder(path: Path) -> bool:return False-__all__ = ["open_file", "reveal_in_folder"]+def open_file_with(file: Path, launch_kind: str, launch_value: str) -> bool:+ """Open *file* in a specific, already-resolved app. Returns True if launched.++ ``launch_kind``/``launch_value`` come from ``resolve_app_launch_target`` in+ the caller (so this module stays free of the plugins layer): ``executable``+ + absolute exe, ``open_a`` + macOS app display-name, ``xdg_open`` (Linux+ default handler), ``startfile`` + a Windows ``.lnk``/app. The file path is+ always passed as the launch argument.++ Unlike ``os.startfile(bare_name)`` — a silent ShellExecute no-op from the+ pythonw background process — every branch starts a real ``subprocess`` so a+ window actually appears. Returns False on a headless host, an unknown kind,+ or a launch error. Never raises (mirrors :func:`open_file`).+ """+ if not detect_capabilities().display_present:+ log.info("open_file_with: no display present — skipping %s", file)+ return False+ try:+ if launch_kind == "executable":+ # Direct exe + the file as its argument (VSCode, Sublime, a browser+ # exe, …). CREATE_NO_WINDOW only suppresses a console, never the GUI.+ subprocess.Popen( # noqa: S603+ [launch_value, str(file)],+ creationflags=NO_WINDOW_CREATIONFLAGS,+ close_fds=True,+ )+ return True+ if launch_kind == "open_a":+ # macOS: `open -a <AppName> <file>` resolves the .app by name.+ subprocess.Popen( # noqa: S603+ ["open", "-a", launch_value, file.as_posix()],+ creationflags=NO_WINDOW_CREATIONFLAGS,+ close_fds=True,+ )+ return True+ if launch_kind == "xdg_open":+ # Linux fallback: hand the file to the desktop's default handler.+ subprocess.Popen( # noqa: S603+ ["xdg-open", file.as_posix()],+ creationflags=NO_WINDOW_CREATIONFLAGS,+ close_fds=True,+ )+ return True+ if launch_kind == "startfile":+ # Windows .lnk/app launched with the file as an argument via `start`.+ subprocess.Popen( # noqa: S603+ ["cmd", "/c", "start", "", launch_value, str(file)],+ creationflags=NO_WINDOW_CREATIONFLAGS,+ close_fds=True,+ )+ return True+ log.warning("open_file_with: unknown launch_kind %r", launch_kind)+ return False+ except OSError as exc:+ log.warning("open_file_with failed for %s (%s): %s", file, launch_value, exc)+ return False+++__all__ = [+ "open_file",+ "open_file_with",+ "reveal_in_folder",+]diff --git a/jarvis/ui/web/frontend/src/components/OpenWithDialog.test.tsx b/jarvis/ui/web/frontend/src/components/OpenWithDialog.test.tsxnew file mode 100644index 0000000000..66a10da563--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/OpenWithDialog.test.tsx@@ -0,0 +1,54 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";++import { OpenWithDialog } from "./OpenWithDialog";++afterEach(cleanup);++const OPENERS = [+ { id: "default", label: "System default app" },+ { id: "browser", label: "Browser" },+ { id: "code", label: "VS Code" },+];++describe("OpenWithDialog", () => {+ it("lists each opener (editor labels pass through, structural ones localise)", () => {+ render(+ <OpenWithDialog openers={OPENERS} onPick={() => {}} onClose={() => {}} />,+ );+ // The editor proper name comes straight from the backend.+ expect(screen.getByText("VS Code")).toBeDefined();+ // "default"/"browser" resolve through i18n (English default locale).+ expect(screen.getByText("System default app")).toBeDefined();+ expect(screen.getByText("Browser")).toBeDefined();+ });++ it("picks an opener with remember=false by default", () => {+ const onPick = vi.fn();+ render(+ <OpenWithDialog openers={OPENERS} onPick={onPick} onClose={() => {}} />,+ );+ fireEvent.click(screen.getByText("VS Code"));+ expect(onPick).toHaveBeenCalledWith("code", false);+ });++ it("passes remember=true once the checkbox is ticked", () => {+ const onPick = vi.fn();+ render(+ <OpenWithDialog openers={OPENERS} onPick={onPick} onClose={() => {}} />,+ );+ fireEvent.click(screen.getByRole("checkbox"));+ fireEvent.click(screen.getByText("System default app"));+ expect(onPick).toHaveBeenCalledWith("default", true);+ });++ it("shows an empty hint when no apps were detected", () => {+ render(+ <OpenWithDialog openers={[]} onPick={() => {}} onClose={() => {}} />,+ );+ expect(screen.queryByRole("checkbox")).toBeNull();+ expect(+ screen.getByText("No apps detected to open this file."),+ ).toBeDefined();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/OpenWithDialog.tsx b/jarvis/ui/web/frontend/src/components/OpenWithDialog.tsxnew file mode 100644index 0000000000..6bc83138b5--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/OpenWithDialog.tsx@@ -0,0 +1,117 @@+/**+ * "Open with…" chooser for an Outputs artifact.+ *+ * Self-contained dialog: lists the apps the backend detected on this host+ * (editors like VS Code, the OS default app, a browser) and lets the user pick+ * one, optionally remembering it as the default. It never touches the global+ * event store; its only outputs are the `onPick` / `onClose` callbacks.+ */+import { useEffect, useState } from "react";+import { AppWindow, FileText, Globe, X } from "lucide-react";++import { cn } from "@/lib/utils";+import { useT } from "@/i18n";+import type { OpenerInfo } from "@/hooks/useOutputs";++export interface OpenWithDialogProps {+ /** The apps that can open the artifact (from `useOpeners`). */+ openers: OpenerInfo[];+ /** Called with the chosen opener id and whether to remember it as default. */+ onPick: (opener: string, remember: boolean) => void;+ /** Called when the user dismisses the dialog (X, Escape, click-outside). */+ onClose: () => void;+}++/** Localise the structural openers; editor labels are proper names from the+ * backend (VS Code, Cursor, …) and pass through unchanged. */+function openerLabel(o: OpenerInfo, t: (k: string) => string): string {+ if (o.id === "default") return t("outputs_view.opener_default");+ if (o.id === "browser") return t("outputs_view.opener_browser");+ return o.label;+}++function OpenerIcon({ id }: { id: string }) {+ const cls = "h-4 w-4 text-muted-foreground";+ if (id === "default") return <FileText className={cls} />;+ if (id === "browser") return <Globe className={cls} />;+ return <AppWindow className={cls} />;+}++export function OpenWithDialog({ openers, onPick, onClose }: OpenWithDialogProps) {+ const t = useT();+ const [remember, setRemember] = useState(false);++ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onClose]);++ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-background/70 backdrop-blur-sm"+ onClick={onClose}+ role="presentation"+ >+ <div+ className="w-full max-w-sm rounded-xl border border-border bg-card p-5 shadow-xl"+ onClick={(e) => e.stopPropagation()}+ role="dialog"+ aria-modal="true"+ >+ <div className="mb-3 flex items-center justify-between">+ <h3 className="text-sm font-semibold text-foreground">+ {t("outputs_view.open_with_title")}+ </h3>+ <button+ type="button"+ onClick={onClose}+ className="rounded p-1 text-muted-foreground hover:bg-secondary/40"+ aria-label={t("common.cancel")}+ >+ <X className="h-4 w-4" />+ </button>+ </div>++ {openers.length === 0 ? (+ <div className="py-4 text-center text-xs text-muted-foreground">+ {t("outputs_view.open_with_empty")}+ </div>+ ) : (+ <ul className="flex flex-col gap-1">+ {openers.map((o) => (+ <li key={o.id}>+ <button+ type="button"+ onClick={() => onPick(o.id, remember)}+ className={cn(+ "flex w-full items-center gap-2.5 rounded-lg border border-transparent",+ "px-3 py-2 text-left text-sm text-foreground/90",+ "hover:border-primary/40 hover:bg-primary/10",+ )}+ >+ <OpenerIcon id={o.id} />+ <span className="truncate">{openerLabel(o, t)}</span>+ </button>+ </li>+ ))}+ </ul>+ )}++ {openers.length > 0 && (+ <label className="mt-4 flex cursor-pointer items-center gap-2 text-xs text-muted-foreground">+ <input+ type="checkbox"+ checked={remember}+ onChange={(e) => setRemember(e.target.checked)}+ className="h-3.5 w-3.5 accent-primary"+ />+ {t("outputs_view.open_with_remember")}+ </label>+ )}+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/hooks/useOutputs.ts b/jarvis/ui/web/frontend/src/hooks/useOutputs.tsindex d3c643e699..32266da13f 100644--- a/jarvis/ui/web/frontend/src/hooks/useOutputs.ts+++ b/jarvis/ui/web/frontend/src/hooks/useOutputs.ts@@ -293,13 +293,76 @@ export async function revealArtifact(slug: string, path: string): Promise<void>if (!r.ok) throw new Error(`HTTP ${r.status}`);}-export async function openArtifactNative(+// --- "Open with" chooser --------------------------------------------------++/** One launchable app in the "open with" chooser. `id` is "default",+ * "browser", or an editor key like "code"; `label` is the display name. */+export interface OpenerInfo {+ id: string;+ label: string;+}++/** The apps that can open an artifact on this host (desktop only; empty on a+ * headless VPS, where the UI falls back to opening the render URL in a tab). */+export function useOpeners() {+ return useQuery<OpenerInfo[]>({+ queryKey: ["outputs-openers"],+ queryFn: async () => {+ const r = await fetch("/api/outputs/openers");+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const data = (await r.json()) as { openers?: OpenerInfo[] };+ return data.openers ?? [];+ },+ staleTime: 60_000,+ });+}++/** The remembered opener id ("" = ask via the chooser on first open). */+export function usePreferredOpener() {+ return useQuery<string>({+ queryKey: ["outputs-preferred-opener"],+ queryFn: async () => {+ const r = await fetch("/api/outputs/preferred-opener");+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const data = (await r.json()) as { opener?: string };+ return data.opener ?? "";+ },+ staleTime: 30_000,+ });+}++/** Persist the remembered opener id (or "" to clear it). */+export function useSetPreferredOpener() {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: async (opener: string) => {+ const r = await fetch("/api/outputs/preferred-opener", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ opener }),+ });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ return (await r.json()) as { opener: string };+ },+ onSuccess: () =>+ qc.invalidateQueries({ queryKey: ["outputs-preferred-opener"] }),+ });+}++/** Open an artifact in the chosen app (desktop only). The backend resolves the+ * opener id to an absolute executable and starts a real process. */+export async function openArtifactWith(slug: string,path: string,+ opener: string,): Promise<void> {const r = await fetch(- `/api/outputs/${slug}/files/${encodeArtifactPath(path)}/open-native`,- { method: "POST" },+ `/api/outputs/${slug}/files/${encodeArtifactPath(path)}/open-with`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ opener }),+ },);if (!r.ok) throw new Error(`HTTP ${r.status}`);}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 859c27a395..9ca3764ec0 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1071,7 +1071,15 @@"continue_label": "Fortsetzen","restart_label": "Neu starten","rerun_starting": "Wird gestartet…",- "rerun_confirm": "Erneut ausführen"+ "rerun_confirm": "Erneut ausführen",+ "open_action": "Öffnen",+ "open_with_title": "Öffnen mit…",+ "open_with_remember": "Als Standard merken",+ "open_with_change": "Öffnen-mit ändern",+ "open_with_empty": "Keine Apps gefunden, um diese Datei zu öffnen.",+ "opener_default": "System-Standard-App",+ "opener_browser": "Browser",+ "reveal_in_folder": "Im Ordner anzeigen"},"common": {"save": "Save",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex a25d234617..6080a3e085 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1071,7 +1071,15 @@"continue_label": "Continue","restart_label": "Restart","rerun_starting": "Starting…",- "rerun_confirm": "Confirm re-run"+ "rerun_confirm": "Confirm re-run",+ "open_action": "Open",+ "open_with_title": "Open with…",+ "open_with_remember": "Remember as default",+ "open_with_change": "Change how this opens",+ "open_with_empty": "No apps detected to open this file.",+ "opener_default": "System default app",+ "opener_browser": "Browser",+ "reveal_in_folder": "Reveal in folder"},"common": {"save": "Save",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex cbe3329e78..40f3bbec63 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1071,7 +1071,15 @@"continue_label": "Continuar","restart_label": "Reiniciar","rerun_starting": "Iniciando…",- "rerun_confirm": "Confirmar reejecución"+ "rerun_confirm": "Confirmar reejecución",+ "open_action": "Abrir",+ "open_with_title": "Abrir con…",+ "open_with_remember": "Recordar como predeterminado",+ "open_with_change": "Cambiar cómo se abre",+ "open_with_empty": "No se detectaron apps para abrir este archivo.",+ "opener_default": "App predeterminada del sistema",+ "opener_browser": "Navegador",+ "reveal_in_folder": "Mostrar en la carpeta"},"common": {"save": "Guardar",diff --git a/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx b/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsxindex ba1ec341cd..044137469e 100644--- a/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx+++ b/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx@@ -50,6 +50,21 @@ function installFetchMock(}),};}+ if (url.includes("/openers")) {+ return {+ ok: true,+ status: 200,+ json: async () => ({+ openers: [+ { id: "default", label: "System default app" },+ { id: "code", label: "VS Code" },+ ],+ }),+ };+ }+ if (url.includes("/preferred-opener")) {+ return { ok: true, status: 200, json: async () => ({ opener: "" }) };+ }if (url.includes("/api/outputs")) {return { ok: true, status: 200, json: async () => ({ sessions }) };}@@ -150,8 +165,11 @@ describe("OutputsView artifact actions", () => {);expect(screen.queryByTitle("Download")).toBeNull();- expect(screen.getByTitle("Open in browser")).toBeDefined();- expect(screen.getByTitle("Open with default app")).toBeDefined();+ // The artifact opens in an app of the user's choice (chooser), not a fixed+ // "open in browser" — and the file is already mirrored to Downloads.+ expect(screen.getByTitle("Open")).toBeDefined();+ expect(screen.getByTitle("Change how this opens")).toBeDefined();expect(screen.getByTitle("Reveal in folder")).toBeDefined();+ expect(screen.queryByTitle("Open in browser")).toBeNull();});});diff --git a/jarvis/ui/web/frontend/src/views/OutputsView.tsx b/jarvis/ui/web/frontend/src/views/OutputsView.tsxindex 71a93a4ef2..61932651c3 100644--- a/jarvis/ui/web/frontend/src/views/OutputsView.tsx+++ b/jarvis/ui/web/frontend/src/views/OutputsView.tsx@@ -9,7 +9,6 @@ import {FileText,ChevronRight,ChevronDown,- AppWindow,} from "lucide-react";import { cn } from "@/lib/utils";import { ViewHeader } from "@/views/ChatsView";@@ -24,12 +23,16 @@ import {useArtifactFile,useCancelMission,useOutputsCapabilities,+ useOpeners,+ usePreferredOpener,+ useSetPreferredOpener,artifactOpenUrl,revealArtifact,- openArtifactNative,+ openArtifactWith,type OutputSummary,type ArtifactSummary,} from "@/hooks/useOutputs";+import { OpenWithDialog } from "@/components/OpenWithDialog";import { useT } from "@/i18n";import { applyMissionDragImage } from "@/lib/missionDragImage";import { useMissionDrag } from "@/store/missionDrag";@@ -523,9 +526,37 @@ function ArtifactRow({file: ArtifactSummary;nativeActions: boolean;}) {+ const t = useT();const [expanded, setExpanded] = useState(false);+ const [chooserOpen, setChooserOpen] = useState(false);const full = useArtifactFile(slug, expanded ? file.path : null);const openUrl = artifactOpenUrl(slug, file.path);+ const openers = useOpeners();+ const preferred = usePreferredOpener();+ const setPreferred = useSetPreferredOpener();++ // Open the file with a specific app (desktop). Remembering persists the+ // choice so the next "Open" click skips the chooser.+ const pickOpener = (opener: string, remember: boolean) => {+ void openArtifactWith(slug, file.path, opener).catch(() => {});+ if (remember) setPreferred.mutate(opener);+ setChooserOpen(false);+ };++ const handleOpen = () => {+ if (!nativeActions) {+ // Headless VPS: the UI is already a real browser tab — open the render+ // URL there (no local apps to launch).+ if (openUrl) window.open(openUrl, "_blank", "noopener,noreferrer");+ return;+ }+ const pref = preferred.data ?? "";+ if (pref) {+ void openArtifactWith(slug, file.path, pref).catch(() => {});+ } else {+ setChooserOpen(true); // first time: ask which app+ }+ };const sizeLabel =file.size < 1024@@ -559,57 +590,63 @@ function ArtifactRow({{sizeLabel}</span><div className="flex shrink-0 items-center gap-0.5">- {openUrl && (+ {(nativeActions || openUrl) && (<buttontype="button"- title="Open in browser"- onClick={() => window.open(openUrl, "_blank", "noopener,noreferrer")}+ title={t("outputs_view.open_action")}+ onClick={handleOpen}className="rounded p-1 hover:bg-secondary/40"><ExternalLink className="h-3.5 w-3.5 text-muted-foreground" /></button>)}{nativeActions && (- <>- <button- type="button"- title="Open with default app"- onClick={() =>- void openArtifactNative(slug, file.path).catch(() => {})- }- className="rounded p-1 hover:bg-secondary/40"- >- <AppWindow className="h-3.5 w-3.5 text-muted-foreground" />- </button>- <button- type="button"- title="Reveal in folder"- onClick={() =>- void revealArtifact(slug, file.path).catch(() => {})- }- className="rounded p-1 hover:bg-secondary/40"- >- <FolderOpen className="h-3.5 w-3.5 text-muted-foreground" />- </button>- </>+ <button+ type="button"+ title={t("outputs_view.open_with_change")}+ onClick={() => setChooserOpen(true)}+ className="rounded p-1 hover:bg-secondary/40"+ >+ <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" />+ </button>+ )}+ {nativeActions && (+ <button+ type="button"+ title={t("outputs_view.reveal_in_folder")}+ onClick={() =>+ void revealArtifact(slug, file.path).catch(() => {})+ }+ className="rounded p-1 hover:bg-secondary/40"+ >+ <FolderOpen className="h-3.5 w-3.5 text-muted-foreground" />+ </button>)}</div></div>+ {chooserOpen && (+ <OpenWithDialog+ openers={openers.data ?? []}+ onPick={pickOpener}+ onClose={() => setChooserOpen(false)}+ />+ )}+{expanded && (<div className="border-t border-border/40 px-3 py-2">{!file.is_text ? (<div className="text-[11px] text-muted-foreground">- Binärdatei — öffne den Ordner auf dem Desktop, um sie anzuzeigen.+ {t("outputs_view.binary_file_hint")}</div>) : full.isLoading ? (<div className="flex items-center gap-2 text-[11px] text-muted-foreground"><Loader2 className="h-3 w-3 animate-spin" />- Lade Datei...+ {t("outputs_view.loading_file")}</div>) : full.isError ? (<div className="text-[11px] text-destructive">- Fehler: {String(full.error)}+ {t("common.error")}: {String(full.error)}</div>) : (<>diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.pyindex 106f27bf80..3619b5c3bf 100644--- a/jarvis/ui/web/outputs_routes.py+++ b/jarvis/ui/web/outputs_routes.py@@ -23,6 +23,7 @@ from pathlib import Pathfrom typing import Anyfrom fastapi import APIRouter, HTTPException, Request+from pydantic import BaseModelfrom starlette.responses import FileResponse, HTMLResponsefrom jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS@@ -713,6 +714,194 @@ async def open_output_artifact_native(return {"opened": bool(opened), "path": str(target)}+# --- "Open with" chooser ----------------------------------------------------+# The user picks which app opens an artifact (an editor like VS Code, the OS+# default app, or a browser). Every launch resolves the app to an absolute+# executable and starts a real subprocess (open_path.open_file/open_file_with)+# — NOT os.startfile(bare_name), which is a silent ShellExecute no-op from the+# pythonw background server (the "open button does nothing" root cause).++# Curated editor candidates shown in the chooser, in priority order. The id is+# the voice/app alias the cross-platform resolver understands; the label is the+# English display name (the frontend localises the structural pieces).+_OPENER_EDITORS: list[tuple[str, str]] = [+ ("code", "VS Code"),+ ("cursor", "Cursor"),+ ("subl", "Sublime Text"),+ ("notepad++", "Notepad++"),+ ("zed", "Zed"),+ ("windsurf", "Windsurf"),+]++# Browsers tried, in order, for the "browser" opener (first installed wins).+_BROWSER_CANDIDATES: tuple[str, ...] = (+ "chrome", "msedge", "firefox", "brave", "opera", "vivaldi",+)+++def _known_opener_ids() -> set[str]:+ """The closed set of opener ids the server will launch — the security+ boundary. A client may only pick one of these, never a raw executable path,+ so an ``open-with`` request can't turn into arbitrary code execution."""+ return {"default", "browser"} | {oid for oid, _ in _OPENER_EDITORS}+++def _macos_app_present(display_name: str) -> bool:+ """True if a macOS ``.app`` bundle with *display_name* exists. Best-effort —+ only consulted on darwin where the resolver yields an ``open_a`` target."""+ for base in ("/Applications", os.path.expanduser("~/Applications")):+ if os.path.isdir(os.path.join(base, f"{display_name}.app")):+ return True+ return False+++def _resolve_installed(app_id: str) -> tuple[str, str] | None:+ """Resolve *app_id* to a launch ``(kind, value)`` IFF it is actually+ installed, else None. Distinguishes a real resolution (executable / a+ Start-Menu ``.lnk`` / a present macOS ``.app``) from the resolver's+ raw-name ``startfile`` fallback, which just means "not found"."""+ from jarvis.plugins.tool.app_resolver import resolve_app_launch_target++ target = resolve_app_launch_target(app_id)+ if target.kind == "executable":+ return (target.kind, target.value)+ if target.kind == "startfile" and target.value.lower().endswith(".lnk"):+ return (target.kind, target.value)+ if target.kind == "open_a" and _macos_app_present(target.value):+ return (target.kind, target.value)+ return None+++def _resolve_browser_target() -> tuple[str, str] | None:+ """Resolve the first installed browser to a launch ``(kind, value)``, or+ None. Launching ``browser_exe <file>`` renders an HTML/PDF artifact in a+ real browser window without the WebView download trap or the strict CSP."""+ for cand in _BROWSER_CANDIDATES:+ resolved = _resolve_installed(cand)+ if resolved is not None:+ return resolved+ return None+++def _resolve_opener(opener_id: str) -> tuple[str, str] | None:+ """Map an opener id to a launch ``(kind, value)``, or None if unavailable.++ ``default`` → the sentinel ``("default", "")`` (caller uses ``open_file``);+ ``browser`` → the first installed browser; an editor key → that editor iff+ installed. Unknown ids resolve to None."""+ if opener_id == "default":+ return ("default", "")+ if opener_id == "browser":+ return _resolve_browser_target()+ if opener_id in {oid for oid, _ in _OPENER_EDITORS}:+ return _resolve_installed(opener_id)+ return None+++def _available_openers() -> list[dict[str, str]]:+ """The openers actually launchable on this host, for the chooser dialog."""+ out: list[dict[str, str]] = [{"id": "default", "label": "System default app"}]+ if _resolve_browser_target() is not None:+ out.append({"id": "browser", "label": "Browser"})+ for oid, label in _OPENER_EDITORS:+ if _resolve_installed(oid) is not None:+ out.append({"id": oid, "label": label})+ return out+++class OpenWithBody(BaseModel):+ opener: str+++class PreferredOpenerBody(BaseModel):+ opener: str = ""++[email protected]("/openers")+def list_openers(request: Request) -> dict[str, Any]:+ """List the apps that can open an artifact here (editors + default + browser).++ Empty on a headless VPS (no local desktop apps): the frontend then falls+ back to opening the render URL in the current browser tab.+ """+ if not getattr(request.app.state, "native_file_actions", False):+ return {"openers": []}+ return {"openers": _available_openers()}++[email protected]("/preferred-opener")+def get_preferred_opener(request: Request) -> dict[str, Any]:+ """Return the remembered opener id (``""`` = ask via the chooser)."""+ cfg = getattr(request.app.state, "config", None)+ opener = ""+ if cfg is not None:+ opener = getattr(getattr(cfg, "ui", None), "preferred_opener", "") or ""+ return {"opener": opener}++[email protected]("/preferred-opener")+def put_preferred_opener(+ body: PreferredOpenerBody, request: Request+) -> dict[str, Any]:+ """Persist the remembered opener id (or ``""`` to clear it).++ Validated against the closed opener set — never a raw path. Persists to+ ``[ui] preferred_opener`` and hot-updates the in-memory config so the next+ open uses it without a restart.+ """+ opener = (body.opener or "").strip()+ if opener and opener not in _known_opener_ids():+ raise HTTPException(status_code=400, detail=f"unknown opener: {opener}")+ from jarvis.core import config_writer++ try:+ config_writer.set_preferred_opener(opener)+ except Exception as exc: # noqa: BLE001+ logger.warning("preferred-opener persist failed: %s", exc)+ cfg = getattr(request.app.state, "config", None)+ ui = getattr(cfg, "ui", None) if cfg is not None else None+ if ui is not None:+ try:+ ui.preferred_opener = opener+ except Exception as exc: # noqa: BLE001+ logger.debug("in-memory preferred_opener update skipped: %s", exc)+ return {"opener": opener}++[email protected]("/{slug}/files/{path:path}/open-with")+async def open_artifact_with(+ slug: str, path: str, body: OpenWithBody, request: Request+) -> dict[str, Any]:+ """Open an artifact in the chosen app. Local desktop only.++ ``opener`` must be a known id (``default`` | ``browser`` | an editor key) —+ never a raw path, so this can't launch an arbitrary client-supplied binary.+ The app is resolved to an absolute executable and started via a real+ subprocess so a window actually appears.+ """+ if not getattr(request.app.state, "native_file_actions", False):+ raise HTTPException(status_code=404, detail="native file actions unavailable")+ opener = (body.opener or "").strip()+ if opener not in _known_opener_ids():+ raise HTTPException(status_code=400, detail=f"unknown opener: {opener}")+ target = _resolve_artifact_target(request, slug, path)+ resolved = _resolve_opener(opener)+ if resolved is None:+ raise HTTPException(+ status_code=409, detail=f"opener not available: {opener}"+ )+ from jarvis.platform import open_path++ kind, value = resolved+ if kind == "default":+ opened = await asyncio.to_thread(open_path.open_file, target)+ else:+ opened = await asyncio.to_thread(+ open_path.open_file_with, target, kind, value+ )+ return {"opened": bool(opened), "opener": opener}++@router.post("/{slug}/open")async def open_output(slug: str, request: Request) -> dict[str, Any]:"""Open the session folder in the OS file explorer (Windows: explorer.exe).diff --git a/tests/unit/platform/test_open_path.py b/tests/unit/platform/test_open_path.pyindex 469c98fe76..8e9d066b28 100644--- a/tests/unit/platform/test_open_path.py+++ b/tests/unit/platform/test_open_path.py@@ -78,3 +78,66 @@ def test_reveal_headless_is_noop():patch.object(op.subprocess, "Popen") as popen:assert op.reveal_in_folder(Path("/x/y/z.md")) is Falsepopen.assert_not_called()+++# --- open_file_with (launch a file in a specific resolved app) ---------------+# Takes an already-resolved launch (kind, value) — NOT a bare app name — and+# starts a real process so a window actually appears (the os.startfile/+# ShellExecute path is a silent no-op from the pythonw background server).+++def test_open_file_with_executable_starts_process_with_file_arg():+ with patch.object(op, "detect_capabilities", return_value=_caps()), \+ patch.object(op, "detect_platform", return_value="win32"), \+ patch.object(op.subprocess, "Popen") as popen:+ ok = op.open_file_with(+ Path(r"C:\out\report.md"), "executable", r"C:\apps\Code.exe"+ )+ assert ok is True+ argv = popen.call_args.args[0]+ assert argv[0] == r"C:\apps\Code.exe"+ assert argv[1] == r"C:\out\report.md"+++def test_open_file_with_open_a_macos_passes_file_after_app():+ with patch.object(op, "detect_capabilities", return_value=_caps()), \+ patch.object(op, "detect_platform", return_value="darwin"), \+ patch.object(op.subprocess, "Popen") as popen:+ ok = op.open_file_with(+ Path("/out/report.md"), "open_a", "Visual Studio Code"+ )+ assert ok is True+ argv = popen.call_args.args[0]+ assert argv[:3] == ["open", "-a", "Visual Studio Code"]+ assert argv[-1] == "/out/report.md"+++def test_open_file_with_xdg_open_linux_opens_file():+ with patch.object(op, "detect_capabilities", return_value=_caps()), \+ patch.object(op, "detect_platform", return_value="linux"), \+ patch.object(op.subprocess, "Popen") as popen:+ ok = op.open_file_with(Path("/out/report.md"), "xdg_open", "")+ assert ok is True+ argv = popen.call_args.args[0]+ assert argv[0] == "xdg-open" and argv[1] == "/out/report.md"+++def test_open_file_with_headless_is_noop():+ with patch.object(op, "detect_capabilities", return_value=_caps(display=False)), \+ patch.object(op.subprocess, "Popen") as popen:+ assert op.open_file_with(Path("/x/y.md"), "executable", "/a/b") is False+ popen.assert_not_called()+++def test_open_file_with_unknown_kind_returns_false():+ with patch.object(op, "detect_capabilities", return_value=_caps()), \+ patch.object(op.subprocess, "Popen") as popen:+ assert op.open_file_with(Path("/x/y.md"), "nonsense", "v") is False+ popen.assert_not_called()+++def test_open_file_with_never_raises_on_error():+ with patch.object(op, "detect_capabilities", return_value=_caps()), \+ patch.object(op, "detect_platform", return_value="linux"), \+ patch.object(op.subprocess, "Popen", side_effect=OSError("boom")):+ assert op.open_file_with(Path("/x/y.md"), "executable", "/a/b") is Falsediff --git a/tests/unit/ui/web/test_outputs_routes.py b/tests/unit/ui/web/test_outputs_routes.pyindex 1934b7b2be..9a8d1912c6 100644--- a/tests/unit/ui/web/test_outputs_routes.py+++ b/tests/unit/ui/web/test_outputs_routes.py@@ -850,3 +850,181 @@ def test_view_rejects_oversize_file(app, monkeypatch):client = TestClient(app)r = client.get(f"/api/outputs/{slug}/files/{rel}/view")assert r.status_code == 413+++# --- "open with" chooser: detection + open-with + preferred-opener -----------+# Replaces the silent-no-op os.startfile/ShellExecute path: the file is opened+# in a resolved editor/app via a real subprocess so a window actually appears.++from types import SimpleNamespace # noqa: E402++from jarvis.plugins.tool.app_resolver import LaunchTarget # noqa: E402+++def _fake_resolver_only(*installed: str):+ """Return a resolve_app_launch_target stub where only *installed* keys map+ to a real executable; everything else returns the raw-name startfile+ fallback (= 'not installed')."""+ def _resolve(name: str) -> LaunchTarget:+ if name in installed:+ return LaunchTarget("executable", rf"C:\apps\{name}.exe")+ return LaunchTarget("startfile", name)+ return _resolve+++def test_openers_native_disabled_returns_empty(app):+ app.state.native_file_actions = False+ client = TestClient(app)+ r = client.get("/api/outputs/openers")+ assert r.status_code == 200+ assert r.json()["openers"] == []+++def test_openers_always_includes_default(app):+ app.state.native_file_actions = True+ with patch(+ "jarvis.plugins.tool.app_resolver.resolve_app_launch_target",+ side_effect=_fake_resolver_only(),+ ), patch(+ "jarvis.ui.web.outputs_routes._resolve_browser_target", return_value=None+ ):+ client = TestClient(app)+ r = client.get("/api/outputs/openers")+ ids = {o["id"] for o in r.json()["openers"]}+ assert "default" in ids+++def test_openers_detects_installed_editor_only(app):+ app.state.native_file_actions = True+ with patch(+ "jarvis.plugins.tool.app_resolver.resolve_app_launch_target",+ side_effect=_fake_resolver_only("code"),+ ), patch(+ "jarvis.ui.web.outputs_routes._resolve_browser_target", return_value=None+ ):+ client = TestClient(app)+ r = client.get("/api/outputs/openers")+ ids = {o["id"] for o in r.json()["openers"]}+ assert "code" in ids+ assert "cursor" not in ids # raw fallback → not installed → hidden+++def test_open_with_404_when_native_disabled(app):+ root = Path(app.state.outputs_root)+ slug = "mission_019ed2dfd0fab"+ rel = _make_deliverable(root, "019ed2dfd0fab1234", "report.md", "# Hi")+ app.state.native_file_actions = False+ client = TestClient(app)+ r = client.post(+ f"/api/outputs/{slug}/files/{rel}/open-with", json={"opener": "default"}+ )+ assert r.status_code == 404+++def test_open_with_default_calls_open_file(app):+ root = Path(app.state.outputs_root)+ slug = "mission_019ed2dfd0fab"+ rel = _make_deliverable(root, "019ed2dfd0fab1234", "report.md", "# Hi")+ app.state.native_file_actions = True+ client = TestClient(app)+ with patch("jarvis.platform.open_path.open_file", return_value=True) as opn:+ r = client.post(+ f"/api/outputs/{slug}/files/{rel}/open-with",+ json={"opener": "default"},+ )+ assert r.status_code == 200+ assert r.json()["opened"] is True+ opn.assert_called_once()+++def test_open_with_editor_calls_open_file_with(app):+ root = Path(app.state.outputs_root)+ slug = "mission_019ed2dfd0fab"+ rel = _make_deliverable(root, "019ed2dfd0fab1234", "report.md", "# Hi")+ app.state.native_file_actions = True+ client = TestClient(app)+ with patch(+ "jarvis.plugins.tool.app_resolver.resolve_app_launch_target",+ side_effect=_fake_resolver_only("code"),+ ), patch(+ "jarvis.platform.open_path.open_file_with", return_value=True+ ) as opn:+ r = client.post(+ f"/api/outputs/{slug}/files/{rel}/open-with",+ json={"opener": "code"},+ )+ assert r.status_code == 200+ assert r.json()["opened"] is True+ opn.assert_called_once()+ # Called with (file_path, kind, value) — the resolved executable.+ args = opn.call_args.args+ assert args[1] == "executable"+ assert args[2].endswith("code.exe")+++def test_open_with_rejects_unknown_opener(app):+ """A free-form opener (path/arbitrary string) must be rejected — the server+ only launches known opener ids, never a client-supplied executable path."""+ root = Path(app.state.outputs_root)+ slug = "mission_019ed2dfd0fab"+ rel = _make_deliverable(root, "019ed2dfd0fab1234", "report.md", "# Hi")+ app.state.native_file_actions = True+ client = TestClient(app)+ r = client.post(+ f"/api/outputs/{slug}/files/{rel}/open-with",+ json={"opener": r"C:\Windows\System32\evil.exe"},+ )+ assert r.status_code == 400+++def test_open_with_blocks_non_deliverable(app):+ root = Path(app.state.outputs_root)+ slug = "mission_019ed2dfd0fab"+ d = root / slug+ d.mkdir(parents=True, exist_ok=True)+ (d / "reflections.md").write_text("secret", encoding="utf-8")+ app.state.native_file_actions = True+ client = TestClient(app)+ r = client.post(+ f"/api/outputs/{slug}/files/reflections.md/open-with",+ json={"opener": "default"},+ )+ assert r.status_code == 404+++def test_get_preferred_opener_reads_config(app):+ app.state.config = SimpleNamespace(ui=SimpleNamespace(preferred_opener="code"))+ client = TestClient(app)+ r = client.get("/api/outputs/preferred-opener")+ assert r.status_code == 200+ assert r.json()["opener"] == "code"+++def test_get_preferred_opener_defaults_empty(app):+ # No config on app.state → empty (chooser will prompt).+ client = TestClient(app)+ r = client.get("/api/outputs/preferred-opener")+ assert r.status_code == 200+ assert r.json()["opener"] == ""+++def test_put_preferred_opener_persists_and_updates(app):+ app.state.config = SimpleNamespace(ui=SimpleNamespace(preferred_opener=""))+ client = TestClient(app)+ with patch(+ "jarvis.core.config_writer.set_preferred_opener"+ ) as setter:+ r = client.put(+ "/api/outputs/preferred-opener", json={"opener": "code"}+ )+ assert r.status_code == 200+ setter.assert_called_once_with("code")+ assert app.state.config.ui.preferred_opener == "code"+++def test_put_preferred_opener_rejects_unknown(app):+ client = TestClient(app)+ r = client.put(+ "/api/outputs/preferred-opener", json={"opener": "../../evil"}+ )+ assert r.status_code == 400