Skip to content

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

Go

perf(chat): fix pending-task index mismatch + cut aggregate request storm (MUL-4159) (#5018)

LinYushen566d51f1c004
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index dcf6d5f36a..76aaa1b422 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -71,6 +71,7 @@ import type {
ChatMessagesPage,
ChatPendingTask,
PendingChatTasksResponse,
+ HasPendingChatTasksResponse,
SendChatMessageResponse,
CancelTaskResponse,
Project,
@@ -1833,6 +1834,10 @@ export class ApiClient {
return this.fetch(`/api/chat/pending-tasks`);
}
+ async hasAnyPendingChatTasks(): Promise<HasPendingChatTasksResponse> {
+ return this.fetch(`/api/chat/pending-tasks/has-any`);
+ }
+
async markChatSessionRead(sessionId: string): Promise<void> {
await this.fetch(`/api/chat/sessions/${sessionId}/read`, { method: "POST" });
}
diff --git a/packages/core/chat/queries.ts b/packages/core/chat/queries.ts
index f8eb8f52ba..513d26ecd0 100644
--- a/packages/core/chat/queries.ts
+++ b/packages/core/chat/queries.ts
@@ -22,6 +22,13 @@ export const chatKeys = {
pendingTask: (sessionId: string) => [...chatKeys.pendingTaskAll(), sessionId] as const,
/** Aggregate of in-flight chat tasks for the current user — FAB reads this. */
pendingTasks: (wsId: string) => [...chatKeys.all(wsId), "pending-tasks"] as const,
+ /**
+ * Boolean "does the user have any in-flight chat task" — the FAB's cheap
+ * running indicator. Separate cache from the detailed `pendingTasks` list so
+ * the FAB (closed-window) and ChatWindow (open) can subscribe independently.
+ */
+ pendingTasksHasAny: (wsId: string) =>
+ [...chatKeys.all(wsId), "pending-tasks", "has-any"] as const,
/** Per-task execution messages — shared with issue agent cards. */
taskMessagesAll: () => ["task-messages"] as const,
taskMessages: (taskId: string) => [...chatKeys.taskMessagesAll(), taskId] as const,
@@ -135,3 +142,18 @@ export function pendingChatTasksOptions(wsId: string) {
staleTime: Infinity,
});
}
+
+/**
+ * Boolean "is any chat task running for me right now" — the cheap sibling of
+ * pendingChatTasksOptions. The FAB uses this (with `enabled: !isOpen`) so the
+ * minimised chat button never fetches or holds the full task list; the
+ * detailed list is reserved for the open ChatWindow (history + stop flows).
+ * Both caches are kept in sync by the task-lifecycle WS handlers.
+ */
+export function hasPendingChatTasksOptions(wsId: string) {
+ return queryOptions({
+ queryKey: chatKeys.pendingTasksHasAny(wsId),
+ queryFn: () => api.hasAnyPendingChatTasks(),
+ staleTime: Infinity,
+ });
+}
diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.ts
index 94e118972c..cdec7bc44e 100644
--- a/packages/core/realtime/use-realtime-sync.test.ts
+++ b/packages/core/realtime/use-realtime-sync.test.ts
@@ -20,6 +20,7 @@ import {
applyWorkspaceUpdatedToCache,
handleInboxNew,
invalidateChatMessageQueries,
+ refetchPendingChatAggregate,
resolveInboxSourceSlug,
} from "./use-realtime-sync";
@@ -147,6 +148,48 @@ describe("invalidateChatMessageQueries", () => {
});
});
+describe("refetchPendingChatAggregate (cross-session pending leak guard)", () => {
+ const wsId = "ws-1";
+
+ it("invalidates the aggregate instead of optimistically writing it, so another member's workspace-broadcast task:* event can't flip this user's has_pending", () => {
+ // Regression for the PR #5018 security review: task:* events are a
+ // workspace fanout with no creator/visibility, so member B's task must not
+ // be able to set member A's FAB to has_pending=true client-side. A's
+ // aggregate currently (correctly) says "nothing pending".
+ const qc = createQueryClient();
+ qc.setQueryData(chatKeys.pendingTasksHasAny(wsId), { has_pending: false });
+ qc.setQueryData(chatKeys.pendingTasks(wsId), { tasks: [] });
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+ const setData = vi.spyOn(qc, "setQueryData");
+
+ refetchPendingChatAggregate(qc, wsId);
+
+ // MUST NOT optimistically flip the boolean or inject a task from the
+ // untrusted event — the cached values are left untouched.
+ expect(qc.getQueryData(chatKeys.pendingTasksHasAny(wsId))).toEqual({
+ has_pending: false,
+ });
+ expect(qc.getQueryData(chatKeys.pendingTasks(wsId))).toEqual({ tasks: [] });
+ expect(setData).not.toHaveBeenCalled();
+
+ // Instead it marks the aggregate stale for an authoritative, server-side
+ // permission-filtered refetch. The has-any key is nested under
+ // pendingTasks, so this one invalidation refreshes both caches.
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: chatKeys.pendingTasks(wsId),
+ });
+ });
+
+ it("no-ops without a workspace id (no accidental cross-workspace invalidation)", () => {
+ const qc = createQueryClient();
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+
+ refetchPendingChatAggregate(qc, undefined);
+
+ expect(invalidate).not.toHaveBeenCalled();
+ });
+});
+
describe("applyWorkspaceUpdatedToCache", () => {
const wsId = "ws-1";
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index a4f07c094e..f2db8b8a82 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -98,6 +98,27 @@ export function invalidateChatMessageQueries(
qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });
}
+// refetchPendingChatAggregate marks the current user's cross-session pending
+// aggregate stale so it is refetched from the permission-filtering endpoint
+// (/api/chat/pending-tasks[/has-any]).
+//
+// SECURITY (review on PR #5018 / MUL-4159): this is deliberately an
+// invalidate, NOT an optimistic setQueryData. Chat `task:*` events are a
+// workspace fanout delivered to every member with no creator / agent
+// visibility in the payload, so optimistically writing the aggregate from them
+// would let one member's task flip another member's FAB to has_pending=true,
+// bypassing the server-side permission filter. Invalidation forces the
+// authoritative, creator+agent-scoped server response to be the source of
+// truth. The has-any key is nested under pendingTasks, so invalidating
+// pendingTasks refreshes both the detailed list and the boolean fast-path.
+export function refetchPendingChatAggregate(
+ qc: QueryClient,
+ wsId: string | null | undefined,
+) {
+ if (!wsId) return;
+ qc.invalidateQueries({ queryKey: chatKeys.pendingTasks(wsId) });
+}
+
export function applyChatDoneToCache(
qc: QueryClient,
payload: ChatDonePayload,
@@ -866,9 +887,35 @@ export function useRealtimeSync(
});
// Helpers reused by chat lifecycle handlers.
+ //
+ // SECURITY (review on PR #5018 / MUL-4159): chat `task:*` events are a
+ // *workspace fanout* — every member of the workspace receives them — and
+ // the payload carries no creator / agent-visibility. So we must NEVER
+ // optimistically write the cross-session pending AGGREGATE
+ // (chatKeys.pendingTasks / chatKeys.pendingTasksHasAny) from these events:
+ // member B starting a chat task would otherwise flip member A's FAB to
+ // has_pending=true, bypassing the server-side permission filter on
+ // /api/chat/pending-tasks[/has-any]. Instead we authoritatively (debounced)
+ // invalidate the aggregate so it is refetched through the filtering
+ // endpoint, which only returns the caller's own creator-owned,
+ // accessible-agent tasks.
+ //
+ // The per-session `pendingTask` cache IS still written directly by the
+ // handlers below — it is keyed by chat_session_id and only rendered for a
+ // session the user is allowed to open (server-gated), so it is not a
+ // cross-user aggregate leak.
+ //
+ // chat:message is intentionally NOT a trigger (it fires per streamed
+ // message and would re-create the request storm MUL-4159 fixed); the
+ // aggregate is refreshed only on task lifecycle transitions, which are
+ // per-task and low-frequency, then coalesced by the debounce below.
+ let aggregateRefreshTimer: ReturnType<typeof setTimeout> | null = null;
const invalidatePendingAggregate = () => {
- const id = getCurrentWsId();
- if (id) qc.invalidateQueries({ queryKey: chatKeys.pendingTasks(id) });
+ if (aggregateRefreshTimer) clearTimeout(aggregateRefreshTimer);
+ aggregateRefreshTimer = setTimeout(() => {
+ aggregateRefreshTimer = null;
+ refetchPendingChatAggregate(qc, getCurrentWsId());
+ }, 750);
};
const invalidateSessionLists = () => {
const id = getCurrentWsId();
@@ -880,7 +927,9 @@ export function useRealtimeSync(
chatWsLogger.info("chat:message (global)", { chat_session_id: payload.chat_session_id });
invalidateChatMessageQueries(qc, payload.chat_session_id);
qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
- invalidatePendingAggregate();
+ // NOTE: intentionally does NOT touch the pending aggregate. chat:message
+ // fires per streamed message with no status; the aggregate is maintained
+ // by the task lifecycle handlers below (MUL-4159).
});
const unsubChatDone = ws.on("chat:done", (p) => {
@@ -903,7 +952,10 @@ export function useRealtimeSync(
// work: they ignore the extra fields and rely on the invalidate
// below, which keeps the old behavior alive.
applyChatDoneToCache(qc, payload);
- invalidatePendingAggregate();
+ // NOTE: the pending aggregate is left to the task:completed / task:failed
+ // handlers (which carry the task_id needed to remove the right entry).
+ // chat:done no longer invalidates it, so a chatty session doesn't refetch
+ // the aggregate on every turn (MUL-4159).
// Assistant message just landed → has_unread may have flipped to true.
invalidateSessionLists();
});
@@ -948,6 +1000,7 @@ export function useRealtimeSync(
return { ...old, status: "running" };
},
);
+ invalidatePendingAggregate();
});
// task:running fires when the daemon transitions a previously-parked task
@@ -965,6 +1018,7 @@ export function useRealtimeSync(
return { ...old, status: "running" };
},
);
+ invalidatePendingAggregate();
});
// task:waiting_local_directory fires when the daemon dequeues a task but
@@ -984,6 +1038,7 @@ export function useRealtimeSync(
return { ...old, status: "waiting_local_directory" };
},
);
+ invalidatePendingAggregate();
},
);
@@ -1140,6 +1195,7 @@ export function useRealtimeSync(
unsubChatSessionRead();
unsubChatSessionDeleted();
unsubChatSessionUpdated();
+ if (aggregateRefreshTimer) clearTimeout(aggregateRefreshTimer);
timers.forEach(clearTimeout);
timers.clear();
};
diff --git a/packages/core/types/chat.ts b/packages/core/types/chat.ts
index de2a51b123..211d4c14c2 100644
--- a/packages/core/types/chat.ts
+++ b/packages/core/types/chat.ts
@@ -23,6 +23,15 @@ export interface PendingChatTasksResponse {
tasks: PendingChatTaskItem[];
}
+/**
+ * Boolean fast-path payload for the FAB "running" indicator — returned by
+ * GET /api/chat/pending-tasks/has-any. The FAB only needs to know whether any
+ * in-flight chat task exists, so it avoids fetching the full task list.
+ */
+export interface HasPendingChatTasksResponse {
+ has_pending: boolean;
+}
+
export interface ChatMessage {
id: string;
chat_session_id: string;
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 1f19fd451e..ea56f8c08c 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -84,6 +84,7 @@ export type {
ChatPendingTask,
PendingChatTaskItem,
PendingChatTasksResponse,
+ HasPendingChatTasksResponse,
SendChatMessageResponse,
CancelledChatMessage,
CancelTaskResponse,
diff --git a/packages/views/chat/components/chat-fab.tsx b/packages/views/chat/components/chat-fab.tsx
index 2e17e11581..8c93239159 100644
--- a/packages/views/chat/components/chat-fab.tsx
+++ b/packages/views/chat/components/chat-fab.tsx
@@ -4,7 +4,7 @@ import { MessageCircle } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { cn } from "@multica/ui/lib/utils";
import { useChatStore } from "@multica/core/chat";
-import { chatSessionsOptions, pendingChatTasksOptions } from "@multica/core/chat/queries";
+import { chatSessionsOptions, hasPendingChatTasksOptions } from "@multica/core/chat/queries";
import { useWorkspaceId } from "@multica/core/hooks";
import { createLogger } from "@multica/core/logger";
import {
@@ -22,12 +22,19 @@ export function ChatFab() {
const isOpen = useChatStore((s) => s.isOpen);
const toggle = useChatStore((s) => s.toggle);
const { data: sessions = [] } = useQuery(chatSessionsOptions(wsId));
- const { data: pending } = useQuery(pendingChatTasksOptions(wsId));
+ // FAB only needs a boolean "is anything running", and only while the window
+ // is closed (when open, ChatWindow owns the detailed pending query). Gating
+ // on `enabled: !isOpen` keeps the minimised button off the per-message
+ // aggregate hot path entirely (MUL-4159).
+ const { data: hasPending } = useQuery({
+ ...hasPendingChatTasksOptions(wsId),
+ enabled: !isOpen,
+ });
if (isOpen) return null;
const unreadSessionCount = sessions.filter((s) => s.has_unread).length;
- const isRunning = (pending?.tasks ?? []).length > 0;
+ const isRunning = hasPending?.has_pending ?? false;
const handleClick = () => {
logger.info("fab.click (open chat)", { unreadSessionCount, isRunning });
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index efe862131b..1c6ecaa92f 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1247,6 +1247,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
})
})
r.Get("/api/chat/pending-tasks", h.ListPendingChatTasks)
+ r.Get("/api/chat/pending-tasks/has-any", h.HasPendingChatTasks)
// Agent-facing channel reads (MUL-3871). The caller's task-scoped token
// resolves to its own chat session; no session/channel id is passed, so
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index ed9a1c66df..b53747a075 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -778,50 +778,101 @@ func (h *Handler) ListPendingChatTasks(w http.ResponseWriter, r *http.Request) {
return
}
- rows, err := h.Queries.ListPendingChatTasksByCreator(r.Context(), db.ListPendingChatTasksByCreatorParams{
- WorkspaceID: parseUUID(workspaceID),
- CreatorID: parseUUID(userID),
- })
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to list pending chat tasks")
+ // No accessible agents → every row would be filtered out anyway. Skip the
+ // DB round-trip and return an empty list (mirrors HasPendingChatTasks).
+ if len(allowed) == 0 {
+ writeJSON(w, http.StatusOK, PendingChatTasksResponse{Tasks: []PendingChatTaskItem{}})
return
}
- // Map session → agent so we can filter without an N+1. The user's own
- // session list is small, so one extra query is cheaper than per-row
- // lookups.
- sessions, err := h.Queries.ListAllChatSessionsByCreator(r.Context(), db.ListAllChatSessionsByCreatorParams{
+ rows, err := h.Queries.ListPendingChatTasksByCreator(r.Context(), db.ListPendingChatTasksByCreatorParams{
WorkspaceID: parseUUID(workspaceID),
CreatorID: parseUUID(userID),
})
if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to resolve chat session agents")
+ writeError(w, http.StatusInternalServerError, "failed to list pending chat tasks")
return
}
- sessionAgent := make(map[string]string, len(sessions))
- for _, s := range sessions {
- sessionAgent[uuidToString(s.ID)] = uuidToString(s.AgentID)
- }
+ // The pending query now returns cs.agent_id per row, so we can filter
+ // out private agents the caller has lost access to directly against the
+ // already-loaded `allowed` set — no second ListAllChatSessionsByCreator
+ // scan on this hot path (MUL-4159).
items := make([]PendingChatTaskItem, 0, len(rows))
for _, row := range rows {
- sessionID := uuidToString(row.ChatSessionID)
- agentID, hasAgent := sessionAgent[sessionID]
- if !hasAgent {
- continue
- }
+ agentID := uuidToString(row.AgentID)
if _, ok := allowed[agentID]; !ok {
continue
}
items = append(items, PendingChatTaskItem{
TaskID: uuidToString(row.TaskID),
Status: row.Status,
- ChatSessionID: sessionID,
+ ChatSessionID: uuidToString(row.ChatSessionID),
})
}
writeJSON(w, http.StatusOK, PendingChatTasksResponse{Tasks: items})
}
+// HasPendingChatTasksResponse is the boolean fast-path payload consumed by the
+// FAB, which only needs to know whether any in-flight chat task exists — not
+// the full list.
+type HasPendingChatTasksResponse struct {
+ HasPending bool `json:"has_pending"`
+}
+
+// HasPendingChatTasks answers "does the current user have any in-flight chat
+// task in this workspace?" with a single EXISTS query, for the FAB's running
+// indicator. It is the boolean sibling of ListPendingChatTasks: the detailed
+// list is reserved for the ChatWindow history / stop-task flows.
+//
+// Permission filtering is preserved end-to-end: the set of agents the caller
+// may currently see is resolved the same way as ListPendingChatTasks and
+// pushed into the query as agent_ids, so a member who lost access to a private
+// agent never sees a true from a task on that agent (MUL-4159). An empty
+// accessible-agent set short-circuits to false without hitting the DB.
+func (h *Handler) HasPendingChatTasks(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+
+ member, ok := h.workspaceMember(w, r, workspaceID)
+ if !ok {
+ return
+ }
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ allowed, ok := h.accessibleAgentIDs(r.Context(), workspaceID, actorType, actorID, member.Role)
+ if !ok {
+ writeError(w, http.StatusInternalServerError, "failed to resolve agent access")
+ return
+ }
+
+ // No accessible agents → nothing the caller may see can be pending.
+ // Skip the round-trip and return false.
+ if len(allowed) == 0 {
+ writeJSON(w, http.StatusOK, HasPendingChatTasksResponse{HasPending: false})
+ return
+ }
+
+ agentIDs := make([]pgtype.UUID, 0, len(allowed))
+ for id := range allowed {
+ agentIDs = append(agentIDs, parseUUID(id))
+ }
+
+ hasPending, err := h.Queries.HasPendingChatTasksByCreator(r.Context(), db.HasPendingChatTasksByCreatorParams{
+ WorkspaceID: parseUUID(workspaceID),
+ CreatorID: parseUUID(userID),
+ AgentIds: agentIDs,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to check pending chat tasks")
+ return
+ }
+
+ writeJSON(w, http.StatusOK, HasPendingChatTasksResponse{HasPending: hasPending})
+}
+
// GetPendingChatTask returns the most recent in-flight task (queued / dispatched
// / running) for a chat session. The frontend polls this on mount / session
// switch so pending UI state survives refresh and reopen.
diff --git a/server/internal/handler/chat_pending_tasks_test.go b/server/internal/handler/chat_pending_tasks_test.go
new file mode 100644
index 0000000000..1a973576cf
--- /dev/null
+++ b/server/internal/handler/chat_pending_tasks_test.go
@@ -0,0 +1,277 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// chatPendingCtxAs injects the workspace + member context that the chi
+// workspace middleware would normally set, resolved for an arbitrary user.
+// The pending-tasks handlers read the workspace id from ctxWorkspaceID and the
+// caller's role from the member context, so a direct handler call needs both.
+func chatPendingCtxAs(t *testing.T, req *http.Request, userID string) *http.Request {
+ t.Helper()
+ memberRow, err := testHandler.Queries.GetMemberByUserAndWorkspace(context.Background(), db.GetMemberByUserAndWorkspaceParams{
+ UserID: util.MustParseUUID(userID),
+ WorkspaceID: util.MustParseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatalf("load member row for %s: %v", userID, err)
+ }
+ return req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, memberRow))
+}
+
+// insertChatSessionAs inserts a chat_session owned by an explicit creator +
+// agent (createHandlerTestChatSession hardcodes testUserID as creator, which
+// these permission tests need to vary).
+func insertChatSessionAs(t *testing.T, agentID, creatorID string) string {
+ t.Helper()
+ var sessionID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status)
+ VALUES ($1, $2, $3, 'pending-tasks-test', 'active')
+ RETURNING id
+ `, testWorkspaceID, agentID, creatorID).Scan(&sessionID); err != nil {
+ t.Fatalf("insert chat session: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, sessionID)
+ })
+ return sessionID
+}
+
+// insertPendingChatTask seeds an in-flight agent_task_queue row bound to a chat
+// session and returns its id.
+func insertPendingChatTask(t *testing.T, agentID, sessionID, status string) string {
+ t.Helper()
+ var taskID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, chat_session_id)
+ VALUES ($1, $2, $3, 0, $4)
+ RETURNING id
+ `, agentID, handlerTestRuntimeID(t), status, sessionID).Scan(&taskID); err != nil {
+ t.Fatalf("insert pending chat task: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ })
+ return taskID
+}
+
+func decodePendingTasks(t *testing.T, w *httptest.ResponseRecorder) PendingChatTasksResponse {
+ t.Helper()
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp PendingChatTasksResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode pending tasks: %v", err)
+ }
+ return resp
+}
+
+func decodeHasPending(t *testing.T, w *httptest.ResponseRecorder) bool {
+ t.Helper()
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp HasPendingChatTasksResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode has-any: %v", err)
+ }
+ return resp.HasPending
+}
+
+func containsPendingTask(tasks []PendingChatTaskItem, taskID string) bool {
+ for _, it := range tasks {
+ if it.TaskID == taskID {
+ return true
+ }
+ }
+ return false
+}
+
+// TestListPendingChatTasks_HidesPrivateAgentFromLostAccessCreator verifies the
+// P1 rewrite still enforces the private-agent gate now that filtering keys off
+// the agent_id returned by the query (instead of a second session-list scan).
+// A member who created a chat with a private agent they can no longer access
+// must not see that task in the aggregate, while a task on a workspace-visible
+// agent they still own is returned.
+func TestListPendingChatTasks_HidesPrivateAgentFromLostAccessCreator(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ privateAgentID, _, memberID := privateAgentTestFixture(t)
+ publicAgentID := createHandlerTestAgent(t, "PendingPublicAgent", []byte("[]"))
+
+ // The plain member is the creator of BOTH sessions, so the creator_id
+ // filter admits both; only the private-agent gate should drop one.
+ privateSession := insertChatSessionAs(t, privateAgentID, memberID)
+ publicSession := insertChatSessionAs(t, publicAgentID, memberID)
+ privateTask := insertPendingChatTask(t, privateAgentID, privateSession, "running")
+ publicTask := insertPendingChatTask(t, publicAgentID, publicSession, "queued")
+
+ w := httptest.NewRecorder()
+ testHandler.ListPendingChatTasks(w, chatPendingCtxAs(t, newRequestAs(memberID, "GET", "/api/chat/pending-tasks", nil), memberID))
+ resp := decodePendingTasks(t, w)
+
+ if containsPendingTask(resp.Tasks, privateTask) {
+ t.Fatalf("private-agent task %s leaked to plain member: %+v", privateTask, resp.Tasks)
+ }
+ if !containsPendingTask(resp.Tasks, publicTask) {
+ t.Fatalf("public-agent task %s missing from plain member's pending list: %+v", publicTask, resp.Tasks)
+ }
+}
+
+// TestListPendingChatTasks_OwnerSeesPrivateAgentTask is the positive control:
+// the agent owner keeps visibility of their own private-agent chat task.
+func TestListPendingChatTasks_OwnerSeesPrivateAgentTask(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ privateAgentID, ownerID, _ := privateAgentTestFixture(t)
+ session := insertChatSessionAs(t, privateAgentID, ownerID)
+ task := insertPendingChatTask(t, privateAgentID, session, "running")
+
+ w := httptest.NewRecorder()
+ testHandler.ListPendingChatTasks(w, chatPendingCtxAs(t, newRequestAs(ownerID, "GET", "/api/chat/pending-tasks", nil), ownerID))
+ resp := decodePendingTasks(t, w)
+
+ if !containsPendingTask(resp.Tasks, task) {
+ t.Fatalf("agent owner did not see their own private-agent task %s: %+v", task, resp.Tasks)
+ }
+}
+
+// TestHasPendingChatTasks_FalseWhenOnlyInaccessiblePrivateAgent verifies the P3
+// boolean endpoint preserves the same permission filtering as the list: a
+// member whose only in-flight task is on a private agent they can't access
+// gets has_pending=false (the FAB must not light up for a task they've lost
+// access to).
+func TestHasPendingChatTasks_FalseWhenOnlyInaccessiblePrivateAgent(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ privateAgentID, _, memberID := privateAgentTestFixture(t)
+ session := insertChatSessionAs(t, privateAgentID, memberID)
+ insertPendingChatTask(t, privateAgentID, session, "running")
+
+ w := httptest.NewRecorder()
+ testHandler.HasPendingChatTasks(w, chatPendingCtxAs(t, newRequestAs(memberID, "GET", "/api/chat/pending-tasks/has-any", nil), memberID))
+ if decodeHasPending(t, w) {
+ t.Fatalf("has-any returned true for a task on a private agent the member cannot access")
+ }
+}
+
+// TestHasPendingChatTasks_TrueWhenAccessiblePublicAgent verifies the boolean
+// endpoint returns true once the member has an in-flight task on an agent they
+// can access — and that an inaccessible private-agent task alongside it does
+// not change the (already true) answer.
+func TestHasPendingChatTasks_TrueWhenAccessiblePublicAgent(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ privateAgentID, _, memberID := privateAgentTestFixture(t)
+ publicAgentID := createHandlerTestAgent(t, "PendingPublicAgentHasAny", []byte("[]"))
+
+ privateSession := insertChatSessionAs(t, privateAgentID, memberID)
+ publicSession := insertChatSessionAs(t, publicAgentID, memberID)
+ insertPendingChatTask(t, privateAgentID, privateSession, "running")
+ insertPendingChatTask(t, publicAgentID, publicSession, "waiting_local_directory")
+
+ w := httptest.NewRecorder()
+ testHandler.HasPendingChatTasks(w, chatPendingCtxAs(t, newRequestAs(memberID, "GET", "/api/chat/pending-tasks/has-any", nil), memberID))
+ if !decodeHasPending(t, w) {
+ t.Fatalf("has-any returned false despite an in-flight task on an accessible public agent")
+ }
+}
+
+// TestHasPendingChatTasks_OwnerOfPrivateAgentSeesTask confirms the boolean
+// endpoint's positive path for a private agent's owner.
+func TestHasPendingChatTasks_OwnerOfPrivateAgentSeesTask(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ privateAgentID, ownerID, _ := privateAgentTestFixture(t)
+ session := insertChatSessionAs(t, privateAgentID, ownerID)
+ insertPendingChatTask(t, privateAgentID, session, "dispatched")
+
+ w := httptest.NewRecorder()
+ testHandler.HasPendingChatTasks(w, chatPendingCtxAs(t, newRequestAs(ownerID, "GET", "/api/chat/pending-tasks/has-any", nil), ownerID))
+ if !decodeHasPending(t, w) {
+ t.Fatalf("has-any returned false for the private agent's own owner")
+ }
+}
+
+// TestHasPendingChatTasks_IgnoresTerminalTasks guards the status predicate: a
+// completed task is not "pending", so the endpoint must return false.
+func TestHasPendingChatTasks_IgnoresTerminalTasks(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ // Use a freshly-created member (via the private-agent fixture) as the
+ // creator so no stray in-flight task from another test can bleed into the
+ // assertion — this user exists only for the duration of this test.
+ _, _, memberID := privateAgentTestFixture(t)
+ publicAgentID := createHandlerTestAgent(t, "PendingTerminalAgent", []byte("[]"))
+ session := insertChatSessionAs(t, publicAgentID, memberID)
+ insertPendingChatTask(t, publicAgentID, session, "completed")
+
+ w := httptest.NewRecorder()
+ testHandler.HasPendingChatTasks(w, chatPendingCtxAs(t, newRequestAs(memberID, "GET", "/api/chat/pending-tasks/has-any", nil), memberID))
+ if decodeHasPending(t, w) {
+ t.Fatalf("has-any returned true for a terminal (completed) task")
+ }
+}
+
+
+// TestHasPendingChatTasks_HidesOtherCreatorsTask locks the cs.creator_id gate:
+// user A's in-flight task on a workspace-visible agent — one B can freely
+// access — must still return has_pending=false for B, because B is not the
+// creator. This is the tenant boundary that the agent-visibility filter does
+// NOT cover (both users can see the agent), so it needs its own guard.
+func TestHasPendingChatTasks_HidesOtherCreatorsTask(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ // ownerID = user A (task creator), memberID = user B (different member).
+ // Both are plain workspace members who can access a workspace-visible agent.
+ _, creatorA, otherB := privateAgentTestFixture(t)
+ publicAgentID := createHandlerTestAgent(t, "PendingCrossCreatorAgent", []byte("[]"))
+ session := insertChatSessionAs(t, publicAgentID, creatorA)
+ insertPendingChatTask(t, publicAgentID, session, "running")
+
+ // B is not the creator → the creator_id filter must drop A's task.
+ w := httptest.NewRecorder()
+ testHandler.HasPendingChatTasks(w, chatPendingCtxAs(t, newRequestAs(otherB, "GET", "/api/chat/pending-tasks/has-any", nil), otherB))
+ if decodeHasPending(t, w) {
+ t.Fatalf("has-any leaked user A's task to user B (cs.creator_id gate not enforced)")
+ }
+
+ // Sanity: A (the creator) does see their own task on the same agent.
+ w = httptest.NewRecorder()
+ testHandler.HasPendingChatTasks(w, chatPendingCtxAs(t, newRequestAs(creatorA, "GET", "/api/chat/pending-tasks/has-any", nil), creatorA))
+ if !decodeHasPending(t, w) {
+ t.Fatalf("has-any returned false for the task's own creator")
+ }
+
+ // The detailed list endpoint enforces the same creator gate.
+ w = httptest.NewRecorder()
+ testHandler.ListPendingChatTasks(w, chatPendingCtxAs(t, newRequestAs(otherB, "GET", "/api/chat/pending-tasks", nil), otherB))
+ if resp := decodePendingTasks(t, w); len(resp.Tasks) != 0 {
+ t.Fatalf("list leaked user A's task to user B: %+v", resp.Tasks)
+ }
+}
\ No newline at end of file
diff --git a/server/migrations/143_agent_task_queue_chat_pending_v2.down.sql b/server/migrations/143_agent_task_queue_chat_pending_v2.down.sql
new file mode 100644
index 0000000000..88092b7de2
--- /dev/null
+++ b/server/migrations/143_agent_task_queue_chat_pending_v2.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_chat_pending_v2;
diff --git a/server/migrations/143_agent_task_queue_chat_pending_v2.up.sql b/server/migrations/143_agent_task_queue_chat_pending_v2.up.sql
new file mode 100644
index 0000000000..444393686d
--- /dev/null
+++ b/server/migrations/143_agent_task_queue_chat_pending_v2.up.sql
@@ -0,0 +1,25 @@
+-- Fix a partial-index predicate mismatch on agent_task_queue (MUL-4159).
+--
+-- Migration 040 created idx_agent_task_queue_chat_pending with the predicate
+-- `status IN ('queued', 'dispatched', 'running')`. Migration 109 later added a
+-- fourth in-flight status, `waiting_local_directory`, and both pending chat
+-- queries (GetPendingChatTask, ListPendingChatTasksByCreator) now filter on all
+-- four statuses. Postgres only uses a partial index when it can prove the query
+-- predicate is a subset of the index predicate; the extra status made the old
+-- index an unusable candidate, so those queries degraded to a Seq Scan on
+-- agent_task_queue (or a non-optimal FK path), which is the root cause of the
+-- high DB load on this path.
+--
+-- This v2 index restores index coverage by including all four in-flight
+-- statuses. The column list (chat_session_id, created_at DESC) is unchanged so
+-- it keeps serving the single-session GetPendingChatTask lookup as well.
+--
+-- The old index is dropped in a separate migration (144) after this one has
+-- built and been verified in EXPLAIN, per the repo convention of never mixing
+-- multiple CONCURRENTLY statements in one migration. This file must stay
+-- single-statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction
+-- or multi-command string.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_chat_pending_v2
+ ON agent_task_queue (chat_session_id, created_at DESC)
+ WHERE chat_session_id IS NOT NULL
+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory');
diff --git a/server/migrations/144_drop_agent_task_queue_chat_pending_v1.down.sql b/server/migrations/144_drop_agent_task_queue_chat_pending_v1.down.sql
new file mode 100644
index 0000000000..d00766fadb
--- /dev/null
+++ b/server/migrations/144_drop_agent_task_queue_chat_pending_v1.down.sql
@@ -0,0 +1,6 @@
+-- Recreate the original three-status partial index from migration 040.
+-- Single-statement CONCURRENTLY per repo convention.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_chat_pending
+ ON agent_task_queue (chat_session_id, created_at DESC)
+ WHERE chat_session_id IS NOT NULL
+ AND status IN ('queued', 'dispatched', 'running');
diff --git a/server/migrations/144_drop_agent_task_queue_chat_pending_v1.up.sql b/server/migrations/144_drop_agent_task_queue_chat_pending_v1.up.sql
new file mode 100644
index 0000000000..725bce746f
--- /dev/null
+++ b/server/migrations/144_drop_agent_task_queue_chat_pending_v1.up.sql
@@ -0,0 +1,12 @@
+-- Drop the superseded partial index from migration 040 (MUL-4159).
+--
+-- idx_agent_task_queue_chat_pending_v2 (migration 143) covers all four
+-- in-flight statuses and the same (chat_session_id, created_at DESC) column
+-- list, so it fully serves both GetPendingChatTask and
+-- ListPendingChatTasksByCreator. The old three-status index is now dead weight
+-- on the write path and can be removed once 143 is verified via EXPLAIN.
+--
+-- Split into its own migration so this file holds a single CONCURRENTLY
+-- statement (repo convention); CREATE/DROP INDEX CONCURRENTLY cannot run inside
+-- a transaction or multi-command string.
+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_chat_pending;
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index aaac155924..a616848d64 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -377,6 +377,41 @@ func (q *Queries) GetPendingChatTask(ctx context.Context, chatSessionID pgtype.U
return i, err
}
+const hasPendingChatTasksByCreator = `-- name: HasPendingChatTasksByCreator :one
+SELECT EXISTS (
+ SELECT 1
+ FROM agent_task_queue atq
+ JOIN chat_session cs ON cs.id = atq.chat_session_id
+ WHERE atq.chat_session_id IS NOT NULL
+ AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ AND cs.workspace_id = $1
+ AND cs.creator_id = $2
+ AND cs.agent_id = ANY($3::uuid[])
+) AS has_pending
+`
+
+type HasPendingChatTasksByCreatorParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ CreatorID pgtype.UUID `json:"creator_id"`
+ AgentIds []pgtype.UUID `json:"agent_ids"`
+}
+
+// Boolean fast-path for the FAB's "running" indicator. Returns a single
+// EXISTS row instead of the full task list, so the planner can stop at the
+// first matching in-flight task (LIMIT 1 semantics via EXISTS).
+//
+// Permission filtering is baked into the query: agent_id = ANY($3) restricts
+// the result to the agents the caller may currently see, so a member who lost
+// access to a private agent never gets a true from a task they can no longer
+// reach. The handler must pass its resolved accessible-agent id set as $3;
+// an empty array yields false.
+func (q *Queries) HasPendingChatTasksByCreator(ctx context.Context, arg HasPendingChatTasksByCreatorParams) (bool, error) {
+ row := q.db.QueryRow(ctx, hasPendingChatTasksByCreator, arg.WorkspaceID, arg.CreatorID, arg.AgentIds)
+ var has_pending bool
+ err := row.Scan(&has_pending)
+ return has_pending, err
+}
+
const linkChatMessageToTask = `-- name: LinkChatMessageToTask :exec
UPDATE chat_message
SET task_id = $2
@@ -610,12 +645,13 @@ func (q *Queries) ListChatSessionsByCreator(ctx context.Context, arg ListChatSes
}
const listPendingChatTasksByCreator = `-- name: ListPendingChatTasksByCreator :many
-SELECT atq.id AS task_id, atq.status, atq.chat_session_id
+SELECT atq.id AS task_id, atq.status, atq.chat_session_id, cs.agent_id
FROM agent_task_queue atq
JOIN chat_session cs ON cs.id = atq.chat_session_id
-WHERE cs.workspace_id = $1
- AND cs.creator_id = $2
+WHERE atq.chat_session_id IS NOT NULL
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ AND cs.workspace_id = $1
+ AND cs.creator_id = $2
ORDER BY atq.created_at DESC
`
@@ -628,11 +664,20 @@ type ListPendingChatTasksByCreatorRow struct {
TaskID pgtype.UUID `json:"task_id"`
Status string `json:"status"`
ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
}
// Aggregate view of all in-flight chat tasks owned by a given creator in a
// workspace. Drives the FAB's "running" indicator when the chat window is
// closed and no single session's query is active.
+//
+// Returns cs.agent_id so the handler can filter tasks belonging to private
+// agents the caller has lost access to using the already-loaded `allowed`
+// set — no second ListAllChatSessionsByCreator scan on the hot path.
+//
+// atq.chat_session_id IS NOT NULL is redundant given the JOIN, but stated
+// explicitly so the planner can prove the query predicate is a subset of the
+// idx_agent_task_queue_chat_pending_v2 partial-index predicate and use it.
func (q *Queries) ListPendingChatTasksByCreator(ctx context.Context, arg ListPendingChatTasksByCreatorParams) ([]ListPendingChatTasksByCreatorRow, error) {
rows, err := q.db.Query(ctx, listPendingChatTasksByCreator, arg.WorkspaceID, arg.CreatorID)
if err != nil {
@@ -642,7 +687,12 @@ func (q *Queries) ListPendingChatTasksByCreator(ctx context.Context, arg ListPen
items := []ListPendingChatTasksByCreatorRow{}
for rows.Next() {
var i ListPendingChatTasksByCreatorRow
- if err := rows.Scan(&i.TaskID, &i.Status, &i.ChatSessionID); err != nil {
+ if err := rows.Scan(
+ &i.TaskID,
+ &i.Status,
+ &i.ChatSessionID,
+ &i.AgentID,
+ ); err != nil {
return nil, err
}
items = append(items, i)
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 87f34d5b71..0790887024 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -159,14 +159,44 @@ LIMIT 1;
-- Aggregate view of all in-flight chat tasks owned by a given creator in a
-- workspace. Drives the FAB's "running" indicator when the chat window is
-- closed and no single session's query is active.
-SELECT atq.id AS task_id, atq.status, atq.chat_session_id
+--
+-- Returns cs.agent_id so the handler can filter tasks belonging to private
+-- agents the caller has lost access to using the already-loaded `allowed`
+-- set — no second ListAllChatSessionsByCreator scan on the hot path.
+--
+-- atq.chat_session_id IS NOT NULL is redundant given the JOIN, but stated
+-- explicitly so the planner can prove the query predicate is a subset of the
+-- idx_agent_task_queue_chat_pending_v2 partial-index predicate and use it.
+SELECT atq.id AS task_id, atq.status, atq.chat_session_id, cs.agent_id
FROM agent_task_queue atq
JOIN chat_session cs ON cs.id = atq.chat_session_id
-WHERE cs.workspace_id = $1
- AND cs.creator_id = $2
+WHERE atq.chat_session_id IS NOT NULL
AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ AND cs.workspace_id = $1
+ AND cs.creator_id = $2
ORDER BY atq.created_at DESC;
+-- name: HasPendingChatTasksByCreator :one
+-- Boolean fast-path for the FAB's "running" indicator. Returns a single
+-- EXISTS row instead of the full task list, so the planner can stop at the
+-- first matching in-flight task (LIMIT 1 semantics via EXISTS).
+--
+-- Permission filtering is baked into the query: agent_id = ANY($3) restricts
+-- the result to the agents the caller may currently see, so a member who lost
+-- access to a private agent never gets a true from a task they can no longer
+-- reach. The handler must pass its resolved accessible-agent id set as $3;
+-- an empty array yields false.
+SELECT EXISTS (
+ SELECT 1
+ FROM agent_task_queue atq
+ JOIN chat_session cs ON cs.id = atq.chat_session_id
+ WHERE atq.chat_session_id IS NOT NULL
+ AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')
+ AND cs.workspace_id = sqlc.arg(workspace_id)
+ AND cs.creator_id = sqlc.arg(creator_id)
+ AND cs.agent_id = ANY(sqlc.arg(agent_ids)::uuid[])
+) AS has_pending;
+
-- name: MarkChatSessionRead :exec
-- Clears unread_since, dropping the session's unread count to 0.
UPDATE chat_session SET unread_since = NULL