merge: remove legacy config APIs
This commit is contained in:
@@ -1,284 +0,0 @@
|
||||
"""Config folder API endpoints."""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from pydantic import Field
|
||||
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.config_folder import ConfigFolder
|
||||
from src.schemas.config_folder import (
|
||||
ConfigFolderCreate,
|
||||
ConfigFolderUpdate,
|
||||
ConfigFolderResponse,
|
||||
ProjectOverrideCreate,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/config-folders", tags=["config-folders"])
|
||||
|
||||
|
||||
@router.get("", summary="List config folders", description="Get all config folders for the current user.")
|
||||
async def list_config_folders(
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""List config folders for the current user."""
|
||||
query = select(ConfigFolder).where(ConfigFolder.user_id == user_id)
|
||||
result = await session.execute(query)
|
||||
folders = result.scalars().all()
|
||||
|
||||
return {
|
||||
"folders": [
|
||||
{
|
||||
"id": str(f.id),
|
||||
"user_id": str(f.user_id),
|
||||
"name": f.name,
|
||||
"description": f.description,
|
||||
"mount_path": f.mount_path,
|
||||
"files": f.files,
|
||||
"project_overrides": f.project_overrides,
|
||||
"is_active": f.is_active,
|
||||
"created_at": f.created_at.isoformat() if f.created_at else None,
|
||||
"updated_at": f.updated_at.isoformat() if f.updated_at else None,
|
||||
}
|
||||
for f in folders
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@router.post("", summary="Create config folder", description="Create a new config folder.", status_code=status.HTTP_201_CREATED)
|
||||
async def create_config_folder(
|
||||
data: ConfigFolderCreate,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Create a config folder."""
|
||||
# Check for duplicate name
|
||||
existing = await session.scalar(
|
||||
select(ConfigFolder).where(
|
||||
ConfigFolder.user_id == user_id,
|
||||
ConfigFolder.name == data.name,
|
||||
)
|
||||
)
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"config folder with name '{data.name}' already exists"
|
||||
)
|
||||
|
||||
folder = ConfigFolder(
|
||||
user_id=user_id,
|
||||
name=data.name,
|
||||
description=data.description,
|
||||
mount_path=data.mount_path,
|
||||
files=data.files,
|
||||
)
|
||||
session.add(folder)
|
||||
await session.commit()
|
||||
await session.refresh(folder)
|
||||
|
||||
return {
|
||||
"id": str(folder.id),
|
||||
"user_id": str(folder.user_id),
|
||||
"name": folder.name,
|
||||
"description": folder.description,
|
||||
"mount_path": folder.mount_path,
|
||||
"files": folder.files,
|
||||
"project_overrides": folder.project_overrides,
|
||||
"is_active": folder.is_active,
|
||||
"created_at": folder.created_at.isoformat() if folder.created_at else None,
|
||||
"updated_at": folder.updated_at.isoformat() if folder.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
@router.put("/{folder_id}", summary="Update config folder", description="Update an existing config folder.")
|
||||
async def update_config_folder(
|
||||
folder_id: uuid.UUID,
|
||||
data: ConfigFolderUpdate,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Update a config folder."""
|
||||
folder = await session.get(ConfigFolder, folder_id)
|
||||
if folder is None or folder.user_id != user_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="config folder not found")
|
||||
|
||||
if data.name is not None:
|
||||
folder.name = data.name
|
||||
if data.description is not None:
|
||||
folder.description = data.description
|
||||
if data.mount_path is not None:
|
||||
folder.mount_path = data.mount_path
|
||||
if data.files is not None:
|
||||
folder.files = data.files
|
||||
if data.is_active is not None:
|
||||
folder.is_active = data.is_active
|
||||
|
||||
await session.commit()
|
||||
await session.refresh(folder)
|
||||
|
||||
return {
|
||||
"id": str(folder.id),
|
||||
"user_id": str(folder.user_id),
|
||||
"name": folder.name,
|
||||
"description": folder.description,
|
||||
"mount_path": folder.mount_path,
|
||||
"files": folder.files,
|
||||
"project_overrides": folder.project_overrides,
|
||||
"is_active": folder.is_active,
|
||||
"created_at": folder.created_at.isoformat() if folder.created_at else None,
|
||||
"updated_at": folder.updated_at.isoformat() if folder.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/{folder_id}", summary="Delete config folder", description="Delete a config folder.", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_config_folder(
|
||||
folder_id: uuid.UUID,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> None:
|
||||
"""Delete a config folder."""
|
||||
folder = await session.get(ConfigFolder, folder_id)
|
||||
if folder is None or folder.user_id != user_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="config folder not found")
|
||||
|
||||
await session.delete(folder)
|
||||
await session.commit()
|
||||
|
||||
|
||||
class ProjectOverrideWithId(ProjectOverrideCreate):
|
||||
project_id: uuid.UUID = Field(description="Project ID for the override")
|
||||
|
||||
|
||||
@router.get("/{folder_id}", summary="Get config folder by ID", description="Get a single config folder by its ID.")
|
||||
async def get_config_folder(
|
||||
folder_id: uuid.UUID,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Get a config folder by ID."""
|
||||
folder = await session.get(ConfigFolder, folder_id)
|
||||
if folder is None or folder.user_id != user_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="config folder not found")
|
||||
|
||||
return {
|
||||
"id": str(folder.id),
|
||||
"user_id": str(folder.user_id),
|
||||
"name": folder.name,
|
||||
"description": folder.description,
|
||||
"mount_path": folder.mount_path,
|
||||
"files": folder.files,
|
||||
"project_overrides": folder.project_overrides,
|
||||
"is_active": folder.is_active,
|
||||
"created_at": folder.created_at.isoformat() if folder.created_at else None,
|
||||
"updated_at": folder.updated_at.isoformat() if folder.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{folder_id}/overrides", summary="Add project override", description="Add a project override to a config folder.")
|
||||
async def add_project_override(
|
||||
folder_id: uuid.UUID,
|
||||
data: ProjectOverrideWithId,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Add a project override to a config folder."""
|
||||
folder = await session.get(ConfigFolder, folder_id)
|
||||
if folder is None or folder.user_id != user_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="config folder not found")
|
||||
|
||||
# Initialize project_overrides if None
|
||||
if folder.project_overrides is None:
|
||||
folder.project_overrides = {}
|
||||
|
||||
# Add/update override
|
||||
override_data = {}
|
||||
if data.mount_path is not None:
|
||||
override_data["mount_path"] = data.mount_path
|
||||
if data.files is not None:
|
||||
override_data["files"] = data.files
|
||||
|
||||
# Use a copy to trigger SQLAlchemy change detection on JSONB
|
||||
current_overrides = dict(folder.project_overrides or {})
|
||||
current_overrides[str(data.project_id)] = override_data
|
||||
folder.project_overrides = current_overrides
|
||||
|
||||
await session.commit()
|
||||
await session.refresh(folder)
|
||||
|
||||
return {
|
||||
"id": str(folder.id),
|
||||
"project_overrides": folder.project_overrides,
|
||||
}
|
||||
|
||||
|
||||
@router.put("/{folder_id}/overrides/{project_id}", summary="Update project override", description="Update a project override.")
|
||||
async def update_project_override(
|
||||
folder_id: uuid.UUID,
|
||||
project_id: uuid.UUID,
|
||||
data: ProjectOverrideCreate,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Update a project override."""
|
||||
folder = await session.get(ConfigFolder, folder_id)
|
||||
if folder is None or folder.user_id != user_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="config folder not found")
|
||||
|
||||
# Initialize project_overrides if None
|
||||
if folder.project_overrides is None:
|
||||
folder.project_overrides = {}
|
||||
|
||||
# Update override
|
||||
current_overrides = dict(folder.project_overrides or {})
|
||||
override_data = current_overrides.get(str(project_id), {})
|
||||
if data.mount_path is not None:
|
||||
override_data["mount_path"] = data.mount_path
|
||||
if data.files is not None:
|
||||
override_data["files"] = data.files
|
||||
|
||||
current_overrides[str(project_id)] = override_data
|
||||
folder.project_overrides = current_overrides
|
||||
|
||||
# Mark the field as modified to ensure SQLAlchemy detects the change
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
flag_modified(folder, "project_overrides")
|
||||
|
||||
await session.commit()
|
||||
await session.refresh(folder)
|
||||
|
||||
return {
|
||||
"id": str(folder.id),
|
||||
"project_overrides": folder.project_overrides,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/{folder_id}/overrides/{project_id}", summary="Remove project override", description="Remove a project override.")
|
||||
async def remove_project_override(
|
||||
folder_id: uuid.UUID,
|
||||
project_id: uuid.UUID,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> None:
|
||||
"""Remove a project override."""
|
||||
folder = await session.get(ConfigFolder, folder_id)
|
||||
if folder is None or folder.user_id != user_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="config folder not found")
|
||||
|
||||
# Remove override if exists
|
||||
current_overrides = dict(folder.project_overrides or {})
|
||||
if str(project_id) in current_overrides:
|
||||
del current_overrides[str(project_id)]
|
||||
folder.project_overrides = current_overrides
|
||||
await session.commit()
|
||||
await session.refresh(folder)
|
||||
|
||||
return {
|
||||
"id": str(folder.id),
|
||||
"project_overrides": folder.project_overrides or {},
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
"""Tool configuration API endpoints."""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
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_config import ToolConfig
|
||||
from src.models.tool_type import ToolType
|
||||
from src.schemas.tool_config import ToolConfigCreate, ToolConfigUpdate, ToolConfigResponse
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/tool-configs", tags=["tool-configs"])
|
||||
|
||||
|
||||
@router.get("", summary="List tool configs", description="Get all tool configs for the current user.")
|
||||
async def list_configs(
|
||||
tool_type_id: str | None = None,
|
||||
project_id: str | None = None,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> list:
|
||||
"""List tool configs for the current user."""
|
||||
query = select(ToolConfig).where(ToolConfig.user_id == user_id)
|
||||
|
||||
if tool_type_id:
|
||||
query = query.where(ToolConfig.tool_type_id == uuid.UUID(tool_type_id))
|
||||
if project_id:
|
||||
query = query.where(ToolConfig.project_id == uuid.UUID(project_id))
|
||||
else:
|
||||
# If no project specified, get only global configs (project_id is None)
|
||||
query = query.where(ToolConfig.project_id.is_(None))
|
||||
|
||||
result = await session.execute(query)
|
||||
configs = result.scalars().all()
|
||||
|
||||
return [
|
||||
{
|
||||
"id": str(c.id),
|
||||
"tool_type_id": str(c.tool_type_id),
|
||||
"project_id": str(c.project_id) if c.project_id else None,
|
||||
"key": c.key,
|
||||
"value": c.value,
|
||||
"config_type": c.config_type,
|
||||
"file_path": c.file_path,
|
||||
"port_override": c.port_override,
|
||||
"start_command": c.start_command,
|
||||
"working_directory": c.working_directory,
|
||||
"environment_variables": c.environment_variables,
|
||||
"volumes": c.volumes,
|
||||
}
|
||||
for c in configs
|
||||
]
|
||||
|
||||
|
||||
@router.post("", summary="Create tool config", description="Create a new tool config.", status_code=status.HTTP_201_CREATED)
|
||||
async def create_config(
|
||||
data: ToolConfigCreate,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Create a tool config."""
|
||||
# Verify tool type exists
|
||||
tool_type = await session.get(ToolType, uuid.UUID(data.tool_type_id))
|
||||
if tool_type is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="tool type not found")
|
||||
|
||||
# Check for existing config with same key
|
||||
query = select(ToolConfig).where(
|
||||
ToolConfig.user_id == user_id,
|
||||
ToolConfig.tool_type_id == uuid.UUID(data.tool_type_id),
|
||||
ToolConfig.key == data.key,
|
||||
)
|
||||
if data.project_id:
|
||||
query = query.where(ToolConfig.project_id == uuid.UUID(data.project_id))
|
||||
else:
|
||||
query = query.where(ToolConfig.project_id.is_(None))
|
||||
|
||||
existing = await session.scalar(query)
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"config with key '{data.key}' already exists"
|
||||
)
|
||||
|
||||
config = ToolConfig(
|
||||
user_id=user_id,
|
||||
tool_type_id=uuid.UUID(data.tool_type_id),
|
||||
project_id=uuid.UUID(data.project_id) if data.project_id else None,
|
||||
key=data.key,
|
||||
value=data.value,
|
||||
config_type=data.config_type,
|
||||
file_path=data.file_path,
|
||||
port_override=data.port_override,
|
||||
start_command=data.start_command,
|
||||
working_directory=data.working_directory,
|
||||
environment_variables=data.environment_variables,
|
||||
volumes=data.volumes,
|
||||
)
|
||||
session.add(config)
|
||||
await session.commit()
|
||||
await session.refresh(config)
|
||||
|
||||
return {
|
||||
"id": str(config.id),
|
||||
"tool_type_id": str(config.tool_type_id),
|
||||
"project_id": str(config.project_id) if config.project_id else None,
|
||||
"key": config.key,
|
||||
"value": config.value,
|
||||
"config_type": config.config_type,
|
||||
"file_path": config.file_path,
|
||||
"port_override": config.port_override,
|
||||
"start_command": config.start_command,
|
||||
"working_directory": config.working_directory,
|
||||
"environment_variables": config.environment_variables,
|
||||
"volumes": config.volumes,
|
||||
}
|
||||
|
||||
|
||||
@router.put("/{config_id}", summary="Update tool config", description="Update an existing tool config.")
|
||||
async def update_config(
|
||||
config_id: uuid.UUID,
|
||||
data: ToolConfigUpdate,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Update a tool config."""
|
||||
config = await session.get(ToolConfig, config_id)
|
||||
if config is None or config.user_id != user_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="config not found")
|
||||
|
||||
if data.key is not None:
|
||||
config.key = data.key
|
||||
if data.value is not None:
|
||||
config.value = data.value
|
||||
if data.config_type is not None:
|
||||
config.config_type = data.config_type
|
||||
if data.file_path is not None:
|
||||
config.file_path = data.file_path
|
||||
if data.port_override is not None:
|
||||
config.port_override = data.port_override
|
||||
if data.start_command is not None:
|
||||
config.start_command = data.start_command
|
||||
if data.working_directory is not None:
|
||||
config.working_directory = data.working_directory
|
||||
if data.environment_variables is not None:
|
||||
config.environment_variables = data.environment_variables
|
||||
if data.volumes is not None:
|
||||
config.volumes = data.volumes
|
||||
|
||||
await session.commit()
|
||||
await session.refresh(config)
|
||||
|
||||
return {
|
||||
"id": str(config.id),
|
||||
"tool_type_id": str(config.tool_type_id),
|
||||
"project_id": str(config.project_id) if config.project_id else None,
|
||||
"key": config.key,
|
||||
"value": config.value,
|
||||
"config_type": config.config_type,
|
||||
"file_path": config.file_path,
|
||||
"port_override": config.port_override,
|
||||
"start_command": config.start_command,
|
||||
"working_directory": config.working_directory,
|
||||
"environment_variables": config.environment_variables,
|
||||
"volumes": config.volumes,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/defaults/{tool_type_id}", summary="Get default configs", description="Get suggested default configs for a tool type.")
|
||||
async def get_default_configs(
|
||||
tool_type_id: str,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> dict:
|
||||
"""Get suggested default configs for a tool type."""
|
||||
tool_type = await session.get(ToolType, uuid.UUID(tool_type_id))
|
||||
if tool_type is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="tool type not found")
|
||||
|
||||
# Return suggested defaults based on required_variables
|
||||
defaults = []
|
||||
for var in tool_type.required_variables:
|
||||
defaults.append({
|
||||
"key": var,
|
||||
"value": "",
|
||||
"config_type": "env",
|
||||
"description": f"Required variable: {var}",
|
||||
})
|
||||
|
||||
return {
|
||||
"tool_type_id": tool_type_id,
|
||||
"suggested_configs": defaults,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/{config_id}", summary="Delete tool config", description="Delete a tool config.")
|
||||
async def delete_config(
|
||||
config_id: uuid.UUID,
|
||||
user_id: uuid.UUID = Depends(get_current_user_id),
|
||||
session: AsyncSession = Depends(get_db_session),
|
||||
) -> None:
|
||||
"""Delete a tool config."""
|
||||
config = await session.get(ToolConfig, config_id)
|
||||
if config is None or config.user_id != user_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="config not found")
|
||||
|
||||
await session.delete(config)
|
||||
await session.commit()
|
||||
@@ -1,5 +1,4 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
import yaml
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
@@ -9,7 +8,12 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from src.auth.dependencies import get_current_user, get_db_session
|
||||
from src.models.tool_type import ToolType
|
||||
from src.models.user import User
|
||||
from src.schemas.tool_type import ToolTypeCreate, ToolTypeResponse, ToolTypeUpdate, ToolTypeValidateRequest
|
||||
from src.schemas.tool_type import (
|
||||
ToolTypeCreate,
|
||||
ToolTypeResponse,
|
||||
ToolTypeUpdate,
|
||||
ToolTypeValidateRequest,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/tool-types", tags=["tool-types"])
|
||||
|
||||
@@ -48,12 +52,15 @@ async def create_tool_type(
|
||||
The newly created tool type.
|
||||
"""
|
||||
await _require_admin(user)
|
||||
|
||||
|
||||
# Check for duplicate name
|
||||
existing = await session.scalar(select(ToolType).where(ToolType.name == data.name))
|
||||
if existing:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="tool type with this name already exists")
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="tool type with this name already exists",
|
||||
)
|
||||
|
||||
tool_type = ToolType(
|
||||
name=data.name,
|
||||
display_name=data.display_name,
|
||||
@@ -67,7 +74,6 @@ async def create_tool_type(
|
||||
required_variables=data.required_variables,
|
||||
category=data.category,
|
||||
interfaces=data.interfaces,
|
||||
is_builtin=False,
|
||||
created_by_id=user.id,
|
||||
)
|
||||
session.add(tool_type)
|
||||
@@ -122,7 +128,9 @@ async def get_tool_type(
|
||||
"""
|
||||
tool_type = await session.get(ToolType, tool_type_id)
|
||||
if tool_type is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="tool type not found")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="tool type not found"
|
||||
)
|
||||
return tool_type
|
||||
|
||||
|
||||
@@ -150,25 +158,30 @@ async def update_tool_type(
|
||||
The updated tool type.
|
||||
"""
|
||||
await _require_admin(user)
|
||||
|
||||
|
||||
tool_type = await session.get(ToolType, tool_type_id)
|
||||
if tool_type is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="tool type not found")
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="tool type not found"
|
||||
)
|
||||
|
||||
if tool_type.is_builtin:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="cannot modify built-in tool types")
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="cannot modify built-in tool types",
|
||||
)
|
||||
|
||||
update_data = data.model_dump(exclude_unset=True)
|
||||
|
||||
|
||||
# Validate port if being updated
|
||||
if "default_port" in update_data:
|
||||
new_port = update_data["default_port"]
|
||||
if new_port <= 0 or new_port > 65535:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Port must be between 1 and 65535"
|
||||
detail="Port must be between 1 and 65535",
|
||||
)
|
||||
|
||||
|
||||
# Only validate port exposure for compose definitions
|
||||
definition_type = update_data.get("definition_type", tool_type.definition_type)
|
||||
if definition_type == "compose":
|
||||
@@ -178,28 +191,37 @@ async def update_tool_type(
|
||||
parsed = yaml.safe_load(template)
|
||||
except yaml.YAMLError:
|
||||
parsed = None
|
||||
|
||||
|
||||
if parsed and isinstance(parsed, dict) and "services" in parsed:
|
||||
port_str = str(new_port)
|
||||
port_exposed = False
|
||||
for service_config in parsed["services"].values():
|
||||
if isinstance(service_config, dict) and "ports" in service_config:
|
||||
if (
|
||||
isinstance(service_config, dict)
|
||||
and "ports" in service_config
|
||||
):
|
||||
for port_mapping in service_config["ports"]:
|
||||
if isinstance(port_mapping, str) and port_str in port_mapping:
|
||||
if (
|
||||
isinstance(port_mapping, str)
|
||||
and port_str in port_mapping
|
||||
):
|
||||
port_exposed = True
|
||||
break
|
||||
elif isinstance(port_mapping, int) and port_mapping == new_port:
|
||||
elif (
|
||||
isinstance(port_mapping, int)
|
||||
and port_mapping == new_port
|
||||
):
|
||||
port_exposed = True
|
||||
break
|
||||
if port_exposed:
|
||||
break
|
||||
|
||||
|
||||
if not port_exposed:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Port {new_port} is not exposed in the compose template"
|
||||
detail=f"Port {new_port} is not exposed in the compose template",
|
||||
)
|
||||
|
||||
|
||||
# Validate required variables for compose definitions
|
||||
definition_type = update_data.get("definition_type", tool_type.definition_type)
|
||||
if definition_type == "compose":
|
||||
@@ -210,7 +232,7 @@ async def update_tool_type(
|
||||
if placeholder not in template:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Required variable '{var}' not found in compose template"
|
||||
detail=f"Required variable '{var}' not found in compose template",
|
||||
)
|
||||
elif "required_variables" in update_data:
|
||||
template = tool_type.compose_template
|
||||
@@ -220,12 +242,12 @@ async def update_tool_type(
|
||||
if placeholder not in template:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Required variable '{var}' not found in compose template"
|
||||
detail=f"Required variable '{var}' not found in compose template",
|
||||
)
|
||||
|
||||
|
||||
for field, value in update_data.items():
|
||||
setattr(tool_type, field, value)
|
||||
|
||||
|
||||
await session.commit()
|
||||
await session.refresh(tool_type)
|
||||
return tool_type
|
||||
@@ -306,10 +328,12 @@ async def validate_tool_type(
|
||||
"""
|
||||
tool_type = await session.get(ToolType, tool_type_id)
|
||||
if tool_type is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="tool type not found")
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="tool type not found"
|
||||
)
|
||||
|
||||
errors = []
|
||||
|
||||
|
||||
if tool_type.definition_type == "compose":
|
||||
if not tool_type.compose_template:
|
||||
errors.append("Compose template is empty")
|
||||
@@ -324,13 +348,13 @@ async def validate_tool_type(
|
||||
errors.append("Compose template must define at least one service")
|
||||
except yaml.YAMLError as e:
|
||||
errors.append(f"Invalid YAML: {e}")
|
||||
|
||||
|
||||
elif tool_type.definition_type == "dockerfile":
|
||||
if not tool_type.dockerfile_template:
|
||||
errors.append("Dockerfile template is empty")
|
||||
elif not tool_type.dockerfile_template.strip().startswith("FROM"):
|
||||
errors.append("Dockerfile must start with a FROM instruction")
|
||||
|
||||
|
||||
return {
|
||||
"valid": len(errors) == 0,
|
||||
"errors": errors,
|
||||
@@ -359,13 +383,18 @@ async def delete_tool_type(
|
||||
None with 204 status code.
|
||||
"""
|
||||
await _require_admin(user)
|
||||
|
||||
|
||||
tool_type = await session.get(ToolType, tool_type_id)
|
||||
if tool_type is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="tool type not found")
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="tool type not found"
|
||||
)
|
||||
|
||||
if tool_type.is_builtin:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="cannot delete built-in tool types")
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="cannot delete built-in tool types",
|
||||
)
|
||||
|
||||
await session.delete(tool_type)
|
||||
await session.commit()
|
||||
|
||||
@@ -19,7 +19,6 @@ ALLOWED_CONTENT_TYPES = {"image/png", "image/jpeg", "image/jpg"}
|
||||
MAX_AVATAR_SIZE = 2 * 1024 * 1024 # 2MB
|
||||
|
||||
|
||||
|
||||
@router.get(
|
||||
"/me",
|
||||
response_model=UserProfileResponse,
|
||||
@@ -66,12 +65,16 @@ async def update_profile(
|
||||
|
||||
if data.name is not None:
|
||||
if len(data.name.strip()) == 0:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="name cannot be empty")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail="name cannot be empty"
|
||||
)
|
||||
user.name = data.name.strip()
|
||||
|
||||
if data.email is not None:
|
||||
if "@" not in data.email:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="invalid email")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail="invalid email"
|
||||
)
|
||||
user.email = data.email.strip()
|
||||
|
||||
await session.commit()
|
||||
@@ -159,7 +162,7 @@ async def get_user_sessions(
|
||||
id=str(inst.id),
|
||||
display_name=inst.display_name,
|
||||
tool_type_name=inst.tool_type.display_name if inst.tool_type else "Unknown",
|
||||
tool_icon=inst.tool_type.icon if inst.tool_type else None,
|
||||
tool_icon=None,
|
||||
tool_type_interfaces=inst.tool_type.interfaces if inst.tool_type else [],
|
||||
repository_name=inst.repository.name if inst.repository else "Unknown",
|
||||
repository_id=str(inst.repository_id),
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
|
||||
@@ -15,16 +14,13 @@ from src.api.projects import router as projects_router
|
||||
from src.api.ssh_keys import router as ssh_keys_router
|
||||
from src.api.terminal import router as terminal_router
|
||||
from src.api.instance_proxy import router as instance_proxy_router
|
||||
from src.api.config_folders import router as config_folders_router
|
||||
from src.api.config_profiles import router as config_profiles_router
|
||||
from src.api.tool_configs import router as tool_configs_router
|
||||
from src.api.tool_instances import router as tool_instances_router
|
||||
from src.api.tool_instances import sessions_router
|
||||
from src.api.tool_types import router as tool_types_router
|
||||
from src.api.user_config import router as user_config_router
|
||||
from src.api.users import router as users_router
|
||||
from src.config import Settings
|
||||
from src.database import SessionLocal, init_database
|
||||
from src.database import init_database
|
||||
from src.logging_config import (
|
||||
ExceptionLoggingMiddleware,
|
||||
RequestLoggingMiddleware,
|
||||
@@ -67,7 +63,9 @@ def _sanitize_validation_errors(errors):
|
||||
"type": error.get("type"),
|
||||
"loc": error.get("loc"),
|
||||
"msg": error.get("msg"),
|
||||
"input": str(error.get("input")) if error.get("input") is not None else None,
|
||||
"input": str(error.get("input"))
|
||||
if error.get("input") is not None
|
||||
else None,
|
||||
}
|
||||
# Convert ctx to safe format
|
||||
ctx = error.get("ctx")
|
||||
@@ -111,12 +109,14 @@ async def on_startup():
|
||||
if not db_ready:
|
||||
logger.error("Database initialization failed. Shutting down.")
|
||||
import sys
|
||||
|
||||
sys.exit(1)
|
||||
|
||||
# Seed built-in data
|
||||
await seed_builtin_tool_types()
|
||||
logger.info("Startup complete.")
|
||||
|
||||
|
||||
app.include_router(health_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(dashboard_router)
|
||||
@@ -126,11 +126,8 @@ app.include_router(ssh_keys_router)
|
||||
app.include_router(git_repositories_router)
|
||||
app.include_router(user_config_router)
|
||||
app.include_router(tool_types_router)
|
||||
app.include_router(config_folders_router)
|
||||
app.include_router(config_profiles_router)
|
||||
app.include_router(tool_instances_router)
|
||||
app.include_router(tool_configs_router)
|
||||
app.include_router(sessions_router)
|
||||
app.include_router(instance_proxy_router)
|
||||
app.include_router(terminal_router)
|
||||
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from src.models.base import Base
|
||||
from src.models.config_folder import ConfigFolder
|
||||
from src.models.config_include import ConfigInclude
|
||||
from src.models.config_mount import ConfigMount
|
||||
from src.models.config_profile import ConfigProfile
|
||||
@@ -13,7 +12,6 @@ from src.models.user_config import UserConfig
|
||||
|
||||
__all__ = [
|
||||
"Base",
|
||||
"ConfigFolder",
|
||||
"ConfigInclude",
|
||||
"ConfigMount",
|
||||
"ConfigProfile",
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
import uuid
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import Boolean, ForeignKey, JSON, String, Text
|
||||
from sqlalchemy import Uuid as UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from src.models.base import Base, TimestampMixin, UUIDPrimaryKeyMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from src.models.user import User
|
||||
|
||||
|
||||
class ConfigFolder(UUIDPrimaryKeyMixin, TimestampMixin, Base):
|
||||
__tablename__ = "config_folders"
|
||||
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(), ForeignKey("users.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
description: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
mount_path: Mapped[str] = mapped_column(String(1024), nullable=False)
|
||||
files: Mapped[dict] = mapped_column(
|
||||
JSON, default=dict, nullable=False
|
||||
) # {"relative/path": "content", ...}
|
||||
project_overrides: Mapped[dict | None] = mapped_column(
|
||||
JSON, default=dict, nullable=True
|
||||
) # {"project_id": {"mount_path": "...", "files": {...}}}
|
||||
# DEPRECATED: Legacy auto-mounting flag. No longer used for launch-time
|
||||
# auto-mounting. Use ConfigProfile and ToolInstance.selected_profile_id instead.
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||
|
||||
user: Mapped["User"] = relationship()
|
||||
@@ -1,8 +1,7 @@
|
||||
import uuid
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import Boolean, ForeignKey, JSON, String, Text
|
||||
from sqlalchemy import Uuid as UUID
|
||||
from sqlalchemy import Boolean, ForeignKey, JSON, String, Text, Uuid as UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from src.models.base import Base, TimestampMixin, UUIDPrimaryKeyMixin
|
||||
@@ -52,3 +51,21 @@ class ToolType(UUIDPrimaryKeyMixin, TimestampMixin, Base):
|
||||
foreign_keys=[manifest_id],
|
||||
)
|
||||
created_by: Mapped["User | None"] = relationship()
|
||||
|
||||
@property
|
||||
def interfaces(self) -> list[str]:
|
||||
"""Backward-compatible API view for the single interface type."""
|
||||
return [self.interface_type]
|
||||
|
||||
@interfaces.setter
|
||||
def interfaces(self, value: list[str] | str) -> None:
|
||||
"""Accept legacy interface lists and store the first interface type."""
|
||||
if isinstance(value, str):
|
||||
self.interface_type = value
|
||||
return
|
||||
self.interface_type = value[0] if value else "web"
|
||||
|
||||
@property
|
||||
def is_builtin(self) -> bool:
|
||||
"""Built-in tools are seeded system tools without a creating user."""
|
||||
return self.created_by_id is None
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
"""Config folder request/response schemas."""
|
||||
|
||||
import uuid
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ConfigFolderCreate(BaseModel):
|
||||
name: str = Field(description="Folder name")
|
||||
description: str | None = Field(default=None, description="Optional description")
|
||||
mount_path: str = Field(description="Mount path in container")
|
||||
files: dict[str, str] | None = Field(
|
||||
default=None, description="Files as {path: content}"
|
||||
)
|
||||
is_active: bool = Field(default=True, description="Whether folder is active")
|
||||
|
||||
|
||||
class ConfigFolderUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
mount_path: str | None = None
|
||||
files: dict[str, str] | None = None
|
||||
is_active: bool | None = None
|
||||
|
||||
|
||||
class ProjectOverrideCreate(BaseModel):
|
||||
project_id: str = Field(description="Project ID to override for")
|
||||
mount_path: str | None = Field(default=None, description="Override mount path")
|
||||
files: dict[str, str] | None = Field(
|
||||
default=None, description="Override files"
|
||||
)
|
||||
is_active: bool | None = Field(default=None, description="Override active state")
|
||||
|
||||
|
||||
class ConfigFolderResponse(BaseModel):
|
||||
id: str
|
||||
user_id: str
|
||||
name: str
|
||||
description: str | None
|
||||
mount_path: str
|
||||
files: dict[str, str] | None
|
||||
is_active: bool
|
||||
created_at: str
|
||||
updated_at: str
|
||||
@@ -1,47 +0,0 @@
|
||||
"""Tool config request/response schemas."""
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ToolConfigCreate(BaseModel):
|
||||
tool_type_id: str = Field(description="UUID of the tool type")
|
||||
key: str = Field(description="Configuration key")
|
||||
value: str = Field(description="Configuration value")
|
||||
config_type: str = Field(default="env", description="Config type: env or file")
|
||||
file_path: str | None = Field(default=None, description="File path for file configs")
|
||||
port_override: int | None = Field(default=None, description="Port override")
|
||||
start_command: str | None = Field(default=None, description="Start command override")
|
||||
working_directory: str | None = Field(default=None, description="Working directory")
|
||||
environment_variables: dict[str, str] | None = Field(
|
||||
default=None, description="Additional environment variables"
|
||||
)
|
||||
volumes: list[dict] | None = Field(default=None, description="Volume mounts")
|
||||
|
||||
|
||||
class ToolConfigUpdate(BaseModel):
|
||||
value: str | None = None
|
||||
config_type: str | None = None
|
||||
file_path: str | None = None
|
||||
port_override: int | None = None
|
||||
start_command: str | None = None
|
||||
working_directory: str | None = None
|
||||
environment_variables: dict[str, str] | None = None
|
||||
volumes: list[dict] | None = None
|
||||
|
||||
|
||||
class ToolConfigResponse(BaseModel):
|
||||
id: str
|
||||
tool_type_id: str
|
||||
user_id: str
|
||||
project_id: str | None
|
||||
key: str
|
||||
value: str
|
||||
config_type: str
|
||||
file_path: str | None
|
||||
port_override: int | None
|
||||
start_command: str | None
|
||||
working_directory: str | None
|
||||
environment_variables: dict[str, str] | None
|
||||
volumes: list[dict] | None
|
||||
created_at: str
|
||||
updated_at: str
|
||||
@@ -46,7 +46,7 @@ async def seed_builtin_tool_types():
|
||||
"display_name": "VS Code Server",
|
||||
"description": "VS Code running in the browser via code-server",
|
||||
"category": "editor",
|
||||
"interfaces": ["web"],
|
||||
"interface_type": "web",
|
||||
"compose_template": """version: "3.8"
|
||||
services:
|
||||
code-server:
|
||||
@@ -69,7 +69,7 @@ services:
|
||||
"display_name": "Jupyter Notebook",
|
||||
"description": "Jupyter Lab for interactive development",
|
||||
"category": "notebook",
|
||||
"interfaces": ["web"],
|
||||
"interface_type": "web",
|
||||
"default_port": 8888,
|
||||
"compose_template": """version: "3.8"
|
||||
services:
|
||||
@@ -90,7 +90,7 @@ services:
|
||||
"display_name": "OpenCode",
|
||||
"description": "AI coding assistant - run opencode in terminal",
|
||||
"category": "ai-assistant",
|
||||
"interfaces": ["terminal"],
|
||||
"interface_type": "terminal",
|
||||
"default_port": 3000,
|
||||
"compose_template": """version: "3.8"
|
||||
services:
|
||||
@@ -129,19 +129,20 @@ volumes:
|
||||
]
|
||||
|
||||
for tool_data in builtin_types:
|
||||
existing = await session.scalar(select(ToolType).where(ToolType.name == tool_data["name"]))
|
||||
existing = await session.scalar(
|
||||
select(ToolType).where(ToolType.name == tool_data["name"])
|
||||
)
|
||||
if not existing:
|
||||
tool_type = ToolType(
|
||||
name=tool_data["name"],
|
||||
display_name=tool_data["display_name"],
|
||||
description=tool_data["description"],
|
||||
category=tool_data["category"],
|
||||
interfaces=tool_data["interfaces"],
|
||||
interface_type=tool_data["interface_type"],
|
||||
definition_type="compose",
|
||||
compose_template=tool_data["compose_template"],
|
||||
required_variables=tool_data["required_variables"],
|
||||
default_port=tool_data.get("default_port"),
|
||||
is_builtin=True,
|
||||
default_port=tool_data["default_port"],
|
||||
)
|
||||
session.add(tool_type)
|
||||
logger.info("Created built-in tool type: %s", tool_data["name"])
|
||||
@@ -150,11 +151,11 @@ volumes:
|
||||
existing.display_name = tool_data["display_name"]
|
||||
existing.description = tool_data["description"]
|
||||
existing.category = tool_data["category"]
|
||||
existing.interfaces = tool_data["interfaces"]
|
||||
existing.interface_type = tool_data["interface_type"]
|
||||
existing.definition_type = "compose"
|
||||
existing.compose_template = tool_data["compose_template"]
|
||||
existing.required_variables = tool_data["required_variables"]
|
||||
existing.default_port = tool_data.get("default_port")
|
||||
existing.default_port = tool_data["default_port"]
|
||||
logger.info("Updated built-in tool type: %s", tool_data["name"])
|
||||
|
||||
await session.commit()
|
||||
|
||||
@@ -7,7 +7,7 @@ from .compose import (
|
||||
write_compose_file,
|
||||
write_env_file,
|
||||
)
|
||||
from .config_staging import write_config_files, write_config_folder_files
|
||||
from .config_staging import write_config_files
|
||||
from .container import (
|
||||
connect_container_to_network,
|
||||
find_free_port,
|
||||
@@ -30,7 +30,6 @@ __all__ = [
|
||||
"write_env_file",
|
||||
"execute_compose_command",
|
||||
"write_config_files",
|
||||
"write_config_folder_files",
|
||||
"get_container_id",
|
||||
"get_container_name",
|
||||
"connect_container_to_network",
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
"""Config folder file staging for Docker instances."""
|
||||
"""Config file staging for Docker instances."""
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def write_config_files(instance_dir: str, files: dict[str, str]) -> None:
|
||||
"""Write config files to the instance directory.
|
||||
|
||||
@@ -24,56 +20,3 @@ def write_config_files(instance_dir: str, files: dict[str, str]) -> None:
|
||||
|
||||
full_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
full_path.write_text(content)
|
||||
|
||||
|
||||
def write_config_folder_files(instance_dir: str, folders: list, project_id: str | None = None) -> list[dict]:
|
||||
"""Write config folder files to the instance directory and return volume mounts.
|
||||
|
||||
Args:
|
||||
instance_dir: Path to instance directory
|
||||
folders: List of ConfigFolder objects
|
||||
project_id: Optional project ID for applying overrides
|
||||
|
||||
Returns:
|
||||
List of volume mount dicts [{"source": "...", "target": "...", "type": "..."}]
|
||||
"""
|
||||
instance_path = Path(instance_dir)
|
||||
volume_mounts = []
|
||||
|
||||
for folder in folders:
|
||||
# Determine mount path (with project override if applicable)
|
||||
mount_path = folder.mount_path
|
||||
files = folder.files.copy()
|
||||
|
||||
if project_id and folder.project_overrides:
|
||||
override = folder.project_overrides.get(str(project_id))
|
||||
if override:
|
||||
if override.get("mount_path"):
|
||||
mount_path = override["mount_path"]
|
||||
if override.get("files"):
|
||||
files.update(override["files"])
|
||||
|
||||
# Write files to instance directory
|
||||
folder_dir = instance_path / "volumes" / folder.name
|
||||
folder_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for file_path, content in files.items():
|
||||
# Security: ensure path doesn't escape folder_dir
|
||||
full_path = folder_dir / file_path
|
||||
try:
|
||||
full_path.resolve().relative_to(folder_dir.resolve())
|
||||
except ValueError:
|
||||
logger.warning("Config folder file path escapes directory: %s", file_path)
|
||||
continue
|
||||
|
||||
full_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
full_path.write_text(content)
|
||||
|
||||
# Add volume mount
|
||||
volume_mounts.append({
|
||||
"source": str(folder_dir),
|
||||
"target": mount_path,
|
||||
"type": "bind",
|
||||
})
|
||||
|
||||
return volume_mounts
|
||||
|
||||
@@ -11,14 +11,11 @@ from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from src.models.config_folder import ConfigFolder
|
||||
from src.models.config_profile import ConfigProfile
|
||||
from src.models.git_repository import GitRepository
|
||||
from src.models.project import Project
|
||||
from src.models.tool_config import ToolConfig
|
||||
from src.models.tool_instance import ToolInstance
|
||||
from src.models.tool_type import ToolType
|
||||
from src.models.user import User
|
||||
@@ -54,7 +51,8 @@ async def create_new_instance(
|
||||
|
||||
instance = ToolInstance(
|
||||
name=instance_name,
|
||||
display_name=display_name or f"{project.name} / {repo.name} / {tool_type.display_name}",
|
||||
display_name=display_name
|
||||
or f"{project.name} / {repo.name} / {tool_type.display_name}",
|
||||
tool_type_id=tool_type.id,
|
||||
repository_id=repo.id,
|
||||
project_id=project.id,
|
||||
@@ -85,16 +83,27 @@ async def start_existing_instance(
|
||||
instance.status = "building"
|
||||
await session.commit()
|
||||
|
||||
env_vars, config_files, port_override, start_command, working_directory, _extra_env, extra_volumes = await _fetch_tool_configs(
|
||||
session, user.id, instance.tool_type_id, project_id
|
||||
)
|
||||
env_vars: dict[str, str] = {}
|
||||
config_files: dict[str, str] = {}
|
||||
port_override = None
|
||||
start_command = None
|
||||
working_directory = None
|
||||
extra_volumes: list[dict] = []
|
||||
|
||||
selected_profile = None
|
||||
if instance.selected_profile_id:
|
||||
selected_profile = await session.get(ConfigProfile, instance.selected_profile_id)
|
||||
selected_profile = await session.get(
|
||||
ConfigProfile, instance.selected_profile_id
|
||||
)
|
||||
if selected_profile and selected_profile.user_id == user.id:
|
||||
instance_dir = os.path.dirname(instance.compose_path)
|
||||
env_vars, port_override, start_command, working_directory, extra_volumes = await compose_svc._apply_resolved_profile(
|
||||
(
|
||||
env_vars,
|
||||
port_override,
|
||||
start_command,
|
||||
working_directory,
|
||||
extra_volumes,
|
||||
) = await compose_svc._apply_resolved_profile(
|
||||
selected_profile,
|
||||
instance_dir,
|
||||
env_vars,
|
||||
@@ -104,14 +113,17 @@ async def start_existing_instance(
|
||||
extra_volumes,
|
||||
)
|
||||
|
||||
env_file_path, extra_volumes = await _stage_configs_and_folders(
|
||||
session, user.id, project_id, os.path.dirname(instance.compose_path),
|
||||
env_vars, config_files, extra_volumes
|
||||
env_file_path, extra_volumes = await _stage_configs(
|
||||
os.path.dirname(instance.compose_path), env_vars, config_files, extra_volumes
|
||||
)
|
||||
|
||||
if port_override or start_command or working_directory or extra_volumes:
|
||||
compose_svc._modify_compose_file(
|
||||
instance.compose_path, port_override, start_command, working_directory, extra_volumes
|
||||
instance.compose_path,
|
||||
port_override,
|
||||
start_command,
|
||||
working_directory,
|
||||
extra_volumes,
|
||||
)
|
||||
|
||||
returncode, _stdout, stderr = compose_svc.execute_compose_command(
|
||||
@@ -138,6 +150,14 @@ async def start_existing_instance(
|
||||
await session.commit()
|
||||
|
||||
tool_type = await session.get(ToolType, instance.tool_type_id)
|
||||
if not tool_type:
|
||||
instance.status = "error"
|
||||
await session.commit()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="tool type not found for instance",
|
||||
)
|
||||
|
||||
success, probe_logs = await _run_readiness_probe(instance, tool_type)
|
||||
if not success:
|
||||
instance.status = "failed"
|
||||
@@ -175,27 +195,45 @@ async def restart_existing_instance(
|
||||
await session.commit()
|
||||
return {"status": instance.status}
|
||||
|
||||
env_vars, config_files, port_override, start_command, working_directory, _extra_env, extra_volumes = await _fetch_tool_configs(
|
||||
session, user.id, instance.tool_type_id, project_id
|
||||
)
|
||||
env_vars: dict[str, str] = {}
|
||||
config_files: dict[str, str] = {}
|
||||
port_override = None
|
||||
start_command = None
|
||||
working_directory = None
|
||||
extra_volumes: list[dict] = []
|
||||
|
||||
stored_profile = None
|
||||
if instance.selected_profile_id:
|
||||
stored_profile = await session.get(ConfigProfile, instance.selected_profile_id)
|
||||
if stored_profile and stored_profile.user_id == user.id:
|
||||
instance_dir = os.path.dirname(instance.compose_path)
|
||||
env_vars, port_override, start_command, working_directory, extra_volumes = await compose_svc._apply_resolved_profile(
|
||||
stored_profile, instance_dir, env_vars, port_override, start_command, working_directory, extra_volumes
|
||||
(
|
||||
env_vars,
|
||||
port_override,
|
||||
start_command,
|
||||
working_directory,
|
||||
extra_volumes,
|
||||
) = await compose_svc._apply_resolved_profile(
|
||||
stored_profile,
|
||||
instance_dir,
|
||||
env_vars,
|
||||
port_override,
|
||||
start_command,
|
||||
working_directory,
|
||||
extra_volumes,
|
||||
)
|
||||
|
||||
env_file_path, extra_volumes = await _stage_configs_and_folders(
|
||||
session, user.id, project_id, os.path.dirname(instance.compose_path),
|
||||
env_vars, config_files, extra_volumes
|
||||
env_file_path, extra_volumes = await _stage_configs(
|
||||
os.path.dirname(instance.compose_path), env_vars, config_files, extra_volumes
|
||||
)
|
||||
|
||||
if port_override or start_command or working_directory or extra_volumes:
|
||||
compose_svc._modify_compose_file(
|
||||
instance.compose_path, port_override, start_command, working_directory, extra_volumes
|
||||
instance.compose_path,
|
||||
port_override,
|
||||
start_command,
|
||||
working_directory,
|
||||
extra_volumes,
|
||||
)
|
||||
|
||||
returncode, _stdout, _stderr = compose_svc.execute_compose_command(
|
||||
@@ -210,6 +248,11 @@ async def restart_existing_instance(
|
||||
instance.last_started_at = datetime.now()
|
||||
|
||||
tool_type = await session.get(ToolType, instance.tool_type_id)
|
||||
if not tool_type:
|
||||
instance.status = "error"
|
||||
await session.commit()
|
||||
return {"status": instance.status}
|
||||
|
||||
await _start_tunnel_if_web(instance, tool_type)
|
||||
await session.commit()
|
||||
|
||||
@@ -235,7 +278,9 @@ async def stop_existing_instance(session: AsyncSession, instance: ToolInstance)
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def delete_existing_instance(session: AsyncSession, instance: ToolInstance) -> None:
|
||||
async def delete_existing_instance(
|
||||
session: AsyncSession, instance: ToolInstance
|
||||
) -> None:
|
||||
"""Delete an instance, its containers, and its directory."""
|
||||
if instance.tunnel_id:
|
||||
try:
|
||||
@@ -255,6 +300,7 @@ async def delete_existing_instance(session: AsyncSession, instance: ToolInstance
|
||||
|
||||
# ── Internal helpers ───────────────────────────────────────────────────────
|
||||
|
||||
|
||||
async def _build_or_render_compose(
|
||||
tool_type: ToolType,
|
||||
instance_name: str,
|
||||
@@ -283,11 +329,11 @@ async def _build_or_render_compose(
|
||||
|
||||
compose_content = (
|
||||
f'version: "3.8"\nservices:\n app:\n'
|
||||
f' image: {image_tag}\n'
|
||||
f' container_name: {instance_name}\n'
|
||||
f" image: {image_tag}\n"
|
||||
f" container_name: {instance_name}\n"
|
||||
f' ports:\n - "{tool_port}:{tool_type.default_port}"\n'
|
||||
f' volumes:\n - {repo.path}:/workspace\n'
|
||||
f' restart: unless-stopped\n'
|
||||
f" volumes:\n - {repo.path}:/workspace\n"
|
||||
f" restart: unless-stopped\n"
|
||||
)
|
||||
else:
|
||||
variables = {
|
||||
@@ -299,6 +345,11 @@ async def _build_or_render_compose(
|
||||
"USER_ID": str(user.id),
|
||||
"PROJECT_ID": str(project_id),
|
||||
}
|
||||
if not tool_type.compose_template:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="tool type has no compose template",
|
||||
)
|
||||
compose_content = compose_svc.render_compose_template(
|
||||
tool_type.compose_template, variables
|
||||
)
|
||||
@@ -307,80 +358,25 @@ async def _build_or_render_compose(
|
||||
return os.path.join(instance_dir, "docker-compose.yml")
|
||||
|
||||
|
||||
async def _fetch_tool_configs(
|
||||
session: AsyncSession,
|
||||
user_id: Any,
|
||||
tool_type_id: Any,
|
||||
project_id: Any,
|
||||
) -> tuple[dict, dict, Any, Any, Any, dict, list]:
|
||||
"""Fetch tool configs and return parsed values."""
|
||||
env_vars: dict[str, str] = {}
|
||||
config_files: dict[str, str] = {}
|
||||
port_override = None
|
||||
start_command = None
|
||||
working_directory = None
|
||||
extra_env_vars: dict[str, str] = {}
|
||||
extra_volumes: list[dict] = []
|
||||
|
||||
query = (
|
||||
select(ToolConfig)
|
||||
.where(ToolConfig.user_id == user_id, ToolConfig.tool_type_id == tool_type_id)
|
||||
.where((ToolConfig.project_id == project_id) | (ToolConfig.project_id.is_(None)))
|
||||
)
|
||||
configs = (await session.execute(query)).scalars().all()
|
||||
|
||||
for cfg in configs:
|
||||
if cfg.config_type == "env":
|
||||
env_vars[cfg.key] = cfg.value
|
||||
elif cfg.config_type == "file" and cfg.file_path:
|
||||
config_files[cfg.file_path] = cfg.value
|
||||
if cfg.port_override:
|
||||
port_override = cfg.port_override
|
||||
if cfg.start_command:
|
||||
start_command = cfg.start_command
|
||||
if cfg.working_directory:
|
||||
working_directory = cfg.working_directory
|
||||
if cfg.environment_variables:
|
||||
extra_env_vars.update(cfg.environment_variables)
|
||||
if cfg.volumes:
|
||||
extra_volumes.extend(cfg.volumes)
|
||||
|
||||
env_vars.update(extra_env_vars)
|
||||
return env_vars, config_files, port_override, start_command, working_directory, extra_env_vars, extra_volumes
|
||||
|
||||
|
||||
async def _stage_configs_and_folders(
|
||||
session: AsyncSession,
|
||||
user_id: Any,
|
||||
project_id: Any,
|
||||
async def _stage_configs(
|
||||
instance_dir: str,
|
||||
env_vars: dict[str, str],
|
||||
config_files: dict[str, str],
|
||||
extra_volumes: list[dict],
|
||||
) -> tuple[str | None, list[dict]]:
|
||||
"""Write env/config files and config folders."""
|
||||
"""Write env/config files for the resolved profile."""
|
||||
env_file_path: str | None = None
|
||||
if env_vars:
|
||||
env_file_path = compose_svc.write_env_file(instance_dir, env_vars)
|
||||
if config_files:
|
||||
config_staging.write_config_files(instance_dir, config_files)
|
||||
|
||||
folder_query = select(ConfigFolder).where(
|
||||
ConfigFolder.user_id == user_id, ConfigFolder.is_active.is_(True)
|
||||
)
|
||||
folders = (await session.execute(folder_query)).scalars().all()
|
||||
if folders:
|
||||
folder_volumes = config_staging.write_config_folder_files(
|
||||
instance_dir, folders, str(project_id)
|
||||
)
|
||||
extra_volumes.extend(folder_volumes)
|
||||
|
||||
return env_file_path, extra_volumes
|
||||
|
||||
|
||||
async def _start_tunnel_if_web(instance: ToolInstance, tool_type: ToolType) -> None:
|
||||
"""Create Cloudflare tunnel for web-enabled tools."""
|
||||
if "web" not in tool_type.interfaces or not tool_type.default_port:
|
||||
if tool_type.interface_type != "web" or not tool_type.default_port:
|
||||
instance.url = None
|
||||
instance.public_url = None
|
||||
return
|
||||
@@ -393,7 +389,9 @@ async def _start_tunnel_if_web(instance: ToolInstance, tool_type: ToolType) -> N
|
||||
instance.tunnel_id = tunnel_info["pid"]
|
||||
instance.public_url = tunnel_info["url"]
|
||||
instance.url = tunnel_info["url"]
|
||||
logger.info("Created tunnel for instance %s: %s", instance.id, tunnel_info["url"])
|
||||
logger.info(
|
||||
"Created tunnel for instance %s: %s", instance.id, tunnel_info["url"]
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("Failed to create tunnel for instance %s: %s", instance.id, exc)
|
||||
instance.status = "error"
|
||||
|
||||
@@ -19,7 +19,6 @@ let warnings = 0;
|
||||
const OVERSIZE_ALLOWLIST = [
|
||||
// Form-heavy admin tabs: 15+ fields each, splitting would create micro-components
|
||||
"components/features/tool-workshop/ToolTypesTab.tsx",
|
||||
"components/features/tool-workshop/ToolConfigsTab.tsx",
|
||||
// Complex terminal hook: WS lifecycle + ping-pong + echo + resize debouncing
|
||||
"hooks/use-terminal-connection.ts",
|
||||
// Terminal component: xterm lifecycle + resize observer + overlay UI
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createConfigFolder,
|
||||
deleteConfigFolder,
|
||||
listConfigFolders,
|
||||
updateConfigFolder,
|
||||
} from "../api/config-folders";
|
||||
|
||||
const mockGet = vi.fn();
|
||||
const mockPost = vi.fn();
|
||||
const mockPut = vi.fn();
|
||||
const mockDelete = vi.fn();
|
||||
|
||||
vi.mock("../api/client", () => ({
|
||||
apiClient: {
|
||||
get: (...args: unknown[]) => mockGet(...args),
|
||||
post: (...args: unknown[]) => mockPost(...args),
|
||||
put: (...args: unknown[]) => mockPut(...args),
|
||||
delete: (...args: unknown[]) => mockDelete(...args),
|
||||
interceptors: {
|
||||
response: {
|
||||
use: vi.fn(),
|
||||
},
|
||||
},
|
||||
},
|
||||
shouldSkipAuthRedirect: vi.fn(() => false),
|
||||
}));
|
||||
|
||||
describe("config_folders API", () => {
|
||||
describe("listConfigFolders", () => {
|
||||
it("returns folders with files and overrides", async () => {
|
||||
const mockResponse = {
|
||||
data: [
|
||||
{
|
||||
id: "folder-1",
|
||||
name: "my-dotfiles",
|
||||
description: "My personal config files",
|
||||
mount_path: "/home/user",
|
||||
files: { ".zshrc": "export ZSH=\"$HOME/.oh-my-zsh\"" },
|
||||
project_overrides: {},
|
||||
is_active: true,
|
||||
user_id: "user-1",
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
mockGet.mockResolvedValue(mockResponse);
|
||||
|
||||
const result = await listConfigFolders();
|
||||
|
||||
expect(result[0].name).toBe("my-dotfiles");
|
||||
expect(result[0].files).toEqual({ ".zshrc": "export ZSH=\"$HOME/.oh-my-zsh\"" });
|
||||
expect(mockGet).toHaveBeenCalledWith("/config-folders");
|
||||
});
|
||||
});
|
||||
|
||||
describe("createConfigFolder", () => {
|
||||
it("creates folder with files", async () => {
|
||||
const mockResponse = {
|
||||
data: {
|
||||
id: "folder-new",
|
||||
name: "new-folder",
|
||||
mount_path: "/workspace",
|
||||
files: { ".env": "API_URL=http://localhost" },
|
||||
is_active: true,
|
||||
user_id: "user-1",
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
},
|
||||
};
|
||||
mockPost.mockResolvedValue(mockResponse);
|
||||
|
||||
const result = await createConfigFolder({
|
||||
name: "new-folder",
|
||||
mount_path: "/workspace",
|
||||
files: { ".env": "API_URL=http://localhost" },
|
||||
});
|
||||
|
||||
expect(result.name).toBe("new-folder");
|
||||
expect(mockPost).toHaveBeenCalledWith(
|
||||
"/config-folders",
|
||||
expect.objectContaining({
|
||||
name: "new-folder",
|
||||
mount_path: "/workspace",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("updateConfigFolder", () => {
|
||||
it("updates folder files", async () => {
|
||||
const mockResponse = {
|
||||
data: {
|
||||
id: "folder-1",
|
||||
name: "updated-folder",
|
||||
mount_path: "/home/user",
|
||||
files: { ".bashrc": "alias ll='ls -la'" },
|
||||
is_active: true,
|
||||
user_id: "user-1",
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
},
|
||||
};
|
||||
mockPut.mockResolvedValue(mockResponse);
|
||||
|
||||
const result = await updateConfigFolder("folder-1", {
|
||||
files: { ".bashrc": "alias ll='ls -la'" },
|
||||
});
|
||||
|
||||
expect(result.files).toEqual({ ".bashrc": "alias ll='ls -la'" });
|
||||
expect(mockPut).toHaveBeenCalledWith(
|
||||
"/config-folders/folder-1",
|
||||
expect.objectContaining({
|
||||
files: { ".bashrc": "alias ll='ls -la'" },
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleteConfigFolder", () => {
|
||||
it("deletes folder", async () => {
|
||||
mockDelete.mockResolvedValue({ data: undefined });
|
||||
|
||||
await deleteConfigFolder("folder-1");
|
||||
|
||||
expect(mockDelete).toHaveBeenCalledWith("/config-folders/folder-1");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,77 +0,0 @@
|
||||
import { apiClient } from "./client";
|
||||
import type {
|
||||
ConfigFolder,
|
||||
CreateConfigFolderRequest,
|
||||
UpdateConfigFolderRequest,
|
||||
ProjectOverrideRequest,
|
||||
} from "../types/config-folder";
|
||||
|
||||
export type {
|
||||
ConfigFolder,
|
||||
CreateConfigFolderRequest,
|
||||
UpdateConfigFolderRequest,
|
||||
ProjectOverrideRequest,
|
||||
} from "../types/config-folder";
|
||||
|
||||
export const listConfigFolders = async (): Promise<ConfigFolder[]> => {
|
||||
const response = await apiClient.get<ConfigFolder[]>("/config-folders");
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const getConfigFolder = async (id: string): Promise<ConfigFolder> => {
|
||||
const response = await apiClient.get<ConfigFolder>(`/config-folders/${id}`);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const createConfigFolder = async (
|
||||
data: CreateConfigFolderRequest,
|
||||
): Promise<ConfigFolder> => {
|
||||
const response = await apiClient.post<ConfigFolder>("/config-folders", data);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const updateConfigFolder = async (
|
||||
id: string,
|
||||
data: UpdateConfigFolderRequest,
|
||||
): Promise<ConfigFolder> => {
|
||||
const response = await apiClient.put<ConfigFolder>(
|
||||
`/config-folders/${id}`,
|
||||
data,
|
||||
);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const deleteConfigFolder = async (id: string): Promise<void> => {
|
||||
await apiClient.delete(`/config-folders/${id}`);
|
||||
};
|
||||
|
||||
export const addProjectOverride = async (
|
||||
id: string,
|
||||
projectId: string,
|
||||
data: ProjectOverrideRequest,
|
||||
): Promise<ConfigFolder> => {
|
||||
const response = await apiClient.post<ConfigFolder>(
|
||||
`/config-folders/${id}/overrides/${projectId}`,
|
||||
data,
|
||||
);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const updateProjectOverride = async (
|
||||
id: string,
|
||||
projectId: string,
|
||||
data: ProjectOverrideRequest,
|
||||
): Promise<ConfigFolder> => {
|
||||
const response = await apiClient.put<ConfigFolder>(
|
||||
`/config-folders/${id}/overrides/${projectId}`,
|
||||
data,
|
||||
);
|
||||
return response.data;
|
||||
};
|
||||
|
||||
export const deleteProjectOverride = async (
|
||||
id: string,
|
||||
projectId: string,
|
||||
): Promise<void> => {
|
||||
await apiClient.delete(`/config-folders/${id}/overrides/${projectId}`);
|
||||
};
|
||||
@@ -1,52 +0,0 @@
|
||||
import { apiClient } from "./client";
|
||||
import type { ToolConfig, CreateToolConfigRequest } from "../types/tool-config";
|
||||
|
||||
export type { ToolConfig, CreateToolConfigRequest } from "../types/tool-config";
|
||||
|
||||
export const listToolConfigs = async (
|
||||
tool_type_id?: string,
|
||||
project_id?: string,
|
||||
): Promise<ToolConfig[]> => {
|
||||
const params = new URLSearchParams();
|
||||
if (tool_type_id) params.append("tool_type_id", tool_type_id);
|
||||
if (project_id) params.append("project_id", project_id);
|
||||
|
||||
const response = await apiClient.get<{ configs: ToolConfig[] }>(
|
||||
`/tool-configs?${params.toString()}`,
|
||||
);
|
||||
return response.data.configs;
|
||||
};
|
||||
|
||||
export const createToolConfig = async (
|
||||
data: CreateToolConfigRequest,
|
||||
): Promise<ToolConfig> => {
|
||||
const response = await apiClient.post<{ configs: ToolConfig[] }>(
|
||||
"/tool-configs",
|
||||
data,
|
||||
);
|
||||
return response.data.configs[0];
|
||||
};
|
||||
|
||||
export const updateToolConfig = async (
|
||||
id: string,
|
||||
data: CreateToolConfigRequest,
|
||||
): Promise<ToolConfig> => {
|
||||
const response = await apiClient.put<{ configs: ToolConfig[] }>(
|
||||
`/tool-configs/${id}`,
|
||||
data,
|
||||
);
|
||||
return response.data.configs[0];
|
||||
};
|
||||
|
||||
export const deleteToolConfig = async (id: string): Promise<void> => {
|
||||
await apiClient.delete(`/tool-configs/${id}`);
|
||||
};
|
||||
|
||||
export const getToolConfigDefaults = async (
|
||||
toolTypeId: string,
|
||||
): Promise<ToolConfig> => {
|
||||
const response = await apiClient.get<ToolConfig>(
|
||||
`/tool-configs/defaults/${toolTypeId}`,
|
||||
);
|
||||
return response.data;
|
||||
};
|
||||
@@ -1,129 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import type { ToolConfig } from "../../../types/tool-config";
|
||||
|
||||
interface ToolConfigFormProps {
|
||||
editingConfig: ToolConfig | null;
|
||||
onSubmit: (data: {
|
||||
key: string;
|
||||
value: string;
|
||||
config_type: string;
|
||||
file_path: string;
|
||||
}) => Promise<void>;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export const ToolConfigForm = ({
|
||||
editingConfig,
|
||||
onSubmit,
|
||||
onCancel,
|
||||
}: ToolConfigFormProps) => {
|
||||
const [formData, setFormData] = useState({
|
||||
key: editingConfig?.key ?? "",
|
||||
value: editingConfig?.value ?? "",
|
||||
config_type: editingConfig?.config_type ?? "env",
|
||||
file_path: editingConfig?.file_path ?? "",
|
||||
});
|
||||
const [saveStatus, setSaveStatus] = useState<
|
||||
"idle" | "saving" | "saved" | "error"
|
||||
>("idle");
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setSaveStatus("saving");
|
||||
try {
|
||||
await onSubmit(formData);
|
||||
setSaveStatus("saved");
|
||||
} catch {
|
||||
setSaveStatus("error");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="card stack">
|
||||
<h3>{editingConfig ? "Edit Config" : "Add Config"}</h3>
|
||||
<form onSubmit={handleSubmit} className="stack">
|
||||
<div>
|
||||
<label htmlFor="config-key">Key</label>
|
||||
<input
|
||||
id="config-key"
|
||||
type="text"
|
||||
value={formData.key}
|
||||
onChange={(e) => setFormData({ ...formData, key: e.target.value })}
|
||||
placeholder="e.g., OPENAI_API_KEY"
|
||||
className="form-input"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="config-type">Type</label>
|
||||
<select
|
||||
id="config-type"
|
||||
value={formData.config_type}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, config_type: e.target.value })
|
||||
}
|
||||
className="form-input"
|
||||
>
|
||||
<option value="env">Environment Variable</option>
|
||||
<option value="file">Configuration File</option>
|
||||
</select>
|
||||
</div>
|
||||
{formData.config_type === "file" && (
|
||||
<div>
|
||||
<label htmlFor="config-file-path">File Path</label>
|
||||
<input
|
||||
id="config-file-path"
|
||||
type="text"
|
||||
value={formData.file_path}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, file_path: e.target.value })
|
||||
}
|
||||
placeholder="e.g., /app/config.json"
|
||||
className="form-input"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label htmlFor="config-value">Value</label>
|
||||
<textarea
|
||||
id="config-value"
|
||||
value={formData.value}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, value: e.target.value })
|
||||
}
|
||||
placeholder={
|
||||
formData.config_type === "env"
|
||||
? "Enter value..."
|
||||
: "Enter file contents..."
|
||||
}
|
||||
className="form-input"
|
||||
rows={formData.config_type === "file" ? 8 : 2}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className="row"
|
||||
style={{ gap: "0.5rem", justifyContent: "flex-end" }}
|
||||
>
|
||||
<button type="button" className="secondary-button" onClick={onCancel}>
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit" className="primary-button">
|
||||
{editingConfig ? "Update" : "Add"} Config
|
||||
</button>
|
||||
</div>
|
||||
{saveStatus === "saved" && (
|
||||
<p className="text-success" style={{ textAlign: "right" }}>
|
||||
Saved successfully!
|
||||
</p>
|
||||
)}
|
||||
{saveStatus === "error" && (
|
||||
<p className="text-error" style={{ textAlign: "right" }}>
|
||||
Failed to save. Please try again.
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,84 +0,0 @@
|
||||
import { Icon } from "../../ui/Icon";
|
||||
import type { ToolConfig } from "../../../types/tool-config";
|
||||
|
||||
interface ToolConfigListProps {
|
||||
configs: ToolConfig[];
|
||||
onEdit: (config: ToolConfig) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}
|
||||
|
||||
export const ToolConfigList = ({
|
||||
configs,
|
||||
onEdit,
|
||||
onDelete,
|
||||
}: ToolConfigListProps) => {
|
||||
if (configs.length === 0) {
|
||||
return <p className="muted">No configurations for this tool yet.</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="stack" style={{ gap: "0.5rem" }}>
|
||||
{configs.map((config) => (
|
||||
<div
|
||||
key={config.id}
|
||||
className="card"
|
||||
style={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
padding: "0.75rem 1rem",
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<div
|
||||
className="row"
|
||||
style={{ gap: "0.5rem", alignItems: "center" }}
|
||||
>
|
||||
<code style={{ fontWeight: 600 }}>{config.key}</code>
|
||||
<span
|
||||
className="badge"
|
||||
style={{
|
||||
fontSize: "0.7rem",
|
||||
textTransform: "uppercase",
|
||||
background:
|
||||
config.config_type === "env"
|
||||
? "var(--color-info)"
|
||||
: "var(--color-warning)",
|
||||
color: "white",
|
||||
padding: "0.125rem 0.5rem",
|
||||
borderRadius: "9999px",
|
||||
}}
|
||||
>
|
||||
{config.config_type}
|
||||
</span>
|
||||
</div>
|
||||
<p
|
||||
className="muted"
|
||||
style={{ marginTop: "0.25rem", fontSize: "0.875rem" }}
|
||||
>
|
||||
{config.config_type === "file" && config.file_path
|
||||
? `File: ${config.file_path}`
|
||||
: "Environment variable"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="row" style={{ gap: "0.5rem" }}>
|
||||
<button
|
||||
className="ghost-button small"
|
||||
onClick={() => onEdit(config)}
|
||||
type="button"
|
||||
>
|
||||
<Icon name="edit" size="sm" />
|
||||
</button>
|
||||
<button
|
||||
className="ghost-button small"
|
||||
onClick={() => void onDelete(config.id)}
|
||||
type="button"
|
||||
>
|
||||
<Icon name="delete" size="sm" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,2 +0,0 @@
|
||||
export { ToolConfigForm } from "./ToolConfigForm";
|
||||
export { ToolConfigList } from "./ToolConfigList";
|
||||
@@ -1,289 +0,0 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Icon } from "../../ui/Icon";
|
||||
import {
|
||||
createConfigFolder,
|
||||
deleteConfigFolder,
|
||||
listConfigFolders,
|
||||
updateConfigFolder,
|
||||
type ConfigFolder,
|
||||
type CreateConfigFolderRequest,
|
||||
type UpdateConfigFolderRequest,
|
||||
} from "../../../api/config-folders";
|
||||
|
||||
export const ConfigFoldersTab = () => {
|
||||
const [folders, setFolders] = useState<ConfigFolder[]>([]);
|
||||
const [status, setStatus] = useState<"loading" | "ready" | "error">(
|
||||
"loading",
|
||||
);
|
||||
const [selectedFolder, setSelectedFolder] = useState<ConfigFolder | null>(
|
||||
null,
|
||||
);
|
||||
const [folderForm, setFolderForm] = useState({
|
||||
name: "",
|
||||
description: "",
|
||||
mount_path: "/home/user",
|
||||
files_json: "{}",
|
||||
is_active: true,
|
||||
});
|
||||
const [folderError, setFolderError] = useState<string | null>(null);
|
||||
const [showFolderForm, setShowFolderForm] = useState(false);
|
||||
|
||||
const loadFolders = useCallback(async () => {
|
||||
setStatus("loading");
|
||||
try {
|
||||
const data = await listConfigFolders();
|
||||
setFolders(data);
|
||||
setStatus("ready");
|
||||
} catch {
|
||||
setStatus("error");
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadFolders();
|
||||
}, [loadFolders]);
|
||||
|
||||
const openCreateFolder = () => {
|
||||
setFolderForm({
|
||||
name: "",
|
||||
description: "",
|
||||
mount_path: "/home/user",
|
||||
files_json: "{}",
|
||||
is_active: true,
|
||||
});
|
||||
setFolderError(null);
|
||||
setShowFolderForm(true);
|
||||
setSelectedFolder(null);
|
||||
};
|
||||
|
||||
const openEditFolder = (folder: ConfigFolder) => {
|
||||
setFolderForm({
|
||||
name: folder.name,
|
||||
description: folder.description || "",
|
||||
mount_path: folder.mount_path,
|
||||
files_json: JSON.stringify(folder.files, null, 2),
|
||||
is_active: folder.is_active,
|
||||
});
|
||||
setFolderError(null);
|
||||
setShowFolderForm(true);
|
||||
setSelectedFolder(folder);
|
||||
};
|
||||
|
||||
const handleFolderSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setFolderError(null);
|
||||
|
||||
if (!folderForm.name.trim() || !folderForm.mount_path.trim()) {
|
||||
setFolderError("Name and mount path are required");
|
||||
return;
|
||||
}
|
||||
|
||||
let files: Record<string, string> | undefined;
|
||||
try {
|
||||
if (
|
||||
folderForm.files_json.trim() &&
|
||||
folderForm.files_json.trim() !== "{}"
|
||||
) {
|
||||
files = JSON.parse(folderForm.files_json);
|
||||
}
|
||||
} catch {
|
||||
setFolderError("Files must be valid JSON object");
|
||||
return;
|
||||
}
|
||||
|
||||
const data: CreateConfigFolderRequest | UpdateConfigFolderRequest = {
|
||||
name: folderForm.name.trim(),
|
||||
description: folderForm.description.trim() || undefined,
|
||||
mount_path: folderForm.mount_path.trim(),
|
||||
files,
|
||||
is_active: folderForm.is_active,
|
||||
};
|
||||
|
||||
try {
|
||||
if (selectedFolder) {
|
||||
await updateConfigFolder(selectedFolder.id, data);
|
||||
} else {
|
||||
await createConfigFolder(data as CreateConfigFolderRequest);
|
||||
}
|
||||
setShowFolderForm(false);
|
||||
setSelectedFolder(null);
|
||||
await loadFolders();
|
||||
} catch (err) {
|
||||
const axiosError = err as { response?: { data?: { detail?: string } } };
|
||||
setFolderError(
|
||||
axiosError?.response?.data?.detail || "Failed to save folder",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteFolder = async (id: string) => {
|
||||
if (!window.confirm("Delete this config folder?")) return;
|
||||
try {
|
||||
await deleteConfigFolder(id);
|
||||
await loadFolders();
|
||||
} catch {
|
||||
alert("Failed to delete folder");
|
||||
}
|
||||
};
|
||||
|
||||
if (status === "loading") {
|
||||
return <p className="muted">Loading Config Folders...</p>;
|
||||
}
|
||||
|
||||
if (status === "error") {
|
||||
return (
|
||||
<div className="card stack">
|
||||
<p className="text-error">Failed to load config folders.</p>
|
||||
<button onClick={() => void loadFolders()}>
|
||||
<Icon name="refresh" size="sm" /> Retry
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
marginBottom: "1rem",
|
||||
}}
|
||||
>
|
||||
<h2>Config Folders</h2>
|
||||
<button onClick={openCreateFolder}>
|
||||
<Icon name="add" size="sm" /> Create Folder
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showFolderForm && (
|
||||
<div className="card stack" style={{ marginBottom: "1rem" }}>
|
||||
<h3>{selectedFolder ? "Edit" : "Create"} Config Folder</h3>
|
||||
<form onSubmit={handleFolderSubmit} className="stack">
|
||||
<div className="form-group">
|
||||
<label htmlFor="folder-name">Name *</label>
|
||||
<input
|
||||
id="folder-name"
|
||||
type="text"
|
||||
value={folderForm.name}
|
||||
onChange={(e) =>
|
||||
setFolderForm({ ...folderForm, name: e.target.value })
|
||||
}
|
||||
placeholder="e.g., my-dotfiles"
|
||||
className="form-input"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="folder-description">Description</label>
|
||||
<input
|
||||
id="folder-description"
|
||||
type="text"
|
||||
value={folderForm.description}
|
||||
onChange={(e) =>
|
||||
setFolderForm({ ...folderForm, description: e.target.value })
|
||||
}
|
||||
placeholder="Optional description"
|
||||
className="form-input"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="folder-mount-path">Mount Path *</label>
|
||||
<input
|
||||
id="folder-mount-path"
|
||||
type="text"
|
||||
value={folderForm.mount_path}
|
||||
onChange={(e) =>
|
||||
setFolderForm({ ...folderForm, mount_path: e.target.value })
|
||||
}
|
||||
placeholder="e.g., /home/user"
|
||||
className="form-input"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="folder-files">Files (JSON object)</label>
|
||||
<textarea
|
||||
id="folder-files"
|
||||
value={folderForm.files_json}
|
||||
onChange={(e) =>
|
||||
setFolderForm({ ...folderForm, files_json: e.target.value })
|
||||
}
|
||||
placeholder='{".zshrc": "export ZSH=...", ".gitconfig": "[user]\\nname = ..."}'
|
||||
className="form-input"
|
||||
rows={8}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label className="checkbox-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={folderForm.is_active}
|
||||
onChange={(e) =>
|
||||
setFolderForm({
|
||||
...folderForm,
|
||||
is_active: e.target.checked,
|
||||
})
|
||||
}
|
||||
/>
|
||||
Active (mount into new instances)
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{folderError && <p className="text-error">{folderError}</p>}
|
||||
|
||||
<div className="dialog-actions">
|
||||
<button type="submit">
|
||||
{selectedFolder ? "Update" : "Create"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowFolderForm(false)}
|
||||
className="button-secondary"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="card-grid">
|
||||
{folders.map((folder) => (
|
||||
<div key={folder.id} className="card">
|
||||
<div className="card-header">
|
||||
<h3>{folder.name}</h3>
|
||||
{folder.is_active && <span className="badge">Active</span>}
|
||||
</div>
|
||||
<p className="text-secondary">
|
||||
{folder.description || "No description"}
|
||||
</p>
|
||||
<div className="tool-type-meta">
|
||||
<span>Mount: {folder.mount_path}</span>
|
||||
<span>Files: {Object.keys(folder.files || {}).length}</span>
|
||||
</div>
|
||||
<div className="card-actions">
|
||||
<button
|
||||
onClick={() => openEditFolder(folder)}
|
||||
className="button-secondary"
|
||||
>
|
||||
<Icon name="edit" size="sm" /> Edit
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDeleteFolder(folder.id)}
|
||||
className="button-danger"
|
||||
>
|
||||
<Icon name="delete" size="sm" /> Delete
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,460 +0,0 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Icon } from "../../ui/Icon";
|
||||
import {
|
||||
createToolConfig,
|
||||
deleteToolConfig,
|
||||
listToolConfigs,
|
||||
updateToolConfig,
|
||||
type CreateToolConfigRequest,
|
||||
type ToolConfig,
|
||||
} from "../../../api/tool-configs";
|
||||
import { listToolTypes, type ToolType } from "../../../api/tool-types";
|
||||
|
||||
export const ToolConfigsTab = () => {
|
||||
const [configs, setConfigs] = useState<ToolConfig[]>([]);
|
||||
const [toolTypes, setToolTypes] = useState<ToolType[]>([]);
|
||||
const [status, setStatus] = useState<"loading" | "ready" | "error">(
|
||||
"loading",
|
||||
);
|
||||
const [selectedConfig, setSelectedConfig] = useState<ToolConfig | null>(null);
|
||||
const [configForm, setConfigForm] = useState({
|
||||
tool_type_id: "",
|
||||
key: "",
|
||||
value: "",
|
||||
config_type: "env",
|
||||
file_path: "",
|
||||
port_override: "",
|
||||
start_command: "",
|
||||
working_directory: "",
|
||||
env_vars_json: "{}",
|
||||
volumes_json: "[]",
|
||||
});
|
||||
const [configError, setConfigError] = useState<string | null>(null);
|
||||
const [showConfigForm, setShowConfigForm] = useState(false);
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
setStatus("loading");
|
||||
try {
|
||||
const [cfgs, types] = await Promise.all([
|
||||
listToolConfigs(),
|
||||
listToolTypes(),
|
||||
]);
|
||||
setConfigs(cfgs);
|
||||
setToolTypes(types);
|
||||
setStatus("ready");
|
||||
} catch {
|
||||
setStatus("error");
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadData();
|
||||
}, [loadData]);
|
||||
|
||||
const openCreateConfig = () => {
|
||||
setConfigForm({
|
||||
tool_type_id: toolTypes[0]?.id || "",
|
||||
key: "",
|
||||
value: "",
|
||||
config_type: "env",
|
||||
file_path: "",
|
||||
port_override: "",
|
||||
start_command: "",
|
||||
working_directory: "",
|
||||
env_vars_json: "{}",
|
||||
volumes_json: "[]",
|
||||
});
|
||||
setConfigError(null);
|
||||
setShowConfigForm(true);
|
||||
setSelectedConfig(null);
|
||||
};
|
||||
|
||||
const openEditConfig = (config: ToolConfig) => {
|
||||
setConfigForm({
|
||||
tool_type_id: config.tool_type_id,
|
||||
key: config.key,
|
||||
value: config.value,
|
||||
config_type: config.config_type,
|
||||
file_path: config.file_path || "",
|
||||
port_override: config.port_override?.toString() || "",
|
||||
start_command: config.start_command || "",
|
||||
working_directory: config.working_directory || "",
|
||||
env_vars_json: config.environment_variables
|
||||
? JSON.stringify(config.environment_variables, null, 2)
|
||||
: "{}",
|
||||
volumes_json: config.volumes
|
||||
? JSON.stringify(config.volumes, null, 2)
|
||||
: "[]",
|
||||
});
|
||||
setConfigError(null);
|
||||
setShowConfigForm(true);
|
||||
setSelectedConfig(config);
|
||||
};
|
||||
|
||||
const handleConfigSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setConfigError(null);
|
||||
|
||||
if (!configForm.tool_type_id || !configForm.key.trim()) {
|
||||
setConfigError("Tool type and key are required");
|
||||
return;
|
||||
}
|
||||
|
||||
let envVars: Record<string, string> | undefined;
|
||||
let volumes:
|
||||
| Array<{ source: string; target: string; type?: string }>
|
||||
| undefined;
|
||||
|
||||
try {
|
||||
if (
|
||||
configForm.env_vars_json.trim() &&
|
||||
configForm.env_vars_json.trim() !== "{}"
|
||||
) {
|
||||
envVars = JSON.parse(configForm.env_vars_json);
|
||||
}
|
||||
} catch {
|
||||
setConfigError("Environment variables must be valid JSON");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (
|
||||
configForm.volumes_json.trim() &&
|
||||
configForm.volumes_json.trim() !== "[]"
|
||||
) {
|
||||
volumes = JSON.parse(configForm.volumes_json);
|
||||
}
|
||||
} catch {
|
||||
setConfigError("Volumes must be valid JSON array");
|
||||
return;
|
||||
}
|
||||
|
||||
const data: CreateToolConfigRequest = {
|
||||
tool_type_id: configForm.tool_type_id,
|
||||
key: configForm.key.trim(),
|
||||
value: configForm.value,
|
||||
config_type: configForm.config_type,
|
||||
file_path:
|
||||
configForm.config_type === "file" ? configForm.file_path : undefined,
|
||||
port_override: configForm.port_override
|
||||
? Number(configForm.port_override)
|
||||
: undefined,
|
||||
start_command: configForm.start_command.trim() || undefined,
|
||||
working_directory: configForm.working_directory.trim() || undefined,
|
||||
environment_variables: envVars,
|
||||
volumes,
|
||||
};
|
||||
|
||||
try {
|
||||
if (selectedConfig) {
|
||||
await updateToolConfig(selectedConfig.id, data);
|
||||
} else {
|
||||
await createToolConfig(data);
|
||||
}
|
||||
setShowConfigForm(false);
|
||||
setSelectedConfig(null);
|
||||
await loadData();
|
||||
} catch (err) {
|
||||
const axiosError = err as { response?: { data?: { detail?: string } } };
|
||||
setConfigError(
|
||||
axiosError?.response?.data?.detail || "Failed to save config",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteConfig = async (id: string) => {
|
||||
if (!window.confirm("Delete this config?")) return;
|
||||
try {
|
||||
await deleteToolConfig(id);
|
||||
await loadData();
|
||||
} catch {
|
||||
alert("Failed to delete config");
|
||||
}
|
||||
};
|
||||
|
||||
if (status === "loading") {
|
||||
return <p className="muted">Loading Configurations...</p>;
|
||||
}
|
||||
|
||||
if (status === "error") {
|
||||
return (
|
||||
<div className="card stack">
|
||||
<p className="text-error">Failed to load configurations.</p>
|
||||
<button onClick={() => void loadData()}>
|
||||
<Icon name="refresh" size="sm" /> Retry
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
marginBottom: "1rem",
|
||||
}}
|
||||
>
|
||||
<h2>Tool Configurations</h2>
|
||||
<button onClick={openCreateConfig}>
|
||||
<Icon name="add" size="sm" /> Add Config
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showConfigForm && (
|
||||
<div className="card stack" style={{ marginBottom: "1rem" }}>
|
||||
<h3>{selectedConfig ? "Edit" : "Add"} Config</h3>
|
||||
<form onSubmit={handleConfigSubmit} className="stack">
|
||||
<div className="form-group">
|
||||
<label htmlFor="config-tool-type">Tool Type *</label>
|
||||
<select
|
||||
id="config-tool-type"
|
||||
value={configForm.tool_type_id}
|
||||
onChange={(e) =>
|
||||
setConfigForm({ ...configForm, tool_type_id: e.target.value })
|
||||
}
|
||||
className="form-input"
|
||||
required
|
||||
>
|
||||
<option value="">Select a tool type...</option>
|
||||
{toolTypes.map((tt) => (
|
||||
<option key={tt.id} value={tt.id}>
|
||||
{tt.display_name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="config-key">Key *</label>
|
||||
<input
|
||||
id="config-key"
|
||||
type="text"
|
||||
value={configForm.key}
|
||||
onChange={(e) =>
|
||||
setConfigForm({ ...configForm, key: e.target.value })
|
||||
}
|
||||
placeholder="e.g., OPENAI_API_KEY"
|
||||
className="form-input"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="config-type">Config Type</label>
|
||||
<select
|
||||
id="config-type"
|
||||
value={configForm.config_type}
|
||||
onChange={(e) =>
|
||||
setConfigForm({ ...configForm, config_type: e.target.value })
|
||||
}
|
||||
className="form-input"
|
||||
>
|
||||
<option value="env">Environment Variable</option>
|
||||
<option value="file">Configuration File</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{configForm.config_type === "file" && (
|
||||
<div className="form-group">
|
||||
<label>File Path</label>
|
||||
<input
|
||||
type="text"
|
||||
value={configForm.file_path}
|
||||
onChange={(e) =>
|
||||
setConfigForm({ ...configForm, file_path: e.target.value })
|
||||
}
|
||||
placeholder="e.g., /app/config.json"
|
||||
className="form-input"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="config-value">Value</label>
|
||||
<textarea
|
||||
id="config-value"
|
||||
value={configForm.value}
|
||||
onChange={(e) =>
|
||||
setConfigForm({ ...configForm, value: e.target.value })
|
||||
}
|
||||
placeholder={
|
||||
configForm.config_type === "env"
|
||||
? "Enter value..."
|
||||
: "Enter file contents..."
|
||||
}
|
||||
className="form-input"
|
||||
rows={configForm.config_type === "file" ? 8 : 2}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="row" style={{ gap: "1rem" }}>
|
||||
<div className="form-group" style={{ flex: 1 }}>
|
||||
<label htmlFor="config-port-override">Port Override</label>
|
||||
<input
|
||||
id="config-port-override"
|
||||
type="number"
|
||||
value={configForm.port_override}
|
||||
onChange={(e) =>
|
||||
setConfigForm({
|
||||
...configForm,
|
||||
port_override: e.target.value,
|
||||
})
|
||||
}
|
||||
placeholder="e.g., 8080"
|
||||
className="form-input"
|
||||
/>
|
||||
</div>
|
||||
<div className="form-group" style={{ flex: 1 }}>
|
||||
<label htmlFor="config-start-command">Start Command</label>
|
||||
<input
|
||||
id="config-start-command"
|
||||
type="text"
|
||||
value={configForm.start_command}
|
||||
onChange={(e) =>
|
||||
setConfigForm({
|
||||
...configForm,
|
||||
start_command: e.target.value,
|
||||
})
|
||||
}
|
||||
placeholder="e.g., npm start"
|
||||
className="form-input"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Working Directory</label>
|
||||
<input
|
||||
type="text"
|
||||
value={configForm.working_directory}
|
||||
onChange={(e) =>
|
||||
setConfigForm({
|
||||
...configForm,
|
||||
working_directory: e.target.value,
|
||||
})
|
||||
}
|
||||
placeholder="e.g., /workspace"
|
||||
className="form-input"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Environment Variables (JSON)</label>
|
||||
<textarea
|
||||
value={configForm.env_vars_json}
|
||||
onChange={(e) =>
|
||||
setConfigForm({
|
||||
...configForm,
|
||||
env_vars_json: e.target.value,
|
||||
})
|
||||
}
|
||||
placeholder='{"KEY": "value"}'
|
||||
className="form-input"
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Volumes (JSON array)</label>
|
||||
<textarea
|
||||
value={configForm.volumes_json}
|
||||
onChange={(e) =>
|
||||
setConfigForm({ ...configForm, volumes_json: e.target.value })
|
||||
}
|
||||
placeholder='[{"source": "/host", "target": "/container"}]'
|
||||
className="form-input"
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{configError && <p className="text-error">{configError}</p>}
|
||||
|
||||
<div className="dialog-actions">
|
||||
<button type="submit">{selectedConfig ? "Update" : "Add"}</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowConfigForm(false)}
|
||||
className="button-secondary"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="stack" style={{ gap: "0.5rem" }}>
|
||||
{configs.length === 0 ? (
|
||||
<p className="muted">No configurations yet.</p>
|
||||
) : (
|
||||
configs.map((config) => (
|
||||
<div
|
||||
key={config.id}
|
||||
className="card"
|
||||
style={{
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
padding: "0.75rem 1rem",
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<div
|
||||
className="row"
|
||||
style={{ gap: "0.5rem", alignItems: "center" }}
|
||||
>
|
||||
<code style={{ fontWeight: 600 }}>{config.key}</code>
|
||||
<span
|
||||
className="badge"
|
||||
style={{
|
||||
fontSize: "0.7rem",
|
||||
textTransform: "uppercase",
|
||||
background:
|
||||
config.config_type === "env"
|
||||
? "var(--color-info)"
|
||||
: "var(--color-warning)",
|
||||
color: "white",
|
||||
padding: "0.125rem 0.5rem",
|
||||
borderRadius: "9999px",
|
||||
}}
|
||||
>
|
||||
{config.config_type}
|
||||
</span>
|
||||
</div>
|
||||
<p
|
||||
className="muted"
|
||||
style={{ marginTop: "0.25rem", fontSize: "0.875rem" }}
|
||||
>
|
||||
{config.config_type === "file" && config.file_path
|
||||
? `File: ${config.file_path}`
|
||||
: "Environment variable"}
|
||||
{config.port_override && ` · Port: ${config.port_override}`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="row" style={{ gap: "0.5rem" }}>
|
||||
<button
|
||||
className="ghost-button small"
|
||||
onClick={() => openEditConfig(config)}
|
||||
type="button"
|
||||
>
|
||||
<Icon name="edit" size="sm" />
|
||||
</button>
|
||||
<button
|
||||
className="ghost-button small"
|
||||
onClick={() => handleDeleteConfig(config.id)}
|
||||
type="button"
|
||||
>
|
||||
<Icon name="delete" size="sm" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -196,7 +196,7 @@ export const ToolTypesTab = () => {
|
||||
const handleDeleteToolType = async (id: string) => {
|
||||
if (
|
||||
!window.confirm(
|
||||
"Delete this tool type? All associated configs will be removed.",
|
||||
"Delete this tool type? Existing instances using it may be affected.",
|
||||
)
|
||||
)
|
||||
return;
|
||||
@@ -327,33 +327,22 @@ export const ToolTypesTab = () => {
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Interfaces</label>
|
||||
<div className="checkbox-group">
|
||||
{["web", "terminal"].map((iface) => (
|
||||
<label key={iface} className="checkbox-label">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={toolTypeForm.interfaces.includes(iface)}
|
||||
onChange={(e) => {
|
||||
if (e.target.checked) {
|
||||
setToolTypeForm({
|
||||
...toolTypeForm,
|
||||
interfaces: [...toolTypeForm.interfaces, iface],
|
||||
});
|
||||
} else {
|
||||
setToolTypeForm({
|
||||
...toolTypeForm,
|
||||
interfaces: toolTypeForm.interfaces.filter(
|
||||
(i) => i !== iface,
|
||||
),
|
||||
});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{iface}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<label htmlFor="tool-type-interface">Interface</label>
|
||||
<select
|
||||
id="tool-type-interface"
|
||||
value={toolTypeForm.interfaces[0] ?? ""}
|
||||
onChange={(e) =>
|
||||
setToolTypeForm({
|
||||
...toolTypeForm,
|
||||
interfaces: e.target.value ? [e.target.value] : [],
|
||||
})
|
||||
}
|
||||
className="form-input"
|
||||
>
|
||||
<option value="">Select interface</option>
|
||||
<option value="web">web</option>
|
||||
<option value="terminal">terminal</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
|
||||
@@ -1,3 +1 @@
|
||||
export { ToolTypesTab } from "./ToolTypesTab";
|
||||
export { ToolConfigsTab } from "./ToolConfigsTab";
|
||||
export { ConfigFoldersTab } from "./ConfigFoldersTab";
|
||||
|
||||
@@ -10,7 +10,6 @@ const TABS = [
|
||||
{ label: "General", path: "general" },
|
||||
{ label: "SSH Keys", path: "ssh-keys" },
|
||||
{ label: "Tool Types", path: "tool-types" },
|
||||
{ label: "Tool Configs", path: "tool-configs" },
|
||||
] as const;
|
||||
|
||||
const THEME_OPTIONS = [
|
||||
@@ -106,7 +105,7 @@ export const SettingsPage = () => {
|
||||
<p className="eyebrow">Configuration</p>
|
||||
<h1>Settings</h1>
|
||||
</div>
|
||||
<p className="muted">General preferences, SSH keys, tool types, and tool configs live here.</p>
|
||||
<p className="muted">General preferences, SSH keys, and tool types live here.</p>
|
||||
</header>
|
||||
|
||||
<nav className="settings-tabs" aria-label="Settings sections">
|
||||
|
||||
@@ -1,205 +0,0 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
import { Icon } from "../components/ui/Icon";
|
||||
import type { ToolType } from "../types/tool-type";
|
||||
import type { ToolConfig } from "../types/tool-config";
|
||||
import { listToolTypes } from "../api/tool-types";
|
||||
import {
|
||||
createToolConfig,
|
||||
deleteToolConfig,
|
||||
listToolConfigs,
|
||||
updateToolConfig,
|
||||
} from "../api/tool-configs";
|
||||
import {
|
||||
ToolConfigForm,
|
||||
ToolConfigList,
|
||||
} from "../components/features/tool-configs";
|
||||
|
||||
type ConfigStatus = "loading" | "ready" | "error";
|
||||
|
||||
export const ToolConfigsPage = () => {
|
||||
const navigate = useNavigate();
|
||||
const [status, setStatus] = useState<ConfigStatus>("loading");
|
||||
const [toolTypes, setToolTypes] = useState<ToolType[]>([]);
|
||||
const [configs, setConfigs] = useState<ToolConfig[]>([]);
|
||||
const [selectedToolType, setSelectedToolType] = useState<string>("");
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
const [editingConfig, setEditingConfig] = useState<ToolConfig | null>(null);
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
try {
|
||||
const [typesData, configsData] = await Promise.all([
|
||||
listToolTypes(),
|
||||
listToolConfigs(),
|
||||
]);
|
||||
setToolTypes(typesData);
|
||||
setConfigs(configsData);
|
||||
if (typesData.length > 0 && !selectedToolType) {
|
||||
setSelectedToolType(typesData[0].id);
|
||||
}
|
||||
setStatus("ready");
|
||||
} catch {
|
||||
setStatus("error");
|
||||
}
|
||||
}, [selectedToolType]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadData();
|
||||
}, [loadData]);
|
||||
|
||||
const handleSubmit = async (data: {
|
||||
key: string;
|
||||
value: string;
|
||||
config_type: string;
|
||||
file_path: string;
|
||||
}) => {
|
||||
const payload = {
|
||||
tool_type_id: selectedToolType,
|
||||
key: data.key,
|
||||
value: data.value,
|
||||
config_type: data.config_type,
|
||||
file_path: data.config_type === "file" ? data.file_path : undefined,
|
||||
};
|
||||
|
||||
if (editingConfig) {
|
||||
await updateToolConfig(editingConfig.id, payload);
|
||||
} else {
|
||||
await createToolConfig(payload);
|
||||
}
|
||||
setShowForm(false);
|
||||
setEditingConfig(null);
|
||||
await loadData();
|
||||
};
|
||||
|
||||
const handleEdit = (config: ToolConfig) => {
|
||||
setEditingConfig(config);
|
||||
setSelectedToolType(config.tool_type_id);
|
||||
setShowForm(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (!window.confirm("Delete this config?")) return;
|
||||
try {
|
||||
await deleteToolConfig(id);
|
||||
await loadData();
|
||||
} catch {
|
||||
// Error handled by UI state
|
||||
}
|
||||
};
|
||||
|
||||
const selectedTool = toolTypes.find((t) => t.id === selectedToolType);
|
||||
const filteredConfigs = configs.filter(
|
||||
(c) => c.tool_type_id === selectedToolType,
|
||||
);
|
||||
|
||||
if (status === "loading") {
|
||||
return (
|
||||
<section className="stack">
|
||||
<div className="page-header">
|
||||
<h1>Tool Configurations</h1>
|
||||
</div>
|
||||
<p className="muted">Loading...</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
if (status === "error") {
|
||||
return (
|
||||
<section className="stack">
|
||||
<div className="page-header">
|
||||
<h1>Tool Configurations</h1>
|
||||
</div>
|
||||
<div className="card stack">
|
||||
<p>Failed to load configurations</p>
|
||||
<button
|
||||
className="secondary-button"
|
||||
onClick={() => void loadData()}
|
||||
type="button"
|
||||
>
|
||||
<Icon name="refresh" size="sm" /> Retry
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="stack">
|
||||
<div className="page-header">
|
||||
<div>
|
||||
<p className="eyebrow">Settings</p>
|
||||
<h1>Tool Configurations</h1>
|
||||
</div>
|
||||
<button
|
||||
className="secondary-button"
|
||||
type="button"
|
||||
onClick={() => navigate("/settings")}
|
||||
>
|
||||
Back to settings
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<label htmlFor="tool-type-select">Select Tool</label>
|
||||
<select
|
||||
id="tool-type-select"
|
||||
value={selectedToolType}
|
||||
onChange={(e) => {
|
||||
setSelectedToolType(e.target.value);
|
||||
setShowForm(false);
|
||||
setEditingConfig(null);
|
||||
}}
|
||||
className="form-input"
|
||||
>
|
||||
{toolTypes.map((tool) => (
|
||||
<option key={tool.id} value={tool.id}>
|
||||
{tool.display_name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{selectedTool && (
|
||||
<p className="muted" style={{ marginTop: "0.5rem" }}>
|
||||
Category: {selectedTool.category} · Interfaces:{" "}
|
||||
{selectedTool.interfaces?.join(", ")}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="card stack">
|
||||
<div
|
||||
className="row"
|
||||
style={{ justifyContent: "space-between", alignItems: "center" }}
|
||||
>
|
||||
<h2>Configuration Variables</h2>
|
||||
<button
|
||||
className="primary-button small"
|
||||
onClick={() => {
|
||||
setShowForm(true);
|
||||
setEditingConfig(null);
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
<Icon name="add" size="sm" /> Add Config
|
||||
</button>
|
||||
</div>
|
||||
<ToolConfigList
|
||||
configs={filteredConfigs}
|
||||
onEdit={handleEdit}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{showForm && (
|
||||
<ToolConfigForm
|
||||
editingConfig={editingConfig}
|
||||
onSubmit={handleSubmit}
|
||||
onCancel={() => {
|
||||
setShowForm(false);
|
||||
setEditingConfig(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
};
|
||||
@@ -1,527 +1,99 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ToolWorkshopPage } from "./ToolWorkshopPage";
|
||||
import * as toolTypesApi from "../api/tool-types";
|
||||
import * as toolConfigsApi from "../api/tool-configs";
|
||||
import * as configFoldersApi from "../api/config-folders";
|
||||
import { ToolWorkshopPage } from "./ToolWorkshopPage";
|
||||
|
||||
const mockToolTypes = [
|
||||
{
|
||||
id: "type-1",
|
||||
name: "code-server",
|
||||
display_name: "VS Code Server",
|
||||
description: "VS Code in browser",
|
||||
category: "editor",
|
||||
interfaces: ["web"],
|
||||
default_port: 8443,
|
||||
definition_type: "compose",
|
||||
compose_template: "version: '3.8'\\nservices:\\n app:\\n image: codercom/code-server",
|
||||
dockerfile_template: null,
|
||||
build_context: null,
|
||||
readiness_probe: null,
|
||||
required_variables: ["REPO_PATH"],
|
||||
is_builtin: true,
|
||||
created_by_id: null,
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
},
|
||||
{
|
||||
id: "type-2",
|
||||
name: "custom-tool",
|
||||
display_name: "Custom Tool",
|
||||
description: "My custom tool",
|
||||
category: "utility",
|
||||
interfaces: ["terminal"],
|
||||
default_port: 8080,
|
||||
definition_type: "dockerfile",
|
||||
compose_template: null,
|
||||
dockerfile_template: "FROM python:3.11",
|
||||
build_context: null,
|
||||
readiness_probe: {
|
||||
command: "python --version",
|
||||
timeout: 30,
|
||||
interval: 2,
|
||||
},
|
||||
required_variables: [],
|
||||
is_builtin: false,
|
||||
created_by_id: "user-1",
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
},
|
||||
];
|
||||
|
||||
const mockConfigs = [
|
||||
{
|
||||
id: "config-1",
|
||||
tool_type_id: "type-1",
|
||||
project_id: null,
|
||||
key: "OPENAI_API_KEY",
|
||||
value: "sk-test123",
|
||||
config_type: "env",
|
||||
file_path: null,
|
||||
port_override: null,
|
||||
start_command: null,
|
||||
working_directory: null,
|
||||
environment_variables: {},
|
||||
volumes: [],
|
||||
},
|
||||
{
|
||||
id: "config-2",
|
||||
tool_type_id: "type-2",
|
||||
project_id: null,
|
||||
key: "advanced-config",
|
||||
value: "test-value",
|
||||
config_type: "env",
|
||||
file_path: null,
|
||||
port_override: 9090,
|
||||
start_command: "python app.py",
|
||||
working_directory: "/app",
|
||||
environment_variables: { DEBUG: "true" },
|
||||
volumes: [{ source: "data", target: "/data", type: "bind" }],
|
||||
},
|
||||
];
|
||||
|
||||
const mockFolders = [
|
||||
{
|
||||
id: "folder-1",
|
||||
user_id: "user-1",
|
||||
name: "my-dotfiles",
|
||||
description: "My personal config files",
|
||||
mount_path: "/home/user",
|
||||
files: { ".zshrc": "export ZSH=\"$HOME/.oh-my-zsh\"" },
|
||||
project_overrides: {},
|
||||
is_active: true,
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
},
|
||||
{
|
||||
id: "folder-2",
|
||||
user_id: "user-1",
|
||||
name: "project-configs",
|
||||
description: "Project specific configs",
|
||||
mount_path: "/workspace",
|
||||
files: { ".env": "API_URL=http://localhost:8080" },
|
||||
project_overrides: {
|
||||
"proj-1": {
|
||||
mount_path: "/app",
|
||||
files: { ".env": "API_URL=http://prod.api" },
|
||||
},
|
||||
},
|
||||
is_active: false,
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
},
|
||||
{
|
||||
id: "type-1",
|
||||
name: "code-server",
|
||||
display_name: "VS Code Server",
|
||||
description: "VS Code in browser",
|
||||
category: "editor",
|
||||
interfaces: ["web"],
|
||||
default_port: 8443,
|
||||
definition_type: "compose",
|
||||
compose_template: "version: '3.8'\nservices:\n app:\n image: codercom/code-server",
|
||||
dockerfile_template: null,
|
||||
build_context: null,
|
||||
readiness_probe: null,
|
||||
required_variables: ["REPO_PATH"],
|
||||
is_builtin: true,
|
||||
created_by_id: null,
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
},
|
||||
{
|
||||
id: "type-2",
|
||||
name: "custom-tool",
|
||||
display_name: "Custom Tool",
|
||||
description: "My custom tool",
|
||||
category: "utility",
|
||||
interfaces: ["terminal"],
|
||||
default_port: 8080,
|
||||
definition_type: "dockerfile",
|
||||
compose_template: null,
|
||||
dockerfile_template: "FROM python:3.11",
|
||||
build_context: null,
|
||||
readiness_probe: {
|
||||
command: "python --version",
|
||||
timeout: 30,
|
||||
interval: 2,
|
||||
},
|
||||
required_variables: [],
|
||||
is_builtin: false,
|
||||
created_by_id: "user-1",
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
},
|
||||
];
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("ToolWorkshopPage", () => {
|
||||
it("renders loading state initially", () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockImplementation(() => new Promise(() => {}));
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockImplementation(() => new Promise(() => {}));
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockImplementation(() => new Promise(() => {}));
|
||||
it("renders loading state initially", () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockImplementation(
|
||||
() => new Promise(() => {}),
|
||||
);
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
expect(screen.getByText(/loading/i)).toBeInTheDocument();
|
||||
});
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
it("renders tool types tab by default", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockResolvedValue(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockResolvedValue(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
expect(screen.getByText(/loading tool types/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
it("renders tool types", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(
|
||||
mockToolTypes as unknown as toolTypesApi.ToolType[],
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText("Custom Tool")).toBeInTheDocument();
|
||||
});
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
it("switches to configs tab", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockResolvedValue(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockResolvedValue(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText("Custom Tool")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /configs/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /folders/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
it("opens tool type creation form", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(
|
||||
mockToolTypes as unknown as toolTypesApi.ToolType[],
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /configs/i }));
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("OPENAI_API_KEY")).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText("advanced-config")).toBeInTheDocument();
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: /create tool type/i }));
|
||||
|
||||
it("switches to folders tab", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockResolvedValue(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockResolvedValue(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /folders/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("my-dotfiles")).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText("project-configs")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens tool type creation form", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockResolvedValue(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockResolvedValue(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /create tool type/i }));
|
||||
|
||||
expect(screen.getByLabelText("Name *")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Display Name *")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("creates tool type with compose definition", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
const createMock = vi.spyOn(toolTypesApi, "createToolType").mockResolvedValue(mockToolTypes[1] as unknown as toolTypesApi.ToolType);
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockResolvedValue(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockResolvedValue(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /create tool type/i }));
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Name *"), {
|
||||
target: { value: "new-tool" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Display Name *"), {
|
||||
target: { value: "New Tool" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Default Port *"), {
|
||||
target: { value: "8080" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText(/compose template/i), {
|
||||
target: { value: "version: '3.8'\\nservices:\\n app:\\n image: nginx" },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /create$/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(createMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: "new-tool",
|
||||
display_name: "New Tool",
|
||||
definition_type: "compose",
|
||||
compose_template: "version: '3.8'\\nservices:\\n app:\\n image: nginx",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("creates tool type with dockerfile definition", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
const createMock = vi.spyOn(toolTypesApi, "createToolType").mockResolvedValue(mockToolTypes[1] as unknown as toolTypesApi.ToolType);
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockResolvedValue(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockResolvedValue(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /create tool type/i }));
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Name *"), {
|
||||
target: { value: "docker-tool" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Display Name *"), {
|
||||
target: { value: "Docker Tool" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Default Port *"), {
|
||||
target: { value: "3000" },
|
||||
});
|
||||
|
||||
// Switch to dockerfile
|
||||
fireEvent.change(screen.getByLabelText("Definition Type"), {
|
||||
target: { value: "dockerfile" },
|
||||
});
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Dockerfile *"), {
|
||||
target: { value: "FROM python:3.11\\nRUN pip install flask" },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /create$/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(createMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: "docker-tool",
|
||||
definition_type: "dockerfile",
|
||||
dockerfile_template: "FROM python:3.11\\nRUN pip install flask",
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("shows readiness probe fields", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockResolvedValue(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockResolvedValue(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /create tool type/i }));
|
||||
|
||||
expect(screen.getByText(/readiness probe command/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/timeout/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/interval/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens config creation form", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockResolvedValue(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockResolvedValue(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /configs/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("OPENAI_API_KEY")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /add config/i }));
|
||||
|
||||
expect(screen.getByLabelText(/key/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/value/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("creates config with advanced fields", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
const configsListMock = vi.spyOn(toolConfigsApi, "listToolConfigs").mockResolvedValue(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
const createMock = vi.spyOn(toolConfigsApi, "createToolConfig").mockResolvedValue(mockConfigs[1] as unknown as toolConfigsApi.ToolConfig);
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockResolvedValue(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /configs/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("OPENAI_API_KEY")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /add config/i }));
|
||||
|
||||
fireEvent.change(screen.getByLabelText(/key/i), {
|
||||
target: { value: "MY_CONFIG" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText(/value/i), {
|
||||
target: { value: "my-value" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText(/port override/i), {
|
||||
target: { value: "9090" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText(/start command/i), {
|
||||
target: { value: "python app.py" },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /add$/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(createMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
key: "MY_CONFIG",
|
||||
value: "my-value",
|
||||
port_override: 9090,
|
||||
start_command: "python app.py",
|
||||
})
|
||||
);
|
||||
});
|
||||
expect(configsListMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("opens folder creation form", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockResolvedValue(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockResolvedValue(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /folders/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("my-dotfiles")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /create folder/i }));
|
||||
|
||||
expect(screen.getByLabelText("Name *")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Mount Path *")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("creates config folder successfully", async () => {
|
||||
const foldersListMock = vi.spyOn(configFoldersApi, "listConfigFolders").mockResolvedValue(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
const createMock = vi.spyOn(configFoldersApi, "createConfigFolder").mockResolvedValue(mockFolders[0] as unknown as configFoldersApi.ConfigFolder);
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockResolvedValue(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /folders/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("my-dotfiles")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /create folder/i }));
|
||||
|
||||
fireEvent.change(screen.getByLabelText("Name *"), {
|
||||
target: { value: "new-folder" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("Mount Path *"), {
|
||||
target: { value: "/home/dev" },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /create$/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(createMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: "new-folder",
|
||||
mount_path: "/home/dev",
|
||||
})
|
||||
);
|
||||
});
|
||||
expect(foldersListMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("shows folder active/inactive status", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockResolvedValue(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockResolvedValue(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /folders/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("my-dotfiles")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Check that active folder shows Active badge
|
||||
expect(screen.getByText("Active")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("handles error state gracefully", async () => {
|
||||
vi.spyOn(toolTypesApi, "listToolTypes").mockRejectedValue(new Error("Network error"));
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockRejectedValue(new Error("Network error"));
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockRejectedValue(new Error("Network error"));
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/failed to load/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(screen.getByRole("button", { name: /retry/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("retries loading after error", async () => {
|
||||
const listMock = vi.spyOn(toolTypesApi, "listToolTypes")
|
||||
.mockRejectedValueOnce(new Error("Network error"))
|
||||
.mockResolvedValueOnce(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs")
|
||||
.mockRejectedValueOnce(new Error("Network error"))
|
||||
.mockResolvedValueOnce(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders")
|
||||
.mockRejectedValueOnce(new Error("Network error"))
|
||||
.mockResolvedValueOnce(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/failed to load/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /retry/i }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("VS Code Server")).toBeInTheDocument();
|
||||
});
|
||||
expect(listMock).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("deletes tool type successfully", async () => {
|
||||
const listMock = vi.spyOn(toolTypesApi, "listToolTypes").mockResolvedValue(mockToolTypes as unknown as toolTypesApi.ToolType[]);
|
||||
const deleteMock = vi.spyOn(toolTypesApi, "deleteToolType").mockResolvedValue(undefined);
|
||||
vi.spyOn(toolConfigsApi, "listToolConfigs").mockResolvedValue(mockConfigs as unknown as toolConfigsApi.ToolConfig[]);
|
||||
vi.spyOn(configFoldersApi, "listConfigFolders").mockResolvedValue(mockFolders as unknown as configFoldersApi.ConfigFolder[]);
|
||||
|
||||
render(<ToolWorkshopPage />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Custom Tool")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Find and click delete button for custom tool (not built-in)
|
||||
const customToolCard = screen.getByText("Custom Tool").closest(".card") ||
|
||||
screen.getByText("Custom Tool").parentElement;
|
||||
if (customToolCard) {
|
||||
const deleteButton = within(customToolCard as HTMLElement).queryByRole("button", { name: /delete/i });
|
||||
if (deleteButton) {
|
||||
vi.spyOn(window, "confirm").mockReturnValue(true);
|
||||
fireEvent.click(deleteButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(deleteMock).toHaveBeenCalledWith("type-2");
|
||||
});
|
||||
expect(listMock).toHaveBeenCalledTimes(2);
|
||||
}
|
||||
}
|
||||
});
|
||||
expect(screen.getByLabelText("Name *")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Display Name *")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,16 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import { Icon } from "../components/ui";
|
||||
import {
|
||||
ToolTypesTab,
|
||||
ToolConfigsTab,
|
||||
ConfigFoldersTab,
|
||||
} from "../components/features/tool-workshop";
|
||||
|
||||
type Tab = "types" | "configs" | "folders";
|
||||
import { ToolTypesTab } from "../components/features/tool-workshop";
|
||||
|
||||
export const ToolWorkshopPage = () => {
|
||||
const [activeTab, setActiveTab] = useState<Tab>("types");
|
||||
|
||||
return (
|
||||
<div className="container">
|
||||
<div
|
||||
@@ -24,54 +14,7 @@ export const ToolWorkshopPage = () => {
|
||||
<h1>Tool Workshop</h1>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="tabs"
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: "0.5rem",
|
||||
marginBottom: "1rem",
|
||||
borderBottom: "1px solid var(--color-border)",
|
||||
}}
|
||||
>
|
||||
{(["types", "configs", "folders"] as Tab[]).map((tab) => (
|
||||
<button
|
||||
key={tab}
|
||||
onClick={() => setActiveTab(tab)}
|
||||
className={activeTab === tab ? "tab-active" : "tab"}
|
||||
style={{
|
||||
padding: "0.5rem 1rem",
|
||||
borderBottom:
|
||||
activeTab === tab
|
||||
? "2px solid var(--color-primary)"
|
||||
: "2px solid transparent",
|
||||
background: "none",
|
||||
border: "none",
|
||||
cursor: "pointer",
|
||||
fontWeight: activeTab === tab ? 600 : 400,
|
||||
}}
|
||||
>
|
||||
{tab === "types" && (
|
||||
<>
|
||||
<Icon name="code" size="sm" /> Tool Types
|
||||
</>
|
||||
)}
|
||||
{tab === "configs" && (
|
||||
<>
|
||||
<Icon name="settings" size="sm" /> Configs
|
||||
</>
|
||||
)}
|
||||
{tab === "folders" && (
|
||||
<>
|
||||
<Icon name="folder" size="sm" /> Config Folders
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{activeTab === "types" && <ToolTypesTab />}
|
||||
{activeTab === "configs" && <ToolConfigsTab />}
|
||||
{activeTab === "folders" && <ConfigFoldersTab />}
|
||||
<ToolTypesTab />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -14,7 +14,6 @@ import { SettingsPage, GeneralSettingsTab } from "./pages/SettingsPage";
|
||||
import { TerminalPage } from "./pages/TerminalPage";
|
||||
import { ToolWorkshopPage } from "./pages/ToolWorkshopPage";
|
||||
import { SSHKeysPage } from "./pages/SshKeysPage";
|
||||
import { ToolConfigsPage } from "./pages/ToolConfigsPage";
|
||||
import { ToolTypesPage } from "./pages/ToolTypesPage";
|
||||
import { SessionsPage } from "./pages/SessionsPage";
|
||||
|
||||
@@ -31,10 +30,6 @@ export const AppRouter = () => {
|
||||
path="/tool-types"
|
||||
element={<Navigate to="/settings/tool-types" replace />}
|
||||
/>
|
||||
<Route
|
||||
path="/tool-configs"
|
||||
element={<Navigate to="/settings/tool-configs" replace />}
|
||||
/>
|
||||
<Route
|
||||
path="/"
|
||||
element={
|
||||
@@ -64,7 +59,6 @@ export const AppRouter = () => {
|
||||
<Route path="general" element={<GeneralSettingsTab />} />
|
||||
<Route path="ssh-keys" element={<SSHKeysPage />} />
|
||||
<Route path="tool-types" element={<ToolTypesPage />} />
|
||||
<Route path="tool-configs" element={<ToolConfigsPage />} />
|
||||
<Route path="*" element={<Navigate to="general" replace />} />
|
||||
</Route>
|
||||
<Route path="tool-workshop" element={<ToolWorkshopPage />} />
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
export interface ConfigFolder {
|
||||
id: string;
|
||||
user_id: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
mount_path: string;
|
||||
files: Record<string, string>;
|
||||
project_overrides: Record<
|
||||
string,
|
||||
{ mount_path?: string; files?: Record<string, string> }
|
||||
> | null;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface CreateConfigFolderRequest {
|
||||
name: string;
|
||||
description?: string;
|
||||
mount_path: string;
|
||||
files?: Record<string, string>;
|
||||
is_active?: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateConfigFolderRequest {
|
||||
name?: string;
|
||||
description?: string;
|
||||
mount_path?: string;
|
||||
files?: Record<string, string>;
|
||||
is_active?: boolean;
|
||||
}
|
||||
|
||||
export interface ProjectOverrideRequest {
|
||||
mount_path?: string;
|
||||
files?: Record<string, string>;
|
||||
}
|
||||
@@ -1,10 +1,4 @@
|
||||
export type { ApiResponse, PaginatedResponse } from "./api-response";
|
||||
export type {
|
||||
ConfigFolder,
|
||||
CreateConfigFolderRequest,
|
||||
UpdateConfigFolderRequest,
|
||||
ProjectOverrideRequest,
|
||||
} from "./config-folder";
|
||||
export type {
|
||||
CommitDetail,
|
||||
CommitHistoryEntry,
|
||||
@@ -18,7 +12,6 @@ export type {
|
||||
} from "./git-repository";
|
||||
export type { Project, ProjectWithRepos } from "./project";
|
||||
export type { Session } from "./session";
|
||||
export type { ToolConfig, CreateToolConfigRequest } from "./tool-config";
|
||||
export type { ToolInstance } from "./tool-instance";
|
||||
export type {
|
||||
CreateToolTypeRequest,
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
export interface ToolConfig {
|
||||
id: string;
|
||||
tool_type_id: string;
|
||||
project_id: string | null;
|
||||
key: string;
|
||||
value: string;
|
||||
config_type: string;
|
||||
file_path: string | null;
|
||||
port_override: number | null;
|
||||
start_command: string | null;
|
||||
working_directory: string | null;
|
||||
environment_variables: Record<string, string> | null;
|
||||
volumes: Array<{ source: string; target: string; type?: string }> | null;
|
||||
}
|
||||
|
||||
export interface CreateToolConfigRequest {
|
||||
tool_type_id: string;
|
||||
project_id?: string;
|
||||
key: string;
|
||||
value: string;
|
||||
config_type?: string;
|
||||
file_path?: string;
|
||||
port_override?: number;
|
||||
start_command?: string;
|
||||
working_directory?: string;
|
||||
environment_variables?: Record<string, string>;
|
||||
volumes?: Array<{ source: string; target: string; type?: string }>;
|
||||
}
|
||||
Reference in New Issue
Block a user