Skip to content

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

Go

perf(agents): index-backed latest-terminal lookup in task snapshot (MUL-5436) (#6085)

Multica Eved4dac0e77c72
diff --git a/packages/core/agents/queries.ts b/packages/core/agents/queries.ts
index da24146194..e17eae1a74 100644
--- a/packages/core/agents/queries.ts
+++ b/packages/core/agents/queries.ts
@@ -46,6 +46,11 @@ export const agentRunCountsKeys = {
// workspace; all agent dots / hover cards / list rows derive presence from
// this cache with zero additional network traffic.
//
+// Presence itself is derived from the active tasks only (see derive-presence.ts
+// and #1823). The one terminal row per agent is used solely for the Squad hover
+// card's "last activity" line; MUL-5436 tracks moving it to a dedicated lazy
+// endpoint so this hot query stops carrying history at all.
+//
// The 30s staleTime is a safety net only; the primary freshness signal is
// WS task events, which invalidate this query immediately. Without WS,
// presence still updates within 30s on focus / mount.
diff --git a/packages/views/agents/components/agent-live-peek-card.test.tsx b/packages/views/agents/components/agent-live-peek-card.test.tsx
index aaa53a30ab..00e7b57eab 100644
--- a/packages/views/agents/components/agent-live-peek-card.test.tsx
+++ b/packages/views/agents/components/agent-live-peek-card.test.tsx
@@ -252,4 +252,34 @@ describe("AgentLivePeekCard", () => {
expect(screen.getByText("Idle")).toBeInTheDocument();
expect(screen.getByText(enAgents.live_peek.failed_indicator)).toBeInTheDocument();
});
+
+ it("ignores cancelled tasks when picking last activity", () => {
+ mockPresence.current = {
+ availability: "online",
+ workload: "idle",
+ runningCount: 0,
+ queuedCount: 0,
+ capacity: 1,
+ };
+ // The snapshot endpoint never returns cancelled rows, but the card must
+ // not treat one as an outcome if it ever does: cancel is a procedural
+ // signal, so a newer cancellation must not mask the older real failure.
+ mockSnapshot.current = [
+ makeTask({
+ id: "task-failed",
+ status: "failed",
+ completed_at: new Date(Date.now() - 10 * 60 * 1000).toISOString(),
+ }),
+ makeTask({
+ id: "task-cancelled",
+ status: "cancelled",
+ completed_at: new Date(Date.now() - 1 * 60 * 1000).toISOString(),
+ }),
+ ];
+
+ renderCard();
+
+ expect(screen.getByText(/10m ago/)).toBeInTheDocument();
+ expect(screen.getByText(enAgents.live_peek.failed_indicator)).toBeInTheDocument();
+ });
});
diff --git a/packages/views/agents/components/agent-live-peek-card.tsx b/packages/views/agents/components/agent-live-peek-card.tsx
index 9b321a251b..1401db0a08 100644
--- a/packages/views/agents/components/agent-live-peek-card.tsx
+++ b/packages/views/agents/components/agent-live-peek-card.tsx
@@ -141,14 +141,17 @@ export function AgentLivePeekCard({ agentId }: AgentLivePeekCardProps) {
);
}
-// Pick the most recent terminal task for last-activity display. Snapshot
-// already caps this to one terminal row per agent (see queries.ts header),
-// but a defensive max-by-completed_at keeps the card honest if that shape
-// ever changes.
+// Pick the most recent terminal task for last-activity display. The snapshot
+// already caps this to one terminal row per agent (see queries.ts header), but
+// a defensive max-by-completed_at keeps the card honest if that shape ever
+// changes. Only completed / failed count, matching the snapshot's outcome
+// filter exactly: cancelled never reaches this card, and treating it as a
+// terminal outcome here would let an aborted attempt mask the agent's last
+// real result if the endpoint ever started returning it.
function pickLatestTerminal(tasks: readonly AgentTask[]): AgentTask | null {
let best: AgentTask | null = null;
for (const t of tasks) {
- if (t.status !== "completed" && t.status !== "failed" && t.status !== "cancelled") {
+ if (t.status !== "completed" && t.status !== "failed") {
continue;
}
if (!t.completed_at) continue;
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index cb90c5969c..008851f2f8 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -2338,15 +2338,18 @@ func (h *Handler) GetWorkspaceAgentActivity30d(w http.ResponseWriter, r *http.Re
writeJSON(w, http.StatusOK, resp)
}
-// ListWorkspaceAgentTaskSnapshot returns the task data the front-end needs to
-// derive each agent's presence: every active task (queued/dispatched/running)
-// plus each agent's most recent OUTCOME task (completed/failed only). Cancelled
-// tasks are excluded from the outcome half by design — cancel is a procedural
-// signal ("attempt aborted"), not an outcome, so it must not mask a prior
-// failure. The front-end picks "active wins, else latest outcome"; a failed
-// outcome stays sticky until the user starts a new task or one succeeds.
-// Per-agent filtering happens in the front-end against this workspace-wide
-// snapshot.
+// ListWorkspaceAgentTaskSnapshot returns the workspace-wide task data the
+// front-end reads for two things: every active task
+// (queued/dispatched/running/waiting_local_directory), which is the current
+// workload presence derives from, plus each agent's most recent OUTCOME task
+// (completed/failed only), which is no longer part of presence since #1823 and
+// only feeds the Squad hover card's "last activity" line. Cancelled tasks are
+// excluded from the outcome half by design — cancel is a procedural signal
+// ("attempt aborted"), not an outcome, so it must not mask a prior failure.
+// Per-agent filtering happens in the front-end against this snapshot.
+//
+// The outcome half is deliberately still served here so shipped desktop builds
+// keep working; MUL-5436 tracks moving it to a dedicated lazy endpoint.
func (h *Handler) ListWorkspaceAgentTaskSnapshot(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
member, ok := h.workspaceMember(w, r, workspaceID)
diff --git a/server/internal/handler/agent_test.go b/server/internal/handler/agent_test.go
index c70b98b1d0..2c6a2c9869 100644
--- a/server/internal/handler/agent_test.go
+++ b/server/internal/handler/agent_test.go
@@ -26,58 +26,73 @@ import (
// - cancelled rows are NEVER returned, even when they are temporally newer
// than a failure — this is what keeps the failed signal sticky after the
// user cancels their queued retry
+// - when two outcomes tie on completed_at AND created_at, exactly one row
+// comes back and the pick is deterministic (id DESC) — the old
+// completed_at-only ordering returned an arbitrary row here
func TestListWorkspaceAgentTaskSnapshot(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
ctx := context.Background()
- // Three agents so we can verify per-agent semantics independently.
+ // Four agents so we can verify per-agent semantics independently.
agentA := createHandlerTestAgent(t, "snapshot-agent-a", []byte(`{}`))
agentB := createHandlerTestAgent(t, "snapshot-agent-b", []byte(`{}`))
agentC := createHandlerTestAgent(t, "snapshot-agent-c", []byte(`{}`))
+ agentD := createHandlerTestAgent(t, "snapshot-agent-d", []byte(`{}`))
type taskFixture struct {
agentID string
status string
completedAt string // SQL expression; "" for NULL
+ createdAt string // SQL expression; "" for the column default
label string
}
fixtures := []taskFixture{
// Agent A — actives + a newer completed supersedes an older failed.
- {agentA, "queued", "", "A.queued"},
- {agentA, "dispatched", "", "A.dispatched"},
- {agentA, "running", "", "A.running"},
- {agentA, "failed", "now() - interval '10 minutes'", "A.old_failed"},
- {agentA, "completed", "now() - interval '30 seconds'", "A.latest_completed"},
+ {agentA, "queued", "", "", "A.queued"},
+ {agentA, "dispatched", "", "", "A.dispatched"},
+ {agentA, "running", "", "", "A.running"},
+ {agentA, "failed", "now() - interval '10 minutes'", "", "A.old_failed"},
+ {agentA, "completed", "now() - interval '30 seconds'", "", "A.latest_completed"},
// Agent B — old failure with no later outcome stays visible (no
// time window).
- {agentB, "failed", "now() - interval '5 minutes'", "B.stale_failed_kept"},
+ {agentB, "failed", "now() - interval '5 minutes'", "", "B.stale_failed_kept"},
// Agent C — failure followed by a NEWER cancelled. The cancelled
// must be skipped by the SQL filter so the failure remains visible.
// This is the scenario where a user fails, then cancels their
// queued retry to debug.
- {agentC, "failed", "now() - interval '5 minutes'", "C.failure"},
- {agentC, "cancelled", "now() - interval '30 seconds'", "C.newer_cancelled_must_be_ignored"},
+ {agentC, "failed", "now() - interval '5 minutes'", "", "C.failure"},
+ {agentC, "cancelled", "now() - interval '30 seconds'", "", "C.newer_cancelled_must_be_ignored"},
+
+ // Agent D — two outcomes that tie on BOTH completed_at and
+ // created_at. Ordering by completed_at alone leaves the winner up
+ // to the plan; the (created_at, id) tie-break makes it id DESC.
+ {agentD, "completed", "timestamptz '2026-05-14 10:00:00+00'", "timestamptz '2026-05-14 09:00:00+00'", "D.tie_one"},
+ {agentD, "failed", "timestamptz '2026-05-14 10:00:00+00'", "timestamptz '2026-05-14 09:00:00+00'", "D.tie_two"},
}
insertedIDs := make([]string, 0, len(fixtures))
+ idByLabel := make(map[string]string, len(fixtures))
for _, f := range fixtures {
var id string
- var query string
- if f.completedAt == "" {
- query = `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority)
- VALUES ($1, $2, $3, 0) RETURNING id`
- } else {
- query = `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, completed_at)
- VALUES ($1, $2, $3, 0, ` + f.completedAt + `) RETURNING id`
+ completedExpr := "NULL"
+ if f.completedAt != "" {
+ completedExpr = f.completedAt
+ }
+ createdExpr := "DEFAULT"
+ if f.createdAt != "" {
+ createdExpr = f.createdAt
}
+ query := `INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, completed_at, created_at)
+ VALUES ($1, $2, $3, 0, ` + completedExpr + `, ` + createdExpr + `) RETURNING id`
if err := testPool.QueryRow(ctx, query, f.agentID, testRuntimeID, f.status).Scan(&id); err != nil {
t.Fatalf("insert %s: %v", f.label, err)
}
insertedIDs = append(insertedIDs, id)
+ idByLabel[f.label] = id
}
t.Cleanup(func() {
for _, id := range insertedIDs {
@@ -101,16 +116,21 @@ func TestListWorkspaceAgentTaskSnapshot(t *testing.T) {
// don't pollute the assertions.
type key struct{ agent, status string }
counts := map[key]int{}
+ returnedForD := make([]string, 0, 2)
for _, task := range tasks {
- if task.AgentID != agentA && task.AgentID != agentB && task.AgentID != agentC {
+ if task.AgentID != agentA && task.AgentID != agentB &&
+ task.AgentID != agentC && task.AgentID != agentD {
continue
}
counts[key{task.AgentID, task.Status}]++
+ if task.AgentID == agentD {
+ returnedForD = append(returnedForD, task.ID)
+ }
}
wantCounts := map[key]int{
// Agent A: 3 actives + the latest outcome (completed). The older
- // failed must be excluded by DISTINCT ON.
+ // failed must be excluded by the per-agent Top-1 lookup.
{agentA, "queued"}: 1,
{agentA, "dispatched"}: 1,
{agentA, "running"}: 1,
@@ -133,10 +153,26 @@ func TestListWorkspaceAgentTaskSnapshot(t *testing.T) {
t.Errorf("agent A old failed must be superseded by newer completed; got %d", counts[key{agentA, "failed"}])
}
+ // Agent D's two outcomes tie on completed_at and created_at, so the
+ // snapshot must still return exactly one row, and it must be the higher
+ // id — the last tie-break in the query's ORDER BY. Without that
+ // tie-break the winner depends on the plan, which made this endpoint's
+ // output non-deterministic for same-timestamp outcomes.
+ if len(returnedForD) != 1 {
+ t.Fatalf("agent D: expected exactly 1 outcome row on a full tie, got %d (%v)", len(returnedForD), returnedForD)
+ }
+ wantD := idByLabel["D.tie_one"]
+ if idByLabel["D.tie_two"] > wantD {
+ wantD = idByLabel["D.tie_two"]
+ }
+ if returnedForD[0] != wantD {
+ t.Errorf("agent D: expected the higher id %s to win the tie, got %s", wantD, returnedForD[0])
+ }
+
// No cancelled row may ever appear in the snapshot — they're filtered at
// SQL level so the front-end's "cancel doesn't mask failure" rule lands
// without any front-end logic.
- for _, agentID := range []string{agentA, agentB, agentC} {
+ for _, agentID := range []string{agentA, agentB, agentC, agentD} {
if counts[key{agentID, "cancelled"}] != 0 {
t.Errorf("agent %s: cancelled rows must be excluded from snapshot; got %d",
agentID, counts[key{agentID, "cancelled"}])
diff --git a/server/migrations/233_agent_task_queue_agent_terminal_latest_index.down.sql b/server/migrations/233_agent_task_queue_agent_terminal_latest_index.down.sql
new file mode 100644
index 0000000000..598df925e0
--- /dev/null
+++ b/server/migrations/233_agent_task_queue_agent_terminal_latest_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_agent_terminal_latest;
diff --git a/server/migrations/233_agent_task_queue_agent_terminal_latest_index.up.sql b/server/migrations/233_agent_task_queue_agent_terminal_latest_index.up.sql
new file mode 100644
index 0000000000..7313c0a149
--- /dev/null
+++ b/server/migrations/233_agent_task_queue_agent_terminal_latest_index.up.sql
@@ -0,0 +1,22 @@
+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction
+-- or share a multi-command migration file.
+--
+-- ListWorkspaceAgentTaskSnapshot needs "the latest terminal task per agent".
+-- Neither existing index can serve that shape:
+-- - idx_agent_task_queue_agent (agent_id, status) from 001_init has no
+-- completed_at, so the planner still has to read and sort every terminal
+-- row of every agent in the workspace.
+-- - idx_agent_task_queue_terminal_completed_at (completed_at) from 231 is
+-- completed_at-first, built for the cross-agent Usage time-window
+-- rollups, so it cannot skip to one agent's newest row.
+-- Both stay: they still serve those other read patterns.
+--
+-- This index leads with agent_id and then carries the snapshot's full tie-break
+-- order, so the per-agent lookup becomes an ordered index scan with LIMIT 1
+-- instead of a workspace-wide sort. The partial predicate matches the query's
+-- status filter verbatim so the planner can prove applicability, and it keeps
+-- the index off the queued / dispatched / running rows the hot dispatch path
+-- churns — a row only enters this index once, when it reaches a terminal state.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_agent_terminal_latest
+ ON agent_task_queue (agent_id, completed_at DESC NULLS LAST, created_at DESC, id DESC)
+ WHERE status IN ('completed', 'failed');
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index daa7f76e4a..425cd5dcc8 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -4095,34 +4095,43 @@ WHERE a.workspace_id = $1
UNION ALL
-SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason, t.initiator_user_id, t.handoff_note, t.prepare_lease_expires_at, t.squad_id, t.runtime_mcp_overlay, t.escalation_for_task_id, t.fire_at, t.originator_user_id, t.runtime_connected_apps, t.coalesced_comment_ids, t.delivered_comment_ids, t.chat_input_task_id, t.chat_finalize_deferred_at, t.originator_source, t.delegated_from_task_id, t.retry_of_task_id, t.rerun_of_task_id, t.rule_version_id, t.trigger_evidence_kind, t.trigger_evidence_ref_id, t.accountable_user_id, t.session_rollout_missing FROM (
- SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing
+SELECT latest.id, latest.agent_id, latest.issue_id, latest.status, latest.priority, latest.dispatched_at, latest.started_at, latest.completed_at, latest.result, latest.error, latest.created_at, latest.context, latest.runtime_id, latest.session_id, latest.work_dir, latest.trigger_comment_id, latest.chat_session_id, latest.autopilot_run_id, latest.attempt, latest.max_attempts, latest.parent_task_id, latest.failure_reason, latest.trigger_summary, latest.force_fresh_session, latest.is_leader_task, latest.wait_reason, latest.initiator_user_id, latest.handoff_note, latest.prepare_lease_expires_at, latest.squad_id, latest.runtime_mcp_overlay, latest.escalation_for_task_id, latest.fire_at, latest.originator_user_id, latest.runtime_connected_apps, latest.coalesced_comment_ids, latest.delivered_comment_ids, latest.chat_input_task_id, latest.chat_finalize_deferred_at, latest.originator_source, latest.delegated_from_task_id, latest.retry_of_task_id, latest.rerun_of_task_id, latest.rule_version_id, latest.trigger_evidence_kind, latest.trigger_evidence_ref_id, latest.accountable_user_id, latest.session_rollout_missing FROM agent a
+JOIN LATERAL (
+ SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason, atq.initiator_user_id, atq.handoff_note, atq.prepare_lease_expires_at, atq.squad_id, atq.runtime_mcp_overlay, atq.escalation_for_task_id, atq.fire_at, atq.originator_user_id, atq.runtime_connected_apps, atq.coalesced_comment_ids, atq.delivered_comment_ids, atq.chat_input_task_id, atq.chat_finalize_deferred_at, atq.originator_source, atq.delegated_from_task_id, atq.retry_of_task_id, atq.rerun_of_task_id, atq.rule_version_id, atq.trigger_evidence_kind, atq.trigger_evidence_ref_id, atq.accountable_user_id, atq.session_rollout_missing
FROM agent_task_queue atq
- JOIN agent a ON a.id = atq.agent_id
- WHERE a.workspace_id = $1
+ WHERE atq.agent_id = a.id
AND atq.status IN ('completed', 'failed')
- ORDER BY atq.agent_id, atq.completed_at DESC NULLS LAST
-) t
+ ORDER BY atq.completed_at DESC NULLS LAST, atq.created_at DESC, atq.id DESC
+ LIMIT 1
+) latest ON TRUE
+WHERE a.workspace_id = $1
`
-// Returns the tasks needed to derive each agent's current presence:
-// - All active tasks (queued / dispatched / running) — for working signal + counts
-// - Each agent's most recent OUTCOME task (completed / failed) — for sticky
-// failed signal
-//
-// The front-end picks "active wins, else latest outcome" — see derive-presence.ts.
+// Returns the tasks the front-end reads off one workspace-wide snapshot:
+// - All active tasks (queued / dispatched / running / waiting_local_directory)
+// — the current workload: working signal + counts (see derive-presence.ts).
+// - Each agent's most recent OUTCOME task (completed / failed) — NOT part of
+// presence since #1823; it is the "last activity" line the Squad hover card
+// renders (agent-live-peek-card.tsx). Kept in this response because shipped
+// desktop builds read it from here; see MUL-5436 for the plan to move it to
+// a dedicated lazy endpoint.
//
// Cancelled tasks are excluded from the outcome half on purpose: cancel is a
// procedural signal ("attempt aborted"), not an outcome. It tells us nothing
// about whether the agent works, so it must NOT be allowed to mask a prior
// failure. Concretely: if an agent fails and then the user cancels the queued
-// retry (or the parent issue closes and cascades cancels), the failed signal
-// has to stay red. Only a real success (completed) or a fresh attempt (active)
-// clears it.
+// retry (or the parent issue closes and cascades cancels), the failure stays
+// the agent's last real outcome.
+//
+// The outcome half is a per-agent LATERAL Top-1 rather than a workspace-wide
+// DISTINCT ON: with idx_agent_task_queue_agent_terminal_latest (migration 233)
+// each agent costs one ordered index scan + LIMIT 1, so the cost no longer
+// grows with how much terminal history the workspace has accumulated. The
+// (created_at, id) tie-break makes the pick deterministic when completed_at
+// ties or is NULL — plain completed_at DESC returned an arbitrary row there.
+// Row shape and row set are unchanged.
//
-// No UI windows in SQL: stickiness is decided by "is the latest outcome a
-// failure?", not a 2-minute clock. JOINs agent because agent_task_queue has
-// no workspace_id column.
+// Both halves JOIN / scan agent because agent_task_queue has no workspace_id.
func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceID pgtype.UUID) ([]AgentTaskQueue, error) {
rows, err := q.db.Query(ctx, listWorkspaceAgentTaskSnapshot, workspaceID)
if err != nil {
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index e464cb335a..21238aeed8 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -1342,23 +1342,31 @@ GROUP BY atq.agent_id, bucket
ORDER BY atq.agent_id, bucket;
-- name: ListWorkspaceAgentTaskSnapshot :many
--- Returns the tasks needed to derive each agent's current presence:
--- - All active tasks (queued / dispatched / running) — for working signal + counts
--- - Each agent's most recent OUTCOME task (completed / failed) — for sticky
--- failed signal
--- The front-end picks "active wins, else latest outcome" — see derive-presence.ts.
+-- Returns the tasks the front-end reads off one workspace-wide snapshot:
+-- - All active tasks (queued / dispatched / running / waiting_local_directory)
+-- — the current workload: working signal + counts (see derive-presence.ts).
+-- - Each agent's most recent OUTCOME task (completed / failed) — NOT part of
+-- presence since #1823; it is the "last activity" line the Squad hover card
+-- renders (agent-live-peek-card.tsx). Kept in this response because shipped
+-- desktop builds read it from here; see MUL-5436 for the plan to move it to
+-- a dedicated lazy endpoint.
--
-- Cancelled tasks are excluded from the outcome half on purpose: cancel is a
-- procedural signal ("attempt aborted"), not an outcome. It tells us nothing
-- about whether the agent works, so it must NOT be allowed to mask a prior
-- failure. Concretely: if an agent fails and then the user cancels the queued
--- retry (or the parent issue closes and cascades cancels), the failed signal
--- has to stay red. Only a real success (completed) or a fresh attempt (active)
--- clears it.
+-- retry (or the parent issue closes and cascades cancels), the failure stays
+-- the agent's last real outcome.
--
--- No UI windows in SQL: stickiness is decided by "is the latest outcome a
--- failure?", not a 2-minute clock. JOINs agent because agent_task_queue has
--- no workspace_id column.
+-- The outcome half is a per-agent LATERAL Top-1 rather than a workspace-wide
+-- DISTINCT ON: with idx_agent_task_queue_agent_terminal_latest (migration 233)
+-- each agent costs one ordered index scan + LIMIT 1, so the cost no longer
+-- grows with how much terminal history the workspace has accumulated. The
+-- (created_at, id) tie-break makes the pick deterministic when completed_at
+-- ties or is NULL — plain completed_at DESC returned an arbitrary row there.
+-- Row shape and row set are unchanged.
+--
+-- Both halves JOIN / scan agent because agent_task_queue has no workspace_id.
SELECT atq.* FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
WHERE a.workspace_id = $1
@@ -1366,14 +1374,16 @@ WHERE a.workspace_id = $1
UNION ALL
-SELECT t.* FROM (
- SELECT DISTINCT ON (atq.agent_id) atq.*
+SELECT latest.* FROM agent a
+JOIN LATERAL (
+ SELECT atq.*
FROM agent_task_queue atq
- JOIN agent a ON a.id = atq.agent_id
- WHERE a.workspace_id = $1
+ WHERE atq.agent_id = a.id
AND atq.status IN ('completed', 'failed')
- ORDER BY atq.agent_id, atq.completed_at DESC NULLS LAST
-) t;
+ ORDER BY atq.completed_at DESC NULLS LAST, atq.created_at DESC, atq.id DESC
+ LIMIT 1
+) latest ON TRUE
+WHERE a.workspace_id = $1;
-- name: ListWorkspaceWorkingAgents :many
-- Workspace-level source for consumers that show currently working agents.