mirror of
https://github.com/multica-ai/multica.git
synced 2026-08-02 10:05:41 +02:00
* 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>
232 lines
7.9 KiB
TypeScript
232 lines
7.9 KiB
TypeScript
/**
|
|
* @vitest-environment jsdom
|
|
*/
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
import { setApiInstance } from "@multica/core/api";
|
|
import type { ApiClient } from "@multica/core/api/client";
|
|
import { pruneIssueSurfaceViewStates } from "@multica/core/issues/stores/surface-view-store";
|
|
import type {
|
|
AgentTask,
|
|
Issue,
|
|
ListIssuesParams,
|
|
ListIssuesResponse,
|
|
} from "@multica/core/types";
|
|
import { IssueSurface } from "./issue-surface";
|
|
|
|
// Mutable so tests can simulate a workspace switch — the workspace layout
|
|
// does not remount its children on switch, so the surface must handle the
|
|
// wsId change itself.
|
|
const mockWsId = vi.hoisted(() => ({ current: "ws-1" }));
|
|
vi.mock("@multica/core/hooks", () => ({
|
|
useWorkspaceId: () => mockWsId.current,
|
|
}));
|
|
|
|
const mockAuthUser = { id: "user-1", email: "test@test.com", name: "Test User" };
|
|
vi.mock("@multica/core/auth", () => ({
|
|
useAuthStore: Object.assign(
|
|
(selector?: (state: unknown) => unknown) => {
|
|
const state = { user: mockAuthUser, isAuthenticated: true };
|
|
return selector ? selector(state) : state;
|
|
},
|
|
{ getState: () => ({ user: mockAuthUser, isAuthenticated: true }) },
|
|
),
|
|
registerAuthStore: vi.fn(),
|
|
createAuthStore: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("../../i18n", () => ({
|
|
useT: () => ({ t: () => "translated" }),
|
|
useTimeAgo: () => () => "now",
|
|
}));
|
|
|
|
vi.mock("../../navigation", () => ({
|
|
AppLink: ({ children, href, ...props }: React.ComponentProps<"a">) => (
|
|
<a href={href} {...props}>
|
|
{children}
|
|
</a>
|
|
),
|
|
useNavigation: () => ({ push: vi.fn(), pathname: "/" }),
|
|
}));
|
|
|
|
vi.mock("@multica/core/paths", async () => {
|
|
const actual = await vi.importActual<typeof import("@multica/core/paths")>(
|
|
"@multica/core/paths",
|
|
);
|
|
return {
|
|
...actual,
|
|
useCurrentWorkspace: () => ({ id: "ws-1", name: "Test WS", slug: "test" }),
|
|
useWorkspacePaths: () => actual.paths.workspace("test"),
|
|
};
|
|
});
|
|
|
|
function makeIssue(id: string, title: string, projectId: string): Issue {
|
|
return {
|
|
id,
|
|
workspace_id: "ws-1",
|
|
number: 1,
|
|
identifier: `MUL-${id}`,
|
|
title,
|
|
description: null,
|
|
status: "todo",
|
|
priority: "none",
|
|
assignee_type: null,
|
|
assignee_id: null,
|
|
creator_type: "member",
|
|
creator_id: "user-1",
|
|
parent_issue_id: null,
|
|
project_id: projectId,
|
|
position: 1,
|
|
stage: null,
|
|
start_date: null,
|
|
due_date: null,
|
|
labels: [],
|
|
metadata: {},
|
|
created_at: "2026-01-01T00:00:00Z",
|
|
updated_at: "2026-01-01T00:00:00Z",
|
|
};
|
|
}
|
|
|
|
function never<T>() {
|
|
return new Promise<T>(() => {});
|
|
}
|
|
|
|
function projectSurface(projectId: string) {
|
|
return (
|
|
<IssueSurface
|
|
scope={{ type: "project", projectId }}
|
|
modes={["list"]}
|
|
renderHeader={() => null}
|
|
renderLoading={() => <div data-testid="surface-loading" />}
|
|
batchToolbar="never"
|
|
/>
|
|
);
|
|
}
|
|
|
|
describe("IssueSurface — scope switch loading semantics", () => {
|
|
let qc: QueryClient;
|
|
|
|
beforeEach(() => {
|
|
mockWsId.current = "ws-1";
|
|
qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
|
// p1 answers immediately with one issue; p2 stays in flight forever so
|
|
// the test can observe the in-between state after switching.
|
|
const listIssues = vi.fn((params?: ListIssuesParams) => {
|
|
if (params?.project_id === "p2") return never<ListIssuesResponse>();
|
|
const issues =
|
|
params?.status === "todo" ? [makeIssue("i1", "P1 issue", "p1")] : [];
|
|
return Promise.resolve({ issues, total: issues.length });
|
|
});
|
|
setApiInstance({
|
|
listIssues,
|
|
listGroupedIssues: vi.fn(() => never()),
|
|
listProjects: vi.fn(() => never()),
|
|
getAgentTaskSnapshot: vi.fn(() => never<AgentTask[]>()),
|
|
getChildIssueProgress: vi.fn(() => never()),
|
|
} as unknown as ApiClient);
|
|
pruneIssueSurfaceViewStates([]);
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup();
|
|
qc.clear();
|
|
pruneIssueSurfaceViewStates([]);
|
|
vi.restoreAllMocks();
|
|
});
|
|
|
|
it("shows loading — not the previous project's issues — while the next project is fetching", async () => {
|
|
// Regression: the list queries use `placeholderData: keepPreviousData` to
|
|
// keep sort/filter changes flicker-free WITHIN one surface. Without a
|
|
// scope-keyed remount, that placeholder leaks ACROSS surfaces: switching
|
|
// pinned projects kept rendering project A's cards (isLoading=false, so
|
|
// no skeleton either) until project B's response landed — the "click does
|
|
// nothing, then it snaps" bug.
|
|
const { rerender } = render(
|
|
<QueryClientProvider client={qc}>{projectSurface("p1")}</QueryClientProvider>,
|
|
);
|
|
|
|
await screen.findByText("P1 issue");
|
|
|
|
rerender(
|
|
<QueryClientProvider client={qc}>{projectSurface("p2")}</QueryClientProvider>,
|
|
);
|
|
|
|
// The switch must be honest: p2 has no data yet, so the surface is
|
|
// loading — p1's cards must not impersonate p2.
|
|
expect(screen.getByTestId("surface-loading")).toBeInTheDocument();
|
|
expect(screen.queryByText("P1 issue")).not.toBeInTheDocument();
|
|
});
|
|
|
|
it("shows a cached project instantly on switch-back (no loading flash)", async () => {
|
|
const { rerender } = render(
|
|
<QueryClientProvider client={qc}>{projectSurface("p1")}</QueryClientProvider>,
|
|
);
|
|
await screen.findByText("P1 issue");
|
|
|
|
rerender(
|
|
<QueryClientProvider client={qc}>{projectSurface("p2")}</QueryClientProvider>,
|
|
);
|
|
expect(screen.getByTestId("surface-loading")).toBeInTheDocument();
|
|
|
|
// Back to p1: its cache is warm, so the list renders immediately from
|
|
// cache — remounting must not degrade the instant-switch path.
|
|
rerender(
|
|
<QueryClientProvider client={qc}>{projectSurface("p1")}</QueryClientProvider>,
|
|
);
|
|
await waitFor(() =>
|
|
expect(screen.getByText("P1 issue")).toBeInTheDocument(),
|
|
);
|
|
expect(screen.queryByTestId("surface-loading")).not.toBeInTheDocument();
|
|
});
|
|
|
|
it("shows loading on a workspace switch even though the scope key is identical", async () => {
|
|
// The workspace layout does NOT remount children on switch, and two
|
|
// workspaces share the same scope key (e.g. "workspace:all") — so the
|
|
// remount key must include wsId, or workspace A's issues impersonate
|
|
// workspace B's while B is still fetching.
|
|
//
|
|
// A fresh element per render — reusing one element reference would let
|
|
// React bail out of re-rendering the subtree entirely, and the wsId
|
|
// change would never propagate.
|
|
const workspaceSurface = () => (
|
|
<IssueSurface
|
|
scope={{ type: "workspace" }}
|
|
modes={["list"]}
|
|
renderHeader={() => null}
|
|
renderLoading={() => <div data-testid="surface-loading" />}
|
|
batchToolbar="never"
|
|
/>
|
|
);
|
|
|
|
const listIssues = vi.fn((params?: ListIssuesParams) => {
|
|
const issues =
|
|
params?.status === "todo" ? [makeIssue("i1", "WS1 issue", "p1")] : [];
|
|
return Promise.resolve({ issues, total: issues.length });
|
|
});
|
|
setApiInstance({
|
|
listIssues,
|
|
listGroupedIssues: vi.fn(() => never()),
|
|
listProjects: vi.fn(() => never()),
|
|
getAgentTaskSnapshot: vi.fn(() => never<AgentTask[]>()),
|
|
getChildIssueProgress: vi.fn(() => never()),
|
|
} as unknown as ApiClient);
|
|
|
|
const { rerender } = render(
|
|
<QueryClientProvider client={qc}>{workspaceSurface()}</QueryClientProvider>,
|
|
);
|
|
await screen.findByText("WS1 issue");
|
|
|
|
// Switch workspace: same scope, new wsId, and the new workspace's
|
|
// fetches hang so the in-between state is observable.
|
|
listIssues.mockImplementation(() => never<ListIssuesResponse>());
|
|
mockWsId.current = "ws-2";
|
|
rerender(
|
|
<QueryClientProvider client={qc}>{workspaceSurface()}</QueryClientProvider>,
|
|
);
|
|
|
|
expect(screen.getByTestId("surface-loading")).toBeInTheDocument();
|
|
expect(screen.queryByText("WS1 issue")).not.toBeInTheDocument();
|
|
});
|
|
});
|