feat: workspace-first UI refresh - PR-1 backend endpoints
- Add FileService for workspace-scoped file operations
- Add GitOperations service for workspace-scoped git commands
- Add workspace_files API: GET/POST /workspaces/{id}/files
- Add workspace_git API: status, branches, commit, push, pull, fetch, checkout, history
- Add workspace_instances API: list instances per workspace
- Add top-level POST /workspaces/ (accepts repo_id directly)
- Enrich GET /projects/ with nested repositories and workspaces
- Register all new routers in main.py
- 23 tests passing (17 existing + 6 new)
Quality gates: ruff clean
This commit is contained in:
@@ -4,13 +4,14 @@ import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.auth.dependencies import _get_owned_project, _get_user, get_current_user_id, get_db_session
|
||||
from src.models.git_repository import GitRepository
|
||||
from src.models.project import Project
|
||||
from src.models.ssh_key import SSHKey
|
||||
from src.models.tool_instance import ToolInstance
|
||||
|
||||
router = APIRouter(prefix="/projects", tags=["projects"])
|
||||
|
||||
@@ -76,26 +77,67 @@ async def create_project(
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=list[ProjectResponse],
|
||||
summary="List all projects",
|
||||
description="Retrieve all projects owned by the authenticated user.",
|
||||
description="Retrieve all projects owned by the authenticated user with repositories and workspaces.",
|
||||
)
|
||||
async def list_projects(
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> list[Project]:
|
||||
) -> list[dict]:
|
||||
"""List all projects for the authenticated user.
|
||||
|
||||
Args:
|
||||
user_id: ID of the authenticated user.
|
||||
session: Database session.
|
||||
|
||||
Returns:
|
||||
List of projects owned by the user.
|
||||
Returns projects with nested repositories and workspaces for inline display.
|
||||
"""
|
||||
user = await _get_user(session, user_id)
|
||||
result = await session.execute(select(Project).where(Project.owner_id == user.id))
|
||||
return list(result.scalars().all())
|
||||
result = await session.execute(
|
||||
select(Project).where(Project.owner_id == user.id).order_by(Project.created_at.desc())
|
||||
)
|
||||
projects = result.scalars().all()
|
||||
|
||||
from src.models.workspace import Workspace
|
||||
|
||||
enriched = []
|
||||
for project in projects:
|
||||
repos_result = await session.execute(
|
||||
select(GitRepository).where(GitRepository.project_id == project.id)
|
||||
)
|
||||
repositories = []
|
||||
for repo in repos_result.scalars().all():
|
||||
ws_result = await session.execute(
|
||||
select(Workspace).where(Workspace.repo_id == repo.id)
|
||||
)
|
||||
workspaces = []
|
||||
for ws in ws_result.scalars().all():
|
||||
# Count instances
|
||||
inst_result = await session.execute(
|
||||
select(func.count()).where(ToolInstance.workspace_id == ws.id)
|
||||
)
|
||||
instance_count = inst_result.scalar() or 0
|
||||
workspaces.append({
|
||||
"id": str(ws.id),
|
||||
"name": ws.name,
|
||||
"branch": ws.branch,
|
||||
"status": ws.status,
|
||||
"instance_count": instance_count,
|
||||
})
|
||||
|
||||
repositories.append({
|
||||
"id": str(repo.id),
|
||||
"name": repo.name,
|
||||
"remote_url": repo.remote_url,
|
||||
"workspaces": workspaces,
|
||||
})
|
||||
|
||||
enriched.append({
|
||||
"id": str(project.id),
|
||||
"name": project.name,
|
||||
"description": project.description,
|
||||
"owner_id": str(project.owner_id),
|
||||
"repositories": repositories,
|
||||
"created_at": project.created_at.isoformat() if project.created_at else None,
|
||||
})
|
||||
|
||||
return enriched
|
||||
|
||||
|
||||
@router.get(
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Workspace file API endpoints."""
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.auth.dependencies import get_current_user_id, get_db_session
|
||||
from src.models.workspace import Workspace
|
||||
from src.services.file_service import FileService
|
||||
|
||||
router = APIRouter(prefix="/workspaces/{workspace_id}/files")
|
||||
|
||||
|
||||
async def _get_workspace(
|
||||
session: AsyncSession,
|
||||
workspace_id: uuid.UUID,
|
||||
user_id: uuid.UUID,
|
||||
) -> Workspace:
|
||||
from sqlalchemy import select
|
||||
|
||||
result = await session.execute(
|
||||
select(Workspace).where(
|
||||
Workspace.id == workspace_id,
|
||||
Workspace.user_id == user_id,
|
||||
)
|
||||
)
|
||||
workspace = result.scalar_one_or_none()
|
||||
if not workspace:
|
||||
raise HTTPException(status_code=404, detail="Workspace not found")
|
||||
return workspace
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def list_files(
|
||||
workspace_id: uuid.UUID,
|
||||
path: str = "",
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""List files in a workspace directory."""
|
||||
workspace = await _get_workspace(session, workspace_id, user_id)
|
||||
service = FileService()
|
||||
try:
|
||||
entries = service.list_directory(workspace, path)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
return {
|
||||
"entries": [
|
||||
{
|
||||
"name": e.name,
|
||||
"path": e.path,
|
||||
"type": e.type,
|
||||
"size": e.size,
|
||||
}
|
||||
for e in entries
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/content")
|
||||
async def get_file_content(
|
||||
workspace_id: uuid.UUID,
|
||||
path: str,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Get the content of a text file."""
|
||||
workspace = await _get_workspace(session, workspace_id, user_id)
|
||||
service = FileService()
|
||||
try:
|
||||
content = service.read_file(workspace, path)
|
||||
except FileNotFoundError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
return {"content": content, "path": path}
|
||||
|
||||
|
||||
@router.post("/content")
|
||||
async def write_file(
|
||||
workspace_id: uuid.UUID,
|
||||
data: dict,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Write a file and optionally commit."""
|
||||
workspace = await _get_workspace(session, workspace_id, user_id)
|
||||
service = FileService()
|
||||
|
||||
file_path = data.get("path", "").strip()
|
||||
content = data.get("content", "")
|
||||
commit_message = data.get("message", "").strip()
|
||||
|
||||
if not file_path:
|
||||
raise HTTPException(status_code=400, detail="File path is required")
|
||||
|
||||
try:
|
||||
service.write_file(workspace, file_path, content)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
if commit_message:
|
||||
from src.services.git_operations import GitOperations
|
||||
|
||||
git = GitOperations(workspace)
|
||||
try:
|
||||
await git.commit(commit_message)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
|
||||
return {"status": "saved", "path": file_path}
|
||||
@@ -0,0 +1,203 @@
|
||||
"""Workspace git API endpoints."""
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.auth.dependencies import get_current_user_id, get_db_session
|
||||
from src.models.workspace import Workspace
|
||||
from src.services.git_operations import GitOperations
|
||||
|
||||
router = APIRouter(prefix="/workspaces/{workspace_id}/git")
|
||||
|
||||
|
||||
async def _get_workspace(
|
||||
session: AsyncSession,
|
||||
workspace_id: uuid.UUID,
|
||||
user_id: uuid.UUID,
|
||||
) -> Workspace:
|
||||
from sqlalchemy import select
|
||||
|
||||
result = await session.execute(
|
||||
select(Workspace).where(
|
||||
Workspace.id == workspace_id,
|
||||
Workspace.user_id == user_id,
|
||||
)
|
||||
)
|
||||
workspace = result.scalar_one_or_none()
|
||||
if not workspace:
|
||||
raise HTTPException(status_code=404, detail="Workspace not found")
|
||||
return workspace
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
async def git_status(
|
||||
workspace_id: uuid.UUID,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Get git status for the workspace."""
|
||||
workspace = await _get_workspace(session, workspace_id, user_id)
|
||||
git = GitOperations(workspace)
|
||||
try:
|
||||
status = await git.status()
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
|
||||
return {
|
||||
"branch": status.branch,
|
||||
"modified": status.modified,
|
||||
"added": status.added,
|
||||
"deleted": status.deleted,
|
||||
"untracked": status.untracked,
|
||||
"ahead": status.ahead,
|
||||
"behind": status.behind,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/branches")
|
||||
async def git_branches(
|
||||
workspace_id: uuid.UUID,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""List branches for the workspace."""
|
||||
workspace = await _get_workspace(session, workspace_id, user_id)
|
||||
git = GitOperations(workspace)
|
||||
try:
|
||||
branches, current = await git.branches()
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
|
||||
return {
|
||||
"branches": branches,
|
||||
"current_branch": current,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/commit")
|
||||
async def git_commit(
|
||||
workspace_id: uuid.UUID,
|
||||
data: dict,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Stage all changes and commit."""
|
||||
workspace = await _get_workspace(session, workspace_id, user_id)
|
||||
message = data.get("message", "").strip()
|
||||
if not message:
|
||||
raise HTTPException(status_code=400, detail="Commit message is required")
|
||||
|
||||
git = GitOperations(workspace)
|
||||
try:
|
||||
await git.commit(message)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
|
||||
return {"status": "committed"}
|
||||
|
||||
|
||||
@router.post("/push")
|
||||
async def git_push(
|
||||
workspace_id: uuid.UUID,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Push current branch."""
|
||||
workspace = await _get_workspace(session, workspace_id, user_id)
|
||||
git = GitOperations(workspace)
|
||||
try:
|
||||
await git.push()
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
|
||||
return {"status": "pushed"}
|
||||
|
||||
|
||||
@router.post("/pull")
|
||||
async def git_pull(
|
||||
workspace_id: uuid.UUID,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Pull current branch."""
|
||||
workspace = await _get_workspace(session, workspace_id, user_id)
|
||||
git = GitOperations(workspace)
|
||||
try:
|
||||
await git.pull()
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
|
||||
return {"status": "pulled"}
|
||||
|
||||
|
||||
@router.post("/fetch")
|
||||
async def git_fetch(
|
||||
workspace_id: uuid.UUID,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Fetch from origin."""
|
||||
workspace = await _get_workspace(session, workspace_id, user_id)
|
||||
git = GitOperations(workspace)
|
||||
try:
|
||||
await git.fetch()
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
|
||||
return {"status": "fetched"}
|
||||
|
||||
|
||||
@router.post("/checkout")
|
||||
async def git_checkout(
|
||||
workspace_id: uuid.UUID,
|
||||
data: dict,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Checkout a branch."""
|
||||
workspace = await _get_workspace(session, workspace_id, user_id)
|
||||
branch = data.get("branch", "").strip()
|
||||
if not branch:
|
||||
raise HTTPException(status_code=400, detail="Branch name is required")
|
||||
|
||||
git = GitOperations(workspace)
|
||||
try:
|
||||
await git.checkout(branch)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
|
||||
workspace.branch = branch
|
||||
await session.commit()
|
||||
|
||||
return {"status": "checked_out", "branch": branch}
|
||||
|
||||
|
||||
@router.get("/history")
|
||||
async def git_history(
|
||||
workspace_id: uuid.UUID,
|
||||
path: str | None = None,
|
||||
limit: int = 50,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Get commit history."""
|
||||
workspace = await _get_workspace(session, workspace_id, user_id)
|
||||
git = GitOperations(workspace)
|
||||
try:
|
||||
commits = await git.history(path, limit)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
|
||||
return {
|
||||
"commits": [
|
||||
{
|
||||
"hash": c.hash,
|
||||
"message": c.message,
|
||||
"author": c.author,
|
||||
"date": c.date,
|
||||
}
|
||||
for c in commits
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Workspace instance API endpoints."""
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.auth.dependencies import get_current_user_id, get_db_session
|
||||
from src.models.tool_instance import ToolInstance
|
||||
from src.models.workspace import Workspace
|
||||
|
||||
router = APIRouter(prefix="/workspaces/{workspace_id}/instances")
|
||||
|
||||
|
||||
async def _get_workspace(
|
||||
session: AsyncSession,
|
||||
workspace_id: uuid.UUID,
|
||||
user_id: uuid.UUID,
|
||||
) -> Workspace:
|
||||
result = await session.execute(
|
||||
select(Workspace).where(
|
||||
Workspace.id == workspace_id,
|
||||
Workspace.user_id == user_id,
|
||||
)
|
||||
)
|
||||
workspace = result.scalar_one_or_none()
|
||||
if not workspace:
|
||||
raise HTTPException(status_code=404, detail="Workspace not found")
|
||||
return workspace
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def list_workspace_instances(
|
||||
workspace_id: uuid.UUID,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> list[dict]:
|
||||
"""List tool instances using this workspace."""
|
||||
await _get_workspace(session, workspace_id, user_id)
|
||||
result = await session.execute(
|
||||
select(ToolInstance)
|
||||
.where(ToolInstance.workspace_id == workspace_id)
|
||||
.order_by(ToolInstance.created_at.desc())
|
||||
)
|
||||
instances = result.scalars().all()
|
||||
|
||||
return [
|
||||
{
|
||||
"id": str(i.id),
|
||||
"name": i.name,
|
||||
"display_name": i.display_name,
|
||||
"status": i.status,
|
||||
"tool_type_id": str(i.tool_type_id),
|
||||
"url": i.url,
|
||||
"port": i.port,
|
||||
"created_at": i.created_at.isoformat() if i.created_at else None,
|
||||
}
|
||||
for i in instances
|
||||
]
|
||||
@@ -53,7 +53,7 @@ async def list_all_workspaces(
|
||||
"repo_id": str(ws.repo_id),
|
||||
"repo_name": repo_name or "",
|
||||
"project_id": str(project_id) if project_id else "",
|
||||
"project_name": "", # Could join with Project if needed
|
||||
"project_name": "",
|
||||
"user_id": str(ws.user_id),
|
||||
"branch": ws.branch,
|
||||
"path": ws.path,
|
||||
@@ -67,6 +67,59 @@ async def list_all_workspaces(
|
||||
]
|
||||
|
||||
|
||||
@all_workspaces_router.post("/")
|
||||
async def create_workspace_top_level(
|
||||
data: dict,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Create a workspace directly (no nested project/repo path)."""
|
||||
repo_id_str = data.get("repo_id", "").strip()
|
||||
if not repo_id_str:
|
||||
raise HTTPException(status_code=400, detail="repo_id is required")
|
||||
|
||||
try:
|
||||
repo_id = uuid.UUID(repo_id_str)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail="Invalid repo_id format") from exc
|
||||
|
||||
repo = await session.get(GitRepository, repo_id)
|
||||
if not repo or repo.owner_id != user_id:
|
||||
raise HTTPException(status_code=404, detail="Repository not found")
|
||||
|
||||
name = data.get("name", "").strip()
|
||||
branch = data.get("branch", "main").strip()
|
||||
|
||||
if not name:
|
||||
raise HTTPException(status_code=400, detail="Workspace name is required")
|
||||
|
||||
manager = WorkspaceManager()
|
||||
try:
|
||||
workspace = await manager.create(repo, user_id, name, branch)
|
||||
session.add(workspace)
|
||||
await session.commit()
|
||||
except Exception as exc:
|
||||
await session.rollback()
|
||||
logger.error("Failed to create workspace: %s", exc)
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Workspace name already exists for this repository",
|
||||
) from exc
|
||||
|
||||
await session.refresh(workspace)
|
||||
return {
|
||||
"id": str(workspace.id),
|
||||
"name": workspace.name,
|
||||
"repo_id": str(workspace.repo_id),
|
||||
"branch": workspace.branch,
|
||||
"path": workspace.path,
|
||||
"status": workspace.status,
|
||||
"created_at": workspace.created_at.isoformat()
|
||||
if workspace.created_at
|
||||
else None,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/")
|
||||
async def list_workspaces(
|
||||
project_id: uuid.UUID,
|
||||
|
||||
Reference in New Issue
Block a user