Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5202: unify Issue Query across List, Board, and Swimlane (#5820)
Multica Eve40f9ecdd56af
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 522d6f7319..0c8ed40fcb 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -227,6 +227,108 @@ describe("ApiClient server Table query", () => {],});});++ it("parses compound lane descriptors and posts the additive union", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ query_fingerprint: "sha256:compound",+ total: 2,+ groups: [+ {+ key: "parent:parent-1",+ value: {+ kind: "parent",+ parent_id: "parent-1",+ parent: {+ id: "parent-1",+ number: 10,+ identifier: "MUL-10",+ title: "Parent",+ status: "todo",+ },+ value_state: "value",+ },+ count: 2,+ secondary_groups: [+ {+ key: "compound:opaque:status:todo",+ value: { kind: "status", status: "todo" },+ count: 2,+ },+ ],+ },+ ],+ next_cursor: null,+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);+ const client = new ApiClient("https://api.example.test");+ const query = {+ scope: { kind: "workspace" as const },+ filters: {},+ sort: { field: "position" as const, direction: "asc" as const },+ };++ await expect(+ client.listIssueTableGroups({+ query,+ group: {+ kind: "compound",+ primary: "parent",+ secondary: "status",+ secondary_values: ["todo"],+ },+ }),+ ).resolves.toMatchObject({+ groups: [+ {+ value: { kind: "parent", parent: { title: "Parent" } },+ secondary_groups: [+ { value: { kind: "status", status: "todo" }, count: 2 },+ ],+ },+ ],+ });+ expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({+ body: expect.stringContaining(+ '"kind":"compound","primary":"parent","secondary":"status","secondary_values":["todo"]',+ ),+ });+ });+});++describe("ApiClient issue move intent", () => {+ it("posts relative anchors without a client-authored position", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ id: "issue-1", position: 15 }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const client = new ApiClient("https://api.example.test");++ await client.moveIssue("issue-1", {+ status: "in_progress",+ before_id: "issue-0",+ after_id: "issue-2",+ });++ expect(fetchMock).toHaveBeenCalledWith(+ "https://api.example.test/api/issues/issue-1/move",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({+ status: "in_progress",+ before_id: "issue-0",+ after_id: "issue-2",+ }),+ }),+ );+ });});describe("ApiClient label response schemas", () => {diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 2e21e06c86..aa601e9527 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -2,6 +2,7 @@ import type {Issue,IssuePriority,CreateIssueRequest,+ MoveIssueRequest,UpdateIssueRequest,GroupedIssuesResponse,ListIssuesResponse,@@ -831,6 +832,13 @@ export class ApiClient {});}+ async moveIssue(id: string, data: MoveIssueRequest): Promise<Issue> {+ return this.fetch(`/api/issues/${id}/move`, {+ method: "POST",+ body: JSON.stringify(data),+ });+ }+async listChildIssues(id: string): Promise<{ issues: Issue[] }> {const raw = await this.fetch<unknown>(`/api/issues/${id}/children`);return parseWithFallback(raw, ChildIssuesResponseSchema, { issues: [] }, {diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 4ad49a066e..9953a52cf2 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -26,6 +26,7 @@ import type {IssueProperty,ListPropertiesResponse,IssuePropertiesResponse,+ IssueTableGroupDescriptor,IssueTableFacetsResponse,IssueTableGroupsResponse,IssueTableRowsResponse,@@ -576,6 +577,14 @@ const IssueTableActorRefSchema = z.object({id: z.string(),}).loose();+const IssueTableParentRefSchema = z.object({+ id: z.string(),+ number: z.number(),+ identifier: z.string(),+ title: z.string(),+ status: z.string(),+}).loose();+const IssueTableGroupValueSchema = z.discriminatedUnion("kind", [z.object({kind: z.literal("status"),@@ -585,6 +594,16 @@ const IssueTableGroupValueSchema = z.discriminatedUnion("kind", [kind: z.literal("assignee"),actor: IssueTableActorRefSchema.nullable(),}).loose(),+ z.object({+ kind: z.literal("project"),+ project_id: z.string().nullable().optional().default(null),+ }).loose(),+ z.object({+ kind: z.literal("parent"),+ parent_id: z.string().nullable().optional().default(null),+ parent: IssueTableParentRefSchema.nullable().optional().default(null),+ value_state: z.enum(["value", "unavailable", "unset"]),+ }).loose(),z.object({kind: z.literal("property"),property_id: z.string(),@@ -593,11 +612,12 @@ const IssueTableGroupValueSchema = z.discriminatedUnion("kind", [}).loose(),]);-const IssueTableGroupDescriptorSchema = z.object({+const IssueTableGroupDescriptorSchema: z.ZodType<IssueTableGroupDescriptor> = z.lazy(() => z.object({key: z.string(),value: IssueTableGroupValueSchema,count: z.number(),-}).loose();+ secondary_groups: z.array(IssueTableGroupDescriptorSchema).optional(),+}).loose());export const IssueTableGroupsResponseSchema = z.object({query_fingerprint: z.string(),diff --git a/packages/core/issues/mutations.test.tsx b/packages/core/issues/mutations.test.tsxindex 4e599f5b2c..b9708f4da6 100644--- a/packages/core/issues/mutations.test.tsx+++ b/packages/core/issues/mutations.test.tsx@@ -403,6 +403,7 @@ describe("useUpdateIssue — optimistic move keeps every bucketed board in sync"let qc: QueryClient;let updateIssue: ReturnType<typeof vi.fn<(id: string, data: unknown) => Promise<Issue>>>;+ let moveIssue: ReturnType<typeof vi.fn<(id: string, data: unknown) => Promise<Issue>>>;function makeBucketed(): ListIssuesCache {return {@@ -430,7 +431,8 @@ describe("useUpdateIssue — optimistic move keeps every bucketed board in sync"beforeEach(() => {qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });updateIssue = vi.fn();- setApiInstance({ updateIssue } as unknown as ApiClient);+ moveIssue = vi.fn();+ setApiInstance({ updateIssue, moveIssue } as unknown as ApiClient);qc.setQueryData<ListIssuesCache>(wsKey, makeBucketed());qc.setQueryData<ListIssuesCache>(myKey, makeBucketed());qc.setQueryData<ListIssuesCache>(projectKey, makeBucketed());@@ -477,6 +479,39 @@ describe("useUpdateIssue — optimistic move keeps every bucketed board in sync"}});+ it("uses server move intent while keeping provisional position optimistic-only", async () => {+ moveIssue.mockResolvedValue(+ makeIssue(1, { status: "in_progress", position: 15 }),+ );+ const { result } = renderHook(() => useUpdateIssue(), {+ wrapper: createWrapper(qc),+ });++ await act(async () => {+ await result.current.mutateAsync({+ id: "issue-1",+ status: "in_progress",+ position: 12,+ move_intent: {+ before_id: "issue-0",+ after_id: "issue-2",+ },+ });+ });++ expect(moveIssue).toHaveBeenCalledWith("issue-1", {+ status: "in_progress",+ before_id: "issue-0",+ after_id: "issue-2",+ });+ expect(updateIssue).not.toHaveBeenCalled();+ expect(+ qc+ .getQueryData<ListIssuesCache>(wsKey)+ ?.byStatus.in_progress?.issues[0]?.position,+ ).toBe(15);+ });+it("optimistically patches the linked inbox row status and reconciles with the server response", async () => {let resolve!: (issue: Issue) => void;updateIssue.mockReturnValue(diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.tsindex 4f09bcd39d..d42333a74d 100644--- a/packages/core/issues/mutations.ts+++ b/packages/core/issues/mutations.ts@@ -39,8 +39,9 @@ import { useRecentIssuesStore } from "./stores";import type { GroupedIssuesResponse, InboxItem, Issue, IssueAssigneeGroup, IssueReaction, IssueStatus } from "../types";import type {CreateIssueRequest,- UpdateIssueRequest,ListIssuesCache,+ MoveIssueRequest,+ UpdateIssueRequest,} from "../types";import type { TimelineEntry, IssueSubscriber, Reaction } from "../types";import { sortTimelineEntriesAsc } from "./timeline-sort";@@ -61,6 +62,15 @@ export type ToggleIssueReactionVars = {existing: IssueReaction | undefined;};+export type UpdateIssueMutationInput = {+ id: string;+ /**+ * Present only for drag/drop. `position` remains in the optimistic patch,+ * while the request sent to the server contains relative anchors instead.+ */+ move_intent?: Pick<MoveIssueRequest, "before_id" | "after_id">;+} & UpdateIssueRequest;+// ---------------------------------------------------------------------------// Per-status pagination// ---------------------------------------------------------------------------@@ -222,9 +232,12 @@ export function useUpdateIssue() {const qc = useQueryClient();const wsId = useWorkspaceId();return useMutation({- mutationFn: ({ id, ...data }: { id: string } & UpdateIssueRequest) =>- api.updateIssue(id, data),- onMutate: ({ id, ...data }) => {+ mutationFn: ({ id, move_intent: moveIntent, ...data }: UpdateIssueMutationInput) => {+ if (!moveIntent) return api.updateIssue(id, data);+ const { position: _optimisticPosition, ...target } = data;+ return api.moveIssue(id, { ...target, ...moveIntent });+ },+ onMutate: ({ id, move_intent: _moveIntent, ...data }) => {// suppress_run / handoff_note are write-time control fields, not Issue// columns — they steer enqueue/injection on the server and must never be// written into the query cache (MUL-3375). Strip them from the patch; the@@ -322,7 +335,13 @@ export function useUpdateIssue() {// optimistically; against the post-write entity the changed dims come// out false unless the server coerced a different value, so this pass// is the plain surgical patch it always was.- const { suppress_run: _suppressRun, handoff_note: _handoffNote, id: _id, ...intent } = vars;+ const {+ suppress_run: _suppressRun,+ handoff_note: _handoffNote,+ move_intent: _moveIntent,+ id: _id,+ ...intent+ } = vars;// Drop `properties` from the reconcile payload: the bag is owned by the// property mutation pipeline (single-key atomic writes + its own// optimistic state). An UpdateIssue snapshot taken before a concurrentdiff --git a/packages/core/types/api.ts b/packages/core/types/api.tsindex 7cd50670c9..6ee394deaa 100644--- a/packages/core/types/api.ts+++ b/packages/core/types/api.ts@@ -50,6 +50,24 @@ export interface UpdateIssueRequest {handoff_note?: string;}+/**+ * Server-owned drag intent. The client may use a provisional position for its+ * optimistic animation, but the canonical position is derived from these+ * workspace-scoped neighbors by `POST /api/issues/:id/move`.+ */+export interface MoveIssueRequest+ extends Pick<+ UpdateIssueRequest,+ | "status"+ | "assignee_type"+ | "assignee_id"+ | "parent_issue_id"+ | "project_id"+ > {+ before_id: string | null;+ after_id: string | null;+}+/** Inputs to `POST /api/issues/preview-trigger`. A nil prospective field means* "leave unchanged"; `isCreate` previews a not-yet-persisted issue. */export interface IssueTriggerPreviewParams {@@ -273,7 +291,18 @@ export type IssueTableGroupSpec =| { kind: "none" }| { kind: "status" }| { kind: "assignee" }- | { kind: "property"; property_id: string };+ | { kind: "project" }+ | { kind: "parent" }+ | {+ kind: "compound";+ primary: "assignee" | "project" | "parent";+ secondary: "status";+ /** Optional visible secondary buckets. When present, the server pages+ * only primary groups that contain at least one matching card and+ * returns `total` for that complete visible result set. */+ secondary_values?: IssueStatus[];+ }+ | { kind: "property"; property_id: string; include_empty?: boolean };/** Response-side actor reference. Kept open for forward compatibility: an* installed desktop client may receive a new actor kind from a newer server. */@@ -282,9 +311,24 @@ export interface IssueTableActorRef {id: string;}+export interface IssueTableParentRef {+ id: string;+ number: number;+ identifier: string;+ title: string;+ status: string;+}+export type IssueTableGroupValue =| { kind: "status"; status: string }| { kind: "assignee"; actor: IssueTableActorRef | null }+ | { kind: "project"; project_id: string | null }+ | {+ kind: "parent";+ parent_id: string | null;+ parent: IssueTableParentRef | null;+ value_state: "value" | "unavailable" | "unset";+ }| {kind: "property";property_id: string;@@ -296,6 +340,9 @@ export interface IssueTableGroupDescriptor {key: string;value: IssueTableGroupValue;count: number;+ /** Present for compound groups. These opaque keys can be passed straight+ * back to `/table/rows`; clients must not reconstruct them. */+ secondary_groups?: IssueTableGroupDescriptor[];}export interface IssueTablePageRequest {diff --git a/packages/views/common/actor-issues-panel.tsx b/packages/views/common/actor-issues-panel.tsxindex 35fcc23d84..7fa7a30a0b 100644--- a/packages/views/common/actor-issues-panel.tsx+++ b/packages/views/common/actor-issues-panel.tsx@@ -1,9 +1,13 @@"use client";-import { useCallback, useMemo, useState } from "react";+import { useMemo, useState } from "react";import { useStore } from "zustand";import { ListTodo, Search } from "lucide-react";-import type { Issue } from "@multica/core/types";+import type {+ Issue,+ IssueTableFacetSpec,+ IssueTableFacetsResponse,+} from "@multica/core/types";import {actorIssuesViewStore,type ActorIssuesScope,@@ -16,24 +20,12 @@ import {ViewRefreshIndicator,} from "../issues/components/issues-header";import { IssueSurface } from "../issues/surface/issue-surface";-import { matchesPinyin } from "../editor/extensions/pinyin-match";import { useT } from "../i18n";export type TaskActorType = "member" | "agent";const SCOPE_VALUES: ActorIssuesScope[] = ["assigned", "created"];-function issueMatchesSearch(issue: Issue, rawQuery: string) {- const query = rawQuery.trim().toLowerCase();- if (!query) return true;- const title = issue.title ?? "";- return (- title.toLowerCase().includes(query) ||- issue.identifier.toLowerCase().includes(query) ||- matchesPinyin(title, query)- );-}-function ActorIssuesHeader({issues,search,@@ -41,6 +33,9 @@ function ActorIssuesHeader({scope,onScopeChange,isRefreshing = false,+ facetCountsExact,+ tableFacetCounts,+ onTableFacetChange,}: {issues: Issue[];search: string;@@ -48,6 +43,9 @@ function ActorIssuesHeader({scope: ActorIssuesScope;onScopeChange: (scope: ActorIssuesScope) => void;isRefreshing?: boolean;+ facetCountsExact: boolean;+ tableFacetCounts?: IssueTableFacetsResponse;+ onTableFacetChange: (facet: IssueTableFacetSpec | null) => void;}) {const { t } = useT("issues");@@ -90,7 +88,13 @@ function ActorIssuesHeader({</div></div><div className="flex items-center">- <IssueDisplayControls scopedIssues={issues} hideViewToggle />+ <IssueDisplayControls+ scopedIssues={issues}+ hideViewToggle+ facetCountsExact={facetCountsExact}+ tableFacetCounts={tableFacetCounts}+ onTableFacetChange={onTableFacetChange}+ /><ViewRefreshIndicator active={isRefreshing} /></div></div>@@ -108,10 +112,6 @@ export function ActorIssuesPanel({const scope = useStore(actorIssuesViewStore, (s) => s.scope);const setScope = useStore(actorIssuesViewStore, (s) => s.setScope);const [search, setSearch] = useState("");- const clientFilter = useCallback(- (issue: Issue) => issueMatchesSearch(issue, search),- [search],- );const surfaceScope = useMemo(() =>({@@ -129,8 +129,7 @@ export function ActorIssuesPanel({modes={["list"]}batchToolbar="always"contentClassName="p-1"- clientFilter={clientFilter}- showClientEmpty={() => search.trim() !== ""}+ search={search}renderHeader={({ controller }) => (<ActorIssuesHeaderissues={controller.surfaceIssues}@@ -139,10 +138,13 @@ export function ActorIssuesPanel({scope={scope}onScopeChange={setScope}isRefreshing={controller.isRefreshing}+ facetCountsExact={controller.facetCountsExact}+ tableFacetCounts={controller.tableFacetCounts}+ onTableFacetChange={controller.setActiveTableFacet}/>)}- renderEmpty={({ controller }) =>- controller.surfaceIssues.length === 0 ? (+ renderEmpty={() =>+ search.trim() === "" ? (<div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-2 text-muted-foreground"><ListTodo className="h-10 w-10 text-muted-foreground/40" /><p className="text-sm">diff --git a/packages/views/issues/components/board-view.tsx b/packages/views/issues/components/board-view.tsxindex 77add6f605..d9a8859df3 100644--- a/packages/views/issues/components/board-view.tsx+++ b/packages/views/issues/components/board-view.tsx@@ -18,6 +18,7 @@ import { toast } from "sonner";import type {Issue,IssueAssigneeGroup,+ IssueAssigneeType,IssueStatus,Project,IssueProperty,@@ -36,6 +37,14 @@ import { HiddenColumnsPanel, HiddenColumnRow } from "./hidden-columns-panel";import { InfiniteScrollSentinel } from "./infinite-scroll-sentinel";import type { ChildProgress } from "./list-row";import type { IssueCreateDefaults } from "../surface/types";+import type {+ IssueStatusPageState,+ IssueStatusPagination,+} from "../surface/use-issue-status-branches";+import type {+ IssueGroupBranches,+ IssueGroupPageState,+} from "../surface/use-issue-group-branches";import { useDragSettle } from "./use-drag-settle";import { useT } from "../../i18n";import {@@ -46,6 +55,7 @@ import {buildColumns,computePosition,findColumn,+ getMoveAnchors,insertIdByPosition,issueMatchesGroup,getMoveUpdates,@@ -162,6 +172,8 @@ function BoardViewImpl({sort,projectId,onCreateIssue,+ statusPagination,+ groupBranches,}: {issues: Issue[];assigneeGroups?: IssueAssigneeGroup[];@@ -180,6 +192,8 @@ function BoardViewImpl({/** When set, the per-column "+" pre-fills the project on the create form. */projectId?: string;onCreateIssue?: (defaults: IssueCreateDefaults) => void;+ statusPagination?: IssueStatusPagination;+ groupBranches?: IssueGroupBranches;}) {const { t } = useT("issues");const storeGrouping = useViewStore((s) => s.grouping);@@ -249,12 +263,40 @@ function BoardViewImpl({: undefined;const groupedIssues = useMemo(() =>- grouping === "assignee" && assigneeGroups+ groupBranches?.enabled+ ? groupBranches.issues+ : grouping === "assignee" && assigneeGroups? assigneeGroups.flatMap((group) => group.issues): issues,- [assigneeGroups, grouping, issues],+ [assigneeGroups, groupBranches, grouping, issues],);- const hydratedAssigneeGroups = useMemo(() => {+ const hydratedAssigneeGroups = useMemo<BoardColumnGroup[] | undefined>(() => {+ if (grouping === "assignee" && groupBranches?.enabled) {+ return groupBranches.descriptors.flatMap((descriptor): BoardColumnGroup[] => {+ if (descriptor.value.kind !== "assignee") return [];+ const actorRef = descriptor.value.actor;+ const actor: { type: IssueAssigneeType; id: string } | null =+ actorRef &&+ (actorRef.type === "member" ||+ actorRef.type === "agent" ||+ actorRef.type === "squad")+ ? { type: actorRef.type, id: actorRef.id }+ : null;+ return [{+ id: descriptor.key,+ title: actor+ ? getActorName(actor.type, actor.id)+ : t(($) => $.filters.no_assignee),+ assigneeType: actor?.type ?? null,+ assigneeId: actor?.id ?? null,+ totalCount: descriptor.count,+ createData: {+ assignee_type: actor?.type ?? null,+ assignee_id: actor?.id ?? null,+ },+ }];+ });+ }if (grouping !== "assignee" || !assigneeGroups) return undefined;const order: Record<string, number> = {member: 0,@@ -283,11 +325,54 @@ function BoardViewImpl({if (aOrder !== bOrder) return aOrder - bOrder;return a.title.localeCompare(b.title);});- }, [assigneeGroups, getActorName, grouping, t]);+ }, [assigneeGroups, getActorName, groupBranches, grouping, t]);+ const groupPagination = useMemo(() => {+ if (!groupBranches?.enabled) return undefined;+ const grouped = new Map<string, IssueGroupPageState[]>();+ for (const descriptor of groupBranches.descriptors) {+ const page = groupBranches.pagination[descriptor.key];+ if (!page) continue;+ let id = descriptor.key;+ if (descriptor.value.kind === "property") {+ const value = descriptor.value;+ id =+ value.value_state === "value" && typeof value.value === "string"+ ? propertyGroupId(value.property_id, value.value)+ : propertyGroupId(value.property_id, null);+ }+ const pages = grouped.get(id) ?? [];+ pages.push(page);+ grouped.set(id, pages);+ }+ return Object.fromEntries(+ Array.from(grouped, ([id, pages]) => [+ id,+ {+ total: pages.reduce((sum, page) => sum + page.total, 0),+ loaded: pages.reduce((sum, page) => sum + page.loaded, 0),+ hasMore: pages.some((page) => page.hasMore),+ isLoading: pages.some((page) => page.isLoading),+ isFetching: pages.some((page) => page.isFetching),+ isError: pages.some((page) => page.isError),+ loadMore: () => {+ for (const page of pages) {+ if (page.hasMore) page.loadMore();+ }+ },+ retry: () => {+ for (const page of pages) {+ if (page.isError) page.retry();+ }+ },+ },+ ]),+ ) as Record<string, IssueGroupPageState>;+ }, [groupBranches]);const groups = useMemo(- () =>- hydratedAssigneeGroups ??- buildGroups(+ () => {+ const built =+ hydratedAssigneeGroups ??+ buildGroups(issues,visibleStatuses,grouping,@@ -295,8 +380,13 @@ function BoardViewImpl({t(($) => $.filters.no_assignee),groupingProperty,t(($) => $.board.no_value),- ),- [hydratedAssigneeGroups, issues, visibleStatuses, grouping, getActorName, groupingProperty, t],+ );+ return built.map((group) => ({+ ...group,+ totalCount: groupPagination?.[group.id]?.total ?? group.totalCount,+ }));+ },+ [hydratedAssigneeGroups, issues, visibleStatuses, grouping, getActorName, groupingProperty, groupPagination, t],);const groupIds = useMemo(() => new Set(groups.map((group) => group.id)),@@ -458,17 +548,24 @@ function BoardViewImpl({// settles. That is the "snaps back to origin, then moves" glitch.// Placement mirrors the cache (insertByPosition) so the settle rebuild// from TanStack Query is a visual no-op.+ const targetIds = insertIdByPosition(+ (cols[overCol] ?? []).filter((id) => id !== activeId),+ activeId,+ currentIssue.position,+ map,+ );setColumns((prev) => {const fromIds = (prev[activeCol] ?? []).filter((cid) => cid !== activeId);- const toIds = insertIdByPosition(- prev[overCol] ?? [],- activeId,- currentIssue.position,- map,- );- return { ...prev, [activeCol]: fromIds, [overCol]: toIds };+ return { ...prev, [activeCol]: fromIds, [overCol]: targetIds };});- onMoveIssue(activeId, getMoveUpdates(finalGroup, currentIssue.position), beginSettle());+ onMoveIssue(+ activeId,+ {+ ...getMoveUpdates(finalGroup, currentIssue.position),+ ...getMoveAnchors(targetIds, activeId),+ },+ beginSettle(),+ );applyPropertyGroupValue(finalGroup, activeId);return;}@@ -490,7 +587,14 @@ function BoardViewImpl({// success (onSuccess already patched the moved card in place), the revert// on error (onError restored the snapshot). Without it a failed move would// strand the card at the drop target, since onSettled no longer refetches.- onMoveIssue(activeId, getMoveUpdates(finalGroup, newPosition), beginSettle());+ onMoveIssue(+ activeId,+ {+ ...getMoveUpdates(finalGroup, newPosition),+ ...getMoveAnchors(finalIds, activeId),+ },+ beginSettle(),+ );applyPropertyGroupValue(finalGroup, activeId);},[groupedIssues, groups, grouping, groupingOptionIds, onMoveIssue, groupIds, groupMap, sortBy, beginSettle, columnsRef, isDraggingRef, setColumns, applyPropertyGroupValue],@@ -506,27 +610,65 @@ function BoardViewImpl({><div className="flex flex-1 min-h-0 gap-4 overflow-x-auto p-2">{groups.length === 0 ? (- <div className="flex min-w-full flex-1 items-center justify-center text-sm text-muted-foreground">- {t(($) => $.board.empty_grouping)}- </div>+ groupBranches?.isError ? (+ <button+ type="button"+ className="flex min-w-full flex-1 items-center justify-center text-sm text-destructive hover:underline"+ onClick={groupBranches.retryGroups}+ >+ {t(($) => $.table.load_more_failed_retry)}+ </button>+ ) : (+ <div className="flex min-w-full flex-1 items-center justify-center text-sm text-muted-foreground">+ {t(($) => $.board.empty_grouping)}+ </div>+ )) : (groups.map((group) =>isStatusGroup(group) ? (- <PaginatedBoardColumn- key={group.id}- group={group}- issueIds={columns[group.id] ?? EMPTY_IDS}- issueMap={issueMapRef.current}- childProgressMap={childProgressMap}- projectMap={projectMap}- myIssuesOpts={myIssuesOpts}- sort={sort}- projectId={projectId}- onCreateIssue={onCreateIssue}- sortLabel={sortLabel}- />+ statusPagination ? (+ <ServerPaginatedBoardColumn+ key={group.id}+ group={group}+ issueIds={columns[group.id] ?? EMPTY_IDS}+ issueMap={issueMapRef.current}+ childProgressMap={childProgressMap}+ projectMap={projectMap}+ page={statusPagination[group.status]}+ projectId={projectId}+ onCreateIssue={onCreateIssue}+ sortLabel={sortLabel}+ />+ ) : (+ <PaginatedBoardColumn+ key={group.id}+ group={group}+ issueIds={columns[group.id] ?? EMPTY_IDS}+ issueMap={issueMapRef.current}+ childProgressMap={childProgressMap}+ projectMap={projectMap}+ myIssuesOpts={myIssuesOpts}+ sort={sort}+ projectId={projectId}+ onCreateIssue={onCreateIssue}+ sortLabel={sortLabel}+ />+ )) : (- assigneeGroupQueryKey && assigneeGroupFilter ? (+ groupPagination?.[group.id] ? (+ <ServerPaginatedBoardColumn+ key={group.id}+ group={group}+ issueIds={columns[group.id] ?? EMPTY_IDS}+ issueMap={issueMapRef.current}+ childProgressMap={childProgressMap}+ projectMap={projectMap}+ page={groupPagination[group.id]!}+ projectId={projectId}+ onCreateIssue={onCreateIssue}+ sortLabel={sortLabel}+ />+ ) : assigneeGroupQueryKey && assigneeGroupFilter ? (<PaginatedAssigneeBoardColumnkey={group.id}group={group}@@ -558,8 +700,16 @@ function BoardViewImpl({),))}+ {groupBranches?.hasMoreGroups && (+ <div className="flex w-8 shrink-0 items-center justify-center">+ <InfiniteScrollSentinel+ onVisible={groupBranches.loadMoreGroups}+ loading={groupBranches.isLoadingMoreGroups}+ />+ </div>+ )}- {groupingProperty && (+ {groupingProperty && !groupBranches?.enabled && (<PropertyBoardPoolLoaderstatuses={visibleStatuses}myIssuesOpts={myIssuesOpts}@@ -572,6 +722,7 @@ function BoardViewImpl({hiddenStatuses={hiddenStatuses}myIssuesOpts={myIssuesOpts}sort={sort}+ statusPagination={statusPagination}/>)}</div>@@ -650,6 +801,58 @@ const PaginatedAssigneeBoardColumn = memo(function PaginatedAssigneeBoardColumn();});+const ServerPaginatedBoardColumn = memo(function ServerPaginatedBoardColumn({+ group,+ issueIds,+ issueMap,+ childProgressMap,+ projectMap,+ page,+ projectId,+ onCreateIssue,+ sortLabel,+}: {+ group: BoardColumnGroup;+ issueIds: string[];+ issueMap: Map<string, Issue>;+ childProgressMap?: Map<string, ChildProgress>;+ projectMap?: Map<string, Project>;+ page: IssueStatusPageState | IssueGroupPageState;+ projectId?: string;+ onCreateIssue?: (defaults: IssueCreateDefaults) => void;+ sortLabel?: string | null;+}) {+ const { t } = useT("issues");+ const footer = page.isError ? (+ <button+ type="button"+ className="w-full py-2 text-xs text-destructive hover:underline"+ onClick={page.retry}+ >+ {t(($) => $.table.load_more_failed_retry)}+ </button>+ ) : page.hasMore ? (+ <InfiniteScrollSentinel+ onVisible={page.loadMore}+ loading={page.isLoading || page.isFetching}+ />+ ) : undefined;+ return (+ <BoardColumn+ group={group}+ issueIds={issueIds}+ issueMap={issueMap}+ childProgressMap={childProgressMap}+ projectMap={projectMap}+ totalCount={page.total}+ projectId={projectId}+ onCreateIssue={onCreateIssue}+ sortLabel={sortLabel}+ footer={footer}+ />+ );+});+const PaginatedBoardColumn = memo(function PaginatedBoardColumn({group,issueIds,@@ -762,21 +965,31 @@ function BoardHiddenColumnsPanel({hiddenStatuses,myIssuesOpts,sort,+ statusPagination,}: {hiddenStatuses: IssueStatus[];myIssuesOpts?: { scope: string; filter: MyIssuesFilter };sort?: IssueSortParam;+ statusPagination?: IssueStatusPagination;}) {return (<HiddenColumnsPanelhiddenStatuses={hiddenStatuses}renderRow={(status) => (- <BoardHiddenColumnRow- key={status}- status={status}- myIssuesOpts={myIssuesOpts}- sort={sort}- />+ statusPagination ? (+ <HiddenColumnRow+ key={status}+ status={status}+ total={statusPagination[status].total}+ />+ ) : (+ <BoardHiddenColumnRow+ key={status}+ status={status}+ myIssuesOpts={myIssuesOpts}+ sort={sort}+ />+ ))}/>);diff --git a/packages/views/issues/components/create-renderers.test.tsx b/packages/views/issues/components/create-renderers.test.tsxindex d7378053fe..02bce0fd55 100644--- a/packages/views/issues/components/create-renderers.test.tsx+++ b/packages/views/issues/components/create-renderers.test.tsx@@ -1,7 +1,9 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { fireEvent, render, screen } from "@testing-library/react";+import { ALL_STATUSES } from "@multica/core/issues/config";import { BoardColumn } from "./board-column";import { ListView } from "./list-view";+import type { IssueStatusPagination } from "../surface/use-issue-status-branches";const openModal = vi.hoisted(() => vi.fn());const hideStatus = vi.hoisted(() => vi.fn());@@ -9,6 +11,24 @@ const showStatus = vi.hoisted(() => vi.fn());const select = vi.hoisted(() => vi.fn());const deselect = vi.hoisted(() => vi.fn());+function emptyStatusPagination(): IssueStatusPagination {+ return Object.fromEntries(+ ALL_STATUSES.map((status) => [+ status,+ {+ total: 0,+ loaded: 0,+ hasMore: false,+ isLoading: false,+ isFetching: false,+ isError: false,+ loadMore: vi.fn(),+ retry: vi.fn(),+ },+ ]),+ ) as unknown as IssueStatusPagination;+}+vi.mock("@multica/core/hooks", () => ({useWorkspaceId: () => "ws-1",}));@@ -134,6 +154,7 @@ describe("issue renderer create entrypoints", () => {<ListViewissues={[]}visibleStatuses={["todo"]}+ statusPagination={emptyStatusPagination()}projectId="project-1"onCreateIssue={onCreateIssue}/>,diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsxindex 2b0c4d685f..f0eb461ece 100644--- a/packages/views/issues/components/issues-header.tsx+++ b/packages/views/issues/components/issues-header.tsx@@ -940,8 +940,9 @@ export function IssueDisplayControls({allowGantt?: boolean;/*** Whether `scopedIssues` covers the surface's full window. Table does not- * pass loaded branch rows here; it supplies `tableFacetCounts` from the- * backend instead, so badges remain exact without downloading all issues.+ * use loaded rows for counts; server-paged List, Board, and Swimlane follow+ * the same rule. They supply `tableFacetCounts` from the backend instead,+ * so badges remain exact without downloading all issues.*/facetCountsExact?: boolean;tableFacetCounts?: IssueTableFacetsResponse;diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsxindex e07355594d..b2c0030397 100644--- a/packages/views/issues/components/issues-page.test.tsx+++ b/packages/views/issues/components/issues-page.test.tsx@@ -62,6 +62,124 @@ vi.mock("../../workspace/workspace-avatar", () => ({// Mock api (queries use api internally)const mockListIssues = vi.hoisted(() => vi.fn().mockResolvedValue({ issues: [], total: 0 }));const mockListGroupedIssues = vi.hoisted(() => vi.fn().mockResolvedValue({ groups: [] }));+const mockListIssueTableGroups = vi.hoisted(() =>+ vi.fn(async (request: any) => {+ if (request.group.kind !== "assignee") {+ return {+ query_fingerprint: "test",+ total: 0,+ groups: [],+ next_cursor: null,+ };+ }+ const response = await mockListGroupedIssues();+ return {+ query_fingerprint: "test",+ total: response.groups.reduce(+ (total: number, group: any) => total + group.total,+ 0,+ ),+ groups: response.groups.map((group: any) => ({+ key: group.id,+ value: {+ kind: "assignee" as const,+ actor:+ group.assignee_type && group.assignee_id+ ? { type: group.assignee_type, id: group.assignee_id }+ : null,+ },+ count: group.total,+ })),+ next_cursor: null,+ };+ }),+);+const mockListIssueTableRows = vi.hoisted(() =>+ vi.fn(async (request: any) => {+ if (request.group.kind === "assignee") {+ const response = await mockListGroupedIssues();+ const group = response.groups.find(+ (candidate: any) => candidate.id === request.group_key,+ );+ const issues = group?.issues ?? [];+ return {+ query_fingerprint: "test",+ group_key: request.group_key,+ parent_id: null,+ total: 0,+ rows: issues.map((issue: Issue) => ({+ issue,+ direct_child_count: 0,+ })),+ branch_total: issues.length,+ next_cursor: null,+ };+ }+ const status = request.group_key?.replace(/^status:/, "");+ const response = await mockListIssues({+ status,+ limit: 50,+ offset: 0,+ ...(request.query.scope.assignee_types+ ? { assignee_types: request.query.scope.assignee_types }+ : {}),+ });+ return {+ query_fingerprint: "test",+ group_key: request.group_key,+ parent_id: null,+ total: 0,+ rows: response.issues.map((issue: Issue) => ({+ issue,+ direct_child_count: 0,+ })),+ branch_total: response.issues.length,+ next_cursor: null,+ };+ }),+);+const mockListIssueTableFacets = vi.hoisted(() =>+ vi.fn(async (request: any) => {+ const statuses = [+ "backlog",+ "todo",+ "in_progress",+ "in_review",+ "done",+ "blocked",+ "cancelled",+ ];+ const groups = await Promise.all(+ statuses.map(async (status) => ({+ status,+ response: await mockListIssues({+ status,+ limit: 50,+ offset: 0,+ ...(request.query.scope.assignee_types+ ? { assignee_types: request.query.scope.assignee_types }+ : {}),+ }),+ })),+ );+ return {+ query_fingerprint: "test",+ total: groups.reduce((sum, group) => sum + group.response.issues.length, 0),+ facets: request.facets.map((facet: any) => ({+ ...facet,+ values:+ facet.kind === "status"+ ? groups+ .filter((group) => group.response.issues.length > 0)+ .map((group) => ({+ key: group.status,+ count: group.response.issues.length,+ }))+ : [],+ })),+ };+ }),+);const mockListMembers = vi.hoisted(() =>vi.fn().mockResolvedValue([{@@ -118,6 +236,9 @@ vi.mock("@multica/core/api", () => ({getBaseUrl: () => "http://127.0.0.1:8080",listIssues: (...args: any[]) => mockListIssues(...args),listGroupedIssues: (...args: any[]) => mockListGroupedIssues(...args),+ listIssueTableGroups: (request: any) => mockListIssueTableGroups(request),+ listIssueTableRows: (request: any) => mockListIssueTableRows(request),+ listIssueTableFacets: (request: any) => mockListIssueTableFacets(request),updateIssue: vi.fn(),listMembers: (...args: any[]) => mockListMembers(...args),listAgents: (...args: any[]) => mockListAgents(...args),@@ -126,6 +247,9 @@ vi.mock("@multica/core/api", () => ({getApi: () => ({listIssues: (...args: any[]) => mockListIssues(...args),listGroupedIssues: (...args: any[]) => mockListGroupedIssues(...args),+ listIssueTableGroups: (request: any) => mockListIssueTableGroups(request),+ listIssueTableRows: (request: any) => mockListIssueTableRows(request),+ listIssueTableFacets: (request: any) => mockListIssueTableFacets(request),updateIssue: vi.fn(),listMembers: (...args: any[]) => mockListMembers(...args),listAgents: (...args: any[]) => mockListAgents(...args),@@ -518,6 +642,29 @@ function renderWithQuery(ui: React.ReactElement) {describe("IssuesPage (shared)", () => {beforeEach(() => {vi.clearAllMocks();+ vi.stubGlobal(+ "IntersectionObserver",+ class {+ private callback: IntersectionObserverCallback;+ constructor(callback: IntersectionObserverCallback) {+ this.callback = callback;+ }+ observe(target: Element) {+ this.callback(+ [{ isIntersecting: true, target } as IntersectionObserverEntry],+ this as unknown as IntersectionObserver,+ );+ }+ unobserve() {}+ disconnect() {}+ takeRecords() {+ return [];+ }+ root = null;+ rootMargin = "0px";+ thresholds = [0];+ },+ );mockListIssues.mockResolvedValue({ issues: [], total: 0 });mockListGroupedIssues.mockResolvedValue({ groups: [] });mockViewState.viewMode = "board";@@ -579,19 +726,23 @@ describe("IssuesPage (shared)", () => {expect(screen.getByText("No assignee")).toBeInTheDocument();});- it("uses grouped assignee endpoint instead of status page sweep", async () => {+ it("uses table group/row branches instead of the legacy status sweep", async () => {mockViewState.grouping = "assignee";mockListGroupedIssues.mockResolvedValue(mockAssigneeGroups(mockIssues));renderWithQuery(<IssuesPage />);await screen.findByText("Implement auth");- expect(mockListGroupedIssues).toHaveBeenCalledWith(+ expect(mockListIssueTableGroups).toHaveBeenCalledWith(+ expect.objectContaining({+ group: { kind: "assignee" },+ page: { limit: 100, cursor: null },+ }),+ );+ expect(mockListIssueTableRows).toHaveBeenCalledWith(expect.objectContaining({- group_by: "assignee",- limit: 50,- offset: 0,- statuses: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],+ group: { kind: "assignee" },+ page: { limit: 50, cursor: null },}),);expect(mockListIssues).not.toHaveBeenCalled();diff --git a/packages/views/issues/components/issues-page.tsx b/packages/views/issues/components/issues-page.tsxindex 919638b7be..8c16f40023 100644--- a/packages/views/issues/components/issues-page.tsx+++ b/packages/views/issues/components/issues-page.tsx@@ -65,7 +65,7 @@ export function IssuesPage() {issues={controller.surfaceIssues}workingIssues={workingIssues}isRefreshing={controller.isRefreshing}- facetCountsExact={controller.viewMode !== "table"}+ facetCountsExact={controller.facetCountsExact}tableFacetCounts={controller.tableFacetCounts}onTableFacetChange={controller.setActiveTableFacet}/>diff --git a/packages/views/issues/components/list-view.tsx b/packages/views/issues/components/list-view.tsxindex 07c6966fc5..91e639107a 100644--- a/packages/views/issues/components/list-view.tsx+++ b/packages/views/issues/components/list-view.tsx@@ -18,8 +18,6 @@ import { SortableContext, verticalListSortingStrategy, arrayMove } from "@dnd-kiimport { Virtuoso } from "react-virtuoso";import { Button } from "@multica/ui/components/ui/button";import type { Issue, IssueStatus, Project } from "@multica/core/types";-import { useLoadMoreByStatus } from "@multica/core/issues/mutations";-import type { IssueSortParam, MyIssuesFilter } from "@multica/core/issues/queries";import { useViewStore } from "@multica/core/issues/stores/view-store-context";import { StatusHeading } from "./status-heading";import { ListRow, DraggableListRow, type ChildProgress } from "./list-row";@@ -33,6 +31,7 @@ import {buildColumns,computePosition,findColumn,+ getMoveAnchors,insertIdByPosition,issueMatchesGroup,getMoveUpdates,@@ -40,6 +39,10 @@ import {import type { BoardColumnGroup } from "./board-column";import { useIssueSurfaceSelection } from "../surface/selection-context";import type { IssueCreateDefaults } from "../surface/types";+import type {+ IssueStatusPageState,+ IssueStatusPagination,+} from "../surface/use-issue-status-branches";import { VirtuosoSeed, VIRTUOSO_SEED_COUNT } from "../../common/virtuoso-seed";import { DeferredTooltip } from "../../common/deferred-tooltip";import { useRestoredScrollRef } from "../../platform";@@ -73,23 +76,19 @@ function ListViewImpl({visibleStatuses,childProgressMap = EMPTY_PROGRESS_MAP,projectMap,- myIssuesScope,- myIssuesFilter,+ statusPagination,projectId,onMoveIssue,onCreateIssue,- sort,}: {issues: Issue[];visibleStatuses: IssueStatus[];childProgressMap?: Map<string, ChildProgress>;projectMap?: Map<string, Project>;- myIssuesScope?: string;- myIssuesFilter?: MyIssuesFilter;+ statusPagination: IssueStatusPagination;projectId?: string;onMoveIssue?: (issueId: string, updates: DragMoveUpdates, onSettled?: () => void) => void;onCreateIssue?: (defaults: IssueCreateDefaults) => void;- sort?: IssueSortParam;}) {const listCollapsedStatuses = useViewStore((s) => s.listCollapsedStatuses@@ -113,10 +112,6 @@ function ListViewImpl({[visibleStatuses, listCollapsedStatuses]);- const myIssuesOpts = myIssuesScope- ? { scope: myIssuesScope, filter: myIssuesFilter ?? {} }- : undefined;-const dragEnabled = !!onMoveIssue;const groups = useMemo(@@ -275,17 +270,24 @@ function ListViewImpl({// jumped across when the mutation settled — the same "snaps back, then// moves" glitch the board view had. Placement mirrors the cache// (insertIdByPosition) so the settle rebuild is a visual no-op.+ const targetIds = insertIdByPosition(+ (cols[finalCol] ?? []).filter((id) => id !== activeId),+ activeId,+ currentIssue.position,+ map,+ );setColumns((prev) => {const fromIds = (prev[activeCol] ?? []).filter((cid) => cid !== activeId);- const toIds = insertIdByPosition(- prev[finalCol] ?? [],- activeId,- currentIssue.position,- map,- );- return { ...prev, [activeCol]: fromIds, [finalCol]: toIds };+ return { ...prev, [activeCol]: fromIds, [finalCol]: targetIds };});- onMoveIssue(activeId, getMoveUpdates(finalGroup, currentIssue.position), beginSettle());+ onMoveIssue(+ activeId,+ {+ ...getMoveUpdates(finalGroup, currentIssue.position),+ ...getMoveAnchors(targetIds, activeId),+ },+ beginSettle(),+ );return;}@@ -304,7 +306,14 @@ function ListViewImpl({// beginSettle() also bumps settleVersion on settle (board-view did, this// branch did not) so a failed position move reverts instead of stranding// the row at the drop target.- onMoveIssue(activeId, getMoveUpdates(finalGroup, newPosition), beginSettle());+ onMoveIssue(+ activeId,+ {+ ...getMoveUpdates(finalGroup, newPosition),+ ...getMoveAnchors(finalIds, activeId),+ },+ beginSettle(),+ );},[issues, groups, onMoveIssue, groupIds, groupMap, sortBy, beginSettle, setColumns, columnsRef, isDraggingRef],);@@ -353,13 +362,12 @@ function ListViewImpl({issueMap={issueMapRef.current}childProgressMap={childProgressMap}projectMap={projectMap}- myIssuesOpts={myIssuesOpts}+ page={statusPagination[status]}projectId={projectId}onCreateIssue={onCreateIssue}dragEnabled={dragEnabled}isExpanded={isExpanded}sortLabel={sortLabel}- sort={sort}scrollParent={scrollEl}/>);@@ -405,13 +413,12 @@ function StatusAccordionItem({issueMap,childProgressMap,projectMap,- myIssuesOpts,+ page,projectId,onCreateIssue,dragEnabled,isExpanded,sortLabel,- sort,scrollParent,}: {status: IssueStatus;@@ -419,13 +426,12 @@ function StatusAccordionItem({issueMap: Map<string, Issue>;childProgressMap: Map<string, ChildProgress>;projectMap?: Map<string, Project>;- myIssuesOpts?: { scope: string; filter: MyIssuesFilter };+ page: IssueStatusPageState;projectId?: string;onCreateIssue?: (defaults: IssueCreateDefaults) => void;dragEnabled: boolean;isExpanded: boolean;sortLabel: string | null;- sort?: IssueSortParam;scrollParent: HTMLElement | null;}) {const { t } = useT("issues");@@ -433,11 +439,6 @@ function StatusAccordionItem({const selectedIds = selection.selectedIds;const select = selection.select;const deselect = selection.deselect;- const { loadMore, hasMore, isLoading, total } = useLoadMoreByStatus(- status,- myIssuesOpts,- sort,- );const issues = useMemo(() => issueIds.flatMap((id) => {@@ -461,11 +462,33 @@ function StatusAccordionItem({// The infinite-scroll sentinel rides Virtuoso's Footer so it sits at the true// end of the virtualized rows and still fires loadMore when scrolled to it.const listComponents = useMemo(- () =>- hasMore- ? { Footer: () => <InfiniteScrollSentinel onVisible={loadMore} loading={isLoading} /> }- : EMPTY_VIRTUOSO_COMPONENTS,- [hasMore, loadMore, isLoading],+ () => {+ if (page.isError) {+ return {+ Footer: () => (+ <button+ type="button"+ className="w-full py-2 text-xs text-destructive hover:underline"+ onClick={page.retry}+ >+ {t(($) => $.table.load_more_failed_retry)}+ </button>+ ),+ };+ }+ if (page.hasMore) {+ return {+ Footer: () => (+ <InfiniteScrollSentinel+ onVisible={page.loadMore}+ loading={page.isLoading || page.isFetching}+ />+ ),+ };+ }+ return EMPTY_VIRTUOSO_COMPONENTS;+ },+ [page, t],);const computeItemKey = (_index: number, issue: Issue) => issue.id;@@ -549,7 +572,7 @@ function StatusAccordionItem({</div><Accordion.Trigger className="group/trigger flex flex-1 items-center gap-2 px-2 h-full text-left outline-none cursor-pointer"><ChevronRight className="size-3.5 shrink-0 text-muted-foreground transition-transform group-aria-expanded/trigger:rotate-90" />- <StatusHeading status={status} count={total} />+ <StatusHeading status={status} count={page.total} /></Accordion.Trigger>{onCreateIssue && (<div className="pr-2">diff --git a/packages/views/issues/components/swimlane-view.test.tsx b/packages/views/issues/components/swimlane-view.test.tsxindex 099ac5ff23..12d355e4a7 100644--- a/packages/views/issues/components/swimlane-view.test.tsx+++ b/packages/views/issues/components/swimlane-view.test.tsx@@ -4,7 +4,11 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { SwimLaneView } from "./swimlane-view";import { IssueContextMenuProvider } from "../actions";import { ScrollRestorationProvider } from "../../platform";-import type { Issue } from "@multica/core/types";+import type {+ Issue,+ IssueTableGroupDescriptor,+} from "@multica/core/types";+import type { IssueGroupBranches } from "../surface/use-issue-group-branches";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../../locales/en/common.json";import enIssues from "../../locales/en/issues.json";@@ -344,6 +348,47 @@ const mockIssues: Issue[] = [},];+function makeServerBranches(+ descriptors: IssueTableGroupDescriptor[],+ issues: Issue[],+): IssueGroupBranches {+ const pagination = Object.fromEntries(+ descriptors.flatMap((descriptor) =>+ (descriptor.secondary_groups ?? []).map((cell) => [+ cell.key,+ {+ total: cell.count,+ loaded: issues.filter(+ (issue) =>+ cell.value.kind === "status" &&+ issue.status === cell.value.status,+ ).length,+ hasMore: false,+ isLoading: false,+ isFetching: false,+ isError: false,+ loadMore: vi.fn(),+ retry: vi.fn(),+ },+ ]),+ ),+ );+ return {+ enabled: true,+ descriptors,+ issues,+ pagination,+ total: issues.length,+ isLoading: false,+ isRefreshing: false,+ isError: false,+ hasMoreGroups: false,+ isLoadingMoreGroups: false,+ loadMoreGroups: vi.fn(),+ retryGroups: vi.fn(),+ };+}+function renderWithI18n(ui: React.ReactNode) {const qc = new QueryClient({defaultOptions: { queries: { retry: false, gcTime: 0 } },@@ -645,6 +690,121 @@ describe("SwimLaneView", () => {expect(screen.getAllByText("Parent Issue 1")).toHaveLength(1);});+ it("hides hidden-only server parent lanes and keeps the parent as a card", () => {+ const parent = mockIssues[0]!;+ const descriptors: IssueTableGroupDescriptor[] = [+ {+ key: "parent:parent-1",+ value: {+ kind: "parent",+ parent_id: "parent-1",+ parent: {+ id: "parent-1",+ number: 1,+ identifier: "PROJ-1",+ title: "Parent Issue 1",+ status: "todo",+ },+ value_state: "value",+ },+ count: 1,+ secondary_groups: [{+ key: "compound:cGFyZW50OnBhcmVudC0x:status:done",+ value: { kind: "status", status: "done" },+ count: 1,+ }],+ },+ {+ key: "parent:none",+ value: {+ kind: "parent",+ parent_id: null,+ parent: null,+ value_state: "unset",+ },+ count: 1,+ secondary_groups: [{+ key: "compound:cGFyZW50Om5vbmU:status:todo",+ value: { kind: "status", status: "todo" },+ count: 1,+ }],+ },+ ];++ renderWithI18n(+ <SwimLaneView+ issues={[parent]}+ visibleStatuses={["todo"]}+ hiddenStatuses={["done"]}+ groupBranches={makeServerBranches(descriptors, [parent])}+ onMoveIssue={vi.fn()}+ />,+ );++ expect(screen.getAllByText("Parent Issue 1")).toHaveLength(1);+ expect(+ screen.queryByRole("link", { name: "Open parent issue" }),+ ).not.toBeInTheDocument();+ });++ it("does not render a server parent header again as a No-parent card", () => {+ const parent = mockIssues[0]!;+ const child = { ...mockIssues[1]!, status: "todo" as const };+ const descriptors: IssueTableGroupDescriptor[] = [+ {+ key: "parent:parent-1",+ value: {+ kind: "parent",+ parent_id: "parent-1",+ parent: {+ id: "parent-1",+ number: 1,+ identifier: "PROJ-1",+ title: "Parent Issue 1",+ status: "todo",+ },+ value_state: "value",+ },+ count: 1,+ secondary_groups: [{+ key: "compound:cGFyZW50OnBhcmVudC0x:status:todo",+ value: { kind: "status", status: "todo" },+ count: 1,+ }],+ },+ {+ key: "parent:none",+ value: {+ kind: "parent",+ parent_id: null,+ parent: null,+ value_state: "unset",+ },+ count: 1,+ secondary_groups: [{+ key: "compound:cGFyZW50Om5vbmU:status:todo",+ value: { kind: "status", status: "todo" },+ count: 1,+ }],+ },+ ];++ renderWithI18n(+ <SwimLaneView+ issues={[parent, child]}+ visibleStatuses={["todo"]}+ groupBranches={makeServerBranches(descriptors, [parent, child])}+ onMoveIssue={vi.fn()}+ />,+ );++ expect(screen.getAllByText("Parent Issue 1")).toHaveLength(1);+ expect(+ screen.getByRole("link", { name: "Open parent issue" }),+ ).toBeInTheDocument();+ expect(screen.getByText("Child Issue 1")).toBeInTheDocument();+ });+it("does not call onMoveIssue when a card is dragged out of 'Other parents'", () => {const mockOnMoveIssue = vi.fn();renderWithI18n(@@ -726,7 +886,13 @@ describe("SwimLaneView", () => {expect(mockOnMoveIssue).toHaveBeenCalledWith("orphan-1",- { parent_issue_id: null, status: "in_progress", position: 300 },+ {+ parent_issue_id: null,+ status: "in_progress",+ position: 300,+ before_id: null,+ after_id: null,+ },expect.any(Function),);});diff --git a/packages/views/issues/components/swimlane-view.tsx b/packages/views/issues/components/swimlane-view.tsxindex e25db44241..a269b486b1 100644--- a/packages/views/issues/components/swimlane-view.tsx+++ b/packages/views/issues/components/swimlane-view.tsx@@ -24,12 +24,14 @@ import type {Issue,IssueAssigneeType,IssueStatus,+ IssueTableGroupDescriptor,Project,UpdateIssueRequest,} from "@multica/core/types";import { useViewStore, useViewStoreApi } from "@multica/core/issues/stores/view-store-context";import { agentTaskSnapshotOptions } from "@multica/core/agents";import { filterIssues, type IssueFilters } from "../utils/filter";+import { getMoveAnchors } from "../utils/drag-utils";import type { SwimlaneGrouping } from "@multica/core/issues/stores/view-store";import { useWorkspacePaths } from "@multica/core/paths";import { useWorkspaceId } from "@multica/core/hooks";@@ -62,6 +64,10 @@ import type { ChildProgress } from "./list-row";import { useT } from "../../i18n";import type { IssueActivityState } from "../surface/activity";import type { IssueCreateDefaults } from "../surface/types";+import type {+ IssueGroupBranches,+ IssueGroupPageState,+} from "../surface/use-issue-group-branches";const COLUMN_WIDTH = 280;const COLUMN_GAP = 16;@@ -81,7 +87,7 @@ function combineChildrenLists(return results.map((r) => r.data);}-type SwimLaneMoveUpdates = Pick<+type SwimLaneMoveTargetUpdates = Pick<UpdateIssueRequest,| "parent_issue_id"| "project_id"@@ -91,6 +97,11 @@ type SwimLaneMoveUpdates = Pick<| "position">;+type SwimLaneMoveUpdates = SwimLaneMoveTargetUpdates & {+ before_id: string | null;+ after_id: string | null;+};+function makeSwimLaneCollision(cellIds: Set<string>): CollisionDetection {return (args) => {const activeId = args.active.id as string;@@ -216,7 +227,7 @@ interface LaneGroup {title: string;identifier: string;/** Parent issue (parent grouping only) — drives the open-parent link + status icon in the header. */- parentIssue: Issue | null;+ parentIssue: Pick<Issue, "id" | "status"> | null;/** Project metadata (project grouping only) — drives the icon in the header. */project: Project | null;/** Actor (assignee grouping only) — drives the avatar in the header. */@@ -227,7 +238,12 @@ interface LaneGroup {* Payload fragment emitted to `onMoveIssue` when an issue is dropped into* this lane. Status + position are filled in by the drag-end handler.*/- moveUpdates: SwimLaneMoveUpdates;+ moveUpdates: SwimLaneMoveTargetUpdates;+ /** Exact server count; legacy builders leave this undefined and use the+ * loaded cell window as before. */+ total?: number;+ /** Opaque compound row keys by status. */+ serverCellKeys?: Partial<Record<IssueStatus, string>>;}const EMPTY_PROGRESS_MAP = new Map<string, ChildProgress>();@@ -452,6 +468,139 @@ function buildAssigneeLanes(];}+function buildServerLanes(+ descriptors: readonly IssueTableGroupDescriptor[],+ grouping: SwimlaneGrouping,+ visibleStatuses: readonly IssueStatus[],+ projects: ReadonlyMap<string, Project> | undefined,+ getActorName: (type: string, id: string) => string,+ storedOrder: string[],+ labels: {+ noParent: string;+ otherParents: string;+ noProject: string;+ noAssignee: string;+ },+): LaneGroup[] {+ const visibleStatusSet = new Set(visibleStatuses);+ const lanes = descriptors.flatMap((descriptor): LaneGroup[] => {+ if (+ (descriptor.secondary_groups ?? []).every(+ (secondary) =>+ secondary.value.kind !== "status" ||+ !visibleStatusSet.has(secondary.value.status as IssueStatus) ||+ secondary.count === 0,+ )+ ) {+ return [];+ }+ const serverCellKeys = Object.fromEntries(+ (descriptor.secondary_groups ?? []).flatMap((secondary) =>+ secondary.value.kind === "status"+ ? [[secondary.value.status, secondary.key]]+ : [],+ ),+ ) as Partial<Record<IssueStatus, string>>;+ const value = descriptor.value;+ if (grouping === "assignee" && value.kind === "assignee") {+ const actorRef = value.actor;+ const actor: { type: IssueAssigneeType; id: string } | null =+ actorRef &&+ (actorRef.type === "member" ||+ actorRef.type === "agent" ||+ actorRef.type === "squad")+ ? { type: actorRef.type, id: actorRef.id }+ : null;+ const rawId = actor ? `${actor.type}:${actor.id}` : NONE_LANE_ID;+ return [{+ key: `assignee:${rawId}`,+ rawId,+ isPinned: actor === null,+ isOrphan: false,+ title: actor+ ? getActorName(actor.type, actor.id)+ : labels.noAssignee,+ identifier: "",+ parentIssue: null,+ project: null,+ actor,+ matches: (issue) =>+ actor+ ? issue.assignee_type === actor.type &&+ issue.assignee_id === actor.id+ : issue.assignee_type === null && issue.assignee_id === null,+ moveUpdates: actor+ ? { assignee_type: actor.type, assignee_id: actor.id }+ : { assignee_type: null, assignee_id: null },+ total: descriptor.count,+ serverCellKeys,+ }];+ }+ if (grouping === "project" && value.kind === "project") {+ const rawId = value.project_id ?? NONE_LANE_ID;+ const project = value.project_id+ ? projects?.get(value.project_id) ?? null+ : null;+ return [{+ key: `project:${rawId}`,+ rawId,+ isPinned: value.project_id === null,+ isOrphan: false,+ title: value.project_id ? project?.title ?? "" : labels.noProject,+ identifier: "",+ parentIssue: null,+ project,+ actor: null,+ matches: (issue) => issue.project_id === value.project_id,+ moveUpdates: { project_id: value.project_id },+ total: descriptor.count,+ serverCellKeys,+ }];+ }+ if (grouping === "parent" && value.kind === "parent") {+ const rawId = value.parent_id ?? NONE_LANE_ID;+ const unavailable = value.value_state === "unavailable";+ return [{+ key: `parent:${rawId}`,+ rawId,+ isPinned: value.parent_id === null || unavailable,+ isOrphan: unavailable,+ title:+ value.parent?.title ??+ (unavailable ? labels.otherParents : labels.noParent),+ identifier: value.parent?.identifier ?? "",+ parentIssue: value.parent+ ? { id: value.parent.id, status: value.parent.status as IssueStatus }+ : null,+ project: null,+ actor: null,+ matches: (issue) => issue.parent_issue_id === value.parent_id,+ moveUpdates: unavailable+ ? {}+ : { parent_issue_id: value.parent_id },+ total: descriptor.count,+ serverCellKeys,+ }];+ }+ return [];+ });+ const orderIndex = new Map<string, number>();+ storedOrder.forEach((rawId, index) => orderIndex.set(rawId, index));+ const originalIndex = new Map(+ lanes.map((lane, index) => [lane.rawId, index]),+ );+ return lanes.toSorted((a, b) => {+ if (a.isPinned !== b.isPinned) return a.isPinned ? -1 : 1;+ const ai = orderIndex.get(a.rawId);+ const bi = orderIndex.get(b.rawId);+ if (ai !== undefined && bi !== undefined) return ai - bi;+ if (ai !== undefined) return -1;+ if (bi !== undefined) return 1;+ return (originalIndex.get(a.rawId) ?? 0) -+ (originalIndex.get(b.rawId) ?? 0);+ });+}+function SwimLaneViewImpl({issues,unfilteredIssues,@@ -467,6 +616,7 @@ function SwimLaneViewImpl({projectId,activityByIssueId,onCreateIssue,+ groupBranches,}: {issues: Issue[];/**@@ -496,6 +646,7 @@ function SwimLaneViewImpl({projectId?: string;activityByIssueId?: ReadonlyMap<string, IssueActivityState>;onCreateIssue?: (defaults: IssueCreateDefaults) => void;+ groupBranches?: IssueGroupBranches;}) {const { t } = useT("issues");const paths = useWorkspacePaths();@@ -587,7 +738,7 @@ function SwimLaneViewImpl({// loaded, grandchild past page — the bug this PR fixes)const qc = useQueryClient();const batchParentIds = useMemo(() => {- if (swimlaneGrouping !== "parent") return [];+ if (groupBranches?.enabled || swimlaneGrouping !== "parent") return [];const ids = new Set<string>();const consider = (id: string | null | undefined) => {if (!id) return;@@ -601,7 +752,7 @@ function SwimLaneViewImpl({if (progress && progress.total > 0) consider(issue.id);}return Array.from(ids).sort();- }, [swimlaneGrouping, issues, childProgressMap]); // eslint-disable-line react-hooks/exhaustive-deps+ }, [groupBranches?.enabled, swimlaneGrouping, issues, childProgressMap]); // eslint-disable-line react-hooks/exhaustive-depsconst { data: batchChildrenMap } = useQuery(childrenByParentsOptions(wsId, batchParentIds, qc),@@ -614,7 +765,7 @@ function SwimLaneViewImpl({const subscribedRef = useRef<Set<string>>(new Set());const sortedSubscribedRef = useRef<string[]>([]);const subscribedParentIds = useMemo(() => {- if (swimlaneGrouping !== "parent") {+ if (groupBranches?.enabled || swimlaneGrouping !== "parent") {if (subscribedRef.current.size > 0) {subscribedRef.current = new Set();sortedSubscribedRef.current = [];@@ -631,7 +782,7 @@ function SwimLaneViewImpl({if (batchChildrenMap) for (const id of batchChildrenMap.keys()) add(id);if (changed) sortedSubscribedRef.current = Array.from(subscribedRef.current).sort();return sortedSubscribedRef.current;- }, [swimlaneGrouping, issues, batchChildrenMap]);+ }, [groupBranches?.enabled, swimlaneGrouping, issues, batchChildrenMap]);// Pure cache observers — enabled:false so no fetch fires, just re-renders// when setQueryData writes to these keys (from batch hydration, optimistic@@ -648,6 +799,7 @@ function SwimLaneViewImpl({// Merge paginated issues with batch-fetched children so parent lanes are// populated even when children are beyond the first page.const mergedIssues = useMemo(() => {+ if (groupBranches?.enabled) return issues;if (swimlaneGrouping !== "parent") return issues;const existingIds = new Set(issues.map((i) => i.id));const extra: Issue[] = [];@@ -676,9 +828,20 @@ function SwimLaneViewImpl({}const filteredExtra = filterIssues(extra, activeFilters);return filteredExtra.length === 0 ? issues : [...issues, ...filteredExtra];- }, [swimlaneGrouping, issues, perParentChildrenLists, subscribedParentIds, batchChildrenMap, activeFilters]);+ }, [groupBranches?.enabled, swimlaneGrouping, issues, perParentChildrenLists, subscribedParentIds, batchChildrenMap, activeFilters]);const laneGroups = useMemo<LaneGroup[]>(() => {+ if (groupBranches?.enabled) {+ return buildServerLanes(+ groupBranches.descriptors,+ swimlaneGrouping,+ sortedStatuses,+ projectMap,+ getActorName,+ swimlaneOrder,+ laneLabels,+ );+ }if (swimlaneGrouping === "project") {return buildProjectLanes(issues, projects, swimlaneOrder, laneLabels);}@@ -698,6 +861,9 @@ function SwimLaneViewImpl({getActorName,swimlaneOrder,laneLabels,+ groupBranches,+ projectMap,+ sortedStatuses,]);// For parent grouping: issues that are themselves lane headers should not@@ -705,7 +871,9 @@ function SwimLaneViewImpl({// never collide this way (lanes are projects/actors, not issues), so the// set is empty there.const headerIssueIds = useMemo(() => {- if (swimlaneGrouping !== "parent") return EMPTY_HEADER_IDS;+ if (swimlaneGrouping !== "parent") {+ return EMPTY_HEADER_IDS;+ }return new Set(laneGroups.filter((g) => g.parentIssue !== null)@@ -791,13 +959,24 @@ function SwimLaneViewImpl({// parent gets promoted to a lane header and the count for that status// drops by 1. Tracked as a follow-up.const statusTotals = useMemo(() => {+ if (groupBranches?.enabled) {+ const totals = new Map<IssueStatus, number>();+ for (const lane of groupBranches.descriptors) {+ for (const cell of lane.secondary_groups ?? []) {+ if (cell.value.kind !== "status") continue;+ const status = cell.value.status as IssueStatus;+ totals.set(status, (totals.get(status) ?? 0) + cell.count);+ }+ }+ return totals;+ }const totals = new Map<IssueStatus, number>();for (const issue of laneSourceIssues) {if (headerIssueIds.has(issue.id)) continue;totals.set(issue.status, (totals.get(issue.status) ?? 0) + 1);}return totals;- }, [laneSourceIssues, headerIssueIds]);+ }, [groupBranches, laneSourceIssues, headerIssueIds]);// Collapsed swimlanes — persisted per-grouping via the view store. The// store keys are raw lane ids (or sentinel `NONE_LANE_ID` / `ORPHAN_LANE_ID`@@ -1130,6 +1309,7 @@ function SwimLaneViewImpl({...targetLane.moveUpdates,status: finalOverCell.status as IssueStatus,position: newPosition,+ ...getMoveAnchors(finalIds, activeId),},() => {isSettlingRef.current = false;@@ -1174,18 +1354,37 @@ function SwimLaneViewImpl({// true end of the lane list; pt-4 reproduces the previous gap-4.const laneComponents = useMemo(() => ({- Footer: () => (- <div className="pt-4">- <SwimLaneLoadMoreRow- sortedStatuses={sortedStatuses}- gridStyle={gridStyle}- myIssuesOpts={myIssuesOpts}- sort={sort}- />- </div>- ),+ Footer: () =>+ groupBranches?.enabled ? (+ groupBranches.hasMoreGroups ? (+ <div className="pt-4">+ <InfiniteScrollSentinel+ onVisible={groupBranches.loadMoreGroups}+ loading={groupBranches.isLoadingMoreGroups}+ />+ </div>+ ) : null+ ) : (+ <div className="pt-4">+ <SwimLaneLoadMoreRow+ sortedStatuses={sortedStatuses}+ gridStyle={gridStyle}+ myIssuesOpts={myIssuesOpts}+ sort={sort}+ />+ </div>+ ),}),- [sortedStatuses, gridStyle, myIssuesOpts, sort],+ [+ groupBranches?.enabled,+ groupBranches?.hasMoreGroups,+ groupBranches?.isLoadingMoreGroups,+ groupBranches?.loadMoreGroups,+ sortedStatuses,+ gridStyle,+ myIssuesOpts,+ sort,+ ],);const computeLaneKey = (_index: number, lane: LaneGroup) => lane.key;@@ -1205,6 +1404,7 @@ function SwimLaneViewImpl({paths={paths}projectId={projectId}onCreateIssue={onCreateIssue}+ groupPagination={groupBranches?.pagination}/></div>);@@ -1219,6 +1419,15 @@ function SwimLaneViewImpl({><div ref={attachScroller} data-tab-scroll-root="swimlane" className="flex flex-1 min-h-0 gap-4 overflow-auto p-4"><div className="flex shrink-0 flex-col" style={{ width: `${trackWidth}px` }}>+ {groupBranches?.isError && laneGroups.length === 0 && (+ <button+ type="button"+ className="py-8 text-sm text-destructive hover:underline"+ onClick={groupBranches.retryGroups}+ >+ {t(($) => $.table.load_more_failed_retry)}+ </button>+ )}{/* Sticky status header row — visually matches the top of a BoardColumn */}<div className="sticky top-0 z-10 mb-2 bg-background/95 pb-2 backdrop-blur supports-[backdrop-filter]:bg-background/75"><div style={gridStyle}>@@ -1369,6 +1578,7 @@ function DraggableSwimLane({paths,projectId,onCreateIssue,+ groupPagination,}: {lane: LaneGroup;grouping: SwimlaneGrouping;@@ -1383,6 +1593,7 @@ function DraggableSwimLane({paths: ReturnType<typeof useWorkspacePaths>;projectId?: string;onCreateIssue?: (defaults: IssueCreateDefaults) => void;+ groupPagination?: Record<string, IssueGroupPageState>;}) {const { t } = useT("issues");const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({@@ -1395,10 +1606,15 @@ function DraggableSwimLane({transition,};- const laneTotal = sortedStatuses.reduce(- (sum, s) => sum + (localCells[lane.key]?.[s]?.length ?? 0),- 0,- );+ const laneTotal = sortedStatuses.reduce((sum, status) => {+ const serverKey = lane.serverCellKeys?.[status];+ return (+ sum ++ (serverKey+ ? (groupPagination?.[serverKey]?.total ?? 0)+ : (localCells[lane.key]?.[status]?.length ?? 0))+ );+ }, 0);return (<div ref={setNodeRef} style={style} className={`flex flex-col ${isDragging ? "opacity-50" : ""}`}>@@ -1481,6 +1697,11 @@ function DraggableSwimLane({projectId={projectId}onCreateIssue={onCreateIssue}readOnly={lane.isOrphan}+ page={+ lane.serverCellKeys?.[status]+ ? groupPagination?.[lane.serverCellKeys[status]!]+ : undefined+ }/>);})}@@ -1501,6 +1722,7 @@ function SwimLaneCell({projectId,onCreateIssue,readOnly = false,+ page,}: {cellId: string;issueIds: string[];@@ -1518,6 +1740,7 @@ function SwimLaneCell({* belong to parents we don't have loaded.*/readOnly?: boolean;+ page?: IssueGroupPageState;}) {// The orphan cell stays enabled in the collision graph so that drops// onto its whitespace area are absorbed here instead of falling through@@ -1572,6 +1795,20 @@ function SwimLaneCell({—</p>)}+ {page?.isError ? (+ <button+ type="button"+ className="w-full py-2 text-xs text-destructive hover:underline"+ onClick={page.retry}+ >+ {t(($) => $.table.load_more_failed_retry)}+ </button>+ ) : page?.hasMore ? (+ <InfiniteScrollSentinel+ onVisible={page.loadMore}+ loading={page.isLoading || page.isFetching}+ />+ ) : null}</div>{/* One of these per lane×status cell (~170 on a real swimlane) —eagerly mounted tooltip roots here were the single largest slicediff --git a/packages/views/issues/components/table-view.tsx b/packages/views/issues/components/table-view.tsxindex d6d195f3d6..92954683c1 100644--- a/packages/views/issues/components/table-view.tsx+++ b/packages/views/issues/components/table-view.tsx@@ -1664,6 +1664,17 @@ export function TableView({? getActorName(value.actor.type, value.actor.id): t(($) => $.table.unassigned);}+ if (value.kind === "project") {+ return value.project_id+ ? value.project_id+ : t(($) => $.swimlane.no_project);+ }+ if (value.kind === "parent") {+ if (value.value_state === "unset") {+ return t(($) => $.swimlane.no_parent);+ }+ return value.parent?.title ?? t(($) => $.table.value_unavailable);+ }if (value.value_state === "unset") return t(($) => $.table.no_value);if (value.value_state === "unavailable") {return t(($) => $.table.value_unavailable);diff --git a/packages/views/issues/surface/issue-surface.test.tsx b/packages/views/issues/surface/issue-surface.test.tsxindex fd648b5b31..e9be43cc36 100644--- a/packages/views/issues/surface/issue-surface.test.tsx+++ b/packages/views/issues/surface/issue-surface.test.tsx@@ -22,6 +22,7 @@ import type {ListIssuesResponse,} from "@multica/core/types";import { IssueSurface } from "./issue-surface";+import { statusTableMethodsFromLegacy } from "./status-table-test-api";// Mutable so tests can simulate a workspace switch — the workspace layout// does not remount its children on switch, so the surface must handle the@@ -158,6 +159,7 @@ describe("IssueSurface — scope switch loading semantics", () => {});setApiInstance({listIssues,+ ...statusTableMethodsFromLegacy(listIssues),listGroupedIssues: vi.fn(() => never()),listProjects: vi.fn(() => never()),getAgentTaskSnapshot: vi.fn(() => never<AgentTask[]>()),@@ -244,6 +246,7 @@ describe("IssueSurface — scope switch loading semantics", () => {});setApiInstance({listIssues,+ ...statusTableMethodsFromLegacy(listIssues),listGroupedIssues: vi.fn(() => never()),listProjects: vi.fn(() => never()),getAgentTaskSnapshot: vi.fn(() => never<AgentTask[]>()),diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsxindex 0359d68e60..7f99daa87c 100644--- a/packages/views/issues/surface/issue-surface.tsx+++ b/packages/views/issues/surface/issue-surface.tsx@@ -53,6 +53,7 @@ export function IssueSurface({modes,surfaceKey,createDefaults,+ search,renderHeader,renderEmpty,renderLoading,@@ -98,6 +99,7 @@ export function IssueSurface({scope={scope}modes={modes}createDefaults={createDefaults}+ search={search}renderHeader={renderHeader}renderEmpty={renderEmpty}renderLoading={renderLoading}@@ -114,6 +116,7 @@ function IssueSurfaceContent({scope,modes,createDefaults,+ search,renderHeader,renderEmpty,renderLoading,@@ -127,6 +130,7 @@ function IssueSurfaceContent({scope,modes,createDefaults,+ search,});const [tableLoadedIssues, setTableLoadedIssues] = useState<Issue[]>([]);const handleTableLoadedIssuesChange = useCallback((next: Issue[]) => {@@ -211,7 +215,7 @@ function IssueSurfaceContent({allowGantt={controller.allowGantt}isRefreshing={controller.isRefreshing}facetCountsExact={- controller.viewMode !== "table"+ controller.facetCountsExact}tableFacetCounts={controller.tableFacetCounts}onTableFacetChange={controller.setActiveTableFacet}@@ -260,6 +264,8 @@ function IssueSurfaceContent({sort={controller.sort}projectId={controller.projectId}onCreateIssue={openCreateIssue}+ statusPagination={controller.statusPagination}+ groupBranches={controller.groupBranches}/>)}{controller.viewMode === "list" && (@@ -268,12 +274,10 @@ function IssueSurfaceContent({visibleStatuses={controller.visibleStatuses}childProgressMap={controller.childProgressMap}projectMap={controller.projectMap}- myIssuesScope={controller.loadMoreScope}- myIssuesFilter={controller.loadMoreFilter}- sort={controller.sort}projectId={controller.projectId}onMoveIssue={controller.moveIssue}onCreateIssue={openCreateIssue}+ statusPagination={controller.statusPagination!}/>)}{controller.viewMode === "table" && (@@ -307,6 +311,7 @@ function IssueSurfaceContent({projectId={controller.projectId}activityByIssueId={controller.activity.activityByIssueId}onCreateIssue={openCreateIssue}+ groupBranches={controller.groupBranches}/>)}</div>diff --git a/packages/views/issues/surface/status-table-test-api.ts b/packages/views/issues/surface/status-table-test-api.tsnew file mode 100644index 0000000000..7baf5601a5--- /dev/null+++ b/packages/views/issues/surface/status-table-test-api.ts@@ -0,0 +1,291 @@+import { ALL_STATUSES } from "@multica/core/issues/config";+import type {+ Issue,+ IssueTableGroupDescriptor,+ IssueStatus,+ IssueTableFacetsRequest,+ IssueTableGroupsRequest,+ IssueTableQuerySpec,+ IssueTableRowsRequest,+ ListIssuesParams,+ ListIssuesResponse,+} from "@multica/core/types";++type LegacyListIssues = (+ params?: ListIssuesParams,+) => Promise<ListIssuesResponse>;++function legacyParamsForStatus(+ query: IssueTableQuerySpec,+ status: IssueStatus,+): ListIssuesParams {+ const scope = query.scope;+ return {+ status,+ limit: 50,+ offset: 0,+ ...(scope.kind === "project" ? { project_id: scope.project_id } : {}),+ ...(scope.kind === "assignee" && scope.actor+ ? {+ assignee_type: scope.actor.type,+ assignee_id: scope.actor.id,+ }+ : {}),+ ...(scope.kind === "creator" && scope.actor+ ? {+ creator_type: scope.actor.type,+ creator_id: scope.actor.id,+ }+ : {}),+ ...(query.search ? { search: query.search } : {}),+ };+}++async function rowsForStatus(+ listIssues: LegacyListIssues,+ query: IssueTableQuerySpec,+ status: IssueStatus,+) {+ if (+ query.filters.statuses &&+ !query.filters.statuses.includes(status)+ ) {+ return [];+ }+ const response = await listIssues(legacyParamsForStatus(query, status));+ return response.issues.filter((issue) => {+ if (+ query.filters.include_sub_issues === false &&+ issue.parent_issue_id !== null+ ) {+ return false;+ }+ return issue.status === status;+ });+}++async function allRows(+ listIssues: LegacyListIssues,+ query: IssueTableQuerySpec,+) {+ const rows = await Promise.all(+ ALL_STATUSES.map((status) =>+ rowsForStatus(+ listIssues,+ { ...query, filters: { ...query.filters, statuses: undefined } },+ status,+ ),+ ),+ );+ return rows.flat();+}++function primaryDescriptor(+ issue: Issue,+ primary: "assignee" | "project" | "parent",+ issueById: ReadonlyMap<string, Issue>,+): Omit<IssueTableGroupDescriptor, "count" | "secondary_groups"> {+ if (primary === "assignee") {+ const actor =+ issue.assignee_type && issue.assignee_id+ ? { type: issue.assignee_type, id: issue.assignee_id }+ : null;+ return {+ key: actor+ ? `assignee:${actor.type}:${actor.id}`+ : "assignee:unassigned",+ value: { kind: "assignee", actor },+ };+ }+ if (primary === "project") {+ return {+ key: issue.project_id ? `project:${issue.project_id}` : "project:none",+ value: { kind: "project", project_id: issue.project_id },+ };+ }+ const parent = issue.parent_issue_id+ ? issueById.get(issue.parent_issue_id) ?? null+ : null;+ return {+ key: issue.parent_issue_id+ ? `parent:${issue.parent_issue_id}`+ : "parent:none",+ value: {+ kind: "parent",+ parent_id: issue.parent_issue_id,+ parent: parent+ ? {+ id: parent.id,+ number: parent.number,+ identifier: parent.identifier,+ title: parent.title,+ status: parent.status,+ }+ : null,+ value_state: issue.parent_issue_id+ ? parent+ ? "value"+ : "unavailable"+ : "unset",+ },+ };+}++/**+ * Transitional adapter for pre-Table test fixtures. Production code never+ * imports this module; it lets existing surface tests keep their small+ * per-status in-memory data source while asserting the new request contract.+ */+export function statusTableMethodsFromLegacy(listIssues: LegacyListIssues) {+ return {+ listIssueTableGroups: async (request: IssueTableGroupsRequest) => {+ if (request.group.kind === "compound") {+ const issues = await allRows(listIssues, request.query);+ const issueById = new Map(issues.map((issue) => [issue.id, issue]));+ const grouped = new Map<+ string,+ {+ descriptor: ReturnType<typeof primaryDescriptor>;+ issues: Issue[];+ }+ >();+ for (const issue of issues) {+ const descriptor = primaryDescriptor(+ issue,+ request.group.primary,+ issueById,+ );+ const current = grouped.get(descriptor.key) ?? {+ descriptor,+ issues: [],+ };+ current.issues.push(issue);+ grouped.set(descriptor.key, current);+ }+ return {+ query_fingerprint: "test",+ total: issues.length,+ groups: Array.from(grouped.values(), ({ descriptor, issues }) => ({+ ...descriptor,+ count: issues.length,+ secondary_groups: ALL_STATUSES.flatMap((status) => {+ const count = issues.filter((issue) => issue.status === status).length;+ return count+ ? [{+ key: `compound:${descriptor.key}:status:${status}`,+ value: { kind: "status" as const, status },+ count,+ }]+ : [];+ }),+ })),+ next_cursor: null,+ };+ }+ const groups = await Promise.all(+ ALL_STATUSES.map(async (status) => ({+ status,+ issues: await rowsForStatus(listIssues, request.query, status),+ })),+ );+ const nonEmpty = groups.filter(({ issues }) => issues.length > 0);+ return {+ query_fingerprint: "test",+ total: nonEmpty.reduce((sum, group) => sum + group.issues.length, 0),+ groups: nonEmpty.map(({ status, issues }) => ({+ key: `status:${status}`,+ value: { kind: "status" as const, status },+ count: issues.length,+ })),+ next_cursor: null,+ };+ },+ listIssueTableRows: async (request: IssueTableRowsRequest) => {+ if (request.group.kind === "compound") {+ const primary = request.group.primary;+ const marker = request.group_key?.lastIndexOf(":status:") ?? -1;+ const status =+ marker >= 0+ ? request.group_key?.slice(marker + ":status:".length)+ : undefined;+ const primaryKey =+ marker >= 0+ ? request.group_key?.slice("compound:".length, marker)+ : undefined;+ const all = await allRows(listIssues, request.query);+ const issueById = new Map(all.map((issue) => [issue.id, issue]));+ const issues = all.filter((issue) => {+ const descriptor = primaryDescriptor(+ issue,+ primary,+ issueById,+ );+ return descriptor.key === primaryKey && issue.status === status;+ });+ return {+ query_fingerprint: "test",+ group_key: request.group_key,+ parent_id: request.parent_id,+ total: 0,+ rows: issues.map((issue) => ({+ issue,+ direct_child_count: 0,+ })),+ branch_total: issues.length,+ next_cursor: null,+ };+ }+ const rawStatus = request.group_key?.replace(/^status:/, "");+ const status = ALL_STATUSES.find((value) => value === rawStatus);+ const issues = status+ ? await rowsForStatus(listIssues, request.query, status)+ : [];+ return {+ query_fingerprint: "test",+ group_key: request.group_key,+ parent_id: request.parent_id,+ total: 0,+ rows: issues.map((issue) => ({+ issue,+ direct_child_count: 0,+ })),+ branch_total: issues.length,+ next_cursor: null,+ };+ },+ listIssueTableFacets: async (request: IssueTableFacetsRequest) => {+ const groups = await Promise.all(+ ALL_STATUSES.map(async (status) => ({+ status,+ issues: await rowsForStatus(+ listIssues,+ {+ ...request.query,+ filters: {+ ...request.query.filters,+ statuses: undefined,+ },+ },+ status,+ ),+ })),+ );+ return {+ query_fingerprint: "test",+ total: groups.reduce((sum, group) => sum + group.issues.length, 0),+ facets: request.facets.map((facet) => ({+ ...facet,+ values:+ facet.kind === "status"+ ? groups+ .filter(({ issues }) => issues.length > 0)+ .map(({ status, issues }) => ({+ key: status,+ count: issues.length,+ }))+ : [],+ })),+ };+ },+ };+}diff --git a/packages/views/issues/surface/types.ts b/packages/views/issues/surface/types.tsindex 95cce2a12b..3894be11db 100644--- a/packages/views/issues/surface/types.ts+++ b/packages/views/issues/surface/types.ts@@ -26,4 +26,6 @@ export interface IssueSurfaceProps {modes: IssueSurfaceMode[];surfaceKey?: string;createDefaults?: IssueCreateDefaults;+ /** Server-owned membership search shared by non-Table issue surfaces. */+ search?: string;}diff --git a/packages/views/issues/surface/use-issue-group-branches.test.tsx b/packages/views/issues/surface/use-issue-group-branches.test.tsxnew file mode 100644index 0000000000..e2dedd4662--- /dev/null+++ b/packages/views/issues/surface/use-issue-group-branches.test.tsx@@ -0,0 +1,282 @@+/**+ * @vitest-environment jsdom+ */+import { afterEach, 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 type {+ Issue,+ IssueTableGroupsRequest,+ IssueTableQuerySpec,+ IssueTableRowsRequest,+} from "@multica/core/types";+import { useIssueGroupBranches } from "./use-issue-group-branches";++function makeIssue(id: string, status: Issue["status"]): Issue {+ return {+ id,+ workspace_id: "ws-1",+ number: id === "child-1" ? 1 : 2,+ identifier: id === "child-1" ? "MUL-1" : "MUL-2",+ title: id,+ description: null,+ status,+ priority: "none",+ assignee_type: null,+ assignee_id: null,+ creator_type: "member",+ creator_id: "user-1",+ parent_issue_id: "parent-1",+ project_id: null,+ position: id === "child-1" ? 1 : 2,+ stage: null,+ start_date: null,+ due_date: null,+ metadata: {},+ properties: {},+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ };+}++const query: IssueTableQuerySpec = {+ scope: { kind: "workspace" },+ filters: { include_sub_issues: true },+ sort: { field: "position", direction: "asc" },+};++function wrapper(queryClient: QueryClient) {+ return function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>+ {children}+ </QueryClientProvider>+ );+ };+}++describe("useIssueGroupBranches", () => {+ afterEach(() => cleanup());++ it("pages group headers only when the surface sentinel asks", async () => {+ const listIssueTableGroups = vi.fn(+ async (request: IssueTableGroupsRequest) => {+ const secondPage = request.page?.cursor === "groups-next";+ return {+ query_fingerprint: "test",+ total: 2,+ groups: [+ {+ key: secondPage+ ? "assignee:unassigned"+ : "assignee:member:user-1",+ value: {+ kind: "assignee" as const,+ actor: secondPage+ ? null+ : { type: "member" as const, id: "user-1" },+ },+ count: 1,+ },+ ],+ next_cursor: secondPage ? null : "groups-next",+ };+ },+ );+ setApiInstance({+ listIssueTableGroups,+ listIssueTableRows: vi.fn(),+ } as unknown as ApiClient);+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const { result } = renderHook(+ () =>+ useIssueGroupBranches({+ wsId: "ws-1",+ query,+ group: { kind: "assignee" },+ enabled: true,+ }),+ { wrapper: wrapper(queryClient) },+ );++ await waitFor(() => expect(result.current.descriptors).toHaveLength(1));+ expect(listIssueTableGroups).toHaveBeenCalledTimes(1);+ expect(result.current.hasMoreGroups).toBe(true);++ act(() => result.current.loadMoreGroups());+ await waitFor(() => expect(result.current.descriptors).toHaveLength(2));+ expect(listIssueTableGroups).toHaveBeenCalledTimes(2);++ queryClient.clear();+ });++ it("keeps exact compound descriptors while paging only visible cells", async () => {+ const first = makeIssue("child-1", "todo");+ const second = makeIssue("child-2", "todo");+ const listIssueTableGroups = vi.fn(async () => ({+ query_fingerprint: "test",+ total: 2,+ groups: [+ {+ key: "parent:parent-1",+ value: {+ kind: "parent" as const,+ parent_id: "parent-1",+ parent: {+ id: "parent-1",+ number: 10,+ identifier: "MUL-10",+ title: "Parent",+ status: "in_progress",+ },+ value_state: "value" as const,+ },+ count: 3,+ secondary_groups: [+ {+ key: "compound:cGFyZW50OnBhcmVudC0x:status:todo",+ value: { kind: "status" as const, status: "todo" },+ count: 2,+ },+ {+ key: "compound:cGFyZW50OnBhcmVudC0x:status:done",+ value: { kind: "status" as const, status: "done" },+ count: 1,+ },+ ],+ },+ ],+ next_cursor: null,+ }));+ const listIssueTableRows = vi.fn(+ async (request: IssueTableRowsRequest) => {+ const continuation = request.page?.cursor === "next";+ return {+ query_fingerprint: "test",+ group_key: request.group_key,+ parent_id: null,+ total: 0,+ rows: [{+ issue: continuation ? second : first,+ direct_child_count: 0,+ }],+ branch_total: 1,+ next_cursor: continuation ? null : "next",+ };+ },+ );+ setApiInstance({+ listIssueTableGroups,+ listIssueTableRows,+ } as unknown as ApiClient);+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });++ const { result } = renderHook(+ () =>+ useIssueGroupBranches({+ wsId: "ws-1",+ query,+ group: {+ kind: "compound",+ primary: "parent",+ secondary: "status",+ secondary_values: ["todo"],+ },+ secondaryValues: ["todo"],+ enabled: true,+ }),+ { wrapper: wrapper(queryClient) },+ );++ await waitFor(() => expect(result.current.descriptors).toHaveLength(1));+ expect(result.current.descriptors[0]?.secondary_groups).toHaveLength(2);+ expect(result.current.total).toBe(2);+ expect(listIssueTableRows).not.toHaveBeenCalled();++ const todoKey =+ result.current.descriptors[0]?.secondary_groups?.[0]?.key ?? "";+ expect(result.current.pagination[todoKey]?.total).toBe(2);+ act(() => result.current.pagination[todoKey]?.loadMore());+ await waitFor(() =>+ expect(result.current.issues.map((issue) => issue.id)).toEqual([+ "child-1",+ ]),+ );+ expect(listIssueTableRows).toHaveBeenCalledTimes(1);+ expect(listIssueTableRows.mock.calls[0]?.[0].group_key).toContain(+ ":status:todo",+ );+ act(() => result.current.pagination[todoKey]?.loadMore());+ await waitFor(() => expect(result.current.issues).toHaveLength(2));+ expect(listIssueTableRows).toHaveBeenCalledTimes(2);++ queryClient.clear();+ });++ it("uses the query-wide compound total before all group pages are loaded", async () => {+ const listIssueTableGroups = vi.fn(async () => ({+ query_fingerprint: "test",+ // A later group page owns the visible card. The loaded descriptor is+ // intentionally hidden-only to catch regressions that reduce `total`+ // from the currently loaded page instead of trusting the server.+ total: 1,+ groups: [+ {+ key: "parent:hidden",+ value: {+ kind: "parent" as const,+ parent_id: "hidden",+ parent: null,+ value_state: "unavailable" as const,+ },+ count: 1,+ secondary_groups: [+ {+ key: "compound:aGlkZGVu:status:done",+ value: { kind: "status" as const, status: "done" },+ count: 1,+ },+ ],+ },+ ],+ next_cursor: "groups-next",+ }));+ setApiInstance({+ listIssueTableGroups,+ listIssueTableRows: vi.fn(),+ } as unknown as ApiClient);+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });++ const { result } = renderHook(+ () =>+ useIssueGroupBranches({+ wsId: "ws-1",+ query,+ group: {+ kind: "compound",+ primary: "parent",+ secondary: "status",+ secondary_values: ["todo"],+ },+ secondaryValues: ["todo"],+ enabled: true,+ }),+ { wrapper: wrapper(queryClient) },+ );++ await waitFor(() => expect(result.current.descriptors).toHaveLength(1));+ expect(result.current.total).toBe(1);+ expect(result.current.hasMoreGroups).toBe(true);++ queryClient.clear();+ });+});diff --git a/packages/views/issues/surface/use-issue-group-branches.ts b/packages/views/issues/surface/use-issue-group-branches.tsnew file mode 100644index 0000000000..1a696aec07--- /dev/null+++ b/packages/views/issues/surface/use-issue-group-branches.ts@@ -0,0 +1,491 @@+"use client";++import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import {+ useInfiniteQuery,+ useQueries,+ useQueryClient,+ type UseQueryResult,+} from "@tanstack/react-query";+import {+ issueKeys,+ issueTableGroupsOptions,+ issueTableRowPageOptions,+} from "@multica/core/issues/queries";+import type {+ Issue,+ IssueTableGroupDescriptor,+ IssueTableGroupsRequest,+ IssueTableQuerySpec,+ IssueTableRowsResponse,+} from "@multica/core/types";++export interface IssueGroupPageState {+ total: number;+ loaded: number;+ hasMore: boolean;+ isLoading: boolean;+ isFetching: boolean;+ isError: boolean;+ loadMore: () => void;+ retry: () => void;+}++export interface IssueGroupBranches {+ enabled: boolean;+ descriptors: IssueTableGroupDescriptor[];+ issues: Issue[];+ pagination: Record<string, IssueGroupPageState>;+ total: number;+ isLoading: boolean;+ isRefreshing: boolean;+ isError: boolean;+ hasMoreGroups: boolean;+ isLoadingMoreGroups: boolean;+ loadMoreGroups: () => void;+ retryGroups: () => void;+}++interface CursorState {+ identity: string;+ cursors: Record<string, Array<string | null>>;+}++interface PageTarget {+ key: string;+ cursor: string | null;+}++interface BranchData {+ rows: Issue[];+ nextCursor: string | null;+ isLoading: boolean;+ isFetching: boolean;+ isError: boolean;+ headUpdatedAt: number;+ headFetching: boolean;+}++function branchDescriptors(+ descriptors: readonly IssueTableGroupDescriptor[],+ secondaryValues?: readonly string[],+): IssueTableGroupDescriptor[] {+ const allowed = secondaryValues ? new Set(secondaryValues) : null;+ return descriptors.flatMap((descriptor) =>+ descriptor.secondary_groups?.length+ ? descriptor.secondary_groups.filter((secondary) => {+ if (!allowed || secondary.value.kind !== "status") return true;+ return allowed.has(secondary.value.status);+ })+ : [descriptor],+ );+}++function issueMatchesDescriptor(+ issue: Issue,+ descriptor: IssueTableGroupDescriptor,+ primary?: IssueTableGroupDescriptor,+) {+ const value = descriptor.value;+ if (value.kind === "status" && issue.status !== value.status) return false;+ const owner = primary?.value ?? value;+ switch (owner.kind) {+ case "assignee":+ return owner.actor+ ? issue.assignee_type === owner.actor.type &&+ issue.assignee_id === owner.actor.id+ : issue.assignee_type === null && issue.assignee_id === null;+ case "project":+ return issue.project_id === owner.project_id;+ case "parent":+ return issue.parent_issue_id === owner.parent_id;+ case "property": {+ const propertyValue = issue.properties?.[owner.property_id];+ if (owner.value_state === "unset") return propertyValue === undefined;+ if (owner.value_state === "value") return propertyValue === owner.value;+ return owner.value !== undefined+ ? propertyValue === owner.value+ : propertyValue !== undefined;+ }+ case "status":+ return issue.status === owner.status;+ }+}++/**+ * Cursor-paged server branches shared by non-status Board and Swimlane.+ * `/groups` owns the complete group catalog and exact counts; every group (or+ * compound lane×status cell) owns an independent `/rows` cursor chain.+ */+export function useIssueGroupBranches({+ wsId,+ query,+ group,+ secondaryValues,+ observeEmptyBranches = false,+ enabled,+}: {+ wsId: string;+ query: IssueTableQuerySpec;+ group: IssueTableGroupsRequest["group"];+ /** For compound groups, keep exact lane descriptors/counts while observing+ * rows only for the currently visible secondary buckets. */+ secondaryValues?: readonly string[];+ /** Compound and include-empty property responses carry zero-count keys.+ * Activate those when their mounted sentinel becomes visible so drag+ * targets have live heads. */+ observeEmptyBranches?: boolean;+ enabled: boolean;+}): IssueGroupBranches {+ const queryClient = useQueryClient();+ const identity = useMemo(+ () => JSON.stringify({ query, group }),+ [group, query],+ );+ const groupsQuery = useInfiniteQuery({+ ...issueTableGroupsOptions(wsId, query, group),+ enabled,+ });++ const descriptors = useMemo(+ () => groupsQuery.data?.pages.flatMap((page) => page.groups) ?? [],+ [groupsQuery.data?.pages],+ );+ const branches = useMemo(+ () => branchDescriptors(descriptors, secondaryValues),+ [descriptors, secondaryValues],+ );+ const branchKeys = useMemo(+ () => branches.map((descriptor) => descriptor.key),+ [branches],+ );+ const [cursorState, setCursorState] = useState<CursorState>({+ identity,+ cursors: {},+ });+ const activeCursorState = useMemo<CursorState>(() => {+ return cursorState.identity === identity+ ? cursorState+ : { identity, cursors: {} };+ }, [cursorState, identity]);+ useEffect(() => {+ if (activeCursorState !== cursorState) {+ setCursorState(activeCursorState);+ }+ }, [activeCursorState, cursorState]);++ const pageTargets = useMemo<PageTarget[]>(+ () =>+ enabled+ ? branchKeys.flatMap((key) =>+ (activeCursorState.cursors[key] ?? []).map((cursor) => ({+ key,+ cursor,+ })),+ )+ : [],+ [activeCursorState.cursors, branchKeys, enabled],+ );+ const headPlaceholderRef = useRef(+ new Map<string, IssueTableRowsResponse>(),+ );+ const pageQueries = useMemo(+ () =>+ pageTargets.map(({ key, cursor }) => {+ const placeholder =+ cursor === null ? headPlaceholderRef.current.get(key) : undefined;+ return {+ ...issueTableRowPageOptions(wsId, {+ query,+ group,+ group_key: key,+ hierarchy: { enabled: false },+ parent_id: null,+ page: { limit: 50, cursor },+ }),+ ...(placeholder ? { placeholderData: () => placeholder } : {}),+ enabled,+ };+ }),+ [enabled, group, pageTargets, query, wsId],+ );+ const pageResults = useQueries({ queries: pageQueries }) as Array<+ UseQueryResult<IssueTableRowsResponse, Error>+ >;+ useEffect(() => {+ const next = new Map(headPlaceholderRef.current);+ for (let index = 0; index < pageTargets.length; index += 1) {+ const target = pageTargets[index];+ const result = pageResults[index];+ if (+ target?.cursor !== null ||+ !result?.data ||+ result.isPlaceholderData ||+ result.isError+ ) {+ continue;+ }+ next.set(target.key, result.data);+ }+ headPlaceholderRef.current = next;+ }, [pageResults, pageTargets]);++ const primaryByBranch = useMemo(() => {+ const map = new Map<string, IssueTableGroupDescriptor>();+ for (const descriptor of descriptors) {+ for (const secondary of descriptor.secondary_groups ?? []) {+ map.set(secondary.key, descriptor);+ }+ }+ return map;+ }, [descriptors]);+ const descriptorByKey = useMemo(+ () => new Map(branches.map((descriptor) => [descriptor.key, descriptor])),+ [branches],+ );+ const branchData = useMemo(() => {+ const result = new Map<string, BranchData>();+ for (const key of branchKeys) {+ result.set(key, {+ rows: [],+ nextCursor: null,+ isLoading: false,+ isFetching: false,+ isError: false,+ headUpdatedAt: 0,+ headFetching: false,+ });+ }+ const headFetching = new Set<string>();+ for (let index = 0; index < pageTargets.length; index += 1) {+ const target = pageTargets[index];+ const page = pageResults[index];+ if (+ target?.cursor === null &&+ page?.isFetching &&+ (activeCursorState.cursors[target.key]?.length ?? 0) > 1+ ) {+ headFetching.add(target.key);+ }+ }+ const seenByKey = new Map<string, Set<string>>();+ for (let index = 0; index < pageTargets.length; index += 1) {+ const target = pageTargets[index];+ const pageResult = pageResults[index];+ if (!target || !pageResult) continue;+ if (target.cursor !== null && headFetching.has(target.key)) continue;+ const current = result.get(target.key);+ const descriptor = descriptorByKey.get(target.key);+ if (!current || !descriptor) continue;+ if (pageResult.data) {+ const seen = seenByKey.get(target.key) ?? new Set<string>();+ for (const row of pageResult.data.rows) {+ if (+ !issueMatchesDescriptor(+ row.issue,+ descriptor,+ primaryByBranch.get(target.key),+ ) ||+ seen.has(row.issue.id)+ ) {+ continue;+ }+ seen.add(row.issue.id);+ current.rows.push(row.issue);+ }+ seenByKey.set(target.key, seen);+ current.nextCursor = pageResult.data.next_cursor;+ }+ current.isLoading ||= pageResult.isPending;+ current.isFetching ||= pageResult.isFetching;+ current.isError ||= pageResult.isError;+ if (target.cursor === null) {+ current.headUpdatedAt = pageResult.dataUpdatedAt;+ current.headFetching = pageResult.isFetching;+ }+ }+ return result;+ }, [+ activeCursorState.cursors,+ branchKeys,+ descriptorByKey,+ pageResults,+ pageTargets,+ primaryByBranch,+ ]);++ const headRevisionRef = useRef<{+ identity: string;+ revisions: Record<string, number>;+ }>({ identity, revisions: {} });+ useEffect(() => {+ const previous =+ headRevisionRef.current.identity === identity+ ? headRevisionRef.current.revisions+ : {};+ const next: Record<string, number> = {};+ const trim = new Set<string>();+ for (const key of branchKeys) {+ const branch = branchData.get(key);+ if (!branch || branch.headUpdatedAt === 0) continue;+ next[key] = branch.headUpdatedAt;+ const seen = previous[key];+ if (+ (activeCursorState.cursors[key]?.length ?? 0) > 1 &&+ (branch.headFetching ||+ (seen !== undefined && seen !== branch.headUpdatedAt))+ ) {+ trim.add(key);+ }+ }+ headRevisionRef.current = { identity, revisions: next };+ if (trim.size === 0) return;+ setCursorState((previousState) => {+ if (previousState.identity !== identity) return previousState;+ const cursors = { ...previousState.cursors };+ for (const key of trim) cursors[key] = [null];+ return { ...previousState, cursors };+ });+ }, [+ activeCursorState.cursors,+ branchData,+ branchKeys,+ identity,+ ]);++ const loadMore = useCallback(+ (key: string) => {+ const cursor = branchData.get(key)?.nextCursor;+ setCursorState((previous) => {+ if (previous.identity !== identity) return previous;+ const current = previous.cursors[key] ?? [];+ // A descriptor does not install a row observer by itself. The first+ // visible sentinel activates the head; subsequent calls append the+ // server cursor. This bounds Swimlane's first paint to mounted lanes+ // instead of lanes × statuses across the complete catalog.+ if (current.length === 0) {+ return {+ ...previous,+ cursors: { ...previous.cursors, [key]: [null] },+ };+ }+ if (!cursor) return previous;+ if (current.includes(cursor)) return previous;+ return {+ ...previous,+ cursors: { ...previous.cursors, [key]: [...current, cursor] },+ };+ });+ },+ [branchData, identity],+ );+ const retry = useCallback(+ (key: string) => {+ void queryClient.refetchQueries({+ queryKey: issueKeys.tableRows(+ wsId,+ query,+ group,+ key,+ false,+ null,+ ),+ exact: false,+ type: "active",+ });+ },+ [group, query, queryClient, wsId],+ );+ const pagination = useMemo(+ () =>+ Object.fromEntries(+ branches.map((descriptor) => {+ const branch = branchData.get(descriptor.key);+ const active =+ (activeCursorState.cursors[descriptor.key]?.length ?? 0) > 0;+ return [+ descriptor.key,+ {+ total: descriptor.count,+ loaded: branch?.rows.length ?? 0,+ hasMore:+ enabled &&+ (active+ ? !!branch?.nextCursor+ : descriptor.count > 0 || observeEmptyBranches),+ isLoading: enabled && (branch?.isLoading ?? false),+ isFetching: enabled && (branch?.isFetching ?? false),+ isError: enabled && (branch?.isError ?? false),+ loadMore: () => loadMore(descriptor.key),+ retry: () => retry(descriptor.key),+ },+ ];+ }),+ ) as Record<string, IssueGroupPageState>,+ [+ activeCursorState.cursors,+ branchData,+ branches,+ enabled,+ loadMore,+ observeEmptyBranches,+ retry,+ ],+ );+ const issues = useMemo(+ () => branchKeys.flatMap((key) => branchData.get(key)?.rows ?? []),+ [branchData, branchKeys],+ );+ const rowsPending = branchKeys.some(+ (key) => branchData.get(key)?.isLoading,+ );+ const rowsFetching = branchKeys.some(+ (key) => branchData.get(key)?.isFetching,+ );+ const fetchNextGroupPage = groupsQuery.fetchNextPage;+ const refetchGroups = groupsQuery.refetch;+ const hasNextGroupPage = groupsQuery.hasNextPage;+ const isFetchingNextGroupPage = groupsQuery.isFetchingNextPage;+ const loadMoreGroups = useCallback(() => {+ if (hasNextGroupPage && !isFetchingNextGroupPage) {+ void fetchNextGroupPage();+ }+ }, [+ fetchNextGroupPage,+ hasNextGroupPage,+ isFetchingNextGroupPage,+ ]);+ const retryGroups = useCallback(() => {+ void refetchGroups();+ }, [refetchGroups]);++ return {+ enabled,+ descriptors,+ issues,+ pagination,+ // `/groups` owns the exact query-wide visible total. Deriving it from+ // loaded descriptors made a hidden-only first group page look globally+ // empty even when a later page contained visible cards.+ total: groupsQuery.data?.pages[0]?.total ?? issues.length,+ isLoading: enabled && groupsQuery.isPending,+ isRefreshing:+ enabled &&+ !groupsQuery.isPending &&+ (groupsQuery.isFetching || rowsPending || rowsFetching),+ isError:+ enabled &&+ (groupsQuery.isError ||+ branchKeys.some((key) => branchData.get(key)?.isError)),+ hasMoreGroups: enabled && !!hasNextGroupPage,+ isLoadingMoreGroups: enabled && isFetchingNextGroupPage,+ loadMoreGroups,+ retryGroups,+ };+}diff --git a/packages/views/issues/surface/use-issue-status-branches.test.tsx b/packages/views/issues/surface/use-issue-status-branches.test.tsxnew file mode 100644index 0000000000..f849a00822--- /dev/null+++ b/packages/views/issues/surface/use-issue-status-branches.test.tsx@@ -0,0 +1,148 @@+/**+ * @vitest-environment jsdom+ */+import { afterEach, 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 type {+ Issue,+ IssueStatus,+ IssueTableQuerySpec,+ IssueTableRowsRequest,+} from "@multica/core/types";+import { useIssueStatusBranches } from "./use-issue-status-branches";++function makeIssue(id: string): Issue {+ return {+ id,+ workspace_id: "ws-1",+ number: id === "issue-1" ? 1 : 2,+ identifier: id === "issue-1" ? "MUL-1" : "MUL-2",+ title: id,+ 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: null,+ position: id === "issue-1" ? 1 : 2,+ stage: null,+ start_date: null,+ due_date: null,+ metadata: {},+ properties: {},+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ };+}++const query: IssueTableQuerySpec = {+ scope: { kind: "workspace" },+ filters: { include_sub_issues: true },+ sort: { field: "position", direction: "asc" },+};++function wrapper(queryClient: QueryClient) {+ return function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>+ {children}+ </QueryClientProvider>+ );+ };+}++describe("useIssueStatusBranches", () => {+ afterEach(() => cleanup());++ it("uses one cursor chain per active status and exact facet totals", async () => {+ const first = makeIssue("issue-1");+ const second = makeIssue("issue-2");+ const listIssueTableRows = vi.fn(+ async (request: IssueTableRowsRequest) => {+ const continuation = request.page?.cursor === "cursor-2";+ const issue = continuation ? second : first;+ return {+ query_fingerprint: "test",+ group_key: request.group_key,+ parent_id: null,+ total: 0,+ rows: [{ issue, direct_child_count: 0 }],+ branch_total: 1,+ next_cursor: continuation ? null : "cursor-2",+ };+ },+ );+ setApiInstance({ listIssueTableRows } as unknown as ApiClient);+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });++ const { result, rerender } = renderHook(+ ({ statuses }: { statuses: IssueStatus[] }) =>+ useIssueStatusBranches({+ wsId: "ws-1",+ query,+ statuses,+ facets: {+ query_fingerprint: "test",+ total: 2,+ facets: [+ {+ kind: "status",+ values: [{ key: "todo", count: 2 }],+ },+ ],+ },+ facetsPending: false,+ facetsFetching: false,+ enabled: true,+ }),+ {+ initialProps: { statuses: ["todo"] },+ wrapper: wrapper(queryClient),+ },+ );++ await waitFor(() =>+ expect(result.current.issues.map((issue) => issue.id)).toEqual([+ "issue-1",+ ]),+ );+ expect(result.current.pagination.todo.total).toBe(2);+ expect(result.current.pagination.todo.hasMore).toBe(true);+ expect(result.current.total).toBe(2);+ expect(result.current.isTotalKnown).toBe(true);++ act(() => result.current.pagination.todo.loadMore());+ await waitFor(() =>+ expect(result.current.issues.map((issue) => issue.id)).toEqual([+ "issue-1",+ "issue-2",+ ]),+ );+ expect(listIssueTableRows).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ group_key: "status:todo",+ page: { limit: 50, cursor: "cursor-2" },+ }),+ );++ // Collapsing a List section removes its active observers. Re-expanding+ // reuses the settled cursor pages instead of restarting another chain.+ rerender({ statuses: [] });+ expect(result.current.issues).toEqual([]);+ rerender({ statuses: ["todo"] });+ await waitFor(() => expect(result.current.issues).toHaveLength(2));+ expect(listIssueTableRows).toHaveBeenCalledTimes(2);++ queryClient.clear();+ });+});diff --git a/packages/views/issues/surface/use-issue-status-branches.ts b/packages/views/issues/surface/use-issue-status-branches.tsnew file mode 100644index 0000000000..0968958b53--- /dev/null+++ b/packages/views/issues/surface/use-issue-status-branches.ts@@ -0,0 +1,418 @@+"use client";++import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import {+ useQueries,+ useQueryClient,+ type UseQueryResult,+} from "@tanstack/react-query";+import { ALL_STATUSES } from "@multica/core/issues/config";+import {+ issueKeys,+ issueTableRowPageOptions,+} from "@multica/core/issues/queries";+import type {+ Issue,+ IssueStatus,+ IssueTableFacetsResponse,+ IssueTableQuerySpec,+ IssueTableRowsResponse,+} from "@multica/core/types";++export interface IssueStatusPageState {+ total: number;+ loaded: number;+ hasMore: boolean;+ isLoading: boolean;+ isFetching: boolean;+ isError: boolean;+ loadMore: () => void;+ retry: () => void;+}++export type IssueStatusPagination = Record<+ IssueStatus,+ IssueStatusPageState+>;++interface StatusCursorState {+ identity: string;+ cursors: Record<IssueStatus, Array<string | null>>;+}++interface StatusPageTarget {+ status: IssueStatus;+ cursor: string | null;+}++interface StatusBranchData {+ rows: Issue[];+ nextCursor: string | null;+ isLoading: boolean;+ isFetching: boolean;+ isError: boolean;+ headUpdatedAt: number;+ headFetching: boolean;+}++function statusGroupKey(status: IssueStatus) {+ return `status:${status}`;+}++function initialCursorState(+ identity: string,+ statuses: readonly IssueStatus[],+): StatusCursorState {+ const cursors = Object.fromEntries(+ ALL_STATUSES.map((status) => [+ status,+ statuses.includes(status) ? [null] : [],+ ]),+ ) as StatusCursorState["cursors"];+ return { identity, cursors };+}++function rebaseCursorState(+ state: StatusCursorState,+ identity: string,+ statuses: readonly IssueStatus[],+) {+ const current =+ state.identity === identity ? state : initialCursorState(identity, statuses);+ let cursors: StatusCursorState["cursors"] | null = null;+ for (const status of statuses) {+ if (current.cursors[status].length > 0) continue;+ cursors ??= { ...current.cursors };+ cursors[status] = [null];+ }+ return cursors ? { ...current, cursors } : current;+}++function statusCountsFromFacets(+ facets: IssueTableFacetsResponse | undefined,+) {+ const counts = new Map<IssueStatus, number>();+ const statusFacet = facets?.facets.find((facet) => facet.kind === "status");+ for (const value of statusFacet?.values ?? []) {+ if (ALL_STATUSES.includes(value.key as IssueStatus)) {+ counts.set(value.key as IssueStatus, value.count);+ }+ }+ return counts;+}++export interface IssueStatusBranches {+ enabled: boolean;+ issues: Issue[];+ pagination: IssueStatusPagination;+ total: number;+ isTotalKnown: boolean;+ isLoading: boolean;+ isRefreshing: boolean;+}++/**+ * Server-authoritative status branches shared by List and status-grouped+ * Board. Every branch page is the same keyset-paged `/table/rows` contract+ * used by Table; status totals come from the disjunctive status facet, so+ * hidden/empty columns never depend on the loaded card window.+ */+export function useIssueStatusBranches({+ wsId,+ query,+ statuses,+ facets,+ facetsPending,+ facetsFetching,+ enabled,+}: {+ wsId: string;+ query: IssueTableQuerySpec;+ statuses: readonly IssueStatus[];+ facets: IssueTableFacetsResponse | undefined;+ facetsPending: boolean;+ facetsFetching: boolean;+ enabled: boolean;+}): IssueStatusBranches {+ const queryClient = useQueryClient();+ const identity = useMemo(() => JSON.stringify(query), [query]);+ const [cursorState, setCursorState] = useState<StatusCursorState>(() =>+ initialCursorState(identity, statuses),+ );+ const activeCursorState = rebaseCursorState(+ cursorState,+ identity,+ statuses,+ );++ useEffect(() => {+ if (cursorState !== activeCursorState) {+ setCursorState(activeCursorState);+ }+ }, [activeCursorState, cursorState]);++ const pageTargets = useMemo<StatusPageTarget[]>(+ () =>+ enabled+ ? statuses.flatMap((status) =>+ activeCursorState.cursors[status].map((cursor) => ({+ status,+ cursor,+ })),+ )+ : [],+ [activeCursorState.cursors, enabled, statuses],+ );+ const headPlaceholderRef = useRef(+ new Map<IssueStatus, IssueTableRowsResponse>(),+ );+ const pageQueries = useMemo(+ () =>+ pageTargets.map(({ status, cursor }) => {+ const placeholder =+ cursor === null ? headPlaceholderRef.current.get(status) : undefined;+ return {+ ...issueTableRowPageOptions(wsId, {+ query,+ group: { kind: "status" },+ group_key: statusGroupKey(status),+ hierarchy: { enabled: false },+ parent_id: null,+ page: { limit: 50, cursor },+ }),+ // useQueries replaces observers when the query hash changes, so its+ // built-in keepPreviousData cannot bridge a filter/sort transition.+ // Retain only the last settled HEAD per fixed status branch. Tails+ // are deliberately detached; exact facets remain server-owned.+ ...(placeholder ? { placeholderData: () => placeholder } : {}),+ enabled,+ };+ }),+ [enabled, pageTargets, query, wsId],+ );+ const pageResults = useQueries({ queries: pageQueries }) as Array<+ UseQueryResult<IssueTableRowsResponse, Error>+ >;+ useEffect(() => {+ const next = new Map(headPlaceholderRef.current);+ for (let index = 0; index < pageTargets.length; index += 1) {+ const target = pageTargets[index];+ const result = pageResults[index];+ if (+ target?.cursor !== null ||+ !result?.data ||+ result.isPlaceholderData ||+ result.isError+ ) {+ continue;+ }+ next.set(target.status, result.data);+ }+ headPlaceholderRef.current = next;+ }, [pageResults, pageTargets]);++ const branchData = useMemo(() => {+ const result = new Map<IssueStatus, StatusBranchData>();+ for (const status of statuses) {+ result.set(status, {+ rows: [],+ nextCursor: null,+ isLoading: false,+ isFetching: false,+ isError: false,+ headUpdatedAt: 0,+ headFetching: false,+ });+ }++ const headFetching = new Set<IssueStatus>();+ for (let index = 0; index < pageTargets.length; index += 1) {+ const target = pageTargets[index];+ const queryResult = pageResults[index];+ if (+ target?.cursor === null &&+ queryResult?.isFetching &&+ activeCursorState.cursors[target.status].length > 1+ ) {+ headFetching.add(target.status);+ }+ }++ const seenByStatus = new Map<IssueStatus, Set<string>>();+ for (let index = 0; index < pageTargets.length; index += 1) {+ const target = pageTargets[index];+ const queryResult = pageResults[index];+ if (!target || !queryResult) continue;+ // A broad invalidation makes every cursor stale as soon as the head+ // starts refreshing. Hide detached tails immediately; the effect below+ // trims their cursor observers before their responses can re-enter.+ if (target.cursor !== null && headFetching.has(target.status)) continue;++ const current = result.get(target.status);+ if (!current) continue;+ const page = queryResult.data;+ if (page) {+ const seen = seenByStatus.get(target.status) ?? new Set<string>();+ for (const row of page.rows) {+ // Realtime can patch an issue's status before the broad query+ // invalidation has moved it between branch caches. Never render a+ // patched card under a status it no longer belongs to.+ if (row.issue.status !== target.status) continue;+ if (seen.has(row.issue.id)) continue;+ seen.add(row.issue.id);+ current.rows.push(row.issue);+ }+ seenByStatus.set(target.status, seen);+ current.nextCursor = page.next_cursor;+ }+ current.isLoading ||= queryResult.isPending;+ current.isFetching ||= queryResult.isFetching;+ current.isError ||= queryResult.isError;+ if (target.cursor === null) {+ current.headUpdatedAt = queryResult.dataUpdatedAt;+ current.headFetching = queryResult.isFetching;+ }+ }+ return result;+ }, [+ activeCursorState.cursors,+ pageResults,+ pageTargets,+ statuses,+ ]);++ // Once a head page refreshes, its old cursor chain no longer belongs to the+ // current snapshot. Match Table's branch behavior by dropping every tail.+ const headRevisionRef = useRef<{+ identity: string;+ revisions: Partial<Record<IssueStatus, number>>;+ }>({ identity, revisions: {} });+ useEffect(() => {+ const previous =+ headRevisionRef.current.identity === identity+ ? headRevisionRef.current.revisions+ : {};+ const next: Partial<Record<IssueStatus, number>> = {};+ const trim = new Set<IssueStatus>();+ for (const status of statuses) {+ const branch = branchData.get(status);+ if (!branch || branch.headUpdatedAt === 0) continue;+ next[status] = branch.headUpdatedAt;+ const seen = previous[status];+ if (+ activeCursorState.cursors[status].length > 1 &&+ (branch.headFetching ||+ (seen !== undefined && seen !== branch.headUpdatedAt))+ ) {+ trim.add(status);+ }+ }+ headRevisionRef.current = { identity, revisions: next };+ if (trim.size === 0) return;+ setCursorState((previousState) => {+ if (previousState.identity !== identity) return previousState;+ const cursors = { ...previousState.cursors };+ for (const status of trim) cursors[status] = [null];+ return { ...previousState, cursors };+ });+ }, [+ activeCursorState.cursors,+ branchData,+ identity,+ statuses,+ ]);++ const counts = useMemo(() => statusCountsFromFacets(facets), [facets]);+ const loadMore = useCallback(+ (status: IssueStatus) => {+ const cursor = branchData.get(status)?.nextCursor;+ if (!cursor) return;+ setCursorState((previous) => {+ if (previous.identity !== identity) return previous;+ const current = previous.cursors[status];+ if (current.includes(cursor)) return previous;+ return {+ ...previous,+ cursors: {+ ...previous.cursors,+ [status]: [...current, cursor],+ },+ };+ });+ },+ [branchData, identity],+ );+ const retry = useCallback(+ (status: IssueStatus) => {+ void queryClient.refetchQueries({+ queryKey: issueKeys.tableRows(+ wsId,+ query,+ { kind: "status" },+ statusGroupKey(status),+ false,+ null,+ ),+ exact: false,+ type: "active",+ });+ },+ [query, queryClient, wsId],+ );++ const pagination = useMemo<IssueStatusPagination>(() => {+ return Object.fromEntries(+ ALL_STATUSES.map((status) => {+ const branch = branchData.get(status);+ const loaded = branch?.rows.length ?? 0;+ const total = counts.get(status) ?? loaded;+ return [+ status,+ {+ total,+ loaded,+ hasMore: enabled && !!branch?.nextCursor,+ isLoading: enabled && (branch?.isLoading ?? false),+ isFetching: enabled && (branch?.isFetching ?? false),+ isError: enabled && (branch?.isError ?? false),+ loadMore: () => loadMore(status),+ retry: () => retry(status),+ },+ ];+ }),+ ) as IssueStatusPagination;+ }, [branchData, counts, enabled, loadMore, retry]);++ const issues = useMemo(+ () => statuses.flatMap((status) => branchData.get(status)?.rows ?? []),+ [branchData, statuses],+ );+ const isTotalKnown = facets !== undefined;+ const total = facets?.total ?? issues.length;+ const rowsPending = statuses.some(+ (status) => branchData.get(status)?.isLoading,+ );+ const rowsFetching = statuses.some(+ (status) => branchData.get(status)?.isFetching,+ );++ return {+ enabled,+ issues,+ pagination,+ total,+ isTotalKnown,+ isLoading: enabled && (facetsPending || rowsPending),+ isRefreshing:+ enabled &&+ !facetsPending &&+ !rowsPending &&+ (facetsFetching || rowsFetching),+ };+}diff --git a/packages/views/issues/surface/use-issue-surface-actions.ts b/packages/views/issues/surface/use-issue-surface-actions.tsindex a71c510eed..194c286601 100644--- a/packages/views/issues/surface/use-issue-surface-actions.ts+++ b/packages/views/issues/surface/use-issue-surface-actions.ts@@ -24,7 +24,10 @@ export type MoveIssueUpdates = Pick<| "position"| "parent_issue_id"| "project_id"->;+> & {+ before_id: string | null;+ after_id: string | null;+};export interface IssueSurfaceActionController {actions: IssueSurfaceActions;@@ -78,12 +81,26 @@ export function useIssueSurfaceActions({updates: MoveIssueUpdates,onSettled?: () => void,) => {- updateIssue(issueId, updates, {- errorMessage: t(($) => $.detail.toast_move_issue_failed),- onSettled,- });+ const { before_id, after_id, ...optimisticUpdates } = updates;+ updateIssueMutation.mutate(+ {+ id: issueId,+ ...optimisticUpdates,+ move_intent: { before_id, after_id },+ },+ {+ onError: (err) => {+ toast.error(+ err instanceof Error && err.message+ ? err.message+ : t(($) => $.detail.toast_move_issue_failed),+ );+ },+ onSettled,+ },+ );},- [t, updateIssue],+ [t, updateIssueMutation],);const openCreateIssue = useCallback(diff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsxindex c0ec3cc5b2..65d1cfd170 100644--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx@@ -8,7 +8,6 @@ import type { ReactNode } from "react";import { setApiInstance } from "@multica/core/api";import type { ApiClient } from "@multica/core/api/client";import { agentTaskSnapshotOptions } from "@multica/core/agents";-import { issueKeys } from "@multica/core/issues/queries";import {getIssueSurfaceViewStore,pruneIssueSurfaceViewStates,@@ -23,6 +22,7 @@ import type {} from "@multica/core/types";import { useIssueSurfaceController } from "./use-issue-surface-controller";import { IssueTableExportIntegrityError } from "../components/table-view-model";+import { statusTableMethodsFromLegacy } from "./status-table-test-api";function makeIssue(overrides: Partial<Issue> & Pick<Issue, "id" | "status">,@@ -123,13 +123,21 @@ describe("useIssueSurfaceController", () => {let getAgentTaskSnapshot: ReturnType<typeof vi.fn<() => Promise<AgentTask[]>>>;+ let listIssueTableRows: ReturnType<typeof vi.fn>;+ let listIssueTableFacets: ReturnType<typeof vi.fn>;beforeEach(() => {qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });listIssues = vi.fn(() => never<ListIssuesResponse>());getAgentTaskSnapshot = vi.fn(() => never<AgentTask[]>());+ const tableMethods = statusTableMethodsFromLegacy(listIssues);+ listIssueTableRows = vi.fn(tableMethods.listIssueTableRows);+ listIssueTableFacets = vi.fn(tableMethods.listIssueTableFacets);setApiInstance({listIssues,+ ...tableMethods,+ listIssueTableRows,+ listIssueTableFacets,listGroupedIssues: vi.fn(() => never()),listProjects: vi.fn(() => never()),getAgentTaskSnapshot,@@ -149,7 +157,7 @@ describe("useIssueSurfaceController", () => {vi.restoreAllMocks();});- it("derives the project scope key, API filter, and sorted myList cache key", async () => {+ it("derives the project scope and canonical server query", async () => {const store = getIssueSurfaceViewStore("project:p1");store.getState().setSortBy("priority");store.getState().setSortDirection("desc");@@ -163,7 +171,7 @@ describe("useIssueSurfaceController", () => {{ wrapper: makeWrapper(qc, "project:p1") },);- await waitFor(() => expect(listIssues).toHaveBeenCalled());+ await waitFor(() => expect(listIssueTableRows).toHaveBeenCalled());const expectedSort = { sort_by: "priority", sort_direction: "desc" } as const;const expectedFilter = { project_id: "p1" };@@ -171,27 +179,23 @@ describe("useIssueSurfaceController", () => {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,+ expect(result.current.tableQuerySpec).toEqual(+ expect.objectContaining({+ scope: { kind: "project", project_id: "p1" },+ sort: { field: "priority", direction: "desc" },}),- ).toBeDefined();- expect(listIssues).toHaveBeenCalledWith(+ );+ expect(listIssueTableRows).toHaveBeenCalledWith(expect.objectContaining({- project_id: "p1",- sort_by: "priority",- sort_direction: "desc",+ query: expect.objectContaining({+ scope: { kind: "project", project_id: "p1" },+ }),+ group: { kind: "status" },}),);});- it("uses the workspace issue list query for workspace scope", async () => {+ it("uses the unified workspace query for workspace scope", async () => {const { result } = renderHook(() =>useIssueSurfaceController({@@ -201,27 +205,65 @@ describe("useIssueSurfaceController", () => {{ wrapper: makeWrapper(qc, "workspace:all") },);- await waitFor(() => expect(listIssues).toHaveBeenCalled());+ await waitFor(() => expect(listIssueTableRows).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,+ expect(result.current.tableQuerySpec.scope).toEqual({+ kind: "workspace",+ });+ expect(listIssueTableRows).toHaveBeenCalledWith(+ expect.objectContaining({+ group_key: "status:backlog",+ page: { limit: 50, cursor: null },}),- ).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 () => {+ it("does not subscribe List to the legacy issue endpoint", async () => {+ const legacyListIssues = vi.fn(() => never<ListIssuesResponse>());+ const tableRows = vi.fn(async (request: any) => ({+ query_fingerprint: "test",+ group_key: request.group_key,+ parent_id: null,+ total: 0,+ rows: [],+ branch_total: 0,+ next_cursor: null,+ }));+ const tableFacets = vi.fn(async () => ({+ query_fingerprint: "test",+ total: 0,+ facets: [{ kind: "status" as const, values: [] }],+ }));+ setApiInstance({+ listIssues: legacyListIssues,+ listIssueTableRows: tableRows,+ listIssueTableFacets: tableFacets,+ listGroupedIssues: vi.fn(() => never()),+ listProjects: vi.fn(() => never()),+ getAgentTaskSnapshot,+ getChildIssueProgress: vi.fn(() => never()),+ } as unknown as ApiClient);++ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "workspace", actorKind: "all" },+ modes: ["list"],+ }),+ { wrapper: makeWrapper(qc, "workspace:all") },+ );++ await waitFor(() => expect(result.current.isLoading).toBe(false));+ expect(tableRows).toHaveBeenCalled();+ expect(tableFacets).toHaveBeenCalled();+ expect(legacyListIssues).not.toHaveBeenCalled();+ });++ it("maps my assigned scope to the unified personal query contract", async () => {const { result } = renderHook(() =>useIssueSurfaceController({@@ -231,30 +273,20 @@ describe("useIssueSurfaceController", () => {{ wrapper: makeWrapper(qc, "my:user-1:assigned") },);- await waitFor(() => expect(listIssues).toHaveBeenCalled());+ await waitFor(() => expect(listIssueTableRows).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" }),- );+ expect(result.current.tableQuerySpec.scope).toEqual({+ kind: "my",+ relation: "assigned",+ });});- it("keeps actor scopes keyed by actor while using the shared list query shape", async () => {+ it("keeps actor scopes keyed by actor in the unified query shape", async () => {const { result } = renderHook(() =>useIssueSurfaceController({@@ -269,27 +301,17 @@ describe("useIssueSurfaceController", () => {{ wrapper: makeWrapper(qc, "actor:agent:agent-1:assigned") },);- await waitFor(() => expect(listIssues).toHaveBeenCalled());+ await waitFor(() => expect(listIssueTableRows).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" }),- );+ expect(result.current.tableQuerySpec.scope).toEqual({+ kind: "assignee",+ actor: { type: "agent", id: "agent-1" },+ });});it.each([@@ -370,7 +392,7 @@ describe("useIssueSurfaceController", () => {expect(result.current.selection.selectedIds).toEqual(new Set());});- it("delegates movement through useUpdateIssue without rewriting the mutation path", () => {+ it("delegates drag movement as a server-owned relative intent", () => {const { result } = renderHook(() =>useIssueSurfaceController({@@ -384,13 +406,28 @@ describe("useIssueSurfaceController", () => {act(() => {result.current.moveIssue("issue-1",- { status: "in_progress", position: 42, project_id: "p2" },+ {+ status: "in_progress",+ position: 42,+ project_id: "p2",+ before_id: "issue-0",+ after_id: "issue-2",+ },onSettled,);});expect(updateIssueMutate).toHaveBeenCalledWith(- { id: "issue-1", status: "in_progress", position: 42, project_id: "p2" },+ {+ id: "issue-1",+ status: "in_progress",+ position: 42,+ project_id: "p2",+ move_intent: {+ before_id: "issue-0",+ after_id: "issue-2",+ },+ },expect.objectContaining({onError: expect.any(Function),onSettled: expect.any(Function),@@ -561,6 +598,98 @@ describe("useIssueSurfaceController", () => {expect(result.current.tableFacetCounts).toBeUndefined();});+ it.each([+ {+ name: "Assignee Board",+ configure: (store: ReturnType<typeof getIssueSurfaceViewStore>) => {+ store.getState().setViewMode("board");+ store.getState().setGrouping("assignee");+ },+ properties: [],+ },+ {+ name: "Property Board",+ configure: (store: ReturnType<typeof getIssueSurfaceViewStore>) => {+ store.getState().setViewMode("board");+ store.getState().setGrouping("property:severity");+ },+ properties: [+ {+ id: "severity",+ workspace_id: "ws-1",+ name: "Severity",+ type: "select",+ config: { options: [] },+ position: 0,+ archived: false,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ },+ ],+ },+ {+ name: "Swimlane",+ configure: (store: ReturnType<typeof getIssueSurfaceViewStore>) => {+ store.getState().setViewMode("swimlane");+ },+ properties: [],+ },+ ])(+ "loads exact filter facets on demand for the server-paged $name",+ async ({ configure, properties }) => {+ const store = getIssueSurfaceViewStore("project:p1");+ configure(store);+ const listIssueTableFacets = vi.fn().mockResolvedValue({+ query_fingerprint: "sha256:group-facets",+ total: 0,+ facets: [{ kind: "priority", values: [{ key: "high", count: 37 }] }],+ });+ const tableMethods = statusTableMethodsFromLegacy(listIssues);+ setApiInstance({+ listIssues,+ ...tableMethods,+ listIssueTableFacets,+ listGroupedIssues: vi.fn(() => never()),+ listProjects: vi.fn(() => never()),+ listProperties: vi.fn(() =>+ Promise.resolve({ properties, total: properties.length }),+ ),+ getAgentTaskSnapshot: vi.fn(() => Promise.resolve([])),+ getChildIssueProgress: vi.fn(() => Promise.resolve([])),+ } as unknown as ApiClient);++ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "project", projectId: "p1" },+ modes: ["board", "list", "swimlane"],+ }),+ { wrapper: makeWrapper(qc, "project:p1") },+ );++ expect(result.current.facetCountsExact).toBe(false);+ expect(listIssueTableFacets).not.toHaveBeenCalled();++ act(() => result.current.setActiveTableFacet({ kind: "priority" }));++ await waitFor(() => expect(listIssueTableFacets).toHaveBeenCalledTimes(1));+ expect(listIssueTableFacets).toHaveBeenCalledWith(+ expect.objectContaining({+ facets: [{ kind: "priority" }],+ include_total: false,+ }),+ );+ await waitFor(() =>+ expect(result.current.tableFacetCounts?.facets).toEqual([+ { kind: "priority", values: [{ key: "high", count: 37 }] },+ ]),+ );++ act(() => result.current.setActiveTableFacet(null));+ expect(result.current.tableFacetCounts).toBeUndefined();+ },+ );+it("fails Table export closed when schema fallback would truncate the CSV", async () => {const store = getIssueSurfaceViewStore("project:p1");store.getState().setViewMode("table");@@ -1108,7 +1237,7 @@ describe("useIssueSurfaceController", () => {// snapshot against the PRE-filter issue set, so any active filter made the// chip disagree with the list it was filtering.- it("keeps the working scope identical to the rendered rows when the filter is on", async () => {+ it("sends the working filter to the server without reconstructing a local scope", async () => {mockListByStatus({todo: [makeIssue({ id: "todo-1", status: "todo" }),@@ -1135,23 +1264,13 @@ describe("useIssueSurfaceController", () => {);await waitFor(() => expect(result.current.isLoading).toBe(false));- await waitFor(() =>- expect(result.current.workingScopeIssues?.length).toBe(2),- );-- // The scope the chip counts agents within must be the rendered list- // itself — that identity is what keeps the chip in step with the filter- // (the chip's own number counts agents, not these rows).- expect(result.current.workingScopeIssues?.map((i) => i.id)).toEqual(- result.current.issues.map((i) => i.id),- );- expect(result.current.issues.map((i) => i.id).sort()).toEqual([- "prog-1",- "todo-1",- ]);+ expect(result.current.tableQuerySpec.filters.working_only).toBe(true);+ // Membership is cursor-paged and server-owned. A partial page cannot+ // produce the exact activity-chip scope, so it stays explicitly unknown.+ expect(result.current.workingScopeIssues).toBeUndefined();});- it("predicts the post-click rows while the filter is still off", async () => {+ it("keeps the activity-chip scope unknown before the server filter is enabled", async () => {mockListByStatus({todo: [makeIssue({ id: "todo-1", status: "todo" }),@@ -1172,19 +1291,14 @@ describe("useIssueSurfaceController", () => {);await waitFor(() => expect(result.current.isLoading).toBe(false));- await waitFor(() =>- expect(result.current.workingScopeIssues?.length).toBe(1),- );- // Filter off: the list still shows both rows, but the chip already- // reports the one row a click would leave.+ // Filter off: the list still shows both loaded rows, while the exact+ // post-click membership remains unknown until the backend predicate runs.expect(result.current.issues).toHaveLength(2);- expect(result.current.workingScopeIssues?.map((i) => i.id)).toEqual([- "todo-1",- ]);+ expect(result.current.workingScopeIssues).toBeUndefined();});- it("narrows the working scope with the status filter, exactly like the list", async () => {+ it("combines the status and working predicates in the canonical server query", async () => {mockListByStatus({todo: [makeIssue({ id: "todo-1", status: "todo" })],in_progress: [makeIssue({ id: "prog-1", status: "in_progress" })],@@ -1197,7 +1311,10 @@ describe("useIssueSurfaceController", () => {// ...but the user is only looking at `todo`.const store = getIssueSurfaceViewStore("project:p1");- act(() => store.getState().toggleStatusFilter("todo"));+ act(() => {+ store.getState().toggleStatusFilter("todo");+ store.getState().toggleAgentRunningFilter();+ });const { result } = renderHook(() =>@@ -1209,18 +1326,13 @@ describe("useIssueSurfaceController", () => {);await waitFor(() => expect(result.current.isLoading).toBe(false));- await waitFor(() =>- expect(result.current.workingScopeIssues?.length).toBe(1),- );- // The regression: the chip used to say 2 here (both issues have running- // agents) while clicking it produced a single row.- expect(result.current.workingScopeIssues?.map((i) => i.id)).toEqual([- "todo-1",- ]);+ expect(result.current.tableQuerySpec.filters.statuses).toEqual(["todo"]);+ expect(result.current.tableQuerySpec.filters.working_only).toBe(true);+ expect(result.current.workingScopeIssues).toBeUndefined();});- it("hides sub-issues from the working scope when the list hides them", async () => {+ it("sends the sub-issue display rule to the same server query", async () => {mockListByStatus({todo: [makeIssue({ id: "parent-1", status: "todo" }),@@ -1245,9 +1357,8 @@ describe("useIssueSurfaceController", () => {await waitFor(() => expect(result.current.isLoading).toBe(false));- // The only running work sits on a sub-issue the display toggle hides, so- // clicking the filter would leave zero rows — the chip must say 0, not 1.- expect(result.current.workingScopeIssues).toEqual([]);+ expect(result.current.tableQuerySpec.filters.include_sub_issues).toBe(false);+ expect(result.current.workingScopeIssues).toBeUndefined();});it("keeps issue-less chat/autopilot tasks out of the working scope", async () => {@@ -1257,7 +1368,6 @@ describe("useIssueSurfaceController", () => {// issue_id "" is how the API models a chat/autopilot task — it must not// become a phantom row (it used to inflate the count by exactly 1).getAgentTaskSnapshot.mockResolvedValue([- makeRunningTask("t-1", "agent-1", "todo-1"),makeRunningTask("t-2", "agent-2", ""),makeRunningTask("t-3", "agent-3", ""),]);@@ -1272,19 +1382,10 @@ describe("useIssueSurfaceController", () => {);await waitFor(() => expect(result.current.isLoading).toBe(false));- await waitFor(() =>- expect(result.current.workingScopeIssues?.length).toBe(1),- );-- expect(result.current.workingScopeIssues?.map((i) => i.id)).toEqual([- "todo-1",- ]);+ expect(result.current.workingScopeIssues).toEqual([]);});- it("scopes swimlane to the cards it draws, not its statusless lane source", async () => {- // SwimLaneView draws cards from `issues` (status filter applied) and uses- // the statusless `swimlaneIssues` only for LANE DISCOVERY. Scoping the- // chip to the statusless set counted rows the canvas never draws.+ it("keeps swimlane chrome bounded while descriptors retain hidden-status counts", async () => {mockListByStatus({todo: [makeIssue({ id: "todo-1", status: "todo" })],in_progress: [makeIssue({ id: "prog-1", status: "in_progress" })],@@ -1310,20 +1411,19 @@ describe("useIssueSurfaceController", () => {);await waitFor(() => expect(result.current.isLoading).toBe(false));- await waitFor(() =>- expect(result.current.workingScopeIssues?.length).toBe(1),- );-- expect(result.current.workingScopeIssues?.map((i) => i.id)).toEqual([- "todo-1",- ]);- expect(result.current.issues.map((i) => i.id)).toEqual(["todo-1"]);- // The statusless lane source still carries both — so a regression back to- // it would make the assertion above fail rather than pass by accident.- expect(result.current.swimlaneIssues.map((i) => i.id).sort()).toEqual([- "prog-1",- "todo-1",- ]);+ // Like Table/List, the migrated Swimlane owns cursor branches and does+ // not materialize another complete working-only window for the chip.+ expect(result.current.workingScopeIssues).toBeUndefined();+ // Controller-only tests do not mount lane cells, so no row branch should+ // activate merely because its descriptor exists.+ expect(result.current.issues).toEqual([]);+ expect(result.current.swimlaneIssues).toEqual([]);+ expect(+ result.current.groupBranches?.descriptors+ .flatMap((lane) => lane.secondary_groups ?? [])+ .map((cell) => cell.value.kind === "status" ? cell.value.status : "")+ .sort(),+ ).toEqual(["in_progress", "todo"]);});// --- gantt canvas scope ------------------------------------------------diff --git a/packages/views/issues/surface/use-issue-surface-controller.ts b/packages/views/issues/surface/use-issue-surface-controller.tsindex cea17e3d66..ea86f7c091 100644--- a/packages/views/issues/surface/use-issue-surface-controller.ts+++ b/packages/views/issues/surface/use-issue-surface-controller.ts@@ -1,7 +1,7 @@"use client";import { useCallback, useEffect, useMemo, useState } from "react";-import { useQuery } from "@tanstack/react-query";+import { keepPreviousData, useQuery } from "@tanstack/react-query";import type { QueryKey } from "@tanstack/react-query";import { api } from "@multica/core/api";import type {@@ -10,10 +10,12 @@ import type {IssueStatus,IssueTableFacetSpec,IssueTableFacetsResponse,+ IssueTableGroupsRequest,IssueTableQuerySpec,Project,} from "@multica/core/types";import { useWorkspaceId } from "@multica/core/hooks";+import { ALL_STATUSES } from "@multica/core/issues/config";import { dateOnlyToLocalDate } from "@multica/core/issues/date";import type {AssigneeGroupedIssuesFilter,@@ -46,11 +48,20 @@ import {type MoveIssueUpdates,} from "./use-issue-surface-actions";import { useIssueSurfaceData } from "./use-issue-surface-data";+import {+ useIssueStatusBranches,+ type IssueStatusPagination,+} from "./use-issue-status-branches";+import {+ useIssueGroupBranches,+ type IssueGroupBranches,+} from "./use-issue-group-branches";interface UseIssueSurfaceControllerInput {scope: IssueScope;modes: IssueSurfaceMode[];createDefaults?: IssueCreateDefaults;+ search?: string;}export interface IssueSurfaceController {@@ -78,6 +89,11 @@ export interface IssueSurfaceController {ganttIssues: Issue[];visibleStatuses: IssueStatus[];hiddenStatuses: IssueStatus[];+ /** Exact server counts plus cursor controls for List/status Board. */+ statusPagination?: IssueStatusPagination;+ /** Exact group catalog plus independent row cursors for Assignee/Property+ * Board and compound Swimlane cells. */+ groupBranches?: IssueGroupBranches;activeFilters: Omit<IssueFilters, "statusFilters" | "runningIssueIds">;activity: IssueSurfaceActivity;actions: IssueSurfaceActions;@@ -94,9 +110,11 @@ export interface IssueSurfaceController {tableSearch: string;/** Canonical server-owned Table membership. */tableQuerySpec: IssueTableQuerySpec;- /** Exact disjunctive counts for the active Table filter submenu. */+ /** Exact disjunctive counts for the active server-backed filter submenu. */tableFacetCounts?: IssueTableFacetsResponse;- /** Load one Table facet when its filter submenu is opened. */+ /** Whether scopedIssues is a complete client window for local count use. */+ facetCountsExact: boolean;+ /** Load one server facet when its filter submenu is opened. */setActiveTableFacet: (facet: IssueTableFacetSpec | null) => void;setTableSearch: (query: string) => void;exportTableIssues: () => Promise<Issue[]>;@@ -149,6 +167,7 @@ export function useIssueSurfaceController({scope,modes,createDefaults,+ search = "",}: UseIssueSurfaceControllerInput): IssueSurfaceController {const wsId = useWorkspaceId();const queryPlan = useMemo<IssueSurfaceQueryPlan>(@@ -179,8 +198,8 @@ export function useIssueSurfaceController({const cardProperties = useViewStore((s) => s.cardProperties);const swimlaneGrouping = useViewStore((s) => s.swimlaneGrouping);const tableColumns = useViewStore((s) => s.tableColumns);+ const listCollapsedStatuses = useViewStore((s) => s.listCollapsedStatuses);const [tableSearch, setTableSearch] = useState("");- const debouncedTableSearch = useDebouncedTableSearch(tableSearch);const allowedModes = useMemo(() => new Set<IssueSurfaceMode>(modes), [modes]);const fallbackMode = modes[0] ?? "list";@@ -252,10 +271,43 @@ export function useIssueSurfaceController({};}, [dateParams, effectivePropertyFilters, propertySortId, rawPropertySortId, sortBy, sortDirection]);+ const groupingPropertyId = propertyIdFromViewKey(grouping);+ const activeGroupingProperty = groupingPropertyId+ ? workspaceProperties.find(+ (property) =>+ property.id === groupingPropertyId && property.type === "select",+ ) ?? null+ : null;+ const effectiveGrouping =+ groupingPropertyId && catalogSettled && !activeGroupingProperty+ ? "status"+ : grouping;const usesAssigneeBoard =- effectiveViewMode === "board" && grouping === "assignee";+ effectiveViewMode === "board" && effectiveGrouping === "assignee";const usesGantt = effectiveViewMode === "gantt" && !!projectId;const usesTable = effectiveViewMode === "table";+ const activeSearch = usesTable ? tableSearch : search;+ const debouncedActiveSearch = useDebouncedTableSearch(activeSearch);+ const usesServerStatusSurface =+ effectiveViewMode === "list" ||+ (effectiveViewMode === "board" && effectiveGrouping === "status");+ const usesServerGroupSurface =+ (effectiveViewMode === "board" && effectiveGrouping !== "status") ||+ effectiveViewMode === "swimlane";+ const usesServerFacets =+ usesTable || usesServerStatusSurface || usesServerGroupSurface;+ const serverStatuses = useMemo<IssueStatus[]>(+ () => {+ const visible =+ statusFilters.length > 0+ ? ALL_STATUSES.filter((status) => statusFilters.includes(status))+ : [...ALL_STATUSES];+ return effectiveViewMode === "list"+ ? visible.filter((status) => !listCollapsedStatuses.includes(status))+ : visible;+ },+ [effectiveViewMode, listCollapsedStatuses, statusFilters],+ );const projectFilterState = useMemo(() => ({@@ -329,7 +381,7 @@ export function useIssueSurfaceController({...(agentRunningFilter ? { working_only: true } : {}),include_sub_issues: showSubIssues,},- ...(debouncedTableSearch ? { search: debouncedTableSearch } : {}),+ ...(debouncedActiveSearch ? { search: debouncedActiveSearch } : {}),sort: {field: sort.sort_by ?? "position",direction: sort.sort_direction ?? "asc",@@ -340,7 +392,7 @@ export function useIssueSurfaceController({assigneeFilters,creatorFilters,dateParams,- debouncedTableSearch,+ debouncedActiveSearch,effectivePropertyFilters,includeNoAssignee,labelFilters,@@ -356,35 +408,102 @@ export function useIssueSurfaceController({const [activeTableFacet, setActiveTableFacet] =useState<IssueTableFacetSpec | null>(null);+ const requestedFacets = useMemo<IssueTableFacetSpec[]>(() => {+ const facets: IssueTableFacetSpec[] = [];+ if (usesServerStatusSurface) facets.push({ kind: "status" });+ if (+ activeTableFacet &&+ !facets.some(+ (facet) =>+ facet.kind === activeTableFacet.kind &&+ (facet.kind !== "property" ||+ activeTableFacet.kind !== "property" ||+ facet.property_id === activeTableFacet.property_id),+ )+ ) {+ facets.push(activeTableFacet);+ }+ // The request shape remains total while disabled.+ return facets.length > 0 ? facets : [{ kind: "status" }];+ }, [activeTableFacet, usesServerStatusSurface]);const tableFacetRequest = useMemo(() => ({query: tableQuerySpec,- // The endpoint requires at least one facet. This fallback is never- // fetched while activeTableFacet is null; it only keeps the request- // shape total for React Query's option factory.- facets: [activeTableFacet ?? { kind: "status" as const }],- // Filter option badges do not consume the query-wide total; rows/groups- // already own the displayed Table total.- include_total: false,+ facets: requestedFacets,+ // Status surfaces consume the facet total as their authoritative empty+ // state. Table rows/groups already own the displayed total.+ include_total: usesServerStatusSurface,}),- [activeTableFacet, tableQuerySpec],+ [requestedFacets, tableQuerySpec, usesServerStatusSurface],);const tableFacetsQuery = useQuery({...issueTableFacetsOptions(wsId, tableFacetRequest),+ placeholderData: keepPreviousData,// Counts are only visible inside one open filter submenu. Eagerly loading// every custom-property facet made a Table mount issue up to 47 SQL// statements and repeatedly scan the issue table after invalidation.- enabled: usesTable && activeTableFacet !== null,+ enabled:+ usesServerStatusSurface ||+ ((usesTable || usesServerGroupSurface) && activeTableFacet !== null),});useEffect(() => {- if (!usesTable) setActiveTableFacet(null);- }, [usesTable]);+ if (!usesServerFacets) setActiveTableFacet(null);+ }, [usesServerFacets]);const requestActiveTableFacet = useCallback((facet: IssueTableFacetSpec | null) => {- setActiveTableFacet(usesTable ? facet : null);+ setActiveTableFacet(usesServerFacets ? facet : null);},- [usesTable],+ [usesServerFacets],);+ const serverStatusBranches = useIssueStatusBranches({+ wsId,+ query: tableQuerySpec,+ statuses: serverStatuses,+ facets: tableFacetsQuery.data,+ facetsPending: tableFacetsQuery.isPending,+ facetsFetching: tableFacetsQuery.isFetching,+ enabled: usesServerStatusSurface,+ });+ const serverGroupSpec = useMemo<IssueTableGroupsRequest["group"]>(() => {+ if (effectiveViewMode === "swimlane") {+ return {+ kind: "compound",+ primary: swimlaneGrouping,+ secondary: "status",+ secondary_values: serverStatuses,+ };+ }+ const propertyId = propertyIdFromViewKey(effectiveGrouping);+ if (propertyId) {+ return {+ kind: "property",+ property_id: propertyId,+ include_empty: true,+ };+ }+ return { kind: "assignee" };+ }, [+ effectiveGrouping,+ effectiveViewMode,+ serverStatuses,+ swimlaneGrouping,+ ]);+ const serverGroupQuery = useMemo<IssueTableQuerySpec>(() => {+ if (effectiveViewMode !== "swimlane") return tableQuerySpec;+ const { statuses: _statuses, ...filters } = tableQuerySpec.filters;+ return { ...tableQuerySpec, filters };+ }, [effectiveViewMode, tableQuerySpec]);+ const serverGroupBranches = useIssueGroupBranches({+ wsId,+ query: serverGroupQuery,+ group: serverGroupSpec,+ secondaryValues:+ effectiveViewMode === "swimlane" ? serverStatuses : undefined,+ observeEmptyBranches:+ effectiveViewMode === "swimlane" ||+ (effectiveViewMode === "board" && activeGroupingProperty !== null),+ enabled: usesServerGroupSurface,+ });// Selection is only meaningful within the current membership window: batch// actions act on selected ids while export/common-field consumers intersect@@ -409,14 +528,14 @@ export function useIssueSurfaceController({agentRunningFilter,showSubIssues,dateParams,- debouncedTableSearch,+ debouncedActiveSearch,]),[agentRunningFilter,assigneeFilters,creatorFilters,dateParams,- debouncedTableSearch,+ debouncedActiveSearch,effectivePropertyFilters,includeNoAssignee,labelFilters,@@ -439,6 +558,8 @@ export function useIssueSurfaceController({usesAssigneeBoard,usesGantt,usesTable,+ serverStatusBranches,+ serverGroupBranches,ganttShowCompleted,sort,activity,@@ -519,22 +640,32 @@ export function useIssueSurfaceController({viewMode: effectiveViewMode,allowGantt: allowedModes.has("gantt") && !!projectId,...data,+ statusPagination: usesServerStatusSurface+ ? data.statusPagination+ : undefined,+ groupBranches: usesServerGroupSurface+ ? serverGroupBranches+ : undefined,// Keep TableView mounted for an empty search result so its local search// control remains available to refine or clear the query. Include the// debounced value as well to avoid a brief empty-screen flash while a// cleared query is waiting to re-fetch the unsearched window.isEmpty:data.isEmpty &&- !(usesTable && (tableSearch.trim() || debouncedTableSearch)),+ !data.isRefreshing &&+ !(usesTable && (tableSearch.trim() || debouncedActiveSearch)),sort,actions,selection,tableSearch,tableQuerySpec,tableFacetCounts:- usesTable && activeTableFacet !== null+ usesServerStatusSurface ||+ ((usesTable || usesServerGroupSurface) && activeTableFacet !== null)? tableFacetsQuery.data: undefined,+ facetCountsExact:+ !usesTable && !usesServerStatusSurface && !usesServerGroupSurface,setActiveTableFacet: requestActiveTableFacet,setTableSearch,openCreateIssue,diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.tsindex 7bf35aeb98..b4da5fb85e 100644--- a/packages/views/issues/surface/use-issue-surface-data.ts+++ b/packages/views/issues/surface/use-issue-surface-data.ts@@ -29,6 +29,11 @@ import {} from "../utils/filter";import type { ChildProgress } from "../components/list-row";import type { IssueSurfaceActivity } from "./activity";+import type {+ IssueStatusBranches,+ IssueStatusPagination,+} from "./use-issue-status-branches";+import type { IssueGroupBranches } from "./use-issue-group-branches";const EMPTY_ISSUES: Issue[] = [];const EMPTY_CHILD_PROGRESS = new Map<string, ChildProgress>();@@ -76,6 +81,7 @@ export interface IssueSurfaceData {ganttIssues: Issue[];visibleStatuses: IssueStatus[];hiddenStatuses: IssueStatus[];+ statusPagination: IssueStatusPagination;activeFilters: Omit<IssueFilters, "statusFilters" | "runningIssueIds">;activity: IssueSurfaceActivity;childProgressMap: Map<string, ChildProgress>;@@ -103,6 +109,8 @@ export function useIssueSurfaceData({usesAssigneeBoard,usesGantt,usesTable,+ serverStatusBranches,+ serverGroupBranches,ganttShowCompleted,sort,activity,@@ -125,6 +133,8 @@ export function useIssueSurfaceData({usesAssigneeBoard: boolean;usesGantt: boolean;usesTable: boolean;+ serverStatusBranches: IssueStatusBranches;+ serverGroupBranches: IssueGroupBranches;/** Gantt's "show completed" display toggle. The canvas hides done/cancelled* rows without it, so the working scope has to honour it too. */ganttShowCompleted: boolean;@@ -184,11 +194,16 @@ export function useIssueSurfaceData({const statusIssuesQuery = useQuery({...issueSurfaceListOptions(wsId, queryPlan, sort),- enabled: !usesAssigneeBoard && !usesGantt && !usesTable,+ enabled:+ !usesAssigneeBoard &&+ !usesGantt &&+ !usesTable &&+ !serverStatusBranches.enabled &&+ !serverGroupBranches.enabled,});const assigneeGroupsQuery = useQuery({...activeAssigneeGroupsOptions,- enabled: usesAssigneeBoard,+ enabled: usesAssigneeBoard && !serverGroupBranches.enabled,});const ganttIssuesQuery = useQuery({...issueSurfaceGanttOptions(wsId, projectId ?? ""),@@ -196,10 +211,22 @@ export function useIssueSurfaceData({});const hasRunningIssues = activity.runningIssueIds.size > 0;const bucketedIssues = useMemo(() => {- return usesAssigneeBoard+ return serverStatusBranches.enabled+ ? serverStatusBranches.issues+ : serverGroupBranches.enabled+ ? serverGroupBranches.issues+ : usesAssigneeBoard? (assigneeGroupsQuery.data?.groups.flatMap((group) => group.issues) ?? []): (statusIssuesQuery.data ?? EMPTY_ISSUES);- }, [assigneeGroupsQuery.data?.groups, statusIssuesQuery.data, usesAssigneeBoard]);+ }, [+ assigneeGroupsQuery.data?.groups,+ serverStatusBranches.enabled,+ serverStatusBranches.issues,+ serverGroupBranches.enabled,+ serverGroupBranches.issues,+ statusIssuesQuery.data,+ usesAssigneeBoard,+ ]);// `cancelled` is a first-class default status (MUL-4290): it is fetched into// the cache like every other status and flows straight through to list /@@ -243,8 +270,16 @@ export function useIssueSurfaceData({);const issues = useMemo(- () => applyIssueFilters(surfaceIssues, baseFilterState, filterContext),- [baseFilterState, filterContext, surfaceIssues],+ () =>+ serverStatusBranches.enabled+ ? surfaceIssues+ : applyIssueFilters(surfaceIssues, baseFilterState, filterContext),+ [+ baseFilterState,+ filterContext,+ serverStatusBranches.enabled,+ surfaceIssues,+ ],);const statuslessFilterState = useMemo<IssueFilterState>(@@ -330,7 +365,7 @@ export function useIssueSurfaceData({ganttShowCompleted,);}- if (usesAssigneeBoard) {+ if (usesAssigneeBoard && !serverGroupBranches.enabled) {return (filterAssigneeGroups(assigneeGroupsQuery.data?.groups, {showSubIssues,@@ -340,7 +375,7 @@ export function useIssueSurfaceData({}) ?? []).flatMap((group) => group.issues);}- if (usesTable) {+ if (usesTable || serverStatusBranches.enabled || serverGroupBranches.enabled) {// Table membership is server-owned and cursor paged. Do not rebuild a// second complete issue window merely to decorate the activity chip:// that was the final hidden auto-materialization loop behind the old@@ -369,6 +404,8 @@ export function useIssueSurfaceData({usesAssigneeBoard,usesGantt,usesTable,+ serverStatusBranches.enabled,+ serverGroupBranches.enabled,]);const {@@ -465,24 +502,32 @@ export function useIssueSurfaceData({],);- const isLoading = usesAssigneeBoard- ? assigneeGroupsQuery.isLoading- : usesGantt+ const isLoading = serverGroupBranches.enabled+ ? serverGroupBranches.isLoading+ : usesAssigneeBoard+ ? assigneeGroupsQuery.isLoading+ : usesGantt? ganttIssuesQuery.isLoading: usesTable? false- : statusIssuesQuery.isLoading;+ : serverStatusBranches.enabled+ ? serverStatusBranches.isLoading+ : statusIssuesQuery.isLoading;// Placeholder-backed revalidation of the ACTIVE query only. First loads are// isLoading (no previous data to place-hold); gantt has no placeholder// phase (its key carries no sort/filter).- const isRefreshing = usesAssigneeBoard- ? assigneeGroupsQuery.isPlaceholderData- : usesGantt+ const isRefreshing = serverGroupBranches.enabled+ ? serverGroupBranches.isRefreshing+ : usesAssigneeBoard+ ? assigneeGroupsQuery.isPlaceholderData+ : usesGantt? false: usesTable? false- : statusIssuesQuery.isPlaceholderData;+ : serverStatusBranches.enabled+ ? serverStatusBranches.isRefreshing+ : statusIssuesQuery.isPlaceholderData;return {surfaceIssues,@@ -502,6 +547,7 @@ export function useIssueSurfaceData({ganttIssues,visibleStatuses,hiddenStatuses,+ statusPagination: serverStatusBranches.pagination,activeFilters,activity,childProgressMap,@@ -521,6 +567,12 @@ export function useIssueSurfaceData({!isLoading &&!usesGantt &&!usesTable &&- surfaceIssues.length === 0,+ (serverStatusBranches.enabled+ ? serverStatusBranches.isTotalKnown &&+ serverStatusBranches.total === 0+ : serverGroupBranches.enabled+ ? !serverGroupBranches.isError &&+ serverGroupBranches.total === 0+ : surfaceIssues.length === 0),};}diff --git a/packages/views/issues/utils/drag-utils.test.ts b/packages/views/issues/utils/drag-utils.test.tsindex faa9e4785a..ba4441c7fc 100644--- a/packages/views/issues/utils/drag-utils.test.ts+++ b/packages/views/issues/utils/drag-utils.test.ts@@ -1,6 +1,13 @@import { describe, expect, it } from "vitest";import type { Issue } from "@multica/core/types";-import { getIssueGroupId, getMoveUpdates, insertIdByPosition, issueMatchesGroup, propertyGroupId } from "./drag-utils";+import {+ getIssueGroupId,+ getMoveAnchors,+ getMoveUpdates,+ insertIdByPosition,+ issueMatchesGroup,+ propertyGroupId,+} from "./drag-utils";function mk(id: string, position: number): Issue {return {@@ -34,6 +41,19 @@ function mapOf(...issues: Issue[]): Map<string, Issue> {return new Map(issues.map((i) => [i.id, i]));}+describe("getMoveAnchors", () => {+ it("derives relative neighbors from the optimistic order", () => {+ expect(getMoveAnchors(["a", "moving", "b"], "moving")).toEqual({+ before_id: "a",+ after_id: "b",+ });+ expect(getMoveAnchors(["moving"], "moving")).toEqual({+ before_id: null,+ after_id: null,+ });+ });+});+describe("insertIdByPosition", () => {it("inserts the id at its position-sorted slot", () => {const map = mapOf(mk("a", 1), mk("c", 3), mk("b", 2));diff --git a/packages/views/issues/utils/drag-utils.ts b/packages/views/issues/utils/drag-utils.tsindex 2c26885c42..d20f75a91f 100644--- a/packages/views/issues/utils/drag-utils.ts+++ b/packages/views/issues/utils/drag-utils.ts@@ -8,11 +8,16 @@ import type { IssueGrouping } from "@multica/core/issues/stores/view-store";import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";import type { BoardColumnGroup } from "../components/board-column";-export type DragMoveUpdates = Pick<+export type DragMoveTargetUpdates = Pick<UpdateIssueRequest,"status" | "assignee_type" | "assignee_id" | "position">;+export type DragMoveUpdates = DragMoveTargetUpdates & {+ before_id: string | null;+ after_id: string | null;+};+const UNASSIGNED_GROUP_ID = "assignee:unassigned";export function makeKanbanCollision(groupIds: Set<string>): CollisionDetection {@@ -89,6 +94,17 @@ export function computePosition(ids: string[], activeId: string, issueMap: Map<sreturn (getPos(ids[idx - 1]!) + getPos(ids[idx + 1]!)) / 2;}+export function getMoveAnchors(+ ids: readonly string[],+ activeId: string,+): Pick<DragMoveUpdates, "before_id" | "after_id"> {+ const index = ids.indexOf(activeId);+ return {+ before_id: index > 0 ? ids[index - 1]! : null,+ after_id: index >= 0 && index < ids.length - 1 ? ids[index + 1]! : null,+ };+}+/*** Insert `id` into `ids` at the slot implied by `position ASC`, reading each* id's position from `issueMap`. Mirrors `insertByPosition` in@@ -138,7 +154,7 @@ export function issueMatchesGroup(issue: Issue, group: BoardColumnGroup): booleaexport function getMoveUpdates(group: BoardColumnGroup,position: number,-): DragMoveUpdates {+): DragMoveTargetUpdates {if (group.status) return { status: group.status, position };// Property columns: the value change is not part of UpdateIssueRequest —// the board applies it through useSetIssueProperty after the position move.diff --git a/packages/views/my-issues/components/my-issues-page.tsx b/packages/views/my-issues/components/my-issues-page.tsxindex c0dd7fd00a..f384144724 100644--- a/packages/views/my-issues/components/my-issues-page.tsx+++ b/packages/views/my-issues/components/my-issues-page.tsx@@ -45,7 +45,7 @@ export function MyIssuesPage() {scope={scope}onScopeChange={setScope}isRefreshing={controller.isRefreshing}- facetCountsExact={controller.viewMode !== "table"}+ facetCountsExact={controller.facetCountsExact}tableFacetCounts={controller.tableFacetCounts}onTableFacetChange={controller.setActiveTableFacet}/>diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex b9b3389acd..1c0f8d1f8a 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1053,6 +1053,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Route("/{id}", func(r chi.Router) {r.Get("/", h.GetIssue)r.Put("/", h.UpdateIssue)+ r.Post("/move", h.MoveIssue)r.Delete("/", h.DeleteIssue)r.Post("/comments/trigger-preview", h.PreviewCommentTriggers)r.Post("/comments", h.CreateComment)diff --git a/server/internal/handler/issue_move.go b/server/internal/handler/issue_move.gonew file mode 100644index 0000000000..2a9739115d--- /dev/null+++ b/server/internal/handler/issue_move.go@@ -0,0 +1,217 @@+package handler++import (+ "bytes"+ "encoding/json"+ "errors"+ "io"+ "math"+ "net/http"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+)++var issueMoveFields = map[string]struct{}{+ "status": {},+ "assignee_type": {},+ "assignee_id": {},+ "parent_issue_id": {},+ "project_id": {},+ "before_id": {},+ "after_id": {},+}++// MoveIssue accepts relative neighbors instead of a client-authored canonical+// position. It resolves both anchors inside the issue's workspace, derives the+// position server-side, then delegates the actual write to UpdateIssue so all+// existing validation, realtime, task-trigger and parent-notification behavior+// stays on one path. The legacy PUT endpoint remains unchanged for released+// clients.+func (h *Handler) MoveIssue(w http.ResponseWriter, r *http.Request) {+ id := chi.URLParam(r, "id")+ current, ok := h.loadIssueForUser(w, r, id)+ if !ok {+ return+ }++ body, err := io.ReadAll(r.Body)+ if err != nil {+ writeError(w, http.StatusBadRequest, "failed to read request body")+ return+ }+ var fields map[string]json.RawMessage+ if err := json.Unmarshal(body, &fields); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ for field := range fields {+ if _, ok := issueMoveFields[field]; !ok {+ writeError(w, http.StatusBadRequest, "unsupported move field: "+field)+ return+ }+ }+ if _, ok := fields["before_id"]; !ok {+ writeError(w, http.StatusBadRequest, "before_id is required")+ return+ }+ if _, ok := fields["after_id"]; !ok {+ writeError(w, http.StatusBadRequest, "after_id is required")+ return+ }+ if rawProjectID, touched := fields["project_id"]; touched && !rawJSONNull(rawProjectID) {+ projectID, valid := decodeIssueMoveAnchor(w, rawProjectID, "project_id")+ if !valid {+ return+ }+ var exists bool+ err := h.DB.QueryRow(r.Context(), `+ SELECT EXISTS (+ SELECT 1+ FROM project+ WHERE workspace_id = $1 AND id = $2+ )+ `, current.WorkspaceID, *projectID).Scan(&exists)+ if err != nil {+ writeIssueTableQueryFailure(w, r, "failed to validate move project")+ return+ }+ if !exists {+ writeError(w, http.StatusBadRequest, "project not found in this workspace")+ return+ }+ }++ beforeID, ok := decodeIssueMoveAnchor(w, fields["before_id"], "before_id")+ if !ok {+ return+ }+ afterID, ok := decodeIssueMoveAnchor(w, fields["after_id"], "after_id")+ if !ok {+ return+ }+ if beforeID != nil && *beforeID == current.ID {+ writeError(w, http.StatusBadRequest, "before_id cannot be the moved issue")+ return+ }+ if afterID != nil && *afterID == current.ID {+ writeError(w, http.StatusBadRequest, "after_id cannot be the moved issue")+ return+ }+ if beforeID != nil && afterID != nil && *beforeID == *afterID {+ writeError(w, http.StatusBadRequest, "move anchors must be distinct")+ return+ }++ // V1 intentionally keeps the canonical write on UpdateIssue so released+ // clients and the new move endpoint share validation, realtime and task+ // side effects. That means anchor resolution and the write are not one+ // transaction: stale/out-of-order anchors fail closed with 409 where+ // detectable, and an exhausted float gap also returns 409 instead of+ // silently renumbering neighboring issues. A future rebalance must move+ // every position writer (including the legacy PUT path) behind one+ // transactional ordering boundary.+ beforePosition, ok := h.issueMoveAnchorPosition(w, r, current.WorkspaceID, beforeID)+ if !ok {+ return+ }+ afterPosition, ok := h.issueMoveAnchorPosition(w, r, current.WorkspaceID, afterID)+ if !ok {+ return+ }+ position, err := issueMovePosition(current.Position, beforePosition, afterPosition)+ if err != nil {+ writeError(w, http.StatusConflict, err.Error())+ return+ }++ delete(fields, "before_id")+ delete(fields, "after_id")+ fields["position"], _ = json.Marshal(position)+ updateBody, err := json.Marshal(fields)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to encode move")+ return+ }+ r.Body = io.NopCloser(bytes.NewReader(updateBody))+ r.ContentLength = int64(len(updateBody))+ h.UpdateIssue(w, r)+}++func decodeIssueMoveAnchor(w http.ResponseWriter, raw json.RawMessage, field string) (*pgtype.UUID, bool) {+ if rawJSONNull(raw) {+ return nil, true+ }+ var value string+ if err := json.Unmarshal(raw, &value); err != nil || value == "" {+ writeError(w, http.StatusBadRequest, field+" must be a UUID or null")+ return nil, false+ }+ id, err := util.ParseUUID(value)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid "+field)+ return nil, false+ }+ return &id, true+}++func rawJSONNull(raw json.RawMessage) bool {+ return bytes.Equal(bytes.TrimSpace(raw), []byte("null"))+}++func (h *Handler) issueMoveAnchorPosition(+ w http.ResponseWriter,+ r *http.Request,+ workspaceID pgtype.UUID,+ id *pgtype.UUID,+) (*float64, bool) {+ if id == nil {+ return nil, true+ }+ var position float64+ err := h.DB.QueryRow(r.Context(), `+ SELECT position+ FROM issue+ WHERE workspace_id = $1 AND id = $2+ `, workspaceID, *id).Scan(&position)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusBadRequest, "move anchor not found in this workspace")+ } else {+ writeIssueTableQueryFailure(w, r, "failed to resolve move anchor")+ }+ return nil, false+ }+ return &position, true+}++func issueMovePosition(current float64, before, after *float64) (float64, error) {+ switch {+ case before != nil && after != nil:+ if !(*before < *after) {+ return 0, errors.New("move anchors are stale or out of order")+ }+ position := *before + (*after-*before)/2+ if !(position > *before && position < *after) ||+ math.IsInf(position, 0) || math.IsNaN(position) {+ return 0, errors.New("move anchors are too close; refresh and retry")+ }+ return position, nil+ case before != nil:+ position := *before + 1+ if math.IsInf(position, 0) || math.IsNaN(position) {+ return 0, errors.New("move position is out of range")+ }+ return position, nil+ case after != nil:+ position := *after - 1+ if math.IsInf(position, 0) || math.IsNaN(position) {+ return 0, errors.New("move position is out of range")+ }+ return position, nil+ default:+ return current, nil+ }+}diff --git a/server/internal/handler/issue_move_test.go b/server/internal/handler/issue_move_test.gonew file mode 100644index 0000000000..fc535e7d93--- /dev/null+++ b/server/internal/handler/issue_move_test.go@@ -0,0 +1,185 @@+package handler++import (+ "context"+ "fmt"+ "math"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"+)++func TestIssueMovePositionUsesRelativeAnchors(t *testing.T) {+ before := 10.0+ after := 20.0+ position, err := issueMovePosition(3, &before, &after)+ if err != nil {+ t.Fatalf("issueMovePosition: %v", err)+ }+ if position != 15 {+ t.Fatalf("position = %v, want 15", position)+ }+}++func TestIssueMovePositionRejectsStaleAnchors(t *testing.T) {+ before := 20.0+ after := 10.0+ if _, err := issueMovePosition(3, &before, &after); err == nil {+ t.Fatal("out-of-order anchors were accepted")+ }+}++func TestIssueMovePositionRejectsExhaustedGap(t *testing.T) {+ before := 1.0+ after := math.Nextafter(before, math.Inf(1))+ if _, err := issueMovePosition(3, &before, &after); err == nil {+ t.Fatal("gap with no representable midpoint was accepted")+ }+}++func TestIssueMovePositionKeepsPositionWithoutAnchors(t *testing.T) {+ position, err := issueMovePosition(7, nil, nil)+ if err != nil {+ t.Fatalf("issueMovePosition: %v", err)+ }+ if position != 7 {+ t.Fatalf("position = %v, want 7", position)+ }+}++func TestMoveIssueRejectsUnsafeInputs(t *testing.T) {+ ctx := context.Background()+ suffix := fmt.Sprintf("%d", time.Now().UnixNano())++ var movedIssueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, title, status, priority, creator_type, creator_id,+ number, position+ )+ VALUES (+ $1, $2, 'todo', 'none', 'member', $3,+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1),+ 100+ )+ RETURNING id+ `, testWorkspaceID, "Move boundary test "+suffix, testUserID).Scan(&movedIssueID); err != nil {+ t.Fatalf("insert moved issue: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, movedIssueID)+ })++ var foreignWorkspaceID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO workspace (name, slug, description, issue_prefix)+ VALUES ($1, $2, '', 'MOV')+ RETURNING id+ `, "Move boundary foreign workspace "+suffix, "move-boundary-"+suffix).Scan(&foreignWorkspaceID); err != nil {+ t.Fatalf("insert foreign workspace: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, foreignWorkspaceID)+ })++ var foreignAnchorID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, title, status, priority, creator_type, creator_id,+ number, position+ )+ VALUES ($1, $2, 'todo', 'none', 'member', $3, 1, 200)+ RETURNING id+ `, foreignWorkspaceID, "Foreign move anchor "+suffix, testUserID).Scan(&foreignAnchorID); err != nil {+ t.Fatalf("insert foreign anchor: %v", err)+ }++ var foreignProjectID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO project (workspace_id, title)+ VALUES ($1, $2)+ RETURNING id+ `, foreignWorkspaceID, "Foreign move project "+suffix).Scan(&foreignProjectID); err != nil {+ t.Fatalf("insert foreign project: %v", err)+ }++ tests := []struct {+ name string+ body map[string]any+ wantError string+ }{+ {+ name: "cross-workspace anchor",+ body: map[string]any{+ "before_id": foreignAnchorID,+ "after_id": nil,+ },+ wantError: "move anchor not found in this workspace",+ },+ {+ name: "cross-workspace project",+ body: map[string]any{+ "project_id": foreignProjectID,+ "before_id": nil,+ "after_id": nil,+ },+ wantError: "project not found in this workspace",+ },+ {+ name: "canonical position bypass",+ body: map[string]any{+ "position": 123,+ "before_id": nil,+ "after_id": nil,+ },+ wantError: "unsupported move field: position",+ },+ {+ name: "self anchor",+ body: map[string]any{+ "before_id": movedIssueID,+ "after_id": nil,+ },+ wantError: "before_id cannot be the moved issue",+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ req := newRequest(+ http.MethodPost,+ "/api/issues/"+movedIssueID+"/move",+ tc.body,+ )+ req = withURLParam(req, "id", movedIssueID)+ testHandler.MoveIssue(w, req)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("MoveIssue: expected 400, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), tc.wantError) {+ t.Fatalf("MoveIssue: expected error %q, got %s", tc.wantError, w.Body.String())+ }+ })+ }++ var title string+ var position float64+ var projectID *string+ if err := testPool.QueryRow(ctx, `+ SELECT title, position, project_id::text+ FROM issue+ WHERE id = $1+ `, movedIssueID).Scan(&title, &position, &projectID); err != nil {+ t.Fatalf("reload moved issue: %v", err)+ }+ if title != "Move boundary test "+suffix || position != 100 || projectID != nil {+ t.Fatalf(+ "rejected moves changed issue: title=%q position=%v project_id=%v",+ title, position, projectID,+ )+ }+}diff --git a/server/internal/handler/issue_table_group.go b/server/internal/handler/issue_table_group.goindex 9a3ac82559..c533fe305c 100644--- a/server/internal/handler/issue_table_group.go+++ b/server/internal/handler/issue_table_group.go@@ -3,6 +3,7 @@ package handlerimport ("context""encoding/base64"+ "encoding/json""errors""fmt""log/slog"@@ -18,18 +19,34 @@ import ()type issueTableGroupValueResponse struct {- Kind string `json:"kind"`- Status string `json:"status,omitempty"`- Actor *issueTableActorRef `json:"actor"`- PropertyID string `json:"property_id,omitempty"`- Value any `json:"value,omitempty"`- ValueState string `json:"value_state,omitempty"`+ Kind string `json:"kind"`+ Status string `json:"status,omitempty"`+ Actor *issueTableActorRef `json:"actor"`+ ProjectID *string `json:"project_id,omitempty"`+ ParentID *string `json:"parent_id,omitempty"`+ Parent *issueTableParentRef `json:"parent,omitempty"`+ PropertyID string `json:"property_id,omitempty"`+ Value any `json:"value,omitempty"`+ ValueState string `json:"value_state,omitempty"`+}++type issueTableParentRef struct {+ ID string `json:"id"`+ Number int32 `json:"number"`+ Identifier string `json:"identifier"`+ Title string `json:"title"`+ Status string `json:"status"`+}++type issueTableGroupContext struct {+ Parent *issueTableParentRef `json:"parent,omitempty"`}type issueTableGroupDescriptorResponse struct {- Key string `json:"key"`- Value issueTableGroupValueResponse `json:"value"`- Count int64 `json:"count"`+ Key string `json:"key"`+ Value issueTableGroupValueResponse `json:"value"`+ Count int64 `json:"count"`+ SecondaryGroups []issueTableGroupDescriptorResponse `json:"secondary_groups,omitempty"`}type issueTableGroupsResponse struct {@@ -47,16 +64,30 @@ type resolvedIssueTableGroup struct {groupSortExpr stringactiveOptionOrder []stringactiveOptions map[string]struct{}+ primary *resolvedIssueTableGroup+ secondaryValues []string+ secondaryFiltered bool}func issueTableGroupIdentity(group issueTableGroupSpec) string {if group.Kind == "property" {- return "group:property:" + group.PropertyID+ return "group:property:" + group.PropertyID + ":empty=" + strconv.FormatBool(group.IncludeEmpty)+ }+ if group.Kind == "compound" {+ identity := "group:compound:" + group.Primary + ":" + group.Secondary+ if group.SecondaryValues != nil {+ identity += ":visible=" + strings.Join(group.SecondaryValues, ",")+ }+ return identity}return "group:" + group.Kind}func (h *Handler) resolveIssueTableGroup(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, group issueTableGroupSpec, allowNone bool) (resolvedIssueTableGroup, bool) {+ if group.Kind != "compound" && group.SecondaryValues != nil {+ writeError(w, http.StatusBadRequest, "group.secondary_values requires group.kind=compound")+ return resolvedIssueTableGroup{}, false+ }switch group.Kind {case "none":if !allowNone {@@ -79,6 +110,55 @@ func (h *Handler) resolveIssueTableGroup(w http.ResponseWriter, r *http.Request,WHEN 'squad' THEN (SELECT s.name FROM squad s WHERE s.workspace_id = $1 AND s.id = split_part(group_value, ':', 2)::uuid)END, ''))`,}, true+ case "project":+ return resolvedIssueTableGroup{+ kind: "project",+ groupExpr: "COALESCE(i.project_id::text, '__no_project__')",+ groupSortExpr: `CASE WHEN group_value = '__no_project__' THEN '' ELSE LOWER(COALESCE(+ (SELECT p.title FROM project p WHERE p.workspace_id = $1 AND p.id = group_value::uuid),+ ''+)) END`,+ }, true+ case "parent":+ return resolvedIssueTableGroup{+ kind: "parent",+ groupExpr: "COALESCE(i.parent_issue_id::text, '__no_parent__')",+ groupSortExpr: `CASE WHEN group_value = '__no_parent__' THEN '' ELSE LOWER(COALESCE(+ (SELECT p.title FROM issue p WHERE p.workspace_id = $1 AND p.id = group_value::uuid),+ ''+)) END`,+ }, true+ case "compound":+ if group.Secondary != "status" {+ writeIssueTableUnsupportedGroup(w, "secondary_group_unsupported", "Only status is supported as a secondary group.")+ return resolvedIssueTableGroup{}, false+ }+ if group.Primary != "assignee" && group.Primary != "project" && group.Primary != "parent" {+ writeIssueTableUnsupportedGroup(w, "primary_group_unsupported", "This primary group is not supported.")+ return resolvedIssueTableGroup{}, false+ }+ seenSecondaryValues := make(map[string]struct{}, len(group.SecondaryValues))+ for _, value := range group.SecondaryValues {+ if !issueTableContainsString(validIssueStatuses, value) {+ writeError(w, http.StatusBadRequest, "invalid group.secondary_values")+ return resolvedIssueTableGroup{}, false+ }+ if _, exists := seenSecondaryValues[value]; exists {+ writeError(w, http.StatusBadRequest, "duplicate group.secondary_values")+ return resolvedIssueTableGroup{}, false+ }+ seenSecondaryValues[value] = struct{}{}+ }+ primary, ok := h.resolveIssueTableGroup(w, r, workspaceID, issueTableGroupSpec{Kind: group.Primary}, false)+ if !ok {+ return resolvedIssueTableGroup{}, false+ }+ return resolvedIssueTableGroup{+ kind: "compound",+ primary: &primary,+ secondaryValues: append([]string(nil), group.SecondaryValues...),+ secondaryFiltered: group.SecondaryValues != nil,+ }, truecase "property":propertyUUID, err := util.ParseUUID(group.PropertyID)if err != nil {@@ -150,6 +230,9 @@ func writeIssueTableUnsupportedGroup(w http.ResponseWriter, code, message string}func (group resolvedIssueTableGroup) expression(addArg func(any) string) string {+ if group.kind == "compound" && group.primary != nil {+ return group.primary.expression(addArg)+ }if group.kind == "property" && group.propertyType == "select" {active := make([]string, 0, len(group.activeOptions))for value := range group.activeOptions {@@ -161,6 +244,9 @@ func (group resolvedIssueTableGroup) expression(addArg func(any) string) string}func (group resolvedIssueTableGroup) sortExpression() string {+ if group.kind == "compound" && group.primary != nil {+ return group.primary.sortExpression()+ }if group.groupSortExpr != "" {return group.groupSortExpr}@@ -168,11 +254,18 @@ func (group resolvedIssueTableGroup) sortExpression() string {}func (group resolvedIssueTableGroup) orderExpression(addArg func(any) string) string {+ if group.kind == "compound" && group.primary != nil {+ return group.primary.orderExpression(addArg)+ }switch group.kind {case "status":return "CASE group_value WHEN 'backlog' THEN 0 WHEN 'todo' THEN 1 WHEN 'in_progress' THEN 2 WHEN 'in_review' THEN 3 WHEN 'done' THEN 4 WHEN 'blocked' THEN 5 WHEN 'cancelled' THEN 6 ELSE 7 END"case "assignee":- return "CASE WHEN group_value = '__unassigned__' THEN 1 ELSE 0 END"+ return "CASE split_part(group_value, ':', 1) WHEN 'member' THEN 0 WHEN 'agent' THEN 1 WHEN 'squad' THEN 2 ELSE 3 END"+ case "project":+ return "CASE WHEN group_value = '__no_project__' THEN 0 ELSE 1 END"+ case "parent":+ return "CASE WHEN group_value = '__no_parent__' THEN 0 ELSE 1 END"case "property":if group.propertyType == "select" {ref := addArg(group.activeOptionOrder)@@ -184,7 +277,51 @@ func (group resolvedIssueTableGroup) orderExpression(addArg func(any) string) st}}-func (group resolvedIssueTableGroup) descriptor(raw string, count int64) (issueTableGroupDescriptorResponse, error) {+func (group resolvedIssueTableGroup) contextExpression(addArg func(any) string, issuePrefix string) string {+ if group.kind == "compound" && group.primary != nil {+ return group.primary.contextExpression(addArg, issuePrefix)+ }+ if group.kind != "parent" {+ return "'{}'::jsonb"+ }+ prefixRef := addArg(issuePrefix)+ return fmt.Sprintf(`CASE WHEN group_value = '__no_parent__' THEN '{}'::jsonb ELSE COALESCE((+ SELECT jsonb_build_object('parent', jsonb_build_object(+ 'id', p.id::text,+ 'number', p.number,+ 'identifier', %s::text || '-' || p.number::text,+ 'title', p.title,+ 'status', p.status+ ))+ FROM issue p+ WHERE p.workspace_id = $1 AND p.id = group_value::uuid+), '{}'::jsonb) END`, prefixRef)+}++func compoundCellGroupKey(primaryKey, status string) string {+ return "compound:" + base64.RawURLEncoding.EncodeToString([]byte(primaryKey)) + ":status:" + status+}++func (group resolvedIssueTableGroup) descriptor(raw string, count int64, context issueTableGroupContext, secondaryCounts map[string]int64) (issueTableGroupDescriptorResponse, error) {+ if group.kind == "compound" && group.primary != nil {+ descriptor, err := group.primary.descriptor(raw, count, context, nil)+ if err != nil {+ return descriptor, err+ }+ descriptor.SecondaryGroups = make([]issueTableGroupDescriptorResponse, 0, len(secondaryCounts))+ for _, status := range validIssueStatuses {+ statusCount := secondaryCounts[status]+ descriptor.SecondaryGroups = append(descriptor.SecondaryGroups, issueTableGroupDescriptorResponse{+ Key: compoundCellGroupKey(descriptor.Key, status),+ Value: issueTableGroupValueResponse{+ Kind: "status",+ Status: status,+ },+ Count: statusCount,+ })+ }+ return descriptor, nil+ }descriptor := issueTableGroupDescriptorResponse{Count: count}switch group.kind {case "status":@@ -208,6 +345,35 @@ func (group resolvedIssueTableGroup) descriptor(raw string, count int64) (issueT}descriptor.Key = "assignee:" + rawdescriptor.Value.Actor = &issueTableActorRef{Type: parts[0], ID: parts[1]}+ case "project":+ descriptor.Value.Kind = "project"+ if raw == "__no_project__" {+ descriptor.Key = "project:none"+ return descriptor, nil+ }+ if _, err := util.ParseUUID(raw); err != nil {+ return descriptor, fmt.Errorf("unexpected project group value %q", raw)+ }+ descriptor.Key = "project:" + raw+ descriptor.Value.ProjectID = &raw+ case "parent":+ descriptor.Value.Kind = "parent"+ if raw == "__no_parent__" {+ descriptor.Key = "parent:none"+ descriptor.Value.ValueState = "unset"+ return descriptor, nil+ }+ if _, err := util.ParseUUID(raw); err != nil {+ return descriptor, fmt.Errorf("unexpected parent group value %q", raw)+ }+ descriptor.Key = "parent:" + raw+ descriptor.Value.ParentID = &raw+ descriptor.Value.Parent = context.Parent+ if context.Parent == nil {+ descriptor.Value.ValueState = "unavailable"+ } else {+ descriptor.Value.ValueState = "value"+ }case "property":state, rawValue, ok := strings.Cut(raw, ":")if !ok {@@ -224,6 +390,9 @@ func (group resolvedIssueTableGroup) descriptor(raw string, count int64) (issueTdescriptor.Value.ValueState = "unset"case "unavailable":descriptor.Value.ValueState = "unavailable"+ if rawValue != "" {+ descriptor.Value.Value = rawValue+ }case "value":descriptor.Value.ValueState = "value"if group.propertyType == "checkbox" {@@ -245,6 +414,29 @@ func (group resolvedIssueTableGroup) descriptor(raw string, count int64) (issueT}func (group resolvedIssueTableGroup) predicate(w http.ResponseWriter, key string, addArg func(any) string) (string, bool) {+ if group.kind == "compound" && group.primary != nil {+ const prefix = "compound:"+ if !strings.HasPrefix(key, prefix) {+ writeError(w, http.StatusBadRequest, "invalid group_key")+ return "", false+ }+ encodedAndStatus := strings.TrimPrefix(key, prefix)+ encoded, status, ok := strings.Cut(encodedAndStatus, ":status:")+ if !ok || !issueTableContainsString(validIssueStatuses, status) {+ writeError(w, http.StatusBadRequest, "invalid group_key")+ return "", false+ }+ decoded, err := base64.RawURLEncoding.DecodeString(encoded)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid group_key")+ return "", false+ }+ primaryPredicate, ok := group.primary.predicate(w, string(decoded), addArg)+ if !ok {+ return "", false+ }+ return fmt.Sprintf("(%s) AND i.status = %s::text", primaryPredicate, addArg(status)), true+ }switch group.kind {case "none":if key != "" {@@ -280,6 +472,38 @@ func (group resolvedIssueTableGroup) predicate(w http.ResponseWriter, key stringreturn "", false}return fmt.Sprintf("i.assignee_type = %s::text AND i.assignee_id = %s::uuid", addArg(parts[0]), addArg(id)), true+ case "project":+ const prefix = "project:"+ if !strings.HasPrefix(key, prefix) {+ writeError(w, http.StatusBadRequest, "invalid group_key")+ return "", false+ }+ raw := strings.TrimPrefix(key, prefix)+ if raw == "none" {+ return "i.project_id IS NULL", true+ }+ id, err := util.ParseUUID(raw)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid group_key")+ return "", false+ }+ return fmt.Sprintf("i.project_id = %s::uuid", addArg(id)), true+ case "parent":+ const prefix = "parent:"+ if !strings.HasPrefix(key, prefix) {+ writeError(w, http.StatusBadRequest, "invalid group_key")+ return "", false+ }+ raw := strings.TrimPrefix(key, prefix)+ if raw == "none" {+ return "i.parent_issue_id IS NULL", true+ }+ id, err := util.ParseUUID(raw)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid group_key")+ return "", false+ }+ return fmt.Sprintf("i.parent_issue_id = %s::uuid", addArg(id)), truecase "property":prefix := "property:" + group.propertyID + ":"if !strings.HasPrefix(key, prefix) {@@ -383,6 +607,7 @@ func (h *Handler) ListIssueTableGroups(w http.ResponseWriter, r *http.Request) {groupExpr := group.expression(addArg)groupSortExpr := group.sortExpression()orderExpr := group.orderExpression(addArg)+ contextExpr := group.contextExpression(addArg, h.getIssuePrefix(r.Context(), compiled.workspaceID))cursorPredicate := "TRUE"if cursor != nil {if cursor.GroupOrder == nil || cursor.GroupSortKey == nil || cursor.GroupCursorKey == nil {@@ -399,24 +624,111 @@ func (h *Handler) ListIssueTableGroups(w http.ResponseWriter, r *http.Request) {))`, orderRef, sortRef, keyRef)}limitRef := addArg(limit + 1)- query := fmt.Sprintf(`WITH grouped AS (- SELECT %s AS group_value, COUNT(*)::bigint AS issue_count- FROM issue i- WHERE %s- GROUP BY 1- ), sorted AS (- SELECT group_value, issue_count, (%s)::text AS group_sort+ groupedCTE := fmt.Sprintf(`grouped AS (+ SELECT %s AS group_value, COUNT(*)::bigint AS issue_count,+ COUNT(*)::bigint AS visible_count, '{}'::jsonb AS secondary_counts+ FROM issue i+ WHERE %s+ GROUP BY 1+)`, groupExpr, compiled.where)+ if request.Group.IncludeEmpty && group.kind == "property" {+ expectedValues := []string{"unset:"}+ if group.propertyType == "select" {+ expectedValues = append(append([]string(nil), group.activeOptionOrder...), "unset:")+ } else {+ expectedValues = []string{"value:false", "value:true", "unset:"}+ }+ expectedRef := addArg(expectedValues)+ groupedCTE = fmt.Sprintf(`actual AS (+ SELECT %s AS group_value, COUNT(*)::bigint AS issue_count+ FROM issue i+ WHERE %s+ GROUP BY 1+), expected AS (+ SELECT unnest(%s::text[]) AS group_value+), grouped AS (+ SELECT e.group_value, COALESCE(a.issue_count, 0)::bigint AS issue_count,+ COALESCE(a.issue_count, 0)::bigint AS visible_count,+ '{}'::jsonb AS secondary_counts+ FROM expected e+ LEFT JOIN actual a USING (group_value)+ UNION ALL+ SELECT a.group_value, a.issue_count, a.issue_count AS visible_count,+ '{}'::jsonb AS secondary_counts+ FROM actual a+ WHERE NOT (a.group_value = ANY(%s::text[]))+)`, groupExpr, compiled.where, expectedRef, expectedRef)+ }+ if group.kind == "compound" {+ groupedCTE = fmt.Sprintf(`cells AS (+ SELECT %s AS group_value, i.status AS secondary_value, COUNT(*)::bigint AS cell_count+ FROM issue i+ WHERE %s+ GROUP BY 1, 2+), grouped AS (+ SELECT group_value,+ SUM(cell_count)::bigint AS issue_count,+ SUM(cell_count)::bigint AS visible_count,+ jsonb_object_agg(secondary_value, cell_count)::jsonb AS secondary_counts+ FROM cells+ GROUP BY group_value+)`, groupExpr, compiled.where)+ if group.secondaryFiltered {+ visibleRef := addArg(group.secondaryValues)+ headerPredicate := "TRUE"+ promotedParentsCTE := ""+ if group.primary != nil && group.primary.kind == "parent" {+ headerPredicate = `NOT (+ i.parent_issue_id IS NULL AND+ EXISTS (SELECT 1 FROM promoted_parents p WHERE p.id = i.id)+ )`+ promotedParentsCTE = fmt.Sprintf(`, promoted_parents AS (+ SELECT DISTINCT child.parent_issue_id AS id+ FROM membership child+ WHERE child.parent_issue_id IS NOT NULL+ AND child.status = ANY(%s::text[])+)`, visibleRef)+ }+ groupedCTE = fmt.Sprintf(`membership AS NOT MATERIALIZED (+ SELECT i.*+ FROM issue i+ WHERE %s+)%s, cells AS (+ SELECT %s AS group_value, i.status AS secondary_value,+ COUNT(*) FILTER (WHERE %s)::bigint AS cell_count+ FROM membership i+ GROUP BY 1, 2+), grouped AS (+ SELECT group_value,+ SUM(cell_count)::bigint AS issue_count,+ COALESCE(+ SUM(cell_count) FILTER (WHERE secondary_value = ANY(%s::text[])),+ 0+ )::bigint AS visible_count,+ jsonb_object_agg(secondary_value, cell_count)::jsonb AS secondary_counts+ FROM cells+ GROUP BY group_value+ HAVING COALESCE(+ SUM(cell_count) FILTER (WHERE secondary_value = ANY(%s::text[])),+ 0+ ) > 0+)`, compiled.where, promotedParentsCTE, groupExpr, headerPredicate, visibleRef, visibleRef)+ }+ }+ query := fmt.Sprintf(`WITH %s, sorted AS (+ SELECT group_value, issue_count, visible_count, secondary_counts, (%s)::text AS group_sort,+ (%s)::jsonb AS group_contextFROM grouped), ranked AS (- SELECT group_value, issue_count, group_sort, (%s)::int AS group_order,- SUM(issue_count) OVER ()::bigint AS total+ SELECT group_value, issue_count, visible_count, secondary_counts, group_sort, group_context, (%s)::int AS group_order,+ SUM(visible_count) OVER ()::bigint AS totalFROM sorted)- SELECT group_value, issue_count, group_sort, group_order, total+ SELECT group_value, issue_count, secondary_counts, group_sort, group_context, group_order, totalFROM rankedWHERE %sORDER BY group_order ASC, group_sort ASC, group_value ASC- LIMIT %s`, groupExpr, compiled.where, groupSortExpr, orderExpr, cursorPredicate, limitRef)+ LIMIT %s`, groupedCTE, groupSortExpr, contextExpr, orderExpr, cursorPredicate, limitRef)rows, err := h.DB.Query(r.Context(), query, args...)if err != nil {@@ -434,13 +746,29 @@ func (h *Handler) ListIssueTableGroups(w http.ResponseWriter, r *http.Request) {for rows.Next() {var raw stringvar count int64+ var secondaryJSON []bytevar sortValue string+ var contextJSON []bytevar order int- if err := rows.Scan(&raw, &count, &sortValue, &order, &total); err != nil {+ if err := rows.Scan(&raw, &count, &secondaryJSON, &sortValue, &contextJSON, &order, &total); err != nil {writeIssueTableQueryFailure(w, r, "failed to list table groups")return}- descriptor, err := group.descriptor(raw, count)+ var context issueTableGroupContext+ if len(contextJSON) > 0 {+ if err := json.Unmarshal(contextJSON, &context); err != nil {+ writeIssueTableQueryFailure(w, r, "failed to resolve table group")+ return+ }+ }+ secondaryCounts := map[string]int64{}+ if len(secondaryJSON) > 0 {+ if err := json.Unmarshal(secondaryJSON, &secondaryCounts); err != nil {+ writeIssueTableQueryFailure(w, r, "failed to resolve table group")+ return+ }+ }+ descriptor, err := group.descriptor(raw, count, context, secondaryCounts)if err != nil {slog.Warn("ListIssueTableGroups descriptor failed", append(logger.RequestAttrs(r), "error", err)...)writeError(w, http.StatusInternalServerError, "failed to resolve table group")diff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.goindex fb8c0755d1..8003eb3b88 100644--- a/server/internal/handler/issue_table_query.go+++ b/server/internal/handler/issue_table_query.go@@ -108,8 +108,12 @@ type issueTableQuerySpec struct {}type issueTableGroupSpec struct {- Kind string `json:"kind"`- PropertyID string `json:"property_id,omitempty"`+ Kind string `json:"kind"`+ PropertyID string `json:"property_id,omitempty"`+ IncludeEmpty bool `json:"include_empty,omitempty"`+ Primary string `json:"primary,omitempty"`+ Secondary string `json:"secondary,omitempty"`+ SecondaryValues []string `json:"secondary_values,omitempty"`}type issueTablePageRequest struct {diff --git a/server/internal/handler/issue_table_query_test.go b/server/internal/handler/issue_table_query_test.goindex 0066d2751b..b521dbfd45 100644--- a/server/internal/handler/issue_table_query_test.go+++ b/server/internal/handler/issue_table_query_test.go@@ -170,6 +170,47 @@ func TestIssueTablePositionCursorIncludesIndexableLowerBound(t *testing.T) {}}+func TestIssueTableGroupIdentityBindsIncludeEmpty(t *testing.T) {+ withoutEmpty := issueTableGroupIdentity(issueTableGroupSpec{+ Kind: "property",+ PropertyID: "00000000-0000-4000-8000-000000000001",+ })+ withEmpty := issueTableGroupIdentity(issueTableGroupSpec{+ Kind: "property",+ PropertyID: "00000000-0000-4000-8000-000000000001",+ IncludeEmpty: true,+ })+ if withoutEmpty == withEmpty {+ t.Fatalf("include-empty property cursors share an identity: %q", withEmpty)+ }+}++func TestIssueTableCompoundCellKeyResolvesPrimaryAndStatus(t *testing.T) {+ primary := resolvedIssueTableGroup{kind: "parent"}+ compound := resolvedIssueTableGroup{kind: "compound", primary: &primary}+ key := compoundCellGroupKey(+ "parent:00000000-0000-4000-8000-000000000001",+ "todo",+ )+ args := make([]any, 0, 2)+ predicate, ok := compound.predicate(+ httptest.NewRecorder(),+ key,+ func(value any) string {+ args = append(args, value)+ return fmt.Sprintf("$%d", len(args))+ },+ )+ if !ok {+ t.Fatal("valid compound cell key was rejected")+ }+ if !strings.Contains(predicate, "i.parent_issue_id = $1::uuid") ||+ !strings.Contains(predicate, "i.status = $2::text") ||+ len(args) != 2 || args[1] != "todo" {+ t.Fatalf("compound cell predicate lost a dimension: %s args=%#v", predicate, args)+ }+}+func TestIssueTableRowsCommitsBeforeBestEffortEnrichment(t *testing.T) {ctx := context.Background()suffix := time.Now().UnixNano()@@ -705,6 +746,10 @@ func TestIssueTableAssigneeNamesResolveAfterGrouping(t *testing.T) {if counts["assignee:member:"+testUserID] != 1 || counts["assignee:unassigned"] != 1 {t.Fatalf("unexpected assignee groups: %#v", counts)}+ if response.Groups[0].Key != "assignee:member:"+testUserID ||+ response.Groups[len(response.Groups)-1].Key != "assignee:unassigned" {+ t.Fatalf("assignee groups are not actor-priority ordered: %#v", response.Groups)+ }sortedAt := strings.Index(groupQuerySQL, "), sorted AS (")nameLookupAt := strings.Index(groupQuerySQL, `SELECT u.name FROM "user" u`)if sortedAt < 0 || nameLookupAt < sortedAt {@@ -712,6 +757,223 @@ func TestIssueTableAssigneeNamesResolveAfterGrouping(t *testing.T) {}}+func TestIssueTableCompoundParentGroupsReturnExactStatusCells(t *testing.T) {+ ctx := context.Background()+ suffix := time.Now().UnixNano()+ var projectID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO project (workspace_id, title)+ VALUES ($1, $2)+ RETURNING id+ `, testWorkspaceID, fmt.Sprintf("Compound parent grouping %d", suffix)).Scan(&projectID); err != nil {+ t.Fatalf("create project: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE project_id = $1`, projectID)+ _, _ = testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID)+ })++ var finalNumber int+ if err := testPool.QueryRow(ctx, `+ UPDATE workspace+ SET issue_counter = GREATEST(+ issue_counter,+ (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)+ ) + 4+ WHERE id = $1+ RETURNING issue_counter+ `, testWorkspaceID).Scan(&finalNumber); err != nil {+ t.Fatalf("reserve issue numbers: %v", err)+ }+ var parentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, title, status, priority, creator_type, creator_id,+ position, number, project_id+ )+ VALUES ($1, 'Parent context', 'done', 'none', 'member', $2, 1, $3, $4)+ RETURNING id+ `, testWorkspaceID, testUserID, finalNumber-3, projectID).Scan(&parentID); err != nil {+ t.Fatalf("create parent: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO issue (+ workspace_id, title, status, priority, creator_type, creator_id,+ parent_issue_id, position, number, project_id+ )+ VALUES+ ($1, 'Child todo', 'todo', 'none', 'member', $2, $3, 2, $4, $5),+ ($1, 'Child review', 'in_review', 'none', 'member', $2, $3, 3, $4 + 1, $5),+ ($1, 'No parent', 'todo', 'none', 'member', $2, NULL, 4, $4 + 2, $5)+ `, testWorkspaceID, testUserID, parentID, finalNumber-2, projectID); err != nil {+ t.Fatalf("seed grouped issues: %v", err)+ }++ recorder := httptest.NewRecorder()+ testHandler.ListIssueTableGroups(recorder, newRequest("POST", "/api/issues/table/groups", issueTableGroupsRequest{+ Query: issueTableQuerySpec{+ Scope: issueTableScope{Kind: "project", ProjectID: projectID},+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},+ },+ Group: issueTableGroupSpec{Kind: "compound", Primary: "parent", Secondary: "status"},+ Page: issueTablePageRequest{Limit: 10},+ }))+ if recorder.Code != http.StatusOK {+ t.Fatalf("compound groups status = %d: %s", recorder.Code, recorder.Body.String())+ }+ var response issueTableGroupsResponse+ if err := json.NewDecoder(recorder.Body).Decode(&response); err != nil {+ t.Fatalf("decode compound groups: %v", err)+ }+ if response.Total != 4 || len(response.Groups) != 2 {+ t.Fatalf("unexpected compound group totals: %#v", response)+ }+ byKey := make(map[string]issueTableGroupDescriptorResponse, len(response.Groups))+ for _, group := range response.Groups {+ byKey[group.Key] = group+ }+ parent := byKey["parent:"+parentID]+ if parent.Count != 2 || parent.Value.Parent == nil ||+ parent.Value.Parent.Title != "Parent context" ||+ parent.Value.ValueState != "value" {+ t.Fatalf("parent descriptor lost context: %#v", parent)+ }+ parentCells := make(map[string]int64, len(parent.SecondaryGroups))+ for _, cell := range parent.SecondaryGroups {+ parentCells[cell.Value.Status] = cell.Count+ if !strings.HasPrefix(cell.Key, "compound:") {+ t.Fatalf("cell key is not opaque compound key: %q", cell.Key)+ }+ }+ if parentCells["todo"] != 1 || parentCells["in_review"] != 1 {+ t.Fatalf("unexpected parent status cells: %#v", parentCells)+ }+ noParent := byKey["parent:none"]+ if noParent.Count != 2 || noParent.Value.ValueState != "unset" {+ t.Fatalf("unexpected no-parent lane: %#v", noParent)+ }++ // A second parent has only a hidden-status child. Under a visible-status+ // compound query it must stay a No-parent card instead of creating an+ // empty lane. The first parent does have a visible child, so it is promoted+ // to a lane header and must disappear from the No-parent rows and counts.+ var hiddenParentNumber int+ if err := testPool.QueryRow(ctx, `+ UPDATE workspace+ SET issue_counter = issue_counter + 2+ WHERE id = $1+ RETURNING issue_counter+ `, testWorkspaceID).Scan(&hiddenParentNumber); err != nil {+ t.Fatalf("reserve hidden-parent issue numbers: %v", err)+ }+ var hiddenParentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, title, status, priority, creator_type, creator_id,+ position, number, project_id+ )+ VALUES ($1, 'Visible parent card', 'todo', 'none', 'member', $2, 5, $3, $4)+ RETURNING id+ `, testWorkspaceID, testUserID, hiddenParentNumber-1, projectID).Scan(&hiddenParentID); err != nil {+ t.Fatalf("create hidden-only parent: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO issue (+ workspace_id, title, status, priority, creator_type, creator_id,+ parent_issue_id, position, number, project_id+ )+ VALUES ($1, 'Hidden child', 'done', 'none', 'member', $2, $3, 6, $4, $5)+ `, testWorkspaceID, testUserID, hiddenParentID, hiddenParentNumber, projectID); err != nil {+ t.Fatalf("create hidden child: %v", err)+ }++ filteredGroup := issueTableGroupSpec{+ Kind: "compound",+ Primary: "parent",+ Secondary: "status",+ SecondaryValues: []string{"todo"},+ }+ filteredRecorder := httptest.NewRecorder()+ testHandler.ListIssueTableGroups(filteredRecorder, newRequest("POST", "/api/issues/table/groups", issueTableGroupsRequest{+ Query: issueTableQuerySpec{+ Scope: issueTableScope{Kind: "project", ProjectID: projectID},+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},+ },+ Group: filteredGroup,+ Page: issueTablePageRequest{Limit: 10},+ }))+ if filteredRecorder.Code != http.StatusOK {+ t.Fatalf("filtered compound groups status = %d: %s", filteredRecorder.Code, filteredRecorder.Body.String())+ }+ var filtered issueTableGroupsResponse+ if err := json.NewDecoder(filteredRecorder.Body).Decode(&filtered); err != nil {+ t.Fatalf("decode filtered compound groups: %v", err)+ }+ if filtered.Total != 3 || len(filtered.Groups) != 2 {+ t.Fatalf("unexpected visible compound groups: %#v", filtered)+ }+ filteredByKey := make(map[string]issueTableGroupDescriptorResponse, len(filtered.Groups))+ for _, descriptor := range filtered.Groups {+ filteredByKey[descriptor.Key] = descriptor+ }+ if _, exists := filteredByKey["parent:"+hiddenParentID]; exists {+ t.Fatalf("hidden-only parent lane was returned: %#v", filtered.Groups)+ }+ filteredParent := filteredByKey["parent:"+parentID]+ filteredNoParent := filteredByKey["parent:none"]+ if filteredParent.Count != 2 || filteredNoParent.Count != 2 {+ t.Fatalf("parent header was not removed from aligned counts: parent=%#v no-parent=%#v", filteredParent, filteredNoParent)+ }++ cellKey := func(descriptor issueTableGroupDescriptorResponse, status string) string {+ t.Helper()+ for _, cell := range descriptor.SecondaryGroups {+ if cell.Value.Status == status {+ return cell.Key+ }+ }+ t.Fatalf("missing %s cell in %#v", status, descriptor)+ return ""+ }+ listCell := func(key string) issueTableRowsResponse {+ t.Helper()+ rowsRecorder := httptest.NewRecorder()+ testHandler.ListIssueTableRows(rowsRecorder, newRequest("POST", "/api/issues/table/rows", issueTableRowsRequest{+ Query: issueTableQuerySpec{+ Scope: issueTableScope{Kind: "project", ProjectID: projectID},+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},+ },+ Group: filteredGroup,+ GroupKey: &key,+ Hierarchy: issueTableHierarchyRequest{Enabled: false},+ Page: issueTablePageRequest{Limit: 10},+ }))+ if rowsRecorder.Code != http.StatusOK {+ t.Fatalf("filtered compound rows status = %d: %s", rowsRecorder.Code, rowsRecorder.Body.String())+ }+ var result issueTableRowsResponse+ if err := json.NewDecoder(rowsRecorder.Body).Decode(&result); err != nil {+ t.Fatalf("decode filtered compound rows: %v", err)+ }+ return result+ }+ noParentTodo := listCell(cellKey(filteredNoParent, "todo"))+ if len(noParentTodo.Rows) != 2 {+ t.Fatalf("unexpected visible no-parent rows: %#v", noParentTodo.Rows)+ }+ noParentIDs := map[string]bool{}+ for _, row := range noParentTodo.Rows {+ noParentIDs[row.Issue.ID] = true+ }+ if noParentIDs[parentID] || !noParentIDs[hiddenParentID] {+ t.Fatalf("parent header/card semantics diverged: %#v", noParentIDs)+ }+ noParentDone := listCell(cellKey(filteredNoParent, "done"))+ if len(noParentDone.Rows) != 0 {+ t.Fatalf("promoted parent remained in No-parent rows: %#v", noParentDone.Rows)+ }+}+func TestIssueTableHierarchyDoesNotCrossGroups(t *testing.T) {ctx := context.Background()var projectID stringdiff --git a/server/internal/handler/issue_table_rows.go b/server/internal/handler/issue_table_rows.goindex c4680ac76c..b0f8002855 100644--- a/server/internal/handler/issue_table_rows.go+++ b/server/internal/handler/issue_table_rows.go@@ -312,6 +312,26 @@ func (h *Handler) ListIssueTableRows(w http.ResponseWriter, r *http.Request) {), `, compiled.where, groupPredicate)pageSource = "membership"pagePredicate = branchPredicate+ } else if group.kind == "compound" &&+ group.primary != nil &&+ group.primary.kind == "parent" &&+ group.secondaryFiltered {+ visibleRef := addArg(group.secondaryValues)+ ctePrefix += fmt.Sprintf(`membership AS NOT MATERIALIZED (+ SELECT i.*+ FROM issue i+ WHERE %s+), promoted_parents AS (+ SELECT DISTINCT child.parent_issue_id AS id+ FROM membership child+ WHERE child.parent_issue_id IS NOT NULL+ AND child.status = ANY(%s::text[])+), `, compiled.where, visibleRef)+ pageSource = "membership"+ pagePredicate = fmt.Sprintf(`(%s) AND NOT (+ i.parent_issue_id IS NULL AND+ EXISTS (SELECT 1 FROM promoted_parents p WHERE p.id = i.id)+)`, groupPredicate)}cte := fmt.Sprintf(`%spage AS MATERIALIZED (SELECT i.*, (%s)::text AS table_sort_key