Files
multica/packages/views/issues/surface/use-issue-surface-controller.test.tsx
Naiyuan Qing ade6b34e5f MUL-3903: Extract shared issue surfaces (#4774)
* MUL-3903 refactor project issue surface state

Co-authored-by: multica-agent <github@multica.ai>

* Refactor project issue surface ownership

Co-authored-by: multica-agent <github@multica.ai>

* Extract shared issue surface entrypoints

Co-authored-by: multica-agent <github@multica.ai>

* Fix issue surface create defaults and selection reset

Co-authored-by: multica-agent <github@multica.ai>

* test(editor): add missing AbortSignal to suggestion items() calls

The suggestion items() contract gained a required signal param; the
mention/slash test call sites were never updated, breaking pnpm typecheck
for @multica/views.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(issues): server-side assignee_types filter on ListIssues

ListGroupedIssues has taken assignee_types since squads shipped, but
ListIssues never did — so the workspace Members/Agents tabs had to fetch
the unfiltered workspace list and post-filter loaded pages client-side,
which made column totals and load-more pagination reflect the unfiltered
counts.

Add the same parse + WHERE clause to ListIssues (count query shares the
WHERE, so totals agree), thread the param through the TS client, and
widen MyIssuesFilter so scoped list caches can carry it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(issues): route issue cache writes through a membership-aware coordinator

useUpdateIssue, useBatchUpdateIssues, and the WS issue:updated handler
each maintained their own similar-but-diverging patch/invalidate rules.
Consolidate them into cache-coordinator.ts (applyIssueChange /
rollbackIssueChange / invalidateIssueDerivatives) so local writes and
remote echoes follow one rules table by construction.

The coordinator is membership-aware via surface/membership.ts
(true | false | unknown against each list cache's own filter contract):

- a change that moves an issue off a filtered surface removes the card
  surgically (bucket total decremented) — fixes assignee changes leaving
  stale cards on My Assigned with no local safety net (previously only
  the WS echo recovered it), and replaces the blanket invalidate-myAll
  net for project moves (MUL-3669) with per-key precision
- possible entry into a loaded list marks that key stale — never
  hard-insert; page/slot is server knowledge
- stale keys flush on settle for mutations (a mid-flight refetch would
  stomp the optimistic state) and immediately for WS
- batch updates now patch detail + inbox like single updates; the
  off-screen bucket-count recovery previously exclusive to the WS path
  now covers local mutations too

Preserved invariants: synchronous optimistic patches (dnd-kit), MUL-3375
control-field stripping, and no refetch of surgically reconciled lists
(the drag-flicker fix).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* refactor(issues): resolve surfaces via core query plan/repository with window-keyed remount

Read-path convergence and the loading/empty semantics that fall out of
it:

- scope -> API params moves from scope.ts helpers into
  surface/query-plan.ts; workspace members/agents become server-filtered
  scoped plans (assignee_types) and the client postFilter machinery is
  deleted — tab counts and load-more are now exact
- query selection moves behind surface/repository.ts; the views data
  hook no longer branches on workspace-vs-scoped plumbing
- IssueSurfaceContent remounts on data-window change (wsId + scope):
  keepPreviousData placeholders keep sort/filter changes flicker-free
  within one window but must never let project A's (or workspace A's)
  cards impersonate B's with no loading state — cold window shows the
  skeleton, warm window hits cache instantly
- isEmpty is only asserted from full-window data; the gantt
  scheduled-only projection can't prove the window is empty, so GanttView's
  own "no scheduled issues" empty state renders instead of the generic
  create-issue one
- per-card project lookups hoist into a surface-level projectMap (drops
  a per-card useQuery), create-defaults typing tightens to
  IssueCreateDefaults

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* perf(issues): count-only arithmetic for off-window status/membership changes

An issue beyond a list's loaded page window used to force a full
first-page refetch just to fix two column counts. When the change is
CERTAIN (base entity known, membership definitive) the coordinator now
does the arithmetic locally:

- stayed a member + status changed: move one unit of total between the
  two buckets (loaded arrays untouched; hasMore stays consistent)
- left the list (reassigned / re-projected): old status bucket total -1
- member-to-member reassignment: counts unaffected, not even a stale key

Entering a list and any uncertainty (no base, unknown membership) still
refetch — the right page/slot is server knowledge. Branches on membership
OUTCOMES, not on which field changed, so future dimensions (team) join
automatically. Biggest win is the WS path: agents flipping off-screen
statuses no longer trigger refetch storms.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(issues): deferred view-refresh indicator during placeholder revalidation

Sort/date changes (and any grouped-board filter change) revalidate behind
the previous snapshot — correct, but on a slow network the click felt
dead: content stays put and isLoading never fires. Surface the state as
isRefreshing (isPlaceholderData of the active query) and render a shared
ViewRefreshIndicator in every issues header: a fixed-width slot (zero
layout shift) whose spinner fades in after 300ms, so sub-second responses
show nothing (NN/g) while slow ones get a working signal.

Bound to the revalidation STATE, not to any particular control — any
current or future server-side view change lights it automatically.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: multica-agent <github@multica.ai>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 14:11:10 +08:00

455 lines
14 KiB
TypeScript

/**
* @vitest-environment jsdom
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
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 { issueKeys } from "@multica/core/issues/queries";
import {
getIssueSurfaceViewStore,
pruneIssueSurfaceViewStates,
} from "@multica/core/issues/stores/surface-view-store";
import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";
import type {
AgentTask,
ListIssuesParams,
ListIssuesResponse,
} from "@multica/core/types";
import { useIssueSurfaceController } from "./use-issue-surface-controller";
const updateIssueMutate = vi.hoisted(() => vi.fn());
const batchUpdateMutateAsync = vi.hoisted(() => vi.fn());
const batchDeleteMutateAsync = vi.hoisted(() => vi.fn());
const openModal = vi.hoisted(() => vi.fn());
vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "ws-1",
}));
vi.mock("@multica/core/issues/mutations", () => ({
useUpdateIssue: () => ({ mutate: updateIssueMutate, isPending: false }),
useBatchUpdateIssues: () => ({
mutateAsync: batchUpdateMutateAsync,
isPending: false,
}),
useBatchDeleteIssues: () => ({
mutateAsync: batchDeleteMutateAsync,
isPending: false,
}),
}));
vi.mock("@multica/core/modals", () => ({
useModalStore: {
getState: () => ({ open: openModal }),
},
}));
vi.mock("../../i18n", () => ({
useT: () => ({ t: () => "translated" }),
}));
function makeWrapper(qc: QueryClient, surfaceKey = "project:p1") {
const store = getIssueSurfaceViewStore(surfaceKey);
return function Wrapper({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={qc}>
<ViewStoreProvider store={store}>{children}</ViewStoreProvider>
</QueryClientProvider>
);
};
}
function never<T>() {
return new Promise<T>(() => {});
}
describe("useIssueSurfaceController", () => {
let qc: QueryClient;
let listIssues: ReturnType<
typeof vi.fn<(params?: ListIssuesParams) => Promise<ListIssuesResponse>>
>;
beforeEach(() => {
qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
listIssues = vi.fn(() => never<ListIssuesResponse>());
setApiInstance({
listIssues,
listGroupedIssues: vi.fn(() => never()),
listProjects: vi.fn(() => never()),
getAgentTaskSnapshot: vi.fn(() => never<AgentTask[]>()),
getChildIssueProgress: vi.fn(() => never()),
} as unknown as ApiClient);
pruneIssueSurfaceViewStates([]);
updateIssueMutate.mockClear();
openModal.mockClear();
batchUpdateMutateAsync.mockResolvedValue(undefined);
batchDeleteMutateAsync.mockResolvedValue(undefined);
});
afterEach(() => {
cleanup();
qc.clear();
pruneIssueSurfaceViewStates([]);
vi.restoreAllMocks();
});
it("derives the project scope key, API filter, and sorted myList cache key", async () => {
const store = getIssueSurfaceViewStore("project:p1");
store.getState().setSortBy("priority");
store.getState().setSortDirection("desc");
const { result } = renderHook(
() =>
useIssueSurfaceController({
scope: { type: "project", projectId: "p1" },
modes: ["board", "list", "swimlane", "gantt"],
}),
{ wrapper: makeWrapper(qc, "project:p1") },
);
await waitFor(() => expect(listIssues).toHaveBeenCalled());
const expectedSort = { sort_by: "priority", sort_direction: "desc" } as const;
const expectedFilter = { project_id: "p1" };
expect(result.current.scopeKey).toBe("project:p1");
expect(result.current.filter).toEqual(expectedFilter);
expect(result.current.sort).toEqual(expectedSort);
expect(
qc.getQueryCache().find({
queryKey: issueKeys.myListSorted(
"ws-1",
"project:p1",
expectedFilter,
expectedSort,
),
exact: true,
}),
).toBeDefined();
expect(listIssues).toHaveBeenCalledWith(
expect.objectContaining({
project_id: "p1",
sort_by: "priority",
sort_direction: "desc",
}),
);
});
it("uses the workspace issue list query for workspace scope", async () => {
const { result } = renderHook(
() =>
useIssueSurfaceController({
scope: { type: "workspace", actorKind: "all" },
modes: ["board", "list", "swimlane"],
}),
{ wrapper: makeWrapper(qc, "workspace:all") },
);
await waitFor(() => expect(listIssues).toHaveBeenCalled());
expect(result.current.scopeKey).toBe("workspace:all");
expect(result.current.filter).toEqual({});
expect(result.current.loadMoreScope).toBeUndefined();
expect(result.current.loadMoreFilter).toBeUndefined();
expect(
qc.getQueryCache().find({
queryKey: issueKeys.listSorted("ws-1", {
sort_by: "position",
sort_direction: undefined,
}),
exact: true,
}),
).toBeDefined();
expect(listIssues).toHaveBeenCalledWith(
expect.objectContaining({ status: "backlog", limit: 50, offset: 0 }),
);
});
it("maps my assigned scope to the existing personal issue query contract", async () => {
const { result } = renderHook(
() =>
useIssueSurfaceController({
scope: { type: "my", relation: "assigned", userId: "user-1" },
modes: ["board", "list", "swimlane"],
}),
{ wrapper: makeWrapper(qc, "my:user-1:assigned") },
);
await waitFor(() => expect(listIssues).toHaveBeenCalled());
const expectedFilter = { assignee_id: "user-1" };
expect(result.current.scopeKey).toBe("my:user-1:assigned");
expect(result.current.filter).toEqual(expectedFilter);
expect(result.current.loadMoreScope).toBe("assigned");
expect(result.current.loadMoreFilter).toEqual(expectedFilter);
expect(
qc.getQueryCache().find({
queryKey: issueKeys.myListSorted(
"ws-1",
"assigned",
expectedFilter,
{ sort_by: "position", sort_direction: undefined },
),
exact: true,
}),
).toBeDefined();
expect(listIssues).toHaveBeenCalledWith(
expect.objectContaining({ assignee_id: "user-1" }),
);
});
it("keeps actor scopes keyed by actor while using the shared list query shape", async () => {
const { result } = renderHook(
() =>
useIssueSurfaceController({
scope: {
type: "actor",
actorType: "agent",
actorId: "agent-1",
relation: "assigned",
},
modes: ["list"],
}),
{ wrapper: makeWrapper(qc, "actor:agent:agent-1:assigned") },
);
await waitFor(() => expect(listIssues).toHaveBeenCalled());
const expectedFilter = { assignee_id: "agent-1" };
expect(result.current.scopeKey).toBe("actor:agent:agent-1:assigned");
expect(result.current.filter).toEqual(expectedFilter);
expect(result.current.loadMoreScope).toBe("actor:agent:agent-1:assigned");
expect(result.current.loadMoreFilter).toEqual(expectedFilter);
expect(
qc.getQueryCache().find({
queryKey: issueKeys.myListSorted(
"ws-1",
"actor:agent:agent-1:assigned",
expectedFilter,
{ sort_by: "position", sort_direction: undefined },
),
exact: true,
}),
).toBeDefined();
expect(listIssues).toHaveBeenCalledWith(
expect.objectContaining({ assignee_id: "agent-1" }),
);
});
it.each([
{
name: "project",
surfaceKey: "project:p1",
scope: { type: "project" as const, projectId: "p1" },
expected: { project_id: "p1", status: "todo" },
},
{
name: "my assigned",
surfaceKey: "my:user-1:assigned",
scope: { type: "my" as const, relation: "assigned" as const, userId: "user-1" },
expected: {
assignee_type: "member",
assignee_id: "user-1",
status: "todo",
},
},
{
name: "actor assigned",
surfaceKey: "actor:agent:agent-1:assigned",
scope: {
type: "actor" as const,
actorType: "agent" as const,
actorId: "agent-1",
relation: "assigned" as const,
},
expected: {
assignee_type: "agent",
assignee_id: "agent-1",
status: "todo",
},
},
])("merges $name create defaults into the create modal payload", ({ scope, surfaceKey, expected }) => {
const { result } = renderHook(
() =>
useIssueSurfaceController({
scope,
modes: ["board", "list", "swimlane", "gantt"],
}),
{ wrapper: makeWrapper(qc, surfaceKey) },
);
act(() => {
result.current.openCreateIssue({ status: "todo" });
});
expect(openModal).toHaveBeenCalledWith("create-issue", expected);
});
it("clears surface selection when the view mode changes within the same scope", async () => {
const store = getIssueSurfaceViewStore("my:user-1:assigned");
store.getState().setViewMode("list");
const { result } = renderHook(
() =>
useIssueSurfaceController({
scope: { type: "my", relation: "assigned", userId: "user-1" },
modes: ["board", "list", "swimlane"],
}),
{ wrapper: makeWrapper(qc, "my:user-1:assigned") },
);
act(() => {
result.current.selection.select(["issue-1"]);
});
expect(result.current.selection.selectedIds).toEqual(new Set(["issue-1"]));
act(() => {
store.getState().setViewMode("board");
});
await waitFor(() => {
expect(result.current.viewMode).toBe("board");
expect(result.current.selection.selectedIds).toEqual(new Set());
});
});
it("delegates movement through useUpdateIssue without rewriting the mutation path", () => {
const { result } = renderHook(
() =>
useIssueSurfaceController({
scope: { type: "project", projectId: "p1" },
modes: ["board", "list", "swimlane", "gantt"],
}),
{ wrapper: makeWrapper(qc, "project:p1") },
);
const onSettled = vi.fn();
act(() => {
result.current.moveIssue(
"issue-1",
{ status: "in_progress", position: 42, project_id: "p2" },
onSettled,
);
});
expect(updateIssueMutate).toHaveBeenCalledWith(
{ id: "issue-1", status: "in_progress", position: 42, project_id: "p2" },
expect.objectContaining({
onError: expect.any(Function),
onSettled: expect.any(Function),
}),
);
const options = updateIssueMutate.mock.calls[0]?.[1] as
| { onSettled?: () => void }
| undefined;
options?.onSettled?.();
expect(onSettled).toHaveBeenCalled();
});
it("exposes surface actions and surface-local selection", async () => {
const { result } = renderHook(
() =>
useIssueSurfaceController({
scope: { type: "project", projectId: "p1" },
modes: ["board", "list", "swimlane", "gantt"],
}),
{ wrapper: makeWrapper(qc, "project:p1") },
);
act(() => {
result.current.selection.select(["issue-1"]);
});
expect(result.current.selection.selectedIds).toEqual(new Set(["issue-1"]));
await act(async () => {
await result.current.actions.batchUpdate(["issue-1"], { status: "done" });
await result.current.actions.batchDelete(["issue-2"]);
});
expect(batchUpdateMutateAsync).toHaveBeenCalledWith({
ids: ["issue-1"],
updates: { status: "done" },
});
expect(batchDeleteMutateAsync).toHaveBeenCalledWith(["issue-2"]);
});
it("never reports isEmpty in gantt mode — an empty scheduled subset cannot prove the window is empty", async () => {
// The gantt query returns only issues with a start/due date. A project
// full of unscheduled issues comes back [] here, and the surface used to
// conclude "no issues linked" and render the generic create-issue empty
// state over GanttView's accurate "no scheduled issues" one.
listIssues.mockResolvedValue({ issues: [], total: 0 });
const { result } = renderHook(
() =>
useIssueSurfaceController({
scope: { type: "project", projectId: "p1" },
modes: ["gantt"],
}),
{ wrapper: makeWrapper(qc, "project:p1") },
);
await waitFor(() => expect(result.current.isLoading).toBe(false));
expect(result.current.viewMode).toBe("gantt");
// Falls through to GanttView, which renders its own scheduled-empty copy.
expect(result.current.isEmpty).toBe(false);
});
it("reports isRefreshing while a view change revalidates behind the previous snapshot", async () => {
const store = getIssueSurfaceViewStore("project:p1");
listIssues.mockResolvedValue({ issues: [], total: 0 });
const { result } = renderHook(
() =>
useIssueSurfaceController({
scope: { type: "project", projectId: "p1" },
modes: ["list"],
}),
{ wrapper: makeWrapper(qc, "project:p1") },
);
// First load is loading, never refreshing — there is no previous
// snapshot to show as a placeholder.
expect(result.current.isLoading).toBe(true);
expect(result.current.isRefreshing).toBe(false);
await waitFor(() => expect(result.current.isLoading).toBe(false));
// Sort change: the key changes, the previous order stays rendered as a
// placeholder while the new order fetches — refreshing, NOT loading.
const resolvers: ((r: ListIssuesResponse) => void)[] = [];
listIssues.mockImplementation(
() => new Promise<ListIssuesResponse>((res) => resolvers.push(res)),
);
act(() => store.getState().setSortBy("priority"));
await waitFor(() => expect(result.current.isRefreshing).toBe(true));
expect(result.current.isLoading).toBe(false);
// The revalidation lands — the indicator clears.
await act(async () => {
for (const resolve of resolvers) resolve({ issues: [], total: 0 });
});
await waitFor(() => expect(result.current.isRefreshing).toBe(false));
});
it("still reports isEmpty for the full-window modes when the list is empty", async () => {
listIssues.mockResolvedValue({ issues: [], total: 0 });
const { result } = renderHook(
() =>
useIssueSurfaceController({
scope: { type: "project", projectId: "p1" },
modes: ["list"],
}),
{ wrapper: makeWrapper(qc, "project:p1") },
);
await waitFor(() => expect(result.current.isLoading).toBe(false));
expect(result.current.isEmpty).toBe(true);
});
});