Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-3903: Extract shared issue surfaces (#4774)
Naiyuan Qingade6b34e5f8d
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex cbc8de8a9a..d02858c8ae 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -499,6 +499,7 @@ export class ApiClient {if (params?.priority) search.set("priority", params.priority);if (params?.assignee_id) search.set("assignee_id", params.assignee_id);if (params?.assignee_ids?.length) search.set("assignee_ids", params.assignee_ids.join(","));+ if (params?.assignee_types?.length) search.set("assignee_types", params.assignee_types.join(","));if (params?.creator_id) search.set("creator_id", params.creator_id);if (params?.project_id) search.set("project_id", params.project_id);if (params?.involves_user_id) search.set("involves_user_id", params.involves_user_id);diff --git a/packages/core/inbox/ws-updaters.ts b/packages/core/inbox/ws-updaters.tsindex 0a5a05dba4..a308dfad9c 100644--- a/packages/core/inbox/ws-updaters.ts+++ b/packages/core/inbox/ws-updaters.ts@@ -12,7 +12,7 @@ export function onInboxNew(qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });}-export function onInboxIssueStatusChanged(+export function patchInboxIssueStatus(qc: QueryClient,wsId: string,issueId: string,@@ -25,6 +25,15 @@ export function onInboxIssueStatusChanged();}+export function onInboxIssueStatusChanged(+ qc: QueryClient,+ wsId: string,+ issueId: string,+ status: IssueStatus,+) {+ patchInboxIssueStatus(qc, wsId, issueId, status);+}+// Mirrors the DB-level ON DELETE CASCADE on inbox_item.issue_id: when an issue// is deleted, all inbox items that referenced it are gone server-side, so drop// them from the cache too.diff --git a/packages/core/issues/cache-coordinator.test.ts b/packages/core/issues/cache-coordinator.test.tsnew file mode 100644index 0000000000..cc9d000739--- /dev/null+++ b/packages/core/issues/cache-coordinator.test.ts@@ -0,0 +1,357 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { QueryClient, hashKey } from "@tanstack/react-query";+import {+ applyIssueChange,+ rollbackIssueChange,+} from "./cache-coordinator";+import { issueChangedDims } from "./surface/membership";+import { issueKeys, type IssueSortParam } from "./queries";+import { inboxKeys } from "../inbox/queries";+import type { InboxItem, Issue, ListIssuesCache } from "../types";++const WS_ID = "ws-1";+const sort: IssueSortParam = { sort_by: "position", sort_direction: undefined };++const wsKey = issueKeys.listSorted(WS_ID, sort);+const myAssignedKey = issueKeys.myListSorted(WS_ID, "assigned", { assignee_id: "me" }, sort);+const myAllKey = issueKeys.myListSorted(WS_ID, "all", {}, sort);+const involvedKey = issueKeys.myListSorted(WS_ID, "agents", { involves_user_id: "me" }, sort);+const projectP1Key = issueKeys.myListSorted(WS_ID, "project:p1", { project_id: "p1" }, sort);+const projectP2Key = issueKeys.myListSorted(WS_ID, "project:p2", { project_id: "p2" }, sort);+const membersKey = issueKeys.myListSorted(+ WS_ID,+ "workspace:members",+ { assignee_types: ["member"] },+ sort,+);+const inboxKey = inboxKeys.list(WS_ID);++function makeIssue(idx: number, overrides: Partial<Issue> = {}): Issue {+ return {+ id: `issue-${idx}`,+ workspace_id: WS_ID,+ number: idx,+ identifier: `MUL-${idx}`,+ title: `Issue ${idx}`,+ description: null,+ status: "todo",+ priority: "none",+ assignee_type: "member",+ assignee_id: "me",+ creator_type: "member",+ creator_id: "me",+ parent_issue_id: null,+ project_id: "p1",+ position: idx,+ stage: null,+ start_date: null,+ due_date: null,+ labels: [],+ metadata: {},+ created_at: "2025-01-01T00:00:00Z",+ updated_at: "2025-01-01T00:00:00Z",+ ...overrides,+ };+}++function bucketed(issues: Issue[], extraTotal = 0): ListIssuesCache {+ return {+ byStatus: {+ todo: {+ issues: issues.filter((i) => i.status === "todo"),+ total: issues.filter((i) => i.status === "todo").length + extraTotal,+ },+ in_progress: {+ issues: issues.filter((i) => i.status === "in_progress"),+ total: issues.filter((i) => i.status === "in_progress").length,+ },+ },+ };+}++function ids(qc: QueryClient, key: readonly unknown[], status: "todo" | "in_progress") {+ const cache = qc.getQueryData<ListIssuesCache>(key);+ return (cache?.byStatus[status]?.issues ?? []).map((i) => i.id);+}++function total(qc: QueryClient, key: readonly unknown[], status: "todo" | "in_progress") {+ return qc.getQueryData<ListIssuesCache>(key)?.byStatus[status]?.total;+}++describe("applyIssueChange", () => {+ let qc: QueryClient;+ const issue = () => makeIssue(1);++ beforeEach(() => {+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ });++ afterEach(() => {+ qc.clear();+ });++ it("plain field change: patches in place everywhere, no removals, no stale keys", () => {+ qc.setQueryData<ListIssuesCache>(wsKey, bucketed([issue()]));+ qc.setQueryData<ListIssuesCache>(myAssignedKey, bucketed([issue()]));+ qc.setQueryData<ListIssuesCache>(involvedKey, bucketed([issue()]));+ qc.setQueryData<Issue>(issueKeys.detail(WS_ID, "issue-1"), issue());++ const patch = { title: "renamed" };+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {+ changed: issueChangedDims(patch, issue()),+ baseIssue: issue(),+ });++ for (const key of [wsKey, myAssignedKey, involvedKey]) {+ const cache = qc.getQueryData<ListIssuesCache>(key);+ expect(cache?.byStatus.todo?.issues[0]?.title).toBe("renamed");+ }+ expect(qc.getQueryData<Issue>(issueKeys.detail(WS_ID, "issue-1"))?.title).toBe(+ "renamed",+ );+ expect(result.staleKeys).toEqual([]);+ });++ it("status change: rebuckets loaded cards, patches inbox, adjusts counts for absent-but-member lists", () => {+ qc.setQueryData<ListIssuesCache>(wsKey, bucketed([issue()]));+ // p1 list loaded but the card is beyond its loaded window — the change+ // is certain (old + new status known, membership definite), so the two+ // bucket totals shift arithmetically with zero requests.+ qc.setQueryData<ListIssuesCache>(projectP1Key, bucketed([], 3));+ // p2 list loaded; the issue was never a member — untouched.+ qc.setQueryData<ListIssuesCache>(projectP2Key, bucketed([]));+ qc.setQueryData<InboxItem[]>(inboxKey, [+ {+ id: "inbox-1",+ workspace_id: WS_ID,+ recipient_type: "member",+ recipient_id: "me",+ actor_type: "member",+ actor_id: "bob",+ type: "status_changed",+ severity: "info",+ issue_id: "issue-1",+ title: "Inbox",+ body: null,+ issue_status: "todo",+ read: false,+ archived: false,+ created_at: "2025-01-01T00:00:00Z",+ details: null,+ },+ ]);++ const patch = { status: "in_progress" as const };+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {+ changed: issueChangedDims(patch, issue()),+ baseIssue: issue(),+ });++ expect(ids(qc, wsKey, "todo")).toEqual([]);+ expect(ids(qc, wsKey, "in_progress")).toEqual(["issue-1"]);+ expect(+ qc.getQueryData<InboxItem[]>(inboxKey)?.[0]?.issue_status,+ ).toBe("in_progress");++ // Off-window count arithmetic: todo 3 → 2, in_progress 0 → 1, loaded+ // arrays untouched, and no refetch needed.+ expect(total(qc, projectP1Key, "todo")).toBe(2);+ expect(total(qc, projectP1Key, "in_progress")).toBe(1);+ expect(ids(qc, projectP1Key, "todo")).toEqual([]);++ const staleHashes = result.staleKeys.map(hashKey);+ expect(staleHashes).not.toContain(hashKey(projectP1Key));+ expect(staleHashes).not.toContain(hashKey(projectP2Key));+ expect(staleHashes).not.toContain(hashKey(wsKey));+ });++ it("off-window leave: decrements the old status bucket total without a refetch", () => {+ // The card is beyond My-Assigned's loaded window; reassigning it to bob+ // means the list's todo total counted it and must lose one.+ qc.setQueryData<ListIssuesCache>(myAssignedKey, bucketed([], 2));++ const patch = { assignee_id: "bob", assignee_type: "member" as const };+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {+ changed: issueChangedDims(patch, issue()),+ baseIssue: issue(),+ });++ expect(total(qc, myAssignedKey, "todo")).toBe(1);+ expect(result.staleKeys).toEqual([]);+ });++ it("off-window member-to-member reassignment leaves counts and pages untouched", () => {+ // Members tab: bob is still a member, membership holds, status unchanged+ // — nothing about this list can have drifted, so not even a stale key.+ qc.setQueryData<ListIssuesCache>(membersKey, bucketed([], 5));++ const patch = { assignee_id: "bob", assignee_type: "member" as const };+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {+ changed: issueChangedDims(patch, issue()),+ baseIssue: issue(),+ });++ expect(total(qc, membersKey, "todo")).toBe(5);+ expect(result.staleKeys).toEqual([]);+ });++ it("rolls off-window count arithmetic back on failure", () => {+ const snapshot = bucketed([], 3);+ qc.setQueryData<ListIssuesCache>(projectP1Key, snapshot);++ const patch = { status: "in_progress" as const };+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {+ changed: issueChangedDims(patch, issue()),+ baseIssue: issue(),+ });+ expect(total(qc, projectP1Key, "todo")).toBe(2);++ rollbackIssueChange(qc, WS_ID, "issue-1", result);+ expect(qc.getQueryData<ListIssuesCache>(projectP1Key)).toEqual(snapshot);+ });++ it("assignee change me→bob: removes from my-assigned (total decremented), keeps members tab, flags union/involves scopes", () => {+ qc.setQueryData<ListIssuesCache>(wsKey, bucketed([issue()]));+ qc.setQueryData<ListIssuesCache>(myAssignedKey, bucketed([issue()]));+ qc.setQueryData<ListIssuesCache>(myAllKey, bucketed([issue()]));+ qc.setQueryData<ListIssuesCache>(involvedKey, bucketed([issue()]));+ qc.setQueryData<ListIssuesCache>(membersKey, bucketed([issue()]));++ const patch = { assignee_id: "bob", assignee_type: "member" as const };+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {+ changed: issueChangedDims(patch, issue()),+ baseIssue: issue(),+ });++ // The bug this fixes: the card must LEAVE my-assigned immediately —+ // no WS echo, no refetch needed.+ expect(ids(qc, myAssignedKey, "todo")).toEqual([]);+ expect(total(qc, myAssignedKey, "todo")).toBe(0);+ // Workspace board and members tab (bob is still a member) keep the card,+ // with the new assignee patched in.+ expect(ids(qc, wsKey, "todo")).toEqual(["issue-1"]);+ expect(ids(qc, membersKey, "todo")).toEqual(["issue-1"]);+ expect(+ qc.getQueryData<ListIssuesCache>(membersKey)?.byStatus.todo?.issues[0]+ ?.assignee_id,+ ).toBe("bob");++ // Union (my:all) and involves membership are server knowledge — patched+ // in place but flagged for a deferred refetch.+ const staleHashes = result.staleKeys.map(hashKey);+ expect(staleHashes).toContain(hashKey(myAllKey));+ expect(staleHashes).toContain(hashKey(involvedKey));+ expect(staleHashes).not.toContain(hashKey(myAssignedKey));+ expect(staleHashes).not.toContain(hashKey(membersKey));+ });++ it("member→agent reassignment: leaves the members tab, enters the loaded agents tab via stale key", () => {+ const agentsKey = issueKeys.myListSorted(+ WS_ID,+ "workspace:agents",+ { assignee_types: ["agent", "squad"] },+ sort,+ );+ qc.setQueryData<ListIssuesCache>(membersKey, bucketed([issue()]));+ qc.setQueryData<ListIssuesCache>(agentsKey, bucketed([]));++ const patch = { assignee_id: "agent-1", assignee_type: "agent" as const };+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {+ changed: issueChangedDims(patch, issue()),+ baseIssue: issue(),+ });++ expect(ids(qc, membersKey, "todo")).toEqual([]);+ // Never hard-insert into the agents tab — the right page/slot is server+ // knowledge; the loaded list is flagged for refetch instead.+ expect(ids(qc, agentsKey, "todo")).toEqual([]);+ expect(result.staleKeys.map(hashKey)).toContain(hashKey(agentsKey));+ });++ it("project move p1→p2: removes from the old project's list, flags the loaded target list, never touches unrelated lists", () => {+ qc.setQueryData<ListIssuesCache>(wsKey, bucketed([issue()]));+ qc.setQueryData<ListIssuesCache>(projectP1Key, bucketed([issue()]));+ qc.setQueryData<ListIssuesCache>(projectP2Key, bucketed([]));+ qc.setQueryData<ListIssuesCache>(myAssignedKey, bucketed([issue()]));++ const patch = { project_id: "p2" };+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {+ changed: issueChangedDims(patch, issue()),+ baseIssue: issue(),+ });++ expect(ids(qc, projectP1Key, "todo")).toEqual([]);+ expect(total(qc, projectP1Key, "todo")).toBe(0);+ expect(ids(qc, wsKey, "todo")).toEqual(["issue-1"]);+ // Assignee list membership is untouched by a project move.+ expect(ids(qc, myAssignedKey, "todo")).toEqual(["issue-1"]);++ const staleHashes = result.staleKeys.map(hashKey);+ expect(staleHashes).toContain(hashKey(projectP2Key));+ expect(staleHashes).not.toContain(hashKey(myAssignedKey));+ expect(staleHashes).not.toContain(hashKey(wsKey));+ });++ it("degrades to a stale key when no base entity is known for an absent card", () => {+ // The card is beyond the list's loaded window and neither detail nor any+ // list holds it — without a base the client cannot rule out that it WAS+ // a member (and left), so the list must refetch.+ qc.setQueryData<ListIssuesCache>(myAssignedKey, bucketed([], 2));++ const patch = { assignee_id: "bob", assignee_type: "member" as const };+ const result = applyIssueChange(qc, WS_ID, "issue-99", patch, {+ changed: issueChangedDims(patch),+ });++ expect(result.staleKeys.map(hashKey)).toContain(hashKey(myAssignedKey));+ });++ it("skips absent cards entirely when the change cannot affect the list", () => {+ // Assignee change, project-filtered list, card absent, base known and in+ // another project — nothing about this list can have drifted.+ qc.setQueryData<ListIssuesCache>(projectP2Key, bucketed([]));++ const patch = { assignee_id: "bob", assignee_type: "member" as const };+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {+ changed: issueChangedDims(patch, issue()),+ baseIssue: issue(),+ });++ expect(result.staleKeys).toEqual([]);+ });++ it("rollbackIssueChange restores lists, detail, and inbox exactly", () => {+ const listSnapshot = bucketed([issue()]);+ qc.setQueryData<ListIssuesCache>(myAssignedKey, listSnapshot);+ qc.setQueryData<Issue>(issueKeys.detail(WS_ID, "issue-1"), issue());+ qc.setQueryData<InboxItem[]>(inboxKey, []);++ const patch = { assignee_id: "bob", assignee_type: "member" as const, status: "in_progress" as const };+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {+ changed: issueChangedDims(patch, issue()),+ baseIssue: issue(),+ });+ expect(ids(qc, myAssignedKey, "todo")).toEqual([]);++ rollbackIssueChange(qc, WS_ID, "issue-1", result);++ expect(qc.getQueryData<ListIssuesCache>(myAssignedKey)).toEqual(listSnapshot);+ expect(qc.getQueryData<Issue>(issueKeys.detail(WS_ID, "issue-1"))).toEqual(issue());+ expect(qc.getQueryData<InboxItem[]>(inboxKey)).toEqual([]);+ });++ it("skips grouped caches living under the same key prefixes", () => {+ // myAssigneeGroups lives under the myAll prefix but has no byStatus shape.+ const groupedKey = issueKeys.myAssigneeGroups(WS_ID, "assigned", {});+ const grouped = { groups: [] };+ qc.setQueryData(groupedKey, grouped);++ const patch = { status: "in_progress" as const };+ const result = applyIssueChange(qc, WS_ID, "issue-1", patch, {+ changed: issueChangedDims(patch),+ });++ expect(qc.getQueryData(groupedKey)).toBe(grouped);+ expect(result.staleKeys.map(hashKey)).not.toContain(hashKey(groupedKey));+ });+});diff --git a/packages/core/issues/cache-coordinator.ts b/packages/core/issues/cache-coordinator.tsnew file mode 100644index 0000000000..09015f7dc0--- /dev/null+++ b/packages/core/issues/cache-coordinator.ts@@ -0,0 +1,274 @@+import { hashKey, type QueryClient, type QueryKey } from "@tanstack/react-query";+import { issueKeys, type MyIssuesFilter } from "./queries";+import { inboxKeys } from "../inbox/queries";+import { patchInboxIssueStatus } from "../inbox/ws-updaters";+import { projectKeys } from "../projects/queries";+import {+ decrementBucketTotal,+ findIssueLocation,+ moveBucketTotal,+ patchIssueInBuckets,+ removeIssueFromBuckets,+} from "./cache-helpers";+import {+ issueMatchesListFilter,+ listFilterDependsOn,+ type IssueChangedDims,+} from "./surface/membership";+import type { InboxItem, Issue, ListIssuesCache } from "../types";++/**+ * IssueCacheCoordinator — the one rules table for how a single issue change+ * propagates through the query cache.+ *+ * Every write path converges here: `useUpdateIssue` (onMutate optimistic ++ * onSuccess server reconcile), `useBatchUpdateIssues`, and the WS+ * `issue:updated` handler all call {@link applyIssueChange}, so "I changed+ * it" and "someone else changed it" follow the same rules by construction.+ *+ * The rules, per loaded bucketed list (workspace board + every myList+ * scope — My Issues, Project, actor panels, workspace members/agents tabs):+ *+ * card present, filter untouched by the change → surgical patch (rebucket+ * on status, position-slot insert; never a refetch — refetching the+ * visible list is what made drags flicker)+ * card present, no longer matches the list's filter → surgical REMOVE+ * (bucket total decremented) — the "issue left this surface" case that a+ * filter-blind patch used to leave behind (MUL-3669)+ * card present, membership undecidable client-side (involves / my:all) →+ * patch + mark the key stale+ * card absent, change can't affect this list → skip+ * card absent, stayed a member + status changed → move one unit of the+ * server total between the two buckets (count-only arithmetic, arrays+ * untouched, zero requests)+ * card absent, left the list (reassigned / re-projected) → old status+ * bucket total -1+ * card absent, may have ENTERED, or anything undecidable (no base entity,+ * unknown membership) → mark the key stale (never hard-insert: the+ * right page/slot under the list's sort+filter is server knowledge)+ *+ * Stale keys are NOT invalidated here — timing is the caller's contract:+ * mutations defer them to onSettled (invalidating mid-flight would refetch+ * uncommitted state and stomp the optimistic patch), the WS path invalidates+ * immediately (the server already committed).+ *+ * The detail cache and the Inbox `issue_status` projection are patched in the+ * same pass. Aggregate projections that cannot be recomputed from one entity+ * (assignee-grouped boards, Gantt, project metrics) go through+ * {@link invalidateIssueDerivatives}.+ */++export interface IssueCacheChangeResult {+ /** Pre-change snapshots of every cache this change touched — feed back to+ * {@link rollbackIssueChange} from onError. */+ prevLists: [QueryKey, ListIssuesCache][];+ prevDetail: Issue | undefined;+ prevInboxList: InboxItem[] | undefined;+ /** Loaded list keys whose server result may have drifted (membership+ * unknown, possible enter/leave beyond the loaded window, bucket-count+ * drift). Invalidate on settle (mutation) or immediately (WS). */+ staleKeys: QueryKey[];+ /** The freshest pre-change copy of the issue found while reconciling —+ * callers use it for parent/children bookkeeping without re-scanning. */+ prevIssue: Issue | undefined;+}++/** The server contract a bucketed list key encodes. `myListSorted` keys are+ * `["issues", wsId, "my", scope, filter, sort]`; the workspace list carries+ * no filter. The `byStatus` shape check upstream keeps grouped/flat caches+ * under the same prefixes out of this path. */+function listContractFromKey(+ key: QueryKey,+): { scope: string | undefined; filter: MyIssuesFilter } {+ if (key[2] === "my") {+ return {+ scope: typeof key[3] === "string" ? key[3] : undefined,+ filter: (key[4] ?? {}) as MyIssuesFilter,+ };+ }+ return { scope: undefined, filter: {} };+}++function bucketedListEntries(+ qc: QueryClient,+ wsId: string,+): [QueryKey, ListIssuesCache][] {+ return [+ ...qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) }),+ ...qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.myAll(wsId) }),+ ].filter(+ (entry): entry is [QueryKey, ListIssuesCache] => !!entry[1]?.byStatus,+ );+}++export function applyIssueChange(+ qc: QueryClient,+ wsId: string,+ id: string,+ patch: Partial<Issue>,+ opts: {+ /** Which membership dimensions this change actually moved — compute via+ * `issueChangedDims` (mutations) or the server's WS flags. */+ changed: IssueChangedDims;+ /** Freshest full pre-change entity, used to judge membership for lists+ * where the card is not loaded. Omitting it degrades those judgments to+ * "unknown" → a deferred refetch, never a wrong patch. */+ baseIssue?: Issue;+ },+): IssueCacheChangeResult {+ const { changed, baseIssue } = opts;+ const prevLists: [QueryKey, ListIssuesCache][] = [];+ const staleKeys: QueryKey[] = [];+ let prevIssue: Issue | undefined = baseIssue;++ for (const [key, data] of bucketedListEntries(qc, wsId)) {+ const { scope, filter } = listContractFromKey(key);+ const loc = findIssueLocation(data, id);+ const filterTouched = listFilterDependsOn(scope, filter, changed);++ if (loc) {+ if (!prevIssue) prevIssue = loc.issue;+ let next: ListIssuesCache;+ if (filterTouched) {+ const membership = issueMatchesListFilter(+ { ...loc.issue, ...patch },+ scope,+ filter,+ );+ if (membership === false) {+ next = removeIssueFromBuckets(data, id);+ } else {+ next = patchIssueInBuckets(data, id, patch);+ if (membership === "unknown") staleKeys.push(key);+ }+ } else {+ next = patchIssueInBuckets(data, id, patch);+ }+ if (next !== data) {+ prevLists.push([key, data]);+ qc.setQueryData<ListIssuesCache>(key, next);+ }+ continue;+ }++ // Card not loaded here. Only a change that can move the issue across+ // this list's filter — or shift a per-status count for an issue beyond+ // the loaded window — needs a reconcile; anything else is a no-op.+ if (!filterTouched && !changed.status) continue;+ const wasMember = baseIssue+ ? issueMatchesListFilter(baseIssue, scope, filter)+ : "unknown";+ const isMember = issueMatchesListFilter(+ { ...baseIssue, ...patch },+ scope,+ filter,+ );+ // Neither before nor after the change does this issue belong to the+ // list — its pages and counts are untouched.+ if (wasMember === false && isMember === false) continue;++ // Certain count arithmetic — branch on the membership OUTCOME, never on+ // which field changed, so status / assignee / project (and future team)+ // all flow through the same two cases. wasMember === true implies a+ // baseIssue exists, so the old status is known.+ if (wasMember === true && baseIssue) {+ if (isMember === true) {+ // Still a member. Only a status change moves a count between+ // buckets; anything else (e.g. member→member reassignment) leaves+ // this list's pages and counts untouched.+ if (!changed.status || patch.status === undefined) continue;+ const next = moveBucketTotal(data, baseIssue.status, patch.status);+ if (next !== data) {+ prevLists.push([key, data]);+ qc.setQueryData<ListIssuesCache>(key, next);+ }+ continue;+ }+ if (isMember === false) {+ // Left the list entirely — the bucket it was counted in loses one.+ const next = decrementBucketTotal(data, baseIssue.status);+ if (next !== data) {+ prevLists.push([key, data]);+ qc.setQueryData<ListIssuesCache>(key, next);+ }+ continue;+ }+ }+ // Entering (its page/slot under the list's sort is server knowledge) or+ // any uncertainty (no base, unknown membership) → refetch instead of+ // guessing.+ staleKeys.push(key);+ }++ const prevDetail = qc.getQueryData<Issue>(issueKeys.detail(wsId, id));+ if (prevDetail) {+ qc.setQueryData<Issue>(issueKeys.detail(wsId, id), {+ ...prevDetail,+ ...patch,+ });+ if (!prevIssue) prevIssue = prevDetail;+ }++ // Inbox rows carry an `issue_status` display snapshot; the issue's status+ // is the real state, so the projection follows every status write.+ let prevInboxList: InboxItem[] | undefined;+ if (patch.status !== undefined) {+ prevInboxList = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));+ if (prevInboxList) patchInboxIssueStatus(qc, wsId, id, patch.status);+ }++ return { prevLists, prevDetail, prevInboxList, staleKeys, prevIssue };+}++/** Restore every snapshot captured by {@link applyIssueChange} — the onError+ * leg of the optimistic lifecycle. */+export function rollbackIssueChange(+ qc: QueryClient,+ wsId: string,+ id: string,+ result: Pick<+ IssueCacheChangeResult,+ "prevLists" | "prevDetail" | "prevInboxList"+ >,+) {+ for (const [key, snapshot] of result.prevLists) {+ qc.setQueryData(key, snapshot);+ }+ if (result.prevDetail !== undefined) {+ qc.setQueryData(issueKeys.detail(wsId, id), result.prevDetail);+ }+ if (result.prevInboxList !== undefined) {+ qc.setQueryData(inboxKeys.list(wsId), result.prevInboxList);+ }+}++/**+ * Refresh the aggregate projections a single-entity patch cannot recompute:+ * assignee-grouped boards (regrouping is server logic), every Project Gantt+ * (schedule membership + row mirrors), and project metrics when the change+ * could shift per-project counts.+ */+export function invalidateIssueDerivatives(+ qc: QueryClient,+ wsId: string,+ opts: { statusOrProjectChanged: boolean },+) {+ qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });+ qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });+ qc.invalidateQueries({ queryKey: issueKeys.projectGanttAll(wsId) });+ if (opts.statusOrProjectChanged) {+ qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });+ }+}++/** Invalidate the stale keys reported by {@link applyIssueChange}, deduped —+ * a batch over N issues can report the same key N times. */+export function invalidateStaleListKeys(qc: QueryClient, staleKeys: QueryKey[]) {+ const seen = new Set<string>();+ for (const key of staleKeys) {+ const hash = hashKey(key);+ if (seen.has(hash)) continue;+ seen.add(hash);+ qc.invalidateQueries({ queryKey: key, exact: true });+ }+}diff --git a/packages/core/issues/cache-helpers.ts b/packages/core/issues/cache-helpers.tsindex 9709c584d8..2c638a83f3 100644--- a/packages/core/issues/cache-helpers.ts+++ b/packages/core/issues/cache-helpers.ts@@ -63,6 +63,43 @@ export function removeIssueFromBuckets(});}+/**+ * Count-only reconcile for an issue BEYOND the loaded window: its status+ * changed server-side, so one unit of `total` moves between buckets while+ * the loaded arrays stay untouched. `hasMore` (loaded < total) stays+ * consistent for free.+ */+export function moveBucketTotal(+ resp: ListIssuesCache,+ from: IssueStatus,+ to: IssueStatus,+): ListIssuesCache {+ if (from === to) return resp;+ const fromBucket = getBucket(resp, from);+ const toBucket = getBucket(resp, to);+ let next = setBucket(resp, from, {+ ...fromBucket,+ total: Math.max(0, fromBucket.total - 1),+ });+ next = setBucket(next, to, { ...toBucket, total: toBucket.total + 1 });+ return next;+}++/**+ * Count-only reconcile for an issue BEYOND the loaded window that LEFT the+ * list (reassigned / moved project): the bucket it was counted in loses one.+ */+export function decrementBucketTotal(+ resp: ListIssuesCache,+ status: IssueStatus,+): ListIssuesCache {+ const bucket = getBucket(resp, status);+ return setBucket(resp, status, {+ ...bucket,+ total: Math.max(0, bucket.total - 1),+ });+}+/*** Insert `issue` into `issues` at the slot implied by `position ASC` — the same* ordering the board renders (server `ORDER BY position ASC`). Returns a newdiff --git a/packages/core/issues/mutations.test.tsx b/packages/core/issues/mutations.test.tsxindex 3438a87bc8..5b73b95004 100644--- a/packages/core/issues/mutations.test.tsx+++ b/packages/core/issues/mutations.test.tsx@@ -19,8 +19,10 @@ import {issueKeys,type IssueSortParam,} from "./queries";+import { inboxKeys } from "../inbox/queries";import type {GroupedIssuesResponse,+ InboxItem,Issue,ListIssuesCache,ListIssuesParams,@@ -63,6 +65,32 @@ function makeIssue(idx: number, overrides: Partial<Issue> = {}): Issue {};}+function makeInboxItem(+ id: string,+ issueId: string,+ overrides: Partial<InboxItem> = {},+): InboxItem {+ return {+ id,+ workspace_id: WS_ID,+ recipient_type: "member",+ recipient_id: "user-1",+ actor_type: "member",+ actor_id: "user-2",+ type: "status_changed",+ severity: "info",+ issue_id: issueId,+ title: `Inbox ${id}`,+ body: null,+ issue_status: "todo",+ read: false,+ archived: false,+ created_at: "2025-01-01T00:00:00Z",+ details: null,+ ...overrides,+ };+}+function createWrapper(qc: QueryClient) {return function Wrapper({ children }: { children: ReactNode }) {return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;@@ -209,6 +237,44 @@ describe("useLoadMoreByStatus", () => {expect(updated?.byStatus.in_progress?.issues).toHaveLength(2);});+ it("targets the project surface cache when myIssues uses a project scope key", async () => {+ const sort: IssueSortParam = { sort_by: "position", sort_direction: undefined };+ const myIssues = { scope: "project:p1", filter: { project_id: "p1" } };+ const activeKey = issueKeys.myListSorted(WS_ID, myIssues.scope, myIssues.filter, sort);+ qc.setQueryData<ListIssuesCache>(activeKey, {+ byStatus: { todo: { issues: [makeIssue(1, { project_id: "p1" })], total: 2 } },+ });++ listIssues.mockResolvedValue({+ issues: [makeIssue(2, { project_id: "p1" })],+ total: 2,+ });++ const { result } = renderHook(+ () => useLoadMoreByStatus("todo", myIssues, sort),+ { wrapper: createWrapper(qc) },+ );++ await act(async () => {+ await result.current.loadMore();+ });++ expect(listIssues).toHaveBeenCalledWith({+ status: "todo",+ limit: 50,+ offset: 1,+ sort_by: "position",+ sort_direction: undefined,+ project_id: "p1",+ });++ const updated = qc.getQueryData<ListIssuesCache>(activeKey);+ expect(updated?.byStatus.todo?.issues.map((i) => i.id)).toEqual([+ "issue-1",+ "issue-2",+ ]);+ });+it("works with no sort (matches the {} key used by sort-less callers)", async () => {const myIssues = { scope: "actor", filter: { assignee_id: "user-2" } };const activeKey = issueKeys.myListSorted(WS_ID, myIssues.scope, myIssues.filter, undefined);@@ -325,10 +391,14 @@ describe("useUpdateIssue — optimistic move keeps every bucketed board in sync"const sort: IssueSortParam = { sort_by: "position", sort_direction: undefined };const myScope = "assigned";const myFilter = { assignee_id: "user-1" };+ const projectScope = "project:p1";+ const projectFilter = { project_id: "p1" };const wsKey = issueKeys.listSorted(WS_ID, sort);+ const inboxKey = inboxKeys.list(WS_ID);// My-Issues AND the Project board both ride this myList cache; a move that// only patched the workspace cache snaps back on those boards.const myKey = issueKeys.myListSorted(WS_ID, myScope, myFilter, sort);+ const projectKey = issueKeys.myListSorted(WS_ID, projectScope, projectFilter, sort);let qc: QueryClient;let updateIssue: ReturnType<typeof vi.fn<(id: string, data: unknown) => Promise<Issue>>>;@@ -350,12 +420,23 @@ describe("useUpdateIssue — optimistic move keeps every bucketed board in sync"return (c?.byStatus[status]?.issues ?? []).map((i) => i.id);}+ function inboxStatus(issueId: string) {+ return qc+ .getQueryData<InboxItem[]>(inboxKey)+ ?.find((item) => item.issue_id === issueId)?.issue_status;+ }+beforeEach(() => {qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });updateIssue = vi.fn();setApiInstance({ updateIssue } as unknown as ApiClient);qc.setQueryData<ListIssuesCache>(wsKey, makeBucketed());qc.setQueryData<ListIssuesCache>(myKey, makeBucketed());+ qc.setQueryData<ListIssuesCache>(projectKey, makeBucketed());+ qc.setQueryData<InboxItem[]>(inboxKey, [+ makeInboxItem("inbox-1", "issue-1"),+ makeInboxItem("inbox-2", "issue-2"),+ ]);});afterEach(() => {@@ -380,7 +461,7 @@ describe("useUpdateIssue — optimistic move keeps every bucketed board in sync"});// Optimistic state — the regression: myList must move too, not just ws.- for (const key of [wsKey, myKey]) {+ for (const key of [wsKey, myKey, projectKey]) {expect(bucketIds(key, "todo")).toEqual([]);expect(bucketIds(key, "in_progress")).toEqual(["issue-1"]);}@@ -390,11 +471,38 @@ describe("useUpdateIssue — optimistic move keeps every bucketed board in sync"});// Authoritative settle keeps the card in place in both caches.- for (const key of [wsKey, myKey]) {+ for (const key of [wsKey, myKey, projectKey]) {expect(bucketIds(key, "in_progress")).toEqual(["issue-1"]);}});+ it("optimistically patches the linked inbox row status and reconciles with the server response", async () => {+ let resolve!: (issue: Issue) => void;+ updateIssue.mockReturnValue(+ new Promise<Issue>((r) => {+ resolve = r;+ }),+ );++ const { result } = renderHook(() => useUpdateIssue(), {+ wrapper: createWrapper(qc),+ });++ act(() => {+ result.current.mutate({ id: "issue-1", status: "in_progress" });+ });++ expect(inboxStatus("issue-1")).toBe("in_progress");+ expect(inboxStatus("issue-2")).toBe("todo");++ await act(async () => {+ resolve(makeIssue(1, { status: "done" }));+ });++ expect(inboxStatus("issue-1")).toBe("done");+ expect(inboxStatus("issue-2")).toBe("todo");+ });+it("rolls both caches back when the request fails", async () => {updateIssue.mockRejectedValue(new Error("boom"));@@ -408,12 +516,29 @@ describe("useUpdateIssue — optimistic move keeps every bucketed board in sync".catch(() => {});});- for (const key of [wsKey, myKey]) {+ for (const key of [wsKey, myKey, projectKey]) {expect(bucketIds(key, "todo")).toEqual(["issue-1"]);expect(bucketIds(key, "in_progress")).toEqual([]);}});+ it("rolls the linked inbox row status back when the request fails", async () => {+ updateIssue.mockRejectedValue(new Error("boom"));++ const { result } = renderHook(() => useUpdateIssue(), {+ wrapper: createWrapper(qc),+ });++ await act(async () => {+ await result.current+ .mutateAsync({ id: "issue-1", status: "in_progress" })+ .catch(() => {});+ });++ expect(inboxStatus("issue-1")).toBe("todo");+ expect(inboxStatus("issue-2")).toBe("todo");+ });+it("does not invalidate the board list on settle (no refetch flicker)", async () => {updateIssue.mockResolvedValue(makeIssue(1, { status: "in_progress", position: 5 }));const invalidateSpy = vi.spyOn(qc, "invalidateQueries");@@ -432,24 +557,57 @@ describe("useUpdateIssue — optimistic move keeps every bucketed board in sync"expect(invalidatedKeys).not.toContainEqual(issueKeys.myAll(WS_ID));});- it("invalidates myAll on settle when project_id changes (drops the issue from the old project's list)", async () => {- // A project move makes the issue leave the old project's filtered list. The- // surgical patch is filter-blind (it never removes a card that no longer- // matches the list filter), so onSettled must refetch myAll to drop it —- // unlike a status-only move, which deliberately does not (MUL-3669 / #4548).- updateIssue.mockResolvedValue(makeIssue(1, { project_id: "project-9" }));+ it("surgically removes the issue from the old project's list on a project move (no blanket myAll refetch)", async () => {+ // A project move makes the issue leave the old project's filtered list.+ // The membership-aware coordinator removes the card from that loaded list+ // in onMutate — deterministic, no WS echo or refetch needed — replacing+ // the old blanket "invalidate myAll on settle" safety net (MUL-3669 /+ // #4548). Lists whose filter the move cannot affect stay untouched.+ let resolve!: (issue: Issue) => void;+ updateIssue.mockReturnValue(+ new Promise<Issue>((r) => {+ resolve = r;+ }),+ );const invalidateSpy = vi.spyOn(qc, "invalidateQueries");const { result } = renderHook(() => useUpdateIssue(), {wrapper: createWrapper(qc),});+ act(() => {+ result.current.mutate({ id: "issue-1", project_id: "project-9" });+ });++ // Optimistic: gone from the old project's list immediately; the+ // workspace board and the assignee-filtered list keep the card.+ expect(bucketIds(projectKey, "todo")).toEqual([]);+ expect(bucketIds(wsKey, "todo")).toEqual(["issue-1"]);+ expect(bucketIds(myKey, "todo")).toEqual(["issue-1"]);+await act(async () => {- await result.current.mutateAsync({ id: "issue-1", project_id: "project-9" });+ resolve(makeIssue(1, { project_id: "project-9" }));});+ expect(bucketIds(projectKey, "todo")).toEqual([]);const invalidatedKeys = invalidateSpy.mock.calls.map((c) => c[0]?.queryKey);- expect(invalidatedKeys).toContainEqual(issueKeys.myAll(WS_ID));+ expect(invalidatedKeys).not.toContainEqual(issueKeys.myAll(WS_ID));+ });++ it("rolls the membership removal back when a project move fails", async () => {+ updateIssue.mockRejectedValue(new Error("boom"));++ const { result } = renderHook(() => useUpdateIssue(), {+ wrapper: createWrapper(qc),+ });++ await act(async () => {+ await result.current+ .mutateAsync({ id: "issue-1", project_id: "project-9" })+ .catch(() => {});+ });++ expect(bucketIds(projectKey, "todo")).toEqual(["issue-1"]);});});@@ -653,10 +811,14 @@ describe("useBatchUpdateIssues — optimistic patch covers filtered boards too",expect(invalidatedKeys).not.toContainEqual(issueKeys.list(WS_ID));});- it("invalidates myAll on settle when project_id changes (drops moved issues from the old project's list)", async () => {- // Mirrors useUpdateIssue: a batch that moves issues between projects must- // refetch myAll so they leave the old project's filtered list, even though a- // status-only batch deliberately does not (MUL-3669 / #4548).+ it("surgically removes moved issues from the old project's list (no blanket myAll refetch)", async () => {+ // Mirrors useUpdateIssue: a batch project move drops the cards from the+ // old project's loaded list via the membership-aware coordinator instead+ // of refetching every filtered list (MUL-3669 / #4548).+ const projectScope = "project:p1";+ const projectFilter = { project_id: "p1" };+ const projectKey = issueKeys.myListSorted(WS_ID, projectScope, projectFilter, sort);+ qc.setQueryData<ListIssuesCache>(projectKey, makeBucketed());batchUpdateIssues.mockResolvedValue({ updated: 1 });const invalidateSpy = vi.spyOn(qc, "invalidateQueries");@@ -671,8 +833,11 @@ describe("useBatchUpdateIssues — optimistic patch covers filtered boards too",});});+ expect(bucketIds(projectKey, "todo")).toEqual([]);+ // The assignee-filtered list is untouched by a project move.+ expect(bucketIds(myKey, "todo")).toEqual(["issue-1"]);const invalidatedKeys = invalidateSpy.mock.calls.map((c) => c[0]?.queryKey);- expect(invalidatedKeys).toContainEqual(issueKeys.myAll(WS_ID));+ expect(invalidatedKeys).not.toContainEqual(issueKeys.myAll(WS_ID));});});diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.tsindex ed008f697b..361b4ce657 100644--- a/packages/core/issues/mutations.ts+++ b/packages/core/issues/mutations.ts@@ -1,5 +1,5 @@import { useState, useCallback } from "react";-import { useMutation, useQueryClient, type QueryKey } from "@tanstack/react-query";+import { hashKey, useMutation, useQueryClient, type QueryKey } from "@tanstack/react-query";import { api } from "../api";import {issueKeys,@@ -9,11 +9,17 @@ import {type MyIssuesFilter,} from "./queries";import { projectKeys } from "../projects/queries";+import { inboxKeys } from "../inbox/queries";+import {+ applyIssueChange,+ invalidateIssueDerivatives,+ invalidateStaleListKeys,+ rollbackIssueChange,+} from "./cache-coordinator";+import { issueChangedDims } from "./surface/membership";import {addIssueToBuckets,- findIssueLocation,getBucket,- patchIssueInBuckets,setBucket,} from "./cache-helpers";import {@@ -28,7 +34,7 @@ import {import { useWorkspaceId } from "../hooks";import { useRecentContextStore } from "../chat/recent-context-store";import { useRecentIssuesStore } from "./stores";-import type { GroupedIssuesResponse, Issue, IssueAssigneeGroup, IssueReaction, IssueStatus } from "../types";+import type { GroupedIssuesResponse, InboxItem, Issue, IssueAssigneeGroup, IssueReaction, IssueStatus } from "../types";import type {CreateIssueRequest,UpdateIssueRequest,@@ -211,21 +217,6 @@ export function useCreateIssue() {export function useUpdateIssue() {const qc = useQueryClient();const wsId = useWorkspaceId();- // Every bucketed board cache an optimistic move must keep in sync: the- // workspace board (issueKeys.list*) AND the My-Issues / Project board- // (issueKeys.myList* under `my`), which share the ListIssuesCache shape.- // Filtering by `byStatus` skips the grouped (assignee) and flat- // (gantt/detail/children) caches that also live under those prefixes. The- // board reconciles local columns from its own feeding cache on settle, so a- // move that only patched the workspace cache would snap back on My-Issues /- // Project boards.- const readBucketedLists = () =>- [- ...qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) }),- ...qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.myAll(wsId) }),- ].filter(- (entry): entry is [QueryKey, ListIssuesCache] => !!entry[1]?.byStatus,- );return useMutation({mutationFn: ({ id, ...data }: { id: string } & UpdateIssueRequest) =>api.updateIssue(id, data),@@ -241,9 +232,19 @@ export function useUpdateIssue() {// before the optimistic update lands.qc.cancelQueries({ queryKey: issueKeys.list(wsId) });qc.cancelQueries({ queryKey: issueKeys.myAll(wsId) });- const prevLists = readBucketedLists();- const firstListData = prevLists[0]?.[1];+ if (patch.status !== undefined) {+ qc.cancelQueries({ queryKey: inboxKeys.list(wsId) });+ }const prevDetail = qc.getQueryData<Issue>(issueKeys.detail(wsId, id));+ // The coordinator owns the cross-cache rules: surgical patch/rebucket+ // where the card is loaded and still belongs, surgical REMOVE where the+ // change moves it off a filtered surface, stale-key bookkeeping where+ // the server result may have drifted (invalidated on settle, not here —+ // a mid-flight refetch would stomp the optimistic state).+ const change = applyIssueChange(qc, wsId, id, patch as Partial<Issue>, {+ changed: issueChangedDims(patch, prevDetail),+ baseIssue: prevDetail,+ });// Resolve parent_issue_id from the freshest source so we can keep the// parent's children cache in sync (used by the parent issue's@@ -252,7 +253,7 @@ export function useUpdateIssue() {// child may live only there, not in detail/list.let parentId: string | null =prevDetail?.parent_issue_id ??- (firstListData ? findIssueLocation(firstListData, id)?.issue.parent_issue_id : null) ??+ change.prevIssue?.parent_issue_id ??null;if (!parentId) {const childrenCaches = qc.getQueriesData<Issue[]>({@@ -271,12 +272,6 @@ export function useUpdateIssue() {? qc.getQueryData<Issue[]>(issueKeys.children(wsId, parentId)): undefined;- for (const [key, cached] of prevLists) {- if (cached) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(cached, id, patch));- }- qc.setQueryData<Issue>(issueKeys.detail(wsId, id), (old) =>- old ? { ...old, ...patch } : old,- );if (parentId) {// When the write re-parents this issue away from `parentId` (detach// to standalone, or move under a different parent), prune it from the@@ -295,16 +290,12 @@ export function useUpdateIssue() {: old?.map((c) => (c.id === id ? { ...c, ...patch } : c)),);}- return { prevLists, prevDetail, prevChildren, parentId, id };+ return { change, prevChildren, parentId, id };},onError: (_err, _vars, ctx) => {- if (ctx?.prevLists) {- for (const [key, snapshot] of ctx.prevLists) {- qc.setQueryData(key, snapshot);- }+ if (ctx) {+ rollbackIssueChange(qc, wsId, ctx.id, ctx.change);}- if (ctx?.prevDetail)- qc.setQueryData(issueKeys.detail(wsId, ctx.id), ctx.prevDetail);if (ctx?.parentId && ctx.prevChildren !== undefined) {qc.setQueryData(issueKeys.children(wsId, ctx.parentId),@@ -312,7 +303,7 @@ export function useUpdateIssue() {);}},- onSuccess: (serverIssue) => {+ onSuccess: (serverIssue, vars) => {// Reconcile with the authoritative server entity by patching the one card// in place — NOT by invalidating + refetching the list. The list refetch// is what made a successful move flicker: the optimistic card was already@@ -320,38 +311,37 @@ export function useUpdateIssue() {// card re-landed. updateIssue returns the full issue and a position update// touches only that row, so a surgical patch is the authoritative// reconcile and is a visual no-op when the optimistic value matched.- for (const [key, cached] of readBucketedLists()) {- qc.setQueryData<ListIssuesCache>(- key,- patchIssueInBuckets(cached, serverIssue.id, serverIssue),- );- }- qc.setQueryData<Issue>(issueKeys.detail(wsId, serverIssue.id), (old) =>- old ? { ...old, ...serverIssue } : old,- );+ //+ // baseIssue = serverIssue: membership moves were already handled+ // 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 reconcile = applyIssueChange(qc, wsId, serverIssue.id, serverIssue, {+ changed: issueChangedDims(intent, serverIssue),+ baseIssue: serverIssue,+ });+ // The server has committed — safe to flush any drift it reported now.+ invalidateStaleListKeys(qc, reconcile.staleKeys);},onSettled: (_data, _err, vars, ctx) => {// The issue's own list + detail caches are reconciled surgically in// onSuccess / onError, so they are deliberately NOT invalidated here — a// full-list refetch on settle is what made drags flicker. Only aggregate- // caches that cannot be patched from a single issue are refreshed below.- qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });- qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });- qc.invalidateQueries({ queryKey: issueKeys.projectGanttAll(wsId) });- if (- vars.status !== undefined ||- Object.prototype.hasOwnProperty.call(vars, "project_id")- ) {- qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });- }- // Local safety net for a project move. The WS echo now carries- // project_changed, but a moved issue must also drop out of the OLD- // project's filtered list here in case the echo is delayed or dropped. The- // surgical onMutate patch is filter-blind — it never removes a card that no- // longer matches the list's project filter — so reconcile by refetching- // myAll whenever project_id was part of this update (MUL-3669 / #4548).- if (Object.prototype.hasOwnProperty.call(vars, "project_id")) {- qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });+ // caches that cannot be patched from a single issue are refreshed, plus+ // the specific list keys the coordinator flagged as drifted (unknown+ // membership, enter/leave beyond the loaded window, bucket-count drift).+ // Those stale keys are the surgical replacement for the old blanket+ // "invalidate myAll on project move" safety net (MUL-3669 / #4548): the+ // old project's loaded list already had the card removed in onMutate,+ // and only genuinely undecidable lists refetch here.+ invalidateIssueDerivatives(qc, wsId, {+ statusOrProjectChanged:+ vars.status !== undefined ||+ Object.prototype.hasOwnProperty.call(vars, "project_id"),+ });+ if (ctx) {+ invalidateStaleListKeys(qc, ctx.change.staleKeys);}// Refresh the issue's attachments cache when the description editor// bound new uploads — the description editor reads `issueAttachments`@@ -469,28 +459,40 @@ export function useBatchUpdateIssues() {updates: UpdateIssueRequest;}) => api.batchUpdateIssues(ids, updates),onMutate: async ({ ids, updates }) => {- // Patch BOTH the workspace board (issueKeys.list) and the filtered- // My-Issues / Project / actor lists (issueKeys.myAll). The single-issue- // update already patches both; batch only touched issueKeys.list, so a- // batch edit on a My-Issues board had no optimistic effect and relied- // entirely on the settle refetch. Filter to bucketed (byStatus) caches so- // grouped/flat caches under the same prefix are skipped.- //// Control fields steer the server; they are not Issue columns and must// not enter the cache (MUL-3375). mutationFn still sends them.const { suppress_run: _suppressRun, handoff_note: _handoffNote, ...patch } = updates;await qc.cancelQueries({ queryKey: issueKeys.list(wsId) });await qc.cancelQueries({ queryKey: issueKeys.myAll(wsId) });- const prevLists = [- ...qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) }),- ...qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.myAll(wsId) }),- ].filter(- (entry): entry is [QueryKey, ListIssuesCache] => !!entry[1]?.byStatus,- );- for (const [key, cached] of prevLists) {- let next = cached;- for (const id of ids) next = patchIssueInBuckets(next, id, patch);- qc.setQueryData<ListIssuesCache>(key, next);+ if (patch.status !== undefined) {+ await qc.cancelQueries({ queryKey: inboxKeys.list(wsId) });+ }++ // Run every issue through the coordinator — the same rules table the+ // single-issue update uses, so a batch edit patches/removes across the+ // workspace board AND every filtered myList surface identically.+ // Snapshots are first-wins per cache key: after the first issue's+ // application a cache already carries partial patches, so only the+ // first snapshot per key is pristine for rollback.+ const prevListByHash = new Map<string, [QueryKey, ListIssuesCache]>();+ const prevDetailById = new Map<string, Issue>();+ let prevInboxList: InboxItem[] | undefined;+ const staleKeys: QueryKey[] = [];+ for (const id of ids) {+ const base = qc.getQueryData<Issue>(issueKeys.detail(wsId, id));+ const change = applyIssueChange(qc, wsId, id, patch as Partial<Issue>, {+ changed: issueChangedDims(patch, base),+ baseIssue: base,+ });+ for (const [key, snapshot] of change.prevLists) {+ const hash = hashKey(key);+ if (!prevListByHash.has(hash)) prevListByHash.set(hash, [key, snapshot]);+ }+ if (change.prevDetail) prevDetailById.set(id, change.prevDetail);+ if (prevInboxList === undefined && change.prevInboxList !== undefined) {+ prevInboxList = change.prevInboxList;+ }+ staleKeys.push(...change.staleKeys);}// Mirror the optimistic patch into any loaded children cache so@@ -512,7 +514,14 @@ export function useBatchUpdateIssues() {);}- return { prevLists, prevChildren, affectedParentIds };+ return {+ prevLists: [...prevListByHash.values()],+ prevDetailById,+ prevInboxList,+ staleKeys,+ prevChildren,+ affectedParentIds,+ };},onError: (_err, _vars, ctx) => {if (ctx?.prevLists) {@@ -520,6 +529,14 @@ export function useBatchUpdateIssues() {qc.setQueryData(key, snapshot);}}+ if (ctx?.prevDetailById) {+ for (const [id, snapshot] of ctx.prevDetailById) {+ qc.setQueryData(issueKeys.detail(wsId, id), snapshot);+ }+ }+ if (ctx?.prevInboxList !== undefined) {+ qc.setQueryData(inboxKeys.list(wsId), ctx.prevInboxList);+ }if (ctx?.prevChildren) {for (const [parentId, snapshot] of ctx.prevChildren) {qc.setQueryData(issueKeys.children(wsId, parentId), snapshot);@@ -528,25 +545,20 @@ export function useBatchUpdateIssues() {},onSettled: (_data, _err, _vars, ctx) => {// Deliberately NOT invalidating issueKeys.list / myAll here: the onMutate- // patch above is a complete surgical reconcile for these bucketed boards- // (batch changes status / priority / project — never a server-computed- // value), so a full-board refetch on settle would only re-introduce the+ // pass above is a complete surgical reconcile for the loaded bucketed+ // boards, so a full-board refetch on settle would only re-introduce the// flicker the single-issue update already removed. Aggregate / grouped- // caches that cannot be recomputed from a single-issue patch are still- // refreshed below.- qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });- qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });- qc.invalidateQueries({ queryKey: issueKeys.projectGanttAll(wsId) });- if (- _vars.updates.status !== undefined ||- Object.prototype.hasOwnProperty.call(_vars.updates, "project_id")- ) {- qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });- }- // Local safety net mirroring useUpdateIssue: drop moved issues from the old- // project's filtered list even if the WS echo is delayed (MUL-3669 / #4548).- if (Object.prototype.hasOwnProperty.call(_vars.updates, "project_id")) {- qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });+ // caches that cannot be recomputed from a single-issue patch are+ // refreshed below, plus the specific keys the coordinator flagged as+ // drifted — the surgical replacement for the old blanket "invalidate+ // myAll on project move" safety net (MUL-3669 / #4548).+ invalidateIssueDerivatives(qc, wsId, {+ statusOrProjectChanged:+ _vars.updates.status !== undefined ||+ Object.prototype.hasOwnProperty.call(_vars.updates, "project_id"),+ });+ if (ctx) {+ invalidateStaleListKeys(qc, ctx.staleKeys);}if (ctx?.affectedParentIds && ctx.affectedParentIds.size > 0) {for (const parentId of ctx.affectedParentIds) {diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex ee1c3bb827..a4123beb96 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -115,7 +115,12 @@ export const issueKeys = {export type MyIssuesFilter = Pick<ListIssuesParams,- "assignee_id" | "assignee_ids" | "creator_id" | "project_id" | "involves_user_id"+ | "assignee_id"+ | "assignee_ids"+ | "assignee_types"+ | "creator_id"+ | "project_id"+ | "involves_user_id">;export type AssigneeGroupedIssuesFilter = Omit<diff --git a/packages/core/issues/stores/index.ts b/packages/core/issues/stores/index.tsindex d5410454c2..27a7306050 100644--- a/packages/core/issues/stores/index.ts+++ b/packages/core/issues/stores/index.ts@@ -43,3 +43,10 @@ export {type ActorFilterValue,type IssueViewState,} from "./view-store";+export {+ ISSUE_SURFACE_VIEW_STORAGE_KEY,+ getIssueSurfaceViewStore,+ clearIssueSurfaceViewState,+ pruneIssueSurfaceViewStates,+ getIssueSurfaceViewStateRegistrySnapshot,+} from "./surface-view-store";diff --git a/packages/core/issues/stores/surface-view-store.test.tsx b/packages/core/issues/stores/surface-view-store.test.tsxnew file mode 100644index 0000000000..8a0379283a--- /dev/null+++ b/packages/core/issues/stores/surface-view-store.test.tsx@@ -0,0 +1,168 @@+// @vitest-environment jsdom+import { beforeAll, beforeEach, afterEach, describe, expect, it } from "vitest";+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { setCurrentWorkspace } from "../../platform/workspace-storage";+import { ViewStoreProvider, useViewStore } from "./view-store-context";+import {+ ISSUE_SURFACE_VIEW_STORAGE_KEY,+ clearIssueSurfaceViewState,+ getIssueSurfaceViewStateRegistrySnapshot,+ getIssueSurfaceViewStore,+ pruneIssueSurfaceViewStates,+} from "./surface-view-store";++const flush = async () => {+ await new Promise((resolve) => queueMicrotask(() => resolve(null)));+ await new Promise((resolve) => queueMicrotask(() => resolve(null)));+};++beforeAll(() => {+ if (typeof globalThis.localStorage?.clear !== "function") {+ const values = new Map<string, string>();+ const storage: Storage = {+ get length() {+ return values.size;+ },+ clear: () => values.clear(),+ getItem: (key) => values.get(key) ?? null,+ key: (index) => Array.from(values.keys())[index] ?? null,+ removeItem: (key) => {+ values.delete(key);+ },+ setItem: (key, value) => {+ values.set(key, value);+ },+ };+ Object.defineProperty(globalThis, "localStorage", {+ configurable: true,+ value: storage,+ });+ Object.defineProperty(window, "localStorage", {+ configurable: true,+ value: storage,+ });+ }+});++beforeEach(async () => {+ localStorage.clear();+ pruneIssueSurfaceViewStates([]);+ setCurrentWorkspace(null, null);+ await flush();+});++afterEach(async () => {+ cleanup();+ pruneIssueSurfaceViewStates([]);+ setCurrentWorkspace(null, null);+ await flush();+});++describe("issue surface view store registry", () => {+ it("isolates view state by surface key inside one workspace registry", async () => {+ setCurrentWorkspace("acme", "ws_a");+ await flush();+ const projectA = getIssueSurfaceViewStore("project:a");+ const projectB = getIssueSurfaceViewStore("project:b");++ projectA.getState().setViewMode("list");+ projectA.getState().togglePriorityFilter("high");++ expect(projectA.getState().viewMode).toBe("list");+ expect(projectB.getState().viewMode).toBe("board");+ expect(projectB.getState().priorityFilters).toEqual([]);++ const raw = localStorage.getItem(`${ISSUE_SURFACE_VIEW_STORAGE_KEY}:acme`);+ expect(raw).not.toBeNull();+ const parsed = JSON.parse(raw as string);+ expect(parsed.state.surfaces["project:a"].state.viewMode).toBe("list");+ expect(parsed.state.surfaces["project:a"].state.priorityFilters).toEqual([+ "high",+ ]);+ expect(parsed.state.surfaces["project:b"]).toBeUndefined();+ });++ it("rehydrates existing surface stores when the workspace changes", async () => {+ setCurrentWorkspace("acme", "ws_a");+ await flush();+ const projectA = getIssueSurfaceViewStore("project:a");+ projectA.getState().setViewMode("list");++ setCurrentWorkspace("beta", "ws_b");+ await flush();+ expect(projectA.getState().viewMode).toBe("board");+ projectA.getState().setViewMode("swimlane");++ setCurrentWorkspace("acme", "ws_a");+ await flush();+ expect(projectA.getState().viewMode).toBe("list");++ setCurrentWorkspace("beta", "ws_b");+ await flush();+ expect(projectA.getState().viewMode).toBe("swimlane");+ });++ it("clears one surface without touching sibling surfaces", async () => {+ setCurrentWorkspace("acme", "ws_a");+ await flush();+ const projectA = getIssueSurfaceViewStore("project:a");+ const projectB = getIssueSurfaceViewStore("project:b");+ projectA.getState().setViewMode("list");+ projectB.getState().setViewMode("gantt");++ clearIssueSurfaceViewState("project:a");++ expect(projectA.getState().viewMode).toBe("board");+ expect(projectB.getState().viewMode).toBe("gantt");+ expect(getIssueSurfaceViewStateRegistrySnapshot()["project:a"]).toBeUndefined();+ expect(getIssueSurfaceViewStateRegistrySnapshot()["project:b"]?.state.viewMode).toBe(+ "gantt",+ );+ });++ it("prunes invalid surfaces and resets live stores for pruned keys", async () => {+ setCurrentWorkspace("acme", "ws_a");+ await flush();+ const projectA = getIssueSurfaceViewStore("project:a");+ const projectB = getIssueSurfaceViewStore("project:b");+ projectA.getState().setViewMode("list");+ projectB.getState().setViewMode("gantt");++ pruneIssueSurfaceViewStates(["project:a"]);++ expect(projectA.getState().viewMode).toBe("list");+ expect(projectB.getState().viewMode).toBe("board");+ expect(getIssueSurfaceViewStateRegistrySnapshot()["project:a"]?.state.viewMode).toBe(+ "list",+ );+ expect(getIssueSurfaceViewStateRegistrySnapshot()["project:b"]).toBeUndefined();+ });++ it("works as a real StoreApi with ViewStoreProvider subscriptions", async () => {+ setCurrentWorkspace("acme", "ws_a");+ await flush();+ const store = getIssueSurfaceViewStore("project:provider");++ function Probe() {+ const viewMode = useViewStore((state) => state.viewMode);+ const setViewMode = useViewStore((state) => state.setViewMode);+ return (+ <button type="button" onClick={() => setViewMode("list")}>+ {viewMode}+ </button>+ );+ }++ render(+ <ViewStoreProvider store={store}>+ <Probe />+ </ViewStoreProvider>,+ );++ expect(screen.getByRole("button", { name: "board" })).toBeTruthy();+ act(() => {+ fireEvent.click(screen.getByRole("button", { name: "board" }));+ });+ expect(screen.getByRole("button", { name: "list" })).toBeTruthy();+ });+});diff --git a/packages/core/issues/stores/surface-view-store.ts b/packages/core/issues/stores/surface-view-store.tsnew file mode 100644index 0000000000..dcd1ff20f4--- /dev/null+++ b/packages/core/issues/stores/surface-view-store.ts@@ -0,0 +1,143 @@+"use client";++import { createStore, type StoreApi } from "zustand/vanilla";+import { createJSONStorage, persist } from "zustand/middleware";+import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";+import { defaultStorage } from "../../platform/storage";+import {+ type IssueViewState,+ mergeViewStatePersisted,+ viewStorePersistOptions,+ viewStoreSlice,+} from "./view-store";++export const ISSUE_SURFACE_VIEW_STORAGE_KEY = "multica_issue_surface_views";++type PersistedIssueViewState = ReturnType<+ ReturnType<typeof viewStorePersistOptions>["partialize"]+>;++interface IssueSurfaceViewEntry {+ state: PersistedIssueViewState;+ updatedAt: string;+}++interface IssueSurfaceViewRegistryState {+ surfaces: Record<string, IssueSurfaceViewEntry>;+ setSurfaceState: (surfaceKey: string, state: IssueViewState) => void;+ clearSurfaceState: (surfaceKey: string) => void;+ pruneSurfaceStates: (validSurfaceKeys: Iterable<string>) => void;+}++const basePersist = viewStorePersistOptions(ISSUE_SURFACE_VIEW_STORAGE_KEY);+const surfaceStores = new Map<string, StoreApi<IssueViewState>>();+const suppressSurfacePersist = new Set<string>();++function persistedIssueViewState(state: IssueViewState): PersistedIssueViewState {+ return basePersist.partialize(state);+}++const issueSurfaceViewRegistryStore = createStore<IssueSurfaceViewRegistryState>()(+ persist(+ (set) => ({+ surfaces: {},+ setSurfaceState: (surfaceKey, state) =>+ set((current) => ({+ surfaces: {+ ...current.surfaces,+ [surfaceKey]: {+ state: persistedIssueViewState(state),+ updatedAt: new Date().toISOString(),+ },+ },+ })),+ clearSurfaceState: (surfaceKey) =>+ set((current) => {+ if (!current.surfaces[surfaceKey]) return current;+ const { [surfaceKey]: _removed, ...surfaces } = current.surfaces;+ return { surfaces };+ }),+ pruneSurfaceStates: (validSurfaceKeys) =>+ set((current) => {+ const valid = new Set(validSurfaceKeys);+ const surfaces = Object.fromEntries(+ Object.entries(current.surfaces).filter(([key]) => valid.has(key)),+ );+ if (Object.keys(surfaces).length === Object.keys(current.surfaces).length) {+ return current;+ }+ return { surfaces };+ }),+ }),+ {+ name: ISSUE_SURFACE_VIEW_STORAGE_KEY,+ storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),+ partialize: (state) => ({ surfaces: state.surfaces }),+ merge: (persisted, current) => {+ const p = (persisted ?? {}) as Partial<IssueSurfaceViewRegistryState>;+ return {+ ...current,+ surfaces: p.surfaces ?? {},+ };+ },+ },+ ),+);++function resetStoreFromRegistry(surfaceKey: string, store: StoreApi<IssueViewState>) {+ const persisted =+ issueSurfaceViewRegistryStore.getState().surfaces[surfaceKey]?.state;+ const defaults = viewStoreSlice(store.setState);+ suppressSurfacePersist.add(surfaceKey);+ try {+ store.setState(mergeViewStatePersisted(persisted, defaults), true);+ } finally {+ suppressSurfacePersist.delete(surfaceKey);+ }+}++function resetAllSurfaceStoresFromRegistry() {+ for (const [surfaceKey, store] of surfaceStores) {+ resetStoreFromRegistry(surfaceKey, store);+ }+}++registerForWorkspaceRehydration(() => {+ void Promise.resolve(issueSurfaceViewRegistryStore.persist.rehydrate()).then(+ resetAllSurfaceStoresFromRegistry,+ );+});++export function getIssueSurfaceViewStore(+ surfaceKey: string,+): StoreApi<IssueViewState> {+ const existing = surfaceStores.get(surfaceKey);+ if (existing) return existing;++ const store = createStore<IssueViewState>()((set) => viewStoreSlice(set));+ resetStoreFromRegistry(surfaceKey, store);+ store.subscribe((state) => {+ if (suppressSurfacePersist.has(surfaceKey)) return;+ issueSurfaceViewRegistryStore.getState().setSurfaceState(surfaceKey, state);+ });+ surfaceStores.set(surfaceKey, store);+ return store;+}++export function clearIssueSurfaceViewState(surfaceKey: string) {+ issueSurfaceViewRegistryStore.getState().clearSurfaceState(surfaceKey);+ const store = surfaceStores.get(surfaceKey);+ if (store) resetStoreFromRegistry(surfaceKey, store);+}++export function pruneIssueSurfaceViewStates(validSurfaceKeys: Iterable<string>) {+ const valid = new Set(validSurfaceKeys);+ issueSurfaceViewRegistryStore.getState().pruneSurfaceStates(valid);+ for (const [surfaceKey, store] of surfaceStores) {+ if (!valid.has(surfaceKey)) resetStoreFromRegistry(surfaceKey, store);+ }+}++export function getIssueSurfaceViewStateRegistrySnapshot() {+ return issueSurfaceViewRegistryStore.getState().surfaces;+}diff --git a/packages/core/issues/surface/membership.test.ts b/packages/core/issues/surface/membership.test.tsnew file mode 100644index 0000000000..e707475798--- /dev/null+++ b/packages/core/issues/surface/membership.test.ts@@ -0,0 +1,193 @@+import { describe, expect, it } from "vitest";+import type { Issue } from "../../types";+import {+ issueChangedDims,+ issueMatchesListFilter,+ listFilterDependsOn,+} from "./membership";++function makeIssue(overrides: Partial<Issue> = {}): Issue {+ return {+ id: "issue-1",+ workspace_id: "ws-1",+ number: 1,+ identifier: "MUL-1",+ title: "Issue 1",+ description: null,+ status: "todo",+ priority: "none",+ assignee_type: "member",+ assignee_id: "me",+ creator_type: "member",+ creator_id: "me",+ parent_issue_id: null,+ project_id: "p1",+ position: 1,+ stage: null,+ start_date: null,+ due_date: null,+ labels: [],+ metadata: {},+ created_at: "2025-01-01T00:00:00Z",+ updated_at: "2025-01-01T00:00:00Z",+ ...overrides,+ };+}++describe("issueMatchesListFilter", () => {+ it("judges assignee_id filters definitively", () => {+ const issue = makeIssue();+ expect(issueMatchesListFilter(issue, "assigned", { assignee_id: "me" })).toBe(true);+ expect(issueMatchesListFilter(issue, "assigned", { assignee_id: "bob" })).toBe(false);+ });++ it("degrades to unknown when the entity is missing the filtered field", () => {+ expect(+ issueMatchesListFilter({ title: "partial" }, "assigned", { assignee_id: "me" }),+ ).toBe("unknown");+ });++ it("judges assignee_types filters, treating unassigned as a definitive miss", () => {+ expect(+ issueMatchesListFilter(makeIssue(), "workspace:members", {+ assignee_types: ["member"],+ }),+ ).toBe(true);+ expect(+ issueMatchesListFilter(makeIssue({ assignee_type: "agent" }), "workspace:members", {+ assignee_types: ["member"],+ }),+ ).toBe(false);+ expect(+ issueMatchesListFilter(+ makeIssue({ assignee_type: null, assignee_id: null }),+ "workspace:agents",+ { assignee_types: ["agent", "squad"] },+ ),+ ).toBe(false);+ });++ it("judges project filters", () => {+ expect(+ issueMatchesListFilter(makeIssue(), "project:p1", { project_id: "p1" }),+ ).toBe(true);+ expect(+ issueMatchesListFilter(makeIssue({ project_id: "p2" }), "project:p1", {+ project_id: "p1",+ }),+ ).toBe(false);+ expect(+ issueMatchesListFilter(makeIssue({ project_id: null }), "project:p1", {+ project_id: "p1",+ }),+ ).toBe(false);+ });++ it("never decides involves_user_id — the ownership graph is server-side", () => {+ expect(+ issueMatchesListFilter(makeIssue(), "agents", { involves_user_id: "me" }),+ ).toBe("unknown");+ });++ it("never decides the my:all union scope", () => {+ expect(issueMatchesListFilter(makeIssue(), "all", {})).toBe("unknown");+ });++ it("ANDs across fields — a definitive miss beats an unknown", () => {+ expect(+ issueMatchesListFilter(+ makeIssue({ project_id: "p2" }),+ "scoped",+ { project_id: "p1", involves_user_id: "me" },+ ),+ ).toBe(false);+ });+});++describe("issueChangedDims", () => {+ it("treats written membership fields as changed when no base is known", () => {+ expect(issueChangedDims({ assignee_id: "bob", assignee_type: "member" })).toEqual({+ assignee: true,+ project: false,+ status: false,+ });+ expect(issueChangedDims({ project_id: null })).toEqual({+ assignee: false,+ project: true,+ status: false,+ });+ });++ it("sharpens against a base entity — writing the same value changes nothing", () => {+ const base = makeIssue();+ expect(issueChangedDims({ assignee_id: "me", assignee_type: "member" }, base)).toEqual({+ assignee: false,+ project: false,+ status: false,+ });+ expect(issueChangedDims({ status: "todo" }, base).status).toBe(false);+ expect(issueChangedDims({ status: "done" }, base).status).toBe(true);+ expect(issueChangedDims({ project_id: "p2" }, base).project).toBe(true);+ });++ it("ignores non-membership fields", () => {+ expect(issueChangedDims({ title: "x", position: 9 })).toEqual({+ assignee: false,+ project: false,+ status: false,+ });+ });+});++describe("listFilterDependsOn", () => {+ const none = { assignee: false, project: false, status: false };++ it("my:all reacts to assignee changes only", () => {+ expect(listFilterDependsOn("all", {}, { ...none, assignee: true })).toBe(true);+ expect(listFilterDependsOn("all", {}, { ...none, project: true })).toBe(false);+ });++ it("assignee-keyed filters react to assignee changes", () => {+ expect(+ listFilterDependsOn("assigned", { assignee_id: "me" }, { ...none, assignee: true }),+ ).toBe(true);+ expect(+ listFilterDependsOn(+ "workspace:members",+ { assignee_types: ["member"] },+ { ...none, assignee: true },+ ),+ ).toBe(true);+ expect(+ listFilterDependsOn("agents", { involves_user_id: "me" }, { ...none, assignee: true }),+ ).toBe(true);+ expect(+ listFilterDependsOn("assigned", { assignee_id: "me" }, { ...none, project: true }),+ ).toBe(false);+ });++ it("project filters react to project changes", () => {+ expect(+ listFilterDependsOn("project:p1", { project_id: "p1" }, { ...none, project: true }),+ ).toBe(true);+ expect(+ listFilterDependsOn("project:p1", { project_id: "p1" }, { ...none, assignee: true }),+ ).toBe(false);+ });++ it("creator filters never react — creator is immutable", () => {+ expect(+ listFilterDependsOn(+ "created",+ { creator_id: "me" },+ { assignee: true, project: true, status: true },+ ),+ ).toBe(false);+ });++ it("the unfiltered workspace list never reacts", () => {+ expect(+ listFilterDependsOn(undefined, {}, { assignee: true, project: true, status: true }),+ ).toBe(false);+ });+});diff --git a/packages/core/issues/surface/membership.ts b/packages/core/issues/surface/membership.tsnew file mode 100644index 0000000000..019cc20f56--- /dev/null+++ b/packages/core/issues/surface/membership.ts@@ -0,0 +1,132 @@+import type { Issue, UpdateIssueRequest } from "../../types";+import type { MyIssuesFilter } from "../queries";++/**+ * Whether an issue belongs to a filtered list cache.+ *+ * `"unknown"` means the client cannot decide from the entity alone — the+ * filter's predicate lives server-side (agent-ownership graph behind+ * `involves_user_id`, the my:all relation union) or the entity is missing the+ * field the filter keys on. Callers patch on `true`, remove on `false`, and+ * patch + invalidate on `"unknown"` — the "certain → patch, uncertain →+ * invalidate" rule applied to list membership.+ */+export type IssueMembership = true | false | "unknown";++/**+ * The field groups a write can touch that move an issue in or out of a+ * filtered list (assignee / project) or shift per-status bucket totals+ * (status). Creator is not here: it is immutable after create.+ */+export interface IssueChangedDims {+ assignee: boolean;+ project: boolean;+ status: boolean;+}++/**+ * Derive the changed dimensions from a mutation patch. `base` (the freshest+ * cached pre-write entity, usually the detail cache) sharpens the answer:+ * writing the same value an issue already has changes nothing. Without a+ * base, any written membership field counts as changed — conservative, at+ * worst one extra list refetch on settle.+ */+export function issueChangedDims(+ patch: Partial<Issue> | UpdateIssueRequest,+ base?: Issue,+): IssueChangedDims {+ const has = (field: string) =>+ Object.prototype.hasOwnProperty.call(patch, field);+ const p = patch as Partial<Issue>;+ return {+ assignee:+ (has("assignee_id") && (!base || base.assignee_id !== p.assignee_id)) ||+ (has("assignee_type") && (!base || base.assignee_type !== p.assignee_type)),+ project: has("project_id") && (!base || base.project_id !== p.project_id),+ status: has("status") && p.status !== undefined && (!base || base.status !== p.status),+ };+}++/**+ * Does this list's server contract depend on any of the changed dimensions?+ * `scope` is the myList scope segment from the query key (`undefined` for the+ * unfiltered workspace list). When this returns false the write cannot move+ * the issue in or out of the list, so a plain field patch is a complete+ * reconcile.+ */+export function listFilterDependsOn(+ scope: string | undefined,+ filter: MyIssuesFilter,+ changed: IssueChangedDims,+): boolean {+ // my:all is the union of assigned / created / involved — the assigned and+ // involved legs key on the assignee.+ if (scope === "all") return changed.assignee;+ if (+ changed.assignee &&+ (filter.assignee_id !== undefined ||+ filter.assignee_ids !== undefined ||+ filter.assignee_types !== undefined ||+ filter.involves_user_id !== undefined)+ ) {+ return true;+ }+ if (changed.project && filter.project_id !== undefined) return true;+ // creator_id filters never react to updates — creator is immutable.+ return false;+}++/**+ * Judge an issue against a list's server contract. AND semantics across+ * filter fields: any definitive miss is `false`; a predicate the client+ * cannot evaluate (or a field the partial entity is missing) degrades the+ * answer to `"unknown"` instead of guessing.+ */+export function issueMatchesListFilter(+ issue: Partial<Issue>,+ scope: string | undefined,+ filter: MyIssuesFilter,+): IssueMembership {+ // my:all — union across relations; the involved leg needs the server's+ // agent-ownership graph, so membership is never decidable client-side.+ if (scope === "all") return "unknown";++ let unknown = false;++ if (filter.assignee_id !== undefined) {+ if (issue.assignee_id === undefined) unknown = true;+ else if (issue.assignee_id !== filter.assignee_id) return false;+ }+ if (filter.assignee_ids !== undefined) {+ if (issue.assignee_id === undefined) unknown = true;+ else if (+ issue.assignee_id === null ||+ !filter.assignee_ids.includes(issue.assignee_id)+ ) {+ return false;+ }+ }+ if (filter.assignee_types !== undefined) {+ if (issue.assignee_type === undefined) unknown = true;+ else if (+ issue.assignee_type === null ||+ !filter.assignee_types.includes(issue.assignee_type)+ ) {+ return false;+ }+ }+ if (filter.creator_id !== undefined) {+ if (issue.creator_id === undefined) unknown = true;+ else if (issue.creator_id !== filter.creator_id) return false;+ }+ if (filter.project_id !== undefined) {+ if (issue.project_id === undefined) unknown = true;+ else if (issue.project_id !== filter.project_id) return false;+ }+ if (filter.involves_user_id !== undefined) {+ // Indirect-assignee predicate (owned agents / squads) — server-only.+ unknown = true;+ }++ return unknown ? "unknown" : true;+}diff --git a/packages/core/issues/surface/query-plan.ts b/packages/core/issues/surface/query-plan.tsnew file mode 100644index 0000000000..5ea411b412--- /dev/null+++ b/packages/core/issues/surface/query-plan.ts@@ -0,0 +1,169 @@+import type { CreateIssueRequest } from "../../types";+import type {+ AssigneeGroupedIssuesFilter,+ MyIssuesFilter,+} from "../queries";+import {+ issueScopeKey,+ UnsupportedIssueScopeError,+ type IssueScope,+} from "./scope";++export type IssueSurfaceQueryPlan =+ | {+ kind: "workspace";+ scopeKey: string;+ queryScope: undefined;+ queryFilter: MyIssuesFilter;+ groupedScopeFilter: AssigneeGroupedIssuesFilter;+ loadMoreScope: undefined;+ loadMoreFilter: undefined;+ userId: undefined;+ createDefaults: Partial<CreateIssueRequest>;+ }+ | {+ kind: "scoped";+ scopeKey: string;+ queryScope: string;+ queryFilter: MyIssuesFilter;+ groupedScopeFilter: AssigneeGroupedIssuesFilter;+ loadMoreScope: string;+ loadMoreFilter: MyIssuesFilter;+ userId?: string;+ createDefaults: Partial<CreateIssueRequest>;+ };++function myRelationPlan(+ scope: Extract<IssueScope, { type: "my" }>,+): Pick<+ Extract<IssueSurfaceQueryPlan, { kind: "scoped" }>,+ "queryScope" | "queryFilter" | "userId" | "createDefaults"+> {+ switch (scope.relation) {+ case "assigned":+ return {+ queryScope: "assigned",+ queryFilter: { assignee_id: scope.userId },+ userId: undefined,+ createDefaults: {+ assignee_type: "member",+ assignee_id: scope.userId,+ },+ };+ case "created":+ return {+ queryScope: "created",+ queryFilter: { creator_id: scope.userId },+ userId: undefined,+ createDefaults: {},+ };+ case "involved":+ return {+ queryScope: "agents",+ queryFilter: { involves_user_id: scope.userId },+ userId: undefined,+ createDefaults: {},+ };+ case "all":+ return {+ queryScope: "all",+ queryFilter: {},+ userId: scope.userId,+ createDefaults: {},+ };+ }+}++export function buildIssueSurfaceQueryPlan(+ scope: IssueScope,+): IssueSurfaceQueryPlan {+ const scopeKey = issueScopeKey(scope);++ switch (scope.type) {+ case "workspace": {+ // Members/Agents tabs are server-filtered scoped lists — assignee_types+ // is a real API param on both the list and grouped endpoints, so each+ // tab gets its own cache entry with correct per-status totals and+ // load-more pagination. Only the unfiltered "all" tab uses the shared+ // workspace list cache.+ if (scope.actorKind === "members" || scope.actorKind === "agents") {+ const queryFilter: MyIssuesFilter =+ scope.actorKind === "members"+ ? { assignee_types: ["member"] }+ : { assignee_types: ["agent", "squad"] };+ return {+ kind: "scoped",+ scopeKey,+ queryScope: scopeKey,+ queryFilter,+ groupedScopeFilter: queryFilter,+ loadMoreScope: scopeKey,+ loadMoreFilter: queryFilter,+ userId: undefined,+ createDefaults: {},+ };+ }+ return {+ kind: "workspace",+ scopeKey,+ queryScope: undefined,+ queryFilter: {},+ groupedScopeFilter: {},+ loadMoreScope: undefined,+ loadMoreFilter: undefined,+ userId: undefined,+ createDefaults: {},+ };+ }+ case "project": {+ const queryFilter = { project_id: scope.projectId };+ return {+ kind: "scoped",+ scopeKey,+ queryScope: scopeKey,+ queryFilter,+ groupedScopeFilter: queryFilter,+ loadMoreScope: scopeKey,+ loadMoreFilter: queryFilter,+ userId: undefined,+ createDefaults: { project_id: scope.projectId },+ };+ }+ case "my": {+ const plan = myRelationPlan(scope);+ return {+ kind: "scoped",+ scopeKey,+ ...plan,+ groupedScopeFilter: plan.queryFilter,+ loadMoreScope: plan.queryScope,+ loadMoreFilter: plan.queryFilter,+ };+ }+ case "actor": {+ const queryFilter =+ scope.relation === "assigned"+ ? { assignee_id: scope.actorId }+ : { creator_id: scope.actorId };+ return {+ kind: "scoped",+ scopeKey,+ queryScope: scopeKey,+ queryFilter,+ groupedScopeFilter: queryFilter,+ loadMoreScope: scopeKey,+ loadMoreFilter: queryFilter,+ userId: undefined,+ createDefaults:+ scope.relation === "assigned"+ ? {+ assignee_type: scope.actorType,+ assignee_id: scope.actorId,+ }+ : {},+ };+ }+ case "team":+ throw new UnsupportedIssueScopeError(scope, "issue surface query plan");+ }+}diff --git a/packages/core/issues/surface/repository.ts b/packages/core/issues/surface/repository.tsnew file mode 100644index 0000000000..59036c4687--- /dev/null+++ b/packages/core/issues/surface/repository.ts@@ -0,0 +1,60 @@+import type { UseQueryOptions } from "@tanstack/react-query";+import {+ issueAssigneeGroupsOptions,+ issueListOptions,+ myIssueAssigneeGroupsOptions,+ myIssueListOptions,+ projectGanttIssuesOptions,+ type AssigneeGroupedIssuesFilter,+ type IssueSortParam,+} from "../queries";+import type {+ GroupedIssuesResponse,+ Issue,+ ListIssuesCache,+} from "../../types";+import type { IssueSurfaceQueryPlan } from "./query-plan";++/**+ * Issue surface repository — resolves a {@link IssueSurfaceQueryPlan} to the+ * concrete query options backing each render mode. Views declare WHICH+ * window they show (scope → plan) and WHICH mode is active; which endpoint,+ * cache key, and pagination style serve it is decided here in core, so the+ * view layer never branches on workspace-vs-scoped plumbing.+ */++/** Status-bucketed list — feeds the board / list / swimlane modes.+ *+ * Both branches share the exact cache shape (`ListIssuesCache` selected to+ * `Issue[]`); the cast below only erases the branch-specific query-key+ * literal so one `useQuery` call site can consume either plan kind. */+export function issueSurfaceListOptions(+ wsId: string,+ plan: IssueSurfaceQueryPlan,+ sort?: IssueSortParam,+): UseQueryOptions<ListIssuesCache, Error, Issue[]> {+ return (+ plan.kind === "workspace"+ ? issueListOptions(wsId, sort)+ : myIssueListOptions(wsId, plan.queryScope, plan.queryFilter, plan.userId, sort)+ ) as UseQueryOptions<ListIssuesCache, Error, Issue[]>;+}++/** Assignee-grouped list — feeds the board's group-by-assignee mode. */+export function issueSurfaceAssigneeGroupsOptions(+ wsId: string,+ plan: IssueSurfaceQueryPlan,+ filter: AssigneeGroupedIssuesFilter,+ sort?: IssueSortParam,+): UseQueryOptions<GroupedIssuesResponse> {+ return (+ plan.kind === "workspace"+ ? issueAssigneeGroupsOptions(wsId, filter, sort)+ : myIssueAssigneeGroupsOptions(wsId, plan.queryScope, filter, plan.userId, sort)+ ) as UseQueryOptions<GroupedIssuesResponse>;+}++/** Scheduled-only issue set — feeds a project surface's Gantt mode. */+export function issueSurfaceGanttOptions(wsId: string, projectId: string) {+ return projectGanttIssuesOptions(wsId, projectId);+}diff --git a/packages/core/issues/surface/scope.test.ts b/packages/core/issues/surface/scope.test.tsnew file mode 100644index 0000000000..7b08477be4--- /dev/null+++ b/packages/core/issues/surface/scope.test.ts@@ -0,0 +1,154 @@+import { describe, expect, it } from "vitest";+import {+ UnsupportedIssueScopeError,+ issueScopeKey,+} from "./scope";+import { buildIssueSurfaceQueryPlan } from "./query-plan";++describe("issue surface scope", () => {+ it("builds stable surface keys", () => {+ expect(issueScopeKey({ type: "workspace" })).toBe("workspace:all");+ expect(issueScopeKey({ type: "workspace", actorKind: "agents" })).toBe(+ "workspace:agents",+ );+ expect(+ issueScopeKey({ type: "my", relation: "assigned", userId: "u1" }),+ ).toBe("my:u1:assigned");+ expect(issueScopeKey({ type: "project", projectId: "p1" })).toBe(+ "project:p1",+ );+ expect(+ issueScopeKey({+ type: "actor",+ actorType: "agent",+ actorId: "a1",+ relation: "created",+ }),+ ).toBe("actor:agent:a1:created");+ expect(issueScopeKey({ type: "team", teamId: "t1" })).toBe("team:t1");+ });++ it("builds the workspace query plan", () => {+ // The unfiltered tab shares the workspace list cache.+ expect(buildIssueSurfaceQueryPlan({ type: "workspace" })).toMatchObject({+ kind: "workspace",+ scopeKey: "workspace:all",+ queryFilter: {},+ groupedScopeFilter: {},+ createDefaults: {},+ });++ // Members/Agents tabs are server-filtered scoped lists: assignee_types+ // rides the list + grouped requests, and each tab owns its cache entry+ // (correct totals + load-more, no client post-filtering).+ expect(+ buildIssueSurfaceQueryPlan({ type: "workspace", actorKind: "agents" }),+ ).toMatchObject({+ kind: "scoped",+ scopeKey: "workspace:agents",+ queryScope: "workspace:agents",+ queryFilter: { assignee_types: ["agent", "squad"] },+ groupedScopeFilter: { assignee_types: ["agent", "squad"] },+ loadMoreScope: "workspace:agents",+ loadMoreFilter: { assignee_types: ["agent", "squad"] },+ createDefaults: {},+ });+ expect(+ buildIssueSurfaceQueryPlan({ type: "workspace", actorKind: "members" }),+ ).toMatchObject({+ kind: "scoped",+ scopeKey: "workspace:members",+ queryFilter: { assignee_types: ["member"] },+ groupedScopeFilter: { assignee_types: ["member"] },+ createDefaults: {},+ });+ });++ it("builds personal issue query plans using the existing query contracts", () => {+ expect(+ buildIssueSurfaceQueryPlan({+ type: "my",+ relation: "assigned",+ userId: "u1",+ }),+ ).toMatchObject({+ scopeKey: "my:u1:assigned",+ queryScope: "assigned",+ queryFilter: { assignee_id: "u1" },+ groupedScopeFilter: { assignee_id: "u1" },+ loadMoreScope: "assigned",+ loadMoreFilter: { assignee_id: "u1" },+ userId: undefined,+ createDefaults: { assignee_type: "member", assignee_id: "u1" },+ });+ expect(+ buildIssueSurfaceQueryPlan({+ type: "my",+ relation: "created",+ userId: "u1",+ }),+ ).toMatchObject({+ queryScope: "created",+ queryFilter: { creator_id: "u1" },+ createDefaults: {},+ });+ expect(+ buildIssueSurfaceQueryPlan({+ type: "my",+ relation: "involved",+ userId: "u1",+ }),+ ).toMatchObject({+ queryScope: "agents",+ queryFilter: { involves_user_id: "u1" },+ createDefaults: {},+ });+ expect(+ buildIssueSurfaceQueryPlan({+ type: "my",+ relation: "all",+ userId: "u1",+ }),+ ).toMatchObject({+ queryScope: "all",+ queryFilter: {},+ groupedScopeFilter: {},+ userId: "u1",+ createDefaults: {},+ });+ });++ it("builds project and actor query plans", () => {+ expect(+ buildIssueSurfaceQueryPlan({ type: "project", projectId: "p1" }),+ ).toMatchObject({+ scopeKey: "project:p1",+ queryScope: "project:p1",+ queryFilter: { project_id: "p1" },+ groupedScopeFilter: { project_id: "p1" },+ createDefaults: { project_id: "p1" },+ });++ expect(+ buildIssueSurfaceQueryPlan({+ type: "actor",+ actorType: "agent",+ actorId: "a1",+ relation: "assigned",+ }),+ ).toMatchObject({+ scopeKey: "actor:agent:a1:assigned",+ queryScope: "actor:agent:a1:assigned",+ queryFilter: { assignee_id: "a1" },+ groupedScopeFilter: { assignee_id: "a1" },+ createDefaults: { assignee_type: "agent", assignee_id: "a1" },+ });+ });++ it("throws for team until the issue API has a team filter", () => {+ const scope = { type: "team" as const, teamId: "t1" };+ expect(() => buildIssueSurfaceQueryPlan(scope)).toThrow(+ UnsupportedIssueScopeError,+ );+ });+});diff --git a/packages/core/issues/surface/scope.ts b/packages/core/issues/surface/scope.tsnew file mode 100644index 0000000000..21a7839795--- /dev/null+++ b/packages/core/issues/surface/scope.ts@@ -0,0 +1,41 @@+import type { IssueAssigneeType } from "../../types";++export type WorkspaceIssueActorKind = "all" | "members" | "agents";++export type IssueScope =+ | { type: "workspace"; actorKind?: WorkspaceIssueActorKind }+ | {+ type: "my";+ relation: "all" | "assigned" | "created" | "involved";+ userId: string;+ }+ | { type: "project"; projectId: string }+ | {+ type: "actor";+ actorType: Extract<IssueAssigneeType, "member" | "agent">;+ actorId: string;+ relation: "assigned" | "created";+ }+ | { type: "team"; teamId: string };++export class UnsupportedIssueScopeError extends Error {+ constructor(scope: IssueScope, operation: string) {+ super(`Issue scope "${issueScopeKey(scope)}" is not supported for ${operation}.`);+ this.name = "UnsupportedIssueScopeError";+ }+}++export function issueScopeKey(scope: IssueScope): string {+ switch (scope.type) {+ case "workspace":+ return `workspace:${scope.actorKind ?? "all"}`;+ case "my":+ return `my:${scope.userId}:${scope.relation}`;+ case "project":+ return `project:${scope.projectId}`;+ case "actor":+ return `actor:${scope.actorType}:${scope.actorId}:${scope.relation}`;+ case "team":+ return `team:${scope.teamId}`;+ }+}diff --git a/packages/core/issues/ws-updaters.test.ts b/packages/core/issues/ws-updaters.test.tsindex 7d7ba631c7..4ae7321f0a 100644--- a/packages/core/issues/ws-updaters.test.ts+++ b/packages/core/issues/ws-updaters.test.ts@@ -301,49 +301,106 @@ describe("onIssueUpdated — position move is surgical, not a list refetch", ()expect(qc.getQueryState(issueKeys.myAll(WS_ID))?.isInvalidated).toBe(false);});- it("invalidates myAll when the assignee changes (membership may shift)", () => {- qc.setQueryData<ListIssuesCache>(issueKeys.myAll(WS_ID), makeListCache(issueA));+ it("removes the card from an assignee-filtered list when the assignee changes (membership-aware, no blanket refetch)", () => {+ const assignedKey = issueKeys.myListSorted(+ WS_ID,+ "assigned",+ { assignee_id: "user-1" },+ undefined,+ );+ const mine: Issue = { ...issueA, assignee_type: "member", assignee_id: "user-1" };+ qc.setQueryData<ListIssuesCache>(assignedKey, makeListCache(mine));onIssueUpdated(qc,WS_ID,- { ...issueA, assignee_type: "member", assignee_id: "user-2" },+ { ...mine, assignee_type: "member", assignee_id: "user-2" },{ assigneeChanged: true },);- expectInvalidated(qc, issueKeys.myAll(WS_ID));+ // The card LEAVES the loaded list surgically — the fix for the residue+ // that used to wait on a refetch (and on the mutation path never came).+ const list = qc.getQueryData<ListIssuesCache>(assignedKey);+ expect(list?.byStatus.todo?.issues).toEqual([]);+ expect(list?.byStatus.todo?.total).toBe(0);+ expect(qc.getQueryState(assignedKey)?.isInvalidated).toBe(false);});- it("invalidates myAll when the project changes (Project board membership)", () => {- qc.setQueryData<ListIssuesCache>(issueKeys.myAll(WS_ID), makeListCache(issueA));+ it("flags union-scope (my:all) lists stale on an assignee change instead of guessing membership", () => {+ const myAllListKey = issueKeys.myListSorted(WS_ID, "all", {}, undefined);+ const mine: Issue = { ...issueA, assignee_type: "member", assignee_id: "user-1" };+ qc.setQueryData<ListIssuesCache>(myAllListKey, makeListCache(mine));++ onIssueUpdated(+ qc,+ WS_ID,+ { ...mine, assignee_type: "member", assignee_id: "user-2" },+ { assigneeChanged: true },+ );++ // Union membership (assigned ∪ created ∪ involved) is server knowledge:+ // the card is patched in place and the list refetches to reconcile.+ const list = qc.getQueryData<ListIssuesCache>(myAllListKey);+ expect(list?.byStatus.todo?.issues[0]?.assignee_id).toBe("user-2");+ expectInvalidated(qc, myAllListKey);+ });- // issueA.project_id is null; moving it into a project shifts Project-board- // membership. No server flag here — this exercises the legacy cache-diff+ it("moves the card out of the old project's list and flags the loaded target list (legacy diff fallback, no server flag)", () => {+ // issueA.project_id is null; moving it into project-9 must reconcile both+ // ends. No server flag here — this exercises the legacy cache-diff// fallback that keeps a new frontend working against an older backend.+ const targetKey = issueKeys.myListSorted(+ WS_ID,+ "project:project-9",+ { project_id: "project-9" },+ undefined,+ );+ qc.setQueryData<ListIssuesCache>(targetKey, makeListCache());+onIssueUpdated(qc, WS_ID, { ...issueA, project_id: "project-9" });- expectInvalidated(qc, issueKeys.myAll(WS_ID));+ // Never hard-inserted (its page/slot is server knowledge) — the loaded+ // target list is refetched instead.+ expect(+ qc.getQueryData<ListIssuesCache>(targetKey)?.byStatus.todo?.issues,+ ).toEqual([]);+ expectInvalidated(qc, targetKey);});- it("invalidates myAll on a server project_changed flag even when the cached project_id already matches (local optimistic move)", () => {- // Reproduces the post-optimistic-move state behind MUL-3669: onMutate has- // already written the NEW project into detail + list, so a cache diff would- // compute projectChanged=false and skip the refetch. The authoritative- // server flag must still drive it.+ it("drops the card from the old project's list on a server project_changed flag even when the cached project_id already matches", () => {+ // Reproduces the drift state behind MUL-3669: the detail cache already+ // carries the NEW project (e.g. a local optimistic write), so a cache+ // diff would compute projectChanged=false — the authoritative server+ // flag must still drive the membership reconcile for any list where the+ // card lingers.const moved: Issue = { ...issueA, project_id: "project-9" };+ const oldProjectKey = issueKeys.myListSorted(+ WS_ID,+ "project:project-1",+ { project_id: "project-1" },+ undefined,+ );qc.setQueryData<Issue>(issueKeys.detail(WS_ID, moved.id), moved);- qc.setQueryData<ListIssuesCache>(issueKeys.myAll(WS_ID), makeListCache(moved));+ qc.setQueryData<ListIssuesCache>(oldProjectKey, makeListCache(moved));onIssueUpdated(qc, WS_ID, moved, { projectChanged: true });- expectInvalidated(qc, issueKeys.myAll(WS_ID));+ expect(+ qc.getQueryData<ListIssuesCache>(oldProjectKey)?.byStatus.todo?.issues,+ ).toEqual([]);});- it("does NOT invalidate myAll when the server flag says project_changed=false (flag overrides the legacy diff)", () => {+ it("does NOT touch project lists when the server flag says project_changed=false (flag overrides the legacy diff)", () => {// No detail/list cache for the issue, so the legacy diff would resolve// oldProjectId=null and fire on the non-null incoming project_id. An explicit// false flag from the server is authoritative and must suppress that.- qc.setQueryData<ListIssuesCache>(issueKeys.myAll(WS_ID), makeListCache(issueA));+ const projectKey = issueKeys.myListSorted(+ WS_ID,+ "project:project-9",+ { project_id: "project-9" },+ undefined,+ );+ qc.setQueryData<ListIssuesCache>(projectKey, makeListCache());onIssueUpdated(qc,@@ -352,7 +409,7 @@ describe("onIssueUpdated — position move is surgical, not a list refetch", (){ projectChanged: false },);- expect(qc.getQueryState(issueKeys.myAll(WS_ID))?.isInvalidated).toBe(false);+ expect(qc.getQueryState(projectKey)?.isInvalidated).toBe(false);});});diff --git a/packages/core/issues/ws-updaters.ts b/packages/core/issues/ws-updaters.tsindex e7d28bad91..004e1a613d 100644--- a/packages/core/issues/ws-updaters.ts+++ b/packages/core/issues/ws-updaters.ts@@ -1,7 +1,12 @@-import type { QueryClient, QueryKey } from "@tanstack/react-query";+import type { QueryClient } from "@tanstack/react-query";import { issueKeys } from "./queries";import { labelKeys } from "../labels/queries";import { projectKeys } from "../projects/queries";+import {+ applyIssueChange,+ invalidateIssueDerivatives,+ invalidateStaleListKeys,+} from "./cache-coordinator";import {addIssueToBuckets,findIssueLocation,@@ -41,106 +46,73 @@ export function onIssueUpdated(wsId: string,issue: Partial<Issue> & { id: string },// assigneeChanged / statusChanged / projectChanged come from the server's- // issue:updated flags. assigneeChanged + projectChanged gate the filtered-list- // (myAll) invalidate so a non-membership change keeps those lists in place- // instead of refetching. statusChanged gates the off-screen count reconcile- // below.+ // issue:updated flags — authoritative "did this write move a membership+ // dimension" signals. They feed the coordinator's changed-dims input so a+ // non-membership change (title / position / priority / label) keeps every+ // loaded list in place instead of refetching.meta: {assigneeChanged?: boolean;statusChanged?: boolean;projectChanged?: boolean;} = {},) {- // Look up the OLD parent before mutating list state, so we can keep- // the parent's children cache in sync (powers the sub-issues list- // shown on the parent issue page).+ // Look up the OLD parent + cached entity before mutating cache state, so we+ // can keep the parent's children cache in sync (powers the sub-issues list+ // shown on the parent issue page) and diff-fallback the change flags.const listQueries = qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) });const firstListData = listQueries[0]?.[1];const detailData = qc.getQueryData<Issue>(issueKeys.detail(wsId, issue.id));+ const cachedIssue =+ detailData ??+ (firstListData ? findIssueLocation(firstListData, issue.id)?.issue : undefined);const oldParentId =- detailData?.parent_issue_id ??- (firstListData ? findIssueLocation(firstListData, issue.id)?.issue.parent_issue_id : null) ??- null;+ detailData?.parent_issue_id ?? cachedIssue?.parent_issue_id ?? null;// The NEW parent comes from the WS payload when parent_issue_id changedconst newParentId = issue.parent_issue_id ?? null;const parentChanged =issue.parent_issue_id !== undefined && newParentId !== oldParentId;- // Project board membership keys on project_id. Prefer the server's- // project_changed flag (authoritative, set on the wire). Fall back to diffing- // the incoming project_id against the cached one only when the flag is absent+ // Prefer the server's flags (authoritative, set on the wire). Fall back to+ // diffing the payload against the cached copy only when a flag is absent// (older backend): the diff is unreliable once a local optimistic move has- // overwritten the cached project_id, but it still covers remote/agent moves+ // overwritten the cached value, but it still covers remote/agent changes// and keeps a new frontend on an old backend from regressing (MUL-3669 /- // #4548). The local move itself is also covered by the onSettled safety net in- // useUpdateIssue, which never depends on this flag.- const oldProjectId =- detailData?.project_id ??- (firstListData ? findIssueLocation(firstListData, issue.id)?.issue.project_id : null) ??- null;- const projectChanged =- meta.projectChanged ??- (issue.project_id !== undefined && (issue.project_id ?? null) !== oldProjectId);-- // A status change shifts two bucket totals (the column header counts).- // patchIssueInBuckets does that surgically, but only when it can find the card- // in a loaded page; a paginated column holds just its first page, so an issue- // outside that window — common when an agent flips the status of something the- // viewer never scrolled to — makes the patch a no-op (it returns the same- // reference) and the totals silently drift. A status change otherwise never- // refetches the list (that refetch was the drag flicker removed by the- // optimistic-update work), so recover the one case the patch cannot: on a- // status-changed no-op, refetch just that single list to reconcile its counts.- const patchOrRefetchCounts = (key: QueryKey, data: ListIssuesCache) => {- const next = patchIssueInBuckets(data, issue.id, issue);- qc.setQueryData<ListIssuesCache>(key, next);- if (next === data && meta.statusChanged) {- qc.invalidateQueries({ queryKey: key });- }+ // #4548). The local move itself is covered by useUpdateIssue's own+ // coordinator pass, which never depends on these flags.+ const oldProjectId = detailData?.project_id ?? cachedIssue?.project_id ?? null;+ const changed = {+ assignee:+ meta.assigneeChanged ??+ (cachedIssue !== undefined &&+ ((issue.assignee_id !== undefined &&+ issue.assignee_id !== cachedIssue.assignee_id) ||+ (issue.assignee_type !== undefined &&+ issue.assignee_type !== cachedIssue.assignee_type))),+ project:+ meta.projectChanged ??+ (issue.project_id !== undefined && (issue.project_id ?? null) !== oldProjectId),+ status:+ meta.statusChanged ??+ (cachedIssue !== undefined &&+ issue.status !== undefined &&+ issue.status !== cachedIssue.status),};- for (const [key, data] of listQueries) {- if (data) patchOrRefetchCounts(key, data);- }- // The workspace board (issueKeys.list) is NOT filtered: an issue is always a- // member, so patchIssueInBuckets above is a complete surgical reconcile —- // cross-status move, same-column reorder, and field updates all land in the- // right bucket/slot. The old `if (position) invalidateQueries(list)` re-pulled- // the entire board on top of that, which is the full-list refetch that made a- // drag (local or echoed back over WS) flicker. It is pure redundancy here.- //- // myAll (My Issues / Project / actor lists) IS filtered. Surgically patch the- // cards that already live in those caches too, so a non-membership change- // (pure status / position / priority / label) reconciles in place — no- // refetch, no flicker — exactly like the workspace board above.- const myListQueries = qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.myAll(wsId) });- for (const [key, data] of myListQueries) {- if (data?.byStatus) patchOrRefetchCounts(key, data);- }- // Only refetch the filtered lists when the change can actually move an issue- // in/out of one. My-Issues / actor-panel membership keys on the assignee (the- // "involves" leg — my agents / my squads — is assignee-based too), so the- // server's assignee_changed flag covers it; the Project board keys on- // project_id. A pure status / position / priority / label change cannot change- // membership, so the surgical patch above is the complete reconcile and we- // skip the invalidate that used to make a My-Issues drag refetch + flicker.- if (meta.assigneeChanged || projectChanged) {- qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });- }- qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });- qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });- if (issue.status !== undefined || issue.project_id !== undefined) {- qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });- }- // Any field change can shift Gantt membership — start_date / due_date may- // have moved in or out of the `scheduled` set, project_id may have- // changed, or the row that is in the cache may need to mirror updated- // metadata (title, status, assignee). Cheaper to invalidate the prefix- // than to mirror the server filter here.- qc.invalidateQueries({ queryKey: issueKeys.projectGanttAll(wsId) });- qc.setQueryData<Issue>(issueKeys.detail(wsId, issue.id), (old) =>- old ? { ...old, ...issue } : old,- );+ // The coordinator applies the same rules table the local mutations use:+ // surgical patch/rebucket where the card is loaded and still belongs,+ // surgical remove where the change moved it off a filtered surface, and+ // stale keys for the drift a patch cannot fix (enter/leave beyond the+ // loaded window, undecidable membership, off-screen bucket counts). The+ // server has already committed, so stale keys are flushed immediately.+ const change = applyIssueChange(qc, wsId, issue.id, issue, {+ changed,+ baseIssue: cachedIssue,+ });+ invalidateStaleListKeys(qc, change.staleKeys);+ invalidateIssueDerivatives(qc, wsId, {+ statusOrProjectChanged:+ issue.status !== undefined || issue.project_id !== undefined,+ });// Invalidate old parent's children (issue was removed from it)if (oldParentId) {diff --git a/packages/core/package.json b/packages/core/package.jsonindex 1465ac3ef4..6b369b9dfc 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -33,6 +33,7 @@"./issues/timeline-sort": "./issues/timeline-sort.ts","./issues/date": "./issues/date.ts","./issues/ws-updaters": "./issues/ws-updaters.ts",+ "./issues/surface/*": "./issues/surface/*.ts","./issues/config": "./issues/config/index.ts","./issues/config/status": "./issues/config/status.ts","./issues/config/priority": "./issues/config/priority.ts",diff --git a/packages/core/platform/storage-cleanup.test.ts b/packages/core/platform/storage-cleanup.test.tsindex a5905b0700..2f52b25b60 100644--- a/packages/core/platform/storage-cleanup.test.ts+++ b/packages/core/platform/storage-cleanup.test.ts@@ -12,6 +12,7 @@ describe("clearWorkspaceStorage", () => {clearWorkspaceStorage(adapter, "ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica_issue_draft:ws_123");+ expect(adapter.removeItem).toHaveBeenCalledWith("multica_issue_surface_views:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica_issues_view:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica_issues_scope:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica_my_issues_view:ws_123");@@ -20,6 +21,6 @@ describe("clearWorkspaceStorage", () => {expect(adapter.removeItem).toHaveBeenCalledWith("multica:chat:drafts:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica:chat:expanded:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica_navigation:ws_123");- expect(adapter.removeItem).toHaveBeenCalledTimes(9);+ expect(adapter.removeItem).toHaveBeenCalledTimes(10);});});diff --git a/packages/core/platform/storage-cleanup.ts b/packages/core/platform/storage-cleanup.tsindex eb9a58bb65..3b043d5d4d 100644--- a/packages/core/platform/storage-cleanup.ts+++ b/packages/core/platform/storage-cleanup.ts@@ -9,6 +9,7 @@ import type { StorageAdapter } from "../types/storage";*/const WORKSPACE_SCOPED_KEYS = ["multica_issue_draft",+ "multica_issue_surface_views","multica_issues_view","multica_issues_scope","multica_my_issues_view",diff --git a/packages/core/projects/mutations.test.tsx b/packages/core/projects/mutations.test.tsxnew file mode 100644index 0000000000..0db7e47006--- /dev/null+++ b/packages/core/projects/mutations.test.tsx@@ -0,0 +1,61 @@+/**+ * @vitest-environment jsdom+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, renderHook } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { setApiInstance } from "../api";+import type { ApiClient } from "../api/client";+import { setCurrentWorkspace } from "../platform/workspace-storage";+import {+ getIssueSurfaceViewStore,+ pruneIssueSurfaceViewStates,+} from "../issues/stores/surface-view-store";+import { useDeleteProject } from "./mutations";++vi.mock("../hooks", () => ({+ useWorkspaceId: () => "ws-1",+}));++function createWrapper(qc: QueryClient) {+ return function Wrapper({ children }: { children: ReactNode }) {+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;+ };+}++describe("useDeleteProject", () => {+ let qc: QueryClient;+ let deleteProject: ReturnType<typeof vi.fn<() => Promise<void>>>;++ beforeEach(() => {+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ deleteProject = vi.fn().mockResolvedValue(undefined);+ setApiInstance({ deleteProject } as unknown as ApiClient);+ setCurrentWorkspace("acme", "ws-1");+ });++ afterEach(() => {+ qc.clear();+ pruneIssueSurfaceViewStates([]);+ setCurrentWorkspace(null, null);+ vi.restoreAllMocks();+ });++ it("clears the deleted project's issue surface view state", async () => {+ const store = getIssueSurfaceViewStore("project:p1");+ store.getState().setViewMode("list");+ expect(store.getState().viewMode).toBe("list");++ const { result } = renderHook(() => useDeleteProject(), {+ wrapper: createWrapper(qc),+ });++ await act(async () => {+ await result.current.mutateAsync("p1");+ });++ expect(deleteProject).toHaveBeenCalledWith("p1");+ expect(store.getState().viewMode).toBe("board");+ });+});diff --git a/packages/core/projects/mutations.ts b/packages/core/projects/mutations.tsindex a2f73d54de..90cf10178d 100644--- a/packages/core/projects/mutations.ts+++ b/packages/core/projects/mutations.ts@@ -3,6 +3,8 @@ import { api } from "../api";import { projectKeys } from "./queries";import { useWorkspaceId } from "../hooks";import { useRecentContextStore } from "../chat/recent-context-store";+import { clearIssueSurfaceViewState } from "../issues/stores/surface-view-store";+import { issueScopeKey } from "../issues/surface/scope";import type { Project, CreateProjectRequest, UpdateProjectRequest, ListProjectsResponse } from "../types";export function useCreateProject() {@@ -71,6 +73,7 @@ export function useDeleteProject() {},onSuccess: (_data, id) => {useRecentContextStore.getState().forgetContext(wsId, { type: "project", id });+ clearIssueSurfaceViewState(issueScopeKey({ type: "project", projectId: id }));},onSettled: () => {qc.invalidateQueries({ queryKey: projectKeys.list(wsId) });diff --git a/packages/core/types/api.ts b/packages/core/types/api.tsindex 1e76bf1f92..001c75e218 100644--- a/packages/core/types/api.ts+++ b/packages/core/types/api.ts@@ -81,6 +81,12 @@ export interface ListIssuesParams {priority?: IssuePriority;assignee_id?: string;assignee_ids?: string[];+ /**+ * Narrow to issues assigned to the given actor kinds (member / agent /+ * squad). Same semantics as `ListGroupedIssuesParams.assignee_types` —+ * powers the workspace Members/Agents tabs server-side.+ */+ assignee_types?: IssueAssigneeType[];creator_id?: string;project_id?: string;/**diff --git a/packages/views/common/actor-issues-panel.tsx b/packages/views/common/actor-issues-panel.tsxindex 1a07471169..35fcc23d84 100644--- a/packages/views/common/actor-issues-panel.tsx+++ b/packages/views/common/actor-issues-panel.tsx@@ -1,31 +1,21 @@"use client";-import { useEffect, useMemo, useState } from "react";+import { useCallback, useMemo, useState } from "react";import { useStore } from "zustand";import { ListTodo, Search } from "lucide-react";-import { useQuery } from "@tanstack/react-query";-import { useWorkspaceId } from "@multica/core/hooks";-import { BOARD_STATUSES } from "@multica/core/issues/config";-import {- childIssueProgressOptions,- myIssueListOptions,- type MyIssuesFilter,-} from "@multica/core/issues/queries";+import type { Issue } from "@multica/core/types";import {actorIssuesViewStore,type ActorIssuesScope,} from "@multica/core/issues/stores/actor-issues-view-store";-import { useIssueSelectionStore } from "@multica/core/issues/stores/selection-store";-import { useClearFiltersOnWorkspaceChange } from "@multica/core/issues/stores/view-store";-import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";import { Button } from "@multica/ui/components/ui/button";import { Input } from "@multica/ui/components/ui/input";-import { Skeleton } from "@multica/ui/components/ui/skeleton";import { Tooltip, TooltipContent, TooltipTrigger } from "@multica/ui/components/ui/tooltip";-import { ListView } from "../issues/components/list-view";-import { BatchActionToolbar } from "../issues/components/batch-action-toolbar";-import { IssueDisplayControls } from "../issues/components/issues-header";-import { filterIssues } from "../issues/utils/filter";+import {+ IssueDisplayControls,+ ViewRefreshIndicator,+} from "../issues/components/issues-header";+import { IssueSurface } from "../issues/surface/issue-surface";import { matchesPinyin } from "../editor/extensions/pinyin-match";import { useT } from "../i18n";@@ -33,6 +23,80 @@ 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,+ onSearchChange,+ scope,+ onScopeChange,+ isRefreshing = false,+}: {+ issues: Issue[];+ search: string;+ onSearchChange: (value: string) => void;+ scope: ActorIssuesScope;+ onScopeChange: (scope: ActorIssuesScope) => void;+ isRefreshing?: boolean;+}) {+ const { t } = useT("issues");++ return (+ <div className="flex h-12 shrink-0 items-center justify-between gap-3 border-b px-4">+ <div className="flex items-center gap-3">+ <div className="relative">+ <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />+ <Input+ value={search}+ onChange={(e) => onSearchChange(e.target.value)}+ placeholder={t(($) => $.actor_issues.search_placeholder)}+ className="h-8 w-64 pl-8 text-sm"+ />+ </div>+ <div className="flex items-center gap-1">+ {SCOPE_VALUES.map((value) => (+ <Tooltip key={value}>+ <TooltipTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className={+ scope === value+ ? "bg-accent text-accent-foreground hover:bg-accent/80"+ : "text-muted-foreground"+ }+ onClick={() => onScopeChange(value)}+ >+ {t(($) => $.actor_issues.scope[value].label)}+ </Button>+ }+ />+ <TooltipContent side="bottom">+ {t(($) => $.actor_issues.scope[value].description)}+ </TooltipContent>+ </Tooltip>+ ))}+ </div>+ </div>+ <div className="flex items-center">+ <IssueDisplayControls scopedIssues={issues} hideViewToggle />+ <ViewRefreshIndicator active={isRefreshing} />+ </div>+ </div>+ );+}+export function ActorIssuesPanel({actorType,actorId,@@ -41,159 +105,44 @@ export function ActorIssuesPanel({actorId: string;}) {const { t } = useT("issues");- const wsId = useWorkspaceId();const scope = useStore(actorIssuesViewStore, (s) => s.scope);const setScope = useStore(actorIssuesViewStore, (s) => s.setScope);- const setViewMode = useStore(actorIssuesViewStore, (s) => s.setViewMode);- const statusFilters = useStore(actorIssuesViewStore, (s) => s.statusFilters);- const priorityFilters = useStore(actorIssuesViewStore, (s) => s.priorityFilters);- const assigneeFilters = useStore(actorIssuesViewStore, (s) => s.assigneeFilters);- const includeNoAssignee = useStore(actorIssuesViewStore, (s) => s.includeNoAssignee);- const creatorFilters = useStore(actorIssuesViewStore, (s) => s.creatorFilters);- const projectFilters = useStore(actorIssuesViewStore, (s) => s.projectFilters);- const includeNoProject = useStore(actorIssuesViewStore, (s) => s.includeNoProject);- const labelFilters = useStore(actorIssuesViewStore, (s) => s.labelFilters);- const showSubIssues = useStore(actorIssuesViewStore, (s) => s.showSubIssues);-const [search, setSearch] = useState("");-- useClearFiltersOnWorkspaceChange(actorIssuesViewStore, wsId);-- // The actor tasks panel is list-only; clear any persisted "board" state- // so list-only affordances (e.g. BatchActionToolbar) render correctly.- useEffect(() => {- setViewMode("list");- }, [setViewMode]);-- useEffect(() => {- useIssueSelectionStore.getState().clear();- }, [scope, actorType, actorId]);-- const queryFilter: MyIssuesFilter = useMemo(- () =>- scope === "assigned"- ? { assignee_id: actorId }- : { creator_id: actorId },- [scope, actorId],- );- const queryScope = `${actorType}:${actorId}:${scope}`;-- const rawIssuesQuery = useQuery(myIssueListOptions(wsId, queryScope, queryFilter));- const rawIssues = useMemo(- () => rawIssuesQuery.data ?? [],- [rawIssuesQuery.data],- );- const isLoading = rawIssuesQuery.isLoading;-- const actorIssues = useMemo(- () =>- rawIssues.filter((issue) =>- scope === "assigned"- ? issue.assignee_type === actorType && issue.assignee_id === actorId- : issue.creator_type === actorType && issue.creator_id === actorId,- ),- [actorId, actorType, rawIssues, scope],+ const clientFilter = useCallback(+ (issue: Issue) => issueMatchesSearch(issue, search),+ [search],);-- const filteredIssues = useMemo(+ const surfaceScope = useMemo(() =>- filterIssues(actorIssues, {- statusFilters,- priorityFilters,- assigneeFilters,- includeNoAssignee,- creatorFilters,- projectFilters,- includeNoProject,- labelFilters,- showSubIssues,+ ({+ type: "actor" as const,+ actorType,+ actorId,+ relation: scope,}),- [- actorIssues,- statusFilters,- priorityFilters,- assigneeFilters,- includeNoAssignee,- creatorFilters,- projectFilters,- includeNoProject,- labelFilters,- showSubIssues,- ],- );-- const issues = useMemo(() => {- const query = search.trim().toLowerCase();- if (!query) return filteredIssues;- return filteredIssues.filter((issue) => {- const title = issue.title ?? "";- return (- title.toLowerCase().includes(query) ||- issue.identifier.toLowerCase().includes(query) ||- matchesPinyin(title, query)- );- });- }, [filteredIssues, search]);-- const { data: childProgressMap = new Map() } = useQuery(- childIssueProgressOptions(wsId),+ [actorId, actorType, scope],);- const visibleStatuses = useMemo(() => {- if (statusFilters.length > 0) {- return BOARD_STATUSES.filter((s) => statusFilters.includes(s));- }- return BOARD_STATUSES;- }, [statusFilters]);-- if (isLoading) {- return <ActorIssuesSkeleton />;- }-return (- <ViewStoreProvider store={actorIssuesViewStore}>- <div className="flex flex-1 min-h-0 flex-col">- <div className="flex h-12 shrink-0 items-center justify-between gap-3 border-b px-4">- <div className="flex items-center gap-3">- <div className="relative">- <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />- <Input- value={search}- onChange={(e) => setSearch(e.target.value)}- placeholder={t(($) => $.actor_issues.search_placeholder)}- className="h-8 w-64 pl-8 text-sm"- />- </div>- <div className="flex items-center gap-1">- {SCOPE_VALUES.map((value) => (- <Tooltip key={value}>- <TooltipTrigger- render={- <Button- variant="outline"- size="sm"- className={- scope === value- ? "bg-accent text-accent-foreground hover:bg-accent/80"- : "text-muted-foreground"- }- onClick={() => setScope(value)}- >- {t(($) => $.actor_issues.scope[value].label)}- </Button>- }- />- <TooltipContent side="bottom">- {t(($) => $.actor_issues.scope[value].description)}- </TooltipContent>- </Tooltip>- ))}- </div>- </div>- <IssueDisplayControls scopedIssues={actorIssues} hideViewToggle />- </div>-- {actorIssues.length === 0 ? (+ <IssueSurface+ scope={surfaceScope}+ modes={["list"]}+ batchToolbar="always"+ contentClassName="p-1"+ clientFilter={clientFilter}+ showClientEmpty={() => search.trim() !== ""}+ renderHeader={({ controller }) => (+ <ActorIssuesHeader+ issues={controller.surfaceIssues}+ search={search}+ onSearchChange={setSearch}+ scope={scope}+ onScopeChange={setScope}+ isRefreshing={controller.isRefreshing}+ />+ )}+ renderEmpty={({ controller }) =>+ controller.surfaceIssues.length === 0 ? (<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">@@ -203,47 +152,13 @@ export function ActorIssuesPanel({{t(($) => $.actor_issues.empty[scope].description)}</p></div>- ) : search.trim() !== "" && issues.length === 0 ? (+ ) : (<div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-2 text-muted-foreground"><Search className="h-10 w-10 text-muted-foreground/40" /><p className="text-sm">{t(($) => $.actor_issues.search_empty)}</p></div>- ) : (- <div className="flex flex-1 min-h-0 flex-col p-1">- <ListView- issues={issues}- visibleStatuses={visibleStatuses}- childProgressMap={childProgressMap}- myIssuesScope={queryScope}- myIssuesFilter={queryFilter}- />- </div>- )}- <BatchActionToolbar issues={issues} />- </div>- </ViewStoreProvider>- );-}--function ActorIssuesSkeleton() {- return (- <div className="flex flex-1 min-h-0 flex-col">- <div className="flex h-12 shrink-0 items-center justify-between border-b px-4">- <div className="flex items-center gap-3">- <Skeleton className="h-8 w-64 rounded-md" />- <Skeleton className="h-8 w-20 rounded-md" />- <Skeleton className="h-8 w-20 rounded-md" />- </div>- <div className="flex items-center gap-1">- <Skeleton className="h-8 w-8 rounded-md" />- <Skeleton className="h-8 w-8 rounded-md" />- </div>- </div>- <div className="flex flex-1 min-h-0 flex-col gap-2 p-4">- {Array.from({ length: 6 }).map((_, i) => (- <Skeleton key={i} className="h-10 w-full rounded-md" />- ))}- </div>- </div>+ )+ }+ />);}diff --git a/packages/views/issues/actions/use-issue-actions.ts b/packages/views/issues/actions/use-issue-actions.tsindex 235f4a2eaf..e443fc0ed2 100644--- a/packages/views/issues/actions/use-issue-actions.ts+++ b/packages/views/issues/actions/use-issue-actions.ts@@ -13,6 +13,7 @@ import { pinListOptions, useCreatePin, useDeletePin } from "@multica/core/pins";import { copyText } from "@multica/ui/lib/clipboard";import { useNavigation } from "../../navigation";import { useT } from "../../i18n";+import { useIssueSurfaceActionsOptional } from "../surface/actions-context";export interface UseIssueActionsResult {isPinned: boolean;@@ -51,6 +52,7 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {);const updateIssue = useUpdateIssue();+ const surfaceActions = useIssueSurfaceActionsOptional();const createPin = useCreatePin();const deletePin = useDeletePin();const openModal = useModalStore((s) => s.open);@@ -86,19 +88,25 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {});return;}- updateIssue.mutate(- { id: issueId, ...updates },- {- onError: (err) =>- toast.error(- err instanceof Error && err.message- ? err.message- : t(($) => $.detail.update_failed),- ),- },- );+ if (surfaceActions) {+ surfaceActions.updateIssue(issueId, updates, {+ errorMessage: t(($) => $.detail.update_failed),+ });+ } else {+ updateIssue.mutate(+ { id: issueId, ...updates },+ {+ onError: (err) =>+ toast.error(+ err instanceof Error && err.message+ ? err.message+ : t(($) => $.detail.update_failed),+ ),+ },+ );+ }},- [issueId, issueStatus, updateIssue, openModal, t],+ [issueId, issueStatus, surfaceActions, updateIssue, openModal, t],);const togglePin = useCallback(() => {@@ -144,20 +152,32 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {// error toast and the optimistic rollback (false confirmation).const removeParent = useCallback(() => {if (!issueId) return;- updateIssue.mutate(- { id: issueId, parent_issue_id: null, stage: null },- {- onSuccess: () =>- toast.success(t(($) => $.actions.remove_parent_issue_success)),- onError: (err) =>- toast.error(- err instanceof Error && err.message- ? err.message- : t(($) => $.detail.update_failed),- ),- },- );- }, [issueId, updateIssue, t]);+ if (surfaceActions) {+ surfaceActions.updateIssue(+ issueId,+ { parent_issue_id: null, stage: null },+ {+ onSuccess: () =>+ toast.success(t(($) => $.actions.remove_parent_issue_success)),+ errorMessage: t(($) => $.detail.update_failed),+ },+ );+ } else {+ updateIssue.mutate(+ { id: issueId, parent_issue_id: null, stage: null },+ {+ onSuccess: () =>+ toast.success(t(($) => $.actions.remove_parent_issue_success)),+ onError: (err) =>+ toast.error(+ err instanceof Error && err.message+ ? err.message+ : t(($) => $.detail.update_failed),+ ),+ },+ );+ }+ }, [issueId, surfaceActions, updateIssue, t]);const openAddChild = useCallback(() => {if (!issueId) return;diff --git a/packages/views/issues/components/batch-action-toolbar.tsx b/packages/views/issues/components/batch-action-toolbar.tsxindex f8bd81d832..75d33d8107 100644--- a/packages/views/issues/components/batch-action-toolbar.tsx+++ b/packages/views/issues/components/batch-action-toolbar.tsx@@ -15,13 +15,14 @@ import {AlertDialogTitle,} from "@multica/ui/components/ui/alert-dialog";import type { Issue, UpdateIssueRequest } from "@multica/core/types";-import { useIssueSelectionStore } from "@multica/core/issues/stores/selection-store";import { commonIssueFields } from "@multica/core/issues/batch";import { useBatchUpdateIssues, useBatchDeleteIssues } from "@multica/core/issues/mutations";import { useModalStore } from "@multica/core/modals";import { StatusPicker, PriorityPicker, AssigneePicker } from "./pickers";import { useT } from "../../i18n";import { cn } from "@multica/ui/lib/utils";+import { useIssueSurfaceActionsOptional } from "../surface/actions-context";+import { useIssueSurfaceSelection } from "../surface/selection-context";export function BatchActionToolbar({issues,@@ -29,9 +30,9 @@ export function BatchActionToolbar({}: {/*** The universe of selectable issues at this call site (the same list the- * rows are rendered from). The toolbar filters it by the global selection to- * reflect the real common status / priority / assignee of the selected- * issues, mirroring how the skill list filters its rows by `selectedIds`.+ * rows are rendered from). The toolbar filters it by the active surface+ * selection to reflect the real common status / priority / assignee of the+ * selected issues, mirroring how the skill list filters rows by `selectedIds`.*/issues: Issue[];/**@@ -43,8 +44,9 @@ export function BatchActionToolbar({placement?: "fixed-bottom" | "inline";}) {const { t } = useT("issues");- const selectedIds = useIssueSelectionStore((s) => s.selectedIds);- const clear = useIssueSelectionStore((s) => s.clear);+ const selection = useIssueSurfaceSelection();+ const selectedIds = selection.selectedIds;+ const clear = selection.clear;const count = selectedIds.size;// Reflect the real shared value of the selected issues in each picker; fall@@ -59,10 +61,12 @@ export function BatchActionToolbar({const [priorityOpen, setPriorityOpen] = useState(false);const [assigneeOpen, setAssigneeOpen] = useState(false);const [deleteOpen, setDeleteOpen] = useState(false);+ const surfaceActions = useIssueSurfaceActionsOptional();const batchUpdate = useBatchUpdateIssues();const batchDelete = useBatchDeleteIssues();const openModal = useModalStore((s) => s.open);- const loading = batchUpdate.isPending || batchDelete.isPending;+ const loading =+ surfaceActions?.isPending ?? (batchUpdate.isPending || batchDelete.isPending);if (count === 0) return null;@@ -70,7 +74,11 @@ export function BatchActionToolbar({const handleBatchUpdate = async (updates: Partial<UpdateIssueRequest>) => {try {- await batchUpdate.mutateAsync({ ids, updates });+ if (surfaceActions) {+ await surfaceActions.batchUpdate(ids, updates);+ } else {+ await batchUpdate.mutateAsync({ ids, updates });+ }toast.success(t(($) => $.batch.update_success, { count }));} catch (err) {toast.error(@@ -123,7 +131,11 @@ export function BatchActionToolbar({const handleBatchDelete = async () => {try {- await batchDelete.mutateAsync(ids);+ if (surfaceActions) {+ await surfaceActions.batchDelete(ids);+ } else {+ await batchDelete.mutateAsync(ids);+ }clear();toast.success(t(($) => $.batch.delete_success, { count }));} catch (err) {@@ -233,4 +245,3 @@ export function BatchActionToolbar({</>);}-diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsxindex fe0e19a9f2..b8c200fe6f 100644--- a/packages/views/issues/components/board-card.tsx+++ b/packages/views/issues/components/board-card.tsx@@ -5,18 +5,13 @@ import { AppLink } from "../../navigation";import { useSortable, defaultAnimateLayoutChanges } from "@dnd-kit/sortable";import type { AnimateLayoutChanges } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";-import { toast } from "sonner";-import type { Issue, UpdateIssueRequest } from "@multica/core/types";+import type { Issue, Project, UpdateIssueRequest } from "@multica/core/types";import { formatDateOnly, isPastDateOnly } from "@multica/core/issues/date";import { CalendarClock, CalendarDays } from "lucide-react";-import { useQuery } from "@tanstack/react-query";import { ActorAvatar } from "../../common/actor-avatar";-import { useUpdateIssue } from "@multica/core/issues/mutations";import { useWorkspacePaths } from "@multica/core/paths";-import { useWorkspaceId } from "@multica/core/hooks";import { useActorName } from "@multica/core/workspace/hooks";import { useTimeAgo } from "../../i18n";-import { projectListOptions } from "@multica/core/projects/queries";import { ProjectIcon } from "../../projects/components/project-icon";import { PriorityIcon } from "./priority-icon";import { PriorityPicker, AssigneePicker, StartDatePicker, DueDatePicker } from "./pickers";@@ -26,6 +21,7 @@ import type { ChildProgress } from "./list-row";import { IssueActionsContextMenu } from "../actions";import { LabelChip } from "../../labels/label-chip";import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";+import { useIssueSurfaceActionsOptional } from "../surface/actions-context";import { useT } from "../../i18n";function formatDate(date: string): string {@@ -60,39 +56,28 @@ export const BoardCardContent = memo(function BoardCardContent({issue,editable = false,childProgress,+ project,}: {issue: Issue;editable?: boolean;childProgress?: ChildProgress;+ project?: Project;}) {const { t } = useT("issues");const timeAgo = useTimeAgo();const storeProperties = useViewStore((s) => s.cardProperties);- const wsId = useWorkspaceId();- const { data: projects = [] } = useQuery({- ...projectListOptions(wsId),- enabled: storeProperties.project && !!issue.project_id,- });- const project = issue.project_id ? projects.find((p) => p.id === issue.project_id) : undefined;const labels = issue.labels ?? [];- const updateIssueMutation = useUpdateIssue();+ const surfaceActions = useIssueSurfaceActionsOptional();const handleUpdate = useCallback((updates: Partial<UpdateIssueRequest>) => {- updateIssueMutation.mutate(- { id: issue.id, ...updates },- {- onError: (err) =>- toast.error(- err instanceof Error && err.message- ? err.message- : t(($) => $.card.update_failed),- ),- },- );+ surfaceActions?.updateIssue(issue.id, updates, {+ errorMessage: t(($) => $.card.update_failed),+ });},- [issue.id, updateIssueMutation, t],+ [issue.id, surfaceActions, t],);+ const canEdit = editable && !!surfaceActions;const showPriority = storeProperties.priority;const showDescription = storeProperties.description && issue.description;@@ -114,7 +99,7 @@ export const BoardCardContent = memo(function BoardCardContent({const priorityLabel = t(($) => $.priority[issue.priority]);const priorityIconNode = showPriority ? (- editable ? (+ canEdit ? (<PickerWrapper><PriorityPickerpriority={issue.priority}@@ -161,7 +146,7 @@ export const BoardCardContent = memo(function BoardCardContent({);const assigneeNode = showAssigneeSection ? (- editable ? (+ canEdit ? (<PickerWrapper className={assigneeContainerClass}><AssigneePickerassigneeType={issue.assignee_type}@@ -230,7 +215,7 @@ export const BoardCardContent = memo(function BoardCardContent({{showRightMeta && (<div className="ml-auto flex shrink-0 items-center gap-2">{showStartDate && (- editable ? (+ canEdit ? (<PickerWrapper className="shrink-0"><StartDatePickerstartDate={issue.start_date}@@ -251,7 +236,7 @@ export const BoardCardContent = memo(function BoardCardContent({))}{showDueDate && (- editable ? (+ canEdit ? (<PickerWrapper className="shrink-0"><DueDatePickerdueDate={issue.due_date}@@ -310,7 +295,17 @@ const animateLayoutChanges: AnimateLayoutChanges = (args) => {return defaultAnimateLayoutChanges(args);};-export const DraggableBoardCard = memo(function DraggableBoardCard({ issue, childProgress, disableSorting }: { issue: Issue; childProgress?: ChildProgress; disableSorting?: boolean }) {+export const DraggableBoardCard = memo(function DraggableBoardCard({+ issue,+ childProgress,+ project,+ disableSorting,+}: {+ issue: Issue;+ childProgress?: ChildProgress;+ project?: Project;+ disableSorting?: boolean;+}) {const p = useWorkspacePaths();const {attributes,@@ -344,7 +339,12 @@ export const DraggableBoardCard = memo(function DraggableBoardCard({ issue, chilhref={p.issueDetail(issue.id)}className={`group block transition-colors ${isDragging ? "pointer-events-none" : ""}`}>- <BoardCardContent issue={issue} editable childProgress={childProgress} />+ <BoardCardContent+ issue={issue}+ editable+ childProgress={childProgress}+ project={project}+ /></AppLink></div></IssueActionsContextMenu>diff --git a/packages/views/issues/components/board-column.tsx b/packages/views/issues/components/board-column.tsxindex 354ba73600..544dc2c950 100644--- a/packages/views/issues/components/board-column.tsx+++ b/packages/views/issues/components/board-column.tsx@@ -5,7 +5,12 @@ import { EyeOff, MoreHorizontal, Plus, UserMinus } from "lucide-react";import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";import { useDroppable } from "@dnd-kit/core";import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable";-import type { Issue, IssueAssigneeType, IssueStatus } from "@multica/core/types";+import type {+ Issue,+ IssueAssigneeType,+ IssueStatus,+ Project,+} from "@multica/core/types";import { Button } from "@multica/ui/components/ui/button";import {DropdownMenu,@@ -14,13 +19,13 @@ import {DropdownMenuItem,} from "@multica/ui/components/ui/dropdown-menu";import { STATUS_CONFIG } from "@multica/core/issues/config";-import { useModalStore } from "@multica/core/modals";import { useViewStoreApi } from "@multica/core/issues/stores/view-store-context";import { StatusHeading } from "./status-heading";import { DraggableBoardCard } from "./board-card";import type { ChildProgress } from "./list-row";import { useT } from "../../i18n";import { ActorAvatar } from "../../common/actor-avatar";+import type { IssueCreateDefaults } from "../surface/types";// Insertion-position prediction intentionally omitted. The server's// ORDER BY uses PostgreSQL's en_US.utf8 collation (glibc), which@@ -37,7 +42,7 @@ export interface BoardColumnGroup {assigneeType?: IssueAssigneeType | null;assigneeId?: string | null;totalCount?: number;- createData?: Record<string, unknown>;+ createData?: IssueCreateDefaults;}export const BoardColumn = memo(function BoardColumn({@@ -45,19 +50,23 @@ export const BoardColumn = memo(function BoardColumn({issueIds,issueMap,childProgressMap,+ projectMap,totalCount,footer,projectId,+ onCreateIssue,sortLabel,}: {group: BoardColumnGroup;issueIds: string[];issueMap: Map<string, Issue>;childProgressMap?: Map<string, ChildProgress>;+ projectMap?: Map<string, Project>;totalCount?: number;footer?: ReactNode;/** When set, the per-column "+" pre-fills the project on the create form. */projectId?: string;+ onCreateIssue?: (defaults: IssueCreateDefaults) => void;sortLabel?: string | null;}) {const status = group.status;@@ -100,27 +109,29 @@ export const BoardColumn = memo(function BoardColumn({</DropdownMenuContent></DropdownMenu>)}- <Tooltip>- <TooltipTrigger- render={- <Button- variant="ghost"- size="icon-sm"- className="rounded-full text-muted-foreground"- onClick={() => {- const data = {- ...(group.createData ?? {}),- ...(projectId ? { project_id: projectId } : {}),- };- useModalStore.getState().open("create-issue", data);- }}- >- <Plus className="size-3.5" />- </Button>- }- />- <TooltipContent>{t(($) => $.board.add_issue_tooltip)}</TooltipContent>- </Tooltip>+ {onCreateIssue && (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ className="rounded-full text-muted-foreground"+ onClick={() => {+ const data = {+ ...(group.createData ?? {}),+ ...(projectId ? { project_id: projectId } : {}),+ };+ onCreateIssue(data);+ }}+ >+ <Plus className="size-3.5" />+ </Button>+ }+ />+ <TooltipContent>{t(($) => $.board.add_issue_tooltip)}</TooltipContent>+ </Tooltip>+ )}</div></div><div className="relative min-h-[200px] flex-1 rounded-lg">@@ -143,7 +154,15 @@ export const BoardColumn = memo(function BoardColumn({><SortableContext items={issueIds} strategy={verticalListSortingStrategy}>{resolvedIssues.map((issue) => (- <DraggableBoardCard key={issue.id} issue={issue} childProgress={childProgressMap?.get(issue.id)} disableSorting={!!sortLabel} />+ <DraggableBoardCard+ key={issue.id}+ issue={issue}+ childProgress={childProgressMap?.get(issue.id)}+ project={+ issue.project_id ? projectMap?.get(issue.project_id) : undefined+ }+ disableSorting={!!sortLabel}+ />))}</SortableContext>{issueIds.length === 0 && (diff --git a/packages/views/issues/components/board-view.tsx b/packages/views/issues/components/board-view.tsxindex 3748f96763..0de0278107 100644--- a/packages/views/issues/components/board-view.tsx+++ b/packages/views/issues/components/board-view.tsx@@ -13,7 +13,12 @@ import {} from "@dnd-kit/core";import type { QueryKey } from "@tanstack/react-query";import { arrayMove } from "@dnd-kit/sortable";-import type { Issue, IssueAssigneeGroup, IssueStatus } from "@multica/core/types";+import type {+ Issue,+ IssueAssigneeGroup,+ IssueStatus,+ Project,+} from "@multica/core/types";import { useLoadMoreByAssigneeGroup, useLoadMoreByStatus } from "@multica/core/issues/mutations";import type { AssigneeGroupedIssuesFilter, IssueSortParam, MyIssuesFilter } from "@multica/core/issues/queries";import { useViewStore } from "@multica/core/issues/stores/view-store-context";@@ -24,6 +29,7 @@ import { BoardCardContent } from "./board-card";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 { useDragSettle } from "./use-drag-settle";import { useT } from "../../i18n";import {@@ -119,10 +125,12 @@ export function BoardView({hiddenStatuses,onMoveIssue,childProgressMap = EMPTY_PROGRESS_MAP,+ projectMap,myIssuesScope,myIssuesFilter,sort,projectId,+ onCreateIssue,}: {issues: Issue[];assigneeGroups?: IssueAssigneeGroup[];@@ -132,6 +140,7 @@ export function BoardView({hiddenStatuses: IssueStatus[];onMoveIssue: (issueId: string, updates: DragMoveUpdates, onSettled?: () => void) => void;childProgressMap?: Map<string, ChildProgress>;+ projectMap?: Map<string, Project>;/** When set, per-status load-more targets the scoped cache instead of the workspace one. */myIssuesScope?: string;myIssuesFilter?: MyIssuesFilter;@@ -139,6 +148,7 @@ export function BoardView({sort?: IssueSortParam;/** When set, the per-column "+" pre-fills the project on the create form. */projectId?: string;+ onCreateIssue?: (defaults: IssueCreateDefaults) => void;}) {const { t } = useT("issues");const grouping = useViewStore((s) => s.grouping);@@ -418,9 +428,11 @@ export function BoardView({issueIds={columns[group.id] ?? EMPTY_IDS}issueMap={issueMapRef.current}childProgressMap={childProgressMap}+ projectMap={projectMap}myIssuesOpts={myIssuesOpts}sort={sort}projectId={projectId}+ onCreateIssue={onCreateIssue}sortLabel={sortLabel}/>) : (@@ -431,10 +443,12 @@ export function BoardView({issueIds={columns[group.id] ?? EMPTY_IDS}issueMap={issueMapRef.current}childProgressMap={childProgressMap}+ projectMap={projectMap}queryKey={assigneeGroupQueryKey}filter={assigneeGroupFilter}sort={sort}projectId={projectId}+ onCreateIssue={onCreateIssue}sortLabel={sortLabel}/>) : (@@ -444,7 +458,9 @@ export function BoardView({issueIds={columns[group.id] ?? EMPTY_IDS}issueMap={issueMapRef.current}childProgressMap={childProgressMap}+ projectMap={projectMap}projectId={projectId}+ onCreateIssue={onCreateIssue}totalCount={group.totalCount}sortLabel={sortLabel}/>@@ -465,7 +481,15 @@ export function BoardView({<DragOverlay dropAnimation={null}>{activeIssue ? (<div style={{ width: BOARD_CARD_WIDTH }} className="rotate-1 cursor-grabbing opacity-90 shadow-lg shadow-black/10">- <BoardCardContent issue={activeIssue} childProgress={childProgressMap.get(activeIssue.id)} />+ <BoardCardContent+ issue={activeIssue}+ childProgress={childProgressMap.get(activeIssue.id)}+ project={+ activeIssue.project_id+ ? projectMap?.get(activeIssue.project_id)+ : undefined+ }+ /></div>) : null}</DragOverlay>@@ -478,20 +502,24 @@ const PaginatedAssigneeBoardColumn = memo(function PaginatedAssigneeBoardColumn(issueIds,issueMap,childProgressMap,+ projectMap,queryKey,filter,sort,projectId,+ onCreateIssue,sortLabel,}: {group: BoardColumnGroup;issueIds: string[];issueMap: Map<string, Issue>;childProgressMap?: Map<string, ChildProgress>;+ projectMap?: Map<string, Project>;queryKey: QueryKey;filter: AssigneeGroupedIssuesFilter;sort?: IssueSortParam;projectId?: string;+ onCreateIssue?: (defaults: IssueCreateDefaults) => void;sortLabel?: string | null;}) {const { loadMore, hasMore, isLoading, total } = useLoadMoreByAssigneeGroup(@@ -510,8 +538,10 @@ const PaginatedAssigneeBoardColumn = memo(function PaginatedAssigneeBoardColumn(issueIds={issueIds}issueMap={issueMap}childProgressMap={childProgressMap}+ projectMap={projectMap}totalCount={total}projectId={projectId}+ onCreateIssue={onCreateIssue}sortLabel={sortLabel}footer={hasMore ? (@@ -527,18 +557,22 @@ const PaginatedBoardColumn = memo(function PaginatedBoardColumn({issueIds,issueMap,childProgressMap,+ projectMap,myIssuesOpts,sort,projectId,+ onCreateIssue,sortLabel,}: {group: BoardColumnGroup & { status: IssueStatus };issueIds: string[];issueMap: Map<string, Issue>;childProgressMap?: Map<string, ChildProgress>;+ projectMap?: Map<string, Project>;myIssuesOpts?: { scope: string; filter: MyIssuesFilter };sort?: IssueSortParam;projectId?: string;+ onCreateIssue?: (defaults: IssueCreateDefaults) => void;sortLabel?: string | null;}) {const { loadMore, hasMore, isLoading, total } = useLoadMoreByStatus(@@ -552,8 +586,10 @@ const PaginatedBoardColumn = memo(function PaginatedBoardColumn({issueIds={issueIds}issueMap={issueMap}childProgressMap={childProgressMap}+ projectMap={projectMap}totalCount={total}projectId={projectId}+ onCreateIssue={onCreateIssue}sortLabel={sortLabel}footer={hasMore ? (diff --git a/packages/views/issues/components/create-renderers.test.tsx b/packages/views/issues/components/create-renderers.test.tsxnew file mode 100644index 0000000000..d7378053fe--- /dev/null+++ b/packages/views/issues/components/create-renderers.test.tsx@@ -0,0 +1,151 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";+import { BoardColumn } from "./board-column";+import { ListView } from "./list-view";++const openModal = vi.hoisted(() => vi.fn());+const hideStatus = vi.hoisted(() => vi.fn());+const showStatus = vi.hoisted(() => vi.fn());+const select = vi.hoisted(() => vi.fn());+const deselect = vi.hoisted(() => vi.fn());++vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "ws-1",+}));++vi.mock("@multica/core/modals", () => ({+ useModalStore: {+ getState: () => ({ open: openModal }),+ },+}));++vi.mock("@multica/core/issues/stores/view-store-context", () => ({+ useViewStore: (selector?: any) => {+ const state = {+ grouping: "status",+ sortBy: "position",+ listCollapsedStatuses: [],+ toggleListCollapsed: vi.fn(),+ };+ return selector ? selector(state) : state;+ },+ useViewStoreApi: () => ({+ getState: () => ({ hideStatus, showStatus }),+ }),+}));++vi.mock("@multica/core/issues/mutations", () => ({+ useLoadMoreByStatus: () => ({+ total: 0,+ loaded: 0,+ hasMore: false,+ isLoading: false,+ loadMore: vi.fn(),+ }),+}));++vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({+ getActorName: (_type: string, id: string) => id,+ }),+}));++vi.mock("../surface/selection-context", () => ({+ useIssueSurfaceSelection: () => ({+ selectedIds: new Set<string>(),+ select,+ deselect,+ toggle: vi.fn(),+ clear: vi.fn(),+ }),+}));++vi.mock("../../i18n", () => ({+ useT: () => ({ t: () => "translated" }),+}));++vi.mock("@dnd-kit/core", () => ({+ DndContext: ({ children }: { children: React.ReactNode }) => children,+ DragOverlay: () => null,+ PointerSensor: class {},+ useSensor: () => ({}),+ useSensors: () => [],+ useDroppable: () => ({ setNodeRef: vi.fn(), isOver: false }),+}));++vi.mock("@dnd-kit/sortable", () => ({+ SortableContext: ({ children }: { children: React.ReactNode }) => children,+ verticalListSortingStrategy: {},+ arrayMove: <T,>(items: T[]) => items,+}));++vi.mock("@base-ui/react/accordion", () => ({+ Accordion: {+ Root: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+ Item: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+ Header: ({ children, className }: { children: React.ReactNode; className?: string }) => (+ <div className={className}>{children}</div>+ ),+ Trigger: ({ children, className }: { children: React.ReactNode; className?: string }) => (+ <button type="button" className={className}>+ {children}+ </button>+ ),+ Panel: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+ },+}));++beforeEach(() => {+ openModal.mockClear();+ hideStatus.mockClear();+ showStatus.mockClear();+ select.mockClear();+ deselect.mockClear();+});++describe("issue renderer create entrypoints", () => {+ it("routes board column create through the surface callback with local defaults", () => {+ const onCreateIssue = vi.fn();++ render(+ <BoardColumn+ group={{ id: "todo", title: "todo", status: "todo", createData: { status: "todo" } }}+ issueIds={[]}+ issueMap={new Map()}+ projectId="project-1"+ onCreateIssue={onCreateIssue}+ />,+ );++ const buttons = screen.getAllByRole("button");+ fireEvent.click(buttons[buttons.length - 1]!);++ expect(onCreateIssue).toHaveBeenCalledWith({+ status: "todo",+ project_id: "project-1",+ });+ expect(openModal).not.toHaveBeenCalled();+ });++ it("routes list status create through the surface callback with local defaults", () => {+ const onCreateIssue = vi.fn();++ render(+ <ListView+ issues={[]}+ visibleStatuses={["todo"]}+ projectId="project-1"+ onCreateIssue={onCreateIssue}+ />,+ );++ const buttons = screen.getAllByRole("button");+ fireEvent.click(buttons[buttons.length - 1]!);++ expect(onCreateIssue).toHaveBeenCalledWith({+ status: "todo",+ project_id: "project-1",+ });+ expect(openModal).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsxindex a5b1cc9bce..604045257e 100644--- a/packages/views/issues/components/issues-header.tsx+++ b/packages/views/issues/components/issues-header.tsx@@ -23,6 +23,7 @@ import {Waves,} from "lucide-react";import { Button } from "@multica/ui/components/ui/button";+import { Spinner } from "@multica/ui/components/ui/spinner";import {DropdownMenu,DropdownMenuTrigger,@@ -617,6 +618,33 @@ function DateSubContent({);}+// ---------------------------------------------------------------------------+// ViewRefreshIndicator+// ---------------------------------------------------------------------------++/**+ * Neutral "view is revalidating" slot for the header controls cluster.+ * Driven by the surface's isRefreshing (placeholder-backed revalidation:+ * sort/date change, grouped-board filter change) — trigger-agnostic on+ * purpose, so any view change that puts a request in flight lights it.+ *+ * The slot is fixed-width so appearing/disappearing never shifts the+ * controls; the 300ms appear delay keeps fast networks indicator-free+ * (NN/g: sub-second responses need no feedback) while slow ones get a+ * "working on it" signal instead of a dead click.+ */+export function ViewRefreshIndicator({ active }: { active: boolean }) {+ return (+ <span className="flex w-4 shrink-0 items-center justify-center">+ {active && (+ <span className="animate-in fade-in fill-mode-backwards [animation-delay:300ms]">+ <Spinner className="size-3.5 text-muted-foreground" />+ </span>+ )}+ </span>+ );+}+// ---------------------------------------------------------------------------// IssuesHeader// ---------------------------------------------------------------------------@@ -626,11 +654,13 @@ export function IssuesHeader({allowGantt = false,dateFilter = null,onDateFilterChange,+ isRefreshing = false,}: {scopedIssues: Issue[];allowGantt?: boolean;dateFilter?: IssueDateFilter | null;onDateFilterChange?: (filter: IssueDateFilter | null) => void;+ isRefreshing?: boolean;}) {const { t } = useT("issues");const scope = useIssuesScopeStore((s) => s.scope);@@ -733,6 +763,7 @@ export function IssuesHeader({dateFilter={dateFilter}onDateFilterChange={onDateFilterChange}/>+ <ViewRefreshIndicator active={isRefreshing} /></div></div></div>diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsxindex e0d17496a2..c0b476836d 100644--- a/packages/views/issues/components/issues-page.test.tsx+++ b/packages/views/issues/components/issues-page.test.tsx@@ -593,15 +593,26 @@ describe("IssuesPage (shared)", () => {expect(screen.getByText("Agents")).toBeInTheDocument();});+ // The Members/Agents tabs filter server-side via assignee_types (the same+ // param the grouped endpoint takes), so the mock mirrors the server's+ // WHERE clause instead of a client-side post-filter.+ function mockListIssuesHonoringAssigneeTypes() {+ mockListIssues.mockImplementation((params: any) => {+ const matches = mockIssues.filter(+ (i) =>+ i.status === params?.status &&+ (!params?.assignee_types ||+ (i.assignee_type !== null &&+ params.assignee_types.includes(i.assignee_type))),+ );+ return Promise.resolve({ issues: matches, total: matches.length });+ });+ }+it("agents scope includes squad-assigned issues", async () => {mockScope = "agents";mockViewState.viewMode = "list";- mockListIssues.mockImplementation((params: any) =>- Promise.resolve({- issues: mockIssues.filter((i) => i.status === params?.status),- total: mockIssues.filter((i) => i.status === params?.status).length,- }),- );+ mockListIssuesHonoringAssigneeTypes();renderWithQuery(<IssuesPage />);// Squad task and agent task should be visible@@ -609,21 +620,22 @@ describe("IssuesPage (shared)", () => {expect(screen.getByText("Squad task")).toBeInTheDocument();// Member task should NOT be visibleexpect(screen.queryByText("Implement auth")).not.toBeInTheDocument();+ expect(mockListIssues).toHaveBeenCalledWith(+ expect.objectContaining({ assignee_types: ["agent", "squad"] }),+ );});it("members scope excludes squad-assigned issues", async () => {mockScope = "members";mockViewState.viewMode = "list";- mockListIssues.mockImplementation((params: any) =>- Promise.resolve({- issues: mockIssues.filter((i) => i.status === params?.status),- total: mockIssues.filter((i) => i.status === params?.status).length,- }),- );+ mockListIssuesHonoringAssigneeTypes();renderWithQuery(<IssuesPage />);await screen.findByText("Implement auth");expect(screen.queryByText("Squad task")).not.toBeInTheDocument();expect(screen.queryByText("Design landing page")).not.toBeInTheDocument();+ expect(mockListIssues).toHaveBeenCalledWith(+ expect.objectContaining({ assignee_types: ["member"] }),+ );});});diff --git a/packages/views/issues/components/issues-page.tsx b/packages/views/issues/components/issues-page.tsxindex 51d36d8def..bd188cacd3 100644--- a/packages/views/issues/components/issues-page.tsx+++ b/packages/views/issues/components/issues-page.tsx@@ -1,256 +1,37 @@"use client";-import { useCallback, useEffect, useMemo } from "react";-import { toast } from "sonner";import { ListTodo } from "lucide-react";-import type { UpdateIssueRequest } from "@multica/core/types";-import { Skeleton } from "@multica/ui/components/ui/skeleton";-import { useQuery } from "@tanstack/react-query";-import { useIssueViewStore, useClearFiltersOnWorkspaceChange, type IssueDateFilter } from "@multica/core/issues/stores/view-store";-import { dateOnlyToLocalDate } from "@multica/core/issues/date";+import type { Issue } from "@multica/core/types";import { useIssuesScopeStore } from "@multica/core/issues/stores/issues-scope-store";-import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";-import { filterIssues, filterAssigneeGroups } from "../utils/filter";-import { BOARD_STATUSES } from "@multica/core/issues/config";-import { useWorkspaceId } from "@multica/core/hooks";-import { issueAssigneeGroupsOptions, issueListOptions, childIssueProgressOptions, type AssigneeGroupedIssuesFilter } from "@multica/core/issues/queries";-import { agentTaskSnapshotOptions } from "@multica/core/agents";-import { useUpdateIssue } from "@multica/core/issues/mutations";-import { useIssueSelectionStore } from "@multica/core/issues/stores/selection-store";+import { useViewStore } from "@multica/core/issues/stores/view-store-context";import { PageHeader } from "../../layout/page-header";-import { IssuesHeader } from "./issues-header";-import { BoardView } from "./board-view";-import { ListView } from "./list-view";-import { SwimLaneView } from "./swimlane-view";-import { BatchActionToolbar } from "./batch-action-toolbar";-import type { ChildProgress } from "./list-row";import { useT } from "../../i18n";+import { IssueSurface } from "../surface/issue-surface";+import { IssuesHeader } from "./issues-header";-const EMPTY_CHILD_PROGRESS = new Map<string, ChildProgress>();--function issueDateFilterToApiParams(filter: IssueDateFilter | null) {- if (!filter) return {};-- const from = dateOnlyToLocalDate(filter.from);- const to = dateOnlyToLocalDate(filter.to);- if (!from || !to) return {};-- const start = from <= to ? from : to;- const endSource = from <= to ? to : from;- const end = new Date(endSource);- end.setDate(end.getDate() + 1);+function IssuesSurfaceHeader({+ issues,+ isRefreshing,+}: {+ issues: Issue[];+ isRefreshing: boolean;+}) {+ const dateFilter = useViewStore((s) => s.dateFilter);+ const setDateFilter = useViewStore((s) => s.setDateFilter);- return {- date_field: filter.field,- date_start: start.toISOString(),- date_end: end.toISOString(),- };+ return (+ <IssuesHeader+ scopedIssues={issues}+ dateFilter={dateFilter}+ onDateFilterChange={setDateFilter}+ isRefreshing={isRefreshing}+ />+ );}export function IssuesPage() {const { t } = useT("issues");- const wsId = useWorkspaceId();-const scope = useIssuesScopeStore((s) => s.scope);- const viewMode = useIssueViewStore((s) => s.viewMode);- const dateFilter = useIssueViewStore((s) => s.dateFilter);- const setDateFilter = useIssueViewStore((s) => s.setDateFilter);- const grouping = useIssueViewStore((s) => s.grouping);- const statusFilters = useIssueViewStore((s) => s.statusFilters);- const priorityFilters = useIssueViewStore((s) => s.priorityFilters);- const assigneeFilters = useIssueViewStore((s) => s.assigneeFilters);- const includeNoAssignee = useIssueViewStore((s) => s.includeNoAssignee);- const creatorFilters = useIssueViewStore((s) => s.creatorFilters);- const projectFilters = useIssueViewStore((s) => s.projectFilters);- const includeNoProject = useIssueViewStore((s) => s.includeNoProject);- const labelFilters = useIssueViewStore((s) => s.labelFilters);- const sortBy = useIssueViewStore((s) => s.sortBy);- const sortDirection = useIssueViewStore((s) => s.sortDirection);- const agentRunningFilter = useIssueViewStore((s) => s.agentRunningFilter);- const showSubIssues = useIssueViewStore((s) => s.showSubIssues);- const usesAssigneeBoard = viewMode === "board" && grouping === "assignee";-- const sort = useMemo(- () => ({- sort_by: sortBy,- sort_direction: sortBy !== "position" ? sortDirection : undefined,- } as const),- [sortBy, sortDirection],- );- const dateParams = useMemo(- () => issueDateFilterToApiParams(dateFilter),- [dateFilter],- );- const queryParams = useMemo(- () => ({ ...sort, ...dateParams }),- [dateParams, sort],- );-- // Derive the set of issue ids that currently have at least one- // `running` agent task. Used by the workspace agents-working filter- // chip. Subscribing the page here (not deep in filter.ts) keeps the- // filter pure and lets the snapshot stay cached at one workspace-- // scoped place — every issue card already subscribes for its own- // indicator, so this is a no-op extra fetch.- const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));- const runningIssueIds = useMemo(() => {- const ids = new Set<string>();- for (const t of snapshot) {- if (t.status === "running" && t.issue_id) ids.add(t.issue_id);- }- return ids;- }, [snapshot]);-- const assigneeGroupFilter = useMemo<AssigneeGroupedIssuesFilter>(() => {- const filter: AssigneeGroupedIssuesFilter = {- statuses: statusFilters.length > 0 ? statusFilters : [...BOARD_STATUSES],- priorities: priorityFilters,- assignee_filters: assigneeFilters,- include_no_assignee: includeNoAssignee,- creator_filters: creatorFilters,- project_ids: projectFilters,- include_no_project: includeNoProject,- label_ids: labelFilters,- };- if (scope === "members") filter.assignee_types = ["member"];- if (scope === "agents") filter.assignee_types = ["agent", "squad"];- return filter;- }, [assigneeFilters, creatorFilters, includeNoAssignee, includeNoProject, labelFilters, priorityFilters, projectFilters, scope, statusFilters]);-- const assigneeGroupsOptions = issueAssigneeGroupsOptions(wsId, assigneeGroupFilter, queryParams);- const statusIssuesQuery = useQuery({- ...issueListOptions(wsId, queryParams),- enabled: !usesAssigneeBoard,- });- const assigneeGroupsQuery = useQuery({- ...assigneeGroupsOptions,- enabled: usesAssigneeBoard,- });- const allIssues = useMemo(- () => statusIssuesQuery.data ?? [],- [statusIssuesQuery.data],- );- const assigneeIssues = useMemo(- () => assigneeGroupsQuery.data?.groups.flatMap((group) => group.issues) ?? [],- [assigneeGroupsQuery.data],- );- // Assignee-grouped board renders from `groups`, bypassing the flat- // `filterIssues` output, so re-apply the client-only "Show sub-issues"- // toggle here (see filterAssigneeGroups).- const filteredAssigneeGroups = useMemo(- () => filterAssigneeGroups(assigneeGroupsQuery.data?.groups, { showSubIssues }),- [assigneeGroupsQuery.data, showSubIssues],- );- const filteredAssigneeIssues = useMemo(- () => filteredAssigneeGroups?.flatMap((group) => group.issues) ?? [],- [filteredAssigneeGroups],- );- const loading = usesAssigneeBoard- ? assigneeGroupsQuery.isLoading- : statusIssuesQuery.isLoading;-- // Clear filter state when switching between workspaces (URL-driven).- useClearFiltersOnWorkspaceChange(useIssueViewStore, wsId);-- useEffect(() => {- useIssueSelectionStore.getState().clear();- }, [viewMode, scope]);-- // Scope pre-filter: narrow by assignee type- const scopedIssues = useMemo(() => {- if (scope === "members")- return allIssues.filter((i) => i.assignee_type === "member");- if (scope === "agents")- return allIssues.filter((i) => i.assignee_type === "agent" || i.assignee_type === "squad");- return allIssues;- }, [allIssues, scope]);-- const headerIssues = usesAssigneeBoard ? assigneeIssues : scopedIssues;-- const issues = useMemo(- () => filterIssues(scopedIssues, { statusFilters, priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters, projectFilters, includeNoProject, labelFilters, agentRunningFilter, runningIssueIds, showSubIssues }),- [scopedIssues, statusFilters, priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters, projectFilters, includeNoProject, labelFilters, agentRunningFilter, runningIssueIds, showSubIssues],- );-- // Status-unfiltered companion for Swimlane — same narrowing as `issues`- // minus the status filter.- const swimlaneIssues = useMemo(- () => filterIssues(scopedIssues, { statusFilters: [], priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters, projectFilters, includeNoProject, labelFilters, agentRunningFilter, runningIssueIds, showSubIssues }),- [scopedIssues, priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters, projectFilters, includeNoProject, labelFilters, agentRunningFilter, runningIssueIds, showSubIssues],- );-- const activeFilters = useMemo(() => ({- priorityFilters,- assigneeFilters,- includeNoAssignee,- creatorFilters,- projectFilters,- includeNoProject,- labelFilters,- agentRunningFilter,- showSubIssues,- }), [- priorityFilters,- assigneeFilters,- includeNoAssignee,- creatorFilters,- projectFilters,- includeNoProject,- labelFilters,- agentRunningFilter,- showSubIssues,- ]);-- // Fetch sub-issue progress from the backend so counts are accurate- // regardless of client-side pagination or filtering of done issues.- const { data: childProgressMap = EMPTY_CHILD_PROGRESS } = useQuery(childIssueProgressOptions(wsId));-- const visibleStatuses = useMemo(() => {- if (statusFilters.length > 0)- return BOARD_STATUSES.filter((s) => statusFilters.includes(s));- return BOARD_STATUSES;- }, [statusFilters]);-- const hiddenStatuses = useMemo(() => {- return BOARD_STATUSES.filter((s) => !visibleStatuses.includes(s));- }, [visibleStatuses]);-- const updateIssueMutation = useUpdateIssue();- const handleMoveIssue = useCallback(- (issueId: string, updates: Pick<UpdateIssueRequest, "status" | "assignee_type" | "assignee_id" | "position" | "parent_issue_id">, onSettled?: () => void) => {- updateIssueMutation.mutate(- { id: issueId, ...updates },- {- onError: (err) =>- toast.error(- err instanceof Error && err.message- ? err.message- : t(($) => $.page.move_failed),- ),- onSettled: () => onSettled?.(),- },- );- },- [updateIssueMutation, t],- );-- const contentSkeleton = viewMode === "list" ? (- <div className="flex-1 min-h-0 overflow-y-auto p-2 space-y-1">- {Array.from({ length: 4 }).map((_, i) => (- <Skeleton key={i} className="h-10 w-full rounded-lg" />- ))}- </div>- ) : (- <div className="flex flex-1 min-h-0 gap-4 overflow-x-auto p-4">- {Array.from({ length: 5 }).map((_, i) => (- <div key={i} className="flex min-w-52 flex-1 flex-col gap-2">- <Skeleton className="h-4 w-20" />- <Skeleton className="h-24 w-full rounded-lg" />- <Skeleton className="h-24 w-full rounded-lg" />- </div>- ))}- </div>- );return (<div className="flex flex-1 min-h-0 flex-col">@@ -259,51 +40,24 @@ export function IssuesPage() {<h1 className="text-sm font-medium">{t(($) => $.page.breadcrumb_title)}</h1></PageHeader>- <ViewStoreProvider store={useIssueViewStore}>- <IssuesHeader- scopedIssues={headerIssues}- dateFilter={dateFilter}- onDateFilterChange={setDateFilter}- />-- {loading ? contentSkeleton : headerIssues.length === 0 ? (+ <IssueSurface+ scope={{ type: "workspace", actorKind: scope }}+ modes={["board", "list", "swimlane"]}+ batchToolbar="list"+ renderHeader={({ controller }) => (+ <IssuesSurfaceHeader+ issues={controller.surfaceIssues}+ isRefreshing={controller.isRefreshing}+ />+ )}+ renderEmpty={() => (<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">{t(($) => $.page.empty_title)}</p><p className="text-xs">{t(($) => $.page.empty_hint)}</p></div>- ) : (- <div className="flex flex-col flex-1 min-h-0">- {viewMode === "board" ? (- <BoardView- issues={usesAssigneeBoard ? filteredAssigneeIssues : issues}- assigneeGroups={usesAssigneeBoard ? filteredAssigneeGroups : undefined}- assigneeGroupQueryKey={usesAssigneeBoard ? assigneeGroupsOptions.queryKey : undefined}- assigneeGroupFilter={usesAssigneeBoard ? assigneeGroupFilter : undefined}- visibleStatuses={visibleStatuses}- hiddenStatuses={hiddenStatuses}- onMoveIssue={handleMoveIssue}- childProgressMap={childProgressMap}- sort={queryParams}- />- ) : viewMode === "swimlane" ? (- <SwimLaneView- issues={issues}- unfilteredIssues={swimlaneIssues}- activeFilters={activeFilters}- visibleStatuses={visibleStatuses}- hiddenStatuses={hiddenStatuses}- onMoveIssue={handleMoveIssue}- childProgressMap={childProgressMap}- sort={queryParams}- />- ) : (- <ListView issues={issues} visibleStatuses={visibleStatuses} childProgressMap={childProgressMap} sort={queryParams} onMoveIssue={handleMoveIssue} />- )}- </div>)}- {viewMode === "list" && <BatchActionToolbar issues={issues} />}- </ViewStoreProvider>+ /></div>);}diff --git a/packages/views/issues/components/list-row.tsx b/packages/views/issues/components/list-row.tsxindex 4b25113588..7d06b7cfd7 100644--- a/packages/views/issues/components/list-row.tsx+++ b/packages/views/issues/components/list-row.tsx@@ -1,25 +1,22 @@"use client";import { memo, type Ref } from "react";-import { useQuery } from "@tanstack/react-query";import { useSortable, defaultAnimateLayoutChanges } from "@dnd-kit/sortable";import type { AnimateLayoutChanges } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";import { AppLink } from "../../navigation";-import type { Issue } from "@multica/core/types";+import type { Issue, Project } from "@multica/core/types";import { formatDateOnly } from "@multica/core/issues/date";import { ActorAvatar } from "../../common/actor-avatar";-import { useIssueSelectionStore } from "@multica/core/issues/stores/selection-store";import { useWorkspacePaths } from "@multica/core/paths";-import { useWorkspaceId } from "@multica/core/hooks";import { useViewStore } from "@multica/core/issues/stores/view-store-context";-import { projectListOptions } from "@multica/core/projects/queries";import { ProjectIcon } from "../../projects/components/project-icon";import { PriorityIcon } from "./priority-icon";import { ProgressRing } from "./progress-ring";import { IssueActionsContextMenu } from "../actions";import { LabelChip } from "../../labels/label-chip";import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";+import { useIssueSurfaceSelection } from "../surface/selection-context";export interface ChildProgress {done: number;@@ -33,6 +30,7 @@ function formatDate(date: string): string {function ListRowContent({issue,childProgress,+ project,isDragging,containerRef,containerStyle,@@ -41,22 +39,18 @@ function ListRowContent({}: {issue: Issue;childProgress?: ChildProgress;+ project?: Project;isDragging?: boolean;containerRef?: Ref<HTMLDivElement>;containerStyle?: React.CSSProperties;containerProps?: Record<string, unknown>;checkboxProps?: Pick<React.HTMLAttributes<HTMLDivElement>, "onClick" | "onMouseDown" | "onPointerDown">;}) {- const selected = useIssueSelectionStore((s) => s.selectedIds.has(issue.id));- const toggle = useIssueSelectionStore((s) => s.toggle);+ const selection = useIssueSurfaceSelection();+ const selected = selection.selectedIds.has(issue.id);+ const toggle = selection.toggle;const p = useWorkspacePaths();const storeProperties = useViewStore((s) => s.cardProperties);- const wsId = useWorkspaceId();- const { data: projects = [] } = useQuery({- ...projectListOptions(wsId),- enabled: storeProperties.project && !!issue.project_id,- });- const project = issue.project_id ? projects.find((pr) => pr.id === issue.project_id) : undefined;const labels = issue.labels ?? [];const showProject = storeProperties.project && project;@@ -158,11 +152,19 @@ function ListRowContent({export const ListRow = memo(function ListRow({issue,childProgress,+ project,}: {issue: Issue;childProgress?: ChildProgress;+ project?: Project;}) {- return <ListRowContent issue={issue} childProgress={childProgress} />;+ return (+ <ListRowContent+ issue={issue}+ childProgress={childProgress}+ project={project}+ />+ );});const animateLayoutChanges: AnimateLayoutChanges = (args) => {@@ -178,10 +180,12 @@ const stopDrag = (e: React.SyntheticEvent) => {export const DraggableListRow = memo(function DraggableListRow({issue,childProgress,+ project,disableSorting,}: {issue: Issue;childProgress?: ChildProgress;+ project?: Project;disableSorting?: boolean;}) {const {@@ -207,6 +211,7 @@ export const DraggableListRow = memo(function DraggableListRow({<ListRowContentissue={issue}childProgress={childProgress}+ project={project}isDragging={isDragging}containerRef={setNodeRef}containerStyle={style}diff --git a/packages/views/issues/components/list-view.tsx b/packages/views/issues/components/list-view.tsxindex 1f12ed61b3..0e0c60b876 100644--- a/packages/views/issues/components/list-view.tsx+++ b/packages/views/issues/components/list-view.tsx@@ -17,12 +17,10 @@ import {import { SortableContext, verticalListSortingStrategy, arrayMove } from "@dnd-kit/sortable";import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";import { Button } from "@multica/ui/components/ui/button";-import type { Issue, IssueStatus } from "@multica/core/types";+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 { useModalStore } from "@multica/core/modals";import { useViewStore } from "@multica/core/issues/stores/view-store-context";-import { useIssueSelectionStore } from "@multica/core/issues/stores/selection-store";import { StatusHeading } from "./status-heading";import { ListRow, DraggableListRow, type ChildProgress } from "./list-row";import { useDragSettle } from "./use-drag-settle";@@ -40,6 +38,8 @@ import {getMoveUpdates,} from "../utils/drag-utils";import type { BoardColumnGroup } from "./board-column";+import { useIssueSurfaceSelection } from "../surface/selection-context";+import type { IssueCreateDefaults } from "../surface/types";const EMPTY_PROGRESS_MAP = new Map<string, ChildProgress>();const EMPTY_IDS: string[] = [];@@ -57,19 +57,23 @@ export function ListView({issues,visibleStatuses,childProgressMap = EMPTY_PROGRESS_MAP,+ projectMap,myIssuesScope,myIssuesFilter,projectId,onMoveIssue,+ onCreateIssue,sort,}: {issues: Issue[];visibleStatuses: IssueStatus[];childProgressMap?: Map<string, ChildProgress>;+ projectMap?: Map<string, Project>;myIssuesScope?: string;myIssuesFilter?: MyIssuesFilter;projectId?: string;onMoveIssue?: (issueId: string, updates: DragMoveUpdates, onSettled?: () => void) => void;+ onCreateIssue?: (defaults: IssueCreateDefaults) => void;sort?: IssueSortParam;}) {const listCollapsedStatuses = useViewStore(@@ -315,8 +319,10 @@ export function ListView({issueIds={columns[statusGroupId(status)] ?? EMPTY_IDS}issueMap={issueMapRef.current}childProgressMap={childProgressMap}+ projectMap={projectMap}myIssuesOpts={myIssuesOpts}projectId={projectId}+ onCreateIssue={onCreateIssue}dragEnabled={dragEnabled}isExpanded={isExpanded}sortLabel={sortLabel}@@ -364,8 +370,10 @@ function StatusAccordionItem({issueIds,issueMap,childProgressMap,+ projectMap,myIssuesOpts,projectId,+ onCreateIssue,dragEnabled,isExpanded,sortLabel,@@ -375,17 +383,20 @@ function StatusAccordionItem({issueIds: string[];issueMap: Map<string, Issue>;childProgressMap: Map<string, ChildProgress>;+ projectMap?: Map<string, Project>;myIssuesOpts?: { scope: string; filter: MyIssuesFilter };projectId?: string;+ onCreateIssue?: (defaults: IssueCreateDefaults) => void;dragEnabled: boolean;isExpanded: boolean;sortLabel: string | null;sort?: IssueSortParam;}) {const { t } = useT("issues");- const selectedIds = useIssueSelectionStore((s) => s.selectedIds);- const select = useIssueSelectionStore((s) => s.select);- const deselect = useIssueSelectionStore((s) => s.deselect);+ const selection = useIssueSurfaceSelection();+ const selectedIds = selection.selectedIds;+ const select = selection.select;+ const deselect = selection.deselect;const { loadMore, hasMore, isLoading, total } = useLoadMoreByStatus(status,myIssuesOpts,@@ -441,27 +452,31 @@ function StatusAccordionItem({<ChevronRight className="size-3.5 shrink-0 text-muted-foreground transition-transform group-aria-expanded/trigger:rotate-90" /><StatusHeading status={status} count={total} /></Accordion.Trigger>- <div className="pr-2">- <Tooltip>- <TooltipTrigger- render={- <Button- variant="ghost"- size="icon-sm"- className="rounded-full text-muted-foreground opacity-0 group-hover/header:opacity-100 transition-opacity"- onClick={() =>- useModalStore- .getState()- .open("create-issue", { status, ...(projectId ? { project_id: projectId } : {}) })- }- />- }- >- <Plus className="size-3.5" />- </TooltipTrigger>- <TooltipContent>{t(($) => $.list.add_issue_tooltip)}</TooltipContent>- </Tooltip>- </div>+ {onCreateIssue && (+ <div className="pr-2">+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ className="rounded-full text-muted-foreground opacity-0 group-hover/header:opacity-100 transition-opacity"+ onClick={() => {+ const defaults = {+ status,+ ...(projectId ? { project_id: projectId } : {}),+ };+ onCreateIssue(defaults);+ }}+ />+ }+ >+ <Plus className="size-3.5" />+ </TooltipTrigger>+ <TooltipContent>{t(($) => $.list.add_issue_tooltip)}</TooltipContent>+ </Tooltip>+ </div>+ )}</Accordion.Header><Accordion.Panel>{issues.length > 0 ? (@@ -472,6 +487,9 @@ function StatusAccordionItem({key={issue.id}issue={issue}childProgress={childProgressMap.get(issue.id)}+ project={+ issue.project_id ? projectMap?.get(issue.project_id) : undefined+ }disableSorting={disableSorting}/>))}@@ -482,7 +500,14 @@ function StatusAccordionItem({) : (<>{issues.map((issue) => (- <ListRow key={issue.id} issue={issue} childProgress={childProgressMap.get(issue.id)} />+ <ListRow+ key={issue.id}+ issue={issue}+ childProgress={childProgressMap.get(issue.id)}+ project={+ issue.project_id ? projectMap?.get(issue.project_id) : undefined+ }+ />))}{hasMore && (<InfiniteScrollSentinel onVisible={loadMore} loading={isLoading} />diff --git a/packages/views/issues/components/swimlane-view.test.tsx b/packages/views/issues/components/swimlane-view.test.tsxindex ae9fe65bdb..edb423a0df 100644--- a/packages/views/issues/components/swimlane-view.test.tsx+++ b/packages/views/issues/components/swimlane-view.test.tsx@@ -47,18 +47,12 @@ vi.mock("@multica/core/paths", async () => {};});-// Stub backend-bound queries that the swimlane invokes for project /-// assignee groupings. The hook MUST return a stable reference each call+// Stub backend-bound hooks that the swimlane invokes for assignee groupings.+// The hook MUST return a stable reference each call// — production `useActorName` wraps its returns in `useMemo`, and the// swimlane feeds the result into a `useMemo(..., [getActorName, ...])`// that then drives a `useEffect(setLocalCells, [cells])` chain. A fresh// object per render therefore loops the effect indefinitely.-vi.mock("@multica/core/projects/queries", () => ({- projectListOptions: (_wsId: string) => ({- queryKey: ["projects", _wsId, "list"],- queryFn: () => Promise.resolve([]),- }),-}));const { mockActorNameResult } = vi.hoisted(() => ({mockActorNameResult: {getActorName: (_type: string, _id: string) => "Mock Actor",@@ -409,11 +403,13 @@ describe("SwimLaneView", () => {expect(screen.getByText("Child Issue 1")).toBeInTheDocument();});- it("triggers modal open when add button is clicked", () => {+ it("calls the create callback when add button is clicked", () => {+ const onCreateIssue = vi.fn();renderWithI18n(<SwimLaneViewissues={mockIssues}onMoveIssue={vi.fn()}+ onCreateIssue={onCreateIssue}/>,);@@ -421,25 +417,48 @@ describe("SwimLaneView", () => {expect(addButtons.length).toBeGreaterThan(0);fireEvent.click(addButtons[0]!);- expect(mockOpenModal).toHaveBeenCalledWith("create-issue", expect.any(Object));+ expect(onCreateIssue).toHaveBeenCalledWith(expect.any(Object));+ expect(mockOpenModal).not.toHaveBeenCalled();});it("includes project_id in the create payload when projectId prop is set", () => {+ const onCreateIssue = vi.fn();+ renderWithI18n(+ <SwimLaneView+ issues={mockIssues}+ onMoveIssue={vi.fn()}+ projectId="proj-42"+ onCreateIssue={onCreateIssue}+ />,+ );++ const addButtons = screen.getAllByRole("button", { name: /add issue/i });+ fireEvent.click(addButtons[0]!);++ expect(onCreateIssue).toHaveBeenCalledWith(+ expect.objectContaining({ project_id: "proj-42" }),+ );+ expect(mockOpenModal).not.toHaveBeenCalled();+ });++ it("routes add button through the surface create callback when provided", () => {+ const onCreateIssue = vi.fn();renderWithI18n(<SwimLaneViewissues={mockIssues}onMoveIssue={vi.fn()}projectId="proj-42"+ onCreateIssue={onCreateIssue}/>,);const addButtons = screen.getAllByRole("button", { name: /add issue/i });fireEvent.click(addButtons[0]!);- expect(mockOpenModal).toHaveBeenCalledWith(- "create-issue",+ expect(onCreateIssue).toHaveBeenCalledWith(expect.objectContaining({ project_id: "proj-42" }),);+ expect(mockOpenModal).not.toHaveBeenCalled();});// A child whose parent isn't in the loaded set — lands in "Other parents".@@ -481,6 +500,7 @@ describe("SwimLaneView", () => {<SwimLaneViewissues={[...mockIssues, orphanChild]}onMoveIssue={vi.fn()}+ onCreateIssue={vi.fn()}/>,);@@ -1063,10 +1083,9 @@ describe("SwimLaneView", () => {// No-project pinned lane is always present.expect(screen.getAllByText("No project").length).toBeGreaterThanOrEqual(1);- // Both issue cards from real projects render — production fetches- // project titles from the API; in tests the mocked listProjects- // returns [] so the lane headers fall back to an empty title and- // we assert on card visibility, not lane title text.+ // Both issue cards from real projects render. The component receives+ // project metadata from its parent, so this standalone test asserts on+ // card visibility rather than lane title text.expect(screen.getByText("Issue A")).toBeInTheDocument();expect(screen.getByText("Issue B")).toBeInTheDocument();expect(screen.getByText("Issue C")).toBeInTheDocument();diff --git a/packages/views/issues/components/swimlane-view.tsx b/packages/views/issues/components/swimlane-view.tsxindex c82b6a3129..785a572a52 100644--- a/packages/views/issues/components/swimlane-view.tsx+++ b/packages/views/issues/components/swimlane-view.tsx@@ -32,7 +32,6 @@ import { filterIssues, type IssueFilters } from "../utils/filter";import type { SwimlaneGrouping } from "@multica/core/issues/stores/view-store";import { useWorkspacePaths } from "@multica/core/paths";import { useWorkspaceId } from "@multica/core/hooks";-import { projectListOptions } from "@multica/core/projects/queries";import { useActorName } from "@multica/core/workspace/hooks";import { useLoadMoreByStatus } from "@multica/core/issues/mutations";import { childrenByParentsOptions, issueKeys, type IssueSortParam, type MyIssuesFilter } from "@multica/core/issues/queries";@@ -44,7 +43,6 @@ import {} from "@multica/ui/components/ui/dropdown-menu";import { sortIssues } from "../utils/sort";import { BOARD_STATUSES, STATUS_CONFIG } from "@multica/core/issues/config";-import { useModalStore } from "@multica/core/modals";import { DraggableBoardCard, BoardCardContent } from "./board-card";import { StatusIcon } from "./status-icon";import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";@@ -57,6 +55,8 @@ import { ProjectIcon } from "../../projects/components/project-icon";import { ActorAvatar } from "../../common/actor-avatar";import type { ChildProgress } from "./list-row";import { useT } from "../../i18n";+import type { IssueActivityState } from "../surface/activity";+import type { IssueCreateDefaults } from "../surface/types";const COLUMN_WIDTH = 280;const COLUMN_GAP = 16;@@ -220,10 +220,10 @@ interface LaneGroup {}const EMPTY_PROGRESS_MAP = new Map<string, ChildProgress>();-const EMPTY_PROJECTS: Project[] = [];// Stable reference for non-parent groupings — keeps the `statusTotals` /// `cells` memos from busting on every render when there are no headers.const EMPTY_HEADER_IDS = new Set<string>();+const EMPTY_PROJECTS: Project[] = [];/*** Build parent-grouping lanes. The "No parent" lane is always pinned at the@@ -449,10 +449,13 @@ export function SwimLaneView({hiddenStatuses = [],onMoveIssue,childProgressMap = EMPTY_PROGRESS_MAP,+ projectMap,myIssuesScope,myIssuesFilter,sort,projectId,+ activityByIssueId,+ onCreateIssue,}: {issues: Issue[];/**@@ -473,12 +476,15 @@ export function SwimLaneView({onSettled?: () => void,) => void;childProgressMap?: Map<string, ChildProgress>;+ projectMap?: Map<string, Project>;myIssuesScope?: string;myIssuesFilter?: MyIssuesFilter;/** Must match the sort the page queried with — embedded in the cache key. */sort?: IssueSortParam;/** Pre-fills `project_id` on the create form for the in-cell "+" button. */projectId?: string;+ activityByIssueId?: ReadonlyMap<string, IssueActivityState>;+ onCreateIssue?: (defaults: IssueCreateDefaults) => void;}) {const { t } = useT("issues");const paths = useWorkspacePaths();@@ -491,14 +497,24 @@ export function SwimLaneView({const wsId = useWorkspaceId();- const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));+ const { data: snapshot = [] } = useQuery({+ ...agentTaskSnapshotOptions(wsId),+ enabled: !activityByIssueId,+ });const runningIssueIds = useMemo(() => {+ if (activityByIssueId) {+ const ids = new Set<string>();+ for (const [issueId, activity] of activityByIssueId) {+ if (activity.isWorking) ids.add(issueId);+ }+ return ids;+ }const ids = new Set<string>();for (const t of snapshot) {if (t.status === "running" && t.issue_id) ids.add(t.issue_id);}return ids;- }, [snapshot]);+ }, [activityByIssueId, snapshot]);const activeFilters = useMemo(() => ({// Status is enforced by visible-column rendering, not by filterIssues@@ -517,10 +533,13 @@ export function SwimLaneView({// per-parent loaded sub-issues get re-added even when the toggle is off.showSubIssues: activeFiltersProp?.showSubIssues ?? true,}), [activeFiltersProp, runningIssueIds]);- const { data: projects = EMPTY_PROJECTS } = useQuery({- ...projectListOptions(wsId),- enabled: swimlaneGrouping === "project",- });+ const projects = useMemo(+ () =>+ swimlaneGrouping === "project" && projectMap+ ? Array.from(projectMap.values())+ : EMPTY_PROJECTS,+ [projectMap, swimlaneGrouping],+ );const { getActorName } = useActorName();const laneSourceIssues = unfilteredIssues ?? issues;@@ -1174,9 +1193,11 @@ export function SwimLaneView({sortedStatuses={sortedStatuses}issueMap={issueMapRef.current}childProgressMap={childProgressMap}+ projectMap={projectMap}gridStyle={gridStyle}paths={paths}projectId={projectId}+ onCreateIssue={onCreateIssue}/>))}<SortableContext@@ -1198,9 +1219,11 @@ export function SwimLaneView({sortedStatuses={sortedStatuses}issueMap={issueMapRef.current}childProgressMap={childProgressMap}+ projectMap={projectMap}gridStyle={gridStyle}paths={paths}projectId={projectId}+ onCreateIssue={onCreateIssue}/>))}</SortableContext>@@ -1226,7 +1249,15 @@ export function SwimLaneView({<DragOverlay dropAnimation={null}>{activeIssue ? (<div className="w-[280px] rotate-2 scale-105 cursor-grabbing opacity-90 shadow-lg shadow-black/10">- <BoardCardContent issue={activeIssue} childProgress={childProgressMap.get(activeIssue.id)} />+ <BoardCardContent+ issue={activeIssue}+ childProgress={childProgressMap.get(activeIssue.id)}+ project={+ activeIssue.project_id+ ? projectMap?.get(activeIssue.project_id)+ : undefined+ }+ /></div>) : null}</DragOverlay>@@ -1257,9 +1288,11 @@ function DraggableSwimLane({sortedStatuses,issueMap,childProgressMap,+ projectMap,gridStyle,paths,projectId,+ onCreateIssue,}: {lane: LaneGroup;grouping: SwimlaneGrouping;@@ -1269,9 +1302,11 @@ function DraggableSwimLane({sortedStatuses: IssueStatus[];issueMap: Map<string, Issue>;childProgressMap: Map<string, ChildProgress>;+ projectMap?: Map<string, Project>;gridStyle: React.CSSProperties;paths: ReturnType<typeof useWorkspacePaths>;projectId?: string;+ onCreateIssue?: (defaults: IssueCreateDefaults) => void;}) {const { t } = useT("issues");const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({@@ -1366,9 +1401,11 @@ function DraggableSwimLane({issueIds={issueIds}issueMap={issueMap}childProgressMap={childProgressMap}+ projectMap={projectMap}status={status}lane={lane}projectId={projectId}+ onCreateIssue={onCreateIssue}readOnly={lane.isOrphan}/>);@@ -1384,18 +1421,22 @@ function SwimLaneCell({issueIds,issueMap,childProgressMap,+ projectMap,status,lane,projectId,+ onCreateIssue,readOnly = false,}: {cellId: string;issueIds: string[];issueMap: Map<string, Issue>;childProgressMap: Map<string, ChildProgress>;+ projectMap?: Map<string, Project>;status: IssueStatus;lane: LaneGroup;projectId?: string;+ onCreateIssue?: (defaults: IssueCreateDefaults) => void;/*** Display-only cell — the create affordance is suppressed and drag-end* upstream refuses to honour drops that would re-anchor a card to this@@ -1425,12 +1466,12 @@ function SwimLaneCell({);const handleAdd = useCallback(() => {- const data: Record<string, unknown> = { status, ...lane.moveUpdates };+ const data: IssueCreateDefaults = { status, ...lane.moveUpdates };// Per-page project override takes precedence (e.g. Project Detail// pre-fills its own project id regardless of grouping).if (projectId) data.project_id = projectId;- useModalStore.getState().open("create-issue", data);- }, [status, lane, projectId]);+ onCreateIssue?.(data);+ }, [status, lane, projectId, onCreateIssue]);return (<div className={`flex min-h-[120px] flex-col rounded-xl ${cfg?.columnBg ?? "bg-muted/40"} p-2`}>@@ -1446,6 +1487,9 @@ function SwimLaneCell({key={issue.id}issue={issue}childProgress={childProgressMap.get(issue.id)}+ project={+ issue.project_id ? projectMap?.get(issue.project_id) : undefined+ }/>))}</SortableContext>@@ -1455,7 +1499,7 @@ function SwimLaneCell({</p>)}</div>- {!readOnly && (+ {!readOnly && onCreateIssue && (<Tooltip><TooltipTriggerrender={diff --git a/packages/views/issues/surface/actions-context.tsx b/packages/views/issues/surface/actions-context.tsxnew file mode 100644index 0000000000..928d6916e7--- /dev/null+++ b/packages/views/issues/surface/actions-context.tsx@@ -0,0 +1,54 @@+"use client";++import { createContext, useContext, type ReactNode } from "react";+import type { UpdateIssueRequest } from "@multica/core/types";+import type { IssueCreateDefaults } from "./types";++export type IssueSurfaceMutationOptions = {+ errorMessage?: string;+ onSuccess?: () => void;+ onError?: (err: unknown) => void;+ onSettled?: () => void;+};++export interface IssueSurfaceActions {+ isPending: boolean;+ createIssue: (defaults?: IssueCreateDefaults) => void;+ updateIssue: (+ issueId: string,+ updates: Partial<UpdateIssueRequest>,+ options?: IssueSurfaceMutationOptions,+ ) => void;+ moveIssue: (+ issueId: string,+ updates: Partial<UpdateIssueRequest>,+ options?: IssueSurfaceMutationOptions,+ ) => void;+ batchUpdate: (+ issueIds: string[],+ updates: Partial<UpdateIssueRequest>,+ ) => Promise<void>;+ batchDelete: (issueIds: string[]) => Promise<void>;+}++const IssueSurfaceActionsContext = createContext<IssueSurfaceActions | null>(+ null,+);++export function IssueSurfaceActionsProvider({+ actions,+ children,+}: {+ actions: IssueSurfaceActions;+ children: ReactNode;+}) {+ return (+ <IssueSurfaceActionsContext.Provider value={actions}>+ {children}+ </IssueSurfaceActionsContext.Provider>+ );+}++export function useIssueSurfaceActionsOptional() {+ return useContext(IssueSurfaceActionsContext);+}diff --git a/packages/views/issues/surface/activity.test.ts b/packages/views/issues/surface/activity.test.tsnew file mode 100644index 0000000000..289e6c01be--- /dev/null+++ b/packages/views/issues/surface/activity.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from "vitest";+import type { AgentTask } from "@multica/core/types";+import { deriveIssueSurfaceActivity } from "./activity";++function task(overrides: Partial<AgentTask>): AgentTask {+ return {+ id: overrides.id ?? "task-1",+ workspace_id: "ws-1",+ issue_id: undefined,+ agent_id: "agent-1",+ status: "queued",+ trigger_type: "manual",+ trigger_source: "manual",+ trigger_ref: null,+ prompt: null,+ error: null,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ started_at: null,+ completed_at: null,+ ...overrides,+ } as AgentTask;+}++describe("deriveIssueSurfaceActivity", () => {+ it("separates running work from queued-only issue activity", () => {+ const activity = deriveIssueSurfaceActivity([+ task({ id: "run-1", issue_id: "i-1", status: "running" }),+ task({ id: "queue-1", issue_id: "i-2", status: "queued" }),+ task({ id: "dispatch-1", issue_id: "i-2", status: "dispatched" }),+ task({ id: "wait-1", issue_id: "i-3", status: "waiting_local_directory" }),+ task({ id: "done-1", issue_id: "i-4", status: "completed" }),+ task({ id: "no-issue", issue_id: undefined, status: "running" }),+ ]);++ expect(activity.runningIssueIds).toEqual(new Set(["i-1"]));+ expect(activity.activityByIssueId.get("i-1")).toMatchObject({+ isWorking: true,+ isQueued: false,+ });+ expect(activity.activityByIssueId.get("i-2")).toMatchObject({+ isWorking: false,+ isQueued: true,+ });+ expect(activity.activityByIssueId.get("i-3")).toMatchObject({+ isWorking: false,+ isQueued: true,+ });+ expect(activity.activityByIssueId.has("i-4")).toBe(false);+ });+});diff --git a/packages/views/issues/surface/activity.ts b/packages/views/issues/surface/activity.tsnew file mode 100644index 0000000000..649af1679c--- /dev/null+++ b/packages/views/issues/surface/activity.ts@@ -0,0 +1,71 @@+"use client";++import { useMemo } from "react";+import { useQuery } from "@tanstack/react-query";+import { agentTaskSnapshotOptions } from "@multica/core/agents";+import { useWorkspaceId } from "@multica/core/hooks";+import type { AgentTask } from "@multica/core/types";++export interface IssueActivityState {+ isWorking: boolean;+ isQueued: boolean;+ runningTasks: AgentTask[];+ queuedTasks: AgentTask[];+}++export interface IssueSurfaceActivity {+ activityByIssueId: Map<string, IssueActivityState>;+ runningIssueIds: Set<string>;+}++function isQueuedTaskStatus(status: AgentTask["status"]) {+ return (+ status === "queued" ||+ status === "dispatched" ||+ status === "waiting_local_directory"+ );+}++export function deriveIssueSurfaceActivity(+ tasks: readonly AgentTask[],+): IssueSurfaceActivity {+ const activityByIssueId = new Map<string, IssueActivityState>();++ for (const task of tasks) {+ if (!task.issue_id) continue;+ if (task.status !== "running" && !isQueuedTaskStatus(task.status)) {+ continue;+ }++ const current =+ activityByIssueId.get(task.issue_id) ?? {+ isWorking: false,+ isQueued: false,+ runningTasks: [],+ queuedTasks: [],+ };++ if (task.status === "running") {+ current.runningTasks.push(task);+ current.isWorking = true;+ } else {+ current.queuedTasks.push(task);+ current.isQueued = true;+ }++ activityByIssueId.set(task.issue_id, current);+ }++ const runningIssueIds = new Set<string>();+ for (const [issueId, activity] of activityByIssueId) {+ if (activity.isWorking) runningIssueIds.add(issueId);+ }++ return { activityByIssueId, runningIssueIds };+}++export function useIssueSurfaceActivity(): IssueSurfaceActivity {+ const wsId = useWorkspaceId();+ const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));+ return useMemo(() => deriveIssueSurfaceActivity(snapshot), [snapshot]);+}diff --git a/packages/views/issues/surface/issue-surface.test.tsx b/packages/views/issues/surface/issue-surface.test.tsxnew file mode 100644index 0000000000..686c3f0c6a--- /dev/null+++ b/packages/views/issues/surface/issue-surface.test.tsx@@ -0,0 +1,231 @@+/**+ * @vitest-environment jsdom+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { setApiInstance } from "@multica/core/api";+import type { ApiClient } from "@multica/core/api/client";+import { pruneIssueSurfaceViewStates } from "@multica/core/issues/stores/surface-view-store";+import type {+ AgentTask,+ Issue,+ ListIssuesParams,+ ListIssuesResponse,+} from "@multica/core/types";+import { IssueSurface } from "./issue-surface";++// Mutable so tests can simulate a workspace switch — the workspace layout+// does not remount its children on switch, so the surface must handle the+// wsId change itself.+const mockWsId = vi.hoisted(() => ({ current: "ws-1" }));+vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => mockWsId.current,+}));++const mockAuthUser = { id: "user-1", email: "[email protected]", name: "Test User" };+vi.mock("@multica/core/auth", () => ({+ useAuthStore: Object.assign(+ (selector?: (state: unknown) => unknown) => {+ const state = { user: mockAuthUser, isAuthenticated: true };+ return selector ? selector(state) : state;+ },+ { getState: () => ({ user: mockAuthUser, isAuthenticated: true }) },+ ),+ registerAuthStore: vi.fn(),+ createAuthStore: vi.fn(),+}));++vi.mock("../../i18n", () => ({+ useT: () => ({ t: () => "translated" }),+ useTimeAgo: () => () => "now",+}));++vi.mock("../../navigation", () => ({+ AppLink: ({ children, href, ...props }: React.ComponentProps<"a">) => (+ <a href={href} {...props}>+ {children}+ </a>+ ),+ useNavigation: () => ({ push: vi.fn(), pathname: "/" }),+}));++vi.mock("@multica/core/paths", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/paths")>(+ "@multica/core/paths",+ );+ return {+ ...actual,+ useCurrentWorkspace: () => ({ id: "ws-1", name: "Test WS", slug: "test" }),+ useWorkspacePaths: () => actual.paths.workspace("test"),+ };+});++function makeIssue(id: string, title: string, projectId: string): Issue {+ return {+ id,+ workspace_id: "ws-1",+ number: 1,+ identifier: `MUL-${id}`,+ title,+ description: null,+ status: "todo",+ priority: "none",+ assignee_type: null,+ assignee_id: null,+ creator_type: "member",+ creator_id: "user-1",+ parent_issue_id: null,+ project_id: projectId,+ position: 1,+ stage: null,+ start_date: null,+ due_date: null,+ labels: [],+ metadata: {},+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ };+}++function never<T>() {+ return new Promise<T>(() => {});+}++function projectSurface(projectId: string) {+ return (+ <IssueSurface+ scope={{ type: "project", projectId }}+ modes={["list"]}+ renderHeader={() => null}+ renderLoading={() => <div data-testid="surface-loading" />}+ batchToolbar="never"+ />+ );+}++describe("IssueSurface — scope switch loading semantics", () => {+ let qc: QueryClient;++ beforeEach(() => {+ mockWsId.current = "ws-1";+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ // p1 answers immediately with one issue; p2 stays in flight forever so+ // the test can observe the in-between state after switching.+ const listIssues = vi.fn((params?: ListIssuesParams) => {+ if (params?.project_id === "p2") return never<ListIssuesResponse>();+ const issues =+ params?.status === "todo" ? [makeIssue("i1", "P1 issue", "p1")] : [];+ return Promise.resolve({ issues, total: issues.length });+ });+ setApiInstance({+ listIssues,+ listGroupedIssues: vi.fn(() => never()),+ listProjects: vi.fn(() => never()),+ getAgentTaskSnapshot: vi.fn(() => never<AgentTask[]>()),+ getChildIssueProgress: vi.fn(() => never()),+ } as unknown as ApiClient);+ pruneIssueSurfaceViewStates([]);+ });++ afterEach(() => {+ cleanup();+ qc.clear();+ pruneIssueSurfaceViewStates([]);+ vi.restoreAllMocks();+ });++ it("shows loading — not the previous project's issues — while the next project is fetching", async () => {+ // Regression: the list queries use `placeholderData: keepPreviousData` to+ // keep sort/filter changes flicker-free WITHIN one surface. Without a+ // scope-keyed remount, that placeholder leaks ACROSS surfaces: switching+ // pinned projects kept rendering project A's cards (isLoading=false, so+ // no skeleton either) until project B's response landed — the "click does+ // nothing, then it snaps" bug.+ const { rerender } = render(+ <QueryClientProvider client={qc}>{projectSurface("p1")}</QueryClientProvider>,+ );++ await screen.findByText("P1 issue");++ rerender(+ <QueryClientProvider client={qc}>{projectSurface("p2")}</QueryClientProvider>,+ );++ // The switch must be honest: p2 has no data yet, so the surface is+ // loading — p1's cards must not impersonate p2.+ expect(screen.getByTestId("surface-loading")).toBeInTheDocument();+ expect(screen.queryByText("P1 issue")).not.toBeInTheDocument();+ });++ it("shows a cached project instantly on switch-back (no loading flash)", async () => {+ const { rerender } = render(+ <QueryClientProvider client={qc}>{projectSurface("p1")}</QueryClientProvider>,+ );+ await screen.findByText("P1 issue");++ rerender(+ <QueryClientProvider client={qc}>{projectSurface("p2")}</QueryClientProvider>,+ );+ expect(screen.getByTestId("surface-loading")).toBeInTheDocument();++ // Back to p1: its cache is warm, so the list renders immediately from+ // cache — remounting must not degrade the instant-switch path.+ rerender(+ <QueryClientProvider client={qc}>{projectSurface("p1")}</QueryClientProvider>,+ );+ await waitFor(() =>+ expect(screen.getByText("P1 issue")).toBeInTheDocument(),+ );+ expect(screen.queryByTestId("surface-loading")).not.toBeInTheDocument();+ });++ it("shows loading on a workspace switch even though the scope key is identical", async () => {+ // The workspace layout does NOT remount children on switch, and two+ // workspaces share the same scope key (e.g. "workspace:all") — so the+ // remount key must include wsId, or workspace A's issues impersonate+ // workspace B's while B is still fetching.+ //+ // A fresh element per render — reusing one element reference would let+ // React bail out of re-rendering the subtree entirely, and the wsId+ // change would never propagate.+ const workspaceSurface = () => (+ <IssueSurface+ scope={{ type: "workspace" }}+ modes={["list"]}+ renderHeader={() => null}+ renderLoading={() => <div data-testid="surface-loading" />}+ batchToolbar="never"+ />+ );++ const listIssues = vi.fn((params?: ListIssuesParams) => {+ const issues =+ params?.status === "todo" ? [makeIssue("i1", "WS1 issue", "p1")] : [];+ return Promise.resolve({ issues, total: issues.length });+ });+ setApiInstance({+ listIssues,+ listGroupedIssues: vi.fn(() => never()),+ listProjects: vi.fn(() => never()),+ getAgentTaskSnapshot: vi.fn(() => never<AgentTask[]>()),+ getChildIssueProgress: vi.fn(() => never()),+ } as unknown as ApiClient);++ const { rerender } = render(+ <QueryClientProvider client={qc}>{workspaceSurface()}</QueryClientProvider>,+ );+ await screen.findByText("WS1 issue");++ // Switch workspace: same scope, new wsId, and the new workspace's+ // fetches hang so the in-between state is observable.+ listIssues.mockImplementation(() => never<ListIssuesResponse>());+ mockWsId.current = "ws-2";+ rerender(+ <QueryClientProvider client={qc}>{workspaceSurface()}</QueryClientProvider>,+ );++ expect(screen.getByTestId("surface-loading")).toBeInTheDocument();+ expect(screen.queryByText("WS1 issue")).not.toBeInTheDocument();+ });+});diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsxnew file mode 100644index 0000000000..cf73c98702--- /dev/null+++ b/packages/views/issues/surface/issue-surface.tsx@@ -0,0 +1,269 @@+"use client";++import { useCallback, useMemo, type ReactNode } from "react";+import { ListTodo, Plus } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { Skeleton } from "@multica/ui/components/ui/skeleton";+import { cn } from "@multica/ui/lib/utils";+import { useWorkspaceId } from "@multica/core/hooks";+import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";+import { getIssueSurfaceViewStore } from "@multica/core/issues/stores/surface-view-store";+import { issueScopeKey } from "@multica/core/issues/surface/scope";+import type { Issue } from "@multica/core/types";+import { BoardView } from "../components/board-view";+import { BatchActionToolbar } from "../components/batch-action-toolbar";+import { GanttView } from "../components/gantt-view";+import { IssuesHeader } from "../components/issues-header";+import { ListView } from "../components/list-view";+import { SwimLaneView } from "../components/swimlane-view";+import { useT } from "../../i18n";+import { IssueSurfaceActionsProvider } from "./actions-context";+import { IssueSurfaceSelectionProvider } from "./selection-context";+import type { IssueCreateDefaults, IssueSurfaceProps } from "./types";+import {+ useIssueSurfaceController,+ type IssueSurfaceController,+} from "./use-issue-surface-controller";++export interface IssueSurfaceRenderContext {+ controller: IssueSurfaceController;+ issues: Issue[];+}++interface IssueSurfaceComponentProps extends IssueSurfaceProps {+ renderHeader?: (context: IssueSurfaceRenderContext) => ReactNode;+ renderEmpty?: (context: IssueSurfaceRenderContext) => ReactNode;+ renderLoading?: (context: IssueSurfaceRenderContext) => ReactNode;+ clientFilter?: (issue: Issue) => boolean;+ showClientEmpty?: (context: IssueSurfaceRenderContext) => boolean;+ batchToolbar?: "always" | "list" | "never";+ contentClassName?: string;+}++export function IssueSurface({+ scope,+ modes,+ surfaceKey,+ createDefaults,+ renderHeader,+ renderEmpty,+ renderLoading,+ clientFilter,+ showClientEmpty,+ batchToolbar = "always",+ contentClassName,+}: IssueSurfaceComponentProps) {+ const wsId = useWorkspaceId();+ const resolvedSurfaceKey = surfaceKey ?? issueScopeKey(scope);+ const store = useMemo(+ () => getIssueSurfaceViewStore(resolvedSurfaceKey),+ [resolvedSurfaceKey],+ );++ return (+ <ViewStoreProvider store={store}>+ {/* Remount on data-window change: the list queries keep the previous+ key's data as a placeholder (keepPreviousData) so sort/filter+ changes within ONE surface never flash a skeleton — but reusing the+ mounted observer across windows made project A's cards impersonate+ project B (with isLoading=false, so no skeleton either) until B's+ fetch landed. A window-keyed remount gives the new window a fresh+ observer: cold window → skeleton, warm window → instant cache hit.+ The window identity is wsId + scope — wsId is required because the+ workspace layout does not remount on workspace switch and two+ workspaces share the same scope key (e.g. "workspace:all"). Keyed+ by data identity, not surfaceKey (view-preference identity). */}+ <IssueSurfaceContent+ key={`${wsId}:${issueScopeKey(scope)}`}+ scope={scope}+ modes={modes}+ createDefaults={createDefaults}+ renderHeader={renderHeader}+ renderEmpty={renderEmpty}+ renderLoading={renderLoading}+ clientFilter={clientFilter}+ showClientEmpty={showClientEmpty}+ batchToolbar={batchToolbar}+ contentClassName={contentClassName}+ />+ </ViewStoreProvider>+ );+}++function IssueSurfaceContent({+ scope,+ modes,+ createDefaults,+ renderHeader,+ renderEmpty,+ renderLoading,+ clientFilter,+ showClientEmpty,+ batchToolbar,+ contentClassName,+}: Omit<IssueSurfaceComponentProps, "surfaceKey">) {+ const { t } = useT("projects");+ const controller = useIssueSurfaceController({+ scope,+ modes,+ createDefaults,+ });+ const issues = useMemo(+ () =>+ clientFilter+ ? controller.issues.filter((issue) => clientFilter(issue))+ : controller.issues,+ [clientFilter, controller.issues],+ );+ const swimlaneIssues = useMemo(+ () =>+ clientFilter+ ? controller.swimlaneIssues.filter((issue) => clientFilter(issue))+ : controller.swimlaneIssues,+ [clientFilter, controller.swimlaneIssues],+ );+ const renderContext = useMemo(+ () => ({ controller, issues }),+ [controller, issues],+ );+ const openCreateIssue = useCallback(+ (defaults?: IssueCreateDefaults) => {+ controller.openCreateIssue(defaults);+ },+ [controller],+ );+ const shouldShowClientEmpty =+ !!clientFilter &&+ issues.length === 0 &&+ (showClientEmpty ? showClientEmpty(renderContext) : true);+ const shouldShowBatchToolbar =+ batchToolbar !== "never" &&+ (batchToolbar === "always" || controller.viewMode === "list");++ return (+ <IssueSurfaceActionsProvider actions={controller.actions}>+ <IssueSurfaceSelectionProvider selection={controller.selection}>+ {renderHeader ? (+ renderHeader(renderContext)+ ) : (+ <IssuesHeader+ scopedIssues={controller.surfaceIssues}+ allowGantt={controller.allowGantt}+ isRefreshing={controller.isRefreshing}+ />+ )}+ {controller.isLoading ? (+ renderLoading ? (+ renderLoading(renderContext)+ ) : (+ <IssueSurfaceSkeleton mode={controller.viewMode} />+ )+ ) : controller.isEmpty || shouldShowClientEmpty ? (+ renderEmpty ? (+ renderEmpty(renderContext)+ ) : (+ <div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-3 text-muted-foreground">+ <ListTodo className="h-10 w-10 text-muted-foreground/40" />+ <p className="text-sm">{t(($) => $.detail.empty_issues_title)}</p>+ <p className="text-xs">{t(($) => $.detail.empty_issues_hint)}</p>+ <Button+ variant="outline"+ size="sm"+ className="mt-1"+ onClick={() => controller.openCreateIssue()}+ >+ <Plus className="size-3.5 mr-1.5" />+ {t(($) => $.detail.empty_issues_new_button)}+ </Button>+ </div>+ )+ ) : (+ <div className={cn("flex flex-col flex-1 min-h-0", contentClassName)}>+ {controller.viewMode === "board" && (+ <BoardView+ issues={+ controller.assigneeGroups+ ? controller.assigneeGroups.flatMap((group) => group.issues)+ : issues+ }+ assigneeGroups={controller.assigneeGroups}+ assigneeGroupQueryKey={controller.assigneeGroupQueryKey}+ assigneeGroupFilter={controller.assigneeGroupFilter}+ visibleStatuses={controller.visibleStatuses}+ hiddenStatuses={controller.hiddenStatuses}+ onMoveIssue={controller.moveIssue}+ childProgressMap={controller.childProgressMap}+ projectMap={controller.projectMap}+ myIssuesScope={controller.loadMoreScope}+ myIssuesFilter={controller.loadMoreFilter}+ sort={controller.sort}+ projectId={controller.projectId}+ onCreateIssue={openCreateIssue}+ />+ )}+ {controller.viewMode === "list" && (+ <ListView+ issues={issues}+ 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}+ />+ )}+ {controller.viewMode === "gantt" && (+ <GanttView issues={controller.filteredGanttIssues} />+ )}+ {controller.viewMode === "swimlane" && (+ <SwimLaneView+ issues={issues}+ unfilteredIssues={swimlaneIssues}+ activeFilters={controller.activeFilters}+ visibleStatuses={controller.visibleStatuses}+ hiddenStatuses={controller.hiddenStatuses}+ onMoveIssue={controller.moveIssue}+ childProgressMap={controller.childProgressMap}+ projectMap={controller.projectMap}+ myIssuesScope={controller.loadMoreScope}+ myIssuesFilter={controller.loadMoreFilter}+ sort={controller.sort}+ projectId={controller.projectId}+ activityByIssueId={controller.activity.activityByIssueId}+ onCreateIssue={openCreateIssue}+ />+ )}+ </div>+ )}+ {shouldShowBatchToolbar && <BatchActionToolbar issues={issues} />}+ </IssueSurfaceSelectionProvider>+ </IssueSurfaceActionsProvider>+ );+}++function IssueSurfaceSkeleton({ mode }: { mode: string }) {+ if (mode === "list") {+ return (+ <div className="flex-1 min-h-0 overflow-y-auto p-2 space-y-1">+ {Array.from({ length: 4 }).map((_, i) => (+ <Skeleton key={i} className="h-10 w-full rounded-lg" />+ ))}+ </div>+ );+ }++ return (+ <div className="flex flex-1 min-h-0 gap-4 overflow-x-auto p-4">+ {Array.from({ length: 5 }).map((_, i) => (+ <div key={i} className="flex min-w-52 flex-1 flex-col gap-2">+ <Skeleton className="h-4 w-20" />+ <Skeleton className="h-24 w-full rounded-lg" />+ <Skeleton className="h-24 w-full rounded-lg" />+ </div>+ ))}+ </div>+ );+}diff --git a/packages/views/issues/surface/selection-context.test.tsx b/packages/views/issues/surface/selection-context.test.tsxnew file mode 100644index 0000000000..15c6682f60--- /dev/null+++ b/packages/views/issues/surface/selection-context.test.tsx@@ -0,0 +1,44 @@+/**+ * @vitest-environment jsdom+ */+import { describe, expect, it } from "vitest";+import { act, renderHook } from "@testing-library/react";+import { useCreateIssueSurfaceSelection } from "./selection-context";++describe("useCreateIssueSurfaceSelection", () => {+ it("keeps selection local to a surface key and clears on surface change", () => {+ const { result, rerender } = renderHook(+ ({ surfaceKey }) => useCreateIssueSurfaceSelection(surfaceKey),+ { initialProps: { surfaceKey: "project:p1" } },+ );++ act(() => {+ result.current.select(["i-1", "i-2"]);+ result.current.toggle("i-3");+ });+ expect(result.current.selectedIds).toEqual(new Set(["i-1", "i-2", "i-3"]));++ act(() => {+ result.current.deselect(["i-2"]);+ });+ expect(result.current.selectedIds).toEqual(new Set(["i-1", "i-3"]));++ rerender({ surfaceKey: "project:p2" });+ expect(result.current.selectedIds).toEqual(new Set());+ });++ it("clears selection on reset key change even when the surface key is stable", () => {+ const { result, rerender } = renderHook(+ ({ resetKey }) => useCreateIssueSurfaceSelection("my:user-1:assigned", resetKey),+ { initialProps: { resetKey: "my:user-1:assigned:list" } },+ );++ act(() => {+ result.current.select(["i-1"]);+ });+ expect(result.current.selectedIds).toEqual(new Set(["i-1"]));++ rerender({ resetKey: "my:user-1:assigned:board" });+ expect(result.current.selectedIds).toEqual(new Set());+ });+});diff --git a/packages/views/issues/surface/selection-context.tsx b/packages/views/issues/surface/selection-context.tsxnew file mode 100644index 0000000000..69f5f682a1--- /dev/null+++ b/packages/views/issues/surface/selection-context.tsx@@ -0,0 +1,105 @@+"use client";++import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useState,+ type ReactNode,+} from "react";+import { useIssueSelectionStore } from "@multica/core/issues/stores/selection-store";++export interface IssueSurfaceSelection {+ selectedIds: Set<string>;+ toggle: (id: string) => void;+ select: (ids: string[]) => void;+ deselect: (ids: string[]) => void;+ clear: () => void;+}++const IssueSurfaceSelectionContext =+ createContext<IssueSurfaceSelection | null>(null);++export function useCreateIssueSurfaceSelection(+ surfaceKey: string,+ resetKey = surfaceKey,+): IssueSurfaceSelection {+ const [selectedIds, setSelectedIds] = useState(() => new Set<string>());++ useEffect(() => {+ setSelectedIds(new Set());+ }, [resetKey]);++ const toggle = useCallback((id: string) => {+ setSelectedIds((current) => {+ const next = new Set(current);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ }, []);++ const select = useCallback((ids: string[]) => {+ setSelectedIds((current) => {+ const next = new Set(current);+ for (const id of ids) next.add(id);+ return next;+ });+ }, []);++ const deselect = useCallback((ids: string[]) => {+ setSelectedIds((current) => {+ const next = new Set(current);+ for (const id of ids) next.delete(id);+ return next;+ });+ }, []);++ const clear = useCallback(() => {+ setSelectedIds(new Set());+ }, []);++ return useMemo(+ () => ({ selectedIds, toggle, select, deselect, clear }),+ [clear, deselect, select, selectedIds, toggle],+ );+}++export function IssueSurfaceSelectionProvider({+ selection,+ children,+}: {+ selection: IssueSurfaceSelection;+ children: ReactNode;+}) {+ return (+ <IssueSurfaceSelectionContext.Provider value={selection}>+ {children}+ </IssueSurfaceSelectionContext.Provider>+ );+}++export function useIssueSurfaceSelectionOptional() {+ return useContext(IssueSurfaceSelectionContext);+}++export function useIssueSurfaceSelection(): IssueSurfaceSelection {+ const surfaceSelection = useIssueSurfaceSelectionOptional();+ const globalSelectedIds = useIssueSelectionStore((s) => s.selectedIds);+ const globalToggle = useIssueSelectionStore((s) => s.toggle);+ const globalSelect = useIssueSelectionStore((s) => s.select);+ const globalDeselect = useIssueSelectionStore((s) => s.deselect);+ const globalClear = useIssueSelectionStore((s) => s.clear);++ return (+ surfaceSelection ?? {+ selectedIds: globalSelectedIds,+ toggle: globalToggle,+ select: globalSelect,+ deselect: globalDeselect,+ clear: globalClear,+ }+ );+}diff --git a/packages/views/issues/surface/types.ts b/packages/views/issues/surface/types.tsnew file mode 100644index 0000000000..38b15f4a47--- /dev/null+++ b/packages/views/issues/surface/types.ts@@ -0,0 +1,27 @@+import type { IssueScope } from "@multica/core/issues/surface/scope";+import type { CreateIssueRequest } from "@multica/core/types";+import type { ViewMode } from "@multica/core/issues/stores/view-store";++export type IssueCreateDefaults = Partial<+ Omit<+ CreateIssueRequest,+ "assignee_type" | "assignee_id" | "parent_issue_id" | "project_id"+ >+> & {+ assignee_type?: CreateIssueRequest["assignee_type"] | null;+ assignee_id?: string | null;+ parent_issue_id?: string | null;+ project_id?: string | null;+};++export type IssueSurfaceMode = Extract<+ ViewMode,+ "board" | "list" | "swimlane" | "gantt"+>;++export interface IssueSurfaceProps {+ scope: IssueScope;+ modes: IssueSurfaceMode[];+ surfaceKey?: string;+ createDefaults?: IssueCreateDefaults;+}diff --git a/packages/views/issues/surface/use-issue-surface-actions.ts b/packages/views/issues/surface/use-issue-surface-actions.tsnew file mode 100644index 0000000000..a71c510eed--- /dev/null+++ b/packages/views/issues/surface/use-issue-surface-actions.ts@@ -0,0 +1,129 @@+"use client";++import { useCallback, useMemo } from "react";+import { toast } from "sonner";+import type { UpdateIssueRequest } from "@multica/core/types";+import {+ useBatchDeleteIssues,+ useBatchUpdateIssues,+ useUpdateIssue,+} from "@multica/core/issues/mutations";+import { useModalStore } from "@multica/core/modals";+import {+ type IssueSurfaceActions,+ type IssueSurfaceMutationOptions,+} from "./actions-context";+import type { IssueCreateDefaults } from "./types";+import { useT } from "../../i18n";++export type MoveIssueUpdates = Pick<+ UpdateIssueRequest,+ | "status"+ | "assignee_type"+ | "assignee_id"+ | "position"+ | "parent_issue_id"+ | "project_id"+>;++export interface IssueSurfaceActionController {+ actions: IssueSurfaceActions;+ openCreateIssue: (defaults?: IssueCreateDefaults) => void;+ moveIssue: (+ issueId: string,+ updates: MoveIssueUpdates,+ onSettled?: () => void,+ ) => void;+}++export function useIssueSurfaceActions({+ createDefaults,+}: {+ createDefaults: IssueCreateDefaults;+}): IssueSurfaceActionController {+ const { t } = useT("projects");+ const updateIssueMutation = useUpdateIssue();+ const batchUpdateMutation = useBatchUpdateIssues();+ const batchDeleteMutation = useBatchDeleteIssues();++ const updateIssue = useCallback(+ (+ issueId: string,+ updates: Partial<UpdateIssueRequest>,+ options?: IssueSurfaceMutationOptions,+ ) => {+ updateIssueMutation.mutate(+ { id: issueId, ...updates },+ {+ onSuccess: () => options?.onSuccess?.(),+ onError: (err) => {+ toast.error(+ err instanceof Error && err.message+ ? err.message+ : (options?.errorMessage ??+ t(($) => $.detail.toast_move_issue_failed)),+ );+ options?.onError?.(err);+ },+ onSettled: () => options?.onSettled?.(),+ },+ );+ },+ [t, updateIssueMutation],+ );++ const moveIssue = useCallback(+ (+ issueId: string,+ updates: MoveIssueUpdates,+ onSettled?: () => void,+ ) => {+ updateIssue(issueId, updates, {+ errorMessage: t(($) => $.detail.toast_move_issue_failed),+ onSettled,+ });+ },+ [t, updateIssue],+ );++ const openCreateIssue = useCallback(+ (defaults?: IssueCreateDefaults) => {+ useModalStore+ .getState()+ .open("create-issue", { ...createDefaults, ...defaults });+ },+ [createDefaults],+ );++ const actions = useMemo<IssueSurfaceActions>(+ () => ({+ isPending:+ updateIssueMutation.isPending ||+ batchUpdateMutation.isPending ||+ batchDeleteMutation.isPending,+ createIssue: openCreateIssue,+ updateIssue,+ moveIssue: (issueId, updates, options) =>+ updateIssue(issueId, updates, {+ errorMessage: t(($) => $.detail.toast_move_issue_failed),+ ...options,+ }),+ batchUpdate: async (issueIds, updates) => {+ await batchUpdateMutation.mutateAsync({ ids: issueIds, updates });+ },+ batchDelete: async (issueIds) => {+ await batchDeleteMutation.mutateAsync(issueIds);+ },+ }),+ [+ batchDeleteMutation,+ batchUpdateMutation,+ openCreateIssue,+ t,+ updateIssue,+ updateIssueMutation.isPending,+ ],+ );++ return { actions, openCreateIssue, moveIssue };+}diff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsxnew file mode 100644index 0000000000..39de80cdc7--- /dev/null+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx@@ -0,0 +1,454 @@+/**+ * @vitest-environment jsdom+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { setApiInstance } from "@multica/core/api";+import type { ApiClient } from "@multica/core/api/client";+import { issueKeys } from "@multica/core/issues/queries";+import {+ getIssueSurfaceViewStore,+ pruneIssueSurfaceViewStates,+} from "@multica/core/issues/stores/surface-view-store";+import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";+import type {+ AgentTask,+ ListIssuesParams,+ ListIssuesResponse,+} from "@multica/core/types";+import { useIssueSurfaceController } from "./use-issue-surface-controller";++const updateIssueMutate = vi.hoisted(() => vi.fn());+const batchUpdateMutateAsync = vi.hoisted(() => vi.fn());+const batchDeleteMutateAsync = vi.hoisted(() => vi.fn());+const openModal = vi.hoisted(() => vi.fn());++vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "ws-1",+}));++vi.mock("@multica/core/issues/mutations", () => ({+ useUpdateIssue: () => ({ mutate: updateIssueMutate, isPending: false }),+ useBatchUpdateIssues: () => ({+ mutateAsync: batchUpdateMutateAsync,+ isPending: false,+ }),+ useBatchDeleteIssues: () => ({+ mutateAsync: batchDeleteMutateAsync,+ isPending: false,+ }),+}));++vi.mock("@multica/core/modals", () => ({+ useModalStore: {+ getState: () => ({ open: openModal }),+ },+}));++vi.mock("../../i18n", () => ({+ useT: () => ({ t: () => "translated" }),+}));++function makeWrapper(qc: QueryClient, surfaceKey = "project:p1") {+ const store = getIssueSurfaceViewStore(surfaceKey);+ return function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={qc}>+ <ViewStoreProvider store={store}>{children}</ViewStoreProvider>+ </QueryClientProvider>+ );+ };+}++function never<T>() {+ return new Promise<T>(() => {});+}++describe("useIssueSurfaceController", () => {+ let qc: QueryClient;+ let listIssues: ReturnType<+ typeof vi.fn<(params?: ListIssuesParams) => Promise<ListIssuesResponse>>+ >;++ beforeEach(() => {+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ listIssues = vi.fn(() => never<ListIssuesResponse>());+ setApiInstance({+ listIssues,+ listGroupedIssues: vi.fn(() => never()),+ listProjects: vi.fn(() => never()),+ getAgentTaskSnapshot: vi.fn(() => never<AgentTask[]>()),+ getChildIssueProgress: vi.fn(() => never()),+ } as unknown as ApiClient);+ pruneIssueSurfaceViewStates([]);+ updateIssueMutate.mockClear();+ openModal.mockClear();+ batchUpdateMutateAsync.mockResolvedValue(undefined);+ batchDeleteMutateAsync.mockResolvedValue(undefined);+ });++ afterEach(() => {+ cleanup();+ qc.clear();+ pruneIssueSurfaceViewStates([]);+ vi.restoreAllMocks();+ });++ it("derives the project scope key, API filter, and sorted myList cache key", async () => {+ const store = getIssueSurfaceViewStore("project:p1");+ store.getState().setSortBy("priority");+ store.getState().setSortDirection("desc");++ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "project", projectId: "p1" },+ modes: ["board", "list", "swimlane", "gantt"],+ }),+ { wrapper: makeWrapper(qc, "project:p1") },+ );++ await waitFor(() => expect(listIssues).toHaveBeenCalled());++ const expectedSort = { sort_by: "priority", sort_direction: "desc" } as const;+ const expectedFilter = { project_id: "p1" };++ expect(result.current.scopeKey).toBe("project:p1");+ expect(result.current.filter).toEqual(expectedFilter);+ expect(result.current.sort).toEqual(expectedSort);+ expect(+ qc.getQueryCache().find({+ queryKey: issueKeys.myListSorted(+ "ws-1",+ "project:p1",+ expectedFilter,+ expectedSort,+ ),+ exact: true,+ }),+ ).toBeDefined();+ expect(listIssues).toHaveBeenCalledWith(+ expect.objectContaining({+ project_id: "p1",+ sort_by: "priority",+ sort_direction: "desc",+ }),+ );+ });++ it("uses the workspace issue list query for workspace scope", async () => {+ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "workspace", actorKind: "all" },+ modes: ["board", "list", "swimlane"],+ }),+ { wrapper: makeWrapper(qc, "workspace:all") },+ );++ await waitFor(() => expect(listIssues).toHaveBeenCalled());++ expect(result.current.scopeKey).toBe("workspace:all");+ expect(result.current.filter).toEqual({});+ expect(result.current.loadMoreScope).toBeUndefined();+ expect(result.current.loadMoreFilter).toBeUndefined();+ expect(+ qc.getQueryCache().find({+ queryKey: issueKeys.listSorted("ws-1", {+ sort_by: "position",+ sort_direction: undefined,+ }),+ exact: true,+ }),+ ).toBeDefined();+ expect(listIssues).toHaveBeenCalledWith(+ expect.objectContaining({ status: "backlog", limit: 50, offset: 0 }),+ );+ });++ it("maps my assigned scope to the existing personal issue query contract", async () => {+ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "my", relation: "assigned", userId: "user-1" },+ modes: ["board", "list", "swimlane"],+ }),+ { wrapper: makeWrapper(qc, "my:user-1:assigned") },+ );++ await waitFor(() => expect(listIssues).toHaveBeenCalled());++ const expectedFilter = { assignee_id: "user-1" };+ expect(result.current.scopeKey).toBe("my:user-1:assigned");+ expect(result.current.filter).toEqual(expectedFilter);+ expect(result.current.loadMoreScope).toBe("assigned");+ expect(result.current.loadMoreFilter).toEqual(expectedFilter);+ expect(+ qc.getQueryCache().find({+ queryKey: issueKeys.myListSorted(+ "ws-1",+ "assigned",+ expectedFilter,+ { sort_by: "position", sort_direction: undefined },+ ),+ exact: true,+ }),+ ).toBeDefined();+ expect(listIssues).toHaveBeenCalledWith(+ expect.objectContaining({ assignee_id: "user-1" }),+ );+ });++ it("keeps actor scopes keyed by actor while using the shared list query shape", async () => {+ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: {+ type: "actor",+ actorType: "agent",+ actorId: "agent-1",+ relation: "assigned",+ },+ modes: ["list"],+ }),+ { wrapper: makeWrapper(qc, "actor:agent:agent-1:assigned") },+ );++ await waitFor(() => expect(listIssues).toHaveBeenCalled());++ const expectedFilter = { assignee_id: "agent-1" };+ expect(result.current.scopeKey).toBe("actor:agent:agent-1:assigned");+ expect(result.current.filter).toEqual(expectedFilter);+ expect(result.current.loadMoreScope).toBe("actor:agent:agent-1:assigned");+ expect(result.current.loadMoreFilter).toEqual(expectedFilter);+ expect(+ qc.getQueryCache().find({+ queryKey: issueKeys.myListSorted(+ "ws-1",+ "actor:agent:agent-1:assigned",+ expectedFilter,+ { sort_by: "position", sort_direction: undefined },+ ),+ exact: true,+ }),+ ).toBeDefined();+ expect(listIssues).toHaveBeenCalledWith(+ expect.objectContaining({ assignee_id: "agent-1" }),+ );+ });++ it.each([+ {+ name: "project",+ surfaceKey: "project:p1",+ scope: { type: "project" as const, projectId: "p1" },+ expected: { project_id: "p1", status: "todo" },+ },+ {+ name: "my assigned",+ surfaceKey: "my:user-1:assigned",+ scope: { type: "my" as const, relation: "assigned" as const, userId: "user-1" },+ expected: {+ assignee_type: "member",+ assignee_id: "user-1",+ status: "todo",+ },+ },+ {+ name: "actor assigned",+ surfaceKey: "actor:agent:agent-1:assigned",+ scope: {+ type: "actor" as const,+ actorType: "agent" as const,+ actorId: "agent-1",+ relation: "assigned" as const,+ },+ expected: {+ assignee_type: "agent",+ assignee_id: "agent-1",+ status: "todo",+ },+ },+ ])("merges $name create defaults into the create modal payload", ({ scope, surfaceKey, expected }) => {+ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope,+ modes: ["board", "list", "swimlane", "gantt"],+ }),+ { wrapper: makeWrapper(qc, surfaceKey) },+ );++ act(() => {+ result.current.openCreateIssue({ status: "todo" });+ });++ expect(openModal).toHaveBeenCalledWith("create-issue", expected);+ });++ it("clears surface selection when the view mode changes within the same scope", async () => {+ const store = getIssueSurfaceViewStore("my:user-1:assigned");+ store.getState().setViewMode("list");++ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "my", relation: "assigned", userId: "user-1" },+ modes: ["board", "list", "swimlane"],+ }),+ { wrapper: makeWrapper(qc, "my:user-1:assigned") },+ );++ act(() => {+ result.current.selection.select(["issue-1"]);+ });+ expect(result.current.selection.selectedIds).toEqual(new Set(["issue-1"]));++ act(() => {+ store.getState().setViewMode("board");+ });++ await waitFor(() => {+ expect(result.current.viewMode).toBe("board");+ expect(result.current.selection.selectedIds).toEqual(new Set());+ });+ });++ it("delegates movement through useUpdateIssue without rewriting the mutation path", () => {+ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "project", projectId: "p1" },+ modes: ["board", "list", "swimlane", "gantt"],+ }),+ { wrapper: makeWrapper(qc, "project:p1") },+ );+ const onSettled = vi.fn();++ act(() => {+ result.current.moveIssue(+ "issue-1",+ { status: "in_progress", position: 42, project_id: "p2" },+ onSettled,+ );+ });++ expect(updateIssueMutate).toHaveBeenCalledWith(+ { id: "issue-1", status: "in_progress", position: 42, project_id: "p2" },+ expect.objectContaining({+ onError: expect.any(Function),+ onSettled: expect.any(Function),+ }),+ );++ const options = updateIssueMutate.mock.calls[0]?.[1] as+ | { onSettled?: () => void }+ | undefined;+ options?.onSettled?.();+ expect(onSettled).toHaveBeenCalled();+ });++ it("exposes surface actions and surface-local selection", async () => {+ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "project", projectId: "p1" },+ modes: ["board", "list", "swimlane", "gantt"],+ }),+ { wrapper: makeWrapper(qc, "project:p1") },+ );++ act(() => {+ result.current.selection.select(["issue-1"]);+ });+ expect(result.current.selection.selectedIds).toEqual(new Set(["issue-1"]));++ await act(async () => {+ await result.current.actions.batchUpdate(["issue-1"], { status: "done" });+ await result.current.actions.batchDelete(["issue-2"]);+ });++ expect(batchUpdateMutateAsync).toHaveBeenCalledWith({+ ids: ["issue-1"],+ updates: { status: "done" },+ });+ expect(batchDeleteMutateAsync).toHaveBeenCalledWith(["issue-2"]);+ });++ it("never reports isEmpty in gantt mode — an empty scheduled subset cannot prove the window is empty", async () => {+ // The gantt query returns only issues with a start/due date. A project+ // full of unscheduled issues comes back [] here, and the surface used to+ // conclude "no issues linked" and render the generic create-issue empty+ // state over GanttView's accurate "no scheduled issues" one.+ listIssues.mockResolvedValue({ issues: [], total: 0 });++ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "project", projectId: "p1" },+ modes: ["gantt"],+ }),+ { wrapper: makeWrapper(qc, "project:p1") },+ );++ await waitFor(() => expect(result.current.isLoading).toBe(false));+ expect(result.current.viewMode).toBe("gantt");+ // Falls through to GanttView, which renders its own scheduled-empty copy.+ expect(result.current.isEmpty).toBe(false);+ });++ it("reports isRefreshing while a view change revalidates behind the previous snapshot", async () => {+ const store = getIssueSurfaceViewStore("project:p1");+ listIssues.mockResolvedValue({ issues: [], total: 0 });++ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "project", projectId: "p1" },+ modes: ["list"],+ }),+ { wrapper: makeWrapper(qc, "project:p1") },+ );++ // First load is loading, never refreshing — there is no previous+ // snapshot to show as a placeholder.+ expect(result.current.isLoading).toBe(true);+ expect(result.current.isRefreshing).toBe(false);+ await waitFor(() => expect(result.current.isLoading).toBe(false));++ // Sort change: the key changes, the previous order stays rendered as a+ // placeholder while the new order fetches — refreshing, NOT loading.+ const resolvers: ((r: ListIssuesResponse) => void)[] = [];+ listIssues.mockImplementation(+ () => new Promise<ListIssuesResponse>((res) => resolvers.push(res)),+ );+ act(() => store.getState().setSortBy("priority"));++ await waitFor(() => expect(result.current.isRefreshing).toBe(true));+ expect(result.current.isLoading).toBe(false);++ // The revalidation lands — the indicator clears.+ await act(async () => {+ for (const resolve of resolvers) resolve({ issues: [], total: 0 });+ });+ await waitFor(() => expect(result.current.isRefreshing).toBe(false));+ });++ it("still reports isEmpty for the full-window modes when the list is empty", async () => {+ listIssues.mockResolvedValue({ issues: [], total: 0 });++ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "project", projectId: "p1" },+ modes: ["list"],+ }),+ { wrapper: makeWrapper(qc, "project:p1") },+ );++ await waitFor(() => expect(result.current.isLoading).toBe(false));+ expect(result.current.isEmpty).toBe(true);+ });+});diff --git a/packages/views/issues/surface/use-issue-surface-controller.ts b/packages/views/issues/surface/use-issue-surface-controller.tsnew file mode 100644index 0000000000..4c66a256fe--- /dev/null+++ b/packages/views/issues/surface/use-issue-surface-controller.ts@@ -0,0 +1,221 @@+"use client";++import { useEffect, useMemo } from "react";+import type { QueryKey } from "@tanstack/react-query";+import type { Issue, IssueAssigneeGroup, Project } from "@multica/core/types";+import { useWorkspaceId } from "@multica/core/hooks";+import { BOARD_STATUSES } from "@multica/core/issues/config";+import { dateOnlyToLocalDate } from "@multica/core/issues/date";+import type {+ AssigneeGroupedIssuesFilter,+ IssueSortParam,+ MyIssuesFilter,+} from "@multica/core/issues/queries";+import {+ buildIssueSurfaceQueryPlan,+ type IssueSurfaceQueryPlan,+} from "@multica/core/issues/surface/query-plan";+import type { IssueScope } from "@multica/core/issues/surface/scope";+import type { IssueDateFilter } from "@multica/core/issues/stores/view-store";+import { useViewStore } from "@multica/core/issues/stores/view-store-context";+import type { IssueFilters } from "../utils/filter";+import type { ChildProgress } from "../components/list-row";+import type { IssueSurfaceMode } from "./types";+import type { IssueSurfaceActivity } from "./activity";+import type { IssueSurfaceActions } from "./actions-context";+import {+ type IssueSurfaceSelection,+ useCreateIssueSurfaceSelection,+} from "./selection-context";+import type { IssueCreateDefaults } from "./types";+import {+ useIssueSurfaceActions,+ type MoveIssueUpdates,+} from "./use-issue-surface-actions";+import { useIssueSurfaceData } from "./use-issue-surface-data";++interface UseIssueSurfaceControllerInput {+ scope: IssueScope;+ modes: IssueSurfaceMode[];+ createDefaults?: IssueCreateDefaults;+}++export interface IssueSurfaceController {+ scopeKey: string;+ projectId?: string;+ createDefaults: IssueCreateDefaults;+ viewMode: IssueSurfaceMode;+ allowGantt: boolean;+ surfaceIssues: Issue[];+ projectIssues: Issue[];+ issues: Issue[];+ swimlaneIssues: Issue[];+ filteredGanttIssues: Issue[];+ assigneeGroups?: IssueAssigneeGroup[];+ assigneeGroupQueryKey?: QueryKey;+ assigneeGroupFilter?: AssigneeGroupedIssuesFilter;+ filter: MyIssuesFilter;+ loadMoreScope?: string;+ loadMoreFilter?: MyIssuesFilter;+ sort: IssueSortParam;+ ganttIssues: Issue[];+ visibleStatuses: typeof BOARD_STATUSES;+ hiddenStatuses: typeof BOARD_STATUSES;+ activeFilters: Omit<IssueFilters, "statusFilters" | "runningIssueIds">;+ activity: IssueSurfaceActivity;+ actions: IssueSurfaceActions;+ selection: IssueSurfaceSelection;+ childProgressMap: Map<string, ChildProgress>;+ projectMap: Map<string, Project>;+ isLoading: boolean;+ /** See IssueSurfaceData.isRefreshing — placeholder-backed revalidation. */+ isRefreshing: boolean;+ isEmpty: boolean;+ openCreateIssue: (defaults?: IssueCreateDefaults) => void;+ moveIssue: (+ issueId: string,+ updates: MoveIssueUpdates,+ onSettled?: () => void,+ ) => void;+}++function issueDateFilterToApiParams(filter: IssueDateFilter | null) {+ if (!filter) return {};++ const from = dateOnlyToLocalDate(filter.from);+ const to = dateOnlyToLocalDate(filter.to);+ if (!from || !to) return {};++ const start = from <= to ? from : to;+ const endSource = from <= to ? to : from;+ const end = new Date(endSource);+ end.setDate(end.getDate() + 1);++ return {+ date_field: filter.field,+ date_start: start.toISOString(),+ date_end: end.toISOString(),+ };+}++export function useIssueSurfaceController({+ scope,+ modes,+ createDefaults,+}: UseIssueSurfaceControllerInput): IssueSurfaceController {+ const wsId = useWorkspaceId();+ const queryPlan = useMemo<IssueSurfaceQueryPlan>(+ () => buildIssueSurfaceQueryPlan(scope),+ [scope],+ );+ const scopeKey = queryPlan.scopeKey;+ const projectId = scope.type === "project" ? scope.projectId : undefined;++ const viewMode = useViewStore((s) => s.viewMode);+ const setViewMode = useViewStore((s) => s.setViewMode);+ const grouping = useViewStore((s) => s.grouping);+ const sortBy = useViewStore((s) => s.sortBy);+ const sortDirection = useViewStore((s) => s.sortDirection);+ const dateFilter = useViewStore((s) => s.dateFilter);+ const statusFilters = useViewStore((s) => s.statusFilters);+ const priorityFilters = useViewStore((s) => s.priorityFilters);+ const assigneeFilters = useViewStore((s) => s.assigneeFilters);+ const includeNoAssignee = useViewStore((s) => s.includeNoAssignee);+ const creatorFilters = useViewStore((s) => s.creatorFilters);+ const projectFilters = useViewStore((s) => s.projectFilters);+ const includeNoProject = useViewStore((s) => s.includeNoProject);+ const labelFilters = useViewStore((s) => s.labelFilters);+ const agentRunningFilter = useViewStore((s) => s.agentRunningFilter);+ const showSubIssues = useViewStore((s) => s.showSubIssues);+ const cardProperties = useViewStore((s) => s.cardProperties);+ const swimlaneGrouping = useViewStore((s) => s.swimlaneGrouping);++ const allowedModes = useMemo(() => new Set<IssueSurfaceMode>(modes), [modes]);+ const fallbackMode = modes[0] ?? "list";+ const effectiveViewMode = allowedModes.has(viewMode as IssueSurfaceMode)+ ? (viewMode as IssueSurfaceMode)+ : fallbackMode;++ useEffect(() => {+ if (!allowedModes.has(viewMode as IssueSurfaceMode)) {+ setViewMode(fallbackMode);+ }+ }, [allowedModes, fallbackMode, setViewMode, viewMode]);++ const resolvedCreateDefaults = useMemo(+ () => ({ ...queryPlan.createDefaults, ...createDefaults }),+ [createDefaults, queryPlan.createDefaults],+ );++ const dateParams = useMemo(+ () => issueDateFilterToApiParams(dateFilter),+ [dateFilter],+ );+ const sort = useMemo<IssueSortParam>(+ () => ({+ sort_by: sortBy,+ sort_direction: sortBy !== "position" ? sortDirection : undefined,+ ...dateParams,+ }),+ [dateParams, sortBy, sortDirection],+ );++ const selection = useCreateIssueSurfaceSelection(+ scopeKey,+ `${scopeKey}:${effectiveViewMode}`,+ );++ const usesAssigneeBoard =+ effectiveViewMode === "board" && grouping === "assignee";+ const usesGantt = effectiveViewMode === "gantt" && !!projectId;++ const projectFilterState = useMemo(+ () => ({+ projectFilters: scope.type === "project" ? [] : projectFilters,+ includeNoProject: scope.type === "project" ? false : includeNoProject,+ }),+ [includeNoProject, projectFilters, scope.type],+ );+ const { projectFilters: viewProjectFilters, includeNoProject: viewIncludeNoProject } =+ projectFilterState;++ const data = useIssueSurfaceData({+ wsId,+ queryPlan,+ projectId,+ usesAssigneeBoard,+ usesGantt,+ sort,+ statusFilters,+ priorityFilters,+ assigneeFilters,+ includeNoAssignee,+ creatorFilters,+ projectFilters: viewProjectFilters,+ includeNoProject: viewIncludeNoProject,+ labelFilters,+ agentRunningFilter,+ showSubIssues,+ loadProjects:+ cardProperties.project ||+ (effectiveViewMode === "swimlane" && swimlaneGrouping === "project"),+ });++ const { actions, openCreateIssue, moveIssue } = useIssueSurfaceActions({+ createDefaults: resolvedCreateDefaults,+ });++ return {+ scopeKey,+ projectId,+ createDefaults: resolvedCreateDefaults,+ viewMode: effectiveViewMode,+ allowGantt: allowedModes.has("gantt") && !!projectId,+ ...data,+ sort,+ actions,+ selection,+ openCreateIssue,+ moveIssue,+ };+}diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.tsnew file mode 100644index 0000000000..622516a206--- /dev/null+++ b/packages/views/issues/surface/use-issue-surface-data.ts@@ -0,0 +1,326 @@+"use client";++import { useMemo } from "react";+import { useQuery, type QueryKey } from "@tanstack/react-query";+import type { Issue, IssueAssigneeGroup, Project } from "@multica/core/types";+import { BOARD_STATUSES } from "@multica/core/issues/config";+import { projectListOptions } from "@multica/core/projects/queries";+import {+ childIssueProgressOptions,+ type AssigneeGroupedIssuesFilter,+ type IssueSortParam,+ type MyIssuesFilter,+} from "@multica/core/issues/queries";+import {+ issueSurfaceAssigneeGroupsOptions,+ issueSurfaceGanttOptions,+ issueSurfaceListOptions,+} from "@multica/core/issues/surface/repository";+import type { IssueSurfaceQueryPlan } from "@multica/core/issues/surface/query-plan";+import type { IssueStatus } from "@multica/core/types";+import {+ applyIssueFilters,+ filterAssigneeGroups,+ type IssueFilterState,+ type IssueFilters,+} from "../utils/filter";+import type { ChildProgress } from "../components/list-row";+import {+ useIssueSurfaceActivity,+ type IssueSurfaceActivity,+} from "./activity";++const EMPTY_ISSUES: Issue[] = [];+const EMPTY_CHILD_PROGRESS = new Map<string, ChildProgress>();+const EMPTY_PROJECTS: Project[] = [];++export interface IssueSurfaceData {+ surfaceIssues: Issue[];+ projectIssues: Issue[];+ issues: Issue[];+ swimlaneIssues: Issue[];+ filteredGanttIssues: Issue[];+ assigneeGroups?: IssueAssigneeGroup[];+ assigneeGroupQueryKey?: QueryKey;+ assigneeGroupFilter?: AssigneeGroupedIssuesFilter;+ filter: MyIssuesFilter;+ loadMoreScope?: string;+ loadMoreFilter?: MyIssuesFilter;+ ganttIssues: Issue[];+ visibleStatuses: typeof BOARD_STATUSES;+ hiddenStatuses: typeof BOARD_STATUSES;+ activeFilters: Omit<IssueFilters, "statusFilters" | "runningIssueIds">;+ activity: IssueSurfaceActivity;+ childProgressMap: Map<string, ChildProgress>;+ projectMap: Map<string, Project>;+ isLoading: boolean;+ /** The window's data is being revalidated while the previous snapshot is+ * shown as a placeholder (sort/date change, or any grouped-board filter+ * change). Drives the header's deferred refresh indicator — content stays+ * put, so this is NOT a loading state. */+ isRefreshing: boolean;+ isEmpty: boolean;+}++export function useIssueSurfaceData({+ wsId,+ queryPlan,+ projectId,+ usesAssigneeBoard,+ usesGantt,+ sort,+ statusFilters,+ priorityFilters,+ assigneeFilters,+ includeNoAssignee,+ creatorFilters,+ projectFilters,+ includeNoProject,+ labelFilters,+ agentRunningFilter,+ showSubIssues,+ loadProjects,+}: {+ wsId: string;+ queryPlan: IssueSurfaceQueryPlan;+ projectId?: string;+ usesAssigneeBoard: boolean;+ usesGantt: boolean;+ sort: IssueSortParam;+ statusFilters: IssueStatus[];+ priorityFilters: IssueFilterState["priorityFilters"];+ assigneeFilters: IssueFilterState["assigneeFilters"];+ includeNoAssignee: boolean;+ creatorFilters: IssueFilterState["creatorFilters"];+ projectFilters: string[];+ includeNoProject: boolean;+ labelFilters: string[];+ agentRunningFilter: boolean;+ showSubIssues: boolean;+ loadProjects: boolean;+}): IssueSurfaceData {+ const activity = useIssueSurfaceActivity();+ const filterContext = useMemo(+ () => ({ activityByIssueId: activity.activityByIssueId }),+ [activity.activityByIssueId],+ );++ const assigneeGroupFilter = useMemo<AssigneeGroupedIssuesFilter>(+ () => ({+ ...queryPlan.groupedScopeFilter,+ statuses: statusFilters.length > 0 ? statusFilters : [...BOARD_STATUSES],+ priorities: priorityFilters,+ assignee_filters: assigneeFilters,+ include_no_assignee: includeNoAssignee,+ creator_filters: creatorFilters,+ project_ids: projectFilters,+ include_no_project: includeNoProject,+ label_ids: labelFilters,+ }),+ [+ assigneeFilters,+ creatorFilters,+ includeNoAssignee,+ includeNoProject,+ labelFilters,+ priorityFilters,+ projectFilters,+ queryPlan.groupedScopeFilter,+ statusFilters,+ ],+ );++ const activeAssigneeGroupsOptions = issueSurfaceAssigneeGroupsOptions(+ wsId,+ queryPlan,+ assigneeGroupFilter,+ sort,+ );++ const statusIssuesQuery = useQuery({+ ...issueSurfaceListOptions(wsId, queryPlan, sort),+ enabled: !usesAssigneeBoard && !usesGantt,+ });+ const assigneeGroupsQuery = useQuery({+ ...activeAssigneeGroupsOptions,+ enabled: usesAssigneeBoard,+ });+ const ganttIssuesQuery = useQuery({+ ...issueSurfaceGanttOptions(wsId, projectId ?? ""),+ enabled: usesGantt,+ });++ const bucketedIssues = useMemo(() => {+ return usesAssigneeBoard+ ? (assigneeGroupsQuery.data?.groups.flatMap((group) => group.issues) ?? [])+ : (statusIssuesQuery.data ?? EMPTY_ISSUES);+ }, [assigneeGroupsQuery.data?.groups, statusIssuesQuery.data, usesAssigneeBoard]);++ const ganttIssues = ganttIssuesQuery.data ?? EMPTY_ISSUES;+ const surfaceIssues = usesGantt ? ganttIssues : bucketedIssues;++ const baseFilterState = useMemo<IssueFilterState>(+ () => ({+ statusFilters,+ priorityFilters,+ assigneeFilters,+ includeNoAssignee,+ creatorFilters,+ projectFilters,+ includeNoProject,+ labelFilters,+ workingOnly: agentRunningFilter,+ showSubIssues,+ }),+ [+ agentRunningFilter,+ assigneeFilters,+ creatorFilters,+ includeNoAssignee,+ includeNoProject,+ labelFilters,+ priorityFilters,+ projectFilters,+ showSubIssues,+ statusFilters,+ ],+ );++ const issues = useMemo(+ () => applyIssueFilters(surfaceIssues, baseFilterState, filterContext),+ [baseFilterState, filterContext, surfaceIssues],+ );++ const statuslessFilterState = useMemo<IssueFilterState>(+ () => ({+ ...baseFilterState,+ statusFilters: [],+ }),+ [baseFilterState],+ );++ const swimlaneIssues = useMemo(+ () => applyIssueFilters(surfaceIssues, statuslessFilterState, filterContext),+ [filterContext, statuslessFilterState, surfaceIssues],+ );++ const filteredGanttIssues = useMemo(+ () => applyIssueFilters(ganttIssues, baseFilterState, filterContext),+ [baseFilterState, filterContext, ganttIssues],+ );++ // The assignee-grouped board renders straight from `groups`, bypassing the+ // flat applyIssueFilters output — re-apply the client-only display filters+ // (Show sub-issues + agents-working) per group.+ const filteredAssigneeGroups = useMemo(+ () =>+ filterAssigneeGroups(assigneeGroupsQuery.data?.groups, {+ showSubIssues,+ agentRunningFilter,+ runningIssueIds: activity.runningIssueIds,+ }),+ [+ activity.runningIssueIds,+ agentRunningFilter,+ assigneeGroupsQuery.data?.groups,+ showSubIssues,+ ],+ );++ const { data: childProgressMap = EMPTY_CHILD_PROGRESS } = useQuery(+ childIssueProgressOptions(wsId),+ );+ const { data: projects = EMPTY_PROJECTS } = useQuery({+ ...projectListOptions(wsId),+ enabled: loadProjects,+ });+ const projectMap = useMemo(+ () => new Map(projects.map((project) => [project.id, project])),+ [projects],+ );++ const visibleStatuses = useMemo(() => {+ if (statusFilters.length > 0) {+ return BOARD_STATUSES.filter((s) => statusFilters.includes(s));+ }+ return BOARD_STATUSES;+ }, [statusFilters]);++ const hiddenStatuses = useMemo(+ () => BOARD_STATUSES.filter((s) => !visibleStatuses.includes(s)),+ [visibleStatuses],+ );++ const activeFilters = useMemo(+ () => ({+ priorityFilters,+ assigneeFilters,+ includeNoAssignee,+ creatorFilters,+ projectFilters,+ includeNoProject,+ labelFilters,+ agentRunningFilter,+ showSubIssues,+ }),+ [+ agentRunningFilter,+ assigneeFilters,+ creatorFilters,+ includeNoAssignee,+ includeNoProject,+ labelFilters,+ priorityFilters,+ projectFilters,+ showSubIssues,+ ],+ );++ const isLoading = usesAssigneeBoard+ ? assigneeGroupsQuery.isLoading+ : usesGantt+ ? ganttIssuesQuery.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+ ? false+ : statusIssuesQuery.isPlaceholderData;++ return {+ surfaceIssues,+ projectIssues: surfaceIssues,+ issues,+ swimlaneIssues,+ filteredGanttIssues,+ assigneeGroups: usesAssigneeBoard ? filteredAssigneeGroups : undefined,+ assigneeGroupQueryKey: usesAssigneeBoard+ ? activeAssigneeGroupsOptions.queryKey+ : undefined,+ assigneeGroupFilter: usesAssigneeBoard ? assigneeGroupFilter : undefined,+ filter: queryPlan.queryFilter,+ loadMoreScope: queryPlan.loadMoreScope,+ loadMoreFilter: queryPlan.loadMoreFilter,+ ganttIssues,+ visibleStatuses,+ hiddenStatuses,+ activeFilters,+ activity,+ childProgressMap,+ projectMap,+ isLoading,+ isRefreshing,+ // isEmpty asserts "this window has no issues". The board/list/swimlane+ // data IS the full window, so an empty result proves it. The gantt query+ // is a scheduled-only PROJECTION — an empty subset cannot prove the+ // window is empty, so never claim it (same "uncertain → don't assert"+ // rule as surface membership). GanttView renders its own accurate+ // "no scheduled issues" empty state instead of the generic create-issue+ // one.+ isEmpty: !isLoading && !usesGantt && surfaceIssues.length === 0,+ };+}diff --git a/packages/views/issues/utils/filter.test.ts b/packages/views/issues/utils/filter.test.tsindex 18978de00f..d7688d01cc 100644--- a/packages/views/issues/utils/filter.test.ts+++ b/packages/views/issues/utils/filter.test.ts@@ -1,6 +1,11 @@import { describe, it, expect } from "vitest";import type { Issue, IssueAssigneeGroup } from "@multica/core/types";-import { filterIssues, filterAssigneeGroups, type IssueFilters } from "./filter";+import {+ applyIssueFilters,+ filterAssigneeGroups,+ filterIssues,+ type IssueFilters,+} from "./filter";const NO_FILTER: IssueFilters = {statusFilters: [],@@ -250,6 +255,24 @@ describe("filterIssues", () => {expect(result.map((i) => i.id)).toEqual(["1"]);});+ it("applies workingOnly from activity context without treating queued issues as working", () => {+ const result = applyIssueFilters(+ issues,+ {+ ...NO_FILTER,+ workingOnly: true,+ },+ {+ activityByIssueId: new Map([+ ["1", { isWorking: true, isQueued: false, runningTasks: [], queuedTasks: [] }],+ ["2", { isWorking: false, isQueued: true, runningTasks: [], queuedTasks: [] }],+ ]),+ },+ );++ expect(result.map((i) => i.id)).toEqual(["1"]);+ });+// --- Show sub-issues display toggle ---const parentChildIssues: Issue[] = [makeIssue({ id: "P1", parent_issue_id: null }),diff --git a/packages/views/issues/utils/filter.ts b/packages/views/issues/utils/filter.tsindex 8a320437f4..44729f2ac8 100644--- a/packages/views/issues/utils/filter.ts+++ b/packages/views/issues/utils/filter.ts@@ -1,5 +1,6 @@-import type { Issue, IssueAssigneeGroup, IssueStatus, IssuePriority } from "@multica/core/types";+import type { Issue, IssueStatus, IssuePriority, IssueAssigneeGroup } from "@multica/core/types";import type { ActorFilterValue } from "@multica/core/issues/stores/view-store";+import type { IssueActivityState } from "../surface/activity";export interface IssueFilters {statusFilters: IssueStatus[];@@ -23,6 +24,32 @@ export interface IssueFilters {showSubIssues?: boolean;}+export interface IssueFilterState {+ statusFilters: IssueStatus[];+ priorityFilters: IssuePriority[];+ assigneeFilters: ActorFilterValue[];+ includeNoAssignee: boolean;+ creatorFilters: ActorFilterValue[];+ projectFilters: string[];+ includeNoProject: boolean;+ labelFilters: string[];+ workingOnly: boolean;+ /** See IssueFilters.showSubIssues — only an explicit `false` hides. */+ showSubIssues?: boolean;+}++export interface IssueFilterContext {+ activityByIssueId?: ReadonlyMap<string, IssueActivityState>;+ runningIssueIds?: ReadonlySet<string>;+}++function issueIsWorking(issueId: string, context: IssueFilterContext) {+ if (context.activityByIssueId) {+ return context.activityByIssueId.get(issueId)?.isWorking === true;+ }+ return context.runningIssueIds?.has(issueId) === true;+}+/*** Filter issues using positive selection model.* Empty arrays = no filter (show all). Non-empty = show only matching.@@ -32,21 +59,25 @@ export interface IssueFilters {* - When assigneeFilters has items → show only those assignees' issues* - When both → show matching assignees + unassigned*/-export function filterIssues(issues: Issue[], filters: IssueFilters): Issue[] {- const { statusFilters, priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters, projectFilters, includeNoProject, labelFilters, agentRunningFilter, runningIssueIds, showSubIssues } = filters;+export function applyIssueFilters(+ issues: Issue[],+ filters: IssueFilterState,+ context: IssueFilterContext = {},+): Issue[] {+ const { statusFilters, priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters, projectFilters, includeNoProject, labelFilters, workingOnly } = filters;const hasAssigneeFilter = assigneeFilters.length > 0 || includeNoAssignee;const hasProjectFilter = projectFilters.length > 0 || includeNoProject;// Empty set passed without `agentRunningFilter` is a no-op. When the// filter is on but the set is missing/empty, hide everything — the// user opted into "only running" and there is nothing running.- const applyAgentRunning = agentRunningFilter === true;+ const applyWorkingOnly = workingOnly === true;+ const hideSubIssues = filters.showSubIssues === false;return issues.filter((issue) => {- if (applyAgentRunning && !(runningIssueIds?.has(issue.id) ?? false))+ if (applyWorkingOnly && !issueIsWorking(issue.id, context))return false;- // "Show sub-issues" off → keep only top-level issues.- if (showSubIssues === false && issue.parent_issue_id) return false;+ if (hideSubIssues && issue.parent_issue_id) return false;if (statusFilters.length > 0 && !statusFilters.includes(issue.status))return false;@@ -101,20 +132,32 @@ export function filterIssues(issues: Issue[], filters: IssueFilters): Issue[] {});}+export function filterIssues(issues: Issue[], filters: IssueFilters): Issue[] {+ return applyIssueFilters(+ issues,+ {+ statusFilters: filters.statusFilters,+ priorityFilters: filters.priorityFilters,+ assigneeFilters: filters.assigneeFilters,+ includeNoAssignee: filters.includeNoAssignee,+ creatorFilters: filters.creatorFilters,+ projectFilters: filters.projectFilters,+ includeNoProject: filters.includeNoProject,+ labelFilters: filters.labelFilters,+ workingOnly: filters.agentRunningFilter === true,+ showSubIssues: filters.showSubIssues,+ },+ { runningIssueIds: filters.runningIssueIds },+ );+}+/**- * Apply the client-only display filters to assignee-grouped board data.- *- * The assignee-grouped board renders from the server-provided `groups` array- * rather than the flat `filterIssues` output, so display toggles that live- * purely on the client — "Show sub-issues" and the "agents working" quick- * filter — must be re-applied here or they silently bypass the assignee board.- * Only these two are handled: everything else (status, priority, label, …) is- * already enforced server-side when the groups are fetched, and re-running it- * here could double-filter against stale query params.- *- * Filtered groups get their `total` recomputed and emptied groups dropped. When- * neither toggle is active the original array is returned by reference so- * callers don't churn renders.+ * Re-apply the client-only display filters to a server-grouped response.+ * The assignee-grouped board renders straight from `groups`, bypassing the+ * flat `applyIssueFilters` output, so the "Show sub-issues" toggle and the+ * agents-working quick filter must be applied per group here. Recomputes+ * each group's total and drops emptied groups. Returns the input by+ * reference when no client filter is active.*/export function filterAssigneeGroups(groups: IssueAssigneeGroup[] | undefined,diff --git a/packages/views/my-issues/components/my-issues-header.tsx b/packages/views/my-issues/components/my-issues-header.tsxindex f78a018404..787e8a59ab 100644--- a/packages/views/my-issues/components/my-issues-header.tsx+++ b/packages/views/my-issues/components/my-issues-header.tsx@@ -1,7 +1,6 @@"use client";import { useMemo } from "react";-import { useStore } from "zustand";import { ChevronDown } from "lucide-react";import { Button } from "@multica/ui/components/ui/button";import {@@ -13,12 +12,26 @@ import {} from "@multica/ui/components/ui/dropdown-menu";import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";import type { Issue } from "@multica/core/types";-import { myIssuesViewStore, type MyIssuesScope } from "@multica/core/issues/stores/my-issues-view-store";+import type { MyIssuesScope } from "@multica/core/issues/stores/my-issues-view-store";+import { useViewStore } from "@multica/core/issues/stores/view-store-context";import { useT } from "../../i18n";import { WorkspaceAgentWorkingChip } from "../../issues/components/workspace-agent-working-chip";-import { IssueDisplayControls } from "../../issues/components/issues-header";+import {+ IssueDisplayControls,+ ViewRefreshIndicator,+} from "../../issues/components/issues-header";-export function MyIssuesHeader({ allIssues }: { allIssues: Issue[] }) {+export function MyIssuesHeader({+ allIssues,+ scope,+ onScopeChange,+ isRefreshing = false,+}: {+ allIssues: Issue[];+ scope: MyIssuesScope;+ onScopeChange: (scope: MyIssuesScope) => void;+ isRefreshing?: boolean;+}) {const { t } = useT("my-issues");const { t: tIssues } = useT("issues");const SCOPES: { value: MyIssuesScope; label: string; description: string }[] = [@@ -27,9 +40,10 @@ export function MyIssuesHeader({ allIssues }: { allIssues: Issue[] }) {{ value: "created", label: t(($) => $.header.scope.created_label), description: t(($) => $.header.scope.created_description) },{ value: "agents", label: t(($) => $.header.scope.agents_label), description: t(($) => $.header.scope.agents_description) },];- const scope = useStore(myIssuesViewStore, (s) => s.scope);- const agentRunningFilter = useStore(myIssuesViewStore, (s) => s.agentRunningFilter);- const act = myIssuesViewStore.getState();+ const agentRunningFilter = useViewStore((s) => s.agentRunningFilter);+ const toggleAgentRunningFilter = useViewStore(+ (s) => s.toggleAgentRunningFilter,+ );const scopedIssueIds = useMemo(() => new Set(allIssues.map((i) => i.id)),[allIssues],@@ -52,7 +66,7 @@ export function MyIssuesHeader({ allIssues }: { allIssues: Issue[] }) {? "bg-accent text-accent-foreground hover:bg-accent/80": "text-muted-foreground"}- onClick={() => act.setScope(s.value)}+ onClick={() => onScopeChange(s.value)}>{s.label}</Button>@@ -79,7 +93,7 @@ export function MyIssuesHeader({ allIssues }: { allIssues: Issue[] }) {<DropdownMenuContent align="start" className="w-auto"><DropdownMenuRadioGroupvalue={scope}- onValueChange={(value) => act.setScope(value as MyIssuesScope)}+ onValueChange={(value) => onScopeChange(value as MyIssuesScope)}>{SCOPES.map((s) => (<DropdownMenuRadioItem key={s.value} value={s.value}>@@ -98,10 +112,11 @@ export function MyIssuesHeader({ allIssues }: { allIssues: Issue[] }) {)}<WorkspaceAgentWorkingChipvalue={agentRunningFilter}- onToggle={act.toggleAgentRunningFilter}+ onToggle={toggleAgentRunningFilter}scopedIssueIds={scopedIssueIds}/><IssueDisplayControls scopedIssues={allIssues} />+ <ViewRefreshIndicator active={isRefreshing} /></div></div></div>diff --git a/packages/views/my-issues/components/my-issues-page.tsx b/packages/views/my-issues/components/my-issues-page.tsxindex d422372158..271e4445b0 100644--- a/packages/views/my-issues/components/my-issues-page.tsx+++ b/packages/views/my-issues/components/my-issues-page.tsx@@ -1,264 +1,26 @@"use client";-import { useCallback, useEffect, useMemo } from "react";import { useStore } from "zustand";-import { toast } from "sonner";import { ListTodo } from "lucide-react";-import type { UpdateIssueRequest } from "@multica/core/types";-import { Skeleton } from "@multica/ui/components/ui/skeleton";import { useAuthStore } from "@multica/core/auth";-import { useQuery } from "@tanstack/react-query";-import { filterIssues, filterAssigneeGroups } from "../../issues/utils/filter";-import { BOARD_STATUSES } from "@multica/core/issues/config";-import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";-import { useIssueSelectionStore } from "@multica/core/issues/stores/selection-store";-import { BoardView } from "../../issues/components/board-view";-import { ListView } from "../../issues/components/list-view";-import { SwimLaneView } from "../../issues/components/swimlane-view";-import { BatchActionToolbar } from "../../issues/components/batch-action-toolbar";-import { useClearFiltersOnWorkspaceChange } from "@multica/core/issues/stores/view-store";-import { useWorkspaceId } from "@multica/core/hooks";-import { myIssueAssigneeGroupsOptions, myIssueListOptions, childIssueProgressOptions, type AssigneeGroupedIssuesFilter, type MyIssuesFilter } from "@multica/core/issues/queries";-import { agentTaskSnapshotOptions } from "@multica/core/agents";-import { useUpdateIssue } from "@multica/core/issues/mutations";-import { myIssuesViewStore } from "@multica/core/issues/stores/my-issues-view-store";+import {+ myIssuesViewStore,+ type MyIssuesScope,+} from "@multica/core/issues/stores/my-issues-view-store";import { PageHeader } from "../../layout/page-header";+import { IssueSurface } from "../../issues/surface/issue-surface";import { useT } from "../../i18n";import { MyIssuesHeader } from "./my-issues-header";+function relationFromScope(scope: MyIssuesScope) {+ return scope === "agents" ? "involved" : scope;+}+export function MyIssuesPage() {const { t } = useT("my-issues");const user = useAuthStore((s) => s.user);- const wsId = useWorkspaceId();- const viewMode = useStore(myIssuesViewStore, (s) => s.viewMode);- const statusFilters = useStore(myIssuesViewStore, (s) => s.statusFilters);- const priorityFilters = useStore(myIssuesViewStore, (s) => s.priorityFilters);const scope = useStore(myIssuesViewStore, (s) => s.scope);- const grouping = useStore(myIssuesViewStore, (s) => s.grouping);- const sortBy = useStore(myIssuesViewStore, (s) => s.sortBy);- const sortDirection = useStore(myIssuesViewStore, (s) => s.sortDirection);- const agentRunningFilter = useStore(myIssuesViewStore, (s) => s.agentRunningFilter);- const showSubIssues = useStore(myIssuesViewStore, (s) => s.showSubIssues);- const usesAssigneeBoard = viewMode === "board" && grouping === "assignee";-- const sort = useMemo(- () => ({- sort_by: sortBy,- sort_direction: sortBy !== "position" ? sortDirection : undefined,- } as const),- [sortBy, sortDirection],- );-- // See issues-page.tsx for the rationale — derive a workspace-wide set- // of issue ids with at least one running task, drive the "agents- // working" quick-filter from it.- const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));- const runningIssueIds = useMemo(() => {- const ids = new Set<string>();- for (const t of snapshot) {- if (t.status === "running" && t.issue_id) ids.add(t.issue_id);- }- return ids;- }, [snapshot]);-- // Clear filter state when switching between workspaces (URL-driven).- useClearFiltersOnWorkspaceChange(myIssuesViewStore, wsId);-- useEffect(() => {- useIssueSelectionStore.getState().clear();- }, [viewMode, scope]);-- // Build server-side filter based on scope. The `agents` tab uses- // `involves_user_id` so the server expands the user's identity to all- // assignees that indirectly belong to them (owned agents + related squads).- // Direct member assignment is intentionally excluded — that is the- // `assigned` tab's semantics.- const filter: MyIssuesFilter = useMemo(() => {- if (!user) return {};- switch (scope) {- case "assigned":- return { assignee_id: user.id };- case "created":- return { creator_id: user.id };- case "agents":- return { involves_user_id: user.id };- case "all":- // "All" is the union of the three single-relation filters above;- // the per-relation user id is plumbed through `userId` to- // myIssue*Options. The filter object stays empty so it carries- // no narrowing of its own.- return {};- default:- return { assignee_id: user.id };- }- }, [scope, user]);-- const assigneeGroupFilter = useMemo<AssigneeGroupedIssuesFilter>(- () => ({- ...filter,- statuses: statusFilters.length > 0 ? statusFilters : [...BOARD_STATUSES],- priorities: priorityFilters,- }),- [filter, priorityFilters, statusFilters],- );- const assigneeGroupsOptions = myIssueAssigneeGroupsOptions(- wsId,- scope,- assigneeGroupFilter,- user?.id,- sort,- );- const statusIssuesQuery = useQuery({- ...myIssueListOptions(wsId, scope, filter, user?.id, sort),- enabled: !usesAssigneeBoard,- });- const assigneeGroupsQuery = useQuery({- ...assigneeGroupsOptions,- enabled: usesAssigneeBoard,- });- const myIssues = useMemo(- () =>- usesAssigneeBoard- ? (assigneeGroupsQuery.data?.groups.flatMap((group) => group.issues) ?? [])- : (statusIssuesQuery.data ?? []),- [assigneeGroupsQuery.data, statusIssuesQuery.data, usesAssigneeBoard],- );- const loading = usesAssigneeBoard- ? assigneeGroupsQuery.isLoading- : statusIssuesQuery.isLoading;-- // Assignee-grouped board renders from `groups`, bypassing the flat- // `filterIssues` output, so re-apply the client-only "Show sub-issues"- // toggle here (see filterAssigneeGroups).- const filteredAssigneeGroups = useMemo(- () => filterAssigneeGroups(assigneeGroupsQuery.data?.groups, { showSubIssues }),- [assigneeGroupsQuery.data, showSubIssues],- );- const filteredAssigneeIssues = useMemo(- () => filteredAssigneeGroups?.flatMap((group) => group.issues) ?? [],- [filteredAssigneeGroups],- );-- // Apply status/priority/agent-running filters from view store- const issues = useMemo(- () =>- filterIssues(myIssues, {- statusFilters,- priorityFilters,- assigneeFilters: [],- includeNoAssignee: false,- creatorFilters: [],- projectFilters: [],- includeNoProject: false,- labelFilters: [],- agentRunningFilter,- runningIssueIds,- showSubIssues,- }),- [myIssues, statusFilters, priorityFilters, agentRunningFilter, runningIssueIds, showSubIssues],- );-- // Status-unfiltered companion for Swimlane.- const swimlaneIssues = useMemo(- () =>- filterIssues(myIssues, {- statusFilters: [],- priorityFilters,- assigneeFilters: [],- includeNoAssignee: false,- creatorFilters: [],- projectFilters: [],- includeNoProject: false,- labelFilters: [],- agentRunningFilter,- runningIssueIds,- showSubIssues,- }),- [myIssues, priorityFilters, agentRunningFilter, runningIssueIds, showSubIssues],- );-- const activeFilters = useMemo(() => ({- priorityFilters,- assigneeFilters: [],- includeNoAssignee: false,- creatorFilters: [],- projectFilters: [],- includeNoProject: false,- labelFilters: [],- agentRunningFilter,- showSubIssues,- }), [priorityFilters, agentRunningFilter, showSubIssues]);-- const { data: childProgressMap = new Map() } = useQuery(childIssueProgressOptions(wsId));-- const visibleStatuses = useMemo(() => {- if (statusFilters.length > 0)- return BOARD_STATUSES.filter((s) => statusFilters.includes(s));- return BOARD_STATUSES;- }, [statusFilters]);-- const hiddenStatuses = useMemo(() => {- return BOARD_STATUSES.filter((s) => !visibleStatuses.includes(s));- }, [visibleStatuses]);-- const updateIssueMutation = useUpdateIssue();- const handleMoveIssue = useCallback(- (issueId: string, updates: Pick<UpdateIssueRequest, "status" | "assignee_type" | "assignee_id" | "position" | "parent_issue_id">, onSettled?: () => void) => {- updateIssueMutation.mutate(- { id: issueId, ...updates },- {- onError: (err) =>- toast.error(- err instanceof Error && err.message- ? err.message- : t(($) => $.errors.move_failed),- ),- onSettled: () => onSettled?.(),- },- );- },- [updateIssueMutation, t],- );-- if (loading) {- return (- <div className="flex flex-1 min-h-0 flex-col">- <div className="flex h-12 shrink-0 items-center gap-2 border-b px-4">- <Skeleton className="h-5 w-5 rounded" />- <Skeleton className="h-4 w-32" />- </div>- <div className="flex h-12 shrink-0 items-center justify-between px-4">- <div className="flex items-center gap-1">- <Skeleton className="h-8 w-14 rounded-md" />- <Skeleton className="h-8 w-20 rounded-md" />- <Skeleton className="h-8 w-16 rounded-md" />- </div>- <div className="flex items-center gap-1">- <Skeleton className="h-8 w-8 rounded-md" />- <Skeleton className="h-8 w-8 rounded-md" />- <Skeleton className="h-8 w-8 rounded-md" />- </div>- </div>- {viewMode === "list" ? (- <div className="flex-1 min-h-0 overflow-y-auto p-2 pt-0 space-y-1">- {Array.from({ length: 4 }).map((_, i) => (- <Skeleton key={i} className="h-10 w-full rounded-lg" />- ))}- </div>- ) : (- <div className="flex flex-1 min-h-0 gap-4 overflow-x-auto p-4">- {Array.from({ length: 5 }).map((_, i) => (- <div key={i} className="flex min-w-52 flex-1 flex-col gap-2">- <Skeleton className="h-4 w-20" />- <Skeleton className="h-24 w-full rounded-lg" />- <Skeleton className="h-24 w-full rounded-lg" />- </div>- ))}- </div>- )}- </div>- );- }+ const setScope = useStore(myIssuesViewStore, (s) => s.setScope);return (<div className="flex flex-1 min-h-0 flex-col">@@ -267,59 +29,32 @@ export function MyIssuesPage() {<h1 className="text-sm font-medium">{t(($) => $.page.breadcrumb)}</h1></PageHeader>- <ViewStoreProvider store={myIssuesViewStore}>- {/* Header: scope tabs (left) + controls (right) */}- <MyIssuesHeader allIssues={myIssues} />- {myIssues.length === 0 ? (- <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">{t(($) => $.page.empty_title)}</p>- <p className="text-xs">{t(($) => $.page.empty_description)}</p>- </div>- ) : (- <div className="flex flex-col flex-1 min-h-0">- {viewMode === "board" ? (- <BoardView- issues={usesAssigneeBoard ? filteredAssigneeIssues : issues}- assigneeGroups={usesAssigneeBoard ? filteredAssigneeGroups : undefined}- assigneeGroupQueryKey={usesAssigneeBoard ? assigneeGroupsOptions.queryKey : undefined}- assigneeGroupFilter={usesAssigneeBoard ? assigneeGroupFilter : undefined}- visibleStatuses={visibleStatuses}- hiddenStatuses={hiddenStatuses}- onMoveIssue={handleMoveIssue}- childProgressMap={childProgressMap}- myIssuesScope={scope}- myIssuesFilter={filter}- sort={sort}- />- ) : viewMode === "swimlane" ? (- <SwimLaneView- issues={issues}- unfilteredIssues={swimlaneIssues}- activeFilters={activeFilters}- visibleStatuses={visibleStatuses}- hiddenStatuses={hiddenStatuses}- onMoveIssue={handleMoveIssue}- childProgressMap={childProgressMap}- myIssuesScope={scope}- myIssuesFilter={filter}- sort={sort}- />- ) : (- <ListView- issues={issues}- visibleStatuses={visibleStatuses}- childProgressMap={childProgressMap}- myIssuesScope={scope}- myIssuesFilter={filter}- sort={sort}- onMoveIssue={handleMoveIssue}- />- )}- </div>- )}- {viewMode === "list" && <BatchActionToolbar issues={issues} />}- </ViewStoreProvider>+ {user ? (+ <IssueSurface+ scope={{+ type: "my",+ userId: user.id,+ relation: relationFromScope(scope),+ }}+ modes={["board", "list", "swimlane"]}+ batchToolbar="list"+ renderHeader={({ controller }) => (+ <MyIssuesHeader+ allIssues={controller.surfaceIssues}+ scope={scope}+ onScopeChange={setScope}+ isRefreshing={controller.isRefreshing}+ />+ )}+ renderEmpty={() => (+ <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">{t(($) => $.page.empty_title)}</p>+ <p className="text-xs">{t(($) => $.page.empty_description)}</p>+ </div>+ )}+ />+ ) : null}</div>);}diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsxindex 21918061dc..06cfd298db 100644--- a/packages/views/projects/components/project-detail.tsx+++ b/packages/views/projects/components/project-detail.tsx@@ -2,51 +2,30 @@import { useMemo, useState, useCallback, useRef, useEffect } from "react";import { useDefaultLayout, usePanelRef } from "react-resizable-panels";-import { Check, ChevronRight, Link2, ListTodo, MoreHorizontal, PanelRight, Pin, PinOff, Plus, Trash2, UserMinus } from "lucide-react";-import { useQuery, type QueryKey } from "@tanstack/react-query";+import { Check, ChevronRight, Link2, MoreHorizontal, PanelRight, Pin, PinOff, Trash2, UserMinus } from "lucide-react";+import { useQuery } from "@tanstack/react-query";import { cn } from "@multica/ui/lib/utils";import { copyText } from "@multica/ui/lib/clipboard";import { toast } from "sonner";-import type { Issue, IssueAssigneeGroup, ProjectStatus, ProjectPriority, UpdateIssueRequest } from "@multica/core/types";+import type { ProjectStatus, ProjectPriority } from "@multica/core/types";import { useAuthStore } from "@multica/core/auth";import { projectDetailOptions } from "@multica/core/projects/queries";import { useUpdateProject, useDeleteProject } from "@multica/core/projects/mutations";import { pinListOptions } from "@multica/core/pins";import { useCreatePin, useDeletePin } from "@multica/core/pins";-import {- myIssueAssigneeGroupsOptions,- myIssueListOptions,- projectGanttIssuesOptions,- childIssueProgressOptions,- type AssigneeGroupedIssuesFilter,- type IssueSortParam,- type MyIssuesFilter,-} from "@multica/core/issues/queries";-import { useUpdateIssue } from "@multica/core/issues/mutations";-import { useModalStore } from "@multica/core/modals";import { memberListOptions, agentListOptions } from "@multica/core/workspace/queries";-import { agentTaskSnapshotOptions } from "@multica/core/agents";import { useWorkspaceId } from "@multica/core/hooks";import { useRecentContextStore } from "@multica/core/chat";import { useWorkspacePaths } from "@multica/core/paths";import { useActorName } from "@multica/core/workspace/hooks";import { PROJECT_STATUS_ORDER, PROJECT_STATUS_CONFIG, PROJECT_PRIORITY_ORDER } from "@multica/core/projects/config";-import { BOARD_STATUSES } from "@multica/core/issues/config";-import { createIssueViewStore } from "@multica/core/issues/stores/view-store";-import { ViewStoreProvider, useViewStore } from "@multica/core/issues/stores/view-store-context";-import { filterIssues, filterAssigneeGroups } from "../../issues/utils/filter";import { getProjectIssueMetrics } from "./project-issue-metrics";import { ActorAvatar } from "../../common/actor-avatar";import { useNavigation } from "../../navigation";import { TitleEditor, ContentEditor, type ContentEditorRef } from "../../editor";import { PriorityIcon } from "../../issues/components/priority-icon";import { ProjectResourcesSection } from "./project-resources-section";-import { IssuesHeader } from "../../issues/components/issues-header";-import { BoardView } from "../../issues/components/board-view";-import { ListView } from "../../issues/components/list-view";-import { GanttView } from "../../issues/components/gantt-view";-import { SwimLaneView } from "../../issues/components/swimlane-view";-import { BatchActionToolbar } from "../../issues/components/batch-action-toolbar";+import { IssueSurface } from "../../issues/surface/issue-surface";import { Skeleton } from "@multica/ui/components/ui/skeleton";import { Button } from "@multica/ui/components/ui/button";import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@multica/ui/components/ui/resizable";@@ -112,306 +91,6 @@ function PropRow({);}-// ----------------------------------------------------------------------------// Project Issues — reuses the existing issues list/board components-// -----------------------------------------------------------------------------const projectViewStore = createIssueViewStore("project_issues_view");--function ProjectIssuesContent({- projectId,- projectIssues,- assigneeGroups,- assigneeGroupQueryKey,- assigneeGroupFilter,- scope,- filter,- sort,- ganttIssues,-}: {- projectId: string;- projectIssues: Issue[];- assigneeGroups?: IssueAssigneeGroup[];- assigneeGroupQueryKey?: QueryKey;- assigneeGroupFilter?: AssigneeGroupedIssuesFilter;- scope: string;- filter: MyIssuesFilter;- sort?: IssueSortParam;- ganttIssues: Issue[];-}) {- const { t } = useT("projects");- const wsId = useWorkspaceId();- const viewMode = useViewStore((s) => s.viewMode);- const statusFilters = useViewStore((s) => s.statusFilters);- const priorityFilters = useViewStore((s) => s.priorityFilters);- const assigneeFilters = useViewStore((s) => s.assigneeFilters);- const includeNoAssignee = useViewStore((s) => s.includeNoAssignee);- const creatorFilters = useViewStore((s) => s.creatorFilters);- const labelFilters = useViewStore((s) => s.labelFilters);- const agentRunningFilter = useViewStore((s) => s.agentRunningFilter);- const showSubIssues = useViewStore((s) => s.showSubIssues);-- const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));- const runningIssueIds = useMemo(() => {- const ids = new Set<string>();- for (const task of snapshot) {- if (task.status === "running" && task.issue_id) ids.add(task.issue_id);- }- return ids;- }, [snapshot]);-- const issues = useMemo(- () => filterIssues(projectIssues, { statusFilters, priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters, projectFilters: [], includeNoProject: false, labelFilters, agentRunningFilter, runningIssueIds, showSubIssues }),- [projectIssues, statusFilters, priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters, labelFilters, agentRunningFilter, runningIssueIds, showSubIssues],- );-- // Status-unfiltered companion for Swimlane.- const swimlaneIssues = useMemo(- () => filterIssues(projectIssues, { statusFilters: [], priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters, projectFilters: [], includeNoProject: false, labelFilters, agentRunningFilter, runningIssueIds, showSubIssues }),- [projectIssues, priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters, labelFilters, agentRunningFilter, runningIssueIds, showSubIssues],- );-- const activeFilters = useMemo(() => ({- priorityFilters,- assigneeFilters,- includeNoAssignee,- creatorFilters,- projectFilters: [],- includeNoProject: false,- labelFilters,- agentRunningFilter,- showSubIssues,- }), [- priorityFilters,- assigneeFilters,- includeNoAssignee,- creatorFilters,- labelFilters,- agentRunningFilter,- showSubIssues,- ]);-- // Gantt rides its own dedicated query (scheduled-only) so it doesn't have- // to wait for every status bucket to paginate in. View-store filters still- // apply so toggling priority / assignee / label hides the same bars.- const filteredGanttIssues = useMemo(- () => filterIssues(ganttIssues, { statusFilters, priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters, projectFilters: [], includeNoProject: false, labelFilters, agentRunningFilter, runningIssueIds, showSubIssues }),- [ganttIssues, statusFilters, priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters, labelFilters, agentRunningFilter, runningIssueIds, showSubIssues],- );-- const filteredAssigneeGroups = useMemo(- () => filterAssigneeGroups(assigneeGroups, { showSubIssues, agentRunningFilter, runningIssueIds }),- [assigneeGroups, showSubIssues, agentRunningFilter, runningIssueIds],- );-- const { data: childProgressMap = new Map() } = useQuery(childIssueProgressOptions(wsId));-- const visibleStatuses = useMemo(() => {- if (statusFilters.length > 0)- return BOARD_STATUSES.filter((s) => statusFilters.includes(s));- return BOARD_STATUSES;- }, [statusFilters]);-- const hiddenStatuses = useMemo(- () => BOARD_STATUSES.filter((s) => !visibleStatuses.includes(s)),- [visibleStatuses],- );-- const updateIssueMutation = useUpdateIssue();- const handleMoveIssue = useCallback(- (issueId: string, updates: Pick<UpdateIssueRequest, "status" | "assignee_type" | "assignee_id" | "position" | "parent_issue_id">, onSettled?: () => void) => {- updateIssueMutation.mutate(- { id: issueId, ...updates },- {- onError: (err) =>- toast.error(- err instanceof Error && err.message- ? err.message- : t(($) => $.detail.toast_move_issue_failed),- ),- onSettled: () => onSettled?.(),- },- );- },- [updateIssueMutation, t],- );-- // Gantt and Swimlane have their own data sources and empty states —- // we never short-circuit them here, otherwise an unscheduled/unparented- // but non-empty project would surface a misleading "no issues" CTA.- // For Board/List the bucketed cache really is the ground truth,- // so an empty result means an empty project.- if (viewMode !== "gantt" && viewMode !== "swimlane" && projectIssues.length === 0) {- return (- <div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-3 text-muted-foreground">- <ListTodo className="h-10 w-10 text-muted-foreground/40" />- <p className="text-sm">{t(($) => $.detail.empty_issues_title)}</p>- <p className="text-xs">{t(($) => $.detail.empty_issues_hint)}</p>- <Button- variant="outline"- size="sm"- className="mt-1"- onClick={() =>- useModalStore.getState().open("create-issue", { project_id: projectId })- }- >- <Plus className="size-3.5 mr-1.5" />- {t(($) => $.detail.empty_issues_new_button)}- </Button>- </div>- );- }-- return (- <div className="flex flex-col flex-1 min-h-0">- {viewMode === "board" && (- <BoardView- issues={filteredAssigneeGroups ? filteredAssigneeGroups.flatMap((group) => group.issues) : issues}- assigneeGroups={filteredAssigneeGroups}- assigneeGroupQueryKey={assigneeGroupQueryKey}- assigneeGroupFilter={assigneeGroupFilter}- visibleStatuses={visibleStatuses}- hiddenStatuses={hiddenStatuses}- onMoveIssue={handleMoveIssue}- childProgressMap={childProgressMap}- myIssuesScope={scope}- myIssuesFilter={filter}- sort={sort}- projectId={projectId}- />- )}- {viewMode === "list" && (- <ListView- issues={issues}- visibleStatuses={visibleStatuses}- childProgressMap={childProgressMap}- myIssuesScope={scope}- myIssuesFilter={filter}- sort={sort}- projectId={projectId}- onMoveIssue={handleMoveIssue}- />- )}- {viewMode === "gantt" && <GanttView issues={filteredGanttIssues} />}- {viewMode === "swimlane" && (- <SwimLaneView- issues={issues}- unfilteredIssues={swimlaneIssues}- activeFilters={activeFilters}- visibleStatuses={visibleStatuses}- hiddenStatuses={hiddenStatuses}- onMoveIssue={handleMoveIssue}- childProgressMap={childProgressMap}- myIssuesScope={scope}- myIssuesFilter={filter}- sort={sort}- projectId={projectId}- />- )}- </div>- );-}--function ProjectIssuesSurface({- projectId,- scope,- filter,-}: {- projectId: string;- scope: string;- filter: MyIssuesFilter;-}) {- const wsId = useWorkspaceId();- const viewMode = useViewStore((s) => s.viewMode);- const grouping = useViewStore((s) => s.grouping);- const sortBy = useViewStore((s) => s.sortBy);- const sortDirection = useViewStore((s) => s.sortDirection);- const statusFilters = useViewStore((s) => s.statusFilters);- const priorityFilters = useViewStore((s) => s.priorityFilters);- const assigneeFilters = useViewStore((s) => s.assigneeFilters);- const includeNoAssignee = useViewStore((s) => s.includeNoAssignee);- const creatorFilters = useViewStore((s) => s.creatorFilters);- const labelFilters = useViewStore((s) => s.labelFilters);- const usesAssigneeBoard = viewMode === "board" && grouping === "assignee";- const usesGantt = viewMode === "gantt";-- const sort = useMemo(- () => ({- sort_by: sortBy,- sort_direction: sortBy !== "position" ? sortDirection : undefined,- } as const),- [sortBy, sortDirection],- );-- const assigneeGroupFilter = useMemo<AssigneeGroupedIssuesFilter>(- () => ({- ...filter,- statuses: statusFilters.length > 0 ? statusFilters : [...BOARD_STATUSES],- priorities: priorityFilters,- assignee_filters: assigneeFilters,- include_no_assignee: includeNoAssignee,- creator_filters: creatorFilters,- label_ids: labelFilters,- }),- [assigneeFilters, creatorFilters, filter, includeNoAssignee, labelFilters, priorityFilters, statusFilters],- );- const assigneeGroupsOptions = myIssueAssigneeGroupsOptions(- wsId,- scope,- assigneeGroupFilter,- undefined,- sort,- );- // Each view owns exactly one data source. Board/List ride the bucketed- // `myIssueListOptions` cache; the assignee-grouped board uses the grouped- // endpoint; Gantt has its own scheduled-only fetch. We gate `enabled` on- // the current view so switching to Gantt doesn't re-trigger the full- // per-status fetch in the background.- const statusIssuesQuery = useQuery({- ...myIssueListOptions(wsId, scope, filter, undefined, sort),- enabled: !usesAssigneeBoard && !usesGantt,- });- const assigneeGroupsQuery = useQuery({- ...assigneeGroupsOptions,- enabled: usesAssigneeBoard,- });- // Gantt has its own data source — a single (paginated) fetch of every- // scheduled issue in the project. Independent from the bucketed Board/List- // cache so it isn't bottlenecked by per-status pagination and reacts in- // isolation to WS updates that move issues into or out of the scheduled- // set.- const ganttIssuesQuery = useQuery({- ...projectGanttIssuesOptions(wsId, projectId),- enabled: usesGantt,- });- const bucketedIssues = usesAssigneeBoard- ? (assigneeGroupsQuery.data?.groups.flatMap((group) => group.issues) ?? [])- : (statusIssuesQuery.data ?? []);- const ganttIssues = ganttIssuesQuery.data ?? [];- // What the header empty-state check looks at depends on the view: Gantt- // would otherwise be blamed for an empty Board cache, even though it has- // its own (potentially non-empty) scheduled cache.- const projectIssues = usesGantt ? ganttIssues : bucketedIssues;-- return (- <>- <IssuesHeader scopedIssues={projectIssues} allowGantt />- <ProjectIssuesContent- projectId={projectId}- projectIssues={projectIssues}- assigneeGroups={usesAssigneeBoard ? assigneeGroupsQuery.data?.groups : undefined}- assigneeGroupQueryKey={usesAssigneeBoard ? assigneeGroupsOptions.queryKey : undefined}- assigneeGroupFilter={usesAssigneeBoard ? assigneeGroupFilter : undefined}- scope={scope}- filter={filter}- sort={sort}- ganttIssues={ganttIssues}- />- <BatchActionToolbar issues={projectIssues} />- </>- );-}-// ---------------------------------------------------------------------------// ProjectDetail// ---------------------------------------------------------------------------@@ -438,9 +117,8 @@ export function ProjectDetail({ projectId }: { projectId: string }) {});}}, [project?.id, project?.title, project?.description, project?.icon, project?.status, recordRecentContext, wsId]);- const projectScope = `project:${projectId}`;- const projectFilter = useMemo<MyIssuesFilter>(- () => ({ project_id: projectId }),+ const issueScope = useMemo(+ () => ({ type: "project" as const, projectId }),[projectId],);const { data: members = [] } = useQuery(memberListOptions(wsId));@@ -856,13 +534,10 @@ export function ProjectDetail({ projectId }: { projectId: string }) {}/>- <ViewStoreProvider store={projectViewStore}>- <ProjectIssuesSurface- projectId={projectId}- scope={projectScope}- filter={projectFilter}- />- </ViewStoreProvider>+ <IssueSurface+ scope={issueScope}+ modes={["board", "list", "swimlane", "gantt"]}+ /></div></ResizablePanel>{!isMobile && <ResizableHandle />}diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 50002d6e0b..d3adce0ddf 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -858,6 +858,18 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {statusFilter = pgtype.Text{String: s, Valid: true}}+ // assignee_types narrows the list to issues assigned to the given actor+ // kinds (member / agent / squad). Mirrors the same param on+ // ListGroupedIssues so the workspace Members/Agents tabs can filter+ // server-side instead of post-filtering loaded pages on the client.+ assigneeTypesFilter := splitCommaParam(r.URL.Query().Get("assignee_types"))+ for _, assigneeType := range assigneeTypesFilter {+ if !isIssueActorType(assigneeType) {+ writeError(w, http.StatusBadRequest, "invalid assignee_types")+ return+ }+ }+// scheduled=true restricts the result to issues that have at least one of// start_date / due_date set. Used by the Project Gantt view, which only// renders schedulable rows and shouldn't pay for the full project list.@@ -917,6 +929,9 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {if len(assigneeIdsFilter) > 0 {where = append(where, fmt.Sprintf("i.assignee_id = ANY(%s::uuid[])", addArg(assigneeIdsFilter)))}+ if len(assigneeTypesFilter) > 0 {+ where = append(where, fmt.Sprintf("i.assignee_type = ANY(%s::text[])", addArg(assigneeTypesFilter)))+ }if creatorFilter.Valid {where = append(where, fmt.Sprintf("i.creator_id = %s::uuid", addArg(creatorFilter)))}diff --git a/server/internal/handler/issue_assignee_types_test.go b/server/internal/handler/issue_assignee_types_test.gonew file mode 100644index 0000000000..760336a485--- /dev/null+++ b/server/internal/handler/issue_assignee_types_test.go@@ -0,0 +1,133 @@+package handler++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"+)++// Backs the workspace Members/Agents tabs: assignee_types on ListIssues must+// filter server-side (same semantics as the ListGroupedIssues param) so the+// client no longer post-filters loaded pages, and `total` must agree with the+// filter so per-status pagination counts stay correct.+func TestListIssues_AssigneeTypesFilter(t *testing.T) {+ ctx := context.Background()+ suffix := time.Now().UnixNano()++ // Dedicated project so counts aren't polluted by other tests sharing the+ // workspace.+ var projectID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO project (workspace_id, title) VALUES ($1, $2) RETURNING id+ `, testWorkspaceID, fmt.Sprintf("Assignee Types %d", suffix)).Scan(&projectID); err != nil {+ t.Fatalf("create project: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID) })++ var agentID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent (+ workspace_id, name, description, runtime_mode, runtime_config,+ runtime_id, visibility, max_concurrent_tasks, owner_id+ )+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'workspace', 1, $4)+ RETURNING id+ `, testWorkspaceID, fmt.Sprintf("Assignee Types Agent %d", suffix), testRuntimeID, testUserID).Scan(&agentID); err != nil {+ t.Fatalf("create agent: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID) })++ insertIssue := func(title string, assigneeType, assigneeID *string) string {+ var number 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)) + 1+ WHERE id = $1 RETURNING issue_counter+ `, testWorkspaceID).Scan(&number); err != nil {+ t.Fatalf("next issue number: %v", err)+ }+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, assignee_type, assignee_id, creator_type, creator_id, position, number, project_id)+ VALUES ($1, $2, 'todo', 'none', $3, $4, 'member', $5, 0, $6, $7) RETURNING id+ `, testWorkspaceID, title, assigneeType, assigneeID, testUserID, number, projectID).Scan(&id); err != nil {+ t.Fatalf("create issue %q: %v", title, err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, id) })+ return id+ }++ memberType, agentType := "member", "agent"+ memberIssue := insertIssue(fmt.Sprintf("at-member-%d", suffix), &memberType, &testUserID)+ agentIssue := insertIssue(fmt.Sprintf("at-agent-%d", suffix), &agentType, &agentID)+ unassignedIssue := insertIssue(fmt.Sprintf("at-none-%d", suffix), nil, nil)++ list := func(query string) (ids []string, total int64) {+ path := fmt.Sprintf("/api/issues?workspace_id=%s&project_id=%s&limit=500%s",+ testWorkspaceID, projectID, query)+ w := httptest.NewRecorder()+ testHandler.ListIssues(w, newRequest("GET", path, nil))+ if w.Code != http.StatusOK {+ t.Fatalf("ListIssues: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp struct {+ Issues []IssueResponse `json:"issues"`+ Total int64 `json:"total"`+ }+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode list response: %v", err)+ }+ for _, iss := range resp.Issues {+ ids = append(ids, iss.ID)+ }+ return ids, resp.Total+ }++ // Baseline: every project issue comes back without the filter.+ allIDs, allTotal := list("")+ for _, want := range []string{memberIssue, agentIssue, unassignedIssue} {+ if !containsIssueID(allIDs, want) {+ t.Fatalf("baseline list missing %s — all=%v", want, allIDs)+ }+ }+ if allTotal != 3 {+ t.Fatalf("baseline total: want 3, got %d", allTotal)+ }++ // Members tab: only member-assigned issues, and total agrees.+ memberIDs, memberTotal := list("&assignee_types=member")+ if !containsIssueID(memberIDs, memberIssue) {+ t.Fatalf("member filter missing %s — got %v", memberIssue, memberIDs)+ }+ if containsIssueID(memberIDs, agentIssue) || containsIssueID(memberIDs, unassignedIssue) {+ t.Fatalf("member filter leaked non-member issues: %v", memberIDs)+ }+ if memberTotal != 1 {+ t.Fatalf("member total: want 1, got %d", memberTotal)+ }++ // Agents tab: agent+squad kinds — squad has no rows here, param must+ // still parse and return the agent-assigned issue only.+ agentIDs, agentTotal := list("&assignee_types=agent,squad")+ if !containsIssueID(agentIDs, agentIssue) {+ t.Fatalf("agent filter missing %s — got %v", agentIssue, agentIDs)+ }+ if containsIssueID(agentIDs, memberIssue) || containsIssueID(agentIDs, unassignedIssue) {+ t.Fatalf("agent filter leaked non-agent issues: %v", agentIDs)+ }+ if agentTotal != 1 {+ t.Fatalf("agent total: want 1, got %d", agentTotal)+ }++ // Unknown actor kinds are a client bug — reject, don't coerce.+ bad := httptest.NewRecorder()+ testHandler.ListIssues(bad, newRequest("GET", fmt.Sprintf(+ "/api/issues?workspace_id=%s&assignee_types=bogus", testWorkspaceID), nil))+ if bad.Code != http.StatusBadRequest {+ t.Fatalf("invalid assignee_types: expected 400, got %d: %s", bad.Code, bad.Body.String())+ }+}