Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(workspace): allow removing missing workspace repos from UI (#2253)

Rishabh Mishra5d54c12e5b55
diff --git a/packages/api-client/src/types/workspace.ts b/packages/api-client/src/types/workspace.ts
index 5c0e9dd8c..519e0879e 100644
--- a/packages/api-client/src/types/workspace.ts
+++ b/packages/api-client/src/types/workspace.ts
@@ -37,6 +37,12 @@ export interface WorkspaceSyncResponse {
results: WorkspaceSyncResult[];
}
+export interface WorkspaceRepoRemovedResponse {
+ ok: boolean;
+ alias: string;
+ remaining_repos: number;
+}
+
export interface WorkspaceCrossRepoSummary {
co_change_count: number;
package_dep_count: number;
diff --git a/packages/api-client/src/workspace.ts b/packages/api-client/src/workspace.ts
index dd48437d2..abc6e7c61 100644
--- a/packages/api-client/src/workspace.ts
+++ b/packages/api-client/src/workspace.ts
@@ -1,10 +1,11 @@
-import { apiGet, apiPost } from "./client";
+import { apiDelete, apiGet, apiPost } from "./client";
import type {
WorkspaceResponse,
WorkspaceContractsResponse,
WorkspaceContractDetail,
WorkspaceCoChangesResponse,
WorkspaceGraphResponse,
+ WorkspaceRepoRemovedResponse,
WorkspaceSyncResponse,
WorkspaceSystemGraphResponse,
WorkspaceBlastRadiusResponse,
@@ -195,3 +196,17 @@ export async function getWorkspaceTestImpact(
fetchOptions,
);
}
+
+/**
+ * Remove a repository entry from `.repowise-workspace.yaml`.
+ */
+export async function removeWorkspaceRepo(
+ alias: string,
+ fetchOptions?: RequestInit,
+): Promise<WorkspaceRepoRemovedResponse> {
+ return apiDelete<WorkspaceRepoRemovedResponse>(
+ `/api/workspace/repos/${encodeURIComponent(alias)}`,
+ fetchOptions,
+ );
+}
+
diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.py
index 4f87baf19..9dfe558a7 100644
--- a/packages/server/src/repowise/server/routers/repos.py
+++ b/packages/server/src/repowise/server/routers/repos.py
@@ -568,6 +568,23 @@ async def delete_repo(
fts=Depends(get_fts),
) -> dict:
"""Delete a repository and all its data."""
+ if repo_id.startswith("ws:"):
+ alias = repo_id[3:]
+ ws_config = getattr(request.app.state, "workspace_config", None)
+ ws_root = getattr(request.app.state, "workspace_root", None)
+ if ws_config is not None and ws_root is not None:
+ ws_root_path = Path(ws_root)
+ entry = ws_config.get_repo(alias)
+ if entry is not None:
+ repo_path_str = str((ws_root_path / entry.path).resolve())
+ ws_config.remove_repo(alias)
+ ws_config.save(ws_root_path)
+ request.app.state.workspace_config = ws_config
+ path_to_rid = getattr(request.app.state, "workspace_path_to_repo_id", None)
+ if path_to_rid and repo_path_str in path_to_rid:
+ path_to_rid.pop(repo_path_str)
+ return {"ok": True, "deleted_pages": 0}
+
repo = await crud.get_repository(session, repo_id)
if repo is None:
raise HTTPException(status_code=404, detail="Repository not found")
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index e80784ebe..62118842a 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -38,6 +38,7 @@ from repowise.server.schemas import (
WorkspaceGraphNode,
WorkspaceGraphResponse,
WorkspaceRepoEntry,
+ WorkspaceRepoRemovedResponse,
WorkspaceResponse,
WorkspaceSyncResponse,
WorkspaceSystemGraphResponse,
@@ -1068,3 +1069,80 @@ async def sync_workspace(
skipped=sum(1 for r in results if r.status == "skipped"),
errors=sum(1 for r in results if r.status == "error"),
)
+
+
+# ---------------------------------------------------------------------------
+# DELETE /api/workspace/repos/{alias}
+# ---------------------------------------------------------------------------
+
+
+ "/repos/{alias}",
+ response_model=WorkspaceRepoRemovedResponse,
+ status_code=200,
+)
+async def remove_workspace_repo(
+ alias: str,
+ request: Request,
+ ws_config=Depends(get_workspace_config),
+):
+ """Remove a repository from the workspace configuration.
+
+ Drops the repo entry from ``.repowise-workspace.yaml`` and cleans up
+ running server state (session factories, FTS, repo id mappings) so
+ the change takes effect immediately without requiring a restart.
+ """
+ _require_workspace(ws_config)
+
+ ws_root = getattr(request.app.state, "workspace_root", None)
+ if ws_root is None:
+ raise HTTPException(status_code=500, detail="Workspace root missing on app state")
+ ws_root_path = Path(ws_root)
+
+ entry = ws_config.get_repo(alias)
+ if entry is None:
+ raise HTTPException(
+ status_code=404,
+ detail=f"Unknown repo alias '{alias}' in workspace.",
+ )
+
+ # Compute absolute repo path to clean up mappings
+ repo_path_str = str((ws_root_path / entry.path).resolve())
+
+ # Remove from config and save to disk
+ removed = ws_config.remove_repo(alias)
+ if removed is None:
+ raise HTTPException(
+ status_code=404,
+ detail=f"Unknown repo alias '{alias}' in workspace.",
+ )
+ ws_config.save(ws_root_path)
+
+ # Update live in-memory app state
+ request.app.state.workspace_config = ws_config
+
+ # Clean up associated in-memory references if present
+ path_to_rid = getattr(request.app.state, "workspace_path_to_repo_id", None)
+ repo_id = None
+ if path_to_rid and repo_path_str in path_to_rid:
+ repo_id = path_to_rid.pop(repo_path_str)
+
+ if repo_id is not None:
+ ws_sessions = getattr(request.app.state, "workspace_sessions", None)
+ if ws_sessions and repo_id in ws_sessions:
+ ws_sessions.pop(repo_id, None)
+
+ ws_fts = getattr(request.app.state, "workspace_fts", None)
+ if ws_fts and repo_id in ws_fts:
+ ws_fts.pop(repo_id, None)
+
+ ws_vs = getattr(request.app.state, "workspace_vector_stores", None)
+ if ws_vs and repo_id in ws_vs:
+ ws_vs.pop(repo_id, None)
+
+ return WorkspaceRepoRemovedResponse(
+ ok=True,
+ alias=alias,
+ remaining_repos=len(ws_config.repos),
+ )
+
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index ed0e4f939..13ed97eb6 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -276,6 +276,7 @@ from .workspace import (
WorkspaceOrphanProvider,
WorkspaceRepoDiagnostics,
WorkspaceRepoEntry,
+ WorkspaceRepoRemovedResponse,
WorkspaceResponse,
WorkspaceSyncResponse,
WorkspaceSyncResult,
@@ -517,6 +518,7 @@ __all__ = [
"WorkspaceOrphanProvider",
"WorkspaceRepoDiagnostics",
"WorkspaceRepoEntry",
+ "WorkspaceRepoRemovedResponse",
"WorkspaceResponse",
"WorkspaceSyncResponse",
"WorkspaceSyncResult",
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index b077646dd..584e593cd 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -5,6 +5,14 @@ from __future__ import annotations
from pydantic import BaseModel, Field
+class WorkspaceRepoRemovedResponse(BaseModel):
+ """Response returned when a repo is removed from the workspace config."""
+
+ ok: bool = True
+ alias: str
+ remaining_repos: int
+
+
class WorkspaceRepoEntry(BaseModel):
alias: str
path: str
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 63a22f4c9..e22435a17 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -3084,6 +3084,13 @@ export interface WorkspaceRepoEntry {
docs_skip_reason?: string | null;
}
+/** Response returned when a repo is removed from the workspace config. */
+export interface WorkspaceRepoRemovedResponse {
+ ok?: boolean;
+ alias: string;
+ remaining_repos: number;
+}
+
export interface WorkspaceResponse {
is_workspace: boolean;
workspace_root?: string | null;
diff --git a/packages/web/src/app/workspace/page.tsx b/packages/web/src/app/workspace/page.tsx
index d0980ce63..d2246bcba 100644
--- a/packages/web/src/app/workspace/page.tsx
+++ b/packages/web/src/app/workspace/page.tsx
@@ -20,7 +20,7 @@ import { CoChangeTable } from "@repowise-dev/ui/workspace/co-change-table";
import { ContractTypeBadge } from "@repowise-dev/ui/workspace/contract-type-badge";
import { formatNumber } from "@repowise-dev/ui/lib/format";
import { getWorkspace, getWorkspaceCoChanges } from "@/lib/api/workspace";
-import { SyncButton } from "./sync-buttons";
+import { RemoveWorkspaceRepoButton, SyncButton } from "./sync-buttons";
export const metadata: Metadata = { title: "Workspace" };
@@ -176,7 +176,9 @@ export default async function WorkspaceDashboardPage() {
repos={repos.slice().sort(byAttention).map(toRow)}
LinkComponent={Link}
actionsFor={(repo) =>
- repo.status === "missing_dir" ? null : (
+ repo.status === "missing_dir" ? (
+ <RemoveWorkspaceRepoButton alias={repo.id} repoName={repo.name} />
+ ) : (
<SyncButton
alias={repo.id}
label={repo.status === "indexed" ? "Sync" : "Index now"}
diff --git a/packages/web/src/app/workspace/sync-buttons.tsx b/packages/web/src/app/workspace/sync-buttons.tsx
index 578cdeacd..c738d9074 100644
--- a/packages/web/src/app/workspace/sync-buttons.tsx
+++ b/packages/web/src/app/workspace/sync-buttons.tsx
@@ -2,8 +2,8 @@
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
-import { RefreshCw } from "lucide-react";
-import { syncWorkspace } from "@/lib/api/workspace";
+import { RefreshCw, Trash2 } from "lucide-react";
+import { removeWorkspaceRepo, syncWorkspace } from "@/lib/api/workspace";
import type { WorkspaceSyncResult } from "@/lib/api/types";
import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";
@@ -101,3 +101,55 @@ function summarizeResults(results: WorkspaceSyncResult[]): string {
if (errored) parts.push(`${errored} error`);
return parts.join(", ");
}
+
+interface RemoveWorkspaceRepoButtonProps {
+ alias: string;
+ repoName?: string;
+}
+
+export function RemoveWorkspaceRepoButton({
+ alias,
+ repoName,
+}: RemoveWorkspaceRepoButtonProps) {
+ const [removing, setRemoving] = useState(false);
+ const [, startTransition] = useTransition();
+ const router = useRouter();
+
+ const handleRemove = async (e: React.MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (
+ typeof window !== "undefined" &&
+ !window.confirm(
+ `Remove '${repoName || alias}' from .repowise-workspace.yaml?`,
+ )
+ ) {
+ return;
+ }
+ setRemoving(true);
+ try {
+ await removeWorkspaceRepo(alias);
+ startTransition(() => router.refresh());
+ } catch (e) {
+ if (typeof window !== "undefined") {
+ window.alert(`Failed to remove: ${toFriendlyMessage(e)}`);
+ }
+ } finally {
+ setRemoving(false);
+ }
+ };
+
+ return (
+ <button
+ type="button"
+ onClick={handleRemove}
+ disabled={removing}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2.5 py-1 text-xs font-medium text-[var(--color-error)] hover:bg-[var(--color-bg-elevated)] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ aria-label={`Remove ${alias} from workspace`}
+ >
+ <Trash2 className="h-3 w-3" />
+ {removing ? "Removing…" : "Remove"}
+ </button>
+ );
+}
+
diff --git a/tests/unit/server/test_workspace_remove_repo.py b/tests/unit/server/test_workspace_remove_repo.py
new file mode 100644
index 000000000..f6825d625
--- /dev/null
+++ b/tests/unit/server/test_workspace_remove_repo.py
@@ -0,0 +1,153 @@
+"""Tests for DELETE /api/workspace/repos/{alias} and removing missing workspace entries."""
+
+from __future__ import annotations
+
+from contextlib import asynccontextmanager
+from pathlib import Path
+from unittest.mock import MagicMock
+
+import pytest
+from fastapi import FastAPI
+from fastapi.responses import JSONResponse
+from httpx import ASGITransport, AsyncClient
+
+from repowise.core.workspace.config import RepoEntry, WorkspaceConfig
+from repowise.server.deps import verify_api_key
+from repowise.server.routers import repos, workspace
+
+
+def _make_workspace_app(
+ *,
+ ws_config: WorkspaceConfig | None = None,
+ workspace_root: str | None = None,
+) -> FastAPI:
+ """Build a minimal FastAPI app with workspace and repos routers + injected state."""
+
+ @asynccontextmanager
+ async def noop_lifespan(app: FastAPI):
+ yield
+
+ app = FastAPI(title="workspace-test", lifespan=noop_lifespan)
+
+ @app.exception_handler(LookupError)
+ async def not_found_handler(request, exc):
+ return JSONResponse(status_code=404, content={"detail": str(exc)})
+
+ app.state.workspace_config = ws_config
+ app.state.workspace_root = workspace_root
+ app.state.session_factory = MagicMock()
+ app.state.fts = MagicMock()
+ app.state.workspace_sessions = {}
+ app.state.workspace_fts = {}
+ app.state.workspace_path_to_repo_id = {}
+ app.state.workspace_vector_stores = {}
+
+ app.include_router(workspace.router)
+ app.include_router(repos.router)
+
+ # Override auth so ASGI test transport (where request.client is None)
+ # doesn't reject every request with 403 when REPOWISE_API_KEY is unset.
+ async def _noop_auth() -> None:
+ return None
+
+ app.dependency_overrides[verify_api_key] = _noop_auth
+ return app
+
+
+async def test_remove_workspace_repo_success(tmp_path: Path):
+ """DELETE /api/workspace/repos/{alias} drops the entry from YAML and live app state."""
+ repo_a = RepoEntry(alias="backend", path="backend", is_primary=True)
+ repo_b = RepoEntry(alias="frontend", path="frontend", is_primary=False)
+ ws_config = WorkspaceConfig(repos=[repo_a, repo_b], default_repo="backend")
+ ws_config.save(tmp_path)
+
+ app = _make_workspace_app(ws_config=ws_config, workspace_root=str(tmp_path))
+
+ frontend_abs = str((tmp_path / "frontend").resolve())
+ app.state.workspace_path_to_repo_id[frontend_abs] = "repo-frontend-id"
+ app.state.workspace_sessions["repo-frontend-id"] = MagicMock()
+ app.state.workspace_fts["repo-frontend-id"] = MagicMock()
+ app.state.workspace_vector_stores["repo-frontend-id"] = MagicMock()
+
+ async with AsyncClient(
+ transport=ASGITransport(app=app),
+ base_url="http://test",
+ ) as client:
+ resp = await client.delete("/api/workspace/repos/frontend")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["ok"] is True
+ assert data["alias"] == "frontend"
+ assert data["remaining_repos"] == 1
+
+ # Verify on-disk configuration
+ reloaded_config = WorkspaceConfig.load(tmp_path)
+ assert len(reloaded_config.repos) == 1
+ assert reloaded_config.repos[0].alias == "backend"
+
+ # Verify in-memory state updates
+ assert len(app.state.workspace_config.repos) == 1
+ assert app.state.workspace_config.repos[0].alias == "backend"
+ assert "repo-frontend-id" not in app.state.workspace_sessions
+ assert "repo-frontend-id" not in app.state.workspace_fts
+ assert "repo-frontend-id" not in app.state.workspace_vector_stores
+ assert frontend_abs not in app.state.workspace_path_to_repo_id
+
+
+async def test_remove_workspace_repo_not_found(tmp_path: Path):
+ """DELETE /api/workspace/repos/{alias} returns 404 for unknown alias."""
+ repo_a = RepoEntry(alias="backend", path="backend", is_primary=True)
+ ws_config = WorkspaceConfig(repos=[repo_a], default_repo="backend")
+ ws_config.save(tmp_path)
+
+ app = _make_workspace_app(ws_config=ws_config, workspace_root=str(tmp_path))
+
+ async with AsyncClient(
+ transport=ASGITransport(app=app),
+ base_url="http://test",
+ ) as client:
+ resp = await client.delete("/api/workspace/repos/unknown-repo")
+ assert resp.status_code == 404
+ assert "Unknown repo alias" in resp.json()["detail"]
+
+
+async def test_remove_workspace_repo_not_workspace_mode():
+ """DELETE /api/workspace/repos/{alias} returns 404 when not in workspace mode."""
+ app = _make_workspace_app(ws_config=None)
+
+ async with AsyncClient(
+ transport=ASGITransport(app=app),
+ base_url="http://test",
+ ) as client:
+ resp = await client.delete("/api/workspace/repos/backend")
+ assert resp.status_code == 404
+ assert "Not running in workspace mode" in resp.json()["detail"]
+
+
+async def test_delete_synthetic_repo_via_repos_router(tmp_path: Path):
+ """DELETE /api/repos/ws:{alias} removes the synthetic entry from workspace config."""
+ repo_a = RepoEntry(alias="backend", path="backend", is_primary=True)
+ repo_b = RepoEntry(alias="missing-folder", path="missing-folder", is_primary=False)
+ ws_config = WorkspaceConfig(repos=[repo_a, repo_b], default_repo="backend")
+ ws_config.save(tmp_path)
+
+ app = _make_workspace_app(ws_config=ws_config, workspace_root=str(tmp_path))
+
+ async with AsyncClient(
+ transport=ASGITransport(app=app),
+ base_url="http://test",
+ ) as client:
+ resp = await client.delete("/api/repos/ws:missing-folder")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["ok"] is True
+ assert data["deleted_pages"] == 0
+
+ # Verify on-disk configuration
+ reloaded_config = WorkspaceConfig.load(tmp_path)
+ assert len(reloaded_config.repos) == 1
+ assert reloaded_config.repos[0].alias == "backend"