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.

feat(ide): sidebar menus offer only actions that work

rubenluetke10-beep63911f489c07
diff --git a/jarvis/agentic_ide/project_links.py b/jarvis/agentic_ide/project_links.py
new file mode 100644
index 0000000000..67290a3d54
--- /dev/null
+++ b/jarvis/agentic_ide/project_links.py
@@ -0,0 +1,86 @@
+"""Where a project folder can be opened besides the IDE itself.
+
+The sidebar's project menu offers "Open on GitHub" only when the folder really
+has a hosted remote, so the menu never shows an action that cannot work. This
+module answers that question: the web address of the folder's ``origin``
+remote, or None.
+
+Only ``http(s)`` addresses ever come out. A remote written as SSH
+(``[email protected]:owner/repo.git``) is rewritten to its web page, and embedded
+credentials (``https://token@host/...``) are stripped, so neither a secret
+nor an arbitrary scheme can reach the browser.
+"""
+
+from __future__ import annotations
+
+import re
+import shutil
+import subprocess
+from pathlib import Path
+from urllib.parse import urlsplit, urlunsplit
+
+from loguru import logger
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+_GIT_TIMEOUT_S = 3.0
+_SCP_LIKE = re.compile(r"^(?:[\w.-]+@)?(?P<host>[\w.-]+):(?P<path>[^/].*)$")
+
+
+def web_url(remote: str) -> str | None:
+ """The browser address of a git remote, or None when it has none."""
+ remote = remote.strip()
+ if not remote:
+ return None
+ if "://" not in remote:
+ match = _SCP_LIKE.match(remote)
+ if match is None:
+ # A local path remote (``../other.git``) has no web page.
+ return None
+ host, path = match.group("host"), match.group("path")
+ else:
+ parts = urlsplit(remote)
+ if parts.scheme not in {"http", "https", "ssh", "git"} or not parts.hostname:
+ return None
+ host, path = parts.hostname, parts.path.lstrip("/")
+ path = path.removesuffix("/").removesuffix(".git")
+ if not path:
+ return None
+ return urlunsplit(("https", host, f"/{path}", "", ""))
+
+
+def host_label(url: str) -> str:
+ """The name the menu uses for a remote's host: GitHub, GitLab, …"""
+ host = (urlsplit(url).hostname or "").lower()
+ for needle, label in (("github", "GitHub"), ("gitlab", "GitLab"), ("bitbucket", "Bitbucket")):
+ if needle in host:
+ return label
+ return host or "the web"
+
+
+def remote_web_url(folder: str | Path) -> str | None:
+ """The web page of ``folder``'s ``origin`` remote, or None.
+
+ None covers every "no" alike: git not installed, not a repository, no
+ origin, a local-path remote, a slow network drive that hits the timeout.
+ """
+ git = shutil.which("git")
+ if git is None:
+ return None
+ try:
+ result = subprocess.run( # noqa: S603 - fixed argv, no shell
+ [git, "-C", str(folder), "remote", "get-url", "origin"],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=_GIT_TIMEOUT_S,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ logger.debug("Project links: no remote for {}: {}", folder, exc)
+ return None
+ if result.returncode != 0:
+ return None
+ return web_url(result.stdout)
diff --git a/jarvis/ui/web/chat_library_routes.py b/jarvis/ui/web/chat_library_routes.py
index 5cb719b99f..154a1354fc 100644
--- a/jarvis/ui/web/chat_library_routes.py
+++ b/jarvis/ui/web/chat_library_routes.py
@@ -306,6 +306,35 @@ def reveal_project(request: Request, project_id: str) -> RevealedOut:
of the user, so the route 404s there like the other native file actions.
The path comes from the stored project, never from the client.
"""
+ folder = _require_folder(request, project_id)
+ from jarvis.platform.open_path import open_file
+
+ return RevealedOut(opened=open_file(Path(folder)))
+
+
+class LauncherOut(BaseModel):
+ id: str
+ label: str
+
+
+class LaunchersOut(BaseModel):
+ """Where this project can be opened right now, so the menu offers only those."""
+
+ file_manager: bool
+ editors: list[LauncherOut]
+ remote_url: str | None = None
+ remote_label: str | None = None
+
+
+class OpenInIn(BaseModel):
+ target: str = Field(
+ min_length=1,
+ max_length=40,
+ description='An editor id from ``/launchers`` or ``"remote"``.',
+ )
+
+
+def _require_folder(request: Request, project_id: str) -> str:
if not bool(getattr(request.app.state, "native_file_actions", False)):
raise HTTPException(status_code=404, detail="native-file-actions-disabled")
folder = _project_folder(project_id)
@@ -313,9 +342,77 @@ def reveal_project(request: Request, project_id: str) -> RevealedOut:
raise HTTPException(status_code=404, detail="No such project")
if not _folder_exists(folder):
raise HTTPException(status_code=404, detail="The project folder is not reachable.")
- from jarvis.platform.open_path import open_file
+ return folder
- return RevealedOut(opened=open_file(Path(folder)))
+
+ "/projects/{project_id}/launchers",
+ response_model=LaunchersOut,
+ summary="Editors and web pages a project's folder can be opened in",
+)
+def project_launchers(request: Request, project_id: str) -> LaunchersOut:
+ """Installed code editors, and the folder's hosted git remote if it has one.
+
+ Asked when the sidebar's menu opens, so the menu shows "Open in Cursor" only
+ where Cursor is installed and "Open on GitHub" only where there is a GitHub
+ remote. A headless host has no local apps: every list comes back empty.
+ """
+ if not bool(getattr(request.app.state, "native_file_actions", False)):
+ return LaunchersOut(file_manager=False, editors=[])
+ folder = _project_folder(project_id)
+ if folder is None:
+ raise HTTPException(status_code=404, detail="No such project")
+ if not _folder_exists(folder):
+ return LaunchersOut(file_manager=False, editors=[])
+ from jarvis.agentic_ide import project_links
+ from jarvis.ui.web import outputs_routes
+
+ editor_ids = {oid for oid, _ in outputs_routes._OPENER_EDITORS}
+ editors = [
+ LauncherOut(id=entry["id"], label=entry["label"])
+ for entry in outputs_routes._available_openers()
+ if entry["id"] in editor_ids
+ ]
+ remote = project_links.remote_web_url(folder)
+ return LaunchersOut(
+ file_manager=True,
+ editors=editors,
+ remote_url=remote,
+ remote_label=project_links.host_label(remote) if remote else None,
+ )
+
+
+ "/projects/{project_id}/open-in",
+ response_model=RevealedOut,
+ summary="Open a project's folder in an editor or its web page",
+)
+def open_project_in(request: Request, project_id: str, body: OpenInIn) -> RevealedOut:
+ """Open the folder in an installed editor, or the remote's page in the browser.
+
+ ``target`` is a closed id — never a path or a URL from the client — so this
+ cannot launch an arbitrary program or page.
+ """
+ folder = _require_folder(request, project_id)
+ from jarvis.agentic_ide import project_links
+
+ if body.target == "remote":
+ url = project_links.remote_web_url(folder)
+ if url is None:
+ raise HTTPException(status_code=404, detail="This folder has no hosted git remote.")
+ import webbrowser
+
+ return RevealedOut(opened=webbrowser.open(url))
+ from jarvis.platform.open_path import open_file_with
+ from jarvis.ui.web import outputs_routes
+
+ if body.target not in {oid for oid, _ in outputs_routes._OPENER_EDITORS}:
+ raise HTTPException(status_code=400, detail="Unknown editor.")
+ resolved = outputs_routes._resolve_opener(body.target)
+ if resolved is None:
+ raise HTTPException(status_code=409, detail="That editor is not installed.")
+ kind, value = resolved
+ return RevealedOut(opened=open_file_with(Path(folder), kind, value))
# --------------------------------------------------------------------------- #
diff --git a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx
index 375be8d895..e003f6b271 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx
@@ -10,9 +10,11 @@ const openProject = vi.hoisted(() => vi.fn());
const deleteProject = vi.hoisted(() => vi.fn());
const reorderProjects = vi.hoisted(() => vi.fn());
const revealProject = vi.hoisted(() => vi.fn());
+const fetchProjectLaunchers = vi.hoisted(() => vi.fn());
+const openProjectIn = vi.hoisted(() => vi.fn());
const robustCopy = vi.hoisted(() => vi.fn());
vi.mock("@/lib/clipboard", () => ({ robustCopy }));
-vi.mock("@/lib/chatLibraryApi", () => ({ patchProject, openProject, deleteProject, reorderProjects, revealProject,
+vi.mock("@/lib/chatLibraryApi", () => ({ patchProject, openProject, deleteProject, reorderProjects, revealProject, fetchProjectLaunchers, openProjectIn,
ChatLibraryError: class extends Error { constructor(message: string, readonly status: number) { super(message); } },
}));
@@ -20,9 +22,13 @@ const renameWorkspace = vi.hoisted(() => vi.fn());
const closeWorkspace = vi.hoisted(() => vi.fn());
const removeWorkspace = vi.hoisted(() => vi.fn());
const reorderWorkspaces = vi.hoisted(() => vi.fn());
+const addTerminal = vi.hoisted(() => vi.fn());
+const fetchWorkspacePanes = vi.hoisted(() => vi.fn());
+const interruptTerminal = vi.hoisted(() => vi.fn());
+const startIdeSession = vi.hoisted(() => vi.fn());
vi.mock("@/lib/agenticIdeApi", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/agenticIdeApi")>();
- return { ...actual, renameWorkspace, closeWorkspace, removeWorkspace, reorderWorkspaces };
+ return { ...actual, renameWorkspace, closeWorkspace, removeWorkspace, reorderWorkspaces, addTerminal, fetchWorkspacePanes, interruptTerminal, startIdeSession };
});
const project = (id = "p1", pinned = false) => ({ id, path: `/${id}`, name: id === "p1" ? "App" : "New App",
@@ -36,6 +42,18 @@ beforeEach(() => {
deleteProject.mockReset().mockResolvedValue(true);
reorderProjects.mockReset().mockResolvedValue([]);
revealProject.mockReset().mockResolvedValue(true);
+ fetchProjectLaunchers.mockReset().mockResolvedValue({
+ file_manager: true, editors: [{ id: "code", label: "VS Code" }], remote_url: "https://github.com/me/app", remote_label: "GitHub",
+ });
+ openProjectIn.mockReset().mockResolvedValue(true);
+ addTerminal.mockReset().mockResolvedValue({});
+ fetchWorkspacePanes.mockReset().mockResolvedValue({ active_id: "p1-w1", panes: [
+ { workspace_id: "p1-w1", key: "T1", agent: "claude", account: null, activity: "working" },
+ { workspace_id: "p1-w1", key: "T2", agent: "codex", account: "work", activity: "waiting" },
+ { workspace_id: "other", key: "T1", agent: "claude", account: null, activity: "working" },
+ ] });
+ interruptTerminal.mockReset().mockResolvedValue(undefined);
+ startIdeSession.mockReset().mockResolvedValue({});
robustCopy.mockReset().mockResolvedValue(true);
renameWorkspace.mockReset().mockResolvedValue({});
closeWorkspace.mockReset().mockResolvedValue({});
@@ -116,10 +134,6 @@ it("gives every workspace row a ⋯ menu and dispatches Jarvis Live", () => {
expect(screen.getByRole("menu", { name: "Workspace actions for Other" })).toBeDefined();
fireEvent.click(screen.getByRole("button", { name: "Workspace actions for Other" }));
expect(screen.queryByRole("menu")).toBeNull();
- fireEvent.click(screen.getByRole("button", { name: "Workspace actions for Work" }));
- fireEvent.click(screen.getByRole("menuitem", { name: "Workspace options…" }));
- expect(useIdeProjectsStore.getState().action).toMatchObject({ kind: "workspace-options", workspaceId: "p1-w1" });
- expect(screen.queryByRole("menu")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Jarvis Live" }));
expect(useIdeProjectsStore.getState().action?.kind).toBe("toggle-voice");
});
@@ -182,7 +196,7 @@ it("opens a workspace menu on right-click with rename and remove", () => {
expect(screen.getByTestId("ide-workspace-menu")).toBeDefined();
expect(screen.getByTestId("ide-workspace-menu-rename").textContent).toContain("Rename workspace");
expect(screen.getByTestId("ide-workspace-menu-close").textContent).toContain("Remove workspace");
- expect(screen.getByTestId("ide-workspace-menu-open")).toBeDefined();
+ expect(screen.getByTestId("ide-workspace-menu-add").textContent).toContain("Add another agent");
});
it("renames a workspace from its right-click menu", async () => {
@@ -269,32 +283,50 @@ it("removes open workspaces when a project is deleted", async () => {
await waitFor(() => expect(useIdeProjectsStore.getState().refreshRequest?.nonce).toBe(1));
});
-it("groups project actions and runs folder actions", async () => {
+it("offers the project's real launchers and runs them", async () => {
render(<IdeProjectTree />);
fireEvent.click(screen.getByRole("button", { name: "Project actions for App" }));
+ await screen.findByRole("menuitem", { name: "Open on GitHub" });
const menu = screen.getByRole("menu", { name: "Project actions for App" });
- expect(menu.querySelectorAll('[role="group"]').length).toBe(3);
expect(Array.from(menu.querySelectorAll('[role="menuitem"]')).map((item) => item.textContent)).toEqual([
- "New workspace", "Open folder", "Copy folder path", "Rename project", "Pin project", "Delete project",
+ "New workspace", "Open in VS Code", expect.stringMatching(/^Show in /), "Open on GitHub",
+ "Rename project", "Pin project", "Delete project",
]);
- fireEvent.click(screen.getByRole("menuitem", { name: "Open folder" }));
- await waitFor(() => expect(revealProject).toHaveBeenCalledWith("p1"));
+ fireEvent.click(screen.getByRole("menuitem", { name: "Open in VS Code" }));
+ await waitFor(() => expect(openProjectIn).toHaveBeenCalledWith("p1", "code"));
+ fireEvent.click(screen.getByRole("button", { name: "Project actions for App" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Open on GitHub" }));
+ await waitFor(() => expect(openProjectIn).toHaveBeenCalledWith("p1", "remote"));
+});
+
+it("hides launchers the backend cannot offer", async () => {
+ fetchProjectLaunchers.mockRejectedValue(new Error("Not Found"));
+ render(<IdeProjectTree />);
fireEvent.click(screen.getByRole("button", { name: "Project actions for App" }));
- fireEvent.click(screen.getByRole("menuitem", { name: "Copy folder path" }));
- await waitFor(() => expect(robustCopy).toHaveBeenCalledWith("/p1"));
+ await waitFor(() => expect(fetchProjectLaunchers).toHaveBeenCalled());
+ expect(screen.queryByRole("menuitem", { name: /Open in|Open on|Show in/ })).toBeNull();
+ expect(screen.getByRole("menuitem", { name: "New workspace" })).toBeDefined();
});
-it("closes an open workspace but keeps it, separately from removing it", async () => {
+it("adds an agent, duplicates the line-up and interrupts only working agents", async () => {
render(<IdeProjectTree />);
fireEvent.click(screen.getByRole("button", { name: "Workspace actions for Work" }));
- fireEvent.click(screen.getByTestId("ide-workspace-menu-stop"));
- expect(screen.getByRole("dialog", { name: "Close Work?" })).toBeDefined();
- fireEvent.click(screen.getByTestId("ide-workspace-confirm-close-confirm"));
- await waitFor(() => expect(closeWorkspace).toHaveBeenCalledWith("p1-w1"));
- expect(removeWorkspace).not.toHaveBeenCalled();
+ fireEvent.click(await screen.findByRole("menuitem", { name: /Interrupt 1 working agent/ }));
+ await waitFor(() => expect(interruptTerminal).toHaveBeenCalledWith("T1", "p1-w1"));
+ expect(interruptTerminal).toHaveBeenCalledTimes(1);
+
+ fireEvent.click(screen.getByRole("button", { name: "Workspace actions for Work" }));
+ fireEvent.click(await screen.findByRole("menuitem", { name: /Duplicate workspace/ }));
+ await waitFor(() => expect(startIdeSession).toHaveBeenCalledWith(
+ "/p1", [{ agent: "claude" }, { agent: "codex", account: "work" }], { projectId: "p1", name: "Work copy" },
+ ));
+
+ fireEvent.click(screen.getByRole("button", { name: "Workspace actions for Work" }));
+ fireEvent.click(screen.getByRole("menuitem", { name: "Add another agent" }));
+ await waitFor(() => expect(addTerminal).toHaveBeenCalledWith({ workspace_id: "p1-w1" }));
});
-it("offers no close or rename on a closed workspace", () => {
+it("offers a closed workspace only what works on it", async () => {
useIdeProjectsStore.setState({
projects: [{
...project(),
@@ -304,7 +336,9 @@ it("offers no close or rename on a closed workspace", () => {
});
render(<IdeProjectTree />);
fireEvent.contextMenu(screen.getByTestId("ide-workspace-row-p1-w1"));
- expect(screen.queryByTestId("ide-workspace-menu-stop")).toBeNull();
- expect((screen.getByRole("menuitem", { name: /Rename workspace/ }) as HTMLButtonElement).disabled).toBe(true);
+ await screen.findByRole("menuitem", { name: "Open in VS Code" });
expect(screen.getByRole("menuitem", { name: "Reopen workspace" })).toBeDefined();
+ for (const missing of [/Rename workspace/, /Add another agent/, /Duplicate/, /Interrupt/]) {
+ expect(screen.queryByRole("menuitem", { name: missing })).toBeNull();
+ }
});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx
index 981384bd01..7f264fc14c 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx
@@ -1,9 +1,9 @@
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";
import { createPortal } from "react-dom";
-import { ArrowUpRight, Check, ChevronDown, ChevronRight, Copy, Folder, FolderOpen, FolderPlus, Loader2, Mic, MoreHorizontal, Pencil, Pin, PinOff, Plus, Power, SlidersHorizontal, Trash2, X, type LucideIcon } from "lucide-react";
-import { ChatLibraryError, deleteProject, openProject, patchProject, reorderProjects, revealProject } from "@/lib/chatLibraryApi";
+import { ArrowUpRight, Check, ChevronDown, ChevronRight, Copy, CopyPlus, Folder, FolderOpen, FolderPlus, Globe, Loader2, Mic, MoreHorizontal, OctagonPause, Pencil, Pin, PinOff, Plus, SquareCode, Trash2, X, type LucideIcon } from "lucide-react";
+import { ChatLibraryError, deleteProject, openProject, patchProject, reorderProjects, revealProject, fetchProjectLaunchers, openProjectIn, type ProjectLaunchers } from "@/lib/chatLibraryApi";
import { robustCopy } from "@/lib/clipboard";
-import { closeWorkspace, removeWorkspace, renameWorkspace, IdeApiError, reorderWorkspaces, type IdeProject, type ProjectWorkspace } from "@/lib/agenticIdeApi";
+import { addTerminal, fetchWorkspacePanes, interruptTerminal, removeWorkspace, renameWorkspace, startIdeSession, IdeApiError, reorderWorkspaces, type IdeProject, type ProjectWorkspace, type WorkspacePaneRow } from "@/lib/agenticIdeApi";
import { useEventStore } from "@/store/events";
import { useIdeProjectsStore } from "@/store/ideProjects";
@@ -69,7 +69,6 @@ export function IdeProjectTree() {
const connectProject = useIdeProjectsStore((state) => state.connectProject);
const newWorkspace = useIdeProjectsStore((state) => state.newWorkspace);
const activateWorkspace = useIdeProjectsStore((state) => state.activateWorkspace);
- const openWorkspaceOptions = useIdeProjectsStore((state) => state.openWorkspaceOptions);
const toggleVoice = useIdeProjectsStore((state) => state.toggleVoice);
const requestRefresh = useIdeProjectsStore((state) => state.requestRefresh);
const pushToast = useEventStore((state) => state.pushToast);
@@ -89,8 +88,12 @@ export function IdeProjectTree() {
>(null);
const [renamingWorkspaceId, setRenamingWorkspaceId] = useState<string | null>(null);
const [draftWorkspaceName, setDraftWorkspaceName] = useState("");
- // "close" keeps a restorable row; "remove" makes the row go away for good.
- const [confirmWorkspace, setConfirmWorkspace] = useState<{ projectId: string; workspaceId: string; mode: "close" | "remove" } | null>(null);
+ const [confirmWorkspace, setConfirmWorkspace] = useState<{ projectId: string; workspaceId: string } | null>(null);
+ // What the open menu can offer beyond the row itself: the project's editors
+ // and remote, and the panes of the workspace. Fetched when a menu opens, so
+ // an item is only shown when it can actually run.
+ const [launchers, setLaunchers] = useState<Record<string, ProjectLaunchers>>({});
+ const [menuPanes, setMenuPanes] = useState<WorkspacePaneRow[] | null>(null);
const [confirmProject, setConfirmProject] = useState<string | null>(null);
const [confirmBusy, setConfirmBusy] = useState(false);
const sawProjectSnapshot = useRef(false);
@@ -220,6 +223,62 @@ export function IdeProjectTree() {
catch (error) { pushToast("error", revealErrorMessage(error)); }
};
+ const menuProjectId = contextMenu?.projectId ?? null;
+ const menuWorkspaceId = contextMenu?.kind === "workspace" ? contextMenu.workspaceId : null;
+ useEffect(() => {
+ if (!menuProjectId) return;
+ let live = true;
+ fetchProjectLaunchers(menuProjectId)
+ .then((found) => { if (live) setLaunchers((previous) => ({ ...previous, [menuProjectId]: found })); })
+ // A headless or older backend has no launchers; the menu simply omits them.
+ .catch(() => { if (live) setLaunchers((previous) => ({ ...previous, [menuProjectId]: { file_manager: false, editors: [], remote_url: null, remote_label: null } })); });
+ return () => { live = false; };
+ }, [menuProjectId]);
+
+ useEffect(() => {
+ setMenuPanes(null);
+ if (!menuWorkspaceId) return;
+ let live = true;
+ fetchWorkspacePanes()
+ .then((found) => { if (live) setMenuPanes(found.panes.filter((pane) => pane.workspace_id === menuWorkspaceId)); })
+ .catch(() => { if (live) setMenuPanes([]); });
+ return () => { live = false; };
+ }, [menuWorkspaceId]);
+
+ const openIn = async (projectId: string, target: string) => {
+ try { await openProjectIn(projectId, target); }
+ catch (error) { pushToast("error", revealErrorMessage(error)); }
+ };
+
+ /** One more pane of the workspace's own agent, then bring the workspace to the front. */
+ const addAgent = async (workspace: ProjectWorkspace) => {
+ try {
+ await addTerminal({ workspace_id: workspace.id });
+ if (workspace.id !== activeWorkspaceId) activateWorkspace(workspace.id);
+ requestRefresh();
+ } catch (error) { pushToast("error", (error as Error).message); }
+ };
+
+ /** A second workspace in the same folder with the same line-up of agents, freshly started. */
+ const duplicateWorkspace = async (project: IdeProject, workspace: ProjectWorkspace, panes: WorkspacePaneRow[]) => {
+ try {
+ await startIdeSession(
+ workspace.folder || project.path,
+ panes.map((pane) => ({ agent: pane.agent, ...(pane.account ? { account: pane.account } : {}) })),
+ { projectId: project.id, name: `${workspace.name} copy` },
+ );
+ requestRefresh();
+ } catch (error) { pushToast("error", (error as Error).message); }
+ };
+
+ /** Escape to every agent that is busy — they stop the current task and keep running. */
+ const interruptAgents = async (workspace: ProjectWorkspace, panes: WorkspacePaneRow[]) => {
+ const results = await Promise.allSettled(panes.map((pane) => interruptTerminal(pane.key, workspace.id)));
+ const failed = results.filter((result) => result.status === "rejected").length;
+ if (failed) pushToast("error", `${failed} of ${panes.length} agents could not be interrupted.`);
+ else pushToast("success", `Interrupted ${panes.length} ${panes.length === 1 ? "agent" : "agents"}.`);
+ };
+
const submitWorkspaceRename = async (workspace: ProjectWorkspace) => {
const name = draftWorkspaceName.trim();
if (!name || name === workspace.name) {
@@ -251,8 +310,7 @@ export function IdeProjectTree() {
}
setConfirmBusy(true);
try {
- if (confirmWorkspace.mode === "close") await closeWorkspace(target.workspace.id);
- else await removeWorkspace(target.workspace.id);
+ await removeWorkspace(target.workspace.id);
setConfirmWorkspace(null);
setContextMenu(null);
requestRefresh();
@@ -535,11 +593,27 @@ export function IdeProjectTree() {
const run = (action: () => void) => () => { setContextMenu(null); action(); };
+ /** Up to two installed editors and the hosted remote, as menu items. */
+ const launcherItems = (project: IdeProject, scope: "project" | "workspace"): TreeMenuItem[] => {
+ const found = launchers[project.id];
+ if (!found) return [];
+ const items: TreeMenuItem[] = found.editors.slice(0, 2).map((editor) => ({
+ id: `editor-${editor.id}`, label: `Open in ${editor.label}`, icon: SquareCode, testId: `ide-${scope}-menu-editor-${editor.id}`,
+ onSelect: run(() => void openIn(project.id, editor.id)),
+ }));
+ if (scope === "project" && found.file_manager) {
+ items.push({ id: "reveal", label: FILE_MANAGER_LABEL, icon: FolderOpen, testId: "ide-project-menu-reveal", onSelect: run(() => void revealFolder(project.id)) });
+ }
+ if (scope === "project" && found.remote_url) {
+ items.push({ id: "remote", label: `Open on ${found.remote_label ?? "the web"}`, icon: Globe, testId: "ide-project-menu-remote", onSelect: run(() => void openIn(project.id, "remote")) });
+ }
+ return items;
+ };
+
const projectMenuSections = (project: IdeProject): TreeMenuItem[][] => [
[
{ id: "new", label: "New workspace", icon: FolderPlus, testId: "ide-project-menu-new", onSelect: run(() => newWorkspace(project.id)) },
- { id: "reveal", label: "Open folder", icon: FolderOpen, testId: "ide-project-menu-reveal", disabled: project.exists === false, onSelect: run(() => void revealFolder(project.id)) },
- { id: "copy", label: "Copy folder path", icon: Copy, testId: "ide-project-menu-copy", onSelect: run(() => void copyPath(project.path)) },
+ ...launcherItems(project, "project"),
],
[
{ id: "rename", label: "Rename project", icon: Pencil, testId: "ide-project-menu-rename", onSelect: run(() => { setDraftName(project.name); setRenamingId(project.id); }) },
@@ -552,26 +626,33 @@ export function IdeProjectTree() {
const workspaceMenuSections = (project: IdeProject, workspace: ProjectWorkspace): TreeMenuItem[][] => {
const isOpen = workspace.status === "open";
- const isActive = workspace.id === activeWorkspaceId;
- const unavailable = !isOpen && !workspace.restorable;
+ const panes = menuPanes ?? [];
+ const busy = panes.filter((pane) => pane.activity === "working" || pane.activity === "asking");
+ const agentActions: TreeMenuItem[] = isOpen ? [
+ { id: "add", label: "Add another agent", icon: Plus, testId: "ide-workspace-menu-add", onSelect: run(() => void addAgent(workspace)) },
+ { id: "duplicate", label: "Duplicate workspace", icon: CopyPlus, testId: "ide-workspace-menu-duplicate", disabled: panes.length === 0,
+ hint: panes.length ? `Starts ${panes.length} fresh ${panes.length === 1 ? "agent" : "agents"}` : undefined,
+ onSelect: run(() => void duplicateWorkspace(project, workspace, panes)) },
+ ...(busy.length ? [{ id: "interrupt", label: `Interrupt ${busy.length} working ${busy.length === 1 ? "agent" : "agents"}`, icon: OctagonPause,
+ testId: "ide-workspace-menu-interrupt", hint: "Stops the current task, keeps the chat", onSelect: run(() => void interruptAgents(workspace, busy)) }] : []),
+ ] : [
+ { id: "reopen", label: "Reopen workspace", icon: ArrowUpRight, testId: "ide-workspace-menu-open", disabled: !workspace.restorable,
+ hint: workspace.restorable ? undefined : "Its folder is not reachable",
+ onSelect: run(() => { activateWorkspace(workspace.id); setProjectOpen(project.id, true); }) },
+ ];
return [
+ agentActions,
[
- { id: "open", label: isActive ? "Current workspace" : isOpen ? "Switch to workspace" : "Reopen workspace", icon: ArrowUpRight, testId: "ide-workspace-menu-open",
- disabled: isActive || unavailable, onSelect: run(() => { activateWorkspace(workspace.id); setProjectOpen(project.id, true); }) },
- { id: "rename", label: "Rename workspace", icon: Pencil, testId: "ide-workspace-menu-rename", disabled: !isOpen,
- hint: isOpen ? undefined : "Reopen it to rename",
- onSelect: run(() => { setDraftWorkspaceName(workspace.name); setRenamingWorkspaceId(workspace.id); setProjectOpen(project.id, true); }) },
- ...(isOpen ? [{ id: "options", label: "Workspace options…", icon: SlidersHorizontal, testId: "ide-workspace-menu-options", onSelect: run(() => openWorkspaceOptions(workspace.id)) }] : []),
- ],
- [
- { id: "reveal", label: "Open folder", icon: FolderOpen, testId: "ide-workspace-menu-reveal", onSelect: run(() => void revealFolder(project.id)) },
+ ...launcherItems(project, "workspace"),
{ id: "copy", label: "Copy folder path", icon: Copy, testId: "ide-workspace-menu-copy", onSelect: run(() => void copyPath(workspace.folder || project.path)) },
],
+ isOpen ? [
+ { id: "rename", label: "Rename workspace", icon: Pencil, testId: "ide-workspace-menu-rename",
+ onSelect: run(() => { setDraftWorkspaceName(workspace.name); setRenamingWorkspaceId(workspace.id); setProjectOpen(project.id, true); }) },
+ ] : [],
[
- ...(isOpen ? [{ id: "close", label: "Close workspace", icon: Power, testId: "ide-workspace-menu-stop", hint: "Stops its agents, keeps the row",
- onSelect: run(() => setConfirmWorkspace({ projectId: project.id, workspaceId: workspace.id, mode: "close" })) }] : []),
{ id: "remove", label: "Remove workspace", icon: Trash2, testId: "ide-workspace-menu-close", destructive: true,
- onSelect: run(() => setConfirmWorkspace({ projectId: project.id, workspaceId: workspace.id, mode: "remove" })) },
+ onSelect: run(() => setConfirmWorkspace({ projectId: project.id, workspaceId: workspace.id })) },
],
];
};
@@ -620,18 +701,11 @@ export function IdeProjectTree() {
)}
{confirmWorkspaceTarget && (
<ConfirmTreeAction
- title={`${confirmWorkspace?.mode === "close" ? "Close" : "Remove"} ${confirmWorkspaceTarget.workspace.name}?`}
- body={(() => {
- const { workspace } = confirmWorkspaceTarget;
- const agents = `${workspace.terminals} coding ${workspace.terminals === 1 ? "agent" : "agents"}`;
- if (confirmWorkspace?.mode === "close") return `Its ${agents} will stop. The workspace stays in the sidebar, so you can reopen it later.`;
- return workspace.status === "open"
- ? `Its ${agents} will stop and the workspace leaves the sidebar. The folder on disk and its chats stay untouched.`
- : "The workspace leaves the sidebar. The folder on disk and its chats stay untouched.";
- })()}
- confirmLabel={confirmWorkspace?.mode === "close"
- ? (confirmBusy ? "Closing…" : `Close ${confirmWorkspaceTarget.workspace.name}`)
- : (confirmBusy ? "Removing…" : `Remove ${confirmWorkspaceTarget.workspace.name}`)}
+ title={`Remove ${confirmWorkspaceTarget.workspace.name}?`}
+ body={confirmWorkspaceTarget.workspace.status === "open"
+ ? `Its ${confirmWorkspaceTarget.workspace.terminals} coding ${confirmWorkspaceTarget.workspace.terminals === 1 ? "agent" : "agents"} will stop and the workspace leaves the sidebar. The folder on disk and its chats stay untouched.`
+ : "The workspace leaves the sidebar. The folder on disk and its chats stay untouched."}
+ confirmLabel={confirmBusy ? "Removing…" : `Remove ${confirmWorkspaceTarget.workspace.name}`}
busy={confirmBusy}
testId="ide-workspace-confirm-close"
onCancel={() => {
@@ -663,7 +737,15 @@ export function IdeProjectTree() {
</div>;
}
-const TREE_MENU_WIDTH = 230;
+const TREE_MENU_WIDTH = 240;
+
+/** What the OS calls its file manager, for the "show the folder" item. */
+const FILE_MANAGER_LABEL = (() => {
+ const platform = typeof navigator === "undefined" ? "" : navigator.userAgent;
+ if (/Windows/i.test(platform)) return "Show in Explorer";
+ if (/Mac OS X|Macintosh/i.test(platform)) return "Show in Finder";
+ return "Show in file manager";
+})();
const TREE_MENU_MARGIN = 8;
/** One row of the sidebar's action menu. */
diff --git a/jarvis/ui/web/frontend/src/lib/chatLibraryApi.ts b/jarvis/ui/web/frontend/src/lib/chatLibraryApi.ts
index 115129eaf1..422c5aa9e8 100644
--- a/jarvis/ui/web/frontend/src/lib/chatLibraryApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/chatLibraryApi.ts
@@ -150,6 +150,27 @@ export async function revealProject(projectId: string): Promise<boolean> {
return body.opened;
}
+/** Where a project's folder can be opened on this machine right now. */
+export interface ProjectLaunchers {
+ file_manager: boolean;
+ editors: { id: string; label: string }[];
+ remote_url: string | null;
+ remote_label: string | null;
+}
+
+export function fetchProjectLaunchers(projectId: string): Promise<ProjectLaunchers> {
+ return request<ProjectLaunchers>(`/projects/${encodeURIComponent(projectId)}/launchers`);
+}
+
+/** Open the folder in an editor from `fetchProjectLaunchers`, or `"remote"` for its web page. */
+export async function openProjectIn(projectId: string, target: string): Promise<boolean> {
+ const body = await request<{ opened: boolean }>(
+ `/projects/${encodeURIComponent(projectId)}/open-in`,
+ { method: "POST", body: JSON.stringify({ target }) },
+ );
+ return body.opened;
+}
+
/**
* Persist a drag-and-drop folder order in the sidebar.
*
diff --git a/tests/unit/agentic_ide/test_chat_library_routes.py b/tests/unit/agentic_ide/test_chat_library_routes.py
index f958e42bee..32f1b8ff36 100644
--- a/tests/unit/agentic_ide/test_chat_library_routes.py
+++ b/tests/unit/agentic_ide/test_chat_library_routes.py
@@ -286,3 +286,53 @@ def test_reveal_is_desktop_only(client: TestClient, tmp_path: Path) -> None:
def test_reveal_refuses_an_unknown_project(client: TestClient) -> None:
client.app.state.native_file_actions = True
assert client.post("/api/chat-library/projects/nope/reveal").status_code == 404
+
+
+def test_launchers_list_only_what_is_available(
+ client: TestClient, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from jarvis.agentic_ide import project_links
+ from jarvis.ui.web import outputs_routes
+
+ monkeypatch.setattr(
+ outputs_routes,
+ "_available_openers",
+ lambda: [
+ {"id": "default", "label": "System default app"},
+ {"id": "cursor", "label": "Cursor"},
+ ],
+ )
+ monkeypatch.setattr(project_links, "remote_web_url", lambda folder: "https://github.com/me/app")
+ client.app.state.native_file_actions = True
+ project = library.ensure_project(tmp_path)
+ body = client.get(f"/api/chat-library/projects/{project.id}/launchers").json()
+ assert body == {
+ "file_manager": True,
+ "editors": [{"id": "cursor", "label": "Cursor"}],
+ "remote_url": "https://github.com/me/app",
+ "remote_label": "GitHub",
+ }
+
+
+def test_launchers_are_empty_on_a_headless_host(client: TestClient, tmp_path: Path) -> None:
+ project = library.ensure_project(tmp_path)
+ body = client.get(f"/api/chat-library/projects/{project.id}/launchers").json()
+ assert body["editors"] == [] and body["file_manager"] is False
+
+
+def test_open_in_accepts_only_known_editors(client: TestClient, tmp_path: Path) -> None:
+ client.app.state.native_file_actions = True
+ project = library.ensure_project(tmp_path)
+ response = client.post(
+ f"/api/chat-library/projects/{project.id}/open-in", json={"target": "calc.exe"}
+ )
+ assert response.status_code == 400
+
+
+def test_open_in_remote_needs_a_remote(client: TestClient, tmp_path: Path) -> None:
+ client.app.state.native_file_actions = True
+ project = library.ensure_project(tmp_path)
+ response = client.post(
+ f"/api/chat-library/projects/{project.id}/open-in", json={"target": "remote"}
+ )
+ assert response.status_code == 404
diff --git a/tests/unit/agentic_ide/test_project_links.py b/tests/unit/agentic_ide/test_project_links.py
new file mode 100644
index 0000000000..2b7639a69f
--- /dev/null
+++ b/tests/unit/agentic_ide/test_project_links.py
@@ -0,0 +1,48 @@
+"""A project's hosted remote, as the sidebar's "Open on GitHub" needs it."""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from jarvis.agentic_ide import project_links
+
+
+ ("remote", "expected"),
+ [
+ ("[email protected]:owner/repo.git", "https://github.com/owner/repo"),
+ ("https://github.com/owner/repo.git\n", "https://github.com/owner/repo"),
+ ("https://x-token:[email protected]/owner/repo", "https://github.com/owner/repo"),
+ ("ssh://[email protected]/group/sub/repo.git", "https://gitlab.com/group/sub/repo"),
+ ("../local/mirror.git", None),
+ ("file:///srv/repo.git", None),
+ ("", None),
+ ],
+)
+def test_remote_becomes_a_safe_web_address(remote: str, expected: str | None) -> None:
+ assert project_links.web_url(remote) == expected
+
+
+def test_host_label_names_the_forge() -> None:
+ assert project_links.host_label("https://github.com/a/b") == "GitHub"
+ assert project_links.host_label("https://gitlab.example.org/a/b") == "GitLab"
+ assert project_links.host_label("https://code.example.org/a/b") == "code.example.org"
+
+
+def test_a_folder_without_git_has_no_remote(tmp_path: Path) -> None:
+ assert project_links.remote_web_url(tmp_path) is None
+
+
+def test_reads_the_origin_of_a_real_repository(tmp_path: Path) -> None:
+ git = pytest.importorskip("shutil").which("git")
+ if git is None:
+ pytest.skip("git is not installed")
+ subprocess.run([git, "init", "-q", str(tmp_path)], check=True) # noqa: S603
+ subprocess.run( # noqa: S603
+ [git, "-C", str(tmp_path), "remote", "add", "origin", "[email protected]:me/app.git"],
+ check=True,
+ )
+ assert project_links.remote_web_url(tmp_path) == "https://github.com/me/app"