Files
hongming 8019231a16
ci-arm64-advisory / fast-checks (push) Waiting to run
Lint shellcheck (arm64 pilot) / shellcheck-arm64 (pilot) (push) Successful in 8s
Block internal-flavored paths / Block forbidden paths (push) Successful in 8s
CI / Detect changes (push) Successful in 9s
CI / Python Lint & Test (push) Successful in 5s
E2E API Smoke Test / detect-changes (push) Successful in 9s
E2E Chat / detect-changes (push) Successful in 8s
E2E Peer Visibility (literal MCP list_peers) / E2E Peer Visibility (local) (push) Successful in 49s
E2E Staging Canvas (Playwright) / detect-changes (push) Successful in 12s
publish-workspace-server-image / build-and-push (push) Successful in 3m12s
E2E Staging SaaS (full lifecycle) / pr-validate (push) Successful in 39s
Handlers Postgres Integration / detect-changes (push) Successful in 4s
Harness Replays / detect-changes (push) Successful in 5s
Lint curl status-code capture / Scan workflows for curl status-capture pollution (push) Successful in 6s
Lint forbidden tenant-env keys / Scan workspace_secrets writers for forbidden env keys (push) Successful in 4s
Lint no tenant GITEA or GITHUB token write / Scan for repo-host token write into tenant workspace surface (push) Successful in 3s
lint-required-workflows-docker-host-pinned / Lint docker-host pin on docker-touching workflows (push) Successful in 3s
lint-continue-on-error-tracking / lint-continue-on-error-tracking (push) Successful in 1m6s
Secret scan / Scan diff for credential-shaped strings (push) Successful in 14s
CI / Canvas (Next.js) (push) Successful in 3s
CI / Shellcheck (E2E scripts) (push) Successful in 2s
Lint workflow YAML (Gitea-1.22.6-hostile shapes) / Lint workflow YAML for Gitea-1.22.6-hostile shapes (push) Successful in 1m25s
E2E Peer Visibility (literal MCP list_peers) / E2E Peer Visibility (push) Successful in 5m19s
E2E Staging External Runtime / E2E Staging External Runtime (push) Successful in 5m30s
E2E API Smoke Test / E2E API Smoke Test (push) Successful in 2m23s
E2E Staging SaaS (full lifecycle) / E2E Staging SaaS (push) Successful in 6m5s
E2E Chat / E2E Chat (push) Successful in 4m6s
CI / Platform (Go) (push) Successful in 5m0s
CI / all-required (push) Successful in 9m45s
E2E Staging Canvas (Playwright) / Canvas tabs E2E (push) Successful in 2s
publish-workspace-server-image / Production auto-deploy (push) Successful in 8m32s
Harness Replays / Harness Replays (push) Successful in 12s
CI / Canvas Deploy Reminder (push) Successful in 2s
Handlers Postgres Integration / Handlers Postgres Integration (push) Successful in 1m37s
Sweep stale Cloudflare Tunnels / Sweep CF tunnels (push) Successful in 8s
Sweep stale e2e-* orgs (staging) / Sweep e2e orgs (push) Successful in 12s
Staging SaaS smoke (every 30 min) / Staging SaaS smoke (push) Successful in 5m9s
main-red-watchdog / watchdog (push) Successful in 32s
gate-check-v3 / gate-check (push) Successful in 25s
Continuous synthetic E2E (staging) / Synthetic E2E against staging (push) Successful in 6m10s
chore(go-module): #1760 rename Go module to git.moleculesai.app/molecule-ai/molecule-core/workspace-server (#1816)
CTO-bypass merge 2026-05-24: #1760 Go module rename to git.moleculesai.app path
2026-05-24 23:37:18 +00:00

236 lines
7.2 KiB
Go

package handlers
import (
"database/sql"
"log"
"net/http"
"git.moleculesai.app/molecule-ai/molecule-core/workspace-server/internal/db"
"git.moleculesai.app/molecule-ai/molecule-core/workspace-server/internal/events"
"github.com/gin-gonic/gin"
)
type AgentHandler struct {
broadcaster *events.Broadcaster
}
func NewAgentHandler(b *events.Broadcaster) *AgentHandler {
return &AgentHandler{broadcaster: b}
}
// Assign handles POST /workspaces/:id/agent
func (h *AgentHandler) Assign(c *gin.Context) {
workspaceID := c.Param("id")
ctx := c.Request.Context()
var body struct {
Model string `json:"model" binding:"required"`
}
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return
}
// Check workspace exists
var status string
err := db.DB.QueryRowContext(ctx,
`SELECT status FROM workspaces WHERE id = $1`, workspaceID).Scan(&status)
if err == sql.ErrNoRows {
c.JSON(http.StatusNotFound, gin.H{"error": "workspace not found"})
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
return
}
// Check no active agent already assigned
var existingCount int
if err := db.DB.QueryRowContext(ctx,
`SELECT COUNT(*) FROM agents WHERE workspace_id = $1 AND status = 'active'`, workspaceID,
).Scan(&existingCount); err != nil {
log.Printf("Agent assign check error: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
return
}
if existingCount > 0 {
c.JSON(http.StatusConflict, gin.H{"error": "workspace already has an active agent, use PATCH to replace"})
return
}
// Insert agent
var agentID string
err = db.DB.QueryRowContext(ctx,
`INSERT INTO agents (workspace_id, model) VALUES ($1, $2) RETURNING id`, workspaceID, body.Model,
).Scan(&agentID)
if err != nil {
log.Printf("Assign agent error: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to assign agent"})
return
}
h.broadcaster.RecordAndBroadcast(ctx, string(events.EventAgentAssigned), workspaceID, map[string]interface{}{
"agent_id": agentID,
"model": body.Model,
})
c.JSON(http.StatusCreated, gin.H{"agent_id": agentID, "model": body.Model})
}
// Replace handles PATCH /workspaces/:id/agent
func (h *AgentHandler) Replace(c *gin.Context) {
workspaceID := c.Param("id")
ctx := c.Request.Context()
var body struct {
Model string `json:"model" binding:"required"`
}
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return
}
// Deactivate current agent
var oldModel string
err := db.DB.QueryRowContext(ctx,
`UPDATE agents SET status = 'replaced', removed_at = now(), removal_reason = 'model_replaced'
WHERE workspace_id = $1 AND status = 'active' RETURNING model`,
workspaceID,
).Scan(&oldModel)
if err == sql.ErrNoRows {
c.JSON(http.StatusNotFound, gin.H{"error": "no active agent to replace"})
return
}
if err != nil {
log.Printf("Replace agent error (deactivate): %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to replace agent"})
return
}
// Insert new agent
var agentID string
err = db.DB.QueryRowContext(ctx,
`INSERT INTO agents (workspace_id, model) VALUES ($1, $2) RETURNING id`, workspaceID, body.Model,
).Scan(&agentID)
if err != nil {
log.Printf("Replace agent error (insert): %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to assign replacement"})
return
}
h.broadcaster.RecordAndBroadcast(ctx, string(events.EventAgentReplaced), workspaceID, map[string]interface{}{
"agent_id": agentID,
"model": body.Model,
"old_model": oldModel,
})
c.JSON(http.StatusOK, gin.H{"agent_id": agentID, "model": body.Model, "old_model": oldModel})
}
// Remove handles DELETE /workspaces/:id/agent
func (h *AgentHandler) Remove(c *gin.Context) {
workspaceID := c.Param("id")
ctx := c.Request.Context()
var agentID, model string
err := db.DB.QueryRowContext(ctx,
`UPDATE agents SET status = 'removed', removed_at = now(), removal_reason = 'manual_removal'
WHERE workspace_id = $1 AND status = 'active' RETURNING id, model`,
workspaceID,
).Scan(&agentID, &model)
if err == sql.ErrNoRows {
c.JSON(http.StatusNotFound, gin.H{"error": "no active agent to remove"})
return
}
if err != nil {
log.Printf("Remove agent error: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to remove agent"})
return
}
h.broadcaster.RecordAndBroadcast(ctx, string(events.EventAgentRemoved), workspaceID, map[string]interface{}{
"agent_id": agentID,
"model": model,
})
c.JSON(http.StatusOK, gin.H{"status": "removed", "agent_id": agentID})
}
// Move handles POST /workspaces/:id/agent/move
func (h *AgentHandler) Move(c *gin.Context) {
sourceID := c.Param("id")
ctx := c.Request.Context()
var body struct {
TargetWorkspaceID string `json:"target_workspace_id" binding:"required"`
}
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return
}
// Check target workspace exists
var targetStatus string
err := db.DB.QueryRowContext(ctx,
`SELECT status FROM workspaces WHERE id = $1`, body.TargetWorkspaceID).Scan(&targetStatus)
if err == sql.ErrNoRows {
c.JSON(http.StatusNotFound, gin.H{"error": "target workspace not found"})
return
}
if err != nil {
log.Printf("Move agent target lookup error: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "target lookup failed"})
return
}
// Check target doesn't already have an agent
var targetAgentCount int
if err := db.DB.QueryRowContext(ctx,
`SELECT COUNT(*) FROM agents WHERE workspace_id = $1 AND status = 'active'`, body.TargetWorkspaceID,
).Scan(&targetAgentCount); err != nil {
log.Printf("Move agent target check error: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "target lookup failed"})
return
}
if targetAgentCount > 0 {
c.JSON(http.StatusConflict, gin.H{"error": "target workspace already has an active agent"})
return
}
// Move the agent: update workspace_id
var agentID, model string
err = db.DB.QueryRowContext(ctx,
`UPDATE agents SET workspace_id = $2
WHERE workspace_id = $1 AND status = 'active' RETURNING id, model`,
sourceID, body.TargetWorkspaceID,
).Scan(&agentID, &model)
if err == sql.ErrNoRows {
c.JSON(http.StatusNotFound, gin.H{"error": "no active agent in source workspace"})
return
}
if err != nil {
log.Printf("Move agent error: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to move agent"})
return
}
// Broadcast on both workspaces
h.broadcaster.RecordAndBroadcast(ctx, string(events.EventAgentMoved), sourceID, map[string]interface{}{
"agent_id": agentID,
"model": model,
"target_workspace_id": body.TargetWorkspaceID,
})
h.broadcaster.RecordAndBroadcast(ctx, string(events.EventAgentMoved), body.TargetWorkspaceID, map[string]interface{}{
"agent_id": agentID,
"model": model,
"source_workspace_id": sourceID,
})
c.JSON(http.StatusOK, gin.H{
"agent_id": agentID,
"model": model,
"from_workspace": sourceID,
"to_workspace": body.TargetWorkspaceID,
})
}