Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix: refresh agent status from active tasks (#1733)

devv-eveba2f19d63121
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index 05ec0f8185..cd38494cae 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -198,21 +198,10 @@ func broadcastFailedTasks(ctx context.Context, queries *db.Queries, taskSvc *ser
}
}
-// reconcileAgentStatus checks running task count and updates agent status.
+// reconcileAgentStatus refreshes agent status from the current active task set.
// Used only by the test-fallback path of broadcastFailedTasks above.
func reconcileAgentStatus(ctx context.Context, queries *db.Queries, bus *events.Bus, agentID pgtype.UUID) {
- running, err := queries.CountRunningTasks(ctx, agentID)
- if err != nil {
- return
- }
- newStatus := "idle"
- if running > 0 {
- newStatus = "working"
- }
- agent, err := queries.UpdateAgentStatus(ctx, db.UpdateAgentStatusParams{
- ID: agentID,
- Status: newStatus,
- })
+ agent, err := queries.RefreshAgentStatusFromTasks(ctx, agentID)
if err != nil {
return
}
diff --git a/server/cmd/server/runtime_sweeper_test.go b/server/cmd/server/runtime_sweeper_test.go
index f8f4c7c8ef..6d7cd93079 100644
--- a/server/cmd/server/runtime_sweeper_test.go
+++ b/server/cmd/server/runtime_sweeper_test.go
@@ -78,6 +78,49 @@ func cleanupSweeperFixture(t *testing.T, issueID, agentID string) {
testPool.Exec(ctx, `UPDATE agent SET status = 'idle' WHERE id = $1`, agentID)
}
+func TestRefreshAgentStatusFromTasks(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+
+ ctx := context.Background()
+ issueID, agentID, taskID := setupSweeperTestFixture(t, "dispatched")
+ t.Cleanup(func() { cleanupSweeperFixture(t, issueID, agentID) })
+
+ queries := db.New(testPool)
+
+ if _, err := testPool.Exec(ctx, `UPDATE agent SET status = 'idle' WHERE id = $1`, agentID); err != nil {
+ t.Fatalf("failed to seed idle agent status: %v", err)
+ }
+
+ agent, err := queries.RefreshAgentStatusFromTasks(ctx, parseUUID(agentID))
+ if err != nil {
+ t.Fatalf("RefreshAgentStatusFromTasks with dispatched task failed: %v", err)
+ }
+ if agent.Status != "working" {
+ t.Fatalf("expected dispatched task to refresh agent status to working, got %q", agent.Status)
+ }
+
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent_task_queue
+ SET status = 'cancelled', completed_at = now()
+ WHERE id = $1
+ `, taskID); err != nil {
+ t.Fatalf("failed to cancel seeded task: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `UPDATE agent SET status = 'working' WHERE id = $1`, agentID); err != nil {
+ t.Fatalf("failed to reseed working agent status: %v", err)
+ }
+
+ agent, err = queries.RefreshAgentStatusFromTasks(ctx, parseUUID(agentID))
+ if err != nil {
+ t.Fatalf("RefreshAgentStatusFromTasks with no active tasks failed: %v", err)
+ }
+ if agent.Status != "idle" {
+ t.Fatalf("expected cancelled-only task set to refresh agent status to idle, got %q", agent.Status)
+ }
+}
+
// TestSweepStaleTasksBroadcastsWithWorkspaceID verifies that when the task sweeper
// fails a stale running task, the task:failed event is broadcast with the correct
// WorkspaceID so it reaches frontend WebSocket clients (events without WorkspaceID
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index fe885ff26b..e956c48ff5 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -192,7 +192,7 @@ func (s *TaskService) CancelTask(ctx context.Context, taskID pgtype.UUID) (*db.A
func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.AgentTaskQueue, error) {
start := time.Now()
var (
- outcome = "unknown"
+ outcome = "unknown"
getAgentMs, countRunningMs, claimAgentMs, updateStatusMs, dispatchMs int64
)
defer func() {
@@ -235,10 +235,10 @@ func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.A
slog.Info("task claimed", "task_id", util.UUIDToString(task.ID), "agent_id", util.UUIDToString(agentID))
- // Update agent status to working. Hits the DB and may publish events,
- // so it must be inside the timed window.
+ // Refresh agent status from active tasks. This avoids a stale unconditional
+ // working write racing after a just-cancelled claim.
t0 = time.Now()
- s.updateAgentStatus(ctx, agentID, "working")
+ s.ReconcileAgentStatus(ctx, agentID)
updateStatusMs = time.Since(t0).Milliseconds()
// Broadcast task:dispatch. ResolveTaskWorkspaceID inside this path can
@@ -257,10 +257,10 @@ func (s *TaskService) ClaimTask(ctx context.Context, agentID pgtype.UUID) (*db.A
func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.UUID) (*db.AgentTaskQueue, error) {
start := time.Now()
var (
- outcome = "no_task"
- listMs, loopMs int64
- listCount, tried int
- claimedFlag bool
+ outcome = "no_task"
+ listMs, loopMs int64
+ listCount, tried int
+ claimedFlag bool
)
defer func() {
totalMs := time.Since(start).Milliseconds()
@@ -806,18 +806,14 @@ func (s *TaskService) ReportProgress(ctx context.Context, taskID string, workspa
})
}
-// ReconcileAgentStatus checks running task count and sets agent status accordingly.
+// ReconcileAgentStatus refreshes agent status from the current active task set.
func (s *TaskService) ReconcileAgentStatus(ctx context.Context, agentID pgtype.UUID) {
- running, err := s.Queries.CountRunningTasks(ctx, agentID)
+ agent, err := s.Queries.RefreshAgentStatusFromTasks(ctx, agentID)
if err != nil {
return
}
- newStatus := "idle"
- if running > 0 {
- newStatus = "working"
- }
- slog.Debug("agent status reconciled", "agent_id", util.UUIDToString(agentID), "status", newStatus, "running_tasks", running)
- s.updateAgentStatus(ctx, agentID, newStatus)
+ slog.Debug("agent status reconciled", "agent_id", util.UUIDToString(agentID), "status", agent.Status)
+ s.publishAgentStatus(agent)
}
func (s *TaskService) updateAgentStatus(ctx context.Context, agentID pgtype.UUID, status string) {
@@ -828,6 +824,10 @@ func (s *TaskService) updateAgentStatus(ctx context.Context, agentID pgtype.UUID
if err != nil {
return
}
+ s.publishAgentStatus(agent)
+}
+
+func (s *TaskService) publishAgentStatus(agent db.Agent) {
s.Bus.Publish(events.Event{
Type: protocol.EventAgentStatus,
WorkspaceID: util.UUIDToString(agent.WorkspaceID),
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 9a83ea6543..167cb1bb15 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -108,10 +108,10 @@ RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, c
`
// Cancels every active task on the issue and returns the affected rows so the
-// caller can reconcile each agent's status and broadcast task:cancelled
-// events (#1587). Prior :exec form silently dropped that info, so internal
-// cancel paths (issue status flips to cancelled/done, etc.) left agents stuck
-// at status="working" with no self-correction.
+// caller can reconcile each agent's status and broadcast task:cancelled events
+// (#1587). Prior :exec form silently dropped that info, so internal cancel
+// paths (issue status flips to cancelled/done, etc.) left agents stuck at
+// status="working" with no self-correction.
func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]AgentTaskQueue, error) {
rows, err := q.db.Query(ctx, cancelAgentTasksByIssue, issueID)
if err != nil {
@@ -1218,6 +1218,46 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID
return items, nil
}
+const refreshAgentStatusFromTasks = `-- name: RefreshAgentStatusFromTasks :one
+UPDATE agent AS a
+SET status = CASE WHEN EXISTS (
+ SELECT 1 FROM agent_task_queue q
+ WHERE q.agent_id = a.id AND q.status IN ('dispatched', 'running')
+) THEN 'working' ELSE 'idle' END,
+ updated_at = now()
+WHERE a.id = $1
+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model
+`
+
+func (q *Queries) RefreshAgentStatusFromTasks(ctx context.Context, id pgtype.UUID) (Agent, error) {
+ row := q.db.QueryRow(ctx, refreshAgentStatusFromTasks, id)
+ var i Agent
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.AvatarUrl,
+ &i.RuntimeMode,
+ &i.RuntimeConfig,
+ &i.Visibility,
+ &i.Status,
+ &i.MaxConcurrentTasks,
+ &i.OwnerID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Description,
+ &i.RuntimeID,
+ &i.Instructions,
+ &i.ArchivedAt,
+ &i.ArchivedBy,
+ &i.CustomEnv,
+ &i.CustomArgs,
+ &i.McpConfig,
+ &i.Model,
+ )
+ return i, err
+}
+
const restoreAgent = `-- name: RestoreAgent :one
UPDATE agent SET archived_at = NULL, archived_by = NULL, updated_at = now()
WHERE id = $1
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index c4c12ad462..1e3cd4ab26 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -275,3 +275,13 @@ ORDER BY created_at DESC;
UPDATE agent SET status = $2, updated_at = now()
WHERE id = $1
RETURNING *;
+
+-- name: RefreshAgentStatusFromTasks :one
+UPDATE agent AS a
+SET status = CASE WHEN EXISTS (
+ SELECT 1 FROM agent_task_queue q
+ WHERE q.agent_id = a.id AND q.status IN ('dispatched', 'running')
+) THEN 'working' ELSE 'idle' END,
+ updated_at = now()
+WHERE a.id = $1
+RETURNING *;