Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions backend/app/api/endpoints/projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
from app.models.user import User
from app.schemas.project import (
AddTaskToProjectResponse,
GitWorkspaceProjectCreate,
GitWorkspaceProjectResponse,
ProjectConversationCreate,
ProjectConversationResponse,
ProjectCreate,
Expand Down Expand Up @@ -88,6 +90,32 @@ def create_project_endpoint(
)


@router.post(
"/git-workspace",
response_model=GitWorkspaceProjectResponse,
status_code=status.HTTP_201_CREATED,
)
async def create_git_workspace_project_endpoint(
project_create: GitWorkspaceProjectCreate,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db),
):
"""Create a Git-backed workspace project and clone it on the selected device."""
Comment on lines +98 to +103

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Instrument the new async endpoint with required tracing decorators/events.

create_git_workspace_project_endpoint is newly added and should be wrapped with @trace_async and span metadata for request-level observability.

As per coding guidelines: Use OpenTelemetry tracing decorators: @trace_asyncor@trace_sync for entire functions, and add_span_event() or set_span_attribute() for adding details to spans.

🧰 Tools
🪛 Ruff (0.15.15)

[warning] 100-100: Do not perform function call Depends in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)


[warning] 101-101: Do not perform function call Depends in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/api/endpoints/projects.py` around lines 98 - 103, Add
OpenTelemetry tracing to the new async endpoint by decorating
create_git_workspace_project_endpoint with `@trace_async` (importing trace_async
from the tracing utilities used in the repo) and instrumenting key points inside
the function with span metadata: call
add_span_event("create_git_workspace_project.started") at start,
set_span_attribute("user.id", current_user.id) and
set_span_attribute("project.type","git_workspace") after validation, and
add_span_event("git.clone.started", {"repo": project_create.repo_url}) before
cloning and add_span_event("git.clone.completed") (or an error event on failure)
after cloning; use the existing add_span_event/set_span_attribute helpers (or
their equivalents) to ensure request-level observability.

try:
return await project_service.create_git_workspace_project(
db=db,
project_data=project_create,
user_id=current_user.id,
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Failed to create Git workspace project: {str(e)}",
)


@router.post(
"/archive-chats",
response_model=TaskArchiveBatchResponse,
Expand Down
38 changes: 38 additions & 0 deletions backend/app/schemas/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from pydantic import BaseModel, ConfigDict, Field, model_validator

from app.core.constants import CLIENT_ORIGIN_FRONTEND, SUPPORTED_CLIENT_ORIGINS
from shared.utils.git_util import get_safe_git_workspace_key


class ProjectTaskBase(BaseModel):
Expand Down Expand Up @@ -167,6 +168,13 @@ def validate_workspace_project(self) -> "ProjectConfig":
if workspace.source == "git":
if not self.git:
raise ValueError("git config is required when workspace.source is git")
if not workspace.checkoutPath:
workspace_key = get_safe_git_workspace_key(
self.git.url,
domain=self.git.domain,
repo=self.git.repo,
)
workspace.checkoutPath = workspace_key
if (
self.execution.targetType == "cloud"
and workspace.checkoutPath
Expand Down Expand Up @@ -224,6 +232,26 @@ class ProjectCreate(ProjectBase):
pass


class GitWorkspaceProjectCreate(BaseModel):
"""Request model for creating a Git-backed workspace project."""

device_id: str = Field(..., min_length=1, description="Local device ID")
git: ProjectGitConfig = Field(..., description="Git repository configuration")
name: Optional[str] = Field(None, min_length=1, max_length=100)
description: str = Field(default="", description="Project description")
color: Optional[str] = Field(None, max_length=20)
client_origin: str = Field(default=CLIENT_ORIGIN_FRONTEND)

model_config = ConfigDict(extra="forbid")

@model_validator(mode="after")
def validate_client_origin(self) -> "GitWorkspaceProjectCreate":
"""Validate project client origin."""
if self.client_origin not in SUPPORTED_CLIENT_ORIGINS:
raise ValueError("Unsupported client_origin")
return self


class ProjectUpdate(BaseModel):
"""Request model for updating a project."""

Expand Down Expand Up @@ -269,6 +297,16 @@ class ProjectWithTasksResponse(ProjectResponse):
)


class GitWorkspaceProjectResponse(BaseModel):
"""Response model for Git-backed workspace creation."""

project: ProjectResponse
checkout_path: str = Field(..., description="Relative checkout path")
reused_existing_checkout: bool = Field(
default=False, description="Whether an existing checkout was reused"
)


class ProjectDeviceSessionResponse(BaseModel):
"""Response model for a project-scoped local device session."""

Expand Down
1 change: 1 addition & 0 deletions backend/app/services/device/command_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ def skill_metadata(skill_file, source, source_kind, manifest):
post_processor="directory_list",
),
"mkdir_p": LocalDeviceCommandDefinition(command="mkdir -p"),
"path_exists": LocalDeviceCommandDefinition(command="test -e"),
"git_clone": LocalDeviceCommandDefinition(command="git clone"),
"git_branch": LocalDeviceCommandDefinition(command="git branch --show-current"),
"git_branch_list": LocalDeviceCommandDefinition(
Expand Down
200 changes: 199 additions & 1 deletion backend/app/services/project_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
Projects are containers for organizing tasks. Each task can belong to one project.
"""

from typing import Optional
import posixpath
from typing import Any, Optional

from fastapi import HTTPException
from sqlalchemy import func
Expand All @@ -18,6 +19,8 @@
from app.models.project import Project
from app.models.task import TaskResource
from app.schemas.project import (
GitWorkspaceProjectCreate,
GitWorkspaceProjectResponse,
ProjectConfig,
ProjectConversationCreate,
ProjectConversationResponse,
Expand All @@ -30,6 +33,11 @@
)
from app.schemas.task import TaskCreate
from app.services.adapters.task_kinds import task_kinds_service
from app.services.device.command_service import (
execute_configured_device_command,
)

GIT_CLONE_TIMEOUT_SECONDS = 600


def create_project(
Expand Down Expand Up @@ -81,6 +89,196 @@ def create_project(
return response


async def create_git_workspace_project(
db: Session,
project_data: GitWorkspaceProjectCreate,
user_id: int,
) -> GitWorkspaceProjectResponse:
"""Create a Git-backed workspace project and clone its checkout."""
Comment on lines +92 to +97

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add required tracing instrumentation to new Git workspace flow functions.

The newly added async service entry points are missing @trace_async and span annotations.

Example pattern
+from app.observability.tracing import trace_async, add_span_event, set_span_attribute
...
+@trace_async
 async def create_git_workspace_project(...):
+    set_span_attribute('project.source', 'git')
+    add_span_event('project.create_git_workspace.start')
     ...
 
+@trace_async
 async def _prepare_git_checkout(...):
+    set_span_attribute('device.id', device_id)
+    add_span_event('project.git_checkout.prepare')
     ...

As per coding guidelines: Use OpenTelemetry tracing decorators: @trace_asyncor@trace_sync for entire functions, and add_span_event() or set_span_attribute() for adding details to spans.

Also applies to: 156-166

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/services/project_service.py` around lines 92 - 97, The new async
service entry point create_git_workspace_project is missing OpenTelemetry
instrumentation: add the `@trace_async` decorator above the async def and inside
the function set relevant span attributes/events (e.g., call set_span_attribute
for project_data fields like repository/url/branch and add_span_event for key
lifecycle steps such as "clone_started" / "clone_succeeded" / "clone_failed");
apply the same pattern to the other async functions referenced around lines
156-166 so each async entry point uses `@trace_async` and emits span
attributes/events to surface important parameters and status.


repo_name = _default_git_project_name(project_data.git.repo, project_data.git.url)
config = ProjectConfig.model_validate(
{
"mode": "workspace",
"execution": {
"targetType": "local",
"deviceId": project_data.device_id,
},
"workspace": {"source": "git"},
"git": project_data.git.model_dump(),
}
)
if not config.workspace or not config.workspace.checkoutPath:
raise HTTPException(
status_code=400,
detail="Git workspace checkout path could not be resolved",
)

project = create_project(
db=db,
project_data=ProjectCreate(
name=project_data.name or repo_name,
description=project_data.description,
color=project_data.color,
client_origin=project_data.client_origin,
config=config,
),
user_id=user_id,
)

try:
reused_checkout = await _prepare_git_checkout(
db=db,
user_id=user_id,
device_id=project_data.device_id,
git_url=project_data.git.url,
branch=project_data.git.branch,
checkout_path=config.workspace.checkoutPath,
)
except Exception:
_deactivate_project(db, project.id, user_id, project_data.client_origin)
raise

return GitWorkspaceProjectResponse(
project=project,
checkout_path=config.workspace.checkoutPath,
reused_existing_checkout=reused_checkout,
)


def _default_git_project_name(repo: Optional[str], git_url: str) -> str:
"""Return a display name for a Git workspace project."""

source = repo or git_url.rstrip("/").split("/")[-1]
return source.rstrip("/").removesuffix(".git").split("/")[-1] or "repository"


async def _prepare_git_checkout(
*,
db: Session,
user_id: int,
device_id: str,
git_url: str,
branch: Optional[str],
checkout_path: str,
) -> bool:
"""Clone the Git checkout on the selected local device."""

root_result = await execute_configured_device_command(
db=db,
user_id=user_id,
device_id=device_id,
command_key="project_workspace_root",
)
workspace_root = str(root_result.get("stdout", "")).strip()
if not workspace_root:
raise HTTPException(status_code=400, detail="Project workspace root is empty")

root_mkdir_result = await execute_configured_device_command(
db=db,
user_id=user_id,
device_id=device_id,
command_key="mkdir_p",
args=[workspace_root],
)
_raise_for_failed_command(
root_mkdir_result,
"Failed to create project workspace root",
)

target_path = _join_device_path(workspace_root, checkout_path)
exists_result = await execute_configured_device_command(
db=db,
user_id=user_id,
device_id=device_id,
command_key="path_exists",
path=workspace_root,
args=[checkout_path],
timeout_seconds=30,
)
if _command_succeeded(exists_result):
raise _target_path_exists_error(target_path)
Comment on lines +190 to +200

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle path_exists execution errors separately from “path not found”.

On Line 199, any non-zero result is treated as “not exists”. If the check command itself fails, clone still proceeds and masks the root cause.

Suggested fix
     exists_result = await execute_configured_device_command(
         db=db,
         user_id=user_id,
         device_id=device_id,
         command_key="path_exists",
         path=workspace_root,
         args=[checkout_path],
         timeout_seconds=30,
     )
+    exists_exit_code = exists_result.get("exit_code")
     if _command_succeeded(exists_result):
         raise _target_path_exists_error(target_path)
+    if exists_exit_code != 1:
+        _raise_for_failed_command(
+            exists_result,
+            "Failed to check whether target project directory exists",
+        )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/services/project_service.py` around lines 190 - 200, The current
logic treats any non-zero result from execute_configured_device_command(...,
command_key="path_exists") as “not exists” and proceeds, which masks execution
failures; update the check around exists_result returned by
execute_configured_device_command (used with command_key "path_exists") to
distinguish an execution error from a genuine “not found” result: inspect the
result's execution status/exit code and error/message fields from exists_result,
if the command failed (non-standard error code or an error message), raise or
propagate an execution error (include the command error details), and only call
_target_path_exists_error when the result specifically indicates the target path
exists per _command_succeeded semantics. Ensure references to
execute_configured_device_command, _command_succeeded, and
_target_path_exists_error are used to locate and update the logic.


parent_path = posixpath.dirname(checkout_path)
if parent_path and parent_path != ".":
mkdir_result = await execute_configured_device_command(
db=db,
user_id=user_id,
device_id=device_id,
command_key="mkdir_p",
path=workspace_root,
args=[parent_path],
)
_raise_for_failed_command(mkdir_result, "Failed to create project directory")

clone_args = _build_git_clone_args(git_url, branch, checkout_path)
clone_result = await execute_configured_device_command(
db=db,
user_id=user_id,
device_id=device_id,
command_key="git_clone",
path=workspace_root,
args=clone_args,
timeout_seconds=GIT_CLONE_TIMEOUT_SECONDS,
max_output_bytes=5 * 1024 * 1024,
)
_raise_for_failed_command(clone_result, "Failed to clone Git repository")
return False


def _build_git_clone_args(
git_url: str,
branch: Optional[str],
checkout_path: str,
) -> list[str]:
args: list[str] = []
if branch and branch.strip():
args.extend(["--branch", branch.strip(), "--single-branch"])
args.extend([git_url, checkout_path])
return args


def _join_device_path(root: str, relative_path: str) -> str:
return f"{root.rstrip('/')}/{relative_path.strip('/')}"


def _command_succeeded(result: dict[str, Any]) -> bool:
return bool(result.get("success")) and result.get("exit_code") == 0


def _raise_for_failed_command(result: dict[str, Any], message: str) -> None:
if _command_succeeded(result):
return
detail = str(result.get("stderr") or result.get("error") or message)
raise HTTPException(status_code=400, detail=detail)


def _target_path_exists_error(target_path: str) -> HTTPException:
return HTTPException(
status_code=409,
detail=f"Target project directory already exists: {target_path}",
)


def _deactivate_project(
db: Session,
project_id: int,
user_id: int,
client_origin: Optional[str],
) -> None:
query = db.query(Project).filter(
Project.id == project_id,
Project.user_id == user_id,
Project.is_active == True,
)
if client_origin:
query = query.filter(Project.client_origin == client_origin)
project = query.first()
if project:
project.is_active = False
db.commit()


def get_project(
db: Session, project_id: int, user_id: int, client_origin: Optional[str] = None
) -> Optional[ProjectWithTasksResponse]:
Expand Down
18 changes: 18 additions & 0 deletions backend/tests/schemas/test_project_config_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,24 @@ def test_workspace_project_git_config_accepts_cloud_relative_checkout_path():
assert config.workspace.checkoutPath == "projects/demo"


def test_workspace_project_git_config_defaults_checkout_path_to_safe_repo_key():
config = ProjectConfig.model_validate(
{
"mode": "workspace",
"execution": {"targetType": "local", "deviceId": "device-1"},
"workspace": {"source": "git"},
"git": {
"url": "https://github.com/wecode-ai/Wegent.git",
"repo": "wecode-ai/Wegent",
"domain": "github.com",
"branch": "main",
},
}
)

assert config.workspace.checkoutPath == "Wegent"


def test_workspace_project_rejects_cloud_absolute_checkout_path():
with pytest.raises(ValidationError):
ProjectConfig.model_validate(
Expand Down
6 changes: 6 additions & 0 deletions backend/tests/services/test_local_device_command_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ def test_local_device_command_registry_default_includes_diagnostic_commands():
mkdir_definition = resolve_local_device_command(
"mkdir_p", settings.LOCAL_DEVICE_COMMANDS
)
path_exists_definition = resolve_local_device_command(
"path_exists", settings.LOCAL_DEVICE_COMMANDS
)
git_clone_definition = resolve_local_device_command(
"git_clone", settings.LOCAL_DEVICE_COMMANDS
)
Expand Down Expand Up @@ -87,6 +90,9 @@ def test_local_device_command_registry_default_includes_diagnostic_commands():
assert mkdir_definition is not None
assert mkdir_definition.command == "mkdir -p"
assert mkdir_definition.post_processor is None
assert path_exists_definition is not None
assert path_exists_definition.command == "test -e"
assert path_exists_definition.post_processor is None
assert git_clone_definition is not None
assert git_clone_definition.command == "git clone"
assert git_clone_definition.post_processor is None
Expand Down
Loading
Loading