Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(ide): make removing a workspace or project drop its sidebar row
rubenluetke10-beepbdf85abb32d3
diff --git a/jarvis/agentic_ide/resume_store.py b/jarvis/agentic_ide/resume_store.pyindex 5098987af0..f510bca199 100644--- a/jarvis/agentic_ide/resume_store.py+++ b/jarvis/agentic_ide/resume_store.py@@ -432,21 +432,71 @@ def save(snapshot: Snapshot) -> None:# would render as a card with no panes in it.clear()return+ with _WRITE_LOCK:+ _write_locked(_merged_with_stored(snapshot))+++def _write_locked(snapshot: Snapshot) -> None:+ """Replace the stored file with ``snapshot`` as-is. Caller holds ``_WRITE_LOCK``."""target = _store_path()tmp = target.with_name(f"{target.name}.tmp-{os.getpid()}-{uuid4().hex[:8]}")- with _WRITE_LOCK:- snapshot = _merged_with_stored(snapshot)+ try:+ target.parent.mkdir(parents=True, exist_ok=True)+ tmp.write_text(json.dumps(snapshot.to_dict(), indent=2), encoding="utf-8")+ os.replace(tmp, target)+ except OSError as exc:+ logger.warning("Agentic IDE: could not persist the resume snapshot: {}", exc)+ # Never leave a half-written temp file behind to be found later.try:- target.parent.mkdir(parents=True, exist_ok=True)- tmp.write_text(json.dumps(snapshot.to_dict(), indent=2), encoding="utf-8")- os.replace(tmp, target)- except OSError as exc:- logger.warning("Agentic IDE: could not persist the resume snapshot: {}", exc)- # Never leave a half-written temp file behind to be found later.- try:- tmp.unlink(missing_ok=True)- except OSError: # noqa: S110 - cleanup is best-effort- pass+ tmp.unlink(missing_ok=True)+ except OSError: # noqa: S110 - cleanup is best-effort+ pass+++def forget(*, session_ids: set[str] | None = None, project_id: str | None = None) -> int:+ """Drop remembered workspaces for good. Returns how many were removed.++ The sidebar lists every remembered workspace as a closed row, and a project+ whose library entry is gone is re-derived from those rows — so removing a+ workspace or deleting a project has to reach this file, or the row comes+ straight back on the next refresh. Matches by workspace id, or by owning+ project (the stored id, else the id derived from the folder). Only the+ record goes; the folder on disk is never touched.++ A later ``save`` cannot bring a forgotten record back: the merge only keeps+ what is still stored plus what is open at that moment.+ """+ ids = session_ids or set()++ def doomed(space: SnapshotWorkspace) -> bool:+ if space.session_id in ids:+ return True+ if project_id is None:+ return False+ return project_id in (space.project_id, project_id_for(space.folder))++ with _WRITE_LOCK:+ stored = load()+ if stored is None:+ return 0+ kept = [space for space in stored.workspaces if not doomed(space)]+ removed = len(stored.workspaces) - len(kept)+ if removed == 0:+ return 0+ if not kept:+ clear()+ return removed+ kept_ids = {space.session_id for space in kept}+ _write_locked(+ Snapshot(+ saved_at=stored.saved_at,+ workspaces=kept,+ active_session_id=(+ stored.active_session_id if stored.active_session_id in kept_ids else ""+ ),+ )+ )+ return removed# How many CLOSED workspaces one restore point may remember in addition to all@@ -691,6 +741,7 @@ __all__ = ["SnapshotWorkspace","clear","folder_key",+ "forget","load","offer","save",diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex d1f70ca241..e8cd41e890 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -2617,6 +2617,25 @@ class Registry:await self._close_locked(target)return True+ async def remove_workspace(self, workspace_id: str) -> bool:+ """Remove a workspace for good: stop its agents and forget its record.++ What the sidebar's "Remove workspace" means, as opposed to ``end``:+ closing keeps the workspace as a closed, restorable row; removing makes+ the row go away. Works on an open workspace and on a remembered closed+ one alike. The folder on disk is never touched. False when the id is+ neither open nor remembered.+ """+ async with self._lock:+ closed = workspace_id in self._sessions+ if closed:+ await self._close_locked(workspace_id)+ # Under the persist lock so a save that read the old state cannot land+ # after the record is gone and write it straight back.+ async with self._persist_lock:+ forgotten = await asyncio.to_thread(resume_store.forget, session_ids={workspace_id})+ return closed or forgotten > 0+async def close_all(self) -> int:"""Close every open workspace. Returns how many were closed.diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex d55f5099fe..3627c3b5f6 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -2131,6 +2131,28 @@ async def close_workspace(request: Request, workspace_id: str) -> dict:return {"ok": True, "closed": workspace_id, "state": registry.state()}+ "/workspaces/{workspace_id}/record",+ summary="Remove one workspace from the sidebar",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def remove_workspace(request: Request, workspace_id: str) -> dict:+ """Stop the workspace's agents if it is open and forget it for good.++ Unlike ``DELETE /workspaces/{workspace_id}``, which keeps a closed,+ restorable row, this makes the row disappear. Works on open and remembered+ (closed) workspaces. The folder on disk is never touched.++ ``404`` when the id is neither open nor remembered.+ """+ registry = get_registry()+ if not await registry.remove_workspace(workspace_id):+ raise HTTPException(status_code=404, detail="That workspace no longer exists.")+ await _announce_coding_mode(request)+ await _announce_workspace(request, registry.session, "closed")+ return {"ok": True, "removed": workspace_id, "state": registry.state()}++async def _installed_agents() -> set[str]:"""Coding CLIs this machine can actually launch, right now.diff --git a/jarvis/ui/web/chat_library_routes.py b/jarvis/ui/web/chat_library_routes.pyindex 7b250e1793..ab3f4dd1be 100644--- a/jarvis/ui/web/chat_library_routes.py+++ b/jarvis/ui/web/chat_library_routes.py@@ -40,7 +40,7 @@ from typing import Anyfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field-from jarvis.agentic_ide import library+from jarvis.agentic_ide import library, resume_storerouter = APIRouter(prefix="/api/chat-library", tags=["chat-library"])@@ -264,7 +264,12 @@ def patch_project(project_id: str, body: PatchProjectIn) -> ProjectOut:openapi_extra={"x-jarvis-dangerous": True},)def delete_project(project_id: str) -> RemovedOut:- return RemovedOut(removed=library.delete_project(project_id))+ # The IDE sidebar re-derives a project row from every remembered workspace+ # in its folder, so the remembered ones have to go too or the project comes+ # straight back. Open workspaces are the caller's to close first.+ removed = library.delete_project(project_id)+ forgotten = resume_store.forget(project_id=project_id)+ return RemovedOut(removed=removed or forgotten > 0)# --------------------------------------------------------------------------- #diff --git a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsxindex e3b7f5c63b..69ec8ed879 100644--- a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.test.tsx@@ -15,10 +15,11 @@ vi.mock("@/lib/chatLibraryApi", () => ({ patchProject, openProject, deleteProjecconst renameWorkspace = vi.hoisted(() => vi.fn());const closeWorkspace = vi.hoisted(() => vi.fn());+const removeWorkspace = vi.hoisted(() => vi.fn());const reorderWorkspaces = vi.hoisted(() => vi.fn());vi.mock("@/lib/agenticIdeApi", async (importOriginal) => {const actual = await importOriginal<typeof import("@/lib/agenticIdeApi")>();- return { ...actual, renameWorkspace, closeWorkspace, reorderWorkspaces };+ return { ...actual, renameWorkspace, closeWorkspace, removeWorkspace, reorderWorkspaces };});const project = (id = "p1", pinned = false) => ({ id, path: `/${id}`, name: id === "p1" ? "App" : "New App",@@ -33,6 +34,7 @@ beforeEach(() => {reorderProjects.mockReset().mockResolvedValue([]);renameWorkspace.mockReset().mockResolvedValue({});closeWorkspace.mockReset().mockResolvedValue({});+ removeWorkspace.mockReset().mockResolvedValue({});reorderWorkspaces.mockReset().mockResolvedValue({});useIdeProjectsStore.setState({ projects: [project()], activeWorkspaceId: "p1-w1", pendingWorkspaceId: null, refreshRequest: null, action: null });});@@ -159,13 +161,13 @@ it("submits only one metadata mutation when a project action is pressed twice",await waitFor(() => expect(useIdeProjectsStore.getState().refreshRequest?.nonce).toBe(1));});-it("opens a workspace menu on right-click with rename and close", () => {+it("opens a workspace menu on right-click with rename and remove", () => {render(<IdeProjectTree />);const row = screen.getByTestId("ide-workspace-row-p1-w1");fireEvent.contextMenu(row);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("Close workspace");+ expect(screen.getByTestId("ide-workspace-menu-close").textContent).toContain("Remove workspace");expect(screen.getByTestId("ide-workspace-menu-open")).toBeDefined();});@@ -179,17 +181,35 @@ it("renames a workspace from its right-click menu", async () => {await waitFor(() => expect(useIdeProjectsStore.getState().refreshRequest?.nonce).toBe(1));});-it("asks for confirmation before closing a workspace", async () => {+it("asks for confirmation before removing a workspace", async () => {render(<IdeProjectTree />);fireEvent.contextMenu(screen.getByTestId("ide-workspace-row-p1-w1"));fireEvent.click(screen.getByTestId("ide-workspace-menu-close"));expect(screen.getByTestId("ide-workspace-confirm-close")).toBeDefined();- expect(closeWorkspace).not.toHaveBeenCalled();+ expect(removeWorkspace).not.toHaveBeenCalled();fireEvent.click(screen.getByTestId("ide-workspace-confirm-close-confirm"));- await waitFor(() => expect(closeWorkspace).toHaveBeenCalledWith("p1-w1"));+ // Remove, not close: a close would leave a closed row behind in the sidebar.+ await waitFor(() => expect(removeWorkspace).toHaveBeenCalledWith("p1-w1"));+ expect(closeWorkspace).not.toHaveBeenCalled();await waitFor(() => expect(useIdeProjectsStore.getState().refreshRequest?.nonce).toBe(1));});+it("removes a closed workspace too", async () => {+ useIdeProjectsStore.setState({+ projects: [{+ ...project(),+ workspaces: [{ ...project().workspaces[0], status: "closed", live_terminals: 0 } as IdeProject["workspaces"][number]],+ }],+ activeWorkspaceId: null,+ });+ render(<IdeProjectTree />);+ fireEvent.contextMenu(screen.getByTestId("ide-workspace-row-p1-w1"));+ expect(screen.getByTestId("ide-workspace-menu-close").textContent).toContain("Remove workspace");+ fireEvent.click(screen.getByTestId("ide-workspace-menu-close"));+ fireEvent.click(screen.getByTestId("ide-workspace-confirm-close-confirm"));+ await waitFor(() => expect(removeWorkspace).toHaveBeenCalledWith("p1-w1"));+});+it("asks for confirmation before deleting a project with no open workspaces", async () => {useIdeProjectsStore.setState({projects: [{diff --git a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsxindex 89d036cf88..76d47369e3 100644--- a/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/IdeProjectTree.tsx@@ -2,7 +2,7 @@ import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent as Reaimport { createPortal } from "react-dom";import { Check, ChevronDown, ChevronRight, Folder, FolderPlus, Loader2, Mic, MoreHorizontal, Pencil, Pin, Plus, Trash2, X } from "lucide-react";import { ChatLibraryError, deleteProject, openProject, patchProject, reorderProjects } from "@/lib/chatLibraryApi";-import { closeWorkspace, renameWorkspace, IdeApiError, reorderWorkspaces, type IdeProject, type ProjectWorkspace } from "@/lib/agenticIdeApi";+import { closeWorkspace, removeWorkspace, renameWorkspace, IdeApiError, reorderWorkspaces, type IdeProject, type ProjectWorkspace } from "@/lib/agenticIdeApi";import { useEventStore } from "@/store/events";import { useIdeProjectsStore } from "@/store/ideProjects";@@ -218,7 +218,7 @@ export function IdeProjectTree() {}setConfirmBusy(true);try {- await closeWorkspace(target.workspace.id);+ await removeWorkspace(target.workspace.id);setConfirmWorkspace(null);setContextMenu(null);requestRefresh();@@ -590,13 +590,13 @@ export function IdeProjectTree() {)}{confirmWorkspaceTarget && (<ConfirmTreeAction- title={`Close ${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. You can reopen it later from this project.`- : "This removes the saved workspace from this project. Its chats stay in the library."+ ? `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 ? "Closing…" : `Close ${confirmWorkspaceTarget.workspace.name}`}+ confirmLabel={confirmBusy ? "Removing…" : `Remove ${confirmWorkspaceTarget.workspace.name}`}busy={confirmBusy}testId="ide-workspace-confirm-close"onCancel={() => {@@ -812,7 +812,7 @@ function TreeContextMenu({className="flex w-full items-center gap-2 px-3 py-1.5 text-left text-xs text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-50"><Trash2 aria-hidden className="h-3.5 w-3.5 shrink-0" />- {isOpen === false ? "Remove workspace" : "Close workspace"}+ Remove workspace</button>)}{kind === "project" && onDeleteProject && (diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex 628bce43c2..69f1e7e7fc 100644--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts@@ -1329,6 +1329,21 @@ export async function closeWorkspace(id: string): Promise<IdeState> {return body.state;}+/**+ * Remove ONE workspace for good: stop its agents if it is open and forget its+ * saved record, so the sidebar row disappears instead of turning into a closed+ * one. The folder on disk is untouched. Returns the state that is left.+ */+export async function removeWorkspace(id: string): Promise<IdeState> {+ const res = await fetch(+ `/api/agentic-ide/workspaces/${encodeURIComponent(id)}/record`,+ { method: "DELETE" },+ );+ if (!res.ok) throw new Error(await detail(res));+ const body = (await res.json()) as { state: IdeState };+ return body.state;+}+/** What reopening the last workspace would bring back, checked against this machine. */export function fetchResumeOffer(): Promise<ResumeOffer> {return getJson<ResumeOffer>("/api/agentic-ide/resume");diff --git a/tests/unit/agentic_ide/test_workspace_removal.py b/tests/unit/agentic_ide/test_workspace_removal.pynew file mode 100644index 0000000000..76010e6941--- /dev/null+++ b/tests/unit/agentic_ide/test_workspace_removal.py@@ -0,0 +1,104 @@+"""Removing a workspace or a project makes its sidebar row go away for good.++Closing keeps a closed, restorable row; removing must not. The sidebar derives+closed rows — and even whole project rows — from the remembered workspaces in+the resume store, so a removal that only touches the registry or the project+library leaves the row on screen. The folder on disk is never touched.+"""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from jarvis.agentic_ide import library, resume_store, session, workspace_catalog+from jarvis.ui.web import agentic_ide_routes as routes+from jarvis.ui.web import chat_library_routes+from tests.fakes.fake_pty_manager import FakePtyManager+++def registry(monkeypatch: pytest.MonkeyPatch) -> session.Registry:+ monkeypatch.setattr(session, "agent_argv", lambda agent: (f"/usr/bin/{agent}",))+ instance = session.Registry(pty_manager=FakePtyManager())+ monkeypatch.setattr(routes, "get_registry", lambda: instance)+ return instance+++def request() -> SimpleNamespace:+ return SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(bus=None)))+++def _row_ids(registry: session.Registry) -> set[str]:+ graph = workspace_catalog.project_graph(registry)+ return {w["id"] for p in graph["projects"] for w in p["workspaces"]}+++async def test_removing_an_open_workspace_stops_it_and_drops_the_row(registry, tmp_path):+ first = await registry.start(str(tmp_path), [{"agent": "claude"}], name="First")+ second = await registry.start(str(tmp_path), [{"agent": "codex"}], name="Second")+ result = await routes.remove_workspace(request(), first.id)+ assert result["removed"] == first.id+ assert registry.get(first.id) is None+ assert _row_ids(registry) == {second.id}+ # A later save of the still-open sibling must not bring the record back.+ await registry.rename(second.id, "Still running")+ assert {w.session_id for w in resume_store.load().workspaces} == {second.id}+ assert tmp_path.is_dir()+++async def test_removing_a_closed_workspace_drops_the_row(registry, tmp_path):+ first = await registry.start(str(tmp_path), [{"agent": "claude"}], name="First")+ second = await registry.start(str(tmp_path), [{"agent": "codex"}], name="Second")+ await registry.end(first.id)+ assert first.id in _row_ids(registry)+ await routes.remove_workspace(request(), first.id)+ assert _row_ids(registry) == {second.id}+++async def test_removing_an_unknown_workspace_is_a_404(registry):+ with pytest.raises(HTTPException) as caught:+ await routes.remove_workspace(request(), "ide_missing")+ assert caught.value.status_code == 404+++async def test_deleting_a_project_forgets_its_closed_workspaces(registry, tmp_path: Path):+ kept_dir = tmp_path / "kept"+ gone_dir = tmp_path / "gone"+ kept_dir.mkdir()+ gone_dir.mkdir()+ gone = library.ensure_project(gone_dir, name="Gone")+ kept = await registry.start(str(kept_dir), [{"agent": "claude"}], name="Kept")+ doomed = await registry.start(+ str(gone_dir), [{"agent": "claude"}], project_id=gone.id, name="Doomed"+ )+ await registry.end(doomed.id)++ assert chat_library_routes.delete_project(gone.id).removed is True++ graph = workspace_catalog.project_graph(registry)+ assert gone.id not in {p["id"] for p in graph["projects"]}+ assert _row_ids(registry) == {kept.id}+ assert gone_dir.is_dir()+++def test_deleting_a_project_known_only_from_its_workspaces_still_removes_it(tmp_path: Path):+ # Older installs derive the project row from the folder alone; there is no+ # library entry to delete, and the row must still go.+ resume_store.save(+ resume_store.snapshot_now(+ [+ resume_store.SnapshotWorkspace(+ session_id="ide_old",+ folder=str(tmp_path),+ terminals=[resume_store.SnapshotTerminal(key="a", name="A", agent="claude")],+ )+ ]+ )+ )+ derived = library.project_id_for(tmp_path)+ assert chat_library_routes.delete_project(derived).removed is True+ assert resume_store.load() is None