Skip to content

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

Go

perf(issues): limit working-agent refresh queries (MUL-7838 PR2) (#9005)

Multica Eveda540ea6eedf
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index 438ef422d4..aeaea6c8a6 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -1,8 +1,8 @@
/**
* @vitest-environment jsdom
*/
-import { QueryClient, QueryClientProvider, type InvalidateQueryFilters } from "@tanstack/react-query";
-import { renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider, QueryObserver, type InvalidateQueryFilters, type QueryKey } from "@tanstack/react-query";
+import { cleanup, renderHook, waitFor } from "@testing-library/react";
import type { ReactNode } from "react";
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import type { WSClient } from "../api/ws-client";
@@ -19,6 +19,8 @@ import {
} from "../workspace/pending-delete";
import { setApiInstance } from "../api";
import type { ApiClient } from "../api/client";
+import type { IssueTableQuerySpec } from "../types";
+import { getCurrentWsId } from "../platform/workspace-storage";
import { forgetLocalSearchIndex } from "../search-index/instance";
import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";
@@ -27,7 +29,7 @@ vi.mock("../search-index/instance", () => ({
}));
vi.mock("../platform/workspace-storage", () => ({
- getCurrentWsId: () => "ws-1",
+ getCurrentWsId: vi.fn(() => "ws-1"),
getCurrentSlug: () => "test-ws",
// Draft stores are now loaded transitively (storage-cleanup → register-all-drafts)
// so their persist wiring must resolve against this mock.
@@ -379,33 +381,158 @@ describe("useRealtimeSync — Table server membership invalidation", () => {
let stores: RealtimeSyncStores;
beforeEach(() => {
- qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
stores = createStores();
});
afterEach(() => {
+ cleanup();
+ qc.clear();
+ vi.mocked(getCurrentWsId).mockReturnValue("ws-1");
vi.useRealTimers();
});
- it("invalidates Table queries after a task lifecycle event", () => {
+ const spec: IssueTableQuerySpec = {
+ scope: { kind: "workspace" },
+ filters: {},
+ sort: { field: "position", direction: "asc" },
+ };
+ const workingFacet = (wsId = "ws-1") => issueKeys.tableFacets(wsId, {
+ query: spec, facets: [{ kind: "working_agents" }],
+ });
+
+ function mountRealtime() {
vi.useFakeTimers();
const ws = createMockWs();
- const invalidate = vi.spyOn(qc, "invalidateQueries");
- renderHook(() => useRealtimeSync(ws, stores), {
+ const hook = renderHook(() => useRealtimeSync(ws, stores), {
wrapper: createWrapper(qc),
});
- const onAny = vi.mocked(ws.onAny).mock.calls[0]?.[0];
- expect(onAny).toBeDefined();
+ const onAny = vi.mocked(ws.onAny).mock.calls[0]![0];
+ return { ...hook, emit: (type: string) => onAny({ type, payload: {} } as never) };
+ }
+
+ it("only invalidates working facets and queries whose membership depends on working state", async () => {
+ const { emit } = mountRealtime();
+ const untouched: QueryKey[] = [workingFacet("ws-2")];
+ const affected: QueryKey[] = [workingFacet(), workspaceWorkingAgentsKeys.list("ws-1", "issue")];
+ // Test both server membership forms, including an explicit empty id set,
+ // across rows, descriptors and ordinary facets such as status counts.
+ const filterCases: IssueTableQuerySpec["filters"][] = [{}, { working_only: false }, { working_only: true }, { working_issue_ids: [] }, { working_issue_ids: ["i1"] }];
+ for (const filters of filterCases) {
+ const query = { ...spec, filters };
+ const keys = [
+ issueKeys.tableRows("ws-1", query, { kind: "none" }, null, false, null),
+ issueKeys.tableGroups("ws-1", query, { kind: "status" }),
+ issueKeys.tableFacets("ws-1", { query, facets: [{ kind: "status" }] }),
+ ];
+ (filters.working_only || filters.working_issue_ids ? affected : untouched).push(...keys);
+ }
+ for (const key of [...untouched, ...affected]) qc.setQueryData(key, []);
+ emit("task:completed");
+ await vi.advanceTimersByTimeAsync(1_000);
+ for (const key of affected) expect(qc.getQueryState(key)?.isInvalidated).toBe(true);
+ for (const key of untouched) expect(qc.getQueryState(key)?.isInvalidated).toBe(false);
+ });
- onAny!({ type: "task:completed", payload: {} } as never);
- vi.advanceTimersByTime(100);
+ it("coalesces a continuous lifecycle stream and eventually clears the final completed run", async () => {
+ const { emit } = mountRealtime();
+ let count = 1;
+ const queryFn = vi.fn(async () => count);
+ qc.setQueryData(workingFacet(), count);
+ const observer = new QueryObserver(qc, { queryKey: workingFacet(), queryFn });
+ const unsubscribe = observer.subscribe(() => {});
+ for (let i = 0; i < 20; i++) {
+ emit(i % 2 ? "agent:updated" : "task:started");
+ await vi.advanceTimersByTimeAsync(200);
+ }
+ expect(queryFn).toHaveBeenCalledTimes(4);
+ count = 0;
+ emit("task:completed");
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(queryFn).toHaveBeenCalledTimes(5);
+ expect(observer.getCurrentResult().data).toBe(0);
+ unsubscribe();
+ });
- expect(invalidate).toHaveBeenCalledWith({
- queryKey: issueKeys.tableAll("ws-1"),
- });
- expect(invalidate).toHaveBeenCalledWith({
- queryKey: workspaceWorkingAgentsKeys.all("ws-1"),
- });
+ it.each(["facet", "projection"])("restarts an in-flight first %s request after completion instead of accepting its stale response", async (kind) => {
+ const { emit } = mountRealtime();
+ const queryKey = kind === "facet" ? workingFacet() : workspaceWorkingAgentsKeys.list("ws-1", "issue");
+ let finishFirst!: (value: number) => void;
+ const queryFn = vi.fn(async () => 0).mockImplementationOnce(() => new Promise<number>((resolve) => { finishFirst = resolve; }));
+ const observer = new QueryObserver(qc, { queryKey, queryFn });
+ const unsubscribe = observer.subscribe(() => {});
+ emit("task:completed");
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(queryFn).toHaveBeenCalledTimes(2);
+ expect(observer.getCurrentResult().data).toBe(0);
+ finishFirst(1);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(observer.getCurrentResult().data).toBe(0);
+ unsubscribe();
+ });
+
+ it("lets slow refreshes finish and performs a trailing refresh for events received in flight", async () => {
+ const { emit } = mountRealtime();
+ let finishSlow!: (value: number) => void;
+ const queryFn = vi.fn(async () => 0).mockImplementationOnce(() => new Promise<number>((resolve) => { finishSlow = resolve; }));
+ qc.setQueryData(workingFacet(), 1);
+ const observer = new QueryObserver(qc, { queryKey: workingFacet(), queryFn });
+ const unsubscribe = observer.subscribe(() => {});
+ emit("task:started");
+ await vi.advanceTimersByTimeAsync(1_000);
+ for (let i = 0; i < 10; i++) {
+ emit("task:completed");
+ await vi.advanceTimersByTimeAsync(200);
+ }
+ expect(queryFn).toHaveBeenCalledTimes(1);
+ finishSlow(1);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(queryFn).toHaveBeenCalledTimes(2);
+ expect(observer.getCurrentResult().data).toBe(0);
+ unsubscribe();
+ });
+
+ it("ignores progress/messages and discards a queued refresh on unmount", async () => {
+ const { emit, unmount } = mountRealtime();
+ qc.setQueryData(workingFacet(), []);
+ qc.setQueryData(workspaceWorkingAgentsKeys.list("ws-1", "issue"), []);
+ emit("task:progress");
+ emit("task:message");
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(qc.getQueryState(workingFacet())?.isInvalidated).toBe(false);
+ expect(qc.getQueryState(workspaceWorkingAgentsKeys.list("ws-1", "issue"))?.isInvalidated).toBe(false);
+ emit("task:completed");
+ unmount();
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(qc.getQueryState(workingFacet())?.isInvalidated).toBe(false);
+ });
+
+ it("keeps a queued refresh scoped to the workspace that received it", async () => {
+ const { emit } = mountRealtime();
+ qc.setQueryData(workingFacet(), []);
+ qc.setQueryData(workingFacet("ws-2"), []);
+ emit("task:completed");
+ vi.mocked(getCurrentWsId).mockReturnValue("ws-2");
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(qc.getQueryState(workingFacet())?.isInvalidated).toBe(true);
+ expect(qc.getQueryState(workingFacet("ws-2"))?.isInvalidated).toBe(false);
+ });
+
+ it("does not schedule a trailing refresh after unmounting during a slow request", async () => {
+ const { emit, unmount } = mountRealtime();
+ let finish!: (value: number) => void;
+ const queryFn = vi.fn(() => new Promise<number>((resolve) => { finish = resolve; }));
+ qc.setQueryData(workingFacet(), 1);
+ const observer = new QueryObserver(qc, { queryKey: workingFacet(), queryFn });
+ const unsubscribe = observer.subscribe(() => {});
+ emit("task:started");
+ await vi.advanceTimersByTimeAsync(1_000);
+ emit("task:completed");
+ unmount();
+ finish(0);
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(queryFn).toHaveBeenCalledTimes(1);
+ unsubscribe();
});
it("invalidates Table queries after a property definition changes", () => {
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 8ba91ca0f2..6bbe715f4b 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -2,7 +2,7 @@
import { useEffect, useRef } from "react";
import { forgetLocalSearchIndex } from "../search-index/instance";
-import { useQueryClient, type InfiniteData, type QueryClient } from "@tanstack/react-query";
+import { useQueryClient, type InfiniteData, type QueryClient, type QueryFilters } from "@tanstack/react-query";
import type { WSClient } from "../api/ws-client";
import type { StoreApi, UseBoundStore } from "zustand";
import type { AuthState } from "../auth/store";
@@ -73,6 +73,8 @@ import {
} from "../chat/pending";
import { resolvePostAuthDestination, useHasOnboarded } from "../paths";
import type {
+ IssueTableFacetsRequest,
+ IssueTableQuerySpec,
MemberAddedPayload,
WorkspaceDeletedPayload,
WorkspaceUpdatedPayload,
@@ -698,6 +700,36 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {
qc.invalidateQueries({ queryKey: workspaceKeys.list() });
}
+async function refreshWorkingAgentQueries(qc: QueryClient, wsId: string): Promise<void> {
+ const filters: QueryFilters[] = [
+ { queryKey: workspaceWorkingAgentsKeys.all(wsId) },
+ {
+ queryKey: issueKeys.tableAll(wsId),
+ predicate: ({ queryKey }) => {
+ const kind = queryKey[3];
+ let spec: IssueTableQuerySpec | undefined;
+ if (kind === "facets") {
+ const request = queryKey[4] as IssueTableFacetsRequest;
+ if (request.facets.some((facet) => facet.kind === "working_agents")) return true;
+ spec = request.query;
+ } else if (kind === "rows" || kind === "groups") {
+ spec = queryKey[4] as IssueTableQuerySpec;
+ }
+ // An explicit empty id list is still a working filter: its next
+ // projection may contain newly started work. Other facets also
+ // depend on this membership, not only rows and group descriptors.
+ return spec?.filters.working_only === true ||
+ spec?.filters.working_issue_ids !== undefined;
+ },
+ },
+ ];
+ // A lifecycle event during the FIRST fetch must not dedupe onto a response
+ // captured before that event. With staleTime=Infinity it could otherwise
+ // leave a completed run visible until another event happens to arrive.
+ await Promise.all(filters.map((filter) => qc.cancelQueries(filter)));
+ await Promise.all(filters.map((filter) => qc.invalidateQueries(filter)));
+}
+
function invalidateSquadMemberStatusQueries(qc: QueryClient, wsId: string): void {
qc.invalidateQueries({
predicate: (query) => {
@@ -768,7 +800,6 @@ export function useRealtimeSync(
const wsId = getCurrentWsId();
if (wsId) {
qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
- qc.invalidateQueries({ queryKey: workspaceWorkingAgentsKeys.all(wsId) });
// Squad members status is derived per agent, so any agent
// change (status flip, archive, runtime swap) needs to refresh the
// per-squad members-status cache without refetching the static squad
@@ -916,12 +947,7 @@ export function useRealtimeSync(
const wsId = getCurrentWsId();
if (!wsId) return;
qc.invalidateQueries({ queryKey: agentTaskSnapshotKeys.list(wsId) });
- qc.invalidateQueries({ queryKey: workspaceWorkingAgentsKeys.all(wsId) });
- // The Table working-agent shortcut derives an assignee set from the
- // projection above. Refresh its server-owned graph alongside that set
- // so rows/groups/facets cannot remain on an old task transition while
- // the projection refetches (global staleTime is Infinity).
- qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
+ // Working-agent projections have their own bounded refresh below.
// 30d activity series shares the same lifecycle signal — any task
// completion / failure shifts the histogram. (Dispatch alone
// doesn't change a completed_at-anchored series, but invalidating
@@ -965,6 +991,33 @@ export function useRealtimeSync(
},
};
+ const workingAgentTimers = new Map<string, ReturnType<typeof setTimeout>>();
+ const workingAgentInFlight = new Set<string>();
+ const workingAgentDirty = new Set<string>();
+ let disposed = false;
+ const scheduleWorkingAgentRefresh = (wsId: string) => {
+ // Flush one second after the FIRST event in a batch. Later events do
+ // not postpone it, so continuous activity cannot starve the projection.
+ // Capture the workspace now: navigation must not redirect a queued
+ // refresh into a different workspace's cache.
+ workingAgentDirty.add(wsId);
+ if (workingAgentTimers.has(wsId) || workingAgentInFlight.has(wsId)) return;
+ workingAgentTimers.set(wsId, setTimeout(async () => {
+ workingAgentTimers.delete(wsId);
+ workingAgentDirty.delete(wsId);
+ workingAgentInFlight.add(wsId);
+ try {
+ await refreshWorkingAgentQueries(qc, wsId);
+ } finally {
+ workingAgentInFlight.delete(wsId);
+ // Serialize slow requests: cancelling our own refresh every second
+ // would starve it under a continuous stream. Events received while
+ // it runs still get one trailing refresh, including the final stop.
+ if (!disposed && workingAgentDirty.has(wsId)) scheduleWorkingAgentRefresh(wsId);
+ }
+ }, 1_000));
+ };
+
const timers = new Map<string, ReturnType<typeof setTimeout>>();
const debouncedRefresh = (prefix: string, fn: () => void) => {
const existing = timers.get(prefix);
@@ -1007,6 +1060,10 @@ export function useRealtimeSync(
const unsubAny = ws.onAny((msg) => {
if (specificEvents.has(msg.type)) return;
const prefix = msg.type.split(":")[0] ?? "";
+ if (prefix === "agent" || (prefix === "task" && msg.type !== "task:progress")) {
+ const wsId = getCurrentWsId();
+ if (wsId) scheduleWorkingAgentRefresh(wsId);
+ }
const refresh = refreshMap[prefix];
if (refresh) debouncedRefresh(prefix, refresh);
});
@@ -1802,6 +1859,10 @@ export function useRealtimeSync(
if (aggregateRefreshTimer) clearTimeout(aggregateRefreshTimer);
timers.forEach(clearTimeout);
timers.clear();
+ disposed = true;
+ workingAgentTimers.forEach(clearTimeout);
+ workingAgentTimers.clear();
+ workingAgentDirty.clear();
};
}, [ws, qc, authStore, onToast]);
diff --git a/packages/views/issues/surface/issue-surface.test.tsx b/packages/views/issues/surface/issue-surface.test.tsx
index fd9700075d..9780ccde63 100644
--- a/packages/views/issues/surface/issue-surface.test.tsx
+++ b/packages/views/issues/surface/issue-surface.test.tsx
@@ -23,6 +23,7 @@ import type {
IssueTableRowsRequest,
ListIssuesParams,
ListIssuesResponse,
+ WorkspaceWorkingAgent,
} from "@multica/core/types";
import { IssueSurface, IssueSurfaceWithStore } from "./issue-surface";
import { createIssueStatusListStore } from "@multica/core/issue-statuses";
@@ -339,7 +340,7 @@ describe("IssueSurface — table pagination ownership", () => {
vi.restoreAllMocks();
});
- it("does not materialize the legacy offset window and starts one cursor root branch", async () => {
+ it("waits for working membership, offers retry on failure, and starts only the resolved cursor root branch", async () => {
const { getIssueSurfaceViewStore } = await import(
"@multica/core/issues/stores/surface-view-store"
);
@@ -354,6 +355,18 @@ describe("IssueSurface — table pagination ownership", () => {
status: "in_progress" as const,
}));
const listIssueTableRows = vi.fn(() => never());
+ let failMembership!: (reason: Error) => void;
+ const getWorkspaceWorkingAgents = vi.fn(async (): Promise<WorkspaceWorkingAgent[]> =>
+ runningIssues.map((issue, index) => ({
+ id: `agent-${index}`,
+ name: `Agent ${index}`,
+ avatar_url: null,
+ running_task_count: 1,
+ issue_ids: [issue.id],
+ })),
+ ).mockImplementationOnce(() => new Promise<WorkspaceWorkingAgent[]>((_, reject) => {
+ failMembership = reject;
+ }));
setApiInstance({
// The board pages by category, so every surface stub answers the catalog
// read. Empty is the real shape for a workspace with no custom statuses:
@@ -374,17 +387,7 @@ describe("IssueSurface — table pagination ownership", () => {
})) as unknown as AgentTask[],
),
),
- getWorkspaceWorkingAgents: vi.fn(() =>
- Promise.resolve(
- runningIssues.map((issue, index) => ({
- id: `agent-${index}`,
- name: `Agent ${index}`,
- avatar_url: null,
- running_task_count: 1,
- issue_ids: [issue.id],
- })),
- ),
- ),
+ getWorkspaceWorkingAgents,
getChildIssueProgress: vi.fn(() => never()),
listProperties: vi.fn(() => never()),
listMembers: vi.fn(() => never()),
@@ -404,11 +407,17 @@ describe("IssueSurface — table pagination ownership", () => {
</QueryClientProvider>,
);
- // The first render has not received the independent working-agents query
- // yet and therefore requests the explicit match-none form. Once that
- // query resolves, the Table owns a new query key containing the agent id
- // list and starts the real branch.
- await waitFor(() => expect(listIssueTableRows).toHaveBeenCalledTimes(2));
+ // Unknown membership must not mount an empty Table branch or show an
+ // empty-state claim. A failed initial request must provide recovery.
+ expect(screen.queryByTestId("surface-loading")).not.toBeNull();
+ expect(listIssueTableRows).not.toHaveBeenCalled();
+ await act(async () => failMembership(new Error("offline")));
+ const alert = await screen.findByRole("alert");
+ expect(screen.queryByTestId("surface-loading")).toBeNull();
+ expect(listIssueTableRows).not.toHaveBeenCalled();
+ fireEvent.click(alert.querySelector("button")!);
+ await waitFor(() => expect(listIssueTableRows).toHaveBeenCalledTimes(1));
+ expect(screen.queryByRole("alert")).toBeNull();
expect(listIssueTableRows).toHaveBeenLastCalledWith(
expect.objectContaining({
group: { kind: "none" },
diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsx
index 1c58345efc..15f8440726 100644
--- a/packages/views/issues/surface/issue-surface.tsx
+++ b/packages/views/issues/surface/issue-surface.tsx
@@ -292,7 +292,9 @@ function IssueSurfaceContent({
cannot be routed without it), so every branch below would render an
unexplained empty surface with no way out. (MUL-6243) */}
{controller.isStatusCatalogError ? (
- <StatusCatalogErrorState onRetry={controller.retryStatusCatalog} />
+ <FilterDependencyErrorState kind="status" onRetry={controller.retryStatusCatalog} />
+ ) : controller.isWorkingFilterError ? (
+ <FilterDependencyErrorState kind="working" onRetry={controller.retryWorkingFilter} />
) : controller.isLoading ? (
renderLoading ? (
renderLoading(renderContext)
@@ -402,12 +404,16 @@ function IssueSurfaceContent({
}
/**
- * Shown when the surface has rows but the active filters match none of them.
- * Shared by every surface, so no caller has to remember that its own empty
- * copy only describes the unfiltered case. The action clears exactly the
- * filters this state tests for, so it always restores content.
+ * Missing filter dependencies must offer recovery instead of claiming that
+ * the filter matched no issues.
*/
-function StatusCatalogErrorState({ onRetry }: { onRetry: () => void }) {
+function FilterDependencyErrorState({
+ kind,
+ onRetry,
+}: {
+ kind: "status" | "working";
+ onRetry: () => void;
+}) {
const { t } = useT("issues");
return (
<div
@@ -415,8 +421,14 @@ function StatusCatalogErrorState({ onRetry }: { onRetry: () => void }) {
className="flex flex-1 min-h-0 flex-col items-center justify-center gap-3 text-muted-foreground"
>
<AlertTriangle className="h-10 w-10 text-faint-foreground" />
- <p className="text-body">{t(($) => $.status_catalog_error.title)}</p>
- <p className="text-caption">{t(($) => $.status_catalog_error.hint)}</p>
+ <p className="text-body">
+ {kind === "working"
+ ? t(($) => $.working_filter_error.title)
+ : t(($) => $.status_catalog_error.title)}
+ </p>
+ {kind === "status" && (
+ <p className="text-caption">{t(($) => $.status_catalog_error.hint)}</p>
+ )}
<Button variant="outline" size="sm" className="mt-1" onClick={onRetry}>
{t(($) => $.status_catalog_error.retry)}
</Button>
diff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsx
index ffae8231ca..7c63a564d2 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx
+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx
@@ -7,6 +7,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";
import { setApiInstance } from "@multica/core/api";
import type { ApiClient } from "@multica/core/api/client";
+import { workspaceWorkingAgentsKeys } from "@multica/core/agents/queries";
import {
getIssueSurfaceViewStore,
pruneIssueSurfaceViewStates,
@@ -1059,7 +1060,9 @@ describe("useIssueSurfaceController", () => {
undefined,
),
);
- expect(result.current.tableQuerySpec.filters.working_issue_ids).toEqual([]);
+ await waitFor(() =>
+ expect(result.current.tableQuerySpec.filters.working_issue_ids).toEqual([]),
+ );
});
it.each(["board", "list", "swimlane"] as const)(
@@ -1547,7 +1550,7 @@ describe("useIssueSurfaceController", () => {
await waitFor(() => expect(result.current.workingAgents).toEqual([]));
});
- it("requests issue working agents so chat/autopilot work stays out of scope", async () => {
+ it.each(["table", "list", "board", "swimlane"] as const)("loads only the scoped working facet on an unfiltered %s surface", async (mode) => {
mockListByStatus({
todo: [makeIssue({ id: "todo-1", status: "todo" })],
});
@@ -1555,17 +1558,105 @@ describe("useIssueSurfaceController", () => {
() =>
useIssueSurfaceController({
scope: { type: "project", projectId: "p1" },
- modes: ["list"],
+ modes: [mode],
}),
{ wrapper: makeWrapper(qc, "project:p1") },
);
await waitFor(() => expect(result.current.isLoading).toBe(false));
await waitFor(() => expect(result.current.workingAgents).toEqual([]));
- expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue", undefined, undefined);
+ expect(getWorkspaceWorkingAgents).not.toHaveBeenCalled();
expect(getAgentTaskSnapshot).not.toHaveBeenCalled();
});
+ it("waits for working membership on activation and after cache removal, and reuses resolved membership", async () => {
+ mockListByStatus({ todo: [makeIssue({ id: "todo-1", status: "todo" })] });
+ let finish!: (agents: WorkspaceWorkingAgent[]) => void;
+ getWorkspaceWorkingAgents.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
+ const store = getIssueSurfaceViewStore("project:p1");
+ const { result } = renderHook(
+ () => useIssueSurfaceController({ scope: { type: "project", projectId: "p1" }, modes: ["list"] }),
+ { wrapper: makeWrapper(qc) },
+ );
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ listIssueTableRows.mockClear();
+ listIssueTableFacets.mockClear();
+ act(() => store.getState().toggleAgentRunningFilter());
+ expect(result.current.isLoading).toBe(true);
+ expect(result.current.isEmpty).toBe(false);
+ expect(result.current.isWorkingFilterError).toBe(false);
+ expect(result.current.tableQuerySpec.filters.working_issue_ids).toBeUndefined();
+ expect(listIssueTableRows).not.toHaveBeenCalled();
+ expect(submenuFacetCalls(listIssueTableFacets)).toHaveLength(0);
+ await act(async () => finish([makeWorkingAgent("agent-1", ["todo-1"])]));
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ expect(result.current.tableQuerySpec.filters.working_issue_ids).toEqual(["todo-1"]);
+ expect(listIssueTableRows).toHaveBeenCalledWith(expect.objectContaining({
+ query: expect.objectContaining({ filters: expect.objectContaining({ working_issue_ids: ["todo-1"] }) }),
+ }));
+ expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue", undefined, undefined);
+ act(() => store.getState().toggleAgentRunningFilter());
+ act(() => store.getState().toggleAgentRunningFilter());
+ expect(getWorkspaceWorkingAgents).toHaveBeenCalledTimes(1);
+ expect(result.current.isLoading).toBe(false);
+
+ act(() => store.getState().toggleAgentRunningFilter());
+ listIssueTableRows.mockClear();
+ act(() => {
+ qc.removeQueries({ queryKey: workspaceWorkingAgentsKeys.all("ws-1") });
+ store.getState().toggleAgentRunningFilter();
+ });
+ await waitFor(() => expect(getWorkspaceWorkingAgents).toHaveBeenCalledTimes(2));
+ expect(result.current.isLoading).toBe(true);
+ expect(result.current.tableQuerySpec.filters.working_issue_ids).toBeUndefined();
+ expect(listIssueTableRows).not.toHaveBeenCalled();
+
+ // An authoritative empty response must still become an explicit empty
+ // filter; omitting it after resolution would fetch unfiltered rows.
+ await act(async () => finish([]));
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ expect(result.current.tableQuerySpec.filters.working_issue_ids).toEqual([]);
+ expect(listIssueTableRows).toHaveBeenCalledWith(expect.objectContaining({
+ query: expect.objectContaining({ filters: expect.objectContaining({ working_issue_ids: [] }) }),
+ }));
+ });
+
+ it("keeps Table loading until working membership resolves, and lets the filter be disabled while pending", async () => {
+ getWorkspaceWorkingAgents.mockImplementation(() => never());
+ const store = getIssueSurfaceViewStore("project:p1");
+ store.getState().toggleAgentRunningFilter();
+ const { result } = renderHook(
+ () => useIssueSurfaceController({ scope: { type: "project", projectId: "p1" }, modes: ["table"] }),
+ { wrapper: makeWrapper(qc) },
+ );
+ await waitFor(() => expect(result.current.workingAgents).toEqual([]));
+ expect(result.current.isLoading).toBe(true);
+ expect(result.current.isEmpty).toBe(false);
+ act(() => store.getState().toggleAgentRunningFilter());
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.tableQuerySpec.filters.working_issue_ids).toBeUndefined();
+ });
+
+ it("offers a retry when the working filter cannot load its initial membership", async () => {
+ mockListByStatus({ todo: [makeIssue({ id: "todo-1", status: "todo" })] });
+ getWorkspaceWorkingAgents.mockRejectedValueOnce(new Error("offline"));
+ const store = getIssueSurfaceViewStore("project:p1");
+ store.getState().toggleAgentRunningFilter();
+ const { result } = renderHook(
+ () => useIssueSurfaceController({ scope: { type: "project", projectId: "p1" }, modes: ["list"] }),
+ { wrapper: makeWrapper(qc) },
+ );
+ await waitFor(() => expect(result.current.isWorkingFilterError).toBe(true));
+ expect(result.current.isEmpty).toBe(false);
+ expect(result.current.tableQuerySpec.filters.working_issue_ids).toBeUndefined();
+ expect(listIssueTableRows).not.toHaveBeenCalled();
+ mockWorkingAgents([makeWorkingAgent("agent-1", ["todo-1"])]);
+ act(() => result.current.retryWorkingFilter());
+ await waitFor(() => expect(result.current.issues.map((issue) => issue.id)).toEqual(["todo-1"]));
+ expect(result.current.isLoading).toBe(false);
+ expect(result.current.isWorkingFilterError).toBe(false);
+ });
+
it("keeps swimlane chrome bounded while descriptors retain hidden-status counts", async () => {
mockListByStatus({
todo: [makeIssue({ id: "todo-1", status: "todo" })],
@@ -1654,6 +1745,22 @@ describe("useIssueSurfaceController", () => {
}),
];
+ it("still loads Gantt's canvas projection without the working filter and leaves its count unknown until ready", async () => {
+ mockGanttIssues(ganttFixture);
+ let finish!: (agents: WorkspaceWorkingAgent[]) => void;
+ getWorkspaceWorkingAgents.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
+ const { result } = renderHook(
+ () => useIssueSurfaceController({ scope: { type: "project", projectId: "p1" }, modes: ["gantt"] }),
+ { wrapper: makeWrapper(qc) },
+ );
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue", undefined, undefined);
+ expect(result.current.workingAgents).toBeUndefined();
+ await act(async () => finish([makeWorkingAgent("agent-1", ["gantt-open"])]));
+ await waitFor(() => expect(result.current.workingAgents).toEqual([{ id: "agent-1", running_task_count: 1 }]));
+ expect(result.current.tableQuerySpec.filters.working_issue_ids).toBeUndefined();
+ });
+
it("filters Gantt by running-task issue ids rather than issue assignees", async () => {
mockGanttIssues(ganttFixture);
mockWorkingAgents([
diff --git a/packages/views/issues/surface/use-issue-surface-controller.ts b/packages/views/issues/surface/use-issue-surface-controller.ts
index 56ea4fee04..515a8e2b82 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.ts
+++ b/packages/views/issues/surface/use-issue-surface-controller.ts
@@ -127,6 +127,9 @@ export interface IssueSurfaceController {
isStatusCatalogError: boolean;
/** Re-runs the failed catalog request behind {@link isStatusCatalogError}. */
retryStatusCatalog: () => void;
+ /** First-load failure while the working filter needs issue membership. */
+ isWorkingFilterError: boolean;
+ retryWorkingFilter: () => void;
openCreateIssue: (defaults?: IssueCreateDefaults) => void;
moveIssue: (
issueId: string,
@@ -412,9 +415,19 @@ export function useIssueSurfaceController({
? "any"
: scope.relation
: undefined;
- const { data: workspaceWorkingAgents = EMPTY_LIST } = useQuery(
- workspaceWorkingAgentsOptions(wsId, "issue", workingAgentMineRelation),
- );
+ const workingAgentsProjection = useQuery({
+ ...workspaceWorkingAgentsOptions(wsId, "issue", workingAgentMineRelation),
+ // Ordinary surfaces get their chip count from the scoped facet. Only an
+ // active working filter or Gantt's canvas count consumes the issue ids.
+ enabled: usesGantt || agentRunningFilter,
+ });
+ const workspaceWorkingAgents = workingAgentsProjection.data ?? EMPTY_LIST;
+ const workingFilterUnresolved =
+ agentRunningFilter && workingAgentsProjection.data === undefined;
+ const workingFilterPending =
+ workingFilterUnresolved && workingAgentsProjection.isPending;
+ const workingFilterError =
+ workingFilterUnresolved && workingAgentsProjection.isError;
const workingIssueIDs = useMemo(() => {
const issueIDs = new Set<string>();
for (const agent of workspaceWorkingAgents) {
@@ -487,7 +500,9 @@ export function useIssueSurfaceController({
? { properties: effectivePropertyFilters }
: {}),
...(date ? { date } : {}),
- ...(agentRunningFilter
+ // Unknown membership must not create a temporary match-nothing query
+ // key. Dependent fetches stay gated until the projection resolves.
+ ...(agentRunningFilter && !workingFilterUnresolved
? { working_issue_ids: [...workingIssueIDs] }
: {}),
include_sub_issues: showSubIssues,
@@ -516,6 +531,7 @@ export function useIssueSurfaceController({
statusFilters,
viewIncludeNoProject,
viewProjectFilters,
+ workingFilterUnresolved,
workingIssueIDs,
]);
// Every consumer below — the facet request, the status/group branch hooks and
@@ -561,8 +577,10 @@ export function useIssueSurfaceController({
// every custom-property facet made a Table mount issue up to 47 SQL
// statements and repeatedly scan the issue table after invalidation.
enabled:
- usesServerStatusSurface ||
- ((usesTable || usesServerGroupSurface) && activeTableFacet !== null),
+ !workingFilterUnresolved && (
+ usesServerStatusSurface ||
+ ((usesTable || usesServerGroupSurface) && activeTableFacet !== null)
+ ),
});
// The header chip's count, kept on its own query rather than folded into the
// submenu facet request above. Two reasons: that request is deliberately
@@ -624,7 +642,7 @@ export function useIssueSurfaceController({
facets: tableFacetsQuery.data,
facetsPending: tableFacetsQuery.isPending,
facetsFetching: tableFacetsQuery.isFetching,
- enabled: usesServerStatusSurface && !statusFilterUnresolved,
+ enabled: usesServerStatusSurface && !statusFilterUnresolved && !workingFilterUnresolved,
});
const serverGroupSpec = useMemo<IssueTableGroupsRequest["group"]>(() => {
if (effectiveViewMode === "swimlane") {
@@ -665,7 +683,7 @@ export function useIssueSurfaceController({
observeEmptyBranches:
effectiveViewMode === "swimlane" ||
(effectiveViewMode === "board" && activeGroupingProperty !== null),
- enabled: usesServerGroupSurface && !statusFilterUnresolved,
+ enabled: usesServerGroupSurface && !statusFilterUnresolved && !workingFilterUnresolved,
});
// Selection is only meaningful within the current membership window: batch
@@ -761,7 +779,7 @@ export function useIssueSurfaceController({
const workingAgents = useMemo<WorkingAgentSummary[] | undefined>(() => {
if (!usesGantt) return facetWorkingAgents;
const rows = data.ganttWorkingScopeIssues;
- if (!rows) return undefined;
+ if (!rows || workingAgentsProjection.data === undefined) return undefined;
const visible = new Set(rows.map((issue) => issue.id));
const summaries: WorkingAgentSummary[] = [];
for (const agent of workspaceWorkingAgents) {
@@ -776,6 +794,7 @@ export function useIssueSurfaceController({
facetWorkingAgents,
usesGantt,
workspaceWorkingAgents,
+ workingAgentsProjection.data,
]);
const exportTableIssues = useCallback(async () => {
@@ -840,6 +859,7 @@ export function useIssueSurfaceController({
viewMode: effectiveViewMode,
allowGantt: allowedModes.has("gantt") && !!projectId,
...surfaceData,
+ isLoading: data.isLoading || workingFilterPending,
workingAgents,
hasActiveFilters,
statusPagination: usesServerStatusSurface
@@ -853,6 +873,7 @@ export function useIssueSurfaceController({
// debounced value as well to avoid a brief empty-screen flash while a
// cleared query is waiting to re-fetch the unsearched window.
isEmpty:
+ !workingFilterUnresolved &&
data.isEmpty &&
!data.isRefreshing &&
!(usesTable && (tableSearch.trim() || debouncedActiveSearch)),
@@ -863,6 +884,10 @@ export function useIssueSurfaceController({
catalog.retry();
data.retryProjectCatalog();
},
+ isWorkingFilterError: workingFilterError,
+ retryWorkingFilter: () => {
+ void workingAgentsProjection.refetch();
+ },
sort,
actions,
selection,
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index b6fce19265..c3fee3c8df 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -36,6 +36,9 @@
"steer_step": "{{name}} added",
"steer_step_read": "Read"
},
+ "working_filter_error": {
+ "title": "Couldn't load issues with working agents"
+ },
"status_catalog_error": {
"title": "Couldn't load the status list",
"hint": "Issues can't be shown until statuses load.",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 349c3f1626..9033f26735 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -36,6 +36,9 @@
"steer_step": "{{name}} a ajouté",
"steer_step_read": "Lu"
},
+ "working_filter_error": {
+ "title": "Impossible de charger les tâches en cours de traitement par les agents"
+ },
"status_catalog_error": {
"title": "Impossible de charger la liste des états",
"hint": "Les tâches ne peuvent pas s’afficher tant que les statuts ne sont pas chargés.",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 34b2d42fe2..54758ab5ee 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -35,6 +35,9 @@
"steer_step": "{{name}} が追加",
"steer_step_read": "既読"
},
+ "working_filter_error": {
+ "title": "エージェントが作業中のタスクを読み込めませんでした"
+ },
"status_catalog_error": {
"title": "ステータス一覧を読み込めませんでした",
"hint": "ステータスを読み込むまでタスクを表示できません。",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 394e2f2707..651e2f7594 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -35,6 +35,9 @@
"steer_step": "{{name}}이(가) 추가",
"steer_step_read": "읽음"
},
+ "working_filter_error": {
+ "title": "에이전트가 작업 중인 태스크를 불러오지 못했습니다"
+ },
"status_catalog_error": {
"title": "상태 목록을 불러오지 못했습니다",
"hint": "상태를 불러와야 태스크를 표시할 수 있습니다.",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 2387af78bf..cfc309dba7 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -35,6 +35,9 @@
"steer_step": "{{name}} 插话",
"steer_step_read": "已读取"
},
+ "working_filter_error": {
+ "title": "无法加载智能体正在处理的任务"
+ },
"status_catalog_error": {
"title": "状态列表加载失败",
"hint": "加载状态后才能显示任务。",