Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5954: feat: saved issue views V1 (MUL-4796) (#6516)
Naiyuan Qing984a2c2bffba
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/issues/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/issues/page.tsxindex 0892c7753b..bd09dd5364 100644--- a/apps/web/app/[workspaceSlug]/(dashboard)/issues/page.tsx+++ b/apps/web/app/[workspaceSlug]/(dashboard)/issues/page.tsx@@ -1,11 +1,22 @@"use client";+import { Suspense } from "react";import { IssuesPage } from "@multica/views/issues/components";import { ErrorBoundary } from "@multica/ui/components/common/error-boundary";+import { useIssueViewUrlSync } from "../../../../platform/use-issue-view-url-sync";++function IssueViewUrlSync() {+ // useSearchParams requires a Suspense boundary in the app router.+ useIssueViewUrlSync({ scope_type: "workspace" });+ return null;+}export default function Page() {return (<ErrorBoundary>+ <Suspense fallback={null}>+ <IssueViewUrlSync />+ </Suspense><IssuesPage /></ErrorBoundary>);diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/my-issues/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/my-issues/page.tsxindex dc0161d8d5..667e5cbbd6 100644--- a/apps/web/app/[workspaceSlug]/(dashboard)/my-issues/page.tsx+++ b/apps/web/app/[workspaceSlug]/(dashboard)/my-issues/page.tsx@@ -1,7 +1,22 @@"use client";+import { Suspense } from "react";import { MyIssuesPage } from "@multica/views/my-issues";+import { useIssueViewUrlSync } from "../../../../platform/use-issue-view-url-sync";++function IssueViewUrlSync() {+ // useSearchParams requires a Suspense boundary in the app router.+ useIssueViewUrlSync({ scope_type: "my" });+ return null;+}export default function Page() {- return <MyIssuesPage />;+ return (+ <>+ <Suspense fallback={null}>+ <IssueViewUrlSync />+ </Suspense>+ <MyIssuesPage />+ </>+ );}diff --git a/apps/web/platform/use-issue-view-url-sync.ts b/apps/web/platform/use-issue-view-url-sync.tsnew file mode 100644index 0000000000..2e8fb047e0--- /dev/null+++ b/apps/web/platform/use-issue-view-url-sync.ts@@ -0,0 +1,52 @@+"use client";++import { useEffect, useRef } from "react";+import { useSearchParams } from "next/navigation";+import { useWorkspaceId } from "@multica/core/hooks";+import {+ issueViewContainerKey,+ useActiveIssueViewStore,+} from "@multica/core/issue-views/active-view-store";+import type { IssueViewScope } from "@multica/core/issue-views/queries";++/**+ * Web-only two-way sync between the active saved view and `?view=<id>`:+ * shareable links in, durable reloads out. Next.js navigation belongs to+ * the platform layer, so this lives here and page wrappers mount it beside+ * the shared page component.+ *+ * The URL wins on mount (a pasted link opens that view); afterwards the+ * store drives the URL via history.replaceState — no navigation, no scroll+ * reset, no re-render of the route tree.+ */+export function useIssueViewUrlSync(scope: IssueViewScope) {+ const wsId = useWorkspaceId();+ const searchParams = useSearchParams();+ const containerKey = issueViewContainerKey(wsId, scope);+ const setActive = useActiveIssueViewStore((s) => s.setActive);+ const activeViewId = useActiveIssueViewStore(+ (s) => s.active[containerKey] ?? null,+ );++ // Mount: adopt the URL's view id (deep link / reload).+ const adopted = useRef(false);+ useEffect(() => {+ if (adopted.current) return;+ adopted.current = true;+ const fromUrl = searchParams.get("view");+ if (fromUrl) setActive(containerKey, fromUrl);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- adopt once per mount+ }, []);++ // Store → URL. replaceState keeps back-button history clean: opening and+ // closing views is view state, not navigation.+ useEffect(() => {+ if (!adopted.current) return;+ const url = new URL(window.location.href);+ const current = url.searchParams.get("view");+ if ((activeViewId ?? null) === (current ?? null)) return;+ if (activeViewId) url.searchParams.set("view", activeViewId);+ else url.searchParams.delete("view");+ window.history.replaceState(window.history.state, "", url.toString());+ }, [activeViewId]);+}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex e74e7abd60..2604d43a05 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -344,6 +344,13 @@ import {EMPTY_LIST_GITHUB_REPOSITORIES_RESPONSE,RuntimeModelListRequestSchema,MALFORMED_RUNTIME_MODEL_LIST_REQUEST,+ IssueViewSchema,+ IssueViewListSchema,+ IssueViewPreferenceSchema,+ EMPTY_ISSUE_VIEW_PREFERENCE,+ type IssueView,+ type IssueViewPreference,+ type CreateIssueViewRequest,} from "./schemas";/** Identifies the calling client to the server.@@ -3035,9 +3042,96 @@ export class ApiClient {});}+ // Saved issue views (MUL-4796). Responses go through zod so installed+ // desktop builds survive backend drift; a malformed list degrades to []+ // (selector shows only built-ins) rather than blanking the page.+ async listIssueViews(params: {+ scope_type: string;+ scope_id?: string | null;+ }): Promise<IssueView[]> {+ const qs = new URLSearchParams({ scope_type: params.scope_type });+ if (params.scope_id) qs.set("scope_id", params.scope_id);+ const raw = await this.fetch<unknown>(`/api/issue-views?${qs.toString()}`);+ return parseWithFallback(raw, IssueViewListSchema, [], {+ endpoint: "GET /api/issue-views",+ });+ }++ async createIssueView(data: CreateIssueViewRequest): Promise<IssueView | null> {+ const raw = await this.fetch<unknown>("/api/issue-views", {+ method: "POST",+ body: JSON.stringify(data),+ });+ // null fallback: the create itself succeeded server-side; a response we+ // cannot parse must not crash the dialog — callers refetch the list.+ return parseWithFallback(raw, IssueViewSchema.nullable(), null, {+ endpoint: "POST /api/issue-views",+ });+ }++ async updateIssueView(+ id: string,+ data: {+ name?: string;+ visibility?: "private" | "workspace";+ scope_variant?: string | null;+ query?: Record<string, unknown>;+ display?: Record<string, unknown>;+ expected_revision: number;+ },+ ): Promise<IssueView | null> {+ const raw = await this.fetch<unknown>(`/api/issue-views/${id}`, {+ method: "PATCH",+ body: JSON.stringify(data),+ });+ return parseWithFallback(raw, IssueViewSchema.nullable(), null, {+ endpoint: "PATCH /api/issue-views/{id}",+ });+ }++ async getIssueView(id: string): Promise<IssueView | null> {+ const raw = await this.fetch<unknown>(`/api/issue-views/${id}`);+ return parseWithFallback(raw, IssueViewSchema.nullable(), null, {+ endpoint: "GET /api/issue-views/{id}",+ });+ }++ async deleteIssueView(id: string): Promise<void> {+ await this.fetch(`/api/issue-views/${id}`, { method: "DELETE" });+ }++ async getIssueViewPreference(params: {+ scope_type: string;+ scope_id?: string | null;+ }): Promise<IssueViewPreference> {+ const qs = new URLSearchParams({ scope_type: params.scope_type });+ if (params.scope_id) qs.set("scope_id", params.scope_id);+ const raw = await this.fetch<unknown>(`/api/issue-view-preferences?${qs.toString()}`);+ return parseWithFallback(raw, IssueViewPreferenceSchema, EMPTY_ISSUE_VIEW_PREFERENCE, {+ endpoint: "GET /api/issue-view-preferences",+ });+ }++ async putIssueViewPreference(data: {+ scope_type: string;+ scope_id?: string | null;+ prefs: { hidden: string[]; order: string[] };+ }): Promise<IssueViewPreference> {+ const raw = await this.fetch<unknown>("/api/issue-view-preferences", {+ method: "PUT",+ body: JSON.stringify(data),+ });+ return parseWithFallback(raw, IssueViewPreferenceSchema, EMPTY_ISSUE_VIEW_PREFERENCE, {+ endpoint: "PUT /api/issue-view-preferences",+ });+ }+// Pinsasync listPins(): Promise<PinnedItem[]> {- return this.fetch("/api/pins");+ // include=view is the capability opt-in: the server withholds view pins+ // from clients that don't declare support (old builds treated any+ // non-issue pin as a project pin and auto-deleted it on 404).+ return this.fetch("/api/pins?include=view");}async createPin(data: CreatePinRequest): Promise<PinnedItem> {diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 01b89bbcf3..1d7b165e02 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -48,6 +48,7 @@ import {TimelineEntriesSchema,UserSchema,} from "./schemas";+import { IssueViewSchema, IssueViewListSchema } from "./schemas";import { parseWithFallback } from "./schema";const baseIssue = {@@ -1244,6 +1245,63 @@ describe("RuntimeModelListRequestSchema", () => {});});+describe("IssueViewSchema", () => {+ const valid = {+ id: "v1",+ workspace_id: "ws1",+ owner_id: "u1",+ name: "Needs review",+ scope_type: "workspace",+ scope_id: null,+ scope_variant: null,+ visibility: "workspace",+ definition_version: 1,+ query: { statusFilters: ["in_review"] },+ display: { viewMode: "board" },+ revision: 3,+ created_at: "2026-08-06T00:00:00Z",+ updated_at: "2026-08-06T00:00:00Z",+ };++ it("parses a well-formed view and keeps unknown future fields", () => {+ const parsed = IssueViewSchema.parse({ ...valid, future_field: "keep me" });+ expect(parsed.name).toBe("Needs review");+ expect(parsed.query).toEqual({ statusFilters: ["in_review"] });+ expect((parsed as unknown as { future_field?: string }).future_field).toBe("keep me");+ });++ it("defaults missing definition blobs instead of failing", () => {+ const parsed = IssueViewSchema.parse({ id: "v2" });+ expect(parsed.query).toEqual({});+ expect(parsed.display).toEqual({});+ expect(parsed.revision).toBe(1);+ });++ it("degrades a malformed list response to [] via parseWithFallback", () => {+ expect(+ parseWithFallback({ nonsense: true }, IssueViewListSchema, [], {+ endpoint: "GET /api/issue-views",+ }),+ ).toEqual([]);+ expect(+ parseWithFallback(null, IssueViewListSchema, [], {+ endpoint: "GET /api/issue-views",+ }),+ ).toEqual([]);+ });++ it("degrades a malformed detail response to null — NOT an error", () => {+ // The sidebar's pinned view rows hinge on this distinction: a parse+ // fallback (null, no error) hides the row, while only a REAL 404+ // error may ever unpin. A malformed body must never destroy a pin.+ expect(+ parseWithFallback({ nonsense: true }, IssueViewSchema.nullable(), null, {+ endpoint: "GET /api/issue-views/{id}",+ }),+ ).toBeNull();+ });+});+// WeCom smart-bot installation schemas. These gate UI affordances (the Connect// dialog, the "ask your operator" state, the revoked-vs-active badge), so a// malformed response must degrade to the safe state rather than a broken one.diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 83ca28e8fb..bc0cd2f0bf 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -211,6 +211,62 @@ export const EMPTY_RESOURCE_LABELS_RESPONSE: ResourceLabelsResponse = {labels: [],};+// Saved issue views (MUL-4796). `query`/`display` are opaque definition+// blobs interpreted client-side per `definition_version` — keep them as+// loose records so newer servers can add fields freely. `scope_type` /+// `visibility` stay lenient strings; downstream code uses explicit `===`+// comparisons and default branches per the API-compat rules.+export const IssueViewSchema = z.object({+ id: z.string(),+ workspace_id: z.string().default(""),+ owner_id: z.string().default(""),+ name: z.string().default(""),+ scope_type: z.string().default("workspace"),+ scope_id: z.string().nullish(),+ scope_variant: z.string().nullish(),+ visibility: z.string().default("private"),+ definition_version: z.number().default(1),+ query: z.record(z.string(), z.unknown()).default({}),+ display: z.record(z.string(), z.unknown()).default({}),+ revision: z.number().default(1),+ created_at: z.string().default(""),+ updated_at: z.string().default(""),+}).loose();++export type IssueView = z.infer<typeof IssueViewSchema>;++export const IssueViewListSchema = z.array(IssueViewSchema);++export const IssueViewPreferenceSchema = z.object({+ scope_type: z.string().default("workspace"),+ scope_id: z.string().nullish(),+ prefs: z.object({+ hidden: z.array(z.string()).default([]),+ order: z.array(z.string()).default([]),+ }).loose().default({ hidden: [], order: [] }),+ updated_at: z.string().default(""),+}).loose();++export type IssueViewPreference = z.infer<typeof IssueViewPreferenceSchema>;++export const EMPTY_ISSUE_VIEW_PREFERENCE: IssueViewPreference = {+ scope_type: "workspace",+ scope_id: null,+ prefs: { hidden: [], order: [] },+ updated_at: "",+};++export interface CreateIssueViewRequest {+ name: string;+ scope_type: "workspace" | "my" | "project";+ scope_id?: string | null;+ scope_variant?: "assigned" | "created" | "involved" | "any" | "members" | "agents" | null;+ visibility: "private" | "workspace";+ definition_version: number;+ query: Record<string, unknown>;+ display: Record<string, unknown>;+}+// Custom property definitions. `type` stays a lenient string so newer server// types don't break installed clients; UI narrows with isKnownPropertyType.export const IssuePropertySchema = z.object({diff --git a/packages/core/issue-views/active-view-store.ts b/packages/core/issue-views/active-view-store.tsnew file mode 100644index 0000000000..abe50df6cf--- /dev/null+++ b/packages/core/issue-views/active-view-store.ts@@ -0,0 +1,62 @@+"use client";++import { create } from "zustand";+import type { FilterDimension } from "../issues/stores/view-store";+import type { IssueViewScope } from "./queries";++/**+ * Which saved view is open on each surface container, keyed by+ * `${wsId}:${scope_type}[:${scope_id}]`. Client/view state (zustand per the+ * state rules): NOT persisted — on web the URL `?view=` param is the durable+ * carrier, and resurrecting a deleted view from storage would strand users.+ */+export function issueViewContainerKey(wsId: string, scope: IssueViewScope): string {+ return scope.scope_id+ ? `${wsId}:${scope.scope_type}:${scope.scope_id}`+ : `${wsId}:${scope.scope_type}`;+}++interface ActiveIssueViewState {+ active: Record<string, string>;+ setActive: (containerKey: string, viewId: string | null) => void;+}++export const useActiveIssueViewStore = create<ActiveIssueViewState>((set) => ({+ active: {},+ setActive: (containerKey, viewId) =>+ set((state) => {+ const active = { ...state.active };+ if (viewId) active[containerKey] = viewId;+ else delete active[containerKey];+ return { active };+ }),+}));++/**+ * Dimensions fixed by a view's saved query. These render as locked chips+ * (no remove affordance) and their sections are disabled in the filter menu+ * — the view's identity cannot be edited in place, only narrowed around.+ */+export function lockedDimensionsFromQuery(+ query: Record<string, unknown>,+): Set<FilterDimension> {+ const locked = new Set<FilterDimension>();+ const nonEmptyArray = (v: unknown) => Array.isArray(v) && v.length > 0;+ if (nonEmptyArray(query.statusFilters)) locked.add("status");+ if (nonEmptyArray(query.priorityFilters)) locked.add("priority");+ if (nonEmptyArray(query.assigneeFilters) || query.includeNoAssignee === true) {+ locked.add("assignee");+ }+ if (nonEmptyArray(query.creatorFilters)) locked.add("creator");+ if (nonEmptyArray(query.projectFilters) || query.includeNoProject === true) {+ locked.add("project");+ }+ if (nonEmptyArray(query.labelFilters)) locked.add("label");+ const propertyFilters = query.propertyFilters;+ if (propertyFilters && typeof propertyFilters === "object") {+ for (const [id, selected] of Object.entries(propertyFilters as Record<string, unknown>)) {+ if (nonEmptyArray(selected)) locked.add(`property:${id}`);+ }+ }+ return locked;+}diff --git a/packages/core/issue-views/baseline.ts b/packages/core/issue-views/baseline.tsnew file mode 100644index 0000000000..86e15217e4--- /dev/null+++ b/packages/core/issue-views/baseline.ts@@ -0,0 +1,98 @@+import type { ActorFilterValue, FilterSnapshot } from "../issues/stores/view-store";+import type { IssuePriority, IssueStatus } from "../types";+import { ALL_STATUSES, PRIORITY_DISPLAY_ORDER } from "../issues/config";++/**+ * The open saved view's query, normalized for two jobs:+ * - membership checks (`has`): the filter menu renders view-fixed VALUES as+ * checked-and-disabled while everything else stays selectable;+ * - resets (`raw`): removing a user-added chip returns its dimension to the+ * view's values, never to empty.+ * The view's own conditions never appear as chips — the view name carries+ * them; chips only show what the user layered on top.+ */+export interface IssueViewBaseline {+ status: Set<string>;+ priority: Set<string>;+ /** Actor keys as `${type}:${id}`. */+ assignee: Set<string>;+ includeNoAssignee: boolean;+ creator: Set<string>;+ project: Set<string>;+ includeNoProject: boolean;+ label: Set<string>;+ /** Property definition id → fixed option ids. */+ property: Map<string, Set<string>>;+ /** Enum-sanitized snapshot, safe to hand straight to `resetFiltersTo`. */+ raw: FilterSnapshot;+}++export function actorFilterKey(actor: ActorFilterValue): string {+ return `${actor.type}:${actor.id}`;+}++function stringArray(v: unknown): string[] {+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];+}++function actorArray(v: unknown): ActorFilterValue[] {+ if (!Array.isArray(v)) return [];+ return v.filter(+ (x): x is ActorFilterValue =>+ !!x && typeof x === "object" && typeof (x as ActorFilterValue).id === "string",+ );+}++export function baselineFromQuery(query: Record<string, unknown>): IssueViewBaseline {+ // Unknown enum members (a newer server, a hand-edited blob) are dropped —+ // a value the store cannot represent must not enter the snapshot.+ const statusFilters = stringArray(query.statusFilters).filter(+ (s): s is IssueStatus => (ALL_STATUSES as readonly string[]).includes(s),+ );+ const priorityFilters = stringArray(query.priorityFilters).filter(+ (p): p is IssuePriority => (PRIORITY_DISPLAY_ORDER as readonly string[]).includes(p),+ );+ const assigneeFilters = actorArray(query.assigneeFilters);+ const creatorFilters = actorArray(query.creatorFilters);+ const projectFilters = stringArray(query.projectFilters);+ const labelFilters = stringArray(query.labelFilters);+ const includeNoAssignee = query.includeNoAssignee === true;+ const includeNoProject = query.includeNoProject === true;++ const propertyFilters: Record<string, string[]> = {};+ const property = new Map<string, Set<string>>();+ if (query.propertyFilters && typeof query.propertyFilters === "object") {+ for (const [id, selected] of Object.entries(+ query.propertyFilters as Record<string, unknown>,+ )) {+ const values = stringArray(selected);+ if (values.length > 0) {+ propertyFilters[id] = values;+ property.set(id, new Set(values));+ }+ }+ }++ return {+ status: new Set(statusFilters),+ priority: new Set(priorityFilters),+ assignee: new Set(assigneeFilters.map(actorFilterKey)),+ includeNoAssignee,+ creator: new Set(creatorFilters.map(actorFilterKey)),+ project: new Set(projectFilters),+ includeNoProject,+ label: new Set(labelFilters),+ property,+ raw: {+ statusFilters,+ priorityFilters,+ assigneeFilters,+ includeNoAssignee,+ creatorFilters,+ projectFilters,+ includeNoProject,+ labelFilters,+ propertyFilters,+ },+ };+}diff --git a/packages/core/issue-views/index.ts b/packages/core/issue-views/index.tsnew file mode 100644index 0000000000..dc820af97f--- /dev/null+++ b/packages/core/issue-views/index.ts@@ -0,0 +1,6 @@+export * from "./queries";+export * from "./mutations";+export * from "./active-view-store";+export * from "./use-active-view";+export * from "./baseline";+export * from "./preferences";diff --git a/packages/core/issue-views/mutations.ts b/packages/core/issue-views/mutations.tsnew file mode 100644index 0000000000..1b290cf9cf--- /dev/null+++ b/packages/core/issue-views/mutations.ts@@ -0,0 +1,66 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { api } from "../api";+import type { IssueView } from "../api/schemas";+import type { CreateIssueViewRequest } from "../api/schemas";+import { issueViewKeys } from "./queries";++/** Create is a confirmed flow (dialog + toast) — no optimism, await then+ * invalidate so every surface's selector refetches. */+export function useCreateIssueView(wsId: string) {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (data: CreateIssueViewRequest) => api.createIssueView(data),+ onSuccess: (created) => {+ // Seed the created view into its scope's list BEFORE invalidating:+ // callers activate it immediately, and an id absent from the (stale)+ // list reads as "view deleted" and bounces the surface back to the+ // default tab. The invalidate still fetches the canonical list.+ if (created) {+ queryClient.setQueryData<IssueView[]>(+ issueViewKeys.list(wsId, {+ scope_type: created.scope_type as "workspace" | "my" | "project",+ scope_id: created.scope_id,+ }),+ (old) =>+ old && !old.some((v) => v.id === created.id)+ ? [...old, created]+ : old,+ );+ }+ void queryClient.invalidateQueries({ queryKey: issueViewKeys.all(wsId) });+ },+ });+}++export interface UpdateIssueViewInput {+ id: string;+ name?: string;+ visibility?: "private" | "workspace";+ scope_variant?: string | null;+ query?: Record<string, unknown>;+ display?: Record<string, unknown>;+ expected_revision: number;+}++/** Optimistic-free by design: edits are a confirmed dialog flow and the 409+ * conflict path (someone else edited first) needs the server's answer. */+export function useUpdateIssueView(wsId: string) {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: ({ id, ...data }: UpdateIssueViewInput) =>+ api.updateIssueView(id, data),+ onSuccess: () => {+ void queryClient.invalidateQueries({ queryKey: issueViewKeys.all(wsId) });+ },+ });+}++export function useDeleteIssueView(wsId: string) {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (id: string) => api.deleteIssueView(id),+ onSuccess: () => {+ void queryClient.invalidateQueries({ queryKey: issueViewKeys.all(wsId) });+ },+ });+}diff --git a/packages/core/issue-views/preferences.ts b/packages/core/issue-views/preferences.tsnew file mode 100644index 0000000000..dd1f1e9b2f--- /dev/null+++ b/packages/core/issue-views/preferences.ts@@ -0,0 +1,94 @@+"use client";++import { queryOptions, useMutation, useQueryClient } from "@tanstack/react-query";+import { api } from "../api";+import type { IssueViewPreference } from "../api/schemas";+import type { IssueViewScope } from "./queries";++export interface ViewBarPrefs {+ hidden: string[];+ order: string[];+}++export const EMPTY_VIEW_BAR_PREFS: ViewBarPrefs = { hidden: [], order: [] };++export const issueViewPrefKeys = {+ all: (wsId: string) => ["issue-view-prefs", wsId] as const,+ scope: (wsId: string, scope: IssueViewScope) =>+ [...issueViewPrefKeys.all(wsId), scope.scope_type, scope.scope_id ?? null] as const,+};++export function issueViewPreferenceOptions(wsId: string, scope: IssueViewScope) {+ return queryOptions({+ queryKey: issueViewPrefKeys.scope(wsId, scope),+ queryFn: () => api.getIssueViewPreference(scope),+ enabled: !!wsId,+ });+}++/**+ * Whole-document upsert with an optimistic patch: show/hide toggles and+ * drag-reorder are the canonical optimistic case (locally predictable, same+ * screen, trivial rollback).+ */+export function useUpdateIssueViewPreference(wsId: string, scope: IssueViewScope) {+ const queryClient = useQueryClient();+ const queryKey = issueViewPrefKeys.scope(wsId, scope);+ return useMutation({+ mutationFn: (prefs: ViewBarPrefs) =>+ api.putIssueViewPreference({ ...scope, prefs }),+ onMutate: async (prefs) => {+ await queryClient.cancelQueries({ queryKey });+ const previous = queryClient.getQueryData<IssueViewPreference>(queryKey);+ const optimistic: IssueViewPreference = {+ scope_type: scope.scope_type,+ scope_id: scope.scope_id ?? null,+ updated_at: previous?.updated_at ?? "",+ prefs: { ...prefs },+ };+ queryClient.setQueryData<IssueViewPreference>(queryKey, optimistic);+ return { previous };+ },+ onError: (_err, _prefs, context) => {+ if (context?.previous) queryClient.setQueryData(queryKey, context.previous);+ },+ onSettled: () => {+ void queryClient.invalidateQueries({ queryKey });+ },+ });+}++/**+ * Compose the view bar: apply the user's order, drop hidden items, keep the+ * anchor built-in ("builtin:" first item) always visible so nobody locks+ * themselves out of a surface. Unknown ids in prefs (deleted views) are+ * ignored; items absent from `order` append in their natural position.+ */+export function applyViewBarPrefs<T extends { barItemId: string }>(+ items: T[],+ prefs: ViewBarPrefs | undefined,+ anchorId: string,+): { visible: T[]; hiddenSet: Set<string>; ordered: T[] } {+ const order = prefs?.order ?? [];+ const hiddenSet = new Set(prefs?.hidden ?? []);+ hiddenSet.delete(anchorId);++ const byId = new Map(items.map((item) => [item.barItemId, item]));+ const ordered: T[] = [];+ for (const id of order) {+ const item = byId.get(id);+ if (item) {+ ordered.push(item);+ byId.delete(id);+ }+ }+ for (const item of items) {+ if (byId.has(item.barItemId)) ordered.push(item);+ }++ return {+ ordered,+ hiddenSet,+ visible: ordered.filter((item) => !hiddenSet.has(item.barItemId)),+ };+}diff --git a/packages/core/issue-views/queries.ts b/packages/core/issue-views/queries.tsnew file mode 100644index 0000000000..9c18cb7ddb--- /dev/null+++ b/packages/core/issue-views/queries.ts@@ -0,0 +1,48 @@+import { queryOptions } from "@tanstack/react-query";+import { api } from "../api";++/** The (scope_type, scope_id) container a surface's views live in. */+export interface IssueViewScope {+ scope_type: "workspace" | "my" | "project";+ scope_id?: string | null;+}++export const issueViewKeys = {+ all: (wsId: string) => ["issue-views", wsId] as const,+ list: (wsId: string, scope: IssueViewScope) =>+ [...issueViewKeys.all(wsId), scope.scope_type, scope.scope_id ?? null] as const,+ detail: (wsId: string, id: string) =>+ [...issueViewKeys.all(wsId), "detail", id] as const,+};++export function issueViewListOptions(wsId: string, scope: IssueViewScope) {+ return queryOptions({+ queryKey: issueViewKeys.list(wsId, scope),+ queryFn: () => api.listIssueViews(scope),+ enabled: !!wsId,+ });+}++/** One view by id — the sidebar pin rows resolve their label/target here. */+export function issueViewDetailOptions(wsId: string, id: string) {+ return queryOptions({+ queryKey: issueViewKeys.detail(wsId, id),+ queryFn: () => api.getIssueView(id),+ enabled: !!wsId && !!id,+ });+}++/**+ * Client-side mirror of the server's canManageIssueView: the owner, or a+ * workspace owner/admin for views shared to the workspace. Drives which+ * affordances render — the server re-checks on every write.+ */+export function canManageIssueView(+ view: { owner_id: string; visibility: string },+ userId: string | null,+ role: string | null | undefined,+): boolean {+ if (!userId) return false;+ if (view.owner_id === userId) return true;+ return view.visibility === "workspace" && (role === "owner" || role === "admin");+}diff --git a/packages/core/issue-views/use-active-view.ts b/packages/core/issue-views/use-active-view.tsnew file mode 100644index 0000000000..6267cc9dbb--- /dev/null+++ b/packages/core/issue-views/use-active-view.ts@@ -0,0 +1,66 @@+"use client";++import { useCallback } from "react";+import { useQuery } from "@tanstack/react-query";+import type { IssueView } from "../api/schemas";+import { issueViewListOptions, type IssueViewScope } from "./queries";+import {+ issueViewContainerKey,+ useActiveIssueViewStore,+} from "./active-view-store";++const EMPTY_VIEWS: IssueView[] = [];++/**+ * The open saved view for one surface container, resolved against the+ * container's list query. `missing` turns true when an id is active but the+ * settled list no longer carries it (deleted / access revoked) — callers+ * exit the view and toast.+ */+export function useActiveIssueView(+ wsId: string,+ scope: IssueViewScope | null,+) {+ const containerKey = scope ? issueViewContainerKey(wsId, scope) : "";+ const activeViewId = useActiveIssueViewStore((s) =>+ containerKey ? (s.active[containerKey] ?? null) : null,+ );+ const setActiveInStore = useActiveIssueViewStore((s) => s.setActive);++ const listQuery = useQuery({+ ...issueViewListOptions(wsId, scope ?? { scope_type: "workspace" }),+ enabled: !!scope && !!wsId,+ });+ const views = listQuery.data ?? EMPTY_VIEWS;+ const activeView = activeViewId+ ? (views.find((v) => v.id === activeViewId) ?? null)+ : null;+ // "Missing" must never fire off a STALE list: right after a create the+ // active id is set before the invalidated list lands, and treating that+ // gap as "view deleted" bounces the surface back to the default tab.+ const missing =+ !!activeViewId &&+ listQuery.isSuccess &&+ !listQuery.isFetching &&+ !activeView;++ const setActive = useCallback(+ (viewId: string | null) => {+ if (containerKey) setActiveInStore(containerKey, viewId);+ },+ [containerKey, setActiveInStore],+ );++ return {+ containerKey,+ activeViewId,+ activeView,+ views,+ // Preference writes prune against this list — callers must not persist+ // a prune until it has actually loaded (an empty in-flight list would+ // read as "every view was deleted").+ viewsReady: listQuery.isSuccess,+ setActive,+ missing,+ };+}diff --git a/packages/core/issues/mutations.test.tsx b/packages/core/issues/mutations.test.tsxindex 76ca4f5dcb..212647b492 100644--- a/packages/core/issues/mutations.test.tsx+++ b/packages/core/issues/mutations.test.tsx@@ -10,8 +10,6 @@ import { setApiInstance } from "../api";import type { ApiClient } from "../api/client";import {useBatchUpdateIssues,- useLoadMoreByAssigneeGroup,- useLoadMoreByStatus,useResolveComment,useUpdateIssue,} from "./mutations";@@ -21,13 +19,9 @@ import {} from "./queries";import { inboxKeys } from "../inbox/queries";import type {- GroupedIssuesResponse,InboxItem,Issue,ListIssuesCache,- ListIssuesParams,- ListGroupedIssuesParams,- ListIssuesResponse,TimelineEntry,} from "../types";@@ -98,296 +92,6 @@ function createWrapper(qc: QueryClient) {};}-describe("useLoadMoreByStatus", () => {- let qc: QueryClient;- let listIssues: ReturnType<typeof vi.fn<(p?: ListIssuesParams) => Promise<ListIssuesResponse>>>;-- beforeEach(() => {- qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });- listIssues = vi.fn();- setApiInstance({ listIssues } as unknown as ApiClient);- });-- afterEach(() => {- qc.clear();- vi.restoreAllMocks();- });-- it("targets the sorted cache key and forwards sort to the API", async () => {- const sort: IssueSortParam = { sort_by: "priority", sort_direction: "desc" };- const activeKey = issueKeys.listSorted(WS_ID, sort);- const seed: ListIssuesCache = {- byStatus: {- todo: { issues: [makeIssue(1)], total: 3 },- },- };- qc.setQueryData<ListIssuesCache>(activeKey, seed);-- listIssues.mockResolvedValue({- issues: [makeIssue(2), makeIssue(3)],- total: 3,- });-- const { result } = renderHook(- () => useLoadMoreByStatus("todo", undefined, sort),- { wrapper: createWrapper(qc) },- );-- expect(result.current.hasMore).toBe(true);- expect(result.current.total).toBe(3);-- await act(async () => {- await result.current.loadMore();- });-- expect(listIssues).toHaveBeenCalledWith({- status: "todo",- limit: 50,- offset: 1,- sort_by: "priority",- sort_direction: "desc",- });-- const updated = qc.getQueryData<ListIssuesCache>(activeKey);- expect(updated?.byStatus.todo?.issues).toHaveLength(3);- expect(updated?.byStatus.todo?.issues.map((i) => i.id)).toEqual([- "issue-1",- "issue-2",- "issue-3",- ]);- });-- it("ignores a stale cache entry under a different sort", async () => {- // Stale entry from a previous sort lingers (kept by gcTime / keepPreviousData).- const staleSort: IssueSortParam = { sort_by: "priority", sort_direction: "desc" };- qc.setQueryData<ListIssuesCache>(issueKeys.listSorted(WS_ID, staleSort), {- byStatus: { todo: { issues: [makeIssue(99)], total: 99 } },- });-- // The active sort cache has its own bucket — load-more must target THIS one.- const activeSort: IssueSortParam = { sort_by: "position", sort_direction: undefined };- const activeKey = issueKeys.listSorted(WS_ID, activeSort);- qc.setQueryData<ListIssuesCache>(activeKey, {- byStatus: { todo: { issues: [makeIssue(1)], total: 2 } },- });-- listIssues.mockResolvedValue({- issues: [makeIssue(2)],- total: 2,- });-- const { result } = renderHook(- () => useLoadMoreByStatus("todo", undefined, activeSort),- { wrapper: createWrapper(qc) },- );-- // total derives from the active key, not the stale one.- expect(result.current.total).toBe(2);-- await act(async () => {- await result.current.loadMore();- });-- expect(listIssues).toHaveBeenCalledWith(- expect.objectContaining({ offset: 1, sort_by: "position" }),- );-- const active = qc.getQueryData<ListIssuesCache>(activeKey);- expect(active?.byStatus.todo?.issues.map((i) => i.id)).toEqual([- "issue-1",- "issue-2",- ]);-- // Stale cache is untouched.- const stale = qc.getQueryData<ListIssuesCache>(issueKeys.listSorted(WS_ID, staleSort));- expect(stale?.byStatus.todo?.issues.map((i) => i.id)).toEqual(["issue-99"]);- });-- it("targets the myList scoped cache when myIssues is provided", async () => {- const sort: IssueSortParam = { sort_by: "title", sort_direction: "asc" };- const myIssues = { scope: "assigned", filter: { assignee_id: "user-1" } };- const activeKey = issueKeys.myListSorted(WS_ID, myIssues.scope, myIssues.filter, sort);- qc.setQueryData<ListIssuesCache>(activeKey, {- byStatus: { in_progress: { issues: [makeIssue(1, { status: "in_progress" })], total: 2 } },- });-- listIssues.mockResolvedValue({- issues: [makeIssue(2, { status: "in_progress" })],- total: 2,- });-- const { result } = renderHook(- () => useLoadMoreByStatus("in_progress", myIssues, sort),- { wrapper: createWrapper(qc) },- );-- await act(async () => {- await result.current.loadMore();- });-- expect(listIssues).toHaveBeenCalledWith({- status: "in_progress",- limit: 50,- offset: 1,- sort_by: "title",- sort_direction: "asc",- assignee_id: "user-1",- });-- const updated = qc.getQueryData<ListIssuesCache>(activeKey);- 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);- qc.setQueryData<ListIssuesCache>(activeKey, {- byStatus: { todo: { issues: [makeIssue(1)], total: 2 } },- });-- listIssues.mockResolvedValue({ issues: [makeIssue(2)], total: 2 });-- const { result } = renderHook(- () => useLoadMoreByStatus("todo", myIssues),- { wrapper: createWrapper(qc) },- );-- expect(result.current.total).toBe(2);- expect(result.current.hasMore).toBe(true);-- await act(async () => {- await result.current.loadMore();- });-- const updated = qc.getQueryData<ListIssuesCache>(activeKey);- expect(updated?.byStatus.todo?.issues).toHaveLength(2);- });-});--describe("useLoadMoreByAssigneeGroup", () => {- let qc: QueryClient;- let listGroupedIssues: ReturnType<- typeof vi.fn<(p: ListGroupedIssuesParams) => Promise<GroupedIssuesResponse>>- >;-- beforeEach(() => {- qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });- listGroupedIssues = vi.fn();- setApiInstance({ listGroupedIssues } as unknown as ApiClient);- });-- afterEach(() => {- qc.clear();- vi.restoreAllMocks();- });-- it("forwards sort to the grouped API and appends into the right group", async () => {- const sort: IssueSortParam = { sort_by: "priority", sort_direction: "desc" };- const queryKey = ["custom", "assignee-groups", "ws-1"] as const;- const seed: GroupedIssuesResponse = {- groups: [- {- id: "assignee:member:user-1",- assignee_type: "member",- assignee_id: "user-1",- issues: [makeIssue(1, { assignee_type: "member", assignee_id: "user-1" })],- total: 2,- },- ],- };- qc.setQueryData<GroupedIssuesResponse>(queryKey, seed);-- listGroupedIssues.mockResolvedValue({- groups: [- {- id: "assignee:member:user-1",- assignee_type: "member",- assignee_id: "user-1",- issues: [makeIssue(2, { assignee_type: "member", assignee_id: "user-1" })],- total: 2,- },- ],- });-- const { result } = renderHook(- () =>- useLoadMoreByAssigneeGroup(- {- id: "assignee:member:user-1",- assignee_type: "member",- assignee_id: "user-1",- },- queryKey,- { statuses: ["todo"] },- sort,- ),- { wrapper: createWrapper(qc) },- );-- expect(result.current.hasMore).toBe(true);- expect(result.current.total).toBe(2);-- await act(async () => {- await result.current.loadMore();- });-- expect(listGroupedIssues).toHaveBeenCalledWith({- group_by: "assignee",- limit: 50,- offset: 1,- sort_by: "priority",- sort_direction: "desc",- statuses: ["todo"],- group_assignee_type: "member",- group_assignee_id: "user-1",- });-- const updated = qc.getQueryData<GroupedIssuesResponse>(queryKey);- expect(updated?.groups[0]?.issues.map((i) => i.id)).toEqual([- "issue-1",- "issue-2",- ]);- });-});-describe("useUpdateIssue — optimistic move keeps every bucketed board in sync", () => {const sort: IssueSortParam = { sort_by: "position", sort_direction: undefined };const myScope = "assigned";diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.tsindex f16f302ab1..cfaeccc12d 100644--- a/packages/core/issues/mutations.ts+++ b/packages/core/issues/mutations.ts@@ -1,13 +1,6 @@-import { useState, useCallback } from "react";import { hashKey, useMutation, useQueryClient, type QueryKey } from "@tanstack/react-query";import { api } from "../api";-import {- issueKeys,- ISSUE_PAGE_SIZE,- type AssigneeGroupedIssuesFilter,- type IssueSortParam,- type MyIssuesFilter,-} from "./queries";+import { issueKeys } from "./queries";import { projectKeys } from "../projects/queries";import { inboxKeys } from "../inbox/queries";import {@@ -19,11 +12,7 @@ import {type IssueTableRowCache,} from "./cache-coordinator";import { issueChangedDims } from "./surface/membership";-import {- addIssueToBuckets,- getBucket,- setBucket,-} from "./cache-helpers";+import { addIssueToBuckets } from "./cache-helpers";import {cleanupDeletedIssueCaches,collectDeletedIssueCacheMetadata,@@ -36,7 +25,7 @@ import {import { useWorkspaceId } from "../hooks";import { useRecentContextStore } from "../chat/recent-context-store";import { useRecentIssuesStore } from "./stores";-import type { GroupedIssuesResponse, InboxItem, Issue, IssueAssigneeGroup, IssueReaction, IssueStatus } from "../types";+import type { InboxItem, Issue, IssueReaction } from "../types";import type {CreateIssueRequest,ListIssuesCache,@@ -75,125 +64,6 @@ export type UpdateIssueMutationInput = {// Per-status pagination// ----------------------------------------------------------------------------/**- * Paginate one status column into the cache. Works for both the workspace- * issue list and per-scope My Issues lists (pass `myIssues` to target the- * latter).- *- * `sort` must match the sort the consuming `useQuery` was called with —- * the query key embeds it (see `listSorted` / `myListSorted`), so a load-more- * with the wrong sort would patch a stale cache entry that nobody is- * subscribed to. It is also threaded into the API request so the appended- * page lines up with the server-side ordering of the existing items.- */-export function useLoadMoreByStatus(- status: IssueStatus,- myIssues?: { scope: string; filter: MyIssuesFilter },- sort?: IssueSortParam,-) {- const qc = useQueryClient();- const wsId = useWorkspaceId();- const [isLoading, setIsLoading] = useState(false);-- const activeKey = myIssues- ? issueKeys.myListSorted(wsId, myIssues.scope, myIssues.filter, sort)- : issueKeys.listSorted(wsId, sort);- const cache = qc.getQueryData<ListIssuesCache>(activeKey);- const bucket = cache?.byStatus[status];- const loaded = bucket?.issues.length ?? 0;- const total = bucket?.total ?? 0;- const hasMore = loaded < total;-- const loadMore = useCallback(async () => {- if (isLoading || !hasMore) return;- setIsLoading(true);- try {- const res = await api.listIssues({- status,- limit: ISSUE_PAGE_SIZE,- offset: loaded,- ...sort,- ...myIssues?.filter,- });- qc.setQueryData<ListIssuesCache>(activeKey, (old) => {- if (!old) return old;- const prev = getBucket(old, status);- const existingIds = new Set(prev.issues.map((i) => i.id));- const appended = res.issues.filter((i) => !existingIds.has(i.id));- return setBucket(old, status, {- issues: [...prev.issues, ...appended],- total: res.total,- });- });- } finally {- setIsLoading(false);- }- }, [qc, activeKey, status, loaded, hasMore, isLoading, myIssues?.filter, sort]);-- return { loadMore, hasMore, isLoading, total };-}--/**- * Paginate one assignee-grouped board column into the cache. `queryKey`- * already pins the active cache entry (it's the same object the consuming- * `useQuery` registered), so the cache lookup and `setQueryData` target the- * right row. `sort` is threaded into the API request so the appended page- * lines up with the server-side ordering of the existing items.- */-export function useLoadMoreByAssigneeGroup(- group: Pick<IssueAssigneeGroup, "id" | "assignee_type" | "assignee_id">,- queryKey: QueryKey,- filter: AssigneeGroupedIssuesFilter,- sort?: IssueSortParam,-) {- const qc = useQueryClient();- const [isLoading, setIsLoading] = useState(false);-- const cache = qc.getQueryData<GroupedIssuesResponse>(queryKey);- const cachedGroup = cache?.groups.find((g) => g.id === group.id);- const loaded = cachedGroup?.issues.length ?? 0;- const total = cachedGroup?.total ?? 0;- const hasMore = loaded < total;-- const loadMore = useCallback(async () => {- if (isLoading || !hasMore) return;- setIsLoading(true);- try {- const res = await api.listGroupedIssues({- group_by: "assignee",- limit: ISSUE_PAGE_SIZE,- offset: loaded,- ...sort,- ...filter,- group_assignee_type: group.assignee_type ?? "none",- group_assignee_id: group.assignee_id ?? undefined,- });- const nextGroup = res.groups[0];- if (!nextGroup) return;-- qc.setQueryData<GroupedIssuesResponse>(queryKey, (old) => {- if (!old) return old;- return {- groups: old.groups.map((existing) => {- if (existing.id !== nextGroup.id) return existing;- const existingIds = new Set(existing.issues.map((issue) => issue.id));- const appended = nextGroup.issues.filter((issue) => !existingIds.has(issue.id));- return {- ...existing,- issues: [...existing.issues, ...appended],- total: nextGroup.total,- };- }),- };- });- } finally {- setIsLoading(false);- }- }, [filter, group.assignee_id, group.assignee_type, hasMore, isLoading, loaded, qc, queryKey, sort]);-- return { loadMore, hasMore, isLoading, total };-}-// ---------------------------------------------------------------------------// Issue CRUD// ---------------------------------------------------------------------------diff --git a/packages/core/issues/queries.test.ts b/packages/core/issues/queries.test.tsindex c6b84a744e..bdf5e1311e 100644--- a/packages/core/issues/queries.test.ts+++ b/packages/core/issues/queries.test.ts@@ -13,14 +13,10 @@ import type {} from "../types";import {CHILDREN_BY_PARENTS_CHUNK_SIZE,- ISSUE_FLAT_PAGE_SIZE,PROJECT_GANTT_MAX_ISSUES,PROJECT_GANTT_PAGE_LIMIT,childrenByParentsOptions,childIssuesOptions,- compareIssuesForSort,- issueFlatExportOptions,- issueFlatListOptions,issueIdentifierOptions,issueKeys,issueTableRowPageOptions,@@ -392,236 +388,37 @@ describe("projectGanttIssuesOptions", () => {const options = projectGanttIssuesOptions(WS_ID, PROJECT_ID);expect(options.queryKey).toEqual(issueKeys.projectGantt(WS_ID, PROJECT_ID));});-});--describe("flat issue table queries", () => {- let qc: QueryClient;-- beforeEach(() => {- qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });- });- afterEach(() => {- qc.clear();- vi.restoreAllMocks();- });-- it("loads one offset page for the interactive table window", async () => {+ it("threads the assignee-type tab into the request and the cache key", async () => {const listIssues = vi.fn<(params?: ListIssuesParams) => Promise<ListIssuesResponse>>().mockResolvedValue({ issues: [makeIssue(1)], total: 1 });installFakeApi(listIssues);- const data = await qc.fetchInfiniteQuery(- issueFlatListOptions(- WS_ID,- "project:project-1",- {- project_id: PROJECT_ID,- q: "release train",- statuses: ["todo", "in_progress"],- priorities: ["high"],- assignee_filters: [{ type: "member", id: "member-1" }],- include_no_assignee: true,- creator_filters: [{ type: "agent", id: "agent-1" }],- project_ids: ["project-2"],- include_no_project: true,- label_ids: ["label-1"],- top_level_only: true,- },- undefined,- { sort_by: "updated_at", sort_direction: "desc" },- ),- );-- expect(data.pages).toHaveLength(1);- expect(data.pages[0]?.issues.map((issue) => issue.id)).toEqual([- "issue-1",+ const agentsTab = projectGanttIssuesOptions(WS_ID, PROJECT_ID, [+ "agent",+ "squad",]);- expect(listIssues).toHaveBeenCalledWith({- project_id: PROJECT_ID,- q: "release train",- statuses: ["todo", "in_progress"],- priorities: ["high"],- assignee_filters: [{ type: "member", id: "member-1" }],- include_no_assignee: true,- creator_filters: [{ type: "agent", id: "agent-1" }],- project_ids: ["project-2"],- include_no_project: true,- label_ids: ["label-1"],- top_level_only: true,- sort_by: "updated_at",- sort_direction: "desc",- limit: ISSUE_FLAT_PAGE_SIZE,- offset: 0,- });- });-- it("walks every page only for an explicit full CSV export", async () => {- const first = Array.from({ length: ISSUE_FLAT_PAGE_SIZE }, (_, index) =>- makeIssue(index + 1),+ await qc.fetchQuery(agentsTab);++ expect(listIssues).toHaveBeenCalledWith(+ expect.objectContaining({+ project_id: PROJECT_ID,+ scheduled: true,+ assignee_types: ["agent", "squad"],+ }),);- const second = [makeIssue(101), makeIssue(102), makeIssue(103)];- const listIssues = vi- .fn<(params?: ListIssuesParams) => Promise<ListIssuesResponse>>()- .mockImplementation(async (params) => ({- issues: (params?.offset ?? 0) === 0 ? first : second,- total: 103,- }));- installFakeApi(listIssues);-- const issues = await qc.fetchQuery(- issueFlatExportOptions(- WS_ID,- "project:project-1",- { project_id: PROJECT_ID },- undefined,- { sort_by: "status", sort_direction: "asc" },- ),+ // Distinct tabs must not share a cache entry.+ expect(agentsTab.queryKey).not.toEqual(+ projectGanttIssuesOptions(WS_ID, PROJECT_ID).queryKey,);-- expect(issues).toHaveLength(103);- expect(listIssues).toHaveBeenCalledTimes(2);- expect(listIssues.mock.calls.map(([params]) => params?.offset)).toEqual([- 0,- ISSUE_FLAT_PAGE_SIZE,- ]);- });-- it("does not silently truncate exports above ten thousand issues", async () => {- const total = 10_001;- const listIssues = vi+ // The unrestricted tab never sends the param.+ const unrestricted = vi.fn<(params?: ListIssuesParams) => Promise<ListIssuesResponse>>()- .mockImplementation(async (params) => {- const offset = params?.offset ?? 0;- const count = Math.min(ISSUE_FLAT_PAGE_SIZE, total - offset);- return {- issues: Array.from({ length: count }, (_, index) =>- makeIssue(offset + index + 1),- ),- total,- };- });- installFakeApi(listIssues);-- const issues = await qc.fetchQuery(- issueFlatExportOptions(WS_ID, "workspace:all", {}, undefined),- );-- expect(issues).toHaveLength(total);- expect(listIssues).toHaveBeenCalledTimes(101);- expect(listIssues.mock.calls.at(-1)?.[0]?.offset).toBe(10_000);- });-- it("keeps paging when the server returns fewer rows than requested", async () => {- const total = 101;- const serverPageSize = 40;- const listIssues = vi- .fn<(params?: ListIssuesParams) => Promise<ListIssuesResponse>>()- .mockImplementation(async (params) => {- const offset = params?.offset ?? 0;- const count = Math.min(serverPageSize, total - offset);- return {- issues: Array.from({ length: count }, (_, index) =>- makeIssue(offset + index + 1),- ),- total,- };- });- installFakeApi(listIssues);-- const issues = await qc.fetchQuery(- issueFlatExportOptions(WS_ID, "workspace:all", {}, undefined),- );-- expect(issues).toHaveLength(total);- expect(listIssues.mock.calls.map(([params]) => params?.offset)).toEqual([- 0, 40, 80,- ]);- });-- it("fails explicitly if the export endpoint stops advancing offsets", async () => {- const page = Array.from({ length: ISSUE_FLAT_PAGE_SIZE }, (_, index) =>- makeIssue(index + 1),- );- const listIssues = vi- .fn<(params?: ListIssuesParams) => Promise<ListIssuesResponse>>()- .mockResolvedValue({ issues: page, total: ISSUE_FLAT_PAGE_SIZE * 2 });- installFakeApi(listIssues);-- await expect(- qc.fetchQuery(- issueFlatExportOptions(WS_ID, "workspace:all", {}, undefined),- ),- ).rejects.toThrow("Issue export pagination did not advance");- expect(listIssues).toHaveBeenCalledTimes(2);- });-- it("deduplicates the three My Issues relations and restores global sort order", async () => {- const shared = makeIssue(1, { status: "done" });- const backlog = makeIssue(2, { status: "backlog" });- const todo = makeIssue(3, { status: "todo" });- const listIssues = vi- .fn<(params?: ListIssuesParams) => Promise<ListIssuesResponse>>()- .mockImplementation(async (params) => {- if (params?.assignee_id) {- return { issues: [shared], total: 1 };- }- if (params?.creator_id) {- return { issues: [backlog, shared], total: 2 };- }- return { issues: [todo], total: 1 };- });- installFakeApi(listIssues);-- const issues = await qc.fetchQuery(- issueFlatExportOptions(- WS_ID,- "all",- {},- "user-1",- { sort_by: "status", sort_direction: "asc" },- ),- );-- expect(issues.map((issue) => issue.id)).toEqual([- backlog.id,- todo.id,- shared.id,- ]);- expect(listIssues).toHaveBeenCalledTimes(3);- });-});--describe("compareIssuesForSort tie-break", () => {- it("orders equal sort values by created_at DESC then id DESC (server ORDER BY parity)", () => {- // Same status AND same created_at — only the id disambiguates. Without a- // unique final key the relative order would depend on input order, which- // is exactly the instability that duplicates/drops rows at page- // boundaries server-side.- const first = makeIssue(1, { created_at: "2025-01-01T00:00:00Z" });- const second = makeIssue(2, { created_at: "2025-01-01T00:00:00Z" });- const sort = { sort_by: "status", sort_direction: "asc" } as const;-- expect(- [first, second].sort((a, b) => compareIssuesForSort(a, b, sort)).map((i) => i.id),- ).toEqual(["issue-2", "issue-1"]);- expect(- [second, first].sort((a, b) => compareIssuesForSort(a, b, sort)).map((i) => i.id),- ).toEqual(["issue-2", "issue-1"]);- });-- it("applies the id tie-break to created_at sorts as well", () => {- const first = makeIssue(1, { created_at: "2025-01-01T00:00:00Z" });- const second = makeIssue(2, { created_at: "2025-01-01T00:00:00Z" });- const sort = { sort_by: "created_at", sort_direction: "desc" } as const;-- expect(- [first, second].sort((a, b) => compareIssuesForSort(a, b, sort)).map((i) => i.id),- ).toEqual(["issue-2", "issue-1"]);- expect(- [second, first].sort((a, b) => compareIssuesForSort(a, b, sort)).map((i) => i.id),- ).toEqual(["issue-2", "issue-1"]);+ .mockResolvedValue({ issues: [], total: 0 });+ installFakeApi(unrestricted);+ await qc.fetchQuery(projectGanttIssuesOptions(WS_ID, PROJECT_ID));+ expect(unrestricted.mock.calls[0]![0]).not.toHaveProperty("assignee_types");});});diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex e80a35dcca..c6c40dca92 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -6,8 +6,8 @@ import {} from "@tanstack/react-query";import { api } from "../api";import type {- GroupedIssuesResponse,Issue,+ IssueAssigneeType,IssueStatus,IssueTableFacetsRequest,IssueTableGroupSpec,@@ -105,8 +105,16 @@ export const issueKeys = {* cache helpers don't have to special-case a non-bucketed shape under* the `my` prefix.*/- projectGantt: (wsId: string, projectId: string) =>- [...issueKeys.projectGanttAll(wsId), projectId] as const,+ projectGantt: (+ wsId: string,+ projectId: string,+ assigneeTypes?: IssueAssigneeType[],+ ) =>+ [+ ...issueKeys.projectGanttAll(wsId),+ projectId,+ assigneeTypes ?? null,+ ] as const,detail: (wsId: string, id: string) =>[...issueKeys.all(wsId), "detail", id] as const,/** Resolve a bare issue identifier (e.g. "MUL-123") to an issue. */@@ -207,7 +215,6 @@ export type AssigneeGroupedIssuesFilter = Omit</** Page size per status column. */export const ISSUE_PAGE_SIZE = 50;-export const ISSUE_FLAT_PAGE_SIZE = 100;/*** Statuses fetched and paginated into the list/board cache — every lifecycle@@ -242,173 +249,6 @@ async function fetchFirstPages(filter: MyIssuesFilter = {}, sort?: IssueSortParareturn { byStatus };}-/**- * "All my issues" — union of three server filters:- * assignee_id=me OR creator_id=me OR involves_user_id=me- *- * The backend has no OR-across-user-filters today, so we run the three- * existing single-filter fetches in parallel and dedupe on the client by- * issue id within each status bucket. Order within each bucket preserves- * the first-seen position (each sub-fetch is already server-sorted).- *- * Personal lists are bounded (tens to a few hundred issues across all- * three relations), so 3× the request count is acceptable — a single- * fetchFirstPages already runs 7 status fetches in parallel, so the total- * here is 21 small parallel requests. Easy enough; no need to add a new- * backend query just for this scope.- *- * `total` per bucket is set to the merged length, not the true server- * total — pagination on the "All" scope is out of scope; the first- * 50-per-status × 3 widening (deduped) is what the page renders.- */-const MERGE_PRIORITY_RANK: Record<string, number> = { urgent: 0, high: 1, medium: 2, low: 3, none: 4 };-const MERGE_STATUS_RANK: Record<string, number> = {- backlog: 0,- todo: 1,- in_progress: 2,- in_review: 3,- done: 4,- blocked: 5,- cancelled: 6,-};--/**- * Comparator mirroring the server's ORDER BY semantics (including- * `property:<id>` sorts and missing-values-last). The merged "All" scope- * concatenates three independently-ordered queries, so without a re-sort the- * relation order (assigned → created → involves) would override the sort the- * user picked — e.g. assigned=9 rendering before created=1 (review round 3).- */-export function compareIssuesForSort(a: Issue, b: Issue, sort?: IssueSortParam): number {- const by = sort?.sort_by ?? "position";- const dir = by !== "position" && sort?.sort_direction === "desc" ? -1 : 1;- // created_at DESC then id DESC, mirroring the server's unique ORDER BY- // suffix — ids disambiguate bulk-created issues that share a timestamp.- const tieBreak = () =>- new Date(b.created_at).getTime() - new Date(a.created_at).getTime() ||- (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);-- const missingAware = (av: string | null, bv: string | null): number => {- if (!av && !bv) return tieBreak();- if (!av) return 1;- if (!bv) return -1;- return dir * av.localeCompare(bv) || tieBreak();- };-- if (by.startsWith("property:")) {- const propertyId = by.slice("property:".length);- const av = a.properties?.[propertyId];- const bv = b.properties?.[propertyId];- const aMissing = av === undefined || Array.isArray(av) || typeof av === "boolean";- const bMissing = bv === undefined || Array.isArray(bv) || typeof bv === "boolean";- if (aMissing && bMissing) return tieBreak();- if (aMissing) return 1;- if (bMissing) return -1;- if (typeof av === "number" && typeof bv === "number") return dir * (av - bv) || tieBreak();- return dir * String(av).localeCompare(String(bv)) || tieBreak();- }- switch (by) {- case "status":- return dir * ((MERGE_STATUS_RANK[a.status] ?? 9) - (MERGE_STATUS_RANK[b.status] ?? 9)) || tieBreak();- case "priority":- return dir * ((MERGE_PRIORITY_RANK[a.priority] ?? 9) - (MERGE_PRIORITY_RANK[b.priority] ?? 9)) || tieBreak();- case "title":- return dir * a.title.localeCompare(b.title) || tieBreak();- case "created_at":- return dir * (new Date(a.created_at).getTime() - new Date(b.created_at).getTime()) || tieBreak();- case "updated_at":- return dir * (new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime()) || tieBreak();- case "start_date":- return missingAware(a.start_date, b.start_date);- case "due_date":- return missingAware(a.due_date, b.due_date);- case "position":- default:- return a.position - b.position || tieBreak();- }-}--async function fetchAllFlatPages(- filter: IssueFlatFilter,- sort?: IssueSortParam,-): Promise<Issue[]> {- const issues: Issue[] = [];- const seenIds = new Set<string>();- let offset = 0;- while (true) {- const response = await api.listIssues({- ...filter,- ...sort,- limit: ISSUE_FLAT_PAGE_SIZE,- offset,- });- let added = 0;- for (const issue of response.issues) {- if (seenIds.has(issue.id)) continue;- seenIds.add(issue.id);- issues.push(issue);- added += 1;- }- if (issues.length >= response.total) break;- if (response.issues.length === 0 || added === 0) {- throw new Error("Issue export pagination did not advance");- }- // Advance by what the server actually returned. This guarantees progress- // even if an older server clamps the requested page size differently.- offset += response.issues.length;- }- return issues;-}--async function fetchAllMyFlatIssues(- userId: string,- filter: IssueFlatFilter,- sort?: IssueSortParam,-): Promise<Issue[]> {- const relations = await Promise.all([- fetchAllFlatPages({ ...filter, assignee_id: userId }, sort),- fetchAllFlatPages({ ...filter, creator_id: userId }, sort),- fetchAllFlatPages({ ...filter, involves_user_id: userId }, sort),- ]);- const byId = new Map<string, Issue>();- for (const issues of relations) {- for (const issue of issues) byId.set(issue.id, issue);- }- return [...byId.values()].sort((a, b) => compareIssuesForSort(a, b, sort));-}--export function issueFlatListOptions(- wsId: string,- scope: string,- filter: IssueFlatFilter,- userId?: string,- sort?: IssueSortParam,-) {- const allMyIssues = scope === "all" && !!userId;- return infiniteQueryOptions({- queryKey: issueKeys.flat(wsId, scope, filter, sort),- initialPageParam: 0,- queryFn: async ({ pageParam }) => {- if (allMyIssues) {- const issues = await fetchAllMyFlatIssues(userId, filter, sort);- return { issues, total: issues.length };- }- return api.listIssues({- ...filter,- ...sort,- limit: ISSUE_FLAT_PAGE_SIZE,- offset: pageParam,- });- },- getNextPageParam: (lastPage, allPages) => {- if (allMyIssues) return undefined;- const loaded = allPages.reduce((count, page) => count + page.issues.length, 0);- return loaded < lastPage.total ? loaded : undefined;- },- placeholderData: keepPreviousData,- });-}-export function issueTableGroupsOptions(wsId: string,query: IssueTableQuerySpec,@@ -483,115 +323,13 @@ export function issueTableFacetsOptions(});}-export function issueFlatExportOptions(- wsId: string,- scope: string,- filter: IssueFlatFilter,- userId?: string,- sort?: IssueSortParam,-) {- return queryOptions({- queryKey: issueKeys.flatExport(wsId, scope, filter, sort),- queryFn: () =>- scope === "all" && userId- ? fetchAllMyFlatIssues(userId, filter, sort)- : fetchAllFlatPages(filter, sort),- staleTime: 0,- });-}--async function fetchAllMyFirstPages(userId: string, sort?: IssueSortParam): Promise<ListIssuesCache> {- const [byAssignee, byCreator, byInvolves] = await Promise.all([- fetchFirstPages({ assignee_id: userId }, sort),- fetchFirstPages({ creator_id: userId }, sort),- fetchFirstPages({ involves_user_id: userId }, sort),- ]);- const byStatus: ListIssuesCache["byStatus"] = {};- for (const status of PAGINATED_STATUSES) {- const seen = new Set<string>();- const merged: Issue[] = [];- for (const cache of [byAssignee, byCreator, byInvolves]) {- const bucket = cache.byStatus[status];- if (!bucket) continue;- for (const issue of bucket.issues) {- if (seen.has(issue.id)) continue;- seen.add(issue.id);- merged.push(issue);- }- }- merged.sort((a, b) => compareIssuesForSort(a, b, sort));- byStatus[status] = { issues: merged, total: merged.length };- }- return { byStatus };-}--/**- * Sibling of {@link fetchAllMyFirstPages} for the assignee-grouped board- * view. Runs the three single-filter grouped queries in parallel and- * merges groups by (assignee_type, assignee_id), deduping issues within- * each group. Extra filters from the page (statuses, priorities, etc.)- * pass through unchanged.- */-async function fetchAllMyAssigneeGroups(- userId: string,- filter: AssigneeGroupedIssuesFilter,- sort?: IssueSortParam,-): Promise<GroupedIssuesResponse> {- const variants: AssigneeGroupedIssuesFilter[] = [- { ...filter, assignee_id: userId },- { ...filter, creator_id: userId },- { ...filter, involves_user_id: userId },- ];- const responses = await Promise.all(- variants.map((f) =>- api.listGroupedIssues({- group_by: "assignee",- limit: ISSUE_PAGE_SIZE,- offset: 0,- ...sort,- ...f,- }),- ),- );- const groupKey = (g: GroupedIssuesResponse["groups"][number]) =>- `${g.assignee_type ?? "_"}::${g.assignee_id ?? "_"}`;- const merged = new Map<string, GroupedIssuesResponse["groups"][number]>();- for (const res of responses) {- for (const group of res.groups) {- const key = groupKey(group);- const existing = merged.get(key);- if (!existing) {- merged.set(key, {- ...group,- issues: [...group.issues],- total: group.issues.length,- });- continue;- }- const seen = new Set(existing.issues.map((i) => i.id));- for (const issue of group.issues) {- if (seen.has(issue.id)) continue;- seen.add(issue.id);- existing.issues.push(issue);- }- existing.total = existing.issues.length;- }- }- const groups = [...merged.values()];- for (const group of groups) {- group.issues.sort((a, b) => compareIssuesForSort(a, b, sort));- }- return { groups };-}-/*** CACHE SHAPE NOTE: The raw cache stores {@link ListIssuesCache} (buckets keyed* by status, each with `{ issues, total }`), and `select` flattens it to* `Issue[]` for consumers. Mutations and ws-updaters must use* `setQueryData<ListIssuesCache>(...)` and preserve the byStatus shape.*- * Fetches the first page of each paginated status in parallel. Use- * {@link useLoadMoreByStatus} to paginate a specific status into the cache.+ * Fetches the first page of each paginated status in parallel.*/export function issueListOptions(wsId: string, sort?: IssueSortParam) {return queryOptions({@@ -602,51 +340,6 @@ export function issueListOptions(wsId: string, sort?: IssueSortParam) {});}-export function issueAssigneeGroupsOptions(- wsId: string,- filter: AssigneeGroupedIssuesFilter,- sort?: IssueSortParam,-) {- return queryOptions<GroupedIssuesResponse>({- queryKey: issueKeys.assigneeGroups(wsId, { ...filter, ...sort }),- queryFn: () =>- api.listGroupedIssues({- group_by: "assignee",- limit: ISSUE_PAGE_SIZE,- offset: 0,- ...sort,- ...filter,- }),- placeholderData: keepPreviousData,- });-}--/**- * Server-filtered issue list for the My Issues page.- * Each scope gets its own cache entry so switching tabs is instant after first load.- */-export function myIssueListOptions(- wsId: string,- scope: string,- filter: MyIssuesFilter,- // Required when scope === "all" — the user id whose three relations- // (assignee, creator, agents+squads) we union over. For every other- // scope the filter object already carries the relevant id and userId- // is ignored.- userId?: string,- sort?: IssueSortParam,-) {- return queryOptions({- queryKey: issueKeys.myListSorted(wsId, scope, filter, sort),- queryFn: () =>- scope === "all" && userId- ? fetchAllMyFirstPages(userId, sort)- : fetchFirstPages(filter, sort),- select: flattenIssueBuckets,- placeholderData: keepPreviousData,- });-}-/*** Page size for the scheduled-issue fetch. The Gantt view always pulls every* scheduled issue (no client pagination), so this is just the chunk size we@@ -662,13 +355,17 @@ export const PROJECT_GANTT_PAGE_LIMIT = 500;*/export const PROJECT_GANTT_MAX_ISSUES = 10_000;-async function fetchProjectGanttIssues(projectId: string) {+async function fetchProjectGanttIssues(+ projectId: string,+ assigneeTypes?: IssueAssigneeType[],+) {const issues = [];let offset = 0;while (offset < PROJECT_GANTT_MAX_ISSUES) {const res = await api.listIssues({project_id: projectId,scheduled: true,+ ...(assigneeTypes?.length ? { assignee_types: assigneeTypes } : {}),limit: PROJECT_GANTT_PAGE_LIMIT,offset,});@@ -693,35 +390,16 @@ async function fetchProjectGanttIssues(projectId: string) {* `total` is reached so an oversized project can't silently lose bars past* the first page.*/-export function projectGanttIssuesOptions(wsId: string, projectId: string) {- return queryOptions({- queryKey: issueKeys.projectGantt(wsId, projectId),- queryFn: () => fetchProjectGanttIssues(projectId),- });-}--export function myIssueAssigneeGroupsOptions(+export function projectGanttIssuesOptions(wsId: string,- scope: string,- filter: AssigneeGroupedIssuesFilter,- // See myIssueListOptions for the userId contract — only consulted when- // scope === "all", and powers the 3-fetch grouped union.- userId?: string,- sort?: IssueSortParam,+ projectId: string,+ // The page's assignee-type tab narrows the Gantt exactly like every+ // other mode — same scope, same single mapping upstream.+ assigneeTypes?: IssueAssigneeType[],) {- return queryOptions<GroupedIssuesResponse>({- queryKey: issueKeys.myAssigneeGroups(wsId, scope, { ...filter, ...sort }),- queryFn: () =>- scope === "all" && userId- ? fetchAllMyAssigneeGroups(userId, filter, sort)- : api.listGroupedIssues({- group_by: "assignee",- limit: ISSUE_PAGE_SIZE,- offset: 0,- ...sort,- ...filter,- }),- placeholderData: keepPreviousData,+ return queryOptions({+ queryKey: issueKeys.projectGantt(wsId, projectId, assigneeTypes),+ queryFn: () => fetchProjectGanttIssues(projectId, assigneeTypes),});}diff --git a/packages/core/issues/stores/index.ts b/packages/core/issues/stores/index.tsindex e21da55950..0b35c11095 100644--- a/packages/core/issues/stores/index.ts+++ b/packages/core/issues/stores/index.ts@@ -15,7 +15,12 @@ export {useViewStore,useViewStoreApi,} from "./view-store-context";-export { useIssuesScopeStore, type IssuesScope } from "./issues-scope-store";+export {+ useIssuesScope,+ useIssuesScopeStore,+ type IssuesScope,+ type IssuesScopePageKey,+} from "./issues-scope-store";export { useCommentCollapseStore } from "./comment-collapse-store";export {useResolvedExpandStore,diff --git a/packages/core/issues/stores/issues-scope-store.test.ts b/packages/core/issues/stores/issues-scope-store.test.tsnew file mode 100644index 0000000000..22e152b9a4--- /dev/null+++ b/packages/core/issues/stores/issues-scope-store.test.ts@@ -0,0 +1,38 @@+// @vitest-environment jsdom+import { beforeEach, describe, expect, it } from "vitest";+import { useIssuesScope, useIssuesScopeStore } from "./issues-scope-store";++describe("issues scope store", () => {+ beforeEach(() => {+ useIssuesScopeStore.setState({ scopes: {} });+ });++ it("keeps each page's tab independent", () => {+ const { setScope } = useIssuesScopeStore.getState();+ setScope("project:p1", "agents");+ setScope("issues", "members");++ const { scopes } = useIssuesScopeStore.getState();+ expect(scopes["project:p1"]).toBe("agents");+ expect(scopes["issues"]).toBe("members");+ expect(scopes["project:p2"]).toBeUndefined();+ });++ it("defaults an untouched page to the unrestricted tab", () => {+ // Same fallback the useIssuesScope hook applies.+ const { scopes } = useIssuesScopeStore.getState();+ expect(scopes["project:p9"] ?? "all").toBe("all");+ expect(useIssuesScope).toBeTypeOf("function");+ });++ it("migrates the v0 global tab onto the Issues page only", () => {+ const migrate = useIssuesScopeStore.persist.getOptions().migrate!;+ expect(migrate({ scope: "agents" }, 0)).toEqual({+ scopes: { issues: "agents" },+ });+ // v0 "all" (or garbage) starts every page fresh.+ expect(migrate({ scope: "all" }, 0)).toEqual({ scopes: {} });+ expect(migrate({ bogus: true }, 0)).toEqual({ scopes: {} });+ expect(migrate(undefined, 0)).toEqual({ scopes: {} });+ });+});diff --git a/packages/core/issues/stores/issues-scope-store.ts b/packages/core/issues/stores/issues-scope-store.tsindex f4cfacad32..00b23b36b8 100644--- a/packages/core/issues/stores/issues-scope-store.ts+++ b/packages/core/issues/stores/issues-scope-store.ts@@ -7,22 +7,52 @@ import { defaultStorage } from "../../platform/storage";export type IssuesScope = "all" | "members" | "agents";+/**+ * Page identity for the assignee-type tab. Every surface remembers its own+ * tab — the Issues page under "issues", each project page under+ * `project:<id>` — so switching tabs inside one project never drags the+ * Issues page (or another project) along with it.+ */+export type IssuesScopePageKey = "issues" | `project:${string}`;+interface IssuesScopeState {- scope: IssuesScope;- setScope: (scope: IssuesScope) => void;+ scopes: Partial<Record<IssuesScopePageKey, IssuesScope>>;+ setScope: (page: IssuesScopePageKey, scope: IssuesScope) => void;}export const useIssuesScopeStore = create<IssuesScopeState>()(persist((set) => ({- scope: "all",- setScope: (scope) => set({ scope }),+ scopes: {},+ setScope: (page, scope) =>+ set((state) => ({ scopes: { ...state.scopes, [page]: scope } })),}),{name: "multica_issues_scope",+ version: 1,storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),+ migrate: (persisted, version) => {+ // v0 stored one tab shared by every page; carry it over as the+ // Issues page's tab and let project pages start fresh on "all".+ if (version === 0) {+ const legacy = (persisted as { scope?: IssuesScope } | undefined)+ ?.scope;+ return {+ scopes:+ legacy === "members" || legacy === "agents"+ ? { issues: legacy }+ : {},+ } as IssuesScopeState;+ }+ return persisted as IssuesScopeState;+ },},),);+/** The page's current tab; "all" until the user picks one. */+export function useIssuesScope(page: IssuesScopePageKey): IssuesScope {+ return useIssuesScopeStore((s) => s.scopes[page] ?? "all");+}+registerForWorkspaceRehydration(() => useIssuesScopeStore.persist.rehydrate());diff --git a/packages/core/issues/stores/surface-view-store.ts b/packages/core/issues/stores/surface-view-store.tsindex dcd1ff20f4..7424f3fb7b 100644--- a/packages/core/issues/stores/surface-view-store.ts+++ b/packages/core/issues/stores/surface-view-store.ts@@ -124,6 +124,29 @@ export function getIssueSurfaceViewStore(return store;}+/**+ * First-open seeding for saved-view surfaces (`view:<id>` keys): apply the+ * view's stored definition ONLY when this user has no local state for the+ * surface yet. Later opens keep the user's own adjustments — the definition+ * is a default, not a sync source.+ */+export function seedIssueSurfaceViewState(+ surfaceKey: string,+ definition: unknown,+) {+ const hasLocal =+ issueSurfaceViewRegistryStore.getState().surfaces[surfaceKey] !== undefined;+ if (hasLocal) return;+ const store = getIssueSurfaceViewStore(surfaceKey);+ // The definition is a server-owned jsonb blob — run it through the same+ // sanitizer persisted snapshots use so a malformed field degrades to the+ // default instead of poisoning the store. setState triggers the persist+ // subscription, so the seed becomes the surface's local state exactly+ // like a user-made change would.+ const defaults = viewStoreSlice(store.setState);+ store.setState(mergeViewStatePersisted(definition, defaults), true);+}+export function clearIssueSurfaceViewState(surfaceKey: string) {issueSurfaceViewRegistryStore.getState().clearSurfaceState(surfaceKey);const store = surfaceStores.get(surfaceKey);diff --git a/packages/core/issues/stores/view-store.ts b/packages/core/issues/stores/view-store.tsindex 4f0d723590..e9d0be47e4 100644--- a/packages/core/issues/stores/view-store.ts+++ b/packages/core/issues/stores/view-store.ts@@ -108,6 +108,31 @@ export interface ActorFilterValue {id: string;}+/** The nine query-defining filter fields as one value — what a saved view+ * fixes, and what resets restore. */+export interface FilterSnapshot {+ statusFilters: IssueStatus[];+ priorityFilters: IssuePriority[];+ assigneeFilters: ActorFilterValue[];+ includeNoAssignee: boolean;+ creatorFilters: ActorFilterValue[];+ projectFilters: string[];+ includeNoProject: boolean;+ labelFilters: string[];+ propertyFilters: Record<string, string[]>;+}++/** Filter-bar chip dimensions. Date is excluded: `dateFilter` lives outside+ * the persisted slice and clears through `setDateFilter(null)`. */+export type FilterDimension =+ | "status"+ | "priority"+ | "assignee"+ | "creator"+ | "project"+ | "label"+ | `property:${string}`;+export const PROPERTY_VIEW_PREFIX = "property:";export function propertyIdFromViewKey(key: string): string | null {@@ -215,6 +240,13 @@ export interface IssueViewState {hideStatus: (status: IssueStatus) => void;showStatus: (status: IssueStatus) => void;clearFilters: () => void;+ /** Clear one filter dimension (a filter-bar chip). `property:<id>` clears+ * that definition's entry only. Paired boolean flags (no-assignee /+ * no-project) clear with their dimension. */+ clearFilterDimension: (dimension: FilterDimension) => void;+ /** Replace every filter field at once — how "reset inside a saved view"+ * returns to the view's own conditions instead of to nothing. */+ resetFiltersTo: (snapshot: FilterSnapshot) => void;setSortBy: (field: SortField) => void;setSortDirection: (dir: SortDirection) => void;toggleCardProperty: (key: keyof CardProperties) => void;@@ -380,6 +412,31 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): IssuedateFilter: null,agentRunningFilter: false,}),+ resetFiltersTo: (snapshot) => set({ ...snapshot }),+ clearFilterDimension: (dimension) =>+ set((state) => {+ switch (dimension) {+ case "status":+ return { statusFilters: [] };+ case "priority":+ return { priorityFilters: [] };+ case "assignee":+ return { assigneeFilters: [], includeNoAssignee: false };+ case "creator":+ return { creatorFilters: [] };+ case "project":+ return { projectFilters: [], includeNoProject: false };+ case "label":+ return { labelFilters: [] };+ default: {+ const propertyId = propertyIdFromViewKey(dimension);+ if (!propertyId || !(propertyId in state.propertyFilters)) return state;+ const propertyFilters = { ...state.propertyFilters };+ delete propertyFilters[propertyId];+ return { propertyFilters };+ }+ }+ }),setSortBy: (field) => set({ sortBy: field }),setSortDirection: (dir) => set({ sortDirection: dir }),toggleCardProperty: (key) =>diff --git a/packages/core/issues/surface/query-plan.ts b/packages/core/issues/surface/query-plan.tsindex 5ea411b412..e57f116747 100644--- a/packages/core/issues/surface/query-plan.ts+++ b/packages/core/issues/surface/query-plan.ts@@ -1,50 +1,39 @@import type { CreateIssueRequest } from "../../types";-import type {- AssigneeGroupedIssuesFilter,- MyIssuesFilter,-} from "../queries";+import type { MyIssuesFilter } from "../queries";import {+ assigneeTypesForActorKind,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>;- };+/**+ * The scope's non-Table residue. Row membership for every list-shaped mode+ * (table, list, board, swimlane) is compiled into an IssueTableQuerySpec by+ * the surface controller and answered by the server-owned Table channel —+ * this plan only carries what that channel does not cover:+ *+ * - `scopeKey`: the surface's cache/persistence identity.+ * - `queryFilter`: the scope as legacy list-API params, consumed solely by+ * the Gantt projection (whose scheduled-only window is not expressible in+ * the Table spec).+ * - `createDefaults`: what a new issue created on this surface inherits.+ */+export interface IssueSurfaceQueryPlan {+ scopeKey: string;+ queryFilter: MyIssuesFilter;+ createDefaults: Partial<CreateIssueRequest>;+}-function myRelationPlan(+function buildMyRelationPlan(scope: Extract<IssueScope, { type: "my" }>,-): Pick<- Extract<IssueSurfaceQueryPlan, { kind: "scoped" }>,- "queryScope" | "queryFilter" | "userId" | "createDefaults"-> {+ scopeKey: string,+): IssueSurfaceQueryPlan {switch (scope.relation) {case "assigned":return {- queryScope: "assigned",+ scopeKey,queryFilter: { assignee_id: scope.userId },- userId: undefined,createDefaults: {assignee_type: "member",assignee_id: scope.userId,@@ -52,25 +41,18 @@ function myRelationPlan(};case "created":return {- queryScope: "created",+ scopeKey,queryFilter: { creator_id: scope.userId },- userId: undefined,createDefaults: {},};case "involved":return {- queryScope: "agents",+ scopeKey,queryFilter: { involves_user_id: scope.userId },- userId: undefined,createDefaults: {},};case "all":- return {- queryScope: "all",- queryFilter: {},- userId: scope.userId,- createDefaults: {},- };+ return { scopeKey, queryFilter: {}, createDefaults: {} };}}@@ -81,79 +63,32 @@ export function buildIssueSurfaceQueryPlan(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: {},- };- }+ const assigneeTypes = assigneeTypesForActorKind(scope.actorKind);return {- kind: "workspace",scopeKey,- queryScope: undefined,- queryFilter: {},- groupedScopeFilter: {},- loadMoreScope: undefined,- loadMoreFilter: undefined,- userId: undefined,+ queryFilter: assigneeTypes ? { assignee_types: assigneeTypes } : {},createDefaults: {},};}case "project": {- const queryFilter = { project_id: scope.projectId };+ const assigneeTypes = assigneeTypesForActorKind(scope.actorKind);return {- kind: "scoped",scopeKey,- queryScope: scopeKey,- queryFilter,- groupedScopeFilter: queryFilter,- loadMoreScope: scopeKey,- loadMoreFilter: queryFilter,- userId: undefined,+ queryFilter: assigneeTypes+ ? { project_id: scope.projectId, assignee_types: assigneeTypes }+ : { project_id: scope.projectId },createDefaults: { project_id: scope.projectId },};}- case "my": {- const plan = myRelationPlan(scope);+ case "my":+ return buildMyRelationPlan(scope, scopeKey);+ case "actor":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,+ queryFilter:+ scope.relation === "assigned"+ ? { assignee_id: scope.actorId }+ : { creator_id: scope.actorId },createDefaults:scope.relation === "assigned"? {@@ -162,7 +97,6 @@ export function buildIssueSurfaceQueryPlan(}: {},};- }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.tsindex db2e5d274b..f36a15c1d7 100644--- a/packages/core/issues/surface/repository.ts+++ b/packages/core/issues/surface/repository.ts@@ -1,95 +1,21 @@-import type { UseQueryOptions } from "@tanstack/react-query";-import {- issueAssigneeGroupsOptions,- issueFlatExportOptions,- issueFlatListOptions,- issueListOptions,- myIssueAssigneeGroupsOptions,- myIssueListOptions,- projectGanttIssuesOptions,- type AssigneeGroupedIssuesFilter,- type IssueFlatFilter,- type IssueSortParam,-} from "../queries";-import type {- GroupedIssuesResponse,- Issue,- ListIssuesCache,-} from "../../types";import type { IssueSurfaceQueryPlan } from "./query-plan";+import { projectGanttIssuesOptions } from "../queries";/**- * 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.+ * Issue surface repository — resolves a {@link IssueSurfaceQueryPlan} to+ * concrete query options. Every list-shaped mode (table, list, board,+ * swimlane) is served by the server-owned Table query channel; the Gantt+ * projection below is the one remaining scoped fetch, and it compiles its+ * assignee-type narrowing from the same plan as everything else.*/--/** 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[]>;-}--/** Flat cross-status window — feeds the table mode with offset pagination. */-export function issueSurfaceFlatOptions(- wsId: string,- plan: IssueSurfaceQueryPlan,- sort?: IssueSortParam,- facets: IssueFlatFilter = {},-) {- return issueFlatListOptions(- wsId,- plan.queryScope ?? plan.scopeKey,- { ...plan.queryFilter, ...facets },- plan.userId,- sort,- );-}--/** Fully materialized flat window used only for an explicit CSV export. */-export function issueSurfaceFlatExportOptions(+export function issueSurfaceGanttOptions(wsId: string,+ projectId: string,plan: IssueSurfaceQueryPlan,- sort?: IssueSortParam,- facets: IssueFlatFilter = {},) {- return issueFlatExportOptions(+ return projectGanttIssuesOptions(wsId,- plan.queryScope ?? plan.scopeKey,- { ...plan.queryFilter, ...facets },- plan.userId,- sort,+ projectId,+ plan.queryFilter.assignee_types,);}--/** 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.tsindex 7b08477be4..415ded2db1 100644--- a/packages/core/issues/surface/scope.test.ts+++ b/packages/core/issues/surface/scope.test.ts@@ -1,5 +1,8 @@import { describe, expect, it } from "vitest";import {+ actorKindForViewVariant,+ assigneeTypesForActorKind,+ myRelationForViewVariant,UnsupportedIssueScopeError,issueScopeKey,} from "./scope";@@ -28,107 +31,41 @@ describe("issue surface scope", () => {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",+ it("compiles each scope to its key, gantt filter, and create defaults", () => {+ expect(buildIssueSurfaceQueryPlan({ type: "workspace" })).toEqual({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",+ ).toEqual({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: {},+ buildIssueSurfaceQueryPlan({+ type: "project",+ projectId: "p1",+ actorKind: "members",+ }),+ ).toEqual({+ scopeKey: "project:p1:members",+ queryFilter: { project_id: "p1", assignee_types: ["member"] },+ createDefaults: { project_id: "p1" },});- });-- it("builds personal issue query plans using the existing query contracts", () => {expect(buildIssueSurfaceQueryPlan({type: "my",relation: "assigned",userId: "u1",}),- ).toMatchObject({+ ).toEqual({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",@@ -136,11 +73,9 @@ describe("issue surface scope", () => {actorId: "a1",relation: "assigned",}),- ).toMatchObject({+ ).toEqual({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" },});});@@ -152,3 +87,33 @@ describe("issue surface scope", () => {);});});++describe("assigneeTypesForActorKind", () => {+ it("maps the three tabs to their API values", () => {+ expect(assigneeTypesForActorKind("members")).toEqual(["member"]);+ expect(assigneeTypesForActorKind("agents")).toEqual(["agent", "squad"]);+ expect(assigneeTypesForActorKind("all")).toBeUndefined();+ expect(assigneeTypesForActorKind(undefined)).toBeUndefined();+ });+});++describe("actorKindForViewVariant", () => {+ it("resolves saved-view variants to a tab, defaulting to all", () => {+ expect(actorKindForViewVariant("members")).toBe("members");+ expect(actorKindForViewVariant("agents")).toBe("agents");+ expect(actorKindForViewVariant(null)).toBe("all");+ expect(actorKindForViewVariant(undefined)).toBe("all");+ expect(actorKindForViewVariant("involved")).toBe("all");+ });+});++describe("myRelationForViewVariant", () => {+ it("resolves my-view variants to a relation, defaulting to all", () => {+ expect(myRelationForViewVariant("assigned")).toBe("assigned");+ expect(myRelationForViewVariant("created")).toBe("created");+ expect(myRelationForViewVariant("involved")).toBe("involved");+ expect(myRelationForViewVariant("any")).toBe("all");+ expect(myRelationForViewVariant(null)).toBe("all");+ expect(myRelationForViewVariant("members")).toBe("all");+ });+});diff --git a/packages/core/issues/surface/scope.ts b/packages/core/issues/surface/scope.tsindex 21a7839795..a791bec9c8 100644--- a/packages/core/issues/surface/scope.ts+++ b/packages/core/issues/surface/scope.ts@@ -9,7 +9,7 @@ export type IssueScope =relation: "all" | "assigned" | "created" | "involved";userId: string;}- | { type: "project"; projectId: string }+ | { type: "project"; projectId: string; actorKind?: WorkspaceIssueActorKind }| {type: "actor";actorType: Extract<IssueAssigneeType, "member" | "agent">;@@ -18,6 +18,41 @@ export type IssueScope =}| { type: "team"; teamId: string };+/**+ * THE single translation between the UI's coarse assignee-type tab and the+ * API's `assignee_types` values. Every channel (list GET params, table+ * query spec, gantt) must compile the tab through this function — do not+ * inline the literal arrays anywhere else.+ */+export function assigneeTypesForActorKind(+ actorKind: WorkspaceIssueActorKind | undefined,+): IssueAssigneeType[] | undefined {+ switch (actorKind) {+ case "members":+ return ["member"];+ case "agents":+ return ["agent", "squad"];+ default:+ return undefined;+ }+}++/** Saved-view scope_variant → tab. Unknown/absent variants mean "all". */+export function actorKindForViewVariant(+ variant: string | null | undefined,+): WorkspaceIssueActorKind {+ return variant === "members" || variant === "agents" ? variant : "all";+}++/** My-view scope_variant → my-scope relation. Unknown/absent means "all". */+export function myRelationForViewVariant(+ variant: string | null | undefined,+): Extract<IssueScope, { type: "my" }>["relation"] {+ return variant === "assigned" || variant === "created" || variant === "involved"+ ? variant+ : "all";+}+export class UnsupportedIssueScopeError extends Error {constructor(scope: IssueScope, operation: string) {super(`Issue scope "${issueScopeKey(scope)}" is not supported for ${operation}.`);@@ -32,7 +67,12 @@ export function issueScopeKey(scope: IssueScope): string {case "my":return `my:${scope.userId}:${scope.relation}`;case "project":- return `project:${scope.projectId}`;+ // The unrestricted tab keeps the historical key so existing persisted+ // display state survives; Members/Agents get their own key (and thus+ // their own per-tab display state), matching the workspace tabs.+ return scope.actorKind === "members" || scope.actorKind === "agents"+ ? `project:${scope.projectId}:${scope.actorKind}`+ : `project:${scope.projectId}`;case "actor":return `actor:${scope.actorType}:${scope.actorId}:${scope.relation}`;case "team":diff --git a/packages/core/package.json b/packages/core/package.jsonindex aa5db6e72f..ab16cad23a 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -94,6 +94,13 @@"./pins": "./pins/index.ts","./pins/queries": "./pins/queries.ts","./pins/mutations": "./pins/mutations.ts",+ "./issue-views": "./issue-views/index.ts",+ "./issue-views/queries": "./issue-views/queries.ts",+ "./issue-views/mutations": "./issue-views/mutations.ts",+ "./issue-views/active-view-store": "./issue-views/active-view-store.ts",+ "./issue-views/use-active-view": "./issue-views/use-active-view.ts",+ "./issue-views/baseline": "./issue-views/baseline.ts",+ "./issue-views/preferences": "./issue-views/preferences.ts","./billing": "./billing/index.ts","./billing/queries": "./billing/queries.ts","./billing/mutations": "./billing/mutations.ts",diff --git a/packages/core/types/api.ts b/packages/core/types/api.tsindex 262cf4f496..2b3aa04c40 100644--- a/packages/core/types/api.ts+++ b/packages/core/types/api.ts@@ -245,7 +245,7 @@ export interface GroupedIssuesResponse {// state such as collapsed groups/parents.export type IssueTableScope =| { kind: "workspace"; assignee_types?: IssueAssigneeType[] }- | { kind: "project"; project_id: string }+ | { kind: "project"; project_id: string; assignee_types?: IssueAssigneeType[] }| { kind: "assignee"; actor: IssueActorRef }| { kind: "creator"; actor: IssueActorRef }| { kind: "my"; relation: "assigned" | "created" | "involved" | "any" };diff --git a/packages/core/types/pin.ts b/packages/core/types/pin.tsindex a86d542c12..e9b60d1d00 100644--- a/packages/core/types/pin.ts+++ b/packages/core/types/pin.ts@@ -1,4 +1,4 @@-export type PinnedItemType = "issue" | "project";+export type PinnedItemType = "issue" | "project" | "view";/*** Pin metadata only. Title / status / identifier / icon are NOT here —diff --git a/packages/ui/components/ui/dropdown-menu.tsx b/packages/ui/components/ui/dropdown-menu.tsxindex 60dd19518a..02d135cf8d 100644--- a/packages/ui/components/ui/dropdown-menu.tsx+++ b/packages/ui/components/ui/dropdown-menu.tsx@@ -23,13 +23,14 @@ function DropdownMenuContent({alignOffset = 0,side = "bottom",sideOffset = 4,+ anchor,className,onClick,...props}: MenuPrimitive.Popup.Props &Pick<MenuPrimitive.Positioner.Props,- "align" | "alignOffset" | "side" | "sideOffset"+ "align" | "alignOffset" | "side" | "sideOffset" | "anchor">) {// Stop click events from bubbling out of the menu. Base UI portals the// popup so DOM is detached, but React's synthetic event system still@@ -44,6 +45,7 @@ function DropdownMenuContent({alignOffset={alignOffset}side={side}sideOffset={sideOffset}+ anchor={anchor}><MenuPrimitive.Popupdata-slot="dropdown-menu-content"diff --git a/packages/ui/styles/base.css b/packages/ui/styles/base.cssindex 6ecb7e487c..cdd7dfe8c4 100644--- a/packages/ui/styles/base.css+++ b/packages/ui/styles/base.css@@ -257,6 +257,16 @@ html[data-sidebar-resizing="true"] * {user-select: none !important;}+/* Row drag-and-drop shares the same cursor contract: while a dnd-kit drag+ * is active the grabbing cursor must survive the pointer leaving the drag+ * handle and win over descendants' own cursor declarations (including the+ * preflight `cursor: pointer` on buttons the pointer crosses mid-drag). */+html[data-dnd-dragging="true"],+html[data-dnd-dragging="true"] * {+ cursor: grabbing !important;+ user-select: none !important;+}+[data-sidebar-resizing="true"] [data-slot="sidebar-gap"],[data-sidebar-resizing="true"] [data-slot="sidebar-container"] {transition: none !important;diff --git a/packages/views/common/actor-issues-panel.tsx b/packages/views/common/actor-issues-panel.tsxindex 3f3c7df82b..9c6b91dacd 100644--- a/packages/views/common/actor-issues-panel.tsx+++ b/packages/views/common/actor-issues-panel.tsx@@ -19,6 +19,7 @@ import {IssueDisplayControls,ViewRefreshIndicator,} from "../issues/components/issues-header";+import { FilterChipsBar } from "../issues/components/filter-chips-bar";import { IssueSurface } from "../issues/surface/issue-surface";import { useT } from "../i18n";@@ -50,6 +51,7 @@ function ActorIssuesHeader({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">@@ -98,6 +100,8 @@ function ActorIssuesHeader({<ViewRefreshIndicator active={isRefreshing} /></div></div>+ <FilterChipsBar />+ </>);}diff --git a/packages/views/common/single-row-fit.ts b/packages/views/common/single-row-fit.tsnew file mode 100644index 0000000000..9bcc4d0c37--- /dev/null+++ b/packages/views/common/single-row-fit.ts@@ -0,0 +1,79 @@+"use client";++import { useCallback, useLayoutEffect, useRef, useState } from "react";++/**+ * Fit calculator for a single-row toolbar that collapses its tail into a+ * trailing trigger (the view bar; reusable for any "N chips + overflow+ * menu" strip).+ *+ * The caller renders every candidate twice: once for real (slice to+ * `fitCount`) and once inside a hidden mirror row attached to+ * `measureRef` (absolutely positioned, `visibility: hidden`, same+ * classes). Natural widths are read off the mirror, so the fit answer+ * never depends on what is currently mounted for real — no feedback+ * loop between measurement and rendering.+ *+ * Rule: the longest prefix that fits alongside `reserve` px of trailing+ * chrome wins. `reserve` must cover everything that is ALWAYS rendered+ * after the items (triggers, menus) — it is subtracted even when every+ * item fits, otherwise a row that exactly fits its items clips the+ * chrome off the end.+ *+ * Remeasures on container resize (ResizeObserver) and after every+ * commit (labels/items change the mirror); state only updates when the+ * answer actually changes, so the extra passes are free.+ */+export function useSingleRowFit({+ count,+ gap,+ reserve,+}: {+ /** Number of candidate items (mirror children must match). */+ count: number;+ /** Horizontal gap between items in px (the container's `gap`). */+ gap: number;+ /** Width in px to hold back for the overflow trigger. */+ reserve: number;+}) {+ const containerRef = useRef<HTMLDivElement | null>(null);+ const measureRef = useRef<HTMLDivElement | null>(null);+ const [fitCount, setFitCount] = useState(count);++ const recompute = useCallback(() => {+ const container = containerRef.current;+ const mirror = measureRef.current;+ if (!container || !mirror) return;+ const available = container.clientWidth;+ const widths = Array.from(mirror.children).map(+ (child) => (child as HTMLElement).offsetWidth,+ );++ let used = 0;+ let next = 0;+ for (let i = 0; i < widths.length; i++) {+ const withItem = used + (i > 0 ? gap : 0) + widths[i]!;+ if (withItem + gap + reserve > available) break;+ used = withItem;+ next = i + 1;+ }+ setFitCount((current) => (current === next ? current : next));+ }, [gap, reserve]);++ // After every commit: the mirror just re-rendered with current labels.+ // eslint-disable-next-line react-hooks/exhaustive-deps -- deliberate every-commit measure; the setState inside is change-guarded+ useLayoutEffect(() => {+ recompute();+ });++ useLayoutEffect(() => {+ const container = containerRef.current;+ if (!container || typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(() => recompute());+ observer.observe(container);+ return () => observer.disconnect();+ }, [recompute]);++ // Never report more than exists (items can shrink between renders).+ return { containerRef, measureRef, fitCount: Math.min(fitCount, count) };+}diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsxindex 46f209a790..66146526d4 100644--- a/packages/views/issues/components/board-card.tsx+++ b/packages/views/issues/components/board-card.tsx@@ -119,7 +119,7 @@ export const BoardCardContent = memo(function BoardCardContent({const priorityLabel = t(($) => $.priority[issue.priority]);const priorityIconNode = showPriority ? (canEdit ? (- <PickerWrapper>+ <PickerWrapper className="flex"><PriorityPickerpriority={issue.priority}onUpdate={handleUpdate}@@ -127,7 +127,7 @@ export const BoardCardContent = memo(function BoardCardContent({<buttontype="button"aria-label={priorityLabel}- className="inline-flex items-center justify-center rounded hover:bg-muted/60"+ className="inline-flex size-5 shrink-0 items-center justify-center rounded hover:bg-muted/60"><PriorityIcon priority={issue.priority} /></button>@@ -135,7 +135,10 @@ export const BoardCardContent = memo(function BoardCardContent({/></PickerWrapper>) : (- <span aria-label={priorityLabel} className="inline-flex items-center justify-center">+ <span+ aria-label={priorityLabel}+ className="inline-flex size-5 shrink-0 items-center justify-center"+ ><PriorityIcon priority={issue.priority} /></span>)@@ -244,7 +247,7 @@ export const BoardCardContent = memo(function BoardCardContent({<div className="ml-auto flex shrink-0 items-center gap-2">{showStartDate && (canEdit ? (- <PickerWrapper className="shrink-0">+ <PickerWrapper className="flex shrink-0"><StartDatePickerstartDate={issue.start_date}onUpdate={handleUpdate}@@ -265,7 +268,7 @@ export const BoardCardContent = memo(function BoardCardContent({)}{showDueDate && (canEdit ? (- <PickerWrapper className="shrink-0">+ <PickerWrapper className="flex shrink-0"><DueDatePickerdueDate={issue.due_date}onUpdate={handleUpdate}diff --git a/packages/views/issues/components/board-column.tsx b/packages/views/issues/components/board-column.tsxindex 160b1b55bf..6c9f99a245 100644--- a/packages/views/issues/components/board-column.tsx+++ b/packages/views/issues/components/board-column.tsx@@ -20,6 +20,7 @@ import {} from "@multica/ui/components/ui/dropdown-menu";import { STATUS_CONFIG } from "@multica/core/issues/config";import { useViewStoreApi } from "@multica/core/issues/stores/view-store-context";+import { useViewBaseline } from "../surface/view-baseline-context";import { StatusHeading } from "./status-heading";import { DraggableBoardCard } from "./board-card";import type { ChildProgress } from "./list-row";@@ -113,6 +114,10 @@ export const BoardColumn = memo(function BoardColumn({const cfg = status ? STATUS_CONFIG[status] : null;const { setNodeRef, isOver } = useDroppable({ id: group.id });const viewStoreApi = useViewStoreApi();+ // A status fixed by the open saved view cannot be hidden from the board —+ // that would silently strip one of the view's own conditions.+ const viewBaseline = useViewBaseline();+ const statusFixedByView = !!status && viewBaseline?.status.has(status) === true;const { t } = useT("issues");// Resolve IDs to Issue objects, preserving parent-provided order@@ -202,7 +207,11 @@ export const BoardColumn = memo(function BoardColumn({}/><DropdownMenuContent align="end">- <DropdownMenuItem onClick={() => viewStoreApi.getState().hideStatus(status)}>+ <DropdownMenuItem+ disabled={statusFixedByView}+ title={statusFixedByView ? t(($) => $.filters.in_view) : undefined}+ onClick={() => viewStoreApi.getState().hideStatus(status)}+ ><EyeOff className="size-3.5" />{t(($) => $.board.hide_column)}</DropdownMenuItem>diff --git a/packages/views/issues/components/board-view.tsx b/packages/views/issues/components/board-view.tsxindex 596487255b..fd502aebd3 100644--- a/packages/views/issues/components/board-view.tsx+++ b/packages/views/issues/components/board-view.tsx@@ -12,19 +12,15 @@ import {type DragEndEvent,type DragOverEvent,} from "@dnd-kit/core";-import type { QueryKey } from "@tanstack/react-query";import { arrayMove } from "@dnd-kit/sortable";import { toast } from "sonner";import type {Issue,- IssueAssigneeGroup,IssueAssigneeType,IssueStatus,Project,IssueProperty,} 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";import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";import { propertyListOptions, useSetIssueProperty, useUnsetIssueProperty } from "@multica/core/properties";@@ -160,36 +156,22 @@ const EMPTY_IDS: string[] = [];function BoardViewImpl({issues,- assigneeGroups,- assigneeGroupQueryKey,- assigneeGroupFilter,visibleStatuses,hiddenStatuses,onMoveIssue,childProgressMap = EMPTY_PROGRESS_MAP,projectMap,- myIssuesScope,- myIssuesFilter,- sort,projectId,onCreateIssue,statusPagination,groupBranches,}: {issues: Issue[];- assigneeGroups?: IssueAssigneeGroup[];- assigneeGroupQueryKey?: QueryKey;- assigneeGroupFilter?: AssigneeGroupedIssuesFilter;visibleStatuses: IssueStatus[];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;- /** Must match the sort the page queried with — embedded in the cache key. */- sort?: IssueSortParam;/** When set, the per-column "+" pre-fills the project on the create form. */projectId?: string;onCreateIssue?: (defaults: IssueCreateDefaults) => void;@@ -259,17 +241,9 @@ function BoardViewImpl({}): null;const { getActorName } = useActorName();- const myIssuesOpts = myIssuesScope- ? { scope: myIssuesScope, filter: myIssuesFilter ?? {} }- : undefined;const groupedIssues = useMemo(- () =>- groupBranches?.enabled- ? groupBranches.issues- : grouping === "assignee" && assigneeGroups- ? assigneeGroups.flatMap((group) => group.issues)- : issues,- [assigneeGroups, groupBranches, grouping, issues],+ () => (groupBranches?.enabled ? groupBranches.issues : issues),+ [groupBranches, issues],);const hydratedAssigneeGroups = useMemo<BoardColumnGroup[] | undefined>(() => {if (grouping === "assignee" && groupBranches?.enabled) {@@ -298,35 +272,8 @@ function BoardViewImpl({}];});}- if (grouping !== "assignee" || !assigneeGroups) return undefined;- const order: Record<string, number> = {- member: 0,- agent: 1,- squad: 2,- none: 3,- };- return assigneeGroups- .map((group) => ({- id: group.id,- title:- group.assignee_type && group.assignee_id- ? getActorName(group.assignee_type, group.assignee_id)- : t(($) => $.filters.no_assignee),- assigneeType: group.assignee_type,- assigneeId: group.assignee_id,- totalCount: group.total,- createData: {- assignee_type: group.assignee_type,- assignee_id: group.assignee_id,- },- }))- .sort((a, b) => {- const aOrder = order[a.assigneeType ?? "none"] ?? 99;- const bOrder = order[b.assigneeType ?? "none"] ?? 99;- if (aOrder !== bOrder) return aOrder - bOrder;- return a.title.localeCompare(b.title);- });- }, [assigneeGroups, getActorName, groupBranches, grouping, t]);+ return undefined;+ }, [getActorName, groupBranches, grouping, t]);const groupPagination = useMemo(() => {if (!groupBranches?.enabled) return undefined;const grouped = new Map<string, IssueGroupPageState[]>();@@ -627,34 +574,18 @@ function BoardViewImpl({) : (groups.map((group) =>isStatusGroup(group) ? (- statusPagination ? (- <ServerPaginatedBoardColumn- key={group.id}- group={group}- issueIds={columns[group.id] ?? EMPTY_IDS}- issueMap={issueMapRef.current}- childProgressMap={childProgressMap}- projectMap={projectMap}- page={statusPagination[group.status]}- projectId={projectId}- onCreateIssue={onCreateIssue}- sortLabel={sortLabel}- />- ) : (- <PaginatedBoardColumn- key={group.id}- group={group}- issueIds={columns[group.id] ?? EMPTY_IDS}- issueMap={issueMapRef.current}- childProgressMap={childProgressMap}- projectMap={projectMap}- myIssuesOpts={myIssuesOpts}- sort={sort}- projectId={projectId}- onCreateIssue={onCreateIssue}- sortLabel={sortLabel}- />- )+ <ServerPaginatedBoardColumn+ key={group.id}+ group={group}+ issueIds={columns[group.id] ?? EMPTY_IDS}+ issueMap={issueMapRef.current}+ childProgressMap={childProgressMap}+ projectMap={projectMap}+ page={statusPagination?.[group.status]}+ projectId={projectId}+ onCreateIssue={onCreateIssue}+ sortLabel={sortLabel}+ />) : (groupPagination?.[group.id] ? (<ServerPaginatedBoardColumn@@ -669,21 +600,6 @@ function BoardViewImpl({onCreateIssue={onCreateIssue}sortLabel={sortLabel}/>- ) : assigneeGroupQueryKey && assigneeGroupFilter ? (- <PaginatedAssigneeBoardColumn- key={group.id}- group={group}- 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}- />) : (<BoardColumnkey={group.id}@@ -710,19 +626,10 @@ function BoardViewImpl({</div>)}- {groupingProperty && !groupBranches?.enabled && (- <PropertyBoardPoolLoader- statuses={visibleStatuses}- myIssuesOpts={myIssuesOpts}- sort={sort}- />- )}{grouping === "status" && hiddenStatuses.length > 0 && (<BoardHiddenColumnsPanelhiddenStatuses={hiddenStatuses}- myIssuesOpts={myIssuesOpts}- sort={sort}statusPagination={statusPagination}/>)}@@ -747,63 +654,6 @@ function BoardViewImpl({);}-const PaginatedAssigneeBoardColumn = memo(function PaginatedAssigneeBoardColumn({- group,- 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(- {- id: group.id,- assignee_type: group.assigneeType ?? null,- assignee_id: group.assigneeId ?? null,- },- queryKey,- filter,- sort,- );- return (- <BoardColumn- group={group}- issueIds={issueIds}- issueMap={issueMap}- childProgressMap={childProgressMap}- projectMap={projectMap}- totalCount={total}- projectId={projectId}- onCreateIssue={onCreateIssue}- sortLabel={sortLabel}- footer={- <ListLoadMoreFooter- hasMore={hasMore}- isLoading={isLoading}- total={total}- onLoadMore={loadMore}- />- }- />- );-});const ServerPaginatedBoardColumn = memo(function ServerPaginatedBoardColumn({group,@@ -821,12 +671,12 @@ const ServerPaginatedBoardColumn = memo(function ServerPaginatedBoardColumn({issueMap: Map<string, Issue>;childProgressMap?: Map<string, ChildProgress>;projectMap?: Map<string, Project>;- page: IssueStatusPageState | IssueGroupPageState;+ page?: IssueStatusPageState | IssueGroupPageState;projectId?: string;onCreateIssue?: (defaults: IssueCreateDefaults) => void;sortLabel?: string | null;}) {- const footer = (+ const footer = page ? (<ListLoadMoreFooterhasMore={page.hasMore}isLoading={page.isLoading || page.isFetching}@@ -835,7 +685,7 @@ const ServerPaginatedBoardColumn = memo(function ServerPaginatedBoardColumn({isError={page.isError}onRetry={page.retry}/>- );+ ) : undefined;return (<BoardColumngroup={group}@@ -843,7 +693,7 @@ const ServerPaginatedBoardColumn = memo(function ServerPaginatedBoardColumn({issueMap={issueMap}childProgressMap={childProgressMap}projectMap={projectMap}- totalCount={page.total}+ totalCount={page?.total ?? group.totalCount}projectId={projectId}onCreateIssue={onCreateIssue}sortLabel={sortLabel}@@ -852,146 +702,23 @@ const ServerPaginatedBoardColumn = memo(function ServerPaginatedBoardColumn({);});-const PaginatedBoardColumn = memo(function PaginatedBoardColumn({- group,- 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(- group.status,- myIssuesOpts,- sort,- );- return (- <BoardColumn- group={group}- issueIds={issueIds}- issueMap={issueMap}- childProgressMap={childProgressMap}- projectMap={projectMap}- totalCount={total}- projectId={projectId}- onCreateIssue={onCreateIssue}- sortLabel={sortLabel}- footer={- <ListLoadMoreFooter- hasMore={hasMore}- isLoading={isLoading}- total={total}- onLoadMore={loadMore}- />- }- />- );-});--/**- * Board-view-specific row that pulls the server-aggregated total from- * `useLoadMoreByStatus` and hands it to the shared {@link HiddenColumnRow}.- * Lives here (not in `hidden-columns-panel.tsx`) so the shared panel stays- * free of `useLoadMoreByStatus` / `myIssuesOpts` coupling — the swimlane- * uses an in-memory total instead.- */-/**- * The property-grouped board derives its columns from the status-bucketed- * pool, which pages per status. Property columns have no per-column- * pagination yet (tracked in MUL-4493), so this strip keeps every issue- * REACHABLE: one sentinel per status that still has server rows loads the- * pool further and the property columns re-derive. Without it, rows beyond- * a status's loaded page silently never join any column (review round 3).- */-function PropertyBoardPoolLoader({- statuses,- myIssuesOpts,- sort,-}: {- statuses: IssueStatus[];- myIssuesOpts?: { scope: string; filter: MyIssuesFilter };- sort?: IssueSortParam;-}) {- return (- <div className="col-span-full flex justify-center py-1">- {statuses.map((status) => (- <PropertyBoardPoolSentinel key={status} status={status} myIssuesOpts={myIssuesOpts} sort={sort} />- ))}- </div>- );-}--function PropertyBoardPoolSentinel({- status,- myIssuesOpts,- sort,-}: {- status: IssueStatus;- myIssuesOpts?: { scope: string; filter: MyIssuesFilter };- sort?: IssueSortParam;-}) {- const { loadMore, hasMore, isLoading } = useLoadMoreByStatus(status, myIssuesOpts, sort);- if (!hasMore) return null;- return <InfiniteScrollSentinel onVisible={loadMore} loading={isLoading} />;-}--function BoardHiddenColumnRow({- status,- myIssuesOpts,- sort,-}: {- status: IssueStatus;- myIssuesOpts?: { scope: string; filter: MyIssuesFilter };- sort?: IssueSortParam;-}) {- const { total } = useLoadMoreByStatus(status, myIssuesOpts, sort);- return <HiddenColumnRow status={status} total={total} />;-}function BoardHiddenColumnsPanel({hiddenStatuses,- myIssuesOpts,- sort,statusPagination,}: {hiddenStatuses: IssueStatus[];- myIssuesOpts?: { scope: string; filter: MyIssuesFilter };- sort?: IssueSortParam;statusPagination?: IssueStatusPagination;}) {return (<HiddenColumnsPanelhiddenStatuses={hiddenStatuses}renderRow={(status) => (- statusPagination ? (- <HiddenColumnRow- key={status}- status={status}- total={statusPagination[status].total}- />- ) : (- <BoardHiddenColumnRow- key={status}- status={status}- myIssuesOpts={myIssuesOpts}- sort={sort}- />- )+ <HiddenColumnRow+ key={status}+ status={status}+ total={statusPagination?.[status]?.total}+ />)}/>);diff --git a/packages/views/issues/components/create-renderers.test.tsx b/packages/views/issues/components/create-renderers.test.tsxindex 02bce0fd55..f941fb8456 100644--- a/packages/views/issues/components/create-renderers.test.tsx+++ b/packages/views/issues/components/create-renderers.test.tsx@@ -54,16 +54,6 @@ vi.mock("@multica/core/issues/stores/view-store-context", () => ({}),}));-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,diff --git a/packages/views/issues/components/filter-chips-bar.tsx b/packages/views/issues/components/filter-chips-bar.tsxnew file mode 100644index 0000000000..f52a0160e8--- /dev/null+++ b/packages/views/issues/components/filter-chips-bar.tsx@@ -0,0 +1,547 @@+"use client";++import { useMemo, type ReactNode } from "react";+import {+ CalendarDays,+ CircleDot,+ FolderKanban,+ SignalHigh,+ Tag,+ User,+ UserPen,+ X,+} from "lucide-react";+import { useQuery } from "@tanstack/react-query";+import { Button } from "@multica/ui/components/ui/button";+import { useWorkspaceId } from "@multica/core/hooks";+import { memberListOptions, agentListOptions, squadListOptions } from "@multica/core/workspace/queries";+import { projectListOptions } from "@multica/core/projects/queries";+import { labelListOptions } from "@multica/core/labels/queries";+import { propertyListOptions } from "@multica/core/properties";+import {+ type ActorFilterValue,+ type FilterDimension,+ type FilterSnapshot,+ type IssueDateFilter,+} from "@multica/core/issues/stores/view-store";+import {+ actorFilterKey,+ type IssueViewBaseline,+} from "@multica/core/issue-views/baseline";+import { useViewStore, useViewStoreApi } from "@multica/core/issues/stores/view-store-context";+import { StatusIcon } from "./status-icon";+import { PriorityIcon } from "./priority-icon";+import { ActorAvatar } from "../../common/actor-avatar";+import { useT } from "../../i18n";++/** One rendered chip: a dimension with its selected values summarised. */+interface FilterChip {+ key: string;+ icon: ReactNode;+ /** Dimension name, e.g. "状态". */+ label: string;+ /** Values summary, e.g. "进行中" or "4 个状态". */+ value: string;+ /** Up to three overlapping value icons rendered before the summary text. */+ valueIcons?: ReactNode;+ onRemove: () => void;+}++function summarize(names: (string | undefined)[]): string {+ const first = names.find((n): n is string => !!n);+ if (first === undefined) return String(names.length);+ const rest = names.length - 1;+ return rest > 0 ? `${first} +${rest}` : first;+}++const CHIP_ICON_CLASS = "size-3 shrink-0 text-muted-foreground";++/** Overlapping value icons, following the runtime-list stack pattern: each+ * icon sits on an opaque wrapper so the one underneath cannot show through. */+function IconStack({ children }: { children: ReactNode[] }) {+ return (+ <span className="flex items-center -space-x-1">+ {children.map((child, i) => (+ <span+ key={i}+ className="inline-flex size-4 items-center justify-center rounded-full bg-background ring-1 ring-border"+ >+ {child}+ </span>+ ))}+ </span>+ );+}++/** Avatar variant of the stack — avatars are already opaque, so they only+ * need the background-colored separation ring. */+function AvatarStack({ actors }: { actors: ActorFilterValue[] }) {+ return (+ <span className="flex items-center -space-x-1">+ {actors.slice(0, 3).map((actor) => (+ <span+ key={`${actor.type}:${actor.id}`}+ className="inline-flex rounded-full ring-2 ring-background"+ >+ <ActorAvatar+ actorType={actor.type}+ actorId={actor.id}+ size="xs"+ profileLink={false}+ />+ </span>+ ))}+ </span>+ );+}++/** Colored-dot stack for labels and select-property options. */+function DotStack({ colors }: { colors: string[] }) {+ if (colors.length === 0) return null;+ return (+ <IconStack>+ {colors.slice(0, 3).map((color, i) => (+ <span+ key={i}+ className="size-2.5 rounded-full"+ style={{ backgroundColor: color }}+ />+ ))}+ </IconStack>+ );+}++/**+ * Active-filter chips for the surrounding ViewStoreProvider's store — works+ * against the live surface store on pages and against the draft store inside+ * the save-view dialog. Name lookups reuse the caches the filter dropdown+ * already populates; a cache miss degrades a chip to a count, never blocks.+ */+function useFilterChips(+ dateFilter: IssueDateFilter | null,+ onDateFilterChange?: (filter: IssueDateFilter | null) => void,+ baseline?: IssueViewBaseline,+) {+ const { t } = useT("issues");+ const wsId = useWorkspaceId();++ 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 propertyFilters = useViewStore((s) => s.propertyFilters);+ const store = useViewStoreApi();++ const hasStoreFilters =+ statusFilters.length > 0 ||+ priorityFilters.length > 0 ||+ assigneeFilters.length > 0 ||+ includeNoAssignee ||+ creatorFilters.length > 0 ||+ projectFilters.length > 0 ||+ includeNoProject ||+ labelFilters.length > 0 ||+ Object.values(propertyFilters).some((selected) => selected.length > 0);+ const showDateChip = !!onDateFilterChange && !!dateFilter;++ const enabled = hasStoreFilters;+ const { data: members = [] } = useQuery({+ ...memberListOptions(wsId),+ enabled: enabled && (assigneeFilters.length > 0 || creatorFilters.length > 0),+ });+ const { data: agents = [] } = useQuery({+ ...agentListOptions(wsId),+ enabled: enabled && (assigneeFilters.length > 0 || creatorFilters.length > 0),+ });+ const { data: squads = [] } = useQuery({+ ...squadListOptions(wsId),+ enabled: enabled && assigneeFilters.some((f) => f.type === "squad"),+ });+ const { data: projects = [] } = useQuery({+ ...projectListOptions(wsId),+ enabled: enabled && projectFilters.length > 0,+ });+ const { data: labels = [] } = useQuery({+ ...labelListOptions(wsId),+ enabled: enabled && labelFilters.length > 0,+ });+ const { data: workspaceProperties = [] } = useQuery({+ ...propertyListOptions(wsId),+ enabled: enabled && Object.keys(propertyFilters).length > 0,+ });++ const actorName = useMemo(() => {+ const byKey = new Map<string, string>();+ for (const m of members) byKey.set(`member:${m.id}`, m.name);+ for (const a of agents) byKey.set(`agent:${a.id}`, a.name);+ for (const s of squads) byKey.set(`squad:${s.id}`, s.name);+ return (actor: ActorFilterValue) => byKey.get(`${actor.type}:${actor.id}`);+ }, [members, agents, squads]);++ // Inside a saved view chips show only the user's additions ON TOP of the+ // view; removing one returns the dimension to the view's values (never+ // empty). Without a baseline this is plain clear.+ const clearDimension = (dimension: FilterDimension) => {+ if (!baseline) {+ store.getState().clearFilterDimension(dimension);+ return;+ }+ const s = store.getState();+ const raw = baseline.raw;+ const current: FilterSnapshot = {+ statusFilters: s.statusFilters,+ priorityFilters: s.priorityFilters,+ assigneeFilters: s.assigneeFilters,+ includeNoAssignee: s.includeNoAssignee,+ creatorFilters: s.creatorFilters,+ projectFilters: s.projectFilters,+ includeNoProject: s.includeNoProject,+ labelFilters: s.labelFilters,+ propertyFilters: s.propertyFilters,+ };+ switch (dimension) {+ case "status":+ s.resetFiltersTo({ ...current, statusFilters: raw.statusFilters });+ break;+ case "priority":+ s.resetFiltersTo({ ...current, priorityFilters: raw.priorityFilters });+ break;+ case "assignee":+ s.resetFiltersTo({+ ...current,+ assigneeFilters: raw.assigneeFilters,+ includeNoAssignee: raw.includeNoAssignee,+ });+ break;+ case "creator":+ s.resetFiltersTo({ ...current, creatorFilters: raw.creatorFilters });+ break;+ case "project":+ s.resetFiltersTo({+ ...current,+ projectFilters: raw.projectFilters,+ includeNoProject: raw.includeNoProject,+ });+ break;+ case "label":+ s.resetFiltersTo({ ...current, labelFilters: raw.labelFilters });+ break;+ default: {+ const propertyId = dimension.slice("property:".length);+ const propertyFilters = { ...current.propertyFilters };+ const base = raw.propertyFilters[propertyId];+ if (base) propertyFilters[propertyId] = base;+ else delete propertyFilters[propertyId];+ s.resetFiltersTo({ ...current, propertyFilters });+ }+ }+ };++ // Values the view already fixes are invisible here — subtract them.+ const deltaStatus = baseline+ ? statusFilters.filter((s) => !baseline.status.has(s))+ : statusFilters;+ const deltaPriority = baseline+ ? priorityFilters.filter((p) => !baseline.priority.has(p))+ : priorityFilters;+ const deltaAssignees = baseline+ ? assigneeFilters.filter((a) => !baseline.assignee.has(actorFilterKey(a)))+ : assigneeFilters;+ const deltaNoAssignee = baseline+ ? includeNoAssignee && !baseline.includeNoAssignee+ : includeNoAssignee;+ const deltaCreators = baseline+ ? creatorFilters.filter((a) => !baseline.creator.has(actorFilterKey(a)))+ : creatorFilters;+ const deltaProjects = baseline+ ? projectFilters.filter((id) => !baseline.project.has(id))+ : projectFilters;+ const deltaNoProject = baseline+ ? includeNoProject && !baseline.includeNoProject+ : includeNoProject;+ const deltaLabels = baseline+ ? labelFilters.filter((id) => !baseline.label.has(id))+ : labelFilters;+ const deltaProperties: Record<string, string[]> = {};+ for (const [id, selected] of Object.entries(propertyFilters)) {+ const fixed = baseline?.property.get(id);+ const delta = fixed ? selected.filter((v) => !fixed.has(v)) : selected;+ if (delta.length > 0) deltaProperties[id] = delta;+ }++ const chips: FilterChip[] = [];++ const [onlyStatus] = deltaStatus;+ if (deltaStatus.length > 0) {+ chips.push({+ key: "status",+ icon: <CircleDot className={CHIP_ICON_CLASS} />,+ label: t(($) => $.filters.section_status),+ valueIcons: (+ <IconStack>+ {deltaStatus.slice(0, 3).map((s) => (+ <StatusIcon key={s} status={s} className="size-3" />+ ))}+ </IconStack>+ ),+ value:+ onlyStatus !== undefined && deltaStatus.length === 1+ ? t(($) => $.status[onlyStatus])+ : t(($) => $.filters.chip_status_count, { count: deltaStatus.length }),+ onRemove: () => clearDimension("status"),+ });+ }+ const [onlyPriority] = deltaPriority;+ if (deltaPriority.length > 0) {+ chips.push({+ key: "priority",+ icon: <SignalHigh className={CHIP_ICON_CLASS} />,+ label: t(($) => $.filters.section_priority),+ valueIcons: (+ <IconStack>+ {deltaPriority.slice(0, 3).map((p) => (+ <PriorityIcon key={p} priority={p} className="size-3" />+ ))}+ </IconStack>+ ),+ value:+ onlyPriority !== undefined && deltaPriority.length === 1+ ? t(($) => $.priority[onlyPriority])+ : t(($) => $.filters.chip_priority_count, { count: deltaPriority.length }),+ onRemove: () => clearDimension("priority"),+ });+ }+ if (deltaAssignees.length > 0 || deltaNoAssignee) {+ const names = deltaAssignees.map(actorName);+ if (deltaNoAssignee) names.push(t(($) => $.filters.no_assignee));+ chips.push({+ key: "assignee",+ icon: <User className={CHIP_ICON_CLASS} />,+ label: t(($) => $.filters.section_assignee),+ valueIcons: deltaAssignees.length > 0 ? <AvatarStack actors={deltaAssignees} /> : undefined,+ value: summarize(names),+ onRemove: () => clearDimension("assignee"),+ });+ }+ if (deltaCreators.length > 0) {+ chips.push({+ key: "creator",+ icon: <UserPen className={CHIP_ICON_CLASS} />,+ label: t(($) => $.filters.section_creator),+ valueIcons: <AvatarStack actors={deltaCreators} />,+ value: summarize(deltaCreators.map(actorName)),+ onRemove: () => clearDimension("creator"),+ });+ }+ if (deltaProjects.length > 0 || deltaNoProject) {+ const projectById = new Map(projects.map((p) => [p.id, p]));+ const names = deltaProjects.map((id) => projectById.get(id)?.title);+ if (deltaNoProject) names.push(t(($) => $.filters.no_project));+ const emojis = deltaProjects+ .map((id) => projectById.get(id)?.icon)+ .filter((icon): icon is string => !!icon);+ chips.push({+ key: "project",+ icon: <FolderKanban className={CHIP_ICON_CLASS} />,+ label: t(($) => $.filters.section_project),+ valueIcons:+ emojis.length > 0 ? (+ <IconStack>+ {emojis.slice(0, 3).map((emoji, i) => (+ <span key={i} className="text-micro leading-none">{emoji}</span>+ ))}+ </IconStack>+ ) : undefined,+ value: summarize(names),+ onRemove: () => clearDimension("project"),+ });+ }+ if (deltaLabels.length > 0) {+ const labelById = new Map(labels.map((l) => [l.id, l]));+ chips.push({+ key: "label",+ icon: <Tag className={CHIP_ICON_CLASS} />,+ label: t(($) => $.filters.section_label),+ valueIcons: (+ <DotStack+ colors={deltaLabels+ .map((id) => labelById.get(id)?.color)+ .filter((c): c is string => !!c)}+ />+ ),+ value: summarize(deltaLabels.map((id) => labelById.get(id)?.name)),+ onRemove: () => clearDimension("label"),+ });+ }+ for (const [propertyId, selected] of Object.entries(deltaProperties)) {+ if (selected.length === 0) continue;+ const definition = workspaceProperties.find((p) => p.id === propertyId);+ // A stale filter on an archived definition is stripped by the surface+ // controller before querying; hide its chip rather than render a ghost.+ if (!definition) continue;+ const optionName = (optionId: string): string | undefined => {+ if (definition.type === "checkbox") {+ return optionId === "true"+ ? t(($) => $.pickers.custom_property.true_label)+ : t(($) => $.pickers.custom_property.false_label);+ }+ return definition.config.options?.find((o) => o.id === optionId)?.name;+ };+ const optionColors =+ definition.type === "checkbox"+ ? []+ : selected+ .map((id) => definition.config.options?.find((o) => o.id === id)?.color)+ .filter((c): c is string => !!c);+ chips.push({+ key: `property:${propertyId}`,+ icon: <Tag className={CHIP_ICON_CLASS} />,+ label: definition.name,+ valueIcons: optionColors.length > 0 ? <DotStack colors={optionColors} /> : undefined,+ value: summarize(selected.map(optionName)),+ onRemove: () => clearDimension(`property:${propertyId}`),+ });+ }+ if (showDateChip && dateFilter) {+ const fieldLabel =+ dateFilter.field === "created_at"+ ? t(($) => $.filters.date_field_created)+ : t(($) => $.filters.date_field_updated);+ const short = (dateOnly: string) => {+ const [, m, d] = dateOnly.split("-");+ return `${Number(m)}/${Number(d)}`;+ };+ chips.push({+ key: "date",+ icon: <CalendarDays className={CHIP_ICON_CLASS} />,+ label: fieldLabel,+ value:+ dateFilter.from === dateFilter.to+ ? short(dateFilter.from)+ : `${short(dateFilter.from)} - ${short(dateFilter.to)}`,+ onRemove: () => onDateFilterChange?.(null),+ });+ }++ const clearAll = () => {+ if (baseline) {+ // Back to exactly the view's own conditions.+ store.getState().resetFiltersTo(baseline.raw);+ onDateFilterChange?.(null);+ return;+ }+ store.getState().clearFilters();+ onDateFilterChange?.(null);+ };++ return { chips, hasAny: chips.length > 0, clearAll };+}++function ChipSpan({ chip }: { chip: FilterChip }) {+ const { t } = useT("issues");+ return (+ // Keyed per dimension: the chip animates in once when its dimension+ // first gains a value; value changes inside it re-render without+ // re-animating. No exit animation — unmount presence isn't worth the+ // machinery for a 150ms nicety.+ <span className="flex h-6 max-w-72 items-center gap-1.5 rounded-md bg-background pl-2 pr-1 text-caption shadow-xs animate-in fade-in-0 zoom-in-95 duration-150">+ <span className="flex shrink-0 items-center gap-1 text-muted-foreground">+ {chip.icon}+ <span>{chip.label}</span>+ </span>+ <span className="flex min-w-0 items-center gap-1">+ {chip.valueIcons}+ <span className="truncate font-medium">{chip.value}</span>+ </span>+ <button+ type="button"+ aria-label={t(($) => $.filters.chip_remove, { name: chip.label })}+ onClick={chip.onRemove}+ className="flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground hover:bg-accent hover:text-foreground"+ >+ <X className="size-3" />+ </button>+ </span>+ );+}++/**+ * Bare chip list for form contexts (the save-view dialog): no bar chrome,+ * no page margins. `trailing` renders after the chips — the add-filter+ * trigger slot. Chips get a border here since they sit on the dialog+ * background rather than the muted bar. Menu-position stability while+ * adding filters is handled by the menu itself (IssueFilterMenu's+ * `freezeAnchor`), not by this list.+ */+export function FilterChipList({ trailing }: { trailing?: ReactNode }) {+ const { chips } = useFilterChips(null);+ return (+ <div className="flex flex-wrap items-center gap-1.5 [&>span]:border [&>span]:border-border [&>span]:shadow-none">+ {chips.map((chip) => (+ <ChipSpan key={chip.key} chip={chip} />+ ))}+ {trailing}+ </div>+ );+}++/**+ * Horizontal strip of active-filter chips shown under the issues header row.+ * Renders nothing when no filter is active. Each chip clears exactly its own+ * dimension; the right-aligned Clear resets everything (including the date+ * filter, which lives outside the view store).+ */+export function FilterChipsBar({+ dateFilter = null,+ onDateFilterChange,+ onSave,+ saveLabel,+ viewBaseline,+}: {+ dateFilter?: IssueDateFilter | null;+ onDateFilterChange?: (filter: IssueDateFilter | null) => void;+ /** Shows the save/edit button. Hosts that support saved views pass this+ * to open their dialog; surfaces without support omit it. */+ onSave?: () => void;+ /** Override for the trailing button label — "编辑"/"另存" in view mode. */+ saveLabel?: string;+ /** Open saved view: chips show only the user's additions on top of it. */+ viewBaseline?: IssueViewBaseline;+}) {+ const { t } = useT("issues");+ const { chips, hasAny, clearAll } = useFilterChips(dateFilter, onDateFilterChange, viewBaseline);++ if (!hasAny) return null;++ return (+ <div className="mx-4 mb-2 flex shrink-0 flex-wrap items-center gap-1.5 rounded-lg bg-muted/50 px-2 py-1.5">+ {chips.map((chip) => (+ <ChipSpan key={chip.key} chip={chip} />+ ))}+ <span className="ml-auto flex items-center gap-1.5">+ <Button+ variant="ghost"+ size="sm"+ onClick={clearAll}+ className="h-6 px-2 text-caption text-muted-foreground"+ >+ {t(($) => $.filters.chip_clear)}+ </Button>+ {onSave && (+ <Button+ variant="outline"+ size="sm"+ onClick={onSave}+ className="h-6 px-2 text-caption"+ >+ {saveLabel ?? t(($) => $.filters.chip_save)}+ </Button>+ )}+ </span>+ </div>+ );+}diff --git a/packages/views/issues/components/hidden-columns-panel.tsx b/packages/views/issues/components/hidden-columns-panel.tsxindex e049147758..5b28b19547 100644--- a/packages/views/issues/components/hidden-columns-panel.tsx+++ b/packages/views/issues/components/hidden-columns-panel.tsx@@ -18,10 +18,10 @@ import { useT } from "../../i18n";* the kanban-style views (board and swimlane).** Each consumer renders its own per-row count via the {@link renderRow} slot —- * the board uses `useLoadMoreByStatus` to fetch the workspace-wide aggregate,- * while the swimlane uses an in-memory total derived from already-loaded- * issues. Centralising the chrome here keeps a future view (calendar /- * timeline / etc.) from forking yet another copy.+ * the board reads the server status facet's exact total, while the swimlane+ * uses an in-memory total derived from already-loaded issues. Centralising+ * the chrome here keeps a future view (calendar / timeline / etc.) from+ * forking yet another copy.*/export function HiddenColumnsPanel({hiddenStatuses,@@ -54,7 +54,7 @@ export function HiddenColumnRow({total,}: {status: IssueStatus;- total: number;+ total?: number;}) {const { t } = useT("issues");const viewStoreApi = useViewStoreApi();@@ -65,7 +65,9 @@ export function HiddenColumnRow({<span className="text-body">{t(($) => $.status[status])}</span></div><div className="flex items-center gap-1.5">- <span className="text-caption text-muted-foreground">{total}</span>+ {total !== undefined && (+ <span className="text-caption text-muted-foreground">{total}</span>+ )}<DropdownMenu><DropdownMenuTriggerrender={diff --git a/packages/views/issues/components/issues-cold-load-loop.test.tsx b/packages/views/issues/components/issues-cold-load-loop.test.tsxindex 94a886f50f..d89dae0099 100644--- a/packages/views/issues/components/issues-cold-load-loop.test.tsx+++ b/packages/views/issues/components/issues-cold-load-loop.test.tsx@@ -92,20 +92,10 @@ vi.mock("@multica/core/issues/config", () => ({},}));-const mockLoadMore = vi.fn();-const loadMoreResult = {- total: 0,- loaded: 0,- hasMore: false,- isLoading: false,- loadMore: mockLoadMore,-};vi.mock("@multica/core/issues/mutations", async (importOriginal) => {const actual = await importOriginal<typeof import("@multica/core/issues/mutations")>();return {...actual,- useLoadMoreByStatus: () => loadMoreResult,- useLoadMoreByAssigneeGroup: () => loadMoreResult,};});diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsxindex 269a3a5dcb..32b651dd2f 100644--- a/packages/views/issues/components/issues-header.tsx+++ b/packages/views/issues/components/issues-header.tsx@@ -1,6 +1,6 @@"use client";-import { useMemo, useState } from "react";+import { cloneElement, useCallback, useEffect, useMemo, useRef, useState } from "react";import {ArrowDown,ArrowUp,@@ -16,7 +16,6 @@ import {Rows3,SignalHigh,SlidersHorizontal,- X,Tag,Table2,User,@@ -48,6 +47,15 @@ import {} from "@multica/ui/components/ui/popover";import { Calendar } from "@multica/ui/components/ui/calendar";import { Switch } from "@multica/ui/components/ui/switch";+import {+ Select,+ SelectTrigger,+ SelectValue,+ SelectContent,+ SelectGroup,+ SelectItem,+} from "@multica/ui/components/ui/select";+import { Toggle } from "@multica/ui/components/ui/toggle";import {ALL_STATUSES,PRIORITY_DISPLAY_ORDER,@@ -86,11 +94,23 @@ import {type ViewMode,} from "@multica/core/issues/stores/view-store";import { useViewStore, useViewStoreApi } from "@multica/core/issues/stores/view-store-context";+import { FilterChipsBar } from "./filter-chips-bar";+import { SaveViewDialog, type SaveViewScope } from "./save-view-dialog";+import { ViewBar } from "./view-bar";+import { toast } from "sonner";+import { useActiveIssueView } from "@multica/core/issue-views/use-active-view";+import { useAuthStore } from "@multica/core/auth";+import type { IssueViewScope } from "@multica/core/issue-views/queries";+import { actorFilterKey, baselineFromQuery, type IssueViewBaseline } from "@multica/core/issue-views/baseline";+import type { IssueView } from "@multica/core/api/schemas";import { addDaysDateOnly, dateOnlyToLocalDate, formatDateOnly, toDateOnly, todayDateOnly } from "@multica/core/issues/date";import {+ useIssuesScope,useIssuesScopeStore,type IssuesScope,+ type IssuesScopePageKey,} from "@multica/core/issues/stores/issues-scope-store";+import { actorKindForViewVariant } from "@multica/core/issues/surface/scope";import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";import { useT } from "../../i18n";import { matchesPinyin } from "../../editor/extensions/pinyin-match";@@ -107,27 +127,40 @@ type LocalDateRange = {// Helpers// ----------------------------------------------------------------------------function getActiveFilterCount(state: {- statusFilters: string[];- priorityFilters: string[];- assigneeFilters: ActorFilterValue[];- includeNoAssignee: boolean;- creatorFilters: ActorFilterValue[];- projectFilters: string[];- includeNoProject: boolean;- labelFilters: string[];- propertyFilters?: Record<string, string[]>;- dateFilter?: IssueDateFilter | null;-}) {+function getActiveFilterCount(+ state: {+ statusFilters: string[];+ priorityFilters: string[];+ assigneeFilters: ActorFilterValue[];+ includeNoAssignee: boolean;+ creatorFilters: ActorFilterValue[];+ projectFilters: string[];+ includeNoProject: boolean;+ labelFilters: string[];+ propertyFilters?: Record<string, string[]>;+ dateFilter?: IssueDateFilter | null;+ },+ // Inside a saved view only the user's additions on top of the view's own+ // query count — the baseline is the view, not "active filtering".+ baseline?: IssueViewBaseline,+) {let count = 0;- if (state.statusFilters.length > 0) count++;- if (state.priorityFilters.length > 0) count++;- if (state.assigneeFilters.length > 0 || state.includeNoAssignee) count++;- if (state.creatorFilters.length > 0) count++;- if (state.projectFilters.length > 0 || state.includeNoProject) count++;- if (state.labelFilters.length > 0) count++;- for (const selected of Object.values(state.propertyFilters ?? {})) {- if (selected.length > 0) count++;+ const delta = (values: string[], fixed?: Set<string>) =>+ fixed ? values.filter((v) => !fixed.has(v)).length : values.length;+ if (delta(state.statusFilters, baseline?.status) > 0) count++;+ if (delta(state.priorityFilters, baseline?.priority) > 0) count++;+ const assigneeDelta =+ delta(state.assigneeFilters.map(actorFilterKey), baseline?.assignee) > 0 ||+ (state.includeNoAssignee && !(baseline?.includeNoAssignee ?? false));+ if (assigneeDelta) count++;+ if (delta(state.creatorFilters.map(actorFilterKey), baseline?.creator) > 0) count++;+ const projectDelta =+ delta(state.projectFilters, baseline?.project) > 0 ||+ (state.includeNoProject && !(baseline?.includeNoProject ?? false));+ if (projectDelta) count++;+ if (delta(state.labelFilters, baseline?.label) > 0) count++;+ for (const [id, selected] of Object.entries(state.propertyFilters ?? {})) {+ if (delta(selected, baseline?.property.get(id)) > 0) count++;}if (state.dateFilter) count++;return count;@@ -273,6 +306,9 @@ function ActorSubContent({onToggleNoAssignee,noAssigneeCount,showSquads = true,+ fixedKeys,+ noAssigneeFixed = false,+ fixedTitle,}: {counts: Map<string, number>;selected: ActorFilterValue[];@@ -282,6 +318,10 @@ function ActorSubContent({onToggleNoAssignee?: () => void;noAssigneeCount?: number;showSquads?: boolean;+ /** Actor keys (`type:id`) fixed by the open saved view. */+ fixedKeys?: Set<string>;+ noAssigneeFixed?: boolean;+ fixedTitle?: string;}) {const { t } = useT("issues");const [search, setSearch] = useState("");@@ -321,6 +361,8 @@ function ActorSubContent({(!query || "no assignee".includes(query) || "unassigned".includes(query)) && (<DropdownMenuCheckboxItemchecked={includeNoAssignee ?? false}+ disabled={noAssigneeFixed}+ title={noAssigneeFixed ? fixedTitle : undefined}onCheckedChange={() => onToggleNoAssignee?.()}className={FILTER_ITEM_CLASS}>@@ -345,6 +387,8 @@ function ActorSubContent({<DropdownMenuCheckboxItemkey={m.user_id}checked={checked}+ disabled={fixedKeys?.has(`member:${m.user_id}`) === true}+ title={fixedKeys?.has(`member:${m.user_id}`) === true ? fixedTitle : undefined}onCheckedChange={() =>onToggle({ type: "member", id: m.user_id })}@@ -374,6 +418,8 @@ function ActorSubContent({<DropdownMenuCheckboxItemkey={a.id}checked={checked}+ disabled={fixedKeys?.has(`agent:${a.id}`) === true}+ title={fixedKeys?.has(`agent:${a.id}`) === true ? fixedTitle : undefined}onCheckedChange={() =>onToggle({ type: "agent", id: a.id })}@@ -403,6 +449,8 @@ function ActorSubContent({<DropdownMenuCheckboxItemkey={s.id}checked={checked}+ disabled={fixedKeys?.has(`squad:${s.id}`) === true}+ title={fixedKeys?.has(`squad:${s.id}`) === true ? fixedTitle : undefined}onCheckedChange={() =>onToggle({ type: "squad", id: s.id })}@@ -443,6 +491,9 @@ function ProjectSubContent({includeNoProject,onToggleNoProject,noProjectCount,+ fixedIds,+ noProjectFixed = false,+ fixedTitle,}: {counts: Map<string, number>;selected: string[];@@ -450,6 +501,9 @@ function ProjectSubContent({includeNoProject: boolean;onToggleNoProject: () => void;noProjectCount: number;+ fixedIds?: Set<string>;+ noProjectFixed?: boolean;+ fixedTitle?: string;}) {const { t } = useT("issues");const [search, setSearch] = useState("");@@ -477,6 +531,8 @@ function ProjectSubContent({{(!query || "no project".includes(query) || "unassigned".includes(query)) && (<DropdownMenuCheckboxItemchecked={includeNoProject}+ disabled={noProjectFixed}+ title={noProjectFixed ? fixedTitle : undefined}onCheckedChange={() => onToggleNoProject()}className={FILTER_ITEM_CLASS}>@@ -498,6 +554,8 @@ function ProjectSubContent({<DropdownMenuCheckboxItemkey={p.id}checked={checked}+ disabled={fixedIds?.has(p.id) === true}+ title={fixedIds?.has(p.id) === true ? fixedTitle : undefined}onCheckedChange={() => onToggle(p.id)}className={FILTER_ITEM_CLASS}>@@ -531,10 +589,14 @@ function LabelSubContent({counts,selected,onToggle,+ fixedIds,+ fixedTitle,}: {counts: Map<string, number>;selected: string[];onToggle: (labelId: string) => void;+ fixedIds?: Set<string>;+ fixedTitle?: string;}) {const { t } = useT("issues");const [search, setSearch] = useState("");@@ -564,6 +626,8 @@ function LabelSubContent({<DropdownMenuCheckboxItemkey={l.id}checked={checked}+ disabled={fixedIds?.has(l.id) === true}+ title={fixedIds?.has(l.id) === true ? fixedTitle : undefined}onCheckedChange={() => onToggle(l.id)}className={FILTER_ITEM_CLASS}>@@ -598,11 +662,15 @@ function PropertyFilterOptions({counts,selected,onToggle,+ fixedIds,+ fixedTitle,}: {property: IssueProperty;counts: Map<string, number> | undefined;selected: string[];onToggle: (optionId: string) => void;+ fixedIds?: Set<string>;+ fixedTitle?: string;}) {const { t } = useT("issues");const options =@@ -626,6 +694,8 @@ function PropertyFilterOptions({<DropdownMenuCheckboxItemkey={option.id}checked={checked}+ disabled={fixedIds?.has(option.id) === true}+ title={fixedIds?.has(option.id) === true ? fixedTitle : undefined}onCheckedChange={() => onToggle(option.id)}className={FILTER_ITEM_CLASS}>@@ -662,6 +732,9 @@ function DateSubContent({}) {const { t } = useT("issues");const [field, setField] = useState<IssueDateField>(value?.field ?? "created_at");+ // Controlled so Apply can dismiss the calendar while the filter menu+ // itself stays open (menu-wide rule: filter edits never close the menu).+ const [calendarOpen, setCalendarOpen] = useState(false);const [range, setRange] = useState<LocalDateRange | undefined>(() => {if (!value) return undefined;const from = dateOnlyToLocalDate(value.from);@@ -690,6 +763,7 @@ function DateSubContent({from: toDateOnly(from),to: toDateOnly(to),});+ setCalendarOpen(false);};return (@@ -709,18 +783,21 @@ function DateSubContent({</DropdownMenuGroup><DropdownMenuSeparator />- <DropdownMenuItem onClick={() => applyPreset(1)}>+ {/* Presets set a filter value, same semantics as toggling a status+ checkbox — keep the menu open so multi-dimension refinement+ continues. Only Reset (terminal) closes. */}+ <DropdownMenuItem closeOnClick={false} onClick={() => applyPreset(1)}>{t(($) => $.filters.date_today)}</DropdownMenuItem>- <DropdownMenuItem onClick={() => applyPreset(3)}>+ <DropdownMenuItem closeOnClick={false} onClick={() => applyPreset(3)}>{t(($) => $.filters.date_last_3_days)}</DropdownMenuItem>- <DropdownMenuItem onClick={() => applyPreset(7)}>+ <DropdownMenuItem closeOnClick={false} onClick={() => applyPreset(7)}>{t(($) => $.filters.date_last_7_days)}</DropdownMenuItem><div className="px-1.5 py-1">- <Popover>+ <Popover open={calendarOpen} onOpenChange={setCalendarOpen}><PopoverTriggerrender={<Button@@ -752,6 +829,7 @@ function DateSubContent({<><DropdownMenuSeparator /><DropdownMenuItem+ closeOnClick={false}onClick={() => {setRange(undefined);onChange(null);@@ -806,6 +884,7 @@ export function IssuesHeader({facetCountsExact = true,tableFacetCounts,onTableFacetChange,+ saveViewScope = { kind: "workspace" },}: {scopedIssues: Issue[];/** See IssueSurfaceController.workingAgents — the surface-scoped projection@@ -819,10 +898,79 @@ export function IssuesHeader({facetCountsExact?: boolean;tableFacetCounts?: IssueTableFacetsResponse;onTableFacetChange?: (facet: IssueTableFacetSpec | null) => void;+ /** Where "save as view" files the view. /issues keeps the workspace+ * default; the project-detail fallback passes its project scope; `null`+ * hides the save affordance entirely. */+ saveViewScope?: SaveViewScope | null;}) {const { t } = useT("issues");- const scope = useIssuesScopeStore((s) => s.scope);- const setScope = useIssuesScopeStore((s) => s.setScope);+ const [saveViewOpen, setSaveViewOpen] = useState(false);+ const headerWsId = useWorkspaceId();+ const viewListScope: IssueViewScope | null = saveViewScope+ ? saveViewScope.kind === "project"+ ? { scope_type: "project", scope_id: saveViewScope.projectId }+ : { scope_type: saveViewScope.kind }+ : null;+ const { activeView, views, viewsReady, setActive, missing } = useActiveIssueView(+ headerWsId,+ viewListScope,+ );+ // The open view vanished (deleted / access revoked): fall back to the+ // built-in default and say so — never a blank page (§7).+ useEffect(() => {+ if (missing) {+ setActive(null);+ toast.info(t(($) => $.view_selector.unavailable));+ }+ }, [missing, setActive, t]);+ const viewBaseline = useMemo(+ () => (activeView ? baselineFromQuery(activeView.query) : undefined),+ [activeView],+ );+ const [editTarget, setEditTarget] = useState<{+ view: IssueView;+ fromDefinition: boolean;+ } | null>(null);+ const currentUserId = useAuthStore((s) => s.user?.id ?? null);+ const isViewOwner = !!activeView && activeView.owner_id === currentUserId;+ // The tab belongs to THIS page (Issues vs each project) — see+ // IssuesScopePageKey. The header both renders the tabs and seeds the+ // save-view dialog's default variant from them.+ const scopePage: IssuesScopePageKey =+ saveViewScope?.kind === "project"+ ? `project:${saveViewScope.projectId}`+ : "issues";+ const scope = useIssuesScope(scopePage);+ const setScopeForPage = useIssuesScopeStore((s) => s.setScope);+ const setScope = useCallback(+ (next: IssuesScope) => setScopeForPage(scopePage, next),+ [setScopeForPage, scopePage],+ );+ // The save dialog's default variant: while a saved view is open the view's+ // own variant wins (the rows on screen ARE that variant — a copy must not+ // silently widen to the page tab); otherwise the page tab applies. Memoized+ // on primitives: the dialog resets its draft when this prop's identity+ // changes, so a fresh object per header render would wipe a half-typed+ // name on any background refetch.+ const dialogActorKind = activeView+ ? actorKindForViewVariant(activeView.scope_variant)+ : scope;+ const dialogProjectId =+ saveViewScope?.kind === "project" ? saveViewScope.projectId : null;+ const dialogMyVariant =+ saveViewScope?.kind === "my" ? saveViewScope.variant : null;+ const dialogScope = useMemo<SaveViewScope | null>(() => {+ if (dialogMyVariant) return { kind: "my", variant: dialogMyVariant };+ if (dialogProjectId)+ return {+ kind: "project",+ projectId: dialogProjectId,+ actorKind: dialogActorKind,+ };+ if (saveViewScope) return { kind: "workspace", actorKind: dialogActorKind };+ return null;+ // eslint-disable-next-line react-hooks/exhaustive-deps -- identity keyed on the primitive projections+ }, [dialogMyVariant, dialogProjectId, dialogActorKind, !!saveViewScope]);// Bind the workspace agents-working chip to the active view store so// shared IssuesHeader consumers (/issues and project detail) toggle the// same filter state as the rest of the display controls. /my-issues keeps@@ -845,31 +993,42 @@ export function IssuesHeader({const scopeLabel = t(($) => $.scope[SCOPE_LABEL_KEY[scope]]);return (- <div className="h-12 shrink-0 overflow-x-auto px-4 [-webkit-overflow-scrolling:touch]">- <div className="flex h-full w-max min-w-full items-center justify-between gap-2">- {/* Left: scope buttons */}- <div className="hidden shrink-0 items-center gap-1 md:flex">- {SCOPE_VALUES.map((s) => (- <Tooltip key={s}>- <TooltipTrigger- render={- <Button- variant="outline"- size="sm"- className={- scope === s- ? "bg-accent text-accent-foreground hover:bg-accent/80"- : "text-muted-foreground"- }- onClick={() => setScope(s)}- >- {t(($) => $.scope[SCOPE_LABEL_KEY[s]])}- </Button>- }- />- <TooltipContent side="bottom">{t(($) => $.scope[SCOPE_DESC_KEY[s]])}</TooltipContent>- </Tooltip>- ))}+ <>+ <div className="min-h-12 shrink-0 px-4 py-2 [-webkit-overflow-scrolling:touch]">+ <div className="flex w-full min-w-0 items-start justify-between gap-2">+ {/* Left: the view bar — built-in tabs and saved views as one flat,+ per-user ordered row; wraps instead of overflowing. */}+ <div className="hidden min-w-0 flex-1 md:block">+ {saveViewScope && viewListScope && (+ <ViewBar+ wsId={headerWsId}+ scope={viewListScope}+ builtins={SCOPE_VALUES.map((s) => ({+ key: s,+ label: t(($) => $.scope[SCOPE_LABEL_KEY[s]]),+ description: t(($) => $.scope[SCOPE_DESC_KEY[s]]),+ active: !activeView && scope === s,+ onSelect: () => {+ // Built-in tabs exit any open saved view; the surface+ // returns to its untouched per-tab state.+ if (activeView) setActive(null);+ setScope(s);+ },+ }))}+ views={views}+ viewsReady={viewsReady}+ activeView={activeView}+ onSelectView={(view) => setActive(view ? view.id : null)}+ onNewView={() => {+ setEditTarget(null);+ setSaveViewOpen(true);+ }}+ onEditView={(view) => {+ setEditTarget({ view, fromDefinition: true });+ setSaveViewOpen(true);+ }}+ />+ )}</div><DropdownMenu>@@ -915,46 +1074,89 @@ export function IssuesHeader({facetCountsExact={facetCountsExact}tableFacetCounts={tableFacetCounts}onTableFacetChange={onTableFacetChange}+ viewBaseline={viewBaseline}/><ViewRefreshIndicator active={isRefreshing} /></div></div></div>+ <FilterChipsBar+ dateFilter={dateFilter}+ onDateFilterChange={onDateFilterChange}+ viewBaseline={viewBaseline}+ saveLabel={+ activeView+ ? isViewOwner+ ? t(($) => $.filters.chip_edit)+ : t(($) => $.filters.chip_save_as)+ : undefined+ }+ onSave={+ saveViewScope+ ? () => {+ setEditTarget(+ activeView && isViewOwner+ ? { view: activeView, fromDefinition: false }+ : null,+ );+ setSaveViewOpen(true);+ }+ : undefined+ }+ />+ {dialogScope && (+ <SaveViewDialog+ open={saveViewOpen}+ onOpenChange={setSaveViewOpen}+ scope={dialogScope}+ editView={editTarget?.view ?? null}+ seedFromDefinition={editTarget?.fromDefinition ?? false}+ />+ )}+ </>);}-export function IssueDisplayControls({- scopedIssues,- hideViewToggle = false,- allowGantt = false,- dateFilter = null,- onDateFilterChange,+/**+ * The full filter menu (every dimension, search, counts) behind a caller-+ * supplied trigger. The toolbar wraps it in its labeled button; the+ * save-view dialog attaches it to a ghost "add filter" chip targeting the+ * draft store. Counts follow `scopedIssues` — pass nothing to hide them.+ */+export function IssueFilterMenu({+ trigger,+ tooltip,+ scopedIssues = NO_COUNT_ISSUES,facetCountsExact = true,tableFacetCounts,onTableFacetChange,+ dateFilter = null,+ onDateFilterChange,+ onOpenChange,+ freezeAnchor = false,+ viewBaseline,}: {- scopedIssues: Issue[];- hideViewToggle?: boolean;- dateFilter?: IssueDateFilter | null;- onDateFilterChange?: (filter: IssueDateFilter | null) => void;- // Only Project Detail renders <GanttView>; other surfaces (global /issues,- // /my-issues, actor panel) ignore viewMode === "gantt" and would silently- // fall back to List if the option were exposed there. Keep Gantt opt-in.- allowGantt?: boolean;- /**- * Whether `scopedIssues` covers the surface's full window. Table does not- * use loaded rows for counts; server-paged List, Board, and Swimlane follow- * the same rule. They supply `tableFacetCounts` from the backend instead,- * so badges remain exact without downloading all issues.- */+ trigger: React.ReactElement;+ tooltip?: string;+ scopedIssues?: Issue[];facetCountsExact?: boolean;tableFacetCounts?: IssueTableFacetsResponse;onTableFacetChange?: (facet: IssueTableFacetSpec | null) => void;+ dateFilter?: IssueDateFilter | null;+ onDateFilterChange?: (filter: IssueDateFilter | null) => void;+ /** Mirrors the menu's open state. */+ onOpenChange?: (open: boolean) => void;+ /** Pin the open menu to the trigger's position AT OPEN TIME (a virtual+ * anchor). With it, chips growing or wrapping can reflow the trigger+ * freely without the open menu ever moving under the pointer. */+ freezeAnchor?: boolean;+ /** Open saved view: values the view fixes render checked-and-disabled+ * ("already in this view"); everything else stays selectable. */+ viewBaseline?: IssueViewBaseline;}) {const { t } = useT("issues");- const [tableGroupMenuOpen, setTableGroupMenuOpen] = useState(false);- const [viewMenuOpen, setViewMenuOpen] = useState(false);- const viewMode = useViewStore((s) => s.viewMode);+ const triggerRef = useRef<HTMLElement>(null);+ const [frozenAnchor, setFrozenAnchor] = useState<{ getBoundingClientRect: () => DOMRect } | null>(null);const statusFilters = useViewStore((s) => s.statusFilters);const priorityFilters = useViewStore((s) => s.priorityFilters);const assigneeFilters = useViewStore((s) => s.assigneeFilters);@@ -964,24 +1166,10 @@ export function IssueDisplayControls({const includeNoProject = useViewStore((s) => s.includeNoProject);const labelFilters = useViewStore((s) => s.labelFilters);const propertyFilters = useViewStore((s) => s.propertyFilters);- const cardPropertyIds = useViewStore((s) => s.cardPropertyIds);- const sortBy = useViewStore((s) => s.sortBy);- const sortDirection = useViewStore((s) => s.sortDirection);- const grouping = useViewStore((s) => s.grouping);- const swimlaneGrouping = useViewStore((s) => s.swimlaneGrouping);- const cardProperties = useViewStore((s) => s.cardProperties);- const tableGrouping = useViewStore((s) => s.tableGrouping ?? "none");- const tableHierarchy = useViewStore((s) => s.tableHierarchy ?? true);- const showSubIssues = useViewStore((s) => s.showSubIssues);- const act = useViewStoreApi().getState();- const headerWsId = useWorkspaceId();- // Active custom-property catalog: drives the filter sections, dynamic- // sort/grouping options, and the card-property toggles below.- const { data: workspaceProperties = [] } = useQuery(propertyListOptions(headerWsId));- const propertyById = useMemo(- () => new Map(workspaceProperties.map((p) => [p.id, p])),- [workspaceProperties],- );+ const viewStoreApi = useViewStoreApi();+ const act = viewStoreApi.getState();+ const wsId = useWorkspaceId();+ const { data: workspaceProperties = [] } = useQuery(propertyListOptions(wsId));const filterableProperties = useMemo(() =>workspaceProperties.filter((p) =>@@ -989,81 +1177,34 @@ export function IssueDisplayControls({),[workspaceProperties],);- const sortableProperties = useMemo(- () => workspaceProperties.filter((p) => p.type === "number" || p.type === "date"),- [workspaceProperties],- );- const groupableProperties = useMemo(- () => workspaceProperties.filter((p) => p.type === "select"),- [workspaceProperties],- );- const tableGroupableProperties = useMemo(- () =>- workspaceProperties.filter((p) =>- ["select", "checkbox"].includes(p.type),- ),- [workspaceProperties],- );-const counts = useIssueCounts(facetCountsExact ? scopedIssues : NO_COUNT_ISSUES,tableFacetCounts,);const showDateFilter = !!onDateFilterChange;-- // Only count filters whose definition is still active — a filter pinned to- // an archived definition is stripped by the surface controller and must- // not light the badge for an effect that no longer exists.const effectivePropertyFilters = useMemo(() => {const activeIds = new Set(filterableProperties.map((p) => p.id));return Object.fromEntries(Object.entries(propertyFilters).filter(([id, selected]) => selected.length > 0 && activeIds.has(id)),);}, [filterableProperties, propertyFilters]);-- const activeFilterCount = getActiveFilterCount({- statusFilters,- priorityFilters,- propertyFilters: effectivePropertyFilters,- assigneeFilters,- includeNoAssignee,- creatorFilters,- projectFilters,- includeNoProject,- labelFilters,- dateFilter: showDateFilter ? dateFilter : null,- });- const hasActiveFilters = activeFilterCount > 0;-- const SORT_LABEL_KEY: Record<typeof SORT_OPTIONS[number]["value"], "sort_manual" | "sort_status" | "sort_priority" | "sort_start_date" | "sort_due_date" | "sort_created" | "sort_updated" | "sort_title"> = {- position: "sort_manual",- status: "sort_status",- priority: "sort_priority",- start_date: "sort_start_date",- due_date: "sort_due_date",- created_at: "sort_created",- updated_at: "sort_updated",- title: "sort_title",- };- const GROUPING_LABEL_KEY: Record<typeof GROUPING_OPTIONS[number]["value"], "group_status" | "group_assignee"> = {- status: "group_status",- assignee: "group_assignee",- };- const SWIMLANE_GROUPING_LABEL_KEY: Record<SwimlaneGrouping, "group_parent" | "group_project" | "group_assignee"> = {- parent: "group_parent",- project: "group_project",- assignee: "group_assignee",- };- const CARD_PROPERTY_LABEL_KEY: Record<typeof CARD_PROPERTY_OPTIONS[number]["key"], "card_priority" | "card_description" | "card_assignee" | "card_start_date" | "card_due_date" | "card_project" | "card_labels" | "card_child_progress"> = {- priority: "card_priority",- description: "card_description",- assignee: "card_assignee",- startDate: "card_start_date",- dueDate: "card_due_date",- project: "card_project",- labels: "card_labels",- childProgress: "card_child_progress",- };+ const hasActiveFilters =+ getActiveFilterCount(+ {+ statusFilters,+ priorityFilters,+ propertyFilters: effectivePropertyFilters,+ assigneeFilters,+ includeNoAssignee,+ creatorFilters,+ projectFilters,+ includeNoProject,+ labelFilters,+ dateFilter: showDateFilter ? dateFilter : null,+ },+ viewBaseline,+ ) > 0;+ const fixedTitle = viewBaseline ? t(($) => $.filters.in_view) : undefined;const dateFilterLabel = showDateFilter && dateFilter? `${t(($) => $.filters[DATE_FIELD_LABEL_KEY[dateFilter.field]])}: ${dateFilter.from === dateFilter.to@@ -1071,72 +1212,37 @@ export function IssueDisplayControls({: `${shortDateLabel(dateFilter.from)} - ${shortDateLabel(dateFilter.to)}`}`: null;- const sortPropertyId = propertyIdFromViewKey(sortBy);- const groupingPropertyId = propertyIdFromViewKey(grouping);- const tableGroupingPropertyId = propertyIdFromViewKey(tableGrouping);- // Property-backed sort/grouping label straight from the definition name;- // a stale persisted id (archived/deleted definition) falls back to the- // manual/status default label.- const sortLabel = sortPropertyId- ? propertyById.get(sortPropertyId)?.name ?? t(($) => $.display.sort_manual)- : t(($) => $.display[SORT_LABEL_KEY[sortBy as keyof typeof SORT_LABEL_KEY]]);- const groupingLabel = groupingPropertyId- ? propertyById.get(groupingPropertyId)?.name ?? t(($) => $.display.group_status)- : t(($) => $.display[GROUPING_LABEL_KEY[grouping as keyof typeof GROUPING_LABEL_KEY]]);- const swimlaneGroupingLabel = t(($) => $.display[SWIMLANE_GROUPING_LABEL_KEY[swimlaneGrouping]]);- const effectiveTableGrouping =- tableGroupingPropertyId && !propertyById.has(tableGroupingPropertyId)- ? "none"- : tableGrouping;- const tableGroupingLabel = tableGroupingPropertyId- ? propertyById.get(tableGroupingPropertyId)?.name ??- t(($) => $.table.group_none)- : effectiveTableGrouping === "status"- ? t(($) => $.table.columns.status)- : effectiveTableGrouping === "assignee"- ? t(($) => $.table.columns.assignee)- : t(($) => $.table.group_none);- const controlButtonClass = "h-8 w-8 gap-1 px-0 text-muted-foreground md:h-7 md:w-auto md:px-2.5";++ // Base UI's render-prop merges its own ref with ours, so cloning the+ // caller's element only adds the ref we need for rect capture.+ const anchoredTrigger = freezeAnchor+ ? cloneElement(trigger, { ref: triggerRef } as Partial<React.HTMLAttributes<HTMLElement>>)+ : trigger;return (- <div className="flex shrink-0 items-center gap-1">- {/* Filter */}- <DropdownMenu- onOpenChange={(open) => {- if (!open) onTableFacetChange?.(null);- }}- >- <Tooltip>- <DropdownMenuTrigger- render={- <TooltipTrigger- render={- <Button- variant={hasActiveFilters ? "default" : "outline"}- size="sm"- className={- hasActiveFilters- ? "h-8 w-8 gap-1 bg-brand px-0 text-white hover:bg-brand/90 md:h-7 md:w-auto md:px-2.5"- : controlButtonClass- }- >- <Filter className="size-3.5" />- <span className="hidden md:inline">- {hasActiveFilters- ? t(($) => $.filters.active_count, { count: activeFilterCount })- : t(($) => $.filters.tooltip)}- </span>- {hasActiveFilters && (- <span className="tabular-nums md:hidden">{activeFilterCount}</span>- )}- </Button>- }- />- }- />- <TooltipContent side="bottom">{t(($) => $.filters.tooltip)}</TooltipContent>- </Tooltip>- <DropdownMenuContent align="end" className="w-auto">+ <DropdownMenu+ onOpenChange={(open) => {+ if (freezeAnchor) {+ if (open && triggerRef.current) {+ const rect = triggerRef.current.getBoundingClientRect();+ setFrozenAnchor({ getBoundingClientRect: () => rect });+ } else if (!open) {+ setFrozenAnchor(null);+ }+ }+ if (!open) onTableFacetChange?.(null);+ onOpenChange?.(open);+ }}+ >+ {tooltip ? (+ <Tooltip>+ <DropdownMenuTrigger render={<TooltipTrigger render={anchoredTrigger} />} />+ <TooltipContent side="bottom">{tooltip}</TooltipContent>+ </Tooltip>+ ) : (+ <DropdownMenuTrigger render={anchoredTrigger} />+ )}+ <DropdownMenuContent align="end" className="w-auto" anchor={frozenAnchor ?? undefined}>{/* Status */}<DropdownMenuSubonOpenChange={(open) =>@@ -1156,10 +1262,13 @@ export function IssueDisplayControls({{ALL_STATUSES.map((s) => {const checked = statusFilters.includes(s);const count = counts.status.get(s) ?? 0;+ const fixed = viewBaseline?.status.has(s) === true;return (<DropdownMenuCheckboxItemkey={s}checked={checked}+ disabled={fixed}+ title={fixed ? fixedTitle : undefined}onCheckedChange={() => act.toggleStatusFilter(s)}className={FILTER_ITEM_CLASS}>@@ -1196,10 +1305,13 @@ export function IssueDisplayControls({{PRIORITY_DISPLAY_ORDER.map((p) => {const checked = priorityFilters.includes(p);const count = counts.priority.get(p) ?? 0;+ const fixed = viewBaseline?.priority.has(p) === true;return (<DropdownMenuCheckboxItemkey={p}checked={checked}+ disabled={fixed}+ title={fixed ? fixedTitle : undefined}onCheckedChange={() => act.togglePriorityFilter(p)}className={FILTER_ITEM_CLASS}>@@ -1261,6 +1373,9 @@ export function IssueDisplayControls({includeNoAssignee={includeNoAssignee}onToggleNoAssignee={act.toggleNoAssignee}noAssigneeCount={counts.noAssignee}+ fixedKeys={viewBaseline?.assignee}+ noAssigneeFixed={viewBaseline?.includeNoAssignee === true}+ fixedTitle={fixedTitle}/></DropdownMenuSubContent></DropdownMenuSub>@@ -1286,6 +1401,8 @@ export function IssueDisplayControls({selected={creatorFilters}onToggle={act.toggleCreatorFilter}showSquads={false}+ fixedKeys={viewBaseline?.creator}+ fixedTitle={fixedTitle}/></DropdownMenuSubContent></DropdownMenuSub>@@ -1313,6 +1430,9 @@ export function IssueDisplayControls({includeNoProject={includeNoProject}onToggleNoProject={act.toggleNoProject}noProjectCount={counts.noProject}+ fixedIds={viewBaseline?.project}+ noProjectFixed={viewBaseline?.includeNoProject === true}+ fixedTitle={fixedTitle}/></DropdownMenuSubContent></DropdownMenuSub>@@ -1337,6 +1457,8 @@ export function IssueDisplayControls({counts={counts.label}selected={labelFilters}onToggle={act.toggleLabelFilter}+ fixedIds={viewBaseline?.label}+ fixedTitle={fixedTitle}/></DropdownMenuSubContent></DropdownMenuSub>@@ -1375,6 +1497,8 @@ export function IssueDisplayControls({counts={counts.property.get(property.id)}selected={selected}onToggle={(optionId) => act.togglePropertyFilter(property.id, optionId)}+ fixedIds={viewBaseline?.property.get(property.id)}+ fixedTitle={fixedTitle}/></DropdownMenuSubContent></DropdownMenuSub>@@ -1387,7 +1511,13 @@ export function IssueDisplayControls({<DropdownMenuSeparator /><DropdownMenuItemonClick={() => {- act.clearFilters();+ if (viewBaseline) {+ // Inside a saved view, reset returns to the view's own+ // conditions, never to nothing.+ act.resetFiltersTo(viewBaseline.raw);+ } else {+ act.clearFilters();+ }onDateFilterChange?.(null);}}>@@ -1396,32 +1526,214 @@ export function IssueDisplayControls({</>)}</DropdownMenuContent>- </DropdownMenu>+ </DropdownMenu>+ );+}- {hasActiveFilters && (- <Tooltip>- <TooltipTrigger- render={- <Button- type="button"- variant="ghost"- size="icon-sm"- aria-label={t(($) => $.filters.reset)}- onClick={() => {- act.clearFilters();- onDateFilterChange?.(null);- }}- className="hidden text-muted-foreground md:inline-flex"- >- <X className="size-3.5" />- </Button>+export function IssueDisplayControls({+ scopedIssues,+ hideViewToggle = false,+ allowGantt = false,+ dateFilter = null,+ onDateFilterChange,+ facetCountsExact = true,+ tableFacetCounts,+ onTableFacetChange,+ viewBaseline,+}: {+ scopedIssues: Issue[];+ hideViewToggle?: boolean;+ dateFilter?: IssueDateFilter | null;+ onDateFilterChange?: (filter: IssueDateFilter | null) => void;+ /** Open saved view: menu marks the view's values checked-and-disabled;+ * the trigger count only counts additions on top. */+ viewBaseline?: IssueViewBaseline;+ // Only Project Detail renders <GanttView>; other surfaces (global /issues,+ // /my-issues, actor panel) ignore viewMode === "gantt" and would silently+ // fall back to List if the option were exposed there. Keep Gantt opt-in.+ allowGantt?: boolean;+ /**+ * Whether `scopedIssues` covers the surface's full window. Table does not+ * use loaded rows for counts; server-paged List, Board, and Swimlane follow+ * the same rule. They supply `tableFacetCounts` from the backend instead,+ * so badges remain exact without downloading all issues.+ */+ facetCountsExact?: boolean;+ tableFacetCounts?: IssueTableFacetsResponse;+ onTableFacetChange?: (facet: IssueTableFacetSpec | null) => void;+}) {+ const { t } = useT("issues");+ const [tableGroupMenuOpen, setTableGroupMenuOpen] = useState(false);+ const [viewMenuOpen, setViewMenuOpen] = useState(false);+ 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 projectFilters = useViewStore((s) => s.projectFilters);+ const includeNoProject = useViewStore((s) => s.includeNoProject);+ const labelFilters = useViewStore((s) => s.labelFilters);+ const propertyFilters = useViewStore((s) => s.propertyFilters);+ const cardPropertyIds = useViewStore((s) => s.cardPropertyIds);+ const sortBy = useViewStore((s) => s.sortBy);+ const sortDirection = useViewStore((s) => s.sortDirection);+ const grouping = useViewStore((s) => s.grouping);+ const swimlaneGrouping = useViewStore((s) => s.swimlaneGrouping);+ const cardProperties = useViewStore((s) => s.cardProperties);+ const tableGrouping = useViewStore((s) => s.tableGrouping ?? "none");+ const tableHierarchy = useViewStore((s) => s.tableHierarchy ?? true);+ const showSubIssues = useViewStore((s) => s.showSubIssues);+ const act = useViewStoreApi().getState();+ const headerWsId = useWorkspaceId();+ // Active custom-property catalog: drives the filter sections, dynamic+ // sort/grouping options, and the card-property toggles below.+ const { data: workspaceProperties = [] } = useQuery(propertyListOptions(headerWsId));+ const propertyById = useMemo(+ () => new Map(workspaceProperties.map((p) => [p.id, p])),+ [workspaceProperties],+ );+ const filterableProperties = useMemo(+ () =>+ workspaceProperties.filter((p) =>+ p.type === "select" || p.type === "multi_select" || p.type === "checkbox",+ ),+ [workspaceProperties],+ );+ const sortableProperties = useMemo(+ () => workspaceProperties.filter((p) => p.type === "number" || p.type === "date"),+ [workspaceProperties],+ );+ const groupableProperties = useMemo(+ () => workspaceProperties.filter((p) => p.type === "select"),+ [workspaceProperties],+ );+ const tableGroupableProperties = useMemo(+ () =>+ workspaceProperties.filter((p) =>+ ["select", "checkbox"].includes(p.type),+ ),+ [workspaceProperties],+ );++ const showDateFilter = !!onDateFilterChange;++ // Only count filters whose definition is still active — a filter pinned to+ // an archived definition is stripped by the surface controller and must+ // not light the badge for an effect that no longer exists.+ const effectivePropertyFilters = useMemo(() => {+ const activeIds = new Set(filterableProperties.map((p) => p.id));+ return Object.fromEntries(+ Object.entries(propertyFilters).filter(([id, selected]) => selected.length > 0 && activeIds.has(id)),+ );+ }, [filterableProperties, propertyFilters]);++ const activeFilterCount = getActiveFilterCount(+ {+ statusFilters,+ priorityFilters,+ propertyFilters: effectivePropertyFilters,+ assigneeFilters,+ includeNoAssignee,+ creatorFilters,+ projectFilters,+ includeNoProject,+ labelFilters,+ dateFilter: showDateFilter ? dateFilter : null,+ },+ viewBaseline,+ );+ const hasActiveFilters = activeFilterCount > 0;++ const SORT_LABEL_KEY: Record<typeof SORT_OPTIONS[number]["value"], "sort_manual" | "sort_status" | "sort_priority" | "sort_start_date" | "sort_due_date" | "sort_created" | "sort_updated" | "sort_title"> = {+ position: "sort_manual",+ status: "sort_status",+ priority: "sort_priority",+ start_date: "sort_start_date",+ due_date: "sort_due_date",+ created_at: "sort_created",+ updated_at: "sort_updated",+ title: "sort_title",+ };+ const GROUPING_LABEL_KEY: Record<typeof GROUPING_OPTIONS[number]["value"], "group_status" | "group_assignee"> = {+ status: "group_status",+ assignee: "group_assignee",+ };+ const SWIMLANE_GROUPING_LABEL_KEY: Record<SwimlaneGrouping, "group_parent" | "group_project" | "group_assignee"> = {+ parent: "group_parent",+ project: "group_project",+ assignee: "group_assignee",+ };+ const CARD_PROPERTY_LABEL_KEY: Record<typeof CARD_PROPERTY_OPTIONS[number]["key"], "card_priority" | "card_description" | "card_assignee" | "card_start_date" | "card_due_date" | "card_project" | "card_labels" | "card_child_progress"> = {+ priority: "card_priority",+ description: "card_description",+ assignee: "card_assignee",+ startDate: "card_start_date",+ dueDate: "card_due_date",+ project: "card_project",+ labels: "card_labels",+ childProgress: "card_child_progress",+ };+ const sortPropertyId = propertyIdFromViewKey(sortBy);+ const groupingPropertyId = propertyIdFromViewKey(grouping);+ const tableGroupingPropertyId = propertyIdFromViewKey(tableGrouping);+ // Property-backed sort/grouping label straight from the definition name;+ // a stale persisted id (archived/deleted definition) falls back to the+ // manual/status default label.+ const sortLabel = sortPropertyId+ ? propertyById.get(sortPropertyId)?.name ?? t(($) => $.display.sort_manual)+ : t(($) => $.display[SORT_LABEL_KEY[sortBy as keyof typeof SORT_LABEL_KEY]]);+ const groupingLabel = groupingPropertyId+ ? propertyById.get(groupingPropertyId)?.name ?? t(($) => $.display.group_status)+ : t(($) => $.display[GROUPING_LABEL_KEY[grouping as keyof typeof GROUPING_LABEL_KEY]]);+ const swimlaneGroupingLabel = t(($) => $.display[SWIMLANE_GROUPING_LABEL_KEY[swimlaneGrouping]]);+ const effectiveTableGrouping =+ tableGroupingPropertyId && !propertyById.has(tableGroupingPropertyId)+ ? "none"+ : tableGrouping;+ const tableGroupingLabel = tableGroupingPropertyId+ ? propertyById.get(tableGroupingPropertyId)?.name ??+ t(($) => $.table.group_none)+ : effectiveTableGrouping === "status"+ ? t(($) => $.table.columns.status)+ : effectiveTableGrouping === "assignee"+ ? t(($) => $.table.columns.assignee)+ : t(($) => $.table.group_none);+ const controlButtonClass = "h-8 w-8 gap-1 px-0 text-muted-foreground md:h-7 md:w-auto md:px-2.5";++ return (+ <div className="flex shrink-0 items-center gap-1">+ <IssueFilterMenu+ trigger={+ <Button+ variant={hasActiveFilters ? "default" : "outline"}+ size="sm"+ className={+ hasActiveFilters+ ? "h-8 w-8 gap-1 bg-brand px-0 text-white hover:bg-brand/90 md:h-7 md:w-auto md:px-2.5"+ : controlButtonClass}- />- <TooltipContent side="bottom">- {t(($) => $.filters.reset)}- </TooltipContent>- </Tooltip>- )}+ >+ <Filter className="size-3.5" />+ <span className="hidden md:inline">+ {hasActiveFilters+ ? t(($) => $.filters.active_count, { count: activeFilterCount })+ : t(($) => $.filters.tooltip)}+ </span>+ {hasActiveFilters && (+ <span className="tabular-nums md:hidden">{activeFilterCount}</span>+ )}+ </Button>+ }+ tooltip={t(($) => $.filters.tooltip)}+ scopedIssues={scopedIssues}+ facetCountsExact={facetCountsExact}+ tableFacetCounts={tableFacetCounts}+ onTableFacetChange={onTableFacetChange}+ dateFilter={showDateFilter ? dateFilter : null}+ onDateFilterChange={onDateFilterChange}+ viewBaseline={viewBaseline}+ />{viewMode === "table" && (<DropdownMenu@@ -1517,89 +1829,88 @@ export function IssueDisplayControls({/><TooltipContent side="bottom">{t(($) => $.display.tooltip)}</TooltipContent></Tooltip>- <PopoverContent align="end" className="w-64 p-0">- {viewMode === "board" && (- <div className="border-b px-3 py-2.5">- <span className="text-caption font-medium text-muted-foreground">- {t(($) => $.display.grouping_section)}- </span>- <div className="mt-2">- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button- variant="outline"- size="sm"- className="w-full justify-between text-caption"- >- {groupingLabel}- <ChevronDown className="size-3 text-muted-foreground" />- </Button>- }- />- <DropdownMenuContent align="start" className="w-auto">- <DropdownMenuRadioGroup value={grouping} onValueChange={(v) => act.setGrouping(v as IssueGrouping)}>- {GROUPING_OPTIONS.map((opt) => (- <DropdownMenuRadioItem key={opt.value} value={opt.value}>- {t(($) => $.display[GROUPING_LABEL_KEY[opt.value]])}- </DropdownMenuRadioItem>- ))}- {groupableProperties.map((property) => (- <DropdownMenuRadioItem key={property.id} value={`property:${property.id}`}>- <PropertyIcon property={property} className="size-3.5 text-caption" />- <span>{property.name}</span>- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>+ <PopoverContent align="end" className="w-64 p-3">+ <div className="space-y-3">+ {/* Uniform rows: caption label left, control right. Spacing+ separates sections — no dividers (see UI rules). */}+ {viewMode === "board" && (+ <div className="flex items-center justify-between gap-3">+ <span className="text-caption font-medium text-muted-foreground">+ {t(($) => $.display.grouping_section)}+ </span>+ <Select+ items={[+ ...GROUPING_OPTIONS.map((opt) => ({+ value: opt.value as string,+ label: t(($) => $.display[GROUPING_LABEL_KEY[opt.value]]),+ })),+ ...groupableProperties.map((p) => ({+ value: `property:${p.id}`,+ label: p.name,+ })),+ ]}+ value={grouping}+ onValueChange={(v) => {+ if (v) act.setGrouping(v as IssueGrouping);+ }}+ >+ <SelectTrigger size="sm" className="w-32" aria-label={t(($) => $.display.grouping_section)}>+ <SelectValue>{groupingLabel}</SelectValue>+ </SelectTrigger>+ <SelectContent align="end">+ <SelectGroup>+ {GROUPING_OPTIONS.map((opt) => (+ <SelectItem key={opt.value} value={opt.value}>+ {t(($) => $.display[GROUPING_LABEL_KEY[opt.value]])}+ </SelectItem>+ ))}+ {groupableProperties.map((property) => (+ <SelectItem key={property.id} value={`property:${property.id}`}>+ {property.name}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select></div>- </div>- )}- {viewMode === "swimlane" && (- <div className="border-b px-3 py-2.5">- <span className="text-caption font-medium text-muted-foreground">- {t(($) => $.display.grouping_section)}- </span>- <div className="mt-2">- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button- variant="outline"- size="sm"- className="w-full justify-between text-caption"- >- {swimlaneGroupingLabel}- <ChevronDown className="size-3 text-muted-foreground" />- </Button>- }- />- <DropdownMenuContent align="start" className="w-auto">- <DropdownMenuRadioGroup- value={swimlaneGrouping}- onValueChange={(v) => act.setSwimlaneGrouping(v as SwimlaneGrouping)}- >- {SWIMLANE_GROUPINGS.map((value) => (- <DropdownMenuRadioItem key={value} value={value}>- {t(($) => $.display[SWIMLANE_GROUPING_LABEL_KEY[value]])}- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>+ )}+ {viewMode === "swimlane" && (+ <div className="flex items-center justify-between gap-3">+ <span className="text-caption font-medium text-muted-foreground">+ {t(($) => $.display.grouping_section)}+ </span>+ <Select+ items={SWIMLANE_GROUPINGS.map((value) => ({+ value: value as string,+ label: t(($) => $.display[SWIMLANE_GROUPING_LABEL_KEY[value]]),+ }))}+ value={swimlaneGrouping}+ onValueChange={(v) => {+ if (v) act.setSwimlaneGrouping(v as SwimlaneGrouping);+ }}+ >+ <SelectTrigger size="sm" className="w-32" aria-label={t(($) => $.display.grouping_section)}>+ <SelectValue>{swimlaneGroupingLabel}</SelectValue>+ </SelectTrigger>+ <SelectContent align="end">+ <SelectGroup>+ {SWIMLANE_GROUPINGS.map((value) => (+ <SelectItem key={value} value={value}>+ {t(($) => $.display[SWIMLANE_GROUPING_LABEL_KEY[value]])}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select></div>- </div>- )}-- {viewMode === "table" && (- <div className="border-b px-3 py-2.5">+ )}+ {viewMode === "table" && (<label className="flex cursor-pointer items-center justify-between gap-3"><span className="min-w-0">- <span className="block text-body">+ <span className="block text-caption font-medium text-muted-foreground">{t(($) => $.table.hierarchy)}</span>- <span className="block text-caption text-muted-foreground">+ <span className="block text-caption text-faint-foreground">{t(($) => $.table.hierarchy_description)}</span></span>@@ -1609,112 +1920,110 @@ export function IssueDisplayControls({onCheckedChange={() => act.toggleTableHierarchy()}/></label>- </div>- )}-- <div className="border-b px-3 py-2.5">- <span className="text-caption font-medium text-muted-foreground">- {t(($) => $.display.ordering_section)}- </span>- <div className="mt-2 flex items-center gap-1.5">- <DropdownMenu>- <DropdownMenuTrigger- render={- <Button- variant="outline"- size="sm"- className="flex-1 justify-between text-caption"- >- {sortLabel}- <ChevronDown className="size-3 text-muted-foreground" />- </Button>- }- />- <DropdownMenuContent align="start" className="w-auto">- <DropdownMenuRadioGroup value={sortBy} onValueChange={(v) => act.setSortBy(v as SortField)}>+ )}+ <div className="flex items-center justify-between gap-3">+ <span className="text-caption font-medium text-muted-foreground">+ {t(($) => $.display.ordering_section)}+ </span>+ <div className="flex items-center gap-1.5">+ <Select+ items={[+ ...SORT_OPTIONS.map((opt) => ({+ value: opt.value as string,+ label: t(($) => $.display[SORT_LABEL_KEY[opt.value as keyof typeof SORT_LABEL_KEY]]),+ })),+ ...sortableProperties.map((p) => ({+ value: `property:${p.id}`,+ label: p.name,+ })),+ ]}+ value={sortBy}+ onValueChange={(v) => {+ if (v) act.setSortBy(v as SortField);+ }}+ >+ <SelectTrigger size="sm" className="w-26" aria-label={t(($) => $.display.ordering_section)}>+ <SelectValue>{sortLabel}</SelectValue>+ </SelectTrigger>+ <SelectContent align="end">+ <SelectGroup>{SORT_OPTIONS.map((opt) => (- <DropdownMenuRadioItem key={opt.value} value={opt.value}>+ <SelectItem key={opt.value} value={opt.value}>{t(($) => $.display[SORT_LABEL_KEY[opt.value as keyof typeof SORT_LABEL_KEY]])}- </DropdownMenuRadioItem>+ </SelectItem>))}{sortableProperties.map((property) => (- <DropdownMenuRadioItem key={property.id} value={`property:${property.id}`}>- <PropertyIcon property={property} className="size-3.5 text-caption" />- <span>{property.name}</span>- </DropdownMenuRadioItem>+ <SelectItem key={property.id} value={`property:${property.id}`}>+ {property.name}+ </SelectItem>))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>- {sortBy !== "position" && (- <Button- variant="outline"- size="icon-sm"- onClick={() =>- act.setSortDirection(sortDirection === "asc" ? "desc" : "asc")- }- title={sortDirection === "asc" ? t(($) => $.display.ascending_title) : t(($) => $.display.descending_title)}- >- {sortDirection === "asc" ? (- <ArrowUp className="size-3.5" />- ) : (- <ArrowDown className="size-3.5" />- )}- </Button>- )}+ </SelectGroup>+ </SelectContent>+ </Select>+ {sortBy !== "position" && (+ <Button+ variant="outline"+ size="icon-sm"+ onClick={() =>+ act.setSortDirection(sortDirection === "asc" ? "desc" : "asc")+ }+ title={sortDirection === "asc" ? t(($) => $.display.ascending_title) : t(($) => $.display.descending_title)}+ >+ {sortDirection === "asc" ? (+ <ArrowUp className="size-3.5" />+ ) : (+ <ArrowDown className="size-3.5" />+ )}+ </Button>+ )}+ </div></div>- </div>-- <label className="flex cursor-pointer items-center justify-between border-b px-3 py-2.5">- <span className="text-body">{t(($) => $.display.show_sub_issues)}</span>- <Switch- size="sm"- checked={showSubIssues}- onCheckedChange={() => act.toggleShowSubIssues()}- />- </label>-- {viewMode !== "table" && (- <div className="px-3 py-2.5">+ <label className="flex cursor-pointer items-center justify-between gap-3"><span className="text-caption font-medium text-muted-foreground">- {t(($) => $.display.card_properties_section)}+ {t(($) => $.display.show_sub_issues)}</span>- <div className="mt-2 space-y-2">- {CARD_PROPERTY_OPTIONS.map((opt) => (- <label- key={opt.key}- className="flex cursor-pointer items-center justify-between"- >- <span className="text-body">{t(($) => $.display[CARD_PROPERTY_LABEL_KEY[opt.key]])}</span>- <Switch+ <Switch+ size="sm"+ checked={showSubIssues}+ onCheckedChange={() => act.toggleShowSubIssues()}+ />+ </label>+ {viewMode !== "table" && (+ <div>+ <span className="text-caption font-medium text-muted-foreground">+ {t(($) => $.display.card_properties_section)}+ </span>+ {/* Chip toggles (pressed = shown on cards). Unpressed chips+ dim so the active set reads at a glance. */}+ <div className="mt-2 flex flex-wrap gap-1">+ {CARD_PROPERTY_OPTIONS.map((opt) => (+ <Toggle+ key={opt.key}size="sm"- checked={cardProperties[opt.key]}- onCheckedChange={() => act.toggleCardProperty(opt.key)}- />- </label>- ))}- {workspaceProperties.map((property) => (- <label- key={property.id}- className="flex cursor-pointer items-center justify-between"- >- <span className="flex min-w-0 items-center gap-1.5 truncate text-body">- <PropertyIcon- property={property}- className="size-3.5 text-caption"- />- <span className="truncate">{property.name}</span>- </span>- <Switch+ variant="outline"+ pressed={cardProperties[opt.key]}+ onPressedChange={() => act.toggleCardProperty(opt.key)}+ className="h-6 rounded-md px-2 text-caption text-muted-foreground hover:bg-muted/60 aria-pressed:border-transparent aria-pressed:bg-accent aria-pressed:text-accent-foreground aria-pressed:hover:bg-accent/80"+ >+ {t(($) => $.display[CARD_PROPERTY_LABEL_KEY[opt.key]])}+ </Toggle>+ ))}+ {workspaceProperties.map((property) => (+ <Toggle+ key={property.id}size="sm"- checked={cardPropertyIds.includes(property.id)}- onCheckedChange={() => act.toggleCardPropertyId(property.id)}- />- </label>- ))}+ variant="outline"+ pressed={cardPropertyIds.includes(property.id)}+ onPressedChange={() => act.toggleCardPropertyId(property.id)}+ className="h-6 max-w-40 rounded-md px-2 text-caption text-muted-foreground hover:bg-muted/60 aria-pressed:border-transparent aria-pressed:bg-accent aria-pressed:text-accent-foreground aria-pressed:hover:bg-accent/80"+ >+ <span className="truncate">{property.name}</span>+ </Toggle>+ ))}+ </div></div>- </div>- )}+ )}+ </div></PopoverContent></Popover>@@ -1805,6 +2114,7 @@ export function IssueDisplayControls({</DropdownMenuContent></DropdownMenu>)}+</div>);}diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsxindex 0b18f6799f..5dbe961e35 100644--- a/packages/views/issues/components/issues-page.test.tsx+++ b/packages/views/issues/components/issues-page.test.tsx@@ -387,11 +387,12 @@ let mockScope = "all";vi.mock("@multica/core/issues/stores/issues-scope-store", () => ({useIssuesScopeStore: Object.assign((selector?: any) => {- const state = { scope: mockScope, setScope: vi.fn() };+ const state = { scopes: { issues: mockScope }, setScope: vi.fn() };return selector ? selector(state) : state;},- { getState: () => ({ scope: mockScope, setScope: vi.fn() }) },+ { getState: () => ({ scopes: { issues: mockScope }, setScope: vi.fn() }) },),+ useIssuesScope: () => mockScope,}));vi.mock("@multica/core/issues/stores/selection-store", () => ({@@ -455,6 +456,7 @@ vi.mock("@dnd-kit/core", () => {vi.mock("@dnd-kit/sortable", () => ({SortableContext: ({ children }: any) => children,verticalListSortingStrategy: {},+ horizontalListSortingStrategy: {},arrayMove: vi.fn(),useSortable: () => ({attributes: {},@@ -467,7 +469,10 @@ vi.mock("@dnd-kit/sortable", () => ({}));vi.mock("@dnd-kit/utilities", () => ({- CSS: { Transform: { toString: () => undefined } },+ CSS: {+ Transform: { toString: () => undefined },+ Translate: { toString: () => undefined },+ },}));// Mock @base-ui/react/accordion (used by ListView)diff --git a/packages/views/issues/components/issues-page.tsx b/packages/views/issues/components/issues-page.tsxindex 26d94b4168..4a8b2f686b 100644--- a/packages/views/issues/components/issues-page.tsx+++ b/packages/views/issues/components/issues-page.tsx@@ -7,7 +7,7 @@ import type {IssueTableFacetsResponse,WorkingAgentSummary,} from "@multica/core/types";-import { useIssuesScopeStore } from "@multica/core/issues/stores/issues-scope-store";+import { useIssuesScope } from "@multica/core/issues/stores/issues-scope-store";import { useViewStore } from "@multica/core/issues/stores/view-store-context";import { PageHeader } from "../../layout/page-header";import { useT } from "../../i18n";@@ -48,7 +48,7 @@ function IssuesSurfaceHeader({export function IssuesPage() {const { t } = useT("issues");- const scope = useIssuesScopeStore((s) => s.scope);+ const scope = useIssuesScope("issues");return (<div className="flex flex-1 min-h-0 flex-col">diff --git a/packages/views/issues/components/manage-views-dialog.tsx b/packages/views/issues/components/manage-views-dialog.tsxnew file mode 100644index 0000000000..4dd016436a--- /dev/null+++ b/packages/views/issues/components/manage-views-dialog.tsx@@ -0,0 +1,259 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import {+ DndContext,+ PointerSensor,+ closestCenter,+ useSensor,+ useSensors,+ type DragEndEvent,+} from "@dnd-kit/core";+import {+ SortableContext,+ arrayMove,+ useSortable,+ verticalListSortingStrategy,+} from "@dnd-kit/sortable";+import { CSS } from "@dnd-kit/utilities";+import { restrictToVerticalAxis } from "@dnd-kit/modifiers";+import { GripVertical, Layers, Pencil, Trash2 } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { Switch } from "@multica/ui/components/ui/switch";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { cn } from "@multica/ui/lib/utils";+import type { IssueView } from "@multica/core/api/schemas";+import {+ DeleteViewConfirm,+ type ViewBarItem,+} from "./view-bar-popover";+import { useT } from "../../i18n";++/** One row in the manager: a built-in tab or a saved view. */+/** The vertical-locked row drag has no DragOverlay under the pointer, so+ * the grabbing cursor is promoted to the document for the drag's duration+ * (see the `data-dnd-dragging` contract in ui/styles/base.css). */+function setDndCursor(on: boolean) {+ if (on) document.documentElement.dataset.dndDragging = "true";+ else delete document.documentElement.dataset.dndDragging;+}++function SortableRow({+ item,+ hidden,+ anchor,+ onToggleHidden,+ onEdit,+ onDelete,+}: {+ item: ViewBarItem;+ hidden: boolean;+ /** The anchor built-in cannot be hidden — its switch is disabled. */+ anchor: boolean;+ onToggleHidden: () => void;+ onEdit?: () => void;+ onDelete?: () => void;+}) {+ const { t } = useT("issues");+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } =+ useSortable({ id: item.barItemId });++ return (+ <div+ ref={setNodeRef}+ style={{ transform: CSS.Translate.toString(transform), transition }}+ className={cn(+ "flex min-w-0 items-center gap-2 rounded-md px-2 py-1.5",+ isDragging && "z-10 bg-accent opacity-80",+ )}+ >+ <button+ type="button"+ {...attributes}+ {...listeners}+ aria-label={t(($) => $.view_bar.drag_handle)}+ className={cn(+ "cursor-grab active:cursor-grabbing text-faint-foreground hover:text-muted-foreground",+ isDragging && "cursor-grabbing",+ )}+ >+ <GripVertical className="size-3.5" />+ </button>+ <span className="min-w-0 flex-1 truncate text-body">+ {item.label}+ {item.kind === "builtin" && (+ <span className="ml-1.5 text-caption text-muted-foreground">+ {t(($) => $.view_bar.builtin_tag)}+ </span>+ )}+ </span>+ {item.kind === "view" && item.canManage && (+ <span className="flex items-center gap-0.5">+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t(($) => $.view_selector.edit)}+ onClick={onEdit}+ >+ <Pencil className="size-3.5" />+ </Button>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t(($) => $.view_bar.delete)}+ onClick={onDelete}+ className="text-muted-foreground hover:text-destructive"+ >+ <Trash2 className="size-3.5" />+ </Button>+ </span>+ )}+ <Switch+ size="sm"+ checked={!hidden}+ disabled={anchor}+ aria-label={t(($) => $.view_bar.visible_toggle)}+ onCheckedChange={onToggleHidden}+ />+ </div>+ );+}++/**+ * Central manager for one surface's view bar: order (drag), visibility+ * (switch), edit/delete for manageable saved views. Order and visibility+ * write the per-user preference document optimistically; edit/delete+ * delegate to the host (they need the save dialog / delete mutation wired+ * to the surface's state).+ */+export function ManageViewsDialog({+ open,+ onOpenChange,+ items,+ hiddenSet,+ anchorId,+ onReorder,+ onToggleHidden,+ onEditView,+ onDeleteView,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** Full ordered list (built-ins + views), pre-composed by the host. */+ items: ViewBarItem[];+ hiddenSet: Set<string>;+ anchorId: string;+ onReorder: (orderedIds: string[]) => void;+ onToggleHidden: (barItemId: string, hidden: boolean) => void;+ onEditView: (view: IssueView) => void;+ onDeleteView: (view: IssueView) => Promise<void>;+}) {+ const { t } = useT("issues");+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),+ );+ // Local order during a drag session so rows follow the pointer without a+ // server round-trip per pixel; committed (one PUT) on drop.+ const [localOrder, setLocalOrder] = useState<string[] | null>(null);+ // If the dialog unmounts mid-drag (close on Escape, view deleted under+ // us), dnd-kit fires no cancel — clear the document cursor ourselves.+ useEffect(() => () => setDndCursor(false), []);+ useEffect(() => {+ if (!open) setLocalOrder(null);+ }, [open]);++ const orderedItems = useMemo(() => {+ if (!localOrder) return items;+ const byId = new Map(items.map((item) => [item.barItemId, item]));+ const next: ViewBarItem[] = [];+ for (const id of localOrder) {+ const item = byId.get(id);+ if (item) {+ next.push(item);+ byId.delete(id);+ }+ }+ return [...next, ...byId.values()];+ }, [items, localOrder]);++ const [deleting, setDeleting] = useState<IssueView | null>(null);++ const handleDragEnd = (event: DragEndEvent) => {+ const { active, over } = event;+ if (!over || active.id === over.id) return;+ const ids = orderedItems.map((item) => item.barItemId);+ const from = ids.indexOf(String(active.id));+ const to = ids.indexOf(String(over.id));+ if (from < 0 || to < 0) return;+ const next = arrayMove(ids, from, to);+ setLocalOrder(next);+ onReorder(next);+ };++ return (+ <>+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-1.5">+ <Layers className="size-4" />+ {t(($) => $.view_bar.manage_title)}+ </DialogTitle>+ <DialogDescription>{t(($) => $.view_bar.manage_hint)}</DialogDescription>+ </DialogHeader>+ <div className="-mx-2 min-w-0 overflow-hidden">+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ // Rows only ever swap vertically — same constraint the table+ // header puts on column reordering, rotated 90°. Horizontal+ // auto-scroll is likewise an axis this gesture cannot act on.+ modifiers={[restrictToVerticalAxis]}+ autoScroll={{ threshold: { x: 0, y: 0.15 } }}+ onDragStart={() => setDndCursor(true)}+ onDragCancel={() => setDndCursor(false)}+ onDragEnd={(event) => {+ setDndCursor(false);+ handleDragEnd(event);+ }}+ >+ <SortableContext+ items={orderedItems.map((item) => item.barItemId)}+ strategy={verticalListSortingStrategy}+ >+ {orderedItems.map((item) => (+ <SortableRow+ key={item.barItemId}+ item={item}+ hidden={hiddenSet.has(item.barItemId)}+ anchor={item.barItemId === anchorId}+ onToggleHidden={() =>+ onToggleHidden(item.barItemId, !hiddenSet.has(item.barItemId))+ }+ onEdit={item.view ? () => onEditView(item.view!) : undefined}+ onDelete={item.view ? () => setDeleting(item.view!) : undefined}+ />+ ))}+ </SortableContext>+ </DndContext>+ </div>+ </DialogContent>+ </Dialog>++ <DeleteViewConfirm+ view={deleting}+ onOpenChange={(open) => {+ if (!open) setDeleting(null);+ }}+ onConfirm={onDeleteView}+ />+ </>+ );+}+diff --git a/packages/views/issues/components/priority-icon.tsx b/packages/views/issues/components/priority-icon.tsxindex 63774a6bab..0db110d17b 100644--- a/packages/views/issues/components/priority-icon.tsx+++ b/packages/views/issues/components/priority-icon.tsx@@ -1,6 +1,14 @@import type { IssuePriority } from "@multica/core/types";import { PRIORITY_CONFIG } from "@multica/core/issues/config";+/**+ * Priority glyphs, two families on purpose:+ * - low / medium / high share one three-bar frame (1 / 2 / 3 bars filled,+ * the rest faint) so severity reads as a fill level at a glance;+ * - urgent breaks out of the scale entirely — a filled badge with an+ * exclamation mark — because it is an interrupt, not "even higher".+ * - none stays a quiet dash.+ */export function PriorityIcon({priority,className = "",@@ -12,8 +20,8 @@ export function PriorityIcon({}) {const cfg = priority in PRIORITY_CONFIG ? PRIORITY_CONFIG[priority as IssuePriority] : null;- // "none" — simple horizontal dashes- if (!cfg || cfg.bars === 0) {+ // "none" — simple horizontal dash+ if (!cfg || priority === "none") {return (<svgviewBox="0 0 16 16"@@ -28,32 +36,48 @@ export function PriorityIcon({);}- const isUrgent = priority === "urgent";+ if (priority === "urgent") {+ return (+ <svg+ viewBox="0 0 16 16"+ className={`h-3.5 w-3.5 ${inheritColor ? "" : cfg.color} shrink-0 ${className}`}+ fill="none"+ >+ <rect x="2" y="2" width="12" height="12" rx="3" fill="currentColor" />+ <line+ x1="8"+ y1="5"+ x2="8"+ y2="8.6"+ stroke="var(--background, #fff)"+ strokeWidth="1.7"+ strokeLinecap="round"+ />+ <circle cx="8" cy="11" r="0.95" fill="var(--background, #fff)" />+ </svg>+ );+ }+ // low / medium / high — a constant three-bar frame; severity = fill count.+ const filled = Math.min(cfg.bars, 3);+ const BAR_HEIGHTS = [6, 9, 12];return (<svgviewBox="0 0 16 16"className={`h-3.5 w-3.5 ${inheritColor ? "" : cfg.color} shrink-0 ${className}`}fill="currentColor"- style={isUrgent ? { animation: "priority-pulse 2s ease-in-out infinite" } : undefined}>- {[0, 1, 2, 3].map((i) => (+ {BAR_HEIGHTS.map((height, i) => (<rectkey={i}- x={1 + i * 4}- width="3"- rx="0.5"- style={{- y: 12 - (i + 1) * 3,- height: (i + 1) * 3,- opacity: i < cfg.bars ? 1 : 0.2,- transition: "y 0.2s ease, height 0.2s ease, opacity 0.2s ease",- }}+ x={2 + i * 4.25}+ y={14 - height}+ width="3.5"+ height={height}+ rx="1"+ opacity={i < filled ? 1 : 0.35}/>))}- {isUrgent && (- <style>{`@keyframes priority-pulse{0%,100%{transform:scale(1)}50%{transform:scale(1.08)}}`}</style>- )}</svg>);}diff --git a/packages/views/issues/components/save-view-dialog.tsx b/packages/views/issues/components/save-view-dialog.tsxnew file mode 100644index 0000000000..3df3d7c45a--- /dev/null+++ b/packages/views/issues/components/save-view-dialog.tsx@@ -0,0 +1,787 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import { createStore, type StoreApi } from "zustand/vanilla";+import { useQuery } from "@tanstack/react-query";+import { ChevronRight, Plus } from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import { Input } from "@multica/ui/components/ui/input";+import { Label } from "@multica/ui/components/ui/label";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from "@multica/ui/components/ui/collapsible";+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@multica/ui/components/ui/select";+import { Toggle } from "@multica/ui/components/ui/toggle";+import { toast } from "sonner";+import { useWorkspaceId } from "@multica/core/hooks";+import { useCreateIssueView, useUpdateIssueView } from "@multica/core/issue-views/mutations";+import {+ issueViewContainerKey,+ useActiveIssueViewStore,+} from "@multica/core/issue-views/active-view-store";+import { ApiError } from "@multica/core/api/client";+import type { CreateIssueViewRequest, IssueView } from "@multica/core/api/schemas";+import { projectListOptions } from "@multica/core/projects/queries";+import { propertyListOptions } from "@multica/core/properties";+import {+ viewStoreSlice,+ viewStorePersistOptions,+ mergeViewStatePersisted,+ GROUPING_OPTIONS,+ SORT_OPTIONS,+ SWIMLANE_GROUPINGS,+ CARD_PROPERTY_OPTIONS,+ type IssueGrouping,+ type IssueViewState,+ type SortField,+ type SwimlaneGrouping,+ type ViewMode,+} from "@multica/core/issues/stores/view-store";+import {+ ViewStoreProvider,+ useViewStore,+ useViewStoreApi,+} from "@multica/core/issues/stores/view-store-context";+import { IssueFilterMenu } from "./issues-header";+import { FilterChipList } from "./filter-chips-bar";+import { useT } from "../../i18n";++/** Where the view being saved will live. Decided by the hosting surface, not+ * by the user — the dialog only explains it. */+export type SaveViewScope =+ | { kind: "workspace"; actorKind?: "all" | "members" | "agents" }+ | { kind: "my"; variant: "any" | "assigned" | "created" | "involved" }+ | {+ kind: "project";+ projectId: string;+ actorKind?: "all" | "members" | "agents";+ };++const WORKSPACE_VARIANTS = ["all", "members", "agents"] as const;+const MY_VARIANTS = ["any", "assigned", "created", "involved"] as const;+type ScopeVariantValue =+ | (typeof WORKSPACE_VARIANTS)[number]+ | (typeof MY_VARIANTS)[number];++const VARIANT_LABEL_KEY = {+ all: "variant_all",+ members: "variant_members",+ agents: "variant_agents",+ any: "variant_my_any",+ assigned: "variant_my_assigned",+ created: "variant_my_created",+ involved: "variant_my_involved",+} as const;++const MY_VARIANT_HINT_KEY = {+ any: "hint_my_any",+ assigned: "hint_my_assigned",+ created: "hint_my_created",+ involved: "hint_my_involved",+} as const;++const LAYOUT_LABEL_KEY = {+ list: "list",+ board: "board",+ table: "table",+ swimlane: "swimlane",+ gantt: "gantt",+} as const;++const GROUPING_LABEL_KEY = {+ status: "group_status",+ assignee: "group_assignee",+} as const;++const SWIMLANE_LABEL_KEY = {+ parent: "group_parent",+ project: "group_project",+ assignee: "group_assignee",+} as const;++const SORT_LABEL_KEY = {+ position: "sort_manual",+ status: "sort_status",+ priority: "sort_priority",+ start_date: "sort_start_date",+ due_date: "sort_due_date",+ created_at: "sort_created",+ updated_at: "sort_updated",+ title: "sort_title",+} as const;++const CARD_PROPERTY_LABEL_KEY = {+ priority: "card_priority",+ description: "card_description",+ assignee: "card_assignee",+ startDate: "card_start_date",+ dueDate: "card_due_date",+ project: "card_project",+ labels: "card_labels",+ childProgress: "card_child_progress",+} as const;++/** Data-only snapshot: `partialize` strips the store's bound actions (which+ * would otherwise write back to the LIVE store) and the deliberately+ * unsaved fields (date filter, agents-working toggle). */+const snapshotState = viewStorePersistOptions("save-view-draft").partialize;++const ROW_LABEL = "w-16 shrink-0 text-caption text-muted-foreground";++/** Filter row + layout row + collapsible display defaults, all bound to the+ * DRAFT store via the surrounding provider. */+function DraftDefinitionFields() {+ const { t } = useT("issues");+ const wsId = useWorkspaceId();+ const viewMode = useViewStore((s) => s.viewMode);+ const grouping = useViewStore((s) => s.grouping);+ const swimlaneGrouping = useViewStore((s) => s.swimlaneGrouping);+ const sortBy = useViewStore((s) => s.sortBy);+ const cardProperties = useViewStore((s) => s.cardProperties);+ const cardPropertyIds = useViewStore((s) => s.cardPropertyIds);+ const act = useViewStoreApi().getState();++ const { data: workspaceProperties = [] } = useQuery(propertyListOptions(wsId));+ const groupableProperties = useMemo(+ () => workspaceProperties.filter((p) => p.type === "select"),+ [workspaceProperties],+ );+ const sortableProperties = useMemo(+ () => workspaceProperties.filter((p) => p.type === "number" || p.type === "date"),+ [workspaceProperties],+ );+ const propertyName = (key: string) =>+ workspaceProperties.find((p) => `property:${p.id}` === key)?.name ??+ t(($) => $.save_view.custom_property);++ const layoutLabel = t(($) => $.view[LAYOUT_LABEL_KEY[viewMode]]);+ const groupingLabel =+ viewMode === "board"+ ? grouping in GROUPING_LABEL_KEY+ ? t(($) => $.display[GROUPING_LABEL_KEY[grouping as keyof typeof GROUPING_LABEL_KEY]])+ : propertyName(grouping)+ : viewMode === "swimlane"+ ? t(($) => $.display[SWIMLANE_LABEL_KEY[swimlaneGrouping]])+ : null;+ const sortLabel =+ sortBy in SORT_LABEL_KEY+ ? t(($) => $.display[SORT_LABEL_KEY[sortBy as keyof typeof SORT_LABEL_KEY]])+ : propertyName(sortBy);+ const displaySummary = [layoutLabel, groupingLabel, sortLabel].filter(Boolean).join(" · ");++ return (+ <>+ {/* Filters: bare chips + the full filter menu behind a ghost chip. */}+ <div className="flex items-start gap-3">+ <Label className={`${ROW_LABEL} pt-1`}>+ {t(($) => $.save_view.filters_label)}+ </Label>+ <div className="min-w-0 flex-1">+ <FilterChipList+ trailing={+ <IssueFilterMenu+ freezeAnchor+ trigger={+ <button+ type="button"+ className="flex h-6 items-center gap-1 rounded-md border border-dashed border-border px-2 text-caption text-muted-foreground hover:border-foreground/30 hover:bg-muted/60 hover:text-foreground"+ >+ <Plus className="size-3" />+ {t(($) => $.save_view.add_filter)}+ </button>+ }+ />+ }+ />+ </div>+ </div>++ {/* Display defaults: captured already; expandable for fine-tuning. */}+ <Collapsible>+ <CollapsibleTrigger className="group flex w-fit max-w-full items-center gap-1.5 rounded-md -mx-1 px-1 py-1 text-left hover:bg-muted/60">+ <ChevronRight className="size-3.5 shrink-0 text-muted-foreground transition-transform group-data-[panel-open]:rotate-90" />+ <span className="text-caption font-medium">+ {t(($) => $.save_view.display_defaults)}+ </span>+ <span className="min-w-0 truncate text-caption text-muted-foreground">+ {displaySummary}+ </span>+ </CollapsibleTrigger>+ <CollapsibleContent className="h-(--collapsible-panel-height) overflow-hidden transition-[height] duration-200 ease-out data-starting-style:h-0 data-ending-style:h-0">+ <div className="space-y-3 pt-2 pl-5">+ <div className="flex items-center gap-3">+ <Label className={ROW_LABEL}>{t(($) => $.save_view.layout_label)}</Label>+ <Select+ items={(["list", "board", "table", "swimlane"] as const).map((mode) => ({+ value: mode as string,+ label: t(($) => $.view[LAYOUT_LABEL_KEY[mode]]),+ }))}+ value={viewMode}+ onValueChange={(v) => {+ if (v) act.setViewMode(v as ViewMode);+ }}+ >+ <SelectTrigger size="sm" className="w-64" aria-label={t(($) => $.save_view.layout_label)}>+ <SelectValue>{layoutLabel}</SelectValue>+ </SelectTrigger>+ <SelectContent align="start">+ <SelectGroup>+ {(["list", "board", "table", "swimlane"] as const).map((mode) => (+ <SelectItem key={mode} value={mode}>+ {t(($) => $.view[LAYOUT_LABEL_KEY[mode]])}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </div>+ {viewMode === "board" && (+ <div className="flex items-center gap-3">+ <Label className={ROW_LABEL}>+ {t(($) => $.display.grouping_section)}+ </Label>+ <Select+ items={[+ ...GROUPING_OPTIONS.map((opt) => ({+ value: opt.value as string,+ label: t(($) => $.display[GROUPING_LABEL_KEY[opt.value]]),+ })),+ ...groupableProperties.map((p) => ({+ value: `property:${p.id}`,+ label: p.name,+ })),+ ]}+ value={grouping}+ onValueChange={(v) => {+ if (v) act.setGrouping(v as IssueGrouping);+ }}+ >+ <SelectTrigger size="sm" className="w-64" aria-label={t(($) => $.display.grouping_section)}>+ <SelectValue>+ {grouping in GROUPING_LABEL_KEY+ ? t(($) => $.display[GROUPING_LABEL_KEY[grouping as keyof typeof GROUPING_LABEL_KEY]])+ : propertyName(grouping)}+ </SelectValue>+ </SelectTrigger>+ <SelectContent align="start">+ <SelectGroup>+ {GROUPING_OPTIONS.map((opt) => (+ <SelectItem key={opt.value} value={opt.value}>+ {t(($) => $.display[GROUPING_LABEL_KEY[opt.value]])}+ </SelectItem>+ ))}+ {groupableProperties.map((property) => (+ <SelectItem key={property.id} value={`property:${property.id}`}>+ {property.name}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </div>+ )}+ {viewMode === "swimlane" && (+ <div className="flex items-center gap-3">+ <Label className={ROW_LABEL}>+ {t(($) => $.display.grouping_section)}+ </Label>+ <Select+ items={SWIMLANE_GROUPINGS.map((value) => ({+ value: value as string,+ label: t(($) => $.display[SWIMLANE_LABEL_KEY[value]]),+ }))}+ value={swimlaneGrouping}+ onValueChange={(v) => {+ if (v) act.setSwimlaneGrouping(v as SwimlaneGrouping);+ }}+ >+ <SelectTrigger size="sm" className="w-64" aria-label={t(($) => $.display.grouping_section)}>+ <SelectValue>+ {t(($) => $.display[SWIMLANE_LABEL_KEY[swimlaneGrouping]])}+ </SelectValue>+ </SelectTrigger>+ <SelectContent align="start">+ <SelectGroup>+ {SWIMLANE_GROUPINGS.map((value) => (+ <SelectItem key={value} value={value}>+ {t(($) => $.display[SWIMLANE_LABEL_KEY[value]])}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </div>+ )}+ <div className="flex items-center gap-3">+ <Label className={ROW_LABEL}>+ {t(($) => $.display.ordering_section)}+ </Label>+ <Select+ items={[+ ...SORT_OPTIONS.map((opt) => ({+ value: opt.value as string,+ label: t(($) => $.display[SORT_LABEL_KEY[opt.value as keyof typeof SORT_LABEL_KEY]]),+ })),+ ...sortableProperties.map((p) => ({+ value: `property:${p.id}`,+ label: p.name,+ })),+ ]}+ value={sortBy}+ onValueChange={(v) => {+ if (v) act.setSortBy(v as SortField);+ }}+ >+ <SelectTrigger size="sm" className="w-64" aria-label={t(($) => $.display.ordering_section)}>+ <SelectValue>{sortLabel}</SelectValue>+ </SelectTrigger>+ <SelectContent align="start">+ <SelectGroup>+ {SORT_OPTIONS.map((opt) => (+ <SelectItem key={opt.value} value={opt.value}>+ {t(($) => $.display[SORT_LABEL_KEY[opt.value as keyof typeof SORT_LABEL_KEY]])}+ </SelectItem>+ ))}+ {sortableProperties.map((property) => (+ <SelectItem key={property.id} value={`property:${property.id}`}>+ {property.name}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </div>+ {viewMode !== "table" && (+ <div className="flex items-start gap-3">+ <Label className={`${ROW_LABEL} pt-1`}>+ {t(($) => $.display.card_properties_section)}+ </Label>+ <div className="flex min-w-0 flex-1 flex-wrap gap-1">+ {CARD_PROPERTY_OPTIONS.map((opt) => (+ <Toggle+ key={opt.key}+ size="sm"+ variant="outline"+ pressed={cardProperties[opt.key]}+ onPressedChange={() => act.toggleCardProperty(opt.key)}+ className="h-6 rounded-md px-2 text-caption text-muted-foreground hover:bg-muted/60 aria-pressed:border-transparent aria-pressed:bg-accent aria-pressed:text-accent-foreground aria-pressed:hover:bg-accent/80"+ >+ {t(($) => $.display[CARD_PROPERTY_LABEL_KEY[opt.key]])}+ </Toggle>+ ))}+ {workspaceProperties.map((property) => (+ <Toggle+ key={property.id}+ size="sm"+ variant="outline"+ pressed={cardPropertyIds.includes(property.id)}+ onPressedChange={() => act.toggleCardPropertyId(property.id)}+ className="h-6 max-w-40 rounded-md px-2 text-caption text-muted-foreground hover:bg-muted/60 aria-pressed:border-transparent aria-pressed:bg-accent aria-pressed:text-accent-foreground aria-pressed:hover:bg-accent/80"+ >+ <span className="truncate">{property.name}</span>+ </Toggle>+ ))}+ </div>+ </div>+ )}+ <p className="text-caption text-faint-foreground">+ {t(($) => $.save_view.default_hint)}+ </p>+ </div>+ </CollapsibleContent>+ </Collapsible>+ </>+ );+}++/**+ * Save the current surface state as a view. Uncontrolled: opening the dialog+ * snapshots the live panel state into a throwaway store, the embedded fields+ * edit THAT copy, and the page underneath never notices. Save reads the+ * copy; closing discards it. Prints until the API exists.+ */+export function SaveViewDialog({+ open,+ onOpenChange,+ scope,+ editView = null,+ seedFromDefinition = false,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ scope: SaveViewScope;+ /** Edit mode: same dialog, prefilled from this view; confirm PATCHes it+ * (with optimistic-concurrency 409 handling) instead of creating. */+ editView?: IssueView | null;+ /** Manager-initiated edits seed from the view's own definition (the user+ * may not have it open); in-view edits keep seeding from the live panel+ * so the user's current additions are part of the draft. */+ seedFromDefinition?: boolean;+}) {+ const { t } = useT("issues");+ const wsId = useWorkspaceId();+ const liveStore = useViewStoreApi();+ const createView = useCreateIssueView(wsId);+ const setActiveInStore = useActiveIssueViewStore((s) => s.setActive);+ const updateView = useUpdateIssueView(wsId);++ const [name, setName] = useState("");+ const [nameError, setNameError] = useState(false);+ const nameInputRef = useRef<HTMLInputElement>(null);+ const [visibility, setVisibility] = useState<"private" | "workspace">("private");+ // Scope-layer variant (the "which tab" axis). Defaults to the tab the+ // user stood on when saving; switchable here because the dialog IS the+ // view-definition editor. scope_type itself never switches.+ const [variant, setVariant] = useState<ScopeVariantValue>("all");+ const [draftStore, setDraftStore] = useState<StoreApi<IssueViewState> | null>(null);++ // Fresh draft per open: seed a private store instance from the live+ // panel's data fields, then let the embedded controls mutate it freely.+ useEffect(() => {+ if (!open) {+ setDraftStore(null);+ return;+ }+ const store = createStore<IssueViewState>()(viewStoreSlice);+ if (seedFromDefinition && editView) {+ // Same sanitizer the surface seed uses — the definition is a server+ // blob, never trusted wholesale.+ const defaults = viewStoreSlice(store.setState);+ store.setState(+ mergeViewStatePersisted({ ...editView.query, ...editView.display }, defaults),+ true,+ );+ } else {+ store.setState(snapshotState(liveStore.getState()));+ }+ setDraftStore(store);+ setName(editView?.name ?? "");+ setNameError(false);+ setVisibility(editView?.visibility === "workspace" ? "workspace" : "private");+ if (scope.kind === "workspace" || scope.kind === "project") {+ const fromEdit = editView?.scope_variant;+ setVariant(+ fromEdit === "members" || fromEdit === "agents"+ ? fromEdit+ : editView+ ? "all"+ : (scope.actorKind ?? "all"),+ );+ } else if (scope.kind === "my") {+ const fromEdit = editView?.scope_variant;+ setVariant(+ fromEdit && (MY_VARIANTS as readonly string[]).includes(fromEdit)+ ? (fromEdit as ScopeVariantValue)+ : scope.variant,+ );+ }+ }, [open, liveStore, editView, seedFromDefinition, scope]);++ const { data: projects = [] } = useQuery({+ ...projectListOptions(wsId),+ enabled: open && scope.kind === "project",+ });+ const projectTitle =+ scope.kind === "project"+ ? projects.find((p) => p.id === scope.projectId)?.title ?? ""+ : "";++ const scopeHint =+ scope.kind === "workspace"+ ? variant === "members"+ ? t(($) => $.save_view.hint_workspace_members)+ : variant === "agents"+ ? t(($) => $.save_view.hint_workspace_agents)+ : t(($) => $.save_view.hint_workspace)+ : scope.kind === "my"+ ? t(($) => $.save_view[+ MY_VARIANT_HINT_KEY[+ (MY_VARIANTS as readonly string[]).includes(variant)+ ? (variant as (typeof MY_VARIANTS)[number])+ : scope.variant+ ]+ ])+ : variant === "members"+ ? t(($) => $.save_view.hint_project_members, { title: projectTitle })+ : variant === "agents"+ ? t(($) => $.save_view.hint_project_agents, { title: projectTitle })+ : t(($) => $.save_view.hint_project, { title: projectTitle });++ const create = () => {+ if (!draftStore) return;+ if (!name.trim()) {+ setNameError(true);+ nameInputRef.current?.focus();+ return;+ }+ const state = draftStore.getState();+ const payload = {+ name: name.trim(),+ visibility: scope.kind === "my" ? ("private" as const) : visibility,+ scope_type: scope.kind,+ scope_id: scope.kind === "project" ? scope.projectId : null,+ scope_variant:+ scope.kind === "my"+ ? ((MY_VARIANTS as readonly string[]).includes(variant)+ ? (variant as CreateIssueViewRequest["scope_variant"])+ : scope.variant)+ : variant === "members" || variant === "agents"+ ? variant+ : null,+ definition_version: 1,+ query: {+ statusFilters: state.statusFilters,+ priorityFilters: state.priorityFilters,+ assigneeFilters: state.assigneeFilters,+ includeNoAssignee: state.includeNoAssignee,+ creatorFilters: state.creatorFilters,+ projectFilters: state.projectFilters,+ includeNoProject: state.includeNoProject,+ labelFilters: state.labelFilters,+ propertyFilters: state.propertyFilters,+ },+ display: {+ // Personal display preference (like layout): saved as the view's+ // first-open default, freely adjustable per user afterwards.+ showSubIssues: state.showSubIssues,+ viewMode: state.viewMode,+ grouping: state.grouping,+ sortBy: state.sortBy,+ sortDirection: state.sortDirection,+ cardProperties: state.cardProperties,+ cardPropertyIds: state.cardPropertyIds,+ tableColumns: state.tableColumns,+ tableGrouping: state.tableGrouping,+ tableHierarchy: state.tableHierarchy,+ tableCalculation: state.tableCalculation,+ swimlaneGrouping: state.swimlaneGrouping,+ ganttZoom: state.ganttZoom,+ ganttShowCompleted: state.ganttShowCompleted,+ },+ };+ if (editView) {+ updateView.mutate(+ {+ id: editView.id,+ name: payload.name,+ visibility: payload.visibility,+ scope_variant: payload.scope_variant ?? null,+ query: payload.query,+ display: payload.display,+ expected_revision: editView.revision,+ },+ {+ onSuccess: () => {+ toast.success(t(($) => $.save_view.toast_updated));+ onOpenChange(false);+ },+ onError: (err) => {+ if (err instanceof ApiError && err.status === 409) {+ toast.error(t(($) => $.save_view.toast_conflict));+ return;+ }+ toast.error(+ err instanceof Error ? err.message : t(($) => $.save_view.toast_failed),+ );+ },+ },+ );+ return;+ }+ createView.mutate(payload, {+ onSuccess: (created) => {+ toast.success(t(($) => $.save_view.toast_created));+ // The view you just saved is the one you want to be looking at:+ // activate it on its surface right away. `created` is null only+ // when the response failed to parse — the list refetch still shows+ // the view, it just doesn't auto-open.+ if (created) {+ setActiveInStore(+ issueViewContainerKey(wsId, {+ scope_type: payload.scope_type,+ scope_id: payload.scope_id,+ }),+ created.id,+ );+ }+ onOpenChange(false);+ },+ onError: (err) => {+ toast.error(+ err instanceof Error ? err.message : t(($) => $.save_view.toast_failed),+ );+ },+ });+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-xl">+ <DialogHeader>+ <DialogTitle>+ {editView+ ? t(($) => $.save_view.edit_title)+ : t(($) => $.save_view.title)}+ </DialogTitle>+ <DialogDescription className="break-words">{scopeHint}</DialogDescription>+ </DialogHeader>++ <div className="space-y-4">+ <div className="flex items-start gap-3">+ <Label className={`${ROW_LABEL} pt-2`} htmlFor="save-view-name">+ {t(($) => $.save_view.name_label)}+ </Label>+ <div className="min-w-0">+ <Input+ id="save-view-name"+ ref={nameInputRef}+ autoFocus+ required+ aria-invalid={nameError || undefined}+ aria-describedby={nameError ? "save-view-name-error" : undefined}+ value={name}+ onChange={(e) => {+ setName(e.target.value);+ if (nameError && e.target.value.trim()) setNameError(false);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") create();+ }}+ maxLength={80}+ placeholder={t(($) => $.save_view.name_placeholder)}+ className="h-8 w-64"+ />+ {nameError && (+ <p+ id="save-view-name-error"+ className="mt-1 text-caption text-destructive animate-in fade-in-0 slide-in-from-top-1 duration-150"+ >+ {t(($) => $.save_view.name_required)}+ </p>+ )}+ </div>+ </div>++ {scope.kind !== "my" && (+ <div className="flex items-center gap-3">+ <Label className={ROW_LABEL}>+ {t(($) => $.save_view.visibility_label)}+ </Label>+ <Select+ items={[+ { value: "private", label: t(($) => $.save_view.visibility_private) },+ { value: "workspace", label: t(($) => $.save_view.visibility_workspace) },+ ]}+ value={visibility}+ onValueChange={(v) => {+ if (v) setVisibility(v as "private" | "workspace");+ }}+ >+ <SelectTrigger size="sm" className="w-64" aria-label={t(($) => $.save_view.visibility_label)}>+ <SelectValue>+ {visibility === "private"+ ? t(($) => $.save_view.visibility_private)+ : t(($) => $.save_view.visibility_workspace)}+ </SelectValue>+ </SelectTrigger>+ <SelectContent align="start">+ <SelectGroup>+ <SelectItem value="private">+ {t(($) => $.save_view.visibility_private)}+ </SelectItem>+ <SelectItem value="workspace">+ {t(($) => $.save_view.visibility_workspace)}+ </SelectItem>+ </SelectGroup>+ </SelectContent>+ </Select>+ </div>+ )}+ {scope.kind === "my" && (+ <p className="pl-19 text-caption text-muted-foreground">+ {t(($) => $.save_view.my_private_note)}+ </p>+ )}++ <div className="flex items-center gap-3">+ <Label className={ROW_LABEL}>+ {scope.kind === "my"+ ? t(($) => $.save_view.scope_label_my)+ : t(($) => $.save_view.scope_label_workspace)}+ </Label>+ <Select+ items={(scope.kind === "my"+ ? MY_VARIANTS+ : WORKSPACE_VARIANTS+ ).map((v) => ({+ value: v as string,+ label: t(($) => $.save_view[VARIANT_LABEL_KEY[v]]),+ }))}+ value={variant}+ onValueChange={(v) => {+ if (v) setVariant(v as ScopeVariantValue);+ }}+ >+ <SelectTrigger size="sm" className="w-64" aria-label={+ scope.kind === "my"+ ? t(($) => $.save_view.scope_label_my)+ : t(($) => $.save_view.scope_label_workspace)+ }>+ <SelectValue>+ {t(($) => $.save_view[VARIANT_LABEL_KEY[variant]])}+ </SelectValue>+ </SelectTrigger>+ <SelectContent align="start">+ <SelectGroup>+ {(scope.kind === "my" ? MY_VARIANTS : WORKSPACE_VARIANTS).map((v) => (+ <SelectItem key={v} value={v}>+ {t(($) => $.save_view[VARIANT_LABEL_KEY[v]])}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </div>++ {draftStore && (+ <ViewStoreProvider store={draftStore}>+ <DraftDefinitionFields />+ </ViewStoreProvider>+ )}+ </div>++ <DialogFooter>+ <Button variant="ghost" size="sm" onClick={() => onOpenChange(false)}>+ {t(($) => $.save_view.cancel)}+ </Button>+ <Button+ size="sm"+ onClick={create}+ disabled={createView.isPending || updateView.isPending}+ >+ {editView+ ? t(($) => $.save_view.update)+ : t(($) => $.save_view.create)}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/views/issues/components/swimlane-view.test.tsx b/packages/views/issues/components/swimlane-view.test.tsxindex 9ccf0c8da4..3a42989715 100644--- a/packages/views/issues/components/swimlane-view.test.tsx+++ b/packages/views/issues/components/swimlane-view.test.tsx@@ -122,27 +122,6 @@ vi.mock("@multica/core/issues/config", () => ({},}));-// Default mock returns hasMore=false so the load-more sentinels render-// as no-op divs and don't pull IntersectionObserver into JSDOM.-const mockLoadMore = vi.fn();-const useLoadMoreByStatusMock = vi.fn(- (_status: string, _opts?: unknown, _sort?: unknown) => ({- total: 0,- loaded: 0,- hasMore: false,- isLoading: false,- loadMore: mockLoadMore,- }),-);-vi.mock("@multica/core/issues/mutations", async (importOriginal) => {- const actual = await importOriginal<typeof import("@multica/core/issues/mutations")>();- return {- ...actual,- useLoadMoreByStatus: (status: string, opts?: unknown, sort?: unknown) =>- useLoadMoreByStatusMock(status, opts, sort),- };-});-type SwimlaneGroupingMock = "parent" | "project" | "assignee";// Mock view store. The lane order and collapsed-lane fields are mutable@@ -421,13 +400,6 @@ describe("SwimLaneView", () => {mockViewState.agentRunningFilter = false;mockListChildrenByParents.mockResolvedValue({ issues: [] });mockGetAgentTaskSnapshot.mockResolvedValue([]);- useLoadMoreByStatusMock.mockImplementation(() => ({- total: 0,- loaded: 0,- hasMore: false,- isLoading: false,- loadMore: mockLoadMore,- }));});it("renders status columns as headers", () => {diff --git a/packages/views/issues/components/swimlane-view.tsx b/packages/views/issues/components/swimlane-view.tsxindex dbf271378c..f882da90ab 100644--- a/packages/views/issues/components/swimlane-view.tsx+++ b/packages/views/issues/components/swimlane-view.tsx@@ -29,14 +29,14 @@ import type {UpdateIssueRequest,} from "@multica/core/types";import { useViewStore, useViewStoreApi } from "@multica/core/issues/stores/view-store-context";+import { useViewBaseline } from "../surface/view-baseline-context";import { filterIssues, type IssueFilters } from "../utils/filter";import { getMoveAnchors } from "../utils/drag-utils";import type { SwimlaneGrouping } from "@multica/core/issues/stores/view-store";import { useWorkspacePaths } from "@multica/core/paths";import { useWorkspaceId } from "@multica/core/hooks";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";+import { childrenByParentsOptions, issueKeys } from "@multica/core/issues/queries";import {DropdownMenu,DropdownMenuTrigger,@@ -609,9 +609,6 @@ function SwimLaneViewImpl({onMoveIssue,childProgressMap = EMPTY_PROGRESS_MAP,projectMap,- myIssuesScope,- myIssuesFilter,- sort,projectId,onCreateIssue,groupBranches,@@ -636,10 +633,6 @@ function SwimLaneViewImpl({) => 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;onCreateIssue?: (defaults: IssueCreateDefaults) => void;@@ -648,6 +641,7 @@ function SwimLaneViewImpl({const { t } = useT("issues");const paths = useWorkspacePaths();const viewStoreApi = useViewStoreApi();+ const viewBaseline = useViewBaseline();const sortBy = useViewStore((s) => s.sortBy);const sortDirection = useViewStore((s) => s.sortDirection);const swimlaneGrouping = useViewStore((s) => s.swimlaneGrouping);@@ -687,14 +681,6 @@ function SwimLaneViewImpl({const laneSourceIssues = unfilteredIssues ?? issues;- const myIssuesOpts = useMemo(- () =>- myIssuesScope- ? { scope: myIssuesScope, filter: myIssuesFilter ?? {} }- : undefined,- [myIssuesScope, myIssuesFilter],- );-// Re-impose canonical status order (ALL_STATUSES) on whatever the controller// marked visible, so columns — including `cancelled`, ordered last — render// in lifecycle order.@@ -1336,35 +1322,20 @@ function SwimLaneViewImpl({const laneComponents = useMemo(() => ({Footer: () =>- groupBranches?.enabled ? (- groupBranches.hasMoreGroups ? (- <div className="pt-4">- <InfiniteScrollSentinel- onVisible={groupBranches.loadMoreGroups}- loading={groupBranches.isLoadingMoreGroups}- />- </div>- ) : null- ) : (+ groupBranches?.enabled && groupBranches.hasMoreGroups ? (<div className="pt-4">- <SwimLaneLoadMoreRow- sortedStatuses={sortedStatuses}- gridStyle={gridStyle}- myIssuesOpts={myIssuesOpts}- sort={sort}+ <InfiniteScrollSentinel+ onVisible={groupBranches.loadMoreGroups}+ loading={groupBranches.isLoadingMoreGroups}/></div>- ),+ ) : null,}),[groupBranches?.enabled,groupBranches?.hasMoreGroups,groupBranches?.isLoadingMoreGroups,groupBranches?.loadMoreGroups,- sortedStatuses,- gridStyle,- myIssuesOpts,- sort,],);@@ -1454,6 +1425,12 @@ function SwimLaneViewImpl({/><DropdownMenuContent align="end"><DropdownMenuItem+ disabled={viewBaseline?.status.has(status) === true}+ title={+ viewBaseline?.status.has(status) === true+ ? t(($) => $.filters.in_view)+ : undefined+ }onClick={() => viewStoreApi.getState().hideStatus(status)}><EyeOff className="size-3.5" />@@ -1832,44 +1809,6 @@ function SwimLaneHiddenColumnsPanel({);}-function SwimLaneLoadMoreRow({- sortedStatuses,- gridStyle,- myIssuesOpts,- sort,-}: {- sortedStatuses: IssueStatus[];- gridStyle: React.CSSProperties;- myIssuesOpts?: { scope: string; filter: MyIssuesFilter };- sort?: IssueSortParam;-}) {- return (- <div style={gridStyle}>- {sortedStatuses.map((status) => (- <SwimLaneLoadMoreCell- key={status}- status={status}- myIssuesOpts={myIssuesOpts}- sort={sort}- />- ))}- </div>- );-}--function SwimLaneLoadMoreCell({- status,- myIssuesOpts,- sort,-}: {- status: IssueStatus;- myIssuesOpts?: { scope: string; filter: MyIssuesFilter };- sort?: IssueSortParam;-}) {- const { loadMore, hasMore, isLoading } = useLoadMoreByStatus(status, myIssuesOpts, sort);- if (!hasMore) return <div />;- return <InfiniteScrollSentinel onVisible={loadMore} loading={isLoading} />;-}/*** Memoized: the surface controller re-renders on loading-flag flips (e.g. adiff --git a/packages/views/issues/components/table-column-picker.test.tsx b/packages/views/issues/components/table-column-picker.test.tsxindex 1907cc4c18..dc84316988 100644--- a/packages/views/issues/components/table-column-picker.test.tsx+++ b/packages/views/issues/components/table-column-picker.test.tsx@@ -39,6 +39,27 @@ vi.mock("@multica/ui/components/ui/dropdown-menu", () => ({{children}</button>),+ DropdownMenuCheckboxItem: ({+ children,+ disabled,+ checked,+ onCheckedChange,+ }: {+ children: ReactNode;+ disabled?: boolean;+ checked?: boolean;+ onCheckedChange?: (checked: boolean) => void;+ }) => (+ <button+ type="button"+ role="menuitemcheckbox"+ aria-checked={checked}+ disabled={disabled}+ onClick={() => onCheckedChange?.(!checked)}+ >+ {children}+ </button>+ ),DropdownMenuLabel: ({ children }: { children: ReactNode }) => (<div>{children}</div>),@@ -81,7 +102,7 @@ describe("TableColumnPicker", () => {renderPicker();await user.click(screen.getByRole("button", { name: "Add column" }));- await user.click(screen.getByRole("menuitem", { name: "Project" }));+ await user.click(screen.getByRole("menuitemcheckbox", { name: "Project" }));expect(toggleTableColumn).toHaveBeenCalledWith("project");});@@ -91,7 +112,9 @@ describe("TableColumnPicker", () => {renderPicker();await user.click(screen.getByRole("button", { name: "Add column" }));- await user.click(screen.getByRole("menuitem", { name: "Environment" }));+ await user.click(+ screen.getByRole("menuitemcheckbox", { name: "Environment" }),+ );expect(toggleTableColumn).toHaveBeenCalledWith("property:property-environment");});diff --git a/packages/views/issues/components/table-view.tsx b/packages/views/issues/components/table-view.tsxindex 86f4b1bad2..edd024130b 100644--- a/packages/views/issues/components/table-view.tsx+++ b/packages/views/issues/components/table-view.tsx@@ -58,6 +58,7 @@ import {DropdownMenu,DropdownMenuContent,DropdownMenuGroup,+ DropdownMenuCheckboxItem,DropdownMenuItem,DropdownMenuLabel,DropdownMenuSeparator,@@ -524,22 +525,14 @@ export function TableColumnPicker({{t(($) => $.table.columns.system_section)}</DropdownMenuLabel>{systemColumns.map((key) => (- <DropdownMenuItem+ <DropdownMenuCheckboxItemkey={key}disabled={key === "title"}- onClick={(event) => {- event.preventDefault();- toggleTableColumn(key);- }}+ checked={selected.has(key)}+ onCheckedChange={() => toggleTableColumn(key)}>- <input- type="checkbox"- checked={selected.has(key)}- readOnly- className="size-3.5 accent-primary"- />{t(($) => $.table.columns[key as ColumnLabelKey])}- </DropdownMenuItem>+ </DropdownMenuCheckboxItem>))}</DropdownMenuGroup>)}@@ -553,21 +546,13 @@ export function TableColumnPicker({{visibleProperties.map((property) => {const key = `property:${property.id}` as const;return (- <DropdownMenuItem+ <DropdownMenuCheckboxItemkey={property.id}- onClick={(event) => {- event.preventDefault();- toggleTableColumn(key);- }}+ checked={selected.has(key)}+ onCheckedChange={() => toggleTableColumn(key)}>- <input- type="checkbox"- checked={selected.has(key)}- readOnly- className="size-3.5 accent-primary"- /><span className="truncate">{property.name}</span>- </DropdownMenuItem>+ </DropdownMenuCheckboxItem>);})}</DropdownMenuGroup>diff --git a/packages/views/issues/components/view-bar-popover.tsx b/packages/views/issues/components/view-bar-popover.tsxnew file mode 100644index 0000000000..c28136e1ac--- /dev/null+++ b/packages/views/issues/components/view-bar-popover.tsx@@ -0,0 +1,306 @@+"use client";++import {+ DndContext,+ PointerSensor,+ closestCenter,+ useSensor,+ useSensors,+ type DragEndEvent,+} from "@dnd-kit/core";+import {+ SortableContext,+ useSortable,+ verticalListSortingStrategy,+} from "@dnd-kit/sortable";+import { CSS } from "@dnd-kit/utilities";+import { restrictToVerticalAxis } from "@dnd-kit/modifiers";+import {+ EyeOff,+ GripVertical,+ MoreHorizontal,+ Pencil,+ Pin,+ PinOff,+ Trash2,+} from "lucide-react";+import { toast } from "sonner";+import { Button } from "@multica/ui/components/ui/button";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@multica/ui/components/ui/alert-dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import { cn } from "@multica/ui/lib/utils";+import type { IssueView } from "@multica/core/api/schemas";+import { useT } from "../../i18n";++/** One entry on the bar: a built-in tab or a saved view. */+export interface ViewBarItem {+ barItemId: string;+ label: string;+ kind: "builtin" | "view";+ view?: IssueView;+ canManage?: boolean;+}++/** The vertical-locked row drag has no DragOverlay under the pointer, so+ * the grabbing cursor is promoted to the document for the drag's duration+ * (see the `data-dnd-dragging` contract in ui/styles/base.css). */+function setDndCursor(on: boolean) {+ if (on) document.documentElement.dataset.dndDragging = "true";+ else delete document.documentElement.dataset.dndDragging;+}++/**+ * The one delete-view confirmation, shared by the manage dialog, the bar's+ * context menu, and the list-panel rows so every entrance carries identical+ * copy and the same "deletes the view only, never issues" contract.+ */+export function DeleteViewConfirm({+ view,+ onOpenChange,+ onConfirm,+}: {+ view: IssueView | null;+ onOpenChange: (open: boolean) => void;+ onConfirm: (view: IssueView) => Promise<void>;+}) {+ const { t } = useT("issues");+ return (+ <AlertDialog open={!!view} onOpenChange={(v) => !v && onOpenChange(false)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t(($) => $.view_bar.delete_title)}</AlertDialogTitle>+ <AlertDialogDescription className="break-words">+ {t(($) => $.view_bar.delete_description, { name: view?.name ?? "" })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{t(($) => $.save_view.cancel)}</AlertDialogCancel>+ <AlertDialogAction+ onClick={() => {+ const target = view;+ onOpenChange(false);+ if (!target) return;+ void onConfirm(target).then(+ () => toast.success(t(($) => $.view_bar.toast_deleted)),+ () => toast.error(t(($) => $.save_view.toast_failed)),+ );+ }}+ >+ {t(($) => $.view_bar.delete)}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}++function SortablePanelRow({+ item,+ active,+ pinned,+ onSelect,+ onEdit,+ onDelete,+ onTogglePin,+ onHide,+}: {+ item: ViewBarItem;+ active: boolean;+ pinned: boolean;+ onSelect: () => void;+ onEdit?: () => void;+ onDelete?: () => void;+ onTogglePin?: () => void;+ onHide?: () => void;+}) {+ const { t } = useT("issues");+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } =+ useSortable({ id: item.barItemId });+ const isView = item.kind === "view";++ return (+ <div+ ref={setNodeRef}+ style={{ transform: CSS.Translate.toString(transform), transition }}+ className={cn(+ "group/view-row flex items-center gap-1.5 rounded-md px-1.5 py-1",+ isDragging ? "z-10 bg-accent opacity-80" : "hover:bg-muted/60",+ )}+ >+ <button+ type="button"+ {...attributes}+ {...listeners}+ aria-label={t(($) => $.view_bar.drag_handle)}+ className={cn(+ "cursor-grab active:cursor-grabbing text-faint-foreground hover:text-muted-foreground",+ isDragging && "cursor-grabbing",+ )}+ >+ <GripVertical className="size-3.5" />+ </button>+ <button+ type="button"+ onClick={onSelect}+ className={cn(+ "flex min-w-0 flex-1 items-center gap-1.5 text-left text-body",+ active && "font-medium",+ )}+ >+ <span className="truncate">{item.label}</span>+ {item.kind === "builtin" && (+ <span className="shrink-0 text-caption text-muted-foreground">+ {t(($) => $.view_bar.builtin_tag)}+ </span>+ )}+ </button>+ {isView && item.view && (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t(($) => $.view_bar.row_menu)}+ className="text-muted-foreground"+ >+ <MoreHorizontal className="size-3.5" />+ </Button>+ }+ />+ <DropdownMenuContent align="end" className="w-44">+ {/* Same permission presentation as the tab context menu:+ edit greys out, delete hides. */}+ <DropdownMenuItem disabled={!item.canManage} onClick={onEdit}>+ <Pencil className="size-3.5" />+ {t(($) => $.view_bar.context_edit)}+ </DropdownMenuItem>+ {item.canManage && (+ <DropdownMenuItem variant="destructive" onClick={onDelete}>+ <Trash2 className="size-3.5" />+ {t(($) => $.view_bar.delete)}+ </DropdownMenuItem>+ )}+ <DropdownMenuItem onClick={onTogglePin}>+ {pinned ? <PinOff className="size-3.5" /> : <Pin className="size-3.5" />}+ {pinned+ ? t(($) => $.view_bar.context_unpin)+ : t(($) => $.view_bar.context_pin)}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={onHide}>+ <EyeOff className="size-3.5" />+ {t(($) => $.view_bar.row_hide)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </div>+ );+}++/**+ * The pulled-down list: EVERY tab on the bar, in bar order, drag to+ * reorder — the same preference document the bar's inline drag writes.+ * Because the bar shows the longest fitting prefix, reordering here IS+ * the control over what stays visible: drag something up to put it on+ * the bar, down to tuck it away. A separator marks the current fold.+ */+export function ViewListPanel({+ items,+ fitCount,+ activeViewId,+ pinnedViewIds,+ onMoveItem,+ onSelectItem,+ onEditView,+ onDeleteView,+ onTogglePin,+ onHideItem,+}: {+ /** All bar candidates in order (hidden ones excluded, as on the bar). */+ items: ViewBarItem[];+ /** How many currently fit on the bar — the fold line. */+ fitCount: number;+ activeViewId: string | null;+ pinnedViewIds: ReadonlySet<string>;+ /** Reorder request: move the item with `activeId` next to `overId`. */+ onMoveItem: (activeId: string, overId: string) => void;+ onSelectItem: (item: ViewBarItem) => void;+ onEditView: (view: IssueView) => void;+ onDeleteView: (view: IssueView) => void;+ onTogglePin: (view: IssueView, pinned: boolean) => void;+ onHideItem: (barItemId: string) => void;+}) {+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),+ );++ const handleDragEnd = (event: DragEndEvent) => {+ setDndCursor(false);+ const { active, over } = event;+ if (!over || active.id === over.id) return;+ onMoveItem(String(active.id), String(over.id));+ };++ return (+ <div className="max-h-96 overflow-y-auto p-1">+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ modifiers={[restrictToVerticalAxis]}+ autoScroll={{ threshold: { x: 0, y: 0.15 } }}+ onDragStart={() => setDndCursor(true)}+ onDragCancel={() => setDndCursor(false)}+ onDragEnd={handleDragEnd}+ >+ <SortableContext+ items={items.map((item) => item.barItemId)}+ strategy={verticalListSortingStrategy}+ >+ {items.map((item, index) => (+ <div key={item.barItemId}>+ {/* The fold: everything above is on the bar right now. */}+ {index === fitCount && index > 0 && (+ <div className="mx-1.5 my-1 border-t border-border" />+ )}+ <SortablePanelRow+ item={item}+ active={+ item.kind === "view" && item.view+ ? item.view.id === activeViewId+ : false+ }+ pinned={!!item.view && pinnedViewIds.has(item.view.id)}+ onSelect={() => onSelectItem(item)}+ onEdit={item.view ? () => onEditView(item.view!) : undefined}+ onDelete={item.view ? () => onDeleteView(item.view!) : undefined}+ onTogglePin={+ item.view+ ? () => onTogglePin(item.view!, pinnedViewIds.has(item.view!.id))+ : undefined+ }+ onHide={() => onHideItem(item.barItemId)}+ />+ </div>+ ))}+ </SortableContext>+ </DndContext>+ </div>+ );+}diff --git a/packages/views/issues/components/view-bar.tsx b/packages/views/issues/components/view-bar.tsxnew file mode 100644index 0000000000..c8342bf7b2--- /dev/null+++ b/packages/views/issues/components/view-bar.tsx@@ -0,0 +1,588 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import {+ DndContext,+ PointerSensor,+ closestCenter,+ useSensor,+ useSensors,+ type DragEndEvent,+} from "@dnd-kit/core";+import {+ SortableContext,+ arrayMove,+ horizontalListSortingStrategy,+ useSortable,+} from "@dnd-kit/sortable";+import { CSS } from "@dnd-kit/utilities";+import { restrictToHorizontalAxis } from "@dnd-kit/modifiers";+import {+ ChevronDown,+ Layers,+ MoreHorizontal,+ Pencil,+ Pin,+ PinOff,+ Plus,+ Settings2,+ Trash2,+} from "lucide-react";+import { Button } from "@multica/ui/components/ui/button";+import {+ ContextMenu,+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuSeparator,+ ContextMenuTrigger,+} from "@multica/ui/components/ui/context-menu";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@multica/ui/components/ui/dropdown-menu";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@multica/ui/components/ui/popover";+import { Tooltip, TooltipContent, TooltipTrigger } from "@multica/ui/components/ui/tooltip";+import { cn } from "@multica/ui/lib/utils";+import type { IssueView } from "@multica/core/api/schemas";+import {+ canManageIssueView,+ type IssueViewScope,+} from "@multica/core/issue-views/queries";+import {+ applyViewBarPrefs,+ issueViewPreferenceOptions,+ useUpdateIssueViewPreference,+ EMPTY_VIEW_BAR_PREFS,+} from "@multica/core/issue-views/preferences";+import { useDeleteIssueView } from "@multica/core/issue-views/mutations";+import { useAuthStore } from "@multica/core/auth";+import { memberListOptions } from "@multica/core/workspace/queries";+import { pinListOptions } from "@multica/core/pins/queries";+import { useCreatePin, useDeletePin } from "@multica/core/pins/mutations";+import { useSingleRowFit } from "../../common/single-row-fit";+import { ManageViewsDialog } from "./manage-views-dialog";+import {+ DeleteViewConfirm,+ ViewListPanel,+ type ViewBarItem,+} from "./view-bar-popover";+import { useT } from "../../i18n";++export interface ViewBarBuiltin {+ key: string;+ label: string;+ description?: string;+ active: boolean;+ onSelect: () => void;+}++/** Width shared by every tab: fits short names, truncates long ones. */+const TAB_MAX_W = "max-w-40";+/** Reserved px beside the tabs: the [⧉] menu and the always-present list+ * trigger; the promoted active tab is the wide shape. */+const RESERVE_BASE = 36 + 32;+const RESERVE_PROMOTED = 36 + 200;++/** One bar tab: sortable in place; suppresses the click that ends a drag. */+function SortableBarTab({+ id,+ children,+}: {+ id: string;+ children: React.ReactNode;+}) {+ const { listeners, setNodeRef, transform, transition, isDragging } =+ useSortable({ id });+ const wasDragged = useRef(false);+ useEffect(() => {+ if (isDragging) {+ wasDragged.current = true;+ return;+ }+ if (!wasDragged.current) return;+ // A drop lands as a click (swallowed below); a cancelled drag (Escape)+ // produces none — clear the flag a tick later so the NEXT real click+ // isn't eaten by a drag that never dropped.+ const timer = window.setTimeout(() => {+ wasDragged.current = false;+ }, 0);+ return () => window.clearTimeout(timer);+ }, [isDragging]);+ return (+ // Listeners only — dnd-kit's aria attributes would make this span a+ // second focusable role=button wrapping the real tab button.+ <span+ ref={setNodeRef}+ style={{ transform: CSS.Translate.toString(transform), transition }}+ className={cn("inline-flex", isDragging && "z-10 opacity-70")}+ {...listeners}+ onClickCapture={(event) => {+ if (wasDragged.current) {+ wasDragged.current = false;+ event.preventDefault();+ event.stopPropagation();+ }+ }}+ >+ {children}+ </span>+ );+}++/** Shared tab chrome so the real row and the measurement mirror agree. */+function BarTabButton({+ label,+ active,+ onClick,+}: {+ label: string;+ active?: boolean;+ onClick?: () => void;+}) {+ return (+ <Button+ variant="outline"+ size="sm"+ className={cn(+ TAB_MAX_W,+ active+ ? "bg-accent text-accent-foreground hover:bg-accent/80"+ : "text-muted-foreground",+ )}+ onClick={onClick}+ tabIndex={onClick ? undefined : -1}+ >+ <span className="truncate">{label}</span>+ </Button>+ );+}++/**+ * The view bar: built-in tabs and saved views as one flat, per-user+ * orderable single row. Everything that fits renders as a tab (drag to+ * reorder, horizontal axis); the rest collapses into a "more" popover+ * that appears only when needed. The OPEN view is always visible — when+ * overflowed it takes the trigger slot with its own name. The [⧉] menu+ * (new view / manage views) is unchanged.+ */+export function ViewBar({+ wsId,+ scope,+ builtins,+ views,+ viewsReady,+ activeView,+ onSelectView,+ onNewView,+ onEditView,+}: {+ wsId: string;+ scope: IssueViewScope;+ builtins: ViewBarBuiltin[];+ views: IssueView[];+ /** True once the views list has actually loaded — see savePrefs. */+ viewsReady: boolean;+ activeView: IssueView | null;+ onSelectView: (view: IssueView | null) => void;+ onNewView: () => void;+ /** Opens the edit dialog seeded from the view's own definition. */+ onEditView: (view: IssueView) => void;+}) {+ const { t } = useT("issues");+ const currentUserId = useAuthStore((s) => s.user?.id ?? null);+ const { data: preference } = useQuery(issueViewPreferenceOptions(wsId, scope));+ const prefs = preference?.prefs ?? EMPTY_VIEW_BAR_PREFS;+ const updatePreference = useUpdateIssueViewPreference(wsId, scope);+ const deleteView = useDeleteIssueView(wsId);+ const [manageOpen, setManageOpen] = useState(false);+ const [moreOpen, setMoreOpen] = useState(false);+ const [deleting, setDeleting] = useState<IssueView | null>(null);++ // The same manage rule the server enforces: owner, or workspace+ // owner/admin for shared views. Members load from cache in one query.+ const { data: members = [] } = useQuery(memberListOptions(wsId));+ const myRole = useMemo(+ () => members.find((m) => m.user_id === currentUserId)?.role ?? null,+ [members, currentUserId],+ );++ const { data: pins = [] } = useQuery({+ ...pinListOptions(wsId, currentUserId ?? ""),+ enabled: !!currentUserId,+ });+ const pinnedViewIds = useMemo(+ () =>+ new Set(+ pins.filter((p) => p.item_type === "view").map((p) => p.item_id),+ ),+ [pins],+ );+ const createPin = useCreatePin();+ const deletePin = useDeletePin();++ const anchorId = builtins.length > 0 ? `builtin:${builtins[0]!.key}` : "";++ const items = useMemo<ViewBarItem[]>(+ () => [+ ...builtins.map((b) => ({+ barItemId: `builtin:${b.key}`,+ label: b.label,+ kind: "builtin" as const,+ })),+ ...views.map((view) => ({+ barItemId: `view:${view.id}`,+ label: view.name,+ kind: "view" as const,+ view,+ canManage: canManageIssueView(view, currentUserId, myRole),+ })),+ ],+ [builtins, views, currentUserId, myRole],+ );++ // Synchronous mirror of a just-dropped order. The preference mutation is+ // optimistic but its onMutate is async — without this, the dropped tab+ // renders back at its OLD slot for a frame before the cache lands, which+ // reads as a bounce. Cleared as soon as the preference data catches up.+ const [localOrder, setLocalOrder] = useState<string[] | null>(null);+ useEffect(() => {+ setLocalOrder(null);+ }, [preference]);+ const displayPrefs = useMemo(+ () => (localOrder ? { ...prefs, order: localOrder } : prefs),+ [prefs, localOrder],+ );++ const { visible, hiddenSet, ordered } = useMemo(+ () => applyViewBarPrefs(items, displayPrefs, anchorId),+ [items, displayPrefs, anchorId],+ );++ const builtinByKey = useMemo(+ () => new Map(builtins.map((b) => [`builtin:${b.key}`, b])),+ [builtins],+ );++ // --- single-row fit -----------------------------------------------------+ // The reserve feeds back into the fit, but only ever grows when items+ // fall out ("more" trigger, then the promoted active tab), which shrinks+ // the fit further and keeps them out — the settle is monotonic.+ const activeBarId = activeView ? `view:${activeView.id}` : null;+ const [promotedTier, setPromotedTier] = useState(false);+ const { containerRef, measureRef, fitCount } = useSingleRowFit({+ count: visible.length,+ gap: 4,+ reserve: promotedTier ? RESERVE_PROMOTED : RESERVE_BASE,+ });+ const fitting = visible.slice(0, fitCount);+ const overflowed = visible.slice(fitCount);+ const activeOverflowed =+ !!activeBarId && overflowed.some((item) => item.barItemId === activeBarId);+ useEffect(() => {+ setPromotedTier(activeOverflowed);+ }, [activeOverflowed]);+ const promoted = promotedTier && activeOverflowed;++ const savePrefs = (next: { hidden: string[]; order: string[] }) => {+ // A drag can land before the views list has loaded; pruning against an+ // in-flight (empty) list would persist "every saved view was deleted"+ // and wipe the user's order and hidden sets. Drop the write instead —+ // the gesture is re-doable one moment later.+ if (!viewsReady) return;+ // Prune ids that no longer resolve so deleted views don't accumulate.+ const known = new Set(items.map((item) => item.barItemId));+ updatePreference.mutate({+ hidden: next.hidden.filter((id) => known.has(id)),+ order: next.order.filter((id) => known.has(id)),+ });+ };++ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),+ );+ // Apply a move NOW (mirror) and persist it — both drag surfaces route+ // through here so the drop lands visually in the same frame.+ const applyMove = (activeId: string, overId: string) => {+ const ids = ordered.map((item) => item.barItemId);+ const from = ids.indexOf(activeId);+ const to = ids.indexOf(overId);+ if (from < 0 || to < 0) return;+ const next = arrayMove(ids, from, to);+ if (viewsReady) setLocalOrder(next);+ savePrefs({ hidden: [...hiddenSet], order: next });+ };++ const handleDragEnd = (event: DragEndEvent) => {+ const { active, over } = event;+ if (!over || active.id === over.id) return;+ applyMove(String(active.id), String(over.id));+ };++ const confirmDelete = async (view: IssueView) => {+ await deleteView.mutateAsync(view.id);+ if (activeView?.id === view.id) onSelectView(null);+ };++ const toggleHidden = (barItemId: string, hidden: boolean) => {+ const nextHidden = new Set(hiddenSet);+ if (hidden) nextHidden.add(barItemId);+ else nextHidden.delete(barItemId);+ savePrefs({+ hidden: [...nextHidden],+ order: ordered.map((item) => item.barItemId),+ });+ // Hiding the open view exits it — an invisible active view would+ // strand the surface with no matching tab.+ if (hidden && activeView && barItemId === `view:${activeView.id}`) {+ onSelectView(null);+ }+ };++ const togglePin = (view: IssueView, pinned: boolean) =>+ pinned+ ? deletePin.mutate({ itemType: "view", itemId: view.id })+ : createPin.mutate({ item_type: "view", item_id: view.id });++ const selectItem = (item: ViewBarItem) => {+ if (item.kind === "builtin") {+ builtinByKey.get(item.barItemId)?.onSelect();+ } else if (item.view) {+ onSelectView(item.view);+ }+ setMoreOpen(false);+ };++ const renderViewTab = (item: ViewBarItem) => {+ const view = item.view!;+ const active = activeView?.id === view.id;+ const pinned = pinnedViewIds.has(view.id);+ return (+ <ContextMenu>+ <ContextMenuTrigger+ render={+ <Button+ variant="outline"+ size="sm"+ className={cn(+ TAB_MAX_W,+ active+ ? "bg-accent text-accent-foreground hover:bg-accent/80"+ : "text-muted-foreground",+ )}+ onClick={() => onSelectView(active ? null : view)}+ />+ }+ >+ <span className="truncate">{view.name}</span>+ </ContextMenuTrigger>+ <ContextMenuContent className="w-44">+ {/* Edit stays visible but disabled without permission — the greyed+ row IS the "you can't" signal. Delete is hidden entirely: a+ destructive dead-end invites a doomed confirm flow. */}+ <ContextMenuItem+ disabled={!item.canManage}+ onClick={() => onEditView(view)}+ >+ <Pencil className="size-3.5" />+ {t(($) => $.view_bar.context_edit)}+ </ContextMenuItem>+ {item.canManage && (+ <ContextMenuItem+ variant="destructive"+ onClick={() => setDeleting(view)}+ >+ <Trash2 className="size-3.5" />+ {t(($) => $.view_bar.delete)}+ </ContextMenuItem>+ )}+ <ContextMenuSeparator />+ <ContextMenuItem onClick={() => togglePin(view, pinned)}>+ {pinned ? <PinOff className="size-3.5" /> : <Pin className="size-3.5" />}+ {pinned+ ? t(($) => $.view_bar.context_unpin)+ : t(($) => $.view_bar.context_pin)}+ </ContextMenuItem>+ </ContextMenuContent>+ </ContextMenu>+ );+ };++ return (+ <div+ ref={containerRef}+ className="relative flex min-w-0 flex-1 flex-nowrap items-center gap-1 overflow-hidden"+ >+ {/* Measurement mirror: every visible candidate at natural width. */}+ <div+ ref={measureRef}+ aria-hidden+ className="pointer-events-none invisible absolute left-0 top-0 flex flex-nowrap items-center gap-1"+ >+ {visible.map((item) => (+ <span key={item.barItemId} className="inline-flex">+ <BarTabButton label={item.label} />+ </span>+ ))}+ </div>++ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ // Same gesture contract as the table's column reordering: tabs slide+ // along the row only. Overflowed items reorder via the manage dialog.+ modifiers={[restrictToHorizontalAxis]}+ onDragEnd={handleDragEnd}+ >+ <SortableContext+ items={fitting.map((item) => item.barItemId)}+ strategy={horizontalListSortingStrategy}+ >+ {fitting.map((item) => {+ if (item.kind === "builtin") {+ const b = builtinByKey.get(item.barItemId);+ if (!b) return null;+ const button = (+ <BarTabButton label={b.label} active={b.active} onClick={b.onSelect} />+ );+ return (+ <SortableBarTab key={item.barItemId} id={item.barItemId}>+ {b.description ? (+ <Tooltip>+ <TooltipTrigger render={button} />+ <TooltipContent side="bottom">{b.description}</TooltipContent>+ </Tooltip>+ ) : (+ button+ )}+ </SortableBarTab>+ );+ }+ return (+ <SortableBarTab key={item.barItemId} id={item.barItemId}>+ {renderViewTab(item)}+ </SortableBarTab>+ );+ })}+ </SortableContext>+ </DndContext>++ {/* The full list — always reachable. Reordering here decides what+ fits on the bar; the open view becomes the trigger when it+ overflows so it never disappears. */}+ <Popover open={moreOpen} onOpenChange={setMoreOpen}>+ <PopoverTrigger+ render={+ promoted && activeView ? (+ <Button+ variant="outline"+ size="sm"+ className={cn(+ TAB_MAX_W,+ "shrink-0 gap-1 bg-accent text-accent-foreground hover:bg-accent/80",+ )}+ >+ <span className="truncate">{activeView.name}</span>+ <ChevronDown className="size-3 shrink-0" />+ </Button>+ ) : (+ <Button+ variant="outline"+ size="sm"+ aria-label={t(($) => $.view_bar.more_label)}+ className="shrink-0 px-1.5 text-muted-foreground"+ >+ <MoreHorizontal className="size-3.5" />+ </Button>+ )+ }+ />+ <PopoverContent align="end" className="w-64 p-0">+ <ViewListPanel+ items={visible}+ fitCount={fitCount}+ activeViewId={activeView?.id ?? null}+ pinnedViewIds={pinnedViewIds}+ onMoveItem={applyMove}+ onSelectItem={selectItem}+ onEditView={(view) => {+ setMoreOpen(false);+ onEditView(view);+ }}+ onDeleteView={(view) => {+ setMoreOpen(false);+ setDeleting(view);+ }}+ onTogglePin={togglePin}+ onHideItem={(barItemId) => {+ setMoreOpen(false);+ toggleHidden(barItemId, true);+ }}+ />+ </PopoverContent>+ </Popover>++ <DropdownMenu>+ <Tooltip>+ <DropdownMenuTrigger+ render={+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t(($) => $.view_bar.menu_label)}+ className="shrink-0 text-muted-foreground"+ >+ <Layers className="size-3.5" />+ </Button>+ }+ />+ }+ />+ <TooltipContent side="bottom">{t(($) => $.view_bar.menu_label)}</TooltipContent>+ </Tooltip>+ <DropdownMenuContent align="start" className="w-44">+ <DropdownMenuItem onClick={onNewView}>+ <Plus className="size-3.5" />+ {t(($) => $.view_bar.menu_new)}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => setManageOpen(true)}>+ <Settings2 className="size-3.5" />+ {t(($) => $.view_bar.menu_manage)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>++ <ManageViewsDialog+ open={manageOpen}+ onOpenChange={setManageOpen}+ items={ordered}+ hiddenSet={hiddenSet}+ anchorId={anchorId}+ onReorder={(orderedIds) => savePrefs({ hidden: [...hiddenSet], order: orderedIds })}+ onToggleHidden={toggleHidden}+ onEditView={(view) => {+ setManageOpen(false);+ onEditView(view);+ }}+ onDeleteView={confirmDelete}+ />++ {/* Context-menu / overflow-row delete share one confirm. */}+ <DeleteViewConfirm+ view={deleting}+ onOpenChange={(open) => {+ if (!open) setDeleting(null);+ }}+ onConfirm={confirmDelete}+ />+ </div>+ );+}diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsxindex 02f7705e77..074136bc6a 100644--- a/packages/views/issues/surface/issue-surface.tsx+++ b/packages/views/issues/surface/issue-surface.tsx@@ -10,8 +10,20 @@ import {useViewStore,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 {+ getIssueSurfaceViewStore,+ seedIssueSurfaceViewState,+} from "@multica/core/issues/stores/surface-view-store";+import { useActiveIssueView } from "@multica/core/issue-views/use-active-view";+import { baselineFromQuery } from "@multica/core/issue-views/baseline";+import { ViewBaselineProvider, useViewBaseline } from "./view-baseline-context";+import type { IssueViewScope } from "@multica/core/issue-views/queries";+import {+ actorKindForViewVariant,+ issueScopeKey,+ myRelationForViewVariant,+ type IssueScope,+} 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";@@ -60,18 +72,60 @@ export function IssueSurface({contentClassName,}: IssueSurfaceComponentProps) {const wsId = useWorkspaceId();- const resolvedSurfaceKey = surfaceKey ?? issueScopeKey(scope);- const store = useMemo(- () => getIssueSurfaceViewStore(resolvedSurfaceKey),- [resolvedSurfaceKey],+ // Saved views exist on workspace / my / project surfaces only.+ const viewScope: IssueViewScope | null =+ scope.type === "workspace"+ ? { scope_type: "workspace" }+ : scope.type === "my"+ ? { scope_type: "my" }+ : scope.type === "project"+ ? { scope_type: "project", scope_id: scope.projectId }+ : null;+ const { activeView } = useActiveIssueView(wsId, viewScope);++ // An open saved view swaps the surface onto its own view-preference key:+ // display/extra-filter adjustments persist per user per view, and the+ // underlying built-in surface state is never touched (no draft machinery).+ const resolvedSurfaceKey = activeView+ ? `view:${activeView.id}`+ : (surfaceKey ?? issueScopeKey(scope));+ const seedDefinition = activeView+ ? { ...activeView.query, ...activeView.display }+ : null;+ const viewBaseline = useMemo(+ () => (activeView ? baselineFromQuery(activeView.query) : null),+ [activeView],);+ // While a view is open, the scope axis the view captured belongs to the+ // VIEW, not to whichever tab the user stood on: workspace/project views+ // carry an assignee-type variant, my views a relation variant. The user's+ // own tab state is never touched — it is exactly where they left it when+ // the view closes (or vanishes). A variant-free view resolves to the+ // unrestricted axis value.+ const effectiveScope: IssueScope =+ activeView && (scope.type === "workspace" || scope.type === "project")+ ? { ...scope, actorKind: actorKindForViewVariant(activeView.scope_variant) }+ : activeView && scope.type === "my"+ ? { ...scope, relation: myRelationForViewVariant(activeView.scope_variant) }+ : scope;+ const store = useMemo(() => {+ // First-open seeding happens HERE, at store-creation time for this key:+ // no React component has subscribed to the new key's store yet, so the+ // setState inside cannot cascade into an in-render update loop (it did+ // when this ran in the component body).+ if (seedDefinition) {+ seedIssueSurfaceViewState(resolvedSurfaceKey, seedDefinition);+ }+ return getIssueSurfaceViewStore(resolvedSurfaceKey);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- seed identity follows the key+ }, [resolvedSurfaceKey]);// Every change of this key tears down and remounts the ENTIRE surface// (providers, DnD, all columns/cards) — by design for data-window changes,// but expensive enough that unexpected flips are performance bugs. Dev-only// breadcrumb so a Performance trace showing double mounts can be tied to// the exact key transition.- const contentKey = `${wsId}:${issueScopeKey(scope)}`;+ const contentKey = `${wsId}:${issueScopeKey(effectiveScope)}:${activeView ? `view:${activeView.id}` : "default"}`;useEffect(() => {if (process.env.NODE_ENV !== "production") {console.warn(`[issue-surface] mount ${contentKey}`);@@ -80,6 +134,7 @@ export function IssueSurface({return (<ViewStoreProvider store={store}>+ <ViewBaselineProvider baseline={viewBaseline}>{/* Remount on data-window change: the list queries keep the previouskey's data as a placeholder (keepPreviousData) so sort/filterchanges within ONE surface never flash a skeleton — but reusing the@@ -93,7 +148,7 @@ export function IssueSurface({by data identity, not surfaceKey (view-preference identity). */}<IssueSurfaceContentkey={contentKey}- scope={scope}+ scope={effectiveScope}modes={modes}createDefaults={createDefaults}search={search}@@ -105,6 +160,7 @@ export function IssueSurface({batchToolbar={batchToolbar}contentClassName={contentClassName}/>+ </ViewBaselineProvider></ViewStoreProvider>);}@@ -165,15 +221,6 @@ function IssueSurfaceContent({},[controller],);- // Stable reference for BoardView's issues: the inline flatMap allocated a- // fresh array every render, defeating BoardView's memo.- const boardIssues = useMemo(- () =>- controller.assigneeGroups- ? controller.assigneeGroups.flatMap((group) => group.issues)- : issues,- [controller.assigneeGroups, issues],- );const shouldShowClientEmpty =!!clientFilter &&issues.length === 0 &&@@ -205,6 +252,13 @@ function IssueSurfaceContent({}tableFacetCounts={controller.tableFacetCounts}onTableFacetChange={controller.setActiveTableFacet}+ saveViewScope={+ scope.type === "project"+ ? { kind: "project", projectId: scope.projectId }+ : scope.type === "workspace"+ ? { kind: "workspace" }+ : null+ }/>)}{controller.isLoading ? (@@ -244,18 +298,12 @@ function IssueSurfaceContent({<div className={cn("flex flex-col flex-1 min-h-0", contentClassName)}>{controller.viewMode === "board" && (<BoardView- issues={boardIssues}- assigneeGroups={controller.assigneeGroups}- assigneeGroupQueryKey={controller.assigneeGroupQueryKey}- assigneeGroupFilter={controller.assigneeGroupFilter}+ issues={issues}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}statusPagination={controller.statusPagination}@@ -299,9 +347,6 @@ function IssueSurfaceContent({onMoveIssue={controller.moveIssue}childProgressMap={controller.childProgressMap}projectMap={controller.projectMap}- myIssuesScope={controller.loadMoreScope}- myIssuesFilter={controller.loadMoreFilter}- sort={controller.sort}projectId={controller.projectId}onCreateIssue={openCreateIssue}groupBranches={controller.groupBranches}@@ -331,13 +376,20 @@ function IssueSurfaceContent({function FilteredEmptyState() {const { t } = useT("issues");const clearFilters = useViewStore((s) => s.clearFilters);+ const resetFiltersTo = useViewStore((s) => s.resetFiltersTo);+ // Inside a saved view "clear" returns to the view's own conditions — the+ // baseline is not clearable from here (only the edit dialog changes it).+ const baseline = useViewBaseline();+ const handleClear = baseline+ ? () => resetFiltersTo(baseline.raw)+ : clearFilters;return (<div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-3 text-muted-foreground"><FilterX className="h-10 w-10 text-faint-foreground" /><p className="text-body">{t(($) => $.filtered_empty.title)}</p><p className="text-caption">{t(($) => $.filtered_empty.hint)}</p>- <Button variant="outline" size="sm" className="mt-1" onClick={clearFilters}>+ <Button variant="outline" size="sm" className="mt-1" onClick={handleClear}>{t(($) => $.filtered_empty.clear_button)}</Button></div>diff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsxindex f5e1e7aff6..ce0f4412c6 100644--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx@@ -220,10 +220,8 @@ describe("useIssueSurfaceController", () => {await waitFor(() => expect(listIssueTableRows).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(result.current.tableQuerySpec).toEqual(expect.objectContaining({@@ -304,9 +302,6 @@ describe("useIssueSurfaceController", () => {await waitFor(() => expect(listIssueTableRows).toHaveBeenCalled());expect(result.current.scopeKey).toBe("workspace:all");- expect(result.current.filter).toEqual({});- expect(result.current.loadMoreScope).toBeUndefined();- expect(result.current.loadMoreFilter).toBeUndefined();expect(result.current.tableQuerySpec.scope).toEqual({kind: "workspace",});@@ -370,12 +365,7 @@ describe("useIssueSurfaceController", () => {);await waitFor(() => expect(listIssueTableRows).toHaveBeenCalled());-- const expectedFilter = { assignee_id: "user-1" };expect(result.current.scopeKey).toBe("my:user-1:assigned");- expect(result.current.filter).toEqual(expectedFilter);- expect(result.current.loadMoreScope).toBe("assigned");- expect(result.current.loadMoreFilter).toEqual(expectedFilter);expect(result.current.tableQuerySpec.scope).toEqual({kind: "my",relation: "assigned",@@ -398,12 +388,7 @@ describe("useIssueSurfaceController", () => {);await waitFor(() => expect(listIssueTableRows).toHaveBeenCalled());-- const expectedFilter = { assignee_id: "agent-1" };expect(result.current.scopeKey).toBe("actor:agent:agent-1:assigned");- expect(result.current.filter).toEqual(expectedFilter);- expect(result.current.loadMoreScope).toBe("actor:agent:agent-1:assigned");- expect(result.current.loadMoreFilter).toEqual(expectedFilter);expect(result.current.tableQuerySpec.scope).toEqual({kind: "assignee",actor: { type: "agent", id: "agent-1" },diff --git a/packages/views/issues/surface/use-issue-surface-controller.ts b/packages/views/issues/surface/use-issue-surface-controller.tsindex 0634bfb567..d9ff88c57d 100644--- a/packages/views/issues/surface/use-issue-surface-controller.ts+++ b/packages/views/issues/surface/use-issue-surface-controller.ts@@ -2,11 +2,9 @@import { useCallback, useEffect, useMemo, useState } from "react";import { hashKey, keepPreviousData, useQuery } from "@tanstack/react-query";-import type { QueryKey } from "@tanstack/react-query";import { api } from "@multica/core/api";import type {Issue,- IssueAssigneeGroup,IssueStatus,IssueTableFacetSpec,IssueTableFacetsResponse,@@ -19,17 +17,16 @@ import { workspaceWorkingAgentsOptions } from "@multica/core/agents";import { useWorkspaceId } from "@multica/core/hooks";import { ALL_STATUSES } from "@multica/core/issues/config";import { dateOnlyToLocalDate } from "@multica/core/issues/date";-import type {- AssigneeGroupedIssuesFilter,- IssueSortParam,- MyIssuesFilter,-} from "@multica/core/issues/queries";+import type { IssueSortParam } from "@multica/core/issues/queries";import { issueTableFacetsOptions } 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 {+ assigneeTypesForActorKind,+ type IssueScope,+} from "@multica/core/issues/surface/scope";import type { IssueDateFilter, SortField } from "@multica/core/issues/stores/view-store";import { propertyListOptions } from "@multica/core/properties";import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";@@ -82,12 +79,6 @@ export interface IssueSurfaceController {* number it cannot stand behind. */workingAgents: WorkingAgentSummary[] | undefined;filteredGanttIssues: Issue[];- assigneeGroups?: IssueAssigneeGroup[];- assigneeGroupQueryKey?: QueryKey;- assigneeGroupFilter?: AssigneeGroupedIssuesFilter;- filter: MyIssuesFilter;- loadMoreScope?: string;- loadMoreFilter?: MyIssuesFilter;sort: IssueSortParam;ganttIssues: Issue[];visibleStatuses: IssueStatus[];@@ -316,8 +307,6 @@ export function useIssueSurfaceController({groupingPropertyId && catalogSettled && !activeGroupingProperty? "status": grouping;- const usesAssigneeBoard =- effectiveViewMode === "board" && effectiveGrouping === "assignee";const usesGantt = effectiveViewMode === "gantt" && !!projectId;const usesTable = effectiveViewMode === "table";const activeSearch = usesTable ? tableSearch : search;@@ -391,19 +380,23 @@ export function useIssueSurfaceController({const derivedTableQuerySpec = useMemo<IssueTableQuerySpec>(() => {let queryScope: IssueTableQuerySpec["scope"];switch (scope.type) {- case "workspace":+ case "workspace": {+ const assigneeTypes = assigneeTypesForActorKind(scope.actorKind);queryScope = {kind: "workspace",- ...(scope.actorKind === "members"- ? { assignee_types: ["member" as const] }- : scope.actorKind === "agents"- ? { assignee_types: ["agent" as const, "squad" as const] }- : {}),+ ...(assigneeTypes ? { assignee_types: assigneeTypes } : {}),};break;- case "project":- queryScope = { kind: "project", project_id: scope.projectId };+ }+ case "project": {+ const assigneeTypes = assigneeTypesForActorKind(scope.actorKind);+ queryScope = {+ kind: "project",+ project_id: scope.projectId,+ ...(assigneeTypes ? { assignee_types: assigneeTypes } : {}),+ };break;+ }case "my":queryScope = {kind: "my",@@ -674,13 +667,11 @@ export function useIssueSurfaceController({wsId,queryPlan,projectId,- usesAssigneeBoard,usesGantt,usesTable,serverStatusBranches,serverGroupBranches,ganttShowCompleted,- sort,statusFilters,priorityFilters,assigneeFilters,diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.tsindex 1dfee2f1f9..a7e541ad97 100644--- a/packages/views/issues/surface/use-issue-surface-data.ts+++ b/packages/views/issues/surface/use-issue-surface-data.ts@@ -1,29 +1,16 @@"use client";import { useCallback, useMemo } from "react";-import {- useQuery,- type QueryKey,-} from "@tanstack/react-query";-import type { Issue, IssueAssigneeGroup, Project } from "@multica/core/types";+import { useQuery } from "@tanstack/react-query";+import type { Issue, Project } from "@multica/core/types";import { ALL_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 { childIssueProgressOptions } from "@multica/core/issues/queries";+import { issueSurfaceGanttOptions } 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";@@ -70,12 +57,6 @@ export interface IssueSurfaceData {* sources its count from the `working_agents` server facet instead. */ganttWorkingScopeIssues: Issue[] | undefined;filteredGanttIssues: Issue[];- assigneeGroups?: IssueAssigneeGroup[];- assigneeGroupQueryKey?: QueryKey;- assigneeGroupFilter?: AssigneeGroupedIssuesFilter;- filter: MyIssuesFilter;- loadMoreScope?: string;- loadMoreFilter?: MyIssuesFilter;ganttIssues: Issue[];visibleStatuses: IssueStatus[];hiddenStatuses: IssueStatus[];@@ -103,13 +84,11 @@ export function useIssueSurfaceData({wsId,queryPlan,projectId,- usesAssigneeBoard,usesGantt,usesTable,serverStatusBranches,serverGroupBranches,ganttShowCompleted,- sort,statusFilters,priorityFilters,assigneeFilters,@@ -127,7 +106,6 @@ export function useIssueSurfaceData({wsId: string;queryPlan: IssueSurfaceQueryPlan;projectId?: string;- usesAssigneeBoard: boolean;usesGantt: boolean;usesTable: boolean;serverStatusBranches: IssueStatusBranches;@@ -135,7 +113,6 @@ export function useIssueSurfaceData({/** Gantt's "show completed" display toggle. The canvas hides done/cancelled* rows without it, so the working scope has to honour it too. */ganttShowCompleted: boolean;- sort: IssueSortParam;statusFilters: IssueStatus[];priorityFilters: IssueFilterState["priorityFilters"];assigneeFilters: IssueFilterState["assigneeFilters"];@@ -151,76 +128,19 @@ export function useIssueSurfaceData({showSubIssues: boolean;loadProjects: boolean;}): IssueSurfaceData {- const assigneeGroupFilter = useMemo<AssigneeGroupedIssuesFilter>(- () => ({- ...queryPlan.groupedScopeFilter,- statuses: statusFilters.length > 0 ? statusFilters : [...ALL_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 &&- !usesTable &&- !serverStatusBranches.enabled &&- !serverGroupBranches.enabled,- });- const assigneeGroupsQuery = useQuery({- ...activeAssigneeGroupsOptions,- enabled: usesAssigneeBoard && !serverGroupBranches.enabled,- });const ganttIssuesQuery = useQuery({- ...issueSurfaceGanttOptions(wsId, projectId ?? ""),+ ...issueSurfaceGanttOptions(wsId, projectId ?? "", queryPlan),enabled: usesGantt,});const workingFilterContext = useMemo(() => ({ runningIssueIds: workingIssueIDs }),[workingIssueIDs],);- const bucketedIssues = useMemo(() => {- return serverStatusBranches.enabled- ? serverStatusBranches.issues- : serverGroupBranches.enabled+ const bucketedIssues = serverStatusBranches.enabled+ ? serverStatusBranches.issues+ : serverGroupBranches.enabled? serverGroupBranches.issues- : usesAssigneeBoard- ? (assigneeGroupsQuery.data?.groups.flatMap((group) => group.issues) ?? [])- : (statusIssuesQuery.data ?? EMPTY_ISSUES);- }, [- assigneeGroupsQuery.data?.groups,- serverStatusBranches.enabled,- serverStatusBranches.issues,- serverGroupBranches.enabled,- serverGroupBranches.issues,- statusIssuesQuery.data,- usesAssigneeBoard,- ]);+ : EMPTY_ISSUES;// `cancelled` is a first-class default status (MUL-4290): it is fetched into// the cache like every other status and flows straight through to list /@@ -312,27 +232,6 @@ export function useIssueSurfaceData({],);- // The assignee-grouped board renders straight from `groups`, bypassing the- // flat applyIssueFilters output — re-apply the remaining client-only- // display filters per group. Server-owned group paths encode running-task- // membership in the canonical query; this fallback uses the same issue ids.- const filteredAssigneeGroups = useMemo(- () =>- filterAssigneeGroups(assigneeGroupsQuery.data?.groups, {- agentRunningFilter,- runningIssueIds: workingIssueIDs,- showSubIssues,- propertyFilters,- }),- [- assigneeGroupsQuery.data?.groups,- agentRunningFilter,- propertyFilters,- showSubIssues,- workingIssueIDs,- ],- );-const workingFilterState = useMemo<IssueFilterState>(() => ({...baseFilterState,@@ -466,30 +365,20 @@ export function useIssueSurfaceData({const isLoading = serverGroupBranches.enabled? serverGroupBranches.isLoading- : usesAssigneeBoard- ? assigneeGroupsQuery.isLoading- : usesGantt+ : usesGantt? ganttIssuesQuery.isLoading- : usesTable- ? false- : serverStatusBranches.enabled- ? serverStatusBranches.isLoading- : statusIssuesQuery.isLoading;+ : serverStatusBranches.enabled+ ? serverStatusBranches.isLoading+ : false;// 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 = serverGroupBranches.enabled? serverGroupBranches.isRefreshing- : usesAssigneeBoard- ? assigneeGroupsQuery.isPlaceholderData- : usesGantt- ? false- : usesTable- ? false- : serverStatusBranches.enabled- ? serverStatusBranches.isRefreshing- : statusIssuesQuery.isPlaceholderData;+ : serverStatusBranches.enabled+ ? serverStatusBranches.isRefreshing+ : false;return {surfaceIssues,@@ -498,14 +387,6 @@ export function useIssueSurfaceData({swimlaneIssues,ganttWorkingScopeIssues,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,@@ -531,9 +412,8 @@ export function useIssueSurfaceData({(serverStatusBranches.enabled? serverStatusBranches.isTotalKnown &&serverStatusBranches.total === 0- : serverGroupBranches.enabled- ? !serverGroupBranches.isError &&- serverGroupBranches.total === 0- : surfaceIssues.length === 0),+ : serverGroupBranches.enabled &&+ !serverGroupBranches.isError &&+ serverGroupBranches.total === 0),};}diff --git a/packages/views/issues/surface/view-baseline-context.tsx b/packages/views/issues/surface/view-baseline-context.tsxnew file mode 100644index 0000000000..af56c484e4--- /dev/null+++ b/packages/views/issues/surface/view-baseline-context.tsx@@ -0,0 +1,30 @@+"use client";++import { createContext, use, type ReactNode } from "react";+import type { IssueViewBaseline } from "@multica/core/issue-views/baseline";++/**+ * The open saved view's baseline for everything living inside an+ * IssueSurface — board column menus, the filtered-empty state, swimlanes.+ * `null` = no view open. Kept as its own context so deep consumers don't+ * need the active-view hook (and its list query) re-run per component.+ */+const ViewBaselineContext = createContext<IssueViewBaseline | null>(null);++export function ViewBaselineProvider({+ baseline,+ children,+}: {+ baseline: IssueViewBaseline | null;+ children: ReactNode;+}) {+ return (+ <ViewBaselineContext.Provider value={baseline}>+ {children}+ </ViewBaselineContext.Provider>+ );+}++export function useViewBaseline(): IssueViewBaseline | null {+ return use(ViewBaselineContext);+}diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsxindex 45550e38e2..94fc13eeb5 100644--- a/packages/views/layout/app-sidebar.tsx+++ b/packages/views/layout/app-sidebar.tsx@@ -16,7 +16,7 @@ import {} from "@dnd-kit/core";import { SortableContext, verticalListSortingStrategy, useSortable, arrayMove } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";-import {+import { Layers,ChevronDown,ChevronRight,LogOut,@@ -57,6 +57,11 @@ import {DropdownMenuTrigger,} from "@multica/ui/components/ui/dropdown-menu";import { useAuthStore } from "@multica/core/auth";+import { issueViewDetailOptions } from "@multica/core/issue-views/queries";+import {+ issueViewContainerKey,+ useActiveIssueViewStore,+} from "@multica/core/issue-views/active-view-store";import { useCurrentWorkspace, useWorkspacePaths, paths } from "@multica/core/paths";import { workspaceListOptions, myInvitationListOptions, workspaceKeys } from "@multica/core/workspace/queries";import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";@@ -177,6 +182,8 @@ function SortablePinItem({onUnpin,label,iconNode,+ onNavigate,+ isActiveOverride,}: {pin: PinnedItem;href: string;@@ -184,6 +191,10 @@ function SortablePinItem({onUnpin: () => void;label: string;iconNode: React.ReactNode;+ /** Runs on a real click (not a drag-release) before navigation. */+ onNavigate?: () => void;+ /** Overrides the plain path comparison (view pins carry extra state). */+ isActiveOverride?: boolean;}) {const { t } = useT("layout");const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: pin.id });@@ -194,7 +205,7 @@ function SortablePinItem({}, [isDragging]);const style = { transform: CSS.Transform.toString(transform), transition };- const isActive = pathname === href;+ const isActive = isActiveOverride ?? pathname === href;return (<SidebarMenuItem@@ -214,6 +225,7 @@ function SortablePinItem({event.preventDefault();return;}+ onNavigate?.();}}className={cn("text-muted-foreground hover:not-data-active:bg-sidebar-accent/70 data-active:bg-sidebar-accent data-active:text-sidebar-accent-foreground",@@ -271,23 +283,80 @@ function PinRow({wsId: string;}) {const isIssue = pin.item_type === "issue";+ const isView = pin.item_type === "view";+ const p = useWorkspacePaths();+ const setActiveView = useActiveIssueViewStore((s) => s.setActive);const issueQuery = useQuery({...issueDetailOptions(wsId, pin.item_id),enabled: isIssue,});const projectQuery = useQuery({...projectDetailOptions(wsId, pin.item_id),- enabled: !isIssue,+ enabled: pin.item_type === "project",+ });+ const viewQuery = useQuery({+ ...issueViewDetailOptions(wsId, pin.item_id),+ enabled: isView,});const triggeredRef = useRef(false);useEffect(() => {+ // Views are exempt from 404-auto-unpin: an installed desktop client+ // talking to an older backend without the view endpoints sees 404 for+ // every view pin — auto-unpinning would permanently delete them all.+ // A deleted view's row simply hides instead.+ if (isView) return;const err = isIssue ? issueQuery.error : projectQuery.error;if (err instanceof ApiError && err.status === 404 && !triggeredRef.current) {triggeredRef.current = true;onUnpin();}- }, [isIssue, issueQuery.error, onUnpin, projectQuery.error]);+ }, [isIssue, isView, issueQuery.error, onUnpin, projectQuery.error]);++ const activeViewByContainer = useActiveIssueViewStore((s) => s.active);+ if (isView) {+ if (viewQuery.isPending) return <PinSkeleton />;+ if (viewQuery.isError || !viewQuery.data) return null;+ const view = viewQuery.data;+ // One resolved scope drives the path AND the container key so an+ // unrecognised scope_type from a newer backend degrades coherently.+ const scopeType: "workspace" | "my" | "project" =+ view.scope_type === "my"+ ? "my"+ : view.scope_type === "project" && view.scope_id+ ? "project"+ : "workspace";+ const viewPath =+ scopeType === "my"+ ? p.myIssues()+ : scopeType === "project"+ ? p.projectDetail(view.scope_id!)+ : p.issues();+ const containerKey = issueViewContainerKey(wsId, {+ scope_type: scopeType,+ scope_id: scopeType === "project" ? view.scope_id : null,+ });+ return (+ <SortablePinItem+ pin={pin}+ // ?view= keeps a web reload on the view for the surfaces that mount+ // the URL-sync hook (/issues, /my-issues). Project pages don't sync+ // yet — there the query is inert and reload falls back to the plain+ // page; click-through activation still works everywhere.+ href={`${viewPath}?view=${view.id}`}+ pathname={pathname}+ onUnpin={onUnpin}+ label={view.name}+ iconNode={<Layers className="!size-3.5 shrink-0" />}+ // Active only when this exact view is open on its surface — the+ // path alone also matches the plain tab.+ isActiveOverride={+ pathname === viewPath && activeViewByContainer[containerKey] === view.id+ }+ onNavigate={() => setActiveView(containerKey, view.id)}+ />+ );+ }if (isIssue) {if (issueQuery.isPending) return <PinSkeleton />;@@ -435,7 +504,14 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }const sidebarScrollRef = useRef<HTMLDivElement>(null);const sidebarFadeStyle = useScrollFade(sidebarScrollRef, 24);const getPinHref = useCallback(- (pin: PinnedItem) => (pin.item_type === "issue" ? p.issueDetail(pin.item_id) : p.projectDetail(pin.item_id)),+ (pin: PinnedItem) =>+ pin.item_type === "issue"+ ? p.issueDetail(pin.item_id)+ : pin.item_type === "project"+ ? p.projectDetail(pin.item_id)+ // Views know their target only after their detail loads — the row+ // resolves its own href; this placeholder never renders as a link.+ : "",[p],);@@ -455,6 +531,9 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }setLocalPinnedWsId(wsId ?? null);}, [wsId]);const visiblePinned = localPinnedWsId === (wsId ?? null) ? localPinned : EMPTY_PINS;+ // View pins are absent here (their href resolves async): while a view+ // pin is active the plain nav row for its surface stays highlighted too.+ // Accepted — suppressing it would need every view detail lifted up here.const isActivePinnedRoute = visiblePinned.some((pin) => pathname === getPinHref(pin));const handleDragStart = useCallback(() => {diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 6ffc577330..ac1a72b921 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -63,8 +63,16 @@"issue_count_one": "{{count}} issue","issue_count_other": "{{count}} issues","reset": "Reset all filters",+ "chip_remove": "Remove {{name}} filter",+ "chip_status_count_other": "{{count}} statuses",+ "chip_priority_count_other": "{{count}} priorities",+ "chip_clear": "Clear",+ "chip_save": "Save","active_count_one": "{{count}} filter",- "active_count_other": "{{count}} filters"+ "active_count_other": "{{count}} filters",+ "in_view": "Already in this view",+ "chip_edit": "Edit",+ "chip_save_as": "Save as"},"display": {"tooltip": "Display settings",@@ -697,5 +705,78 @@"row_backlog_hint": "keeps the agent paused","row_todo_label": "Todo","row_todo_hint": "starts the agent"+ },+ "save_view": {+ "title": "Save as view",+ "hint_workspace": "Based on all workspace issues",+ "hint_my_any": "Based on My issues · All",+ "hint_my_assigned": "Based on My issues · Assigned",+ "hint_my_created": "Based on My issues · Created",+ "hint_my_involved": "Based on My issues · Involved",+ "hint_project": "Based on project “{{title}}”, available only on that project page",+ "hint_project_agents": "Based on project “{{title}}” issues assigned to agents, available only on that project page",+ "hint_project_members": "Based on project “{{title}}” issues assigned to members, available only on that project page",+ "my_private_note": "My issues views are visible only to you",+ "name_label": "Name",+ "visibility_label": "Visibility",+ "visibility_private": "Only visible to me",+ "visibility_workspace": "Visible to workspace members",+ "filters_label": "Filters",+ "custom_property": "Custom property",+ "create": "Create view",+ "layout_label": "Layout",+ "display_defaults": "Default display",+ "default_hint": "How members first see this view; everyone can adjust for themselves afterwards",+ "add_filter": "Add filter",+ "name_placeholder": "e.g. Needs review",+ "cancel": "Cancel",+ "name_required": "Enter a view name",+ "toast_created": "View created",+ "toast_failed": "Failed to create view",+ "edit_title": "Edit view",+ "update": "Save changes",+ "toast_updated": "View updated",+ "toast_conflict": "Someone else edited this view — reopen it and try again",+ "hint_workspace_members": "Based on workspace issues assigned to members",+ "hint_workspace_agents": "Based on workspace issues assigned to agents",+ "scope_label_workspace": "Assignee type",+ "scope_label_my": "Relation to me",+ "variant_all": "Any assignee",+ "variant_members": "Assigned to members",+ "variant_agents": "Assigned to agents",+ "variant_my_any": "Any relation",+ "variant_my_assigned": "Assigned to me",+ "variant_my_created": "Created by me",+ "variant_my_involved": "Involved"+ },+ "view_selector": {+ "trigger": "Views",+ "empty": "No saved views yet",+ "private_group": "Private",+ "shared_group": "Shared with workspace",+ "exit": "Exit view",+ "unavailable": "This view is no longer available",+ "edit": "Edit view"+ },+ "view_bar": {+ "menu_label": "Views",+ "menu_new": "New view",+ "builtin_tag": "Built-in",+ "drag_handle": "Drag to reorder",+ "delete": "Delete",+ "delete_title": "Delete view?",+ "delete_description": "“{{name}}” will be deleted for everyone who can see it",+ "toast_deleted": "View deleted",+ "context_edit": "Edit view",+ "context_pin": "Pin to sidebar",+ "context_unpin": "Unpin from sidebar",+ "row_menu": "More actions",+ "row_hide": "Hide from bar",+ "row_show": "Show on bar",+ "menu_manage": "Manage views",+ "manage_title": "Manage views",+ "manage_hint": "Order and visibility only affect you",+ "visible_toggle": "Show in view bar",+ "more_label": "More views"}}diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex daf6e2e464..91243dc36f 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -62,7 +62,15 @@"squads_group": "スクワッド","issue_count_other": "タスク {{count}} 件","reset": "すべてのフィルターをリセット",- "active_count_other": "フィルター {{count}} 件"+ "chip_remove": "{{name}}フィルターを削除",+ "chip_status_count_other": "ステータス{{count}}件",+ "chip_priority_count_other": "優先度{{count}}件",+ "chip_clear": "クリア",+ "chip_save": "保存",+ "active_count_other": "フィルター {{count}} 件",+ "in_view": "このビューに含まれています",+ "chip_edit": "編集",+ "chip_save_as": "別名で保存"},"display": {"tooltip": "表示設定",@@ -667,5 +675,78 @@"row_backlog_hint": "エージェントを一時停止のままにします","row_todo_label": "未着手","row_todo_hint": "エージェントを開始します"+ },+ "save_view": {+ "title": "ビューとして保存",+ "hint_workspace": "ワークスペースの全 issue をもとに作成",+ "hint_my_any": "「マイ issue · すべて」をもとに作成",+ "hint_my_assigned": "「マイ issue · 自分に割り当て」をもとに作成",+ "hint_my_created": "「マイ issue · 自分が作成」をもとに作成",+ "hint_my_involved": "「マイ issue · 関与中」をもとに作成",+ "hint_project": "プロジェクト「{{title}}」をもとに作成(そのプロジェクトページでのみ利用可能)",+ "hint_project_agents": "プロジェクト「{{title}}」のエージェントが担当する issue をもとに作成(そのプロジェクトページでのみ利用可能)",+ "hint_project_members": "プロジェクト「{{title}}」のメンバーが担当する issue をもとに作成(そのプロジェクトページでのみ利用可能)",+ "my_private_note": "マイ issue のビューは自分にのみ表示されます",+ "name_label": "名前",+ "visibility_label": "公開範囲",+ "visibility_private": "自分のみ",+ "visibility_workspace": "ワークスペースのメンバーに表示",+ "filters_label": "フィルター",+ "custom_property": "カスタムプロパティ",+ "create": "ビューを作成",+ "layout_label": "レイアウト",+ "display_defaults": "デフォルト表示",+ "default_hint": "メンバーが最初にこのビューを開いたときの表示。以降は各自で調整できます",+ "add_filter": "フィルターを追加",+ "name_placeholder": "例:レビュー待ち",+ "cancel": "キャンセル",+ "name_required": "ビュー名を入力してください",+ "toast_created": "ビューを作成しました",+ "toast_failed": "ビューの作成に失敗しました",+ "edit_title": "ビューを編集",+ "update": "変更を保存",+ "toast_updated": "ビューを更新しました",+ "toast_conflict": "他のユーザーがこのビューを編集しました。開き直してから再試行してください",+ "hint_workspace_members": "メンバーが担当するワークスペースの issue をもとに作成",+ "hint_workspace_agents": "エージェントが担当するワークスペースの issue をもとに作成",+ "scope_label_workspace": "担当者タイプ",+ "scope_label_my": "自分との関係",+ "variant_all": "担当者を問わない",+ "variant_members": "メンバーに割り当て",+ "variant_agents": "エージェントに割り当て",+ "variant_my_any": "何らかの関わり",+ "variant_my_assigned": "自分に割り当て",+ "variant_my_created": "自分が作成",+ "variant_my_involved": "関与中"+ },+ "view_selector": {+ "trigger": "ビュー",+ "empty": "保存されたビューはまだありません",+ "private_group": "プライベート",+ "shared_group": "ワークスペース共有",+ "exit": "ビューを終了",+ "unavailable": "このビューは利用できなくなりました",+ "edit": "ビューを編集"+ },+ "view_bar": {+ "menu_label": "ビュー",+ "menu_new": "新規ビュー",+ "builtin_tag": "組み込み",+ "drag_handle": "ドラッグで並べ替え",+ "delete": "削除",+ "delete_title": "ビューを削除しますか?",+ "delete_description": "「{{name}}」は閲覧できる全メンバーから削除されます",+ "toast_deleted": "ビューを削除しました",+ "context_edit": "ビューを編集",+ "context_pin": "サイドバーに固定",+ "context_unpin": "サイドバーから固定解除",+ "row_menu": "その他の操作",+ "row_hide": "バーから隠す",+ "row_show": "バーに表示",+ "menu_manage": "ビューを管理",+ "manage_title": "ビューを管理",+ "manage_hint": "並び順と表示設定は自分にのみ適用されます",+ "visible_toggle": "ビューバーに表示",+ "more_label": "その他のビュー"}}diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 2772b49854..4ec5fa272d 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -62,7 +62,15 @@"squads_group": "스쿼드","issue_count_other": "태스크 {{count}}개","reset": "필터 모두 초기화",- "active_count_other": "필터 {{count}}개"+ "chip_remove": "{{name}} 필터 제거",+ "chip_status_count_other": "상태 {{count}}개",+ "chip_priority_count_other": "우선순위 {{count}}개",+ "chip_clear": "지우기",+ "chip_save": "저장",+ "active_count_other": "필터 {{count}}개",+ "in_view": "이미 이 뷰에 포함되어 있습니다",+ "chip_edit": "편집",+ "chip_save_as": "다른 이름으로 저장"},"display": {"tooltip": "보기 설정",@@ -667,5 +675,78 @@"row_backlog_hint": "에이전트를 대기 상태로 유지","row_todo_label": "할 일","row_todo_hint": "에이전트 시작"+ },+ "save_view": {+ "title": "뷰로 저장",+ "hint_workspace": "워크스페이스 전체 이슈 기준으로 생성",+ "hint_my_any": "「내 이슈 · 전체」 기준으로 생성",+ "hint_my_assigned": "「내 이슈 · 나에게 할당됨」 기준으로 생성",+ "hint_my_created": "「내 이슈 · 내가 생성함」 기준으로 생성",+ "hint_my_involved": "「내 이슈 · 참여 중」 기준으로 생성",+ "hint_project": "프로젝트 「{{title}}」 기준으로 생성, 해당 프로젝트 페이지에서만 사용 가능",+ "hint_project_agents": "프로젝트 「{{title}}」에서 에이전트가 담당하는 이슈 기준으로 생성, 해당 프로젝트 페이지에서만 사용 가능",+ "hint_project_members": "프로젝트 「{{title}}」에서 구성원이 담당하는 이슈 기준으로 생성, 해당 프로젝트 페이지에서만 사용 가능",+ "my_private_note": "내 이슈 뷰는 본인에게만 표시됩니다",+ "name_label": "이름",+ "visibility_label": "공개 범위",+ "visibility_private": "나만 보기",+ "visibility_workspace": "워크스페이스 구성원에게 표시",+ "filters_label": "필터",+ "custom_property": "사용자 지정 속성",+ "create": "뷰 만들기",+ "layout_label": "레이아웃",+ "display_defaults": "기본 표시",+ "default_hint": "구성원이 이 뷰를 처음 열 때의 표시 방식이며, 이후 각자 조정할 수 있습니다",+ "add_filter": "필터 추가",+ "name_placeholder": "예: 리뷰 필요",+ "cancel": "취소",+ "name_required": "뷰 이름을 입력하세요",+ "toast_created": "뷰가 생성되었습니다",+ "toast_failed": "뷰 생성에 실패했습니다",+ "edit_title": "뷰 편집",+ "update": "변경 사항 저장",+ "toast_updated": "뷰가 업데이트되었습니다",+ "toast_conflict": "다른 사용자가 이 뷰를 편집했습니다. 다시 연 후 시도하세요",+ "hint_workspace_members": "구성원이 담당하는 워크스페이스 이슈 기준으로 생성",+ "hint_workspace_agents": "에이전트가 담당하는 워크스페이스 이슈 기준으로 생성",+ "scope_label_workspace": "담당자 유형",+ "scope_label_my": "나와의 관계",+ "variant_all": "담당자 무관",+ "variant_members": "구성원에게 할당됨",+ "variant_agents": "에이전트에게 할당됨",+ "variant_my_any": "모든 관련",+ "variant_my_assigned": "나에게 할당됨",+ "variant_my_created": "내가 생성함",+ "variant_my_involved": "참여 중"+ },+ "view_selector": {+ "trigger": "뷰",+ "empty": "저장된 뷰가 아직 없습니다",+ "private_group": "비공개",+ "shared_group": "워크스페이스 공유",+ "exit": "뷰 나가기",+ "unavailable": "이 뷰는 더 이상 사용할 수 없습니다",+ "edit": "뷰 편집"+ },+ "view_bar": {+ "menu_label": "뷰",+ "menu_new": "새 뷰",+ "builtin_tag": "기본 제공",+ "drag_handle": "드래그로 순서 변경",+ "delete": "삭제",+ "delete_title": "뷰를 삭제할까요?",+ "delete_description": "「{{name}}」이(가) 볼 수 있는 모든 구성원에게서 삭제됩니다",+ "toast_deleted": "뷰가 삭제되었습니다",+ "context_edit": "뷰 편집",+ "context_pin": "사이드바에 고정",+ "context_unpin": "사이드바 고정 해제",+ "row_menu": "추가 작업",+ "row_hide": "바에서 숨기기",+ "row_show": "바에 표시",+ "menu_manage": "뷰 관리",+ "manage_title": "뷰 관리",+ "manage_hint": "순서와 표시 설정은 본인에게만 적용됩니다",+ "visible_toggle": "뷰 바에 표시",+ "more_label": "더 많은 뷰"}}diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex bfc1d31463..310b824dfd 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -62,7 +62,15 @@"squads_group": "小队","issue_count_other": "{{count}} 个任务","reset": "重置全部筛选",- "active_count_other": "{{count}} 个筛选"+ "chip_remove": "移除{{name}}筛选",+ "chip_status_count_other": "{{count}} 个状态",+ "chip_priority_count_other": "{{count}} 个优先级",+ "chip_clear": "清除",+ "chip_save": "保存",+ "active_count_other": "{{count}} 个筛选",+ "in_view": "已包含在视图中",+ "chip_edit": "编辑",+ "chip_save_as": "另存"},"display": {"tooltip": "显示设置",@@ -667,5 +675,78 @@"row_backlog_hint": "智能体保持暂停","row_todo_label": "Todo","row_todo_hint": "启动智能体"+ },+ "save_view": {+ "title": "保存为视图",+ "hint_workspace": "基于工作区全部 issues 创建",+ "hint_my_any": "基于「我的 issues · 全部」创建",+ "hint_my_assigned": "基于「我的 issues · 分配给我」创建",+ "hint_my_created": "基于「我的 issues · 我创建的」创建",+ "hint_my_involved": "基于「我的 issues · 我参与的」创建",+ "hint_project": "基于项目「{{title}}」创建,仅在该项目页面可用",+ "hint_project_agents": "基于项目「{{title}}」中智能体负责的 issues 创建,仅在该项目页面可用",+ "hint_project_members": "基于项目「{{title}}」中成员负责的 issues 创建,仅在该项目页面可用",+ "my_private_note": "我的 issues 视图仅自己可见",+ "name_label": "名称",+ "visibility_label": "可见性",+ "visibility_private": "仅自己可见",+ "visibility_workspace": "工作区成员可见",+ "filters_label": "筛选",+ "custom_property": "自定义属性",+ "create": "创建视图",+ "layout_label": "布局",+ "display_defaults": "默认显示",+ "default_hint": "成员首次打开此视图时的显示方式,之后各自可调",+ "add_filter": "添加筛选",+ "name_placeholder": "例如:需要 Review",+ "cancel": "取消",+ "name_required": "请输入视图名称",+ "toast_created": "视图已创建",+ "toast_failed": "创建视图失败",+ "edit_title": "编辑视图",+ "update": "保存修改",+ "toast_updated": "视图已更新",+ "toast_conflict": "视图已被他人修改,请重新打开后再试",+ "hint_workspace_members": "基于工作区中成员负责的 issues 创建",+ "hint_workspace_agents": "基于工作区中智能体负责的 issues 创建",+ "scope_label_workspace": "负责人类型",+ "scope_label_my": "与我的关系",+ "variant_all": "不限负责人",+ "variant_members": "分配给成员",+ "variant_agents": "分配给智能体",+ "variant_my_any": "任何相关",+ "variant_my_assigned": "分配给我",+ "variant_my_created": "我创建的",+ "variant_my_involved": "我参与的"+ },+ "view_selector": {+ "trigger": "视图",+ "empty": "还没有保存的视图",+ "private_group": "私有",+ "shared_group": "工作区共享",+ "exit": "退出视图",+ "unavailable": "该视图已不可用",+ "edit": "编辑视图"+ },+ "view_bar": {+ "menu_label": "视图",+ "menu_new": "新增视图",+ "builtin_tag": "内置",+ "drag_handle": "拖拽排序",+ "delete": "删除",+ "delete_title": "删除视图?",+ "delete_description": "「{{name}}」将对所有可见成员删除",+ "toast_deleted": "视图已删除",+ "context_edit": "编辑视图",+ "context_pin": "固定到侧栏",+ "context_unpin": "从侧栏取消固定",+ "row_menu": "更多操作",+ "row_hide": "在栏中隐藏",+ "row_show": "在栏中显示",+ "menu_manage": "管理视图",+ "manage_title": "管理视图",+ "manage_hint": "排序与显隐只影响你自己",+ "visible_toggle": "在视图栏显示",+ "more_label": "更多视图"}}diff --git a/packages/views/my-issues/components/my-issues-header.tsx b/packages/views/my-issues/components/my-issues-header.tsxindex a7f0c16101..d13fd84e9c 100644--- a/packages/views/my-issues/components/my-issues-header.tsx+++ b/packages/views/my-issues/components/my-issues-header.tsx@@ -1,5 +1,6 @@"use client";+import { useEffect, useState } from "react";import { ChevronDown } from "lucide-react";import { Button } from "@multica/ui/components/ui/button";import {@@ -9,7 +10,6 @@ import {DropdownMenuRadioItem,DropdownMenuTrigger,} from "@multica/ui/components/ui/dropdown-menu";-import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";import type {Issue,IssueTableFacetSpec,@@ -24,6 +24,22 @@ import {IssueDisplayControls,ViewRefreshIndicator,} from "../../issues/components/issues-header";+import { FilterChipsBar } from "../../issues/components/filter-chips-bar";+import { toast } from "sonner";+import { SaveViewDialog, type SaveViewScope } from "../../issues/components/save-view-dialog";+import { useActiveIssueView } from "@multica/core/issue-views/use-active-view";+import { useWorkspaceId } from "@multica/core/hooks";+import { baselineFromQuery } from "@multica/core/issue-views/baseline";+import { ViewBar } from "../../issues/components/view-bar";+import type { IssueView } from "@multica/core/api/schemas";++/** My Issues tab → saved-view scope_variant (API vocabulary). */+const SAVE_VARIANT: Record<MyIssuesScope, Extract<SaveViewScope, { kind: "my" }>["variant"]> = {+ all: "any",+ assigned: "assigned",+ created: "created",+ agents: "involved",+};export function MyIssuesHeader({allIssues,@@ -50,6 +66,24 @@ export function MyIssuesHeader({}) {const { t } = useT("my-issues");const { t: tIssues } = useT("issues");+ const [saveViewOpen, setSaveViewOpen] = useState(false);+ const saveScope: SaveViewScope = { kind: "my", variant: SAVE_VARIANT[scope] };+ const wsId = useWorkspaceId();+ const { activeView, views, viewsReady, setActive, missing } = useActiveIssueView(+ wsId,+ { scope_type: "my" },+ );+ useEffect(() => {+ if (missing) {+ setActive(null);+ toast.info(tIssues(($) => $.view_selector.unavailable));+ }+ }, [missing, setActive, tIssues]);+ const viewBaseline = activeView ? baselineFromQuery(activeView.query) : undefined;+ const [editTarget, setEditTarget] = useState<{+ view: IssueView;+ fromDefinition: boolean;+ } | null>(null);const SCOPES: { value: MyIssuesScope; label: string; description: string }[] = [{ value: "all", label: t(($) => $.header.scope.all_label), description: t(($) => $.header.scope.all_description) },{ value: "assigned", label: t(($) => $.header.scope.assigned_label), description: t(($) => $.header.scope.assigned_description) },@@ -63,30 +97,36 @@ export function MyIssuesHeader({const scopeLabel = SCOPES.find((s) => s.value === scope)?.label ?? SCOPES[0]?.label;return (- <div className="h-12 shrink-0 overflow-x-auto px-4 [-webkit-overflow-scrolling:touch]">- <div className="flex h-full w-max min-w-full items-center justify-between gap-2">- <div className="hidden shrink-0 items-center gap-1 md:flex">- {SCOPES.map((s) => (- <Tooltip key={s.value}>- <TooltipTrigger- render={- <Button- variant="outline"- size="sm"- className={- scope === s.value- ? "bg-accent text-accent-foreground hover:bg-accent/80"- : "text-muted-foreground"- }- onClick={() => onScopeChange(s.value)}- >- {s.label}- </Button>- }- />- <TooltipContent side="bottom">{s.description}</TooltipContent>- </Tooltip>- ))}+ <>+ <div className="min-h-12 shrink-0 px-4 py-2 [-webkit-overflow-scrolling:touch]">+ <div className="flex w-full min-w-0 items-start justify-between gap-2">+ <div className="hidden min-w-0 flex-1 md:block">+ <ViewBar+ wsId={wsId}+ scope={{ scope_type: "my" }}+ builtins={SCOPES.map((s) => ({+ key: s.value,+ label: s.label,+ description: s.description,+ active: !activeView && scope === s.value,+ onSelect: () => {+ if (activeView) setActive(null);+ onScopeChange(s.value);+ },+ }))}+ views={views}+ viewsReady={viewsReady}+ activeView={activeView}+ onSelectView={(view) => setActive(view ? view.id : null)}+ onNewView={() => {+ setEditTarget(null);+ setSaveViewOpen(true);+ }}+ onEditView={(view) => {+ setEditTarget({ view, fromDefinition: true });+ setSaveViewOpen(true);+ }}+ /></div><DropdownMenu>@@ -132,10 +172,29 @@ export function MyIssuesHeader({facetCountsExact={facetCountsExact}tableFacetCounts={tableFacetCounts}onTableFacetChange={onTableFacetChange}+ viewBaseline={viewBaseline}/><ViewRefreshIndicator active={isRefreshing} /></div></div></div>+ <FilterChipsBar+ viewBaseline={viewBaseline}+ saveLabel={activeView ? tIssues(($) => $.filters.chip_edit) : undefined}+ onSave={() => {+ setEditTarget(+ activeView ? { view: activeView, fromDefinition: false } : null,+ );+ setSaveViewOpen(true);+ }}+ />+ <SaveViewDialog+ open={saveViewOpen}+ onOpenChange={setSaveViewOpen}+ scope={saveScope}+ editView={editTarget?.view ?? null}+ seedFromDefinition={editTarget?.fromDefinition ?? false}+ />+ </>);}diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsxindex 6c1327eb00..ed12f5f8ee 100644--- a/packages/views/projects/components/project-detail.tsx+++ b/packages/views/projects/components/project-detail.tsx@@ -15,6 +15,7 @@ import { pinListOptions } from "@multica/core/pins";import { useCreatePin, useDeletePin } from "@multica/core/pins";import { memberListOptions, agentListOptions } from "@multica/core/workspace/queries";import { useWorkspaceId } from "@multica/core/hooks";+import { useIssuesScope } from "@multica/core/issues/stores";import { useRecentContextStore } from "@multica/core/chat";import { useWorkspacePaths } from "@multica/core/paths";import { useActorName } from "@multica/core/workspace/hooks";@@ -119,9 +120,10 @@ export function ProjectDetail({ projectId }: { projectId: string }) {});}}, [project?.id, project?.title, project?.description, project?.icon, project?.status, recordRecentContext, wsId]);+ const issueTab = useIssuesScope(`project:${projectId}`);const issueScope = useMemo(- () => ({ type: "project" as const, projectId }),- [projectId],+ () => ({ type: "project" as const, projectId, actorKind: issueTab }),+ [projectId, issueTab],);const { data: members = [] } = useQuery(memberListOptions(wsId));const { data: agents = [] } = useQuery(agentListOptions(wsId));diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex c2fed60ba6..17b18bf83c 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1451,6 +1451,19 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Delete("/{itemType}/{itemId}", h.DeletePin)})+ // Saved issue views (MUL-4796).+ r.Get("/api/issue-view-preferences", h.GetIssueViewPreference)+ r.Put("/api/issue-view-preferences", h.PutIssueViewPreference)+ r.Route("/api/issue-views", func(r chi.Router) {+ r.Get("/", h.ListIssueViews)+ r.Post("/", h.CreateIssueView)+ r.Route("/{id}", func(r chi.Router) {+ r.Get("/", h.GetIssueViewByID)+ r.Patch("/", h.UpdateIssueView)+ r.Delete("/", h.DeleteIssueView)+ })+ })+// Attachmentsr.Get("/api/attachments/{id}", h.GetAttachmentByID)// /api/attachments/{id}/download is registered in thediff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.goindex a72c667353..881d874ce5 100644--- a/server/internal/handler/issue_table_query.go+++ b/server/internal/handler/issue_table_query.go@@ -432,17 +432,25 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,where = append(where, fmt.Sprintf("i.priority = ANY(%s::text[])", addArg(sortedUniqueStrings(spec.Filters.Priorities))))}- switch spec.Scope.Kind {- case "workspace":+ // Workspace and project scopes share the optional assignee-type+ // narrowing (the Members/Agents tabs above both surfaces).+ appendAssigneeTypes := func() bool {for _, actorType := range spec.Scope.AssigneeTypes {if !isIssueActorType(actorType) {writeError(w, http.StatusBadRequest, "invalid scope.assignee_types")- return issueTableSQL{}, false+ return false}}if len(spec.Scope.AssigneeTypes) > 0 {where = append(where, fmt.Sprintf("i.assignee_type = ANY(%s::text[])", addArg(sortedUniqueStrings(spec.Scope.AssigneeTypes))))}+ return true+ }+ switch spec.Scope.Kind {+ case "workspace":+ if !appendAssigneeTypes() {+ return issueTableSQL{}, false+ }case "project":projectID, err := util.ParseUUID(spec.Scope.ProjectID)if err != nil {@@ -450,6 +458,9 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,return issueTableSQL{}, false}where = append(where, fmt.Sprintf("i.project_id = %s::uuid", addArg(projectID)))+ if !appendAssigneeTypes() {+ return issueTableSQL{}, false+ }case "assignee":if spec.Scope.Actor == nil {writeError(w, http.StatusBadRequest, "scope.actor is required")diff --git a/server/internal/handler/issue_table_query_test.go b/server/internal/handler/issue_table_query_test.goindex d008ab1a4d..799846dcd2 100644--- a/server/internal/handler/issue_table_query_test.go+++ b/server/internal/handler/issue_table_query_test.go@@ -168,6 +168,48 @@ func TestIssueTableExplicitEmptyAssigneesMatchesNone(t *testing.T) {}}+func TestIssueTableProjectScopeAssigneeTypes(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ spec := issueTableQuerySpec{+ Scope: issueTableScope{+ Kind: "project",+ ProjectID: "00000000-0000-0000-0000-000000000001",+ AssigneeTypes: []string{"agent", "squad"},+ },+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},+ }++ w := httptest.NewRecorder()+ compiled, ok := testHandler.compileIssueTableQuery(+ w,+ newRequest(http.MethodPost, "/api/issues/table/rows", nil),+ spec,+ )+ if !ok {+ t.Fatalf("compile failed: %d %s", w.Code, w.Body.String())+ }+ if !strings.Contains(compiled.where, "i.project_id") {+ t.Fatalf("project predicate missing: %q", compiled.where)+ }+ if !strings.Contains(compiled.where, "i.assignee_type = ANY") {+ t.Fatalf("assignee-type narrowing missing on project scope: %q", compiled.where)+ }++ bad := spec+ bad.Scope.AssigneeTypes = []string{"martian"}+ w = httptest.NewRecorder()+ if _, ok := testHandler.compileIssueTableQuery(+ w,+ newRequest(http.MethodPost, "/api/issues/table/rows", nil),+ bad,+ ); ok {+ t.Fatal("invalid assignee_types must be rejected on project scope")+ }+}+func TestIssueTableWorkingIssueIDsAreExplicitAndAssigneeIndependent(t *testing.T) {if testHandler == nil {t.Skip("database not available")diff --git a/server/internal/handler/issue_view.go b/server/internal/handler/issue_view.gonew file mode 100644index 0000000000..d6b79fdd5f--- /dev/null+++ b/server/internal/handler/issue_view.go@@ -0,0 +1,449 @@+package handler++import (+ "encoding/json"+ "errors"+ "net/http"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Saved issue views (MUL-4796): server-backed filter definitions with+// display defaults. `query` is the shared identity of a view; `display`+// only seeds a member's first open. Both are opaque JSON to the server —+// interpretation lives in the client definition_version contract.++const issueViewNameMaxLen = 80++// issueViewBodyMaxBytes bounds every saved-view write. The query/display+// blobs are filter documents — real ones are a few KB; the cap is the+// abuse backstop, comfortably above any legitimate payload.+const issueViewBodyMaxBytes = 128 * 1024++// issueViewsPerOwnerMax bounds table growth per member per workspace.+const issueViewsPerOwnerMax = 100++var (+ validIssueViewScopeTypes = []string{"workspace", "my", "project"}+ validIssueViewMyVariants = []string{"assigned", "created", "involved", "any"}+ validIssueViewWorkspaceVariants = []string{"members", "agents"}+ validIssueViewVisibilities = []string{"private", "workspace"}+)++// validateIssueViewVariant returns the pgtype value for a scope_variant+// input under the given scope_type, or ok=false when the pairing is+// invalid. Workspace and project variants are optional assignee-type+// narrowing (NULL = the unrestricted All tab); my variants are required.+func validateIssueViewVariant(scopeType string, variant *string) (pgtype.Text, bool) {+ switch scopeType {+ case "my":+ if variant == nil || !contains(validIssueViewMyVariants, *variant) {+ return pgtype.Text{}, false+ }+ return pgtype.Text{String: *variant, Valid: true}, true+ default: // workspace, project+ if variant == nil || *variant == "" || *variant == "all" {+ return pgtype.Text{}, true+ }+ if !contains(validIssueViewWorkspaceVariants, *variant) {+ return pgtype.Text{}, false+ }+ return pgtype.Text{String: *variant, Valid: true}, true+ }+}++type IssueViewResponse struct {+ ID string `json:"id"`+ WorkspaceID string `json:"workspace_id"`+ OwnerID string `json:"owner_id"`+ Name string `json:"name"`+ ScopeType string `json:"scope_type"`+ ScopeID *string `json:"scope_id"`+ ScopeVariant *string `json:"scope_variant"`+ Visibility string `json:"visibility"`+ DefinitionVersion int32 `json:"definition_version"`+ Query json.RawMessage `json:"query"`+ Display json.RawMessage `json:"display"`+ Revision int32 `json:"revision"`+ CreatedAt string `json:"created_at"`+ UpdatedAt string `json:"updated_at"`+}++func issueViewToResponse(v db.IssueView) IssueViewResponse {+ return IssueViewResponse{+ ID: uuidToString(v.ID),+ WorkspaceID: uuidToString(v.WorkspaceID),+ OwnerID: uuidToString(v.OwnerID),+ Name: v.Name,+ ScopeType: v.ScopeType,+ ScopeID: uuidToPtr(v.ScopeID),+ ScopeVariant: textToPtr(v.ScopeVariant),+ Visibility: v.Visibility,+ DefinitionVersion: v.DefinitionVersion,+ Query: json.RawMessage(v.Query),+ Display: json.RawMessage(v.Display),+ Revision: v.Revision,+ CreatedAt: timestampToString(v.CreatedAt),+ UpdatedAt: timestampToString(v.UpdatedAt),+ }+}++// canReadIssueView: owner always; workspace-shared views for any member.+// (My-scope views are constrained to private by the DB CHECK, so they only+// ever match the owner branch.)+func canReadIssueView(v db.IssueView, userID pgtype.UUID) bool {+ return v.OwnerID == userID || v.Visibility == "workspace"+}++func isJSONObject(raw json.RawMessage) bool {+ var m map[string]json.RawMessage+ if json.Unmarshal(raw, &m) != nil {+ return false+ }+ // JSON null unmarshals into a nil map without error — reject it here+ // instead of letting the DB CHECK turn it into a 500.+ return m != nil+}++type CreateIssueViewRequest struct {+ Name string `json:"name"`+ ScopeType string `json:"scope_type"`+ ScopeID *string `json:"scope_id"`+ ScopeVariant *string `json:"scope_variant"`+ Visibility string `json:"visibility"`+ DefinitionVersion int32 `json:"definition_version"`+ Query json.RawMessage `json:"query"`+ Display json.RawMessage `json:"display"`+}++func (h *Handler) CreateIssueView(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, h.resolveWorkspaceID(r), "workspace id")+ if !ok {+ return+ }++ var req CreateIssueViewRequest+ r.Body = http.MaxBytesReader(w, r.Body, issueViewBodyMaxBytes)+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if l := len([]rune(req.Name)); l < 1 || l > issueViewNameMaxLen {+ writeError(w, http.StatusBadRequest, "name must be between 1 and 80 characters")+ return+ }+ ownedCount, err := h.Queries.CountIssueViewsByOwner(r.Context(), db.CountIssueViewsByOwnerParams{+ WorkspaceID: wsUUID,+ OwnerID: parseUUID(userID),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to check view quota")+ return+ }+ if ownedCount >= issueViewsPerOwnerMax {+ writeError(w, http.StatusBadRequest, "view limit reached for this workspace")+ return+ }+ if !contains(validIssueViewScopeTypes, req.ScopeType) {+ writeError(w, http.StatusBadRequest, "invalid scope_type")+ return+ }+ if req.Visibility == "" {+ req.Visibility = "private"+ }+ if !contains(validIssueViewVisibilities, req.Visibility) {+ writeError(w, http.StatusBadRequest, "invalid visibility")+ return+ }+ if req.DefinitionVersion <= 0 {+ req.DefinitionVersion = 1+ }+ if len(req.Query) == 0 || !isJSONObject(req.Query) {+ writeError(w, http.StatusBadRequest, "query must be a JSON object")+ return+ }+ if len(req.Display) == 0 {+ req.Display = json.RawMessage("{}")+ }+ if !isJSONObject(req.Display) {+ writeError(w, http.StatusBadRequest, "display must be a JSON object")+ return+ }++ scopeVariant, variantOK := validateIssueViewVariant(req.ScopeType, req.ScopeVariant)+ if !variantOK {+ writeError(w, http.StatusBadRequest, "invalid scope_variant for this scope_type")+ return+ }+ var scopeID pgtype.UUID+ switch req.ScopeType {+ case "project":+ if req.ScopeID == nil {+ writeError(w, http.StatusBadRequest, "scope_id is required for project views")+ return+ }+ projUUID, ok := parseUUIDOrBadRequest(w, *req.ScopeID, "scope_id")+ if !ok {+ return+ }+ // The project must exist in this workspace — a view on a foreign or+ // deleted project would be unreachable and could leak across tenants.+ if _, err := h.Queries.GetProjectInWorkspace(r.Context(), db.GetProjectInWorkspaceParams{+ ID: projUUID, WorkspaceID: wsUUID,+ }); err != nil {+ writeError(w, http.StatusNotFound, "project not found")+ return+ }+ scopeID = projUUID+ case "my":+ // My Issues is a per-user perspective; sharing it is meaningless.+ req.Visibility = "private"+ }++ view, err := h.Queries.CreateIssueView(r.Context(), db.CreateIssueViewParams{+ WorkspaceID: wsUUID,+ OwnerID: parseUUID(userID),+ Name: req.Name,+ ScopeType: req.ScopeType,+ ScopeID: scopeID,+ ScopeVariant: scopeVariant,+ Visibility: req.Visibility,+ DefinitionVersion: req.DefinitionVersion,+ Query: req.Query,+ Display: req.Display,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to create view")+ return+ }+ writeJSON(w, http.StatusCreated, issueViewToResponse(view))+}++func (h *Handler) ListIssueViews(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, h.resolveWorkspaceID(r), "workspace id")+ if !ok {+ return+ }++ scopeType := r.URL.Query().Get("scope_type")+ if !contains(validIssueViewScopeTypes, scopeType) {+ writeError(w, http.StatusBadRequest, "invalid scope_type")+ return+ }+ var scopeID pgtype.UUID+ if raw := r.URL.Query().Get("scope_id"); raw != "" {+ id, ok := parseUUIDOrBadRequest(w, raw, "scope_id")+ if !ok {+ return+ }+ scopeID = id+ }++ views, err := h.Queries.ListIssueViewsForUser(r.Context(), db.ListIssueViewsForUserParams{+ WorkspaceID: wsUUID,+ ScopeType: scopeType,+ OwnerID: parseUUID(userID),+ ScopeID: scopeID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list views")+ return+ }+ resp := make([]IssueViewResponse, len(views))+ for i, v := range views {+ resp[i] = issueViewToResponse(v)+ }+ writeJSON(w, http.StatusOK, resp)+}++// loadIssueViewForUser resolves the id, enforces workspace scoping, and+// applies read authorization. Unauthorized and missing are both 404 so a+// private view's existence never leaks.+func (h *Handler) loadIssueViewForUser(w http.ResponseWriter, r *http.Request, userID string) (db.IssueView, pgtype.UUID, bool) {+ wsUUID, ok := parseUUIDOrBadRequest(w, h.resolveWorkspaceID(r), "workspace id")+ if !ok {+ return db.IssueView{}, pgtype.UUID{}, false+ }+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "view id")+ if !ok {+ return db.IssueView{}, pgtype.UUID{}, false+ }+ view, err := h.Queries.GetIssueView(r.Context(), db.GetIssueViewParams{+ ID: idUUID, WorkspaceID: wsUUID,+ })+ if err != nil || !canReadIssueView(view, parseUUID(userID)) {+ writeError(w, http.StatusNotFound, "view not found")+ return db.IssueView{}, pgtype.UUID{}, false+ }+ return view, wsUUID, true+}++func (h *Handler) GetIssueViewByID(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ view, _, ok := h.loadIssueViewForUser(w, r, userID)+ if !ok {+ return+ }+ writeJSON(w, http.StatusOK, issueViewToResponse(view))+}++// canManageIssueView: the owner, or a workspace admin/owner for shared+// views. Private views of others are invisible (404 in the loader), so+// admin powers never reach them.+func (h *Handler) canManageIssueView(r *http.Request, view db.IssueView, userID string) bool {+ if view.OwnerID == parseUUID(userID) {+ return true+ }+ if view.Visibility != "workspace" {+ return false+ }+ member, err := h.Queries.GetMemberByUserAndWorkspace(r.Context(), db.GetMemberByUserAndWorkspaceParams{+ UserID: parseUUID(userID),+ WorkspaceID: view.WorkspaceID,+ })+ if err != nil {+ return false+ }+ return roleAllowed(member.Role, "owner", "admin")+}++type UpdateIssueViewRequest struct {+ Name *string `json:"name"`+ Visibility *string `json:"visibility"`+ ScopeVariant *string `json:"scope_variant"`+ Query json.RawMessage `json:"query"`+ Display json.RawMessage `json:"display"`+ ExpectedRevision int32 `json:"expected_revision"`+}++func (h *Handler) UpdateIssueView(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ view, wsUUID, ok := h.loadIssueViewForUser(w, r, userID)+ if !ok {+ return+ }+ if !h.canManageIssueView(r, view, userID) {+ writeError(w, http.StatusForbidden, "insufficient permissions")+ return+ }++ var req UpdateIssueViewRequest+ r.Body = http.MaxBytesReader(w, r.Body, issueViewBodyMaxBytes)+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if req.ExpectedRevision <= 0 {+ writeError(w, http.StatusBadRequest, "expected_revision is required")+ return+ }++ name := view.Name+ if req.Name != nil {+ if l := len([]rune(*req.Name)); l < 1 || l > issueViewNameMaxLen {+ writeError(w, http.StatusBadRequest, "name must be between 1 and 80 characters")+ return+ }+ name = *req.Name+ }+ visibility := view.Visibility+ if req.Visibility != nil {+ if !contains(validIssueViewVisibilities, *req.Visibility) {+ writeError(w, http.StatusBadRequest, "invalid visibility")+ return+ }+ if view.ScopeType == "my" && *req.Visibility != "private" {+ writeError(w, http.StatusBadRequest, "my views are always private")+ return+ }+ visibility = *req.Visibility+ }+ query := json.RawMessage(view.Query)+ if len(req.Query) > 0 {+ if !isJSONObject(req.Query) {+ writeError(w, http.StatusBadRequest, "query must be a JSON object")+ return+ }+ query = req.Query+ }+ display := json.RawMessage(view.Display)+ if len(req.Display) > 0 {+ if !isJSONObject(req.Display) {+ writeError(w, http.StatusBadRequest, "display must be a JSON object")+ return+ }+ display = req.Display+ }+ // scope_type itself is immutable; the variant within it may switch.+ scopeVariant := view.ScopeVariant+ if req.ScopeVariant != nil {+ next, variantOK := validateIssueViewVariant(view.ScopeType, req.ScopeVariant)+ if !variantOK {+ writeError(w, http.StatusBadRequest, "invalid scope_variant for this scope_type")+ return+ }+ scopeVariant = next+ }++ updated, err := h.Queries.UpdateIssueView(r.Context(), db.UpdateIssueViewParams{+ ID: view.ID,+ WorkspaceID: wsUUID,+ Name: name,+ Visibility: visibility,+ ScopeVariant: scopeVariant,+ Query: query,+ Display: display,+ Revision: req.ExpectedRevision,+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ // The row exists (we just loaded it) — zero rows means the+ // revision moved underneath the caller.+ writeError(w, http.StatusConflict, "view was modified by someone else")+ return+ }+ writeError(w, http.StatusInternalServerError, "failed to update view")+ return+ }+ writeJSON(w, http.StatusOK, issueViewToResponse(updated))+}++func (h *Handler) DeleteIssueView(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ view, wsUUID, ok := h.loadIssueViewForUser(w, r, userID)+ if !ok {+ return+ }+ if !h.canManageIssueView(r, view, userID) {+ writeError(w, http.StatusForbidden, "insufficient permissions")+ return+ }+ if _, err := h.Queries.DeleteIssueView(r.Context(), db.DeleteIssueViewParams{+ ID: view.ID, WorkspaceID: wsUUID,+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete view")+ return+ }+ w.WriteHeader(http.StatusNoContent)+}diff --git a/server/internal/handler/issue_view_preference.go b/server/internal/handler/issue_view_preference.gonew file mode 100644index 0000000000..be99cd00b0--- /dev/null+++ b/server/internal/handler/issue_view_preference.go@@ -0,0 +1,155 @@+package handler++import (+ "encoding/json"+ "errors"+ "net/http"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Per-user view-bar preferences (hidden items + order) for one surface+// container. The prefs document is client-owned and opaque here beyond+// being a JSON object; item ids inside are "builtin:<key>" / "view:<uuid>".++// resolvePreferenceScope validates scope params and backfills scope_id so+// the composite key never carries NULL: workspace scope uses the workspace+// id, my scope the user id, project scope the project id (validated).+func (h *Handler) resolvePreferenceScope(+ w http.ResponseWriter, r *http.Request,+ wsUUID pgtype.UUID, userID string, scopeType, rawScopeID string,+) (pgtype.UUID, bool) {+ switch scopeType {+ case "workspace":+ return wsUUID, true+ case "my":+ return parseUUID(userID), true+ case "project":+ if rawScopeID == "" {+ writeError(w, http.StatusBadRequest, "scope_id is required for project scope")+ return pgtype.UUID{}, false+ }+ projUUID, ok := parseUUIDOrBadRequest(w, rawScopeID, "scope_id")+ if !ok {+ return pgtype.UUID{}, false+ }+ if _, err := h.Queries.GetProjectInWorkspace(r.Context(), db.GetProjectInWorkspaceParams{+ ID: projUUID, WorkspaceID: wsUUID,+ }); err != nil {+ writeError(w, http.StatusNotFound, "project not found")+ return pgtype.UUID{}, false+ }+ return projUUID, true+ default:+ writeError(w, http.StatusBadRequest, "invalid scope_type")+ return pgtype.UUID{}, false+ }+}++type IssueViewPreferenceResponse struct {+ ScopeType string `json:"scope_type"`+ ScopeID *string `json:"scope_id"`+ Prefs json.RawMessage `json:"prefs"`+ UpdatedAt string `json:"updated_at"`+}++func (h *Handler) GetIssueViewPreference(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, h.resolveWorkspaceID(r), "workspace id")+ if !ok {+ return+ }+ scopeType := r.URL.Query().Get("scope_type")+ scopeID, ok := h.resolvePreferenceScope(w, r, wsUUID, userID, scopeType, r.URL.Query().Get("scope_id"))+ if !ok {+ return+ }++ pref, err := h.Queries.GetIssueViewPreference(r.Context(), db.GetIssueViewPreferenceParams{+ WorkspaceID: wsUUID,+ UserID: parseUUID(userID),+ ScopeType: scopeType,+ ScopeID: scopeID,+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ // No row yet — an empty document, not an error.+ writeJSON(w, http.StatusOK, IssueViewPreferenceResponse{+ ScopeType: scopeType,+ ScopeID: uuidToPtr(scopeID),+ Prefs: json.RawMessage("{}"),+ })+ return+ }+ writeError(w, http.StatusInternalServerError, "failed to load preference")+ return+ }+ writeJSON(w, http.StatusOK, IssueViewPreferenceResponse{+ ScopeType: pref.ScopeType,+ ScopeID: uuidToPtr(pref.ScopeID),+ Prefs: json.RawMessage(pref.Prefs),+ UpdatedAt: timestampToString(pref.UpdatedAt),+ })+}++type PutIssueViewPreferenceRequest struct {+ ScopeType string `json:"scope_type"`+ ScopeID *string `json:"scope_id"`+ Prefs json.RawMessage `json:"prefs"`+}++func (h *Handler) PutIssueViewPreference(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ wsUUID, ok := parseUUIDOrBadRequest(w, h.resolveWorkspaceID(r), "workspace id")+ if !ok {+ return+ }+ var req PutIssueViewPreferenceRequest+ r.Body = http.MaxBytesReader(w, r.Body, issueViewBodyMaxBytes)+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ rawScopeID := ""+ if req.ScopeID != nil {+ rawScopeID = *req.ScopeID+ }+ scopeID, ok := h.resolvePreferenceScope(w, r, wsUUID, userID, req.ScopeType, rawScopeID)+ if !ok {+ return+ }+ if len(req.Prefs) == 0 {+ req.Prefs = json.RawMessage("{}")+ }+ if !isJSONObject(req.Prefs) {+ writeError(w, http.StatusBadRequest, "prefs must be a JSON object")+ return+ }++ pref, err := h.Queries.UpsertIssueViewPreference(r.Context(), db.UpsertIssueViewPreferenceParams{+ WorkspaceID: wsUUID,+ UserID: parseUUID(userID),+ ScopeType: req.ScopeType,+ ScopeID: scopeID,+ Prefs: req.Prefs,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to save preference")+ return+ }+ writeJSON(w, http.StatusOK, IssueViewPreferenceResponse{+ ScopeType: pref.ScopeType,+ ScopeID: uuidToPtr(pref.ScopeID),+ Prefs: json.RawMessage(pref.Prefs),+ UpdatedAt: timestampToString(pref.UpdatedAt),+ })+}diff --git a/server/internal/handler/issue_view_preference_test.go b/server/internal/handler/issue_view_preference_test.gonew file mode 100644index 0000000000..51a3d58d20--- /dev/null+++ b/server/internal/handler/issue_view_preference_test.go@@ -0,0 +1,98 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestIssueViewPreferenceRoundTrip(t *testing.T) {+ t.Cleanup(func() {+ testPool.Exec(context.Background(),+ `DELETE FROM issue_view_preference WHERE workspace_id = $1`, testWorkspaceID)+ })++ // Empty document before any write.+ w := httptest.NewRecorder()+ testHandler.GetIssueViewPreference(w, newRequest("GET", "/api/issue-view-preferences?scope_type=workspace", nil))+ if w.Code != http.StatusOK {+ t.Fatalf("get(empty): expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var got IssueViewPreferenceResponse+ json.NewDecoder(w.Body).Decode(&got)+ if string(got.Prefs) != "{}" {+ t.Fatalf("expected empty prefs doc, got %s", got.Prefs)+ }++ // Upsert then read back.+ prefs := map[string]any{+ "hidden": []string{"builtin:members"},+ "order": []string{"builtin:all", "view:abc"},+ }+ w = httptest.NewRecorder()+ testHandler.PutIssueViewPreference(w, newRequest("PUT", "/api/issue-view-preferences", map[string]any{+ "scope_type": "workspace",+ "prefs": prefs,+ }))+ if w.Code != http.StatusOK {+ t.Fatalf("put: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ w = httptest.NewRecorder()+ testHandler.GetIssueViewPreference(w, newRequest("GET", "/api/issue-view-preferences?scope_type=workspace", nil))+ json.NewDecoder(w.Body).Decode(&got)+ var round map[string]any+ json.Unmarshal(got.Prefs, &round)+ if hidden, _ := round["hidden"].([]any); len(hidden) != 1 || hidden[0] != "builtin:members" {+ t.Fatalf("round-trip lost hidden: %s", got.Prefs)+ }++ // Second write replaces wholesale (last-write-wins).+ w = httptest.NewRecorder()+ testHandler.PutIssueViewPreference(w, newRequest("PUT", "/api/issue-view-preferences", map[string]any{+ "scope_type": "workspace",+ "prefs": map[string]any{"hidden": []string{}},+ }))+ if w.Code != http.StatusOK {+ t.Fatalf("put2: expected 200, got %d", w.Code)+ }+ w = httptest.NewRecorder()+ testHandler.GetIssueViewPreference(w, newRequest("GET", "/api/issue-view-preferences?scope_type=workspace", nil))+ json.NewDecoder(w.Body).Decode(&got)+ // Fresh map: Unmarshal into a populated map merges keys instead of+ // replacing them, which would fake a stale `order` here.+ round = nil+ json.Unmarshal(got.Prefs, &round)+ if _, hasOrder := round["order"]; hasOrder {+ t.Fatalf("expected wholesale replace to drop order, got %s", got.Prefs)+ }+}++func TestIssueViewPreferenceIsPerUser(t *testing.T) {+ t.Cleanup(func() {+ testPool.Exec(context.Background(),+ `DELETE FROM issue_view_preference WHERE workspace_id = $1`, testWorkspaceID)+ })++ w := httptest.NewRecorder()+ testHandler.PutIssueViewPreference(w, newRequest("PUT", "/api/issue-view-preferences", map[string]any{+ "scope_type": "workspace",+ "prefs": map[string]any{"hidden": []string{"view:x"}},+ }))+ if w.Code != http.StatusOK {+ t.Fatalf("put: expected 200, got %d", w.Code)+ }++ otherID := createSecondWorkspaceMember(t)+ w = httptest.NewRecorder()+ req := newRequest("GET", "/api/issue-view-preferences?scope_type=workspace", nil)+ req.Header.Set("X-User-ID", otherID)+ testHandler.GetIssueViewPreference(w, req)+ var got IssueViewPreferenceResponse+ json.NewDecoder(w.Body).Decode(&got)+ if string(got.Prefs) != "{}" {+ t.Fatalf("another member must not inherit my prefs, got %s", got.Prefs)+ }+}diff --git a/server/internal/handler/issue_view_test.go b/server/internal/handler/issue_view_test.gonew file mode 100644index 0000000000..05674f61a5--- /dev/null+++ b/server/internal/handler/issue_view_test.go@@ -0,0 +1,616 @@+package handler++import (+ "strings"+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"++)++func createIssueViewForTest(t *testing.T, body map[string]any) (IssueViewResponse, int, string) {+ t.Helper()+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/issue-views", body)+ testHandler.CreateIssueView(w, req)+ var view IssueViewResponse+ if w.Code == http.StatusCreated {+ json.NewDecoder(w.Body).Decode(&view)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue_view WHERE id = $1`, view.ID)+ })+ }+ return view, w.Code, w.Body.String()+}++func TestCreateAndListIssueView(t *testing.T) {++ view, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Needs review",+ "scope_type": "workspace",+ "visibility": "workspace",+ "query": map[string]any{"statusFilters": []string{"in_review"}},+ "display": map[string]any{"viewMode": "board"},+ })+ if code != http.StatusCreated {+ t.Fatalf("create: expected 201, got %d: %s", code, body)+ }+ if view.Revision != 1 || view.DefinitionVersion != 1 {+ t.Fatalf("expected revision=1 definition_version=1, got %d/%d", view.Revision, view.DefinitionVersion)+ }+ if view.Visibility != "workspace" {+ t.Fatalf("expected workspace visibility, got %s", view.Visibility)+ }++ w := httptest.NewRecorder()+ testHandler.ListIssueViews(w, newRequest("GET", "/api/issue-views?scope_type=workspace", nil))+ if w.Code != http.StatusOK {+ t.Fatalf("list: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var views []IssueViewResponse+ json.NewDecoder(w.Body).Decode(&views)+ found := false+ for _, v := range views {+ if v.ID == view.ID {+ found = true+ }+ }+ if !found {+ t.Fatalf("created view %s missing from list", view.ID)+ }+}++func TestMyIssueViewForcedPrivate(t *testing.T) {++ view, code, body := createIssueViewForTest(t, map[string]any{+ "name": "My assigned",+ "scope_type": "my",+ "scope_variant": "assigned",+ "visibility": "workspace", // must be overridden+ "query": map[string]any{},+ })+ if code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", code, body)+ }+ if view.Visibility != "private" {+ t.Fatalf("my view must be forced private, got %s", view.Visibility)+ }+ if view.ScopeVariant == nil || *view.ScopeVariant != "assigned" {+ t.Fatalf("scope_variant not persisted: %+v", view.ScopeVariant)+ }+}++func TestIssueViewPrivateInvisibleToOthers(t *testing.T) {++ view, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Mine only",+ "scope_type": "workspace",+ "visibility": "private",+ "query": map[string]any{},+ })+ if code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", code, body)+ }++ // A second member of the same workspace must neither list nor fetch it.+ otherID := createSecondWorkspaceMember(t)++ w := httptest.NewRecorder()+ req := newRequest("GET", "/api/issue-views?scope_type=workspace", nil)+ req.Header.Set("X-User-ID", otherID)+ testHandler.ListIssueViews(w, req)+ var views []IssueViewResponse+ json.NewDecoder(w.Body).Decode(&views)+ for _, v := range views {+ if v.ID == view.ID {+ t.Fatalf("private view leaked into another member's list")+ }+ }++ w = httptest.NewRecorder()+ req = newRequest("GET", "/api/issue-views/"+view.ID, nil)+ req.Header.Set("X-User-ID", otherID)+ req = withURLParam(req, "id", view.ID)+ testHandler.GetIssueViewByID(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404 for foreign private view, got %d", w.Code)+ }+}++func TestUpdateIssueViewRevisionConflict(t *testing.T) {++ view, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Conflict target",+ "scope_type": "workspace",+ "query": map[string]any{},+ })+ if code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", code, body)+ }++ patch := func(rev int32, name string) int {+ w := httptest.NewRecorder()+ req := newRequest("PATCH", "/api/issue-views/"+view.ID, map[string]any{+ "name": name,+ "expected_revision": rev,+ })+ req = withURLParam(req, "id", view.ID)+ testHandler.UpdateIssueView(w, req)+ return w.Code+ }++ if got := patch(1, "First rename"); got != http.StatusOK {+ t.Fatalf("first patch: expected 200, got %d", got)+ }+ // Same expected_revision again → the row is at revision 2 now.+ if got := patch(1, "Stale rename"); got != http.StatusConflict {+ t.Fatalf("stale patch: expected 409, got %d", got)+ }+ if got := patch(2, "Second rename"); got != http.StatusOK {+ t.Fatalf("fresh patch: expected 200, got %d", got)+ }+}++// createSecondWorkspaceMember inserts another user + membership in the test+// workspace and returns the user id.+func createSecondWorkspaceMember(t *testing.T) string {+ t.Helper()+ ctx := context.Background()+ var userID string+ email := fmt.Sprintf("issue-view-other-%[email protected]", t.Name())+ if err := testPool.QueryRow(ctx, `+ INSERT INTO "user" (email, name) VALUES ($1, 'View Other')+ ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name+ RETURNING id+ `, email).Scan(&userID); err != nil {+ t.Fatalf("create second user: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')+ ON CONFLICT DO NOTHING+ `, testWorkspaceID, userID); err != nil {+ t.Fatalf("create second membership: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, userID)+ testPool.Exec(ctx, `DELETE FROM "user" WHERE id = $1`, userID)+ })+ return userID+}++func TestWorkspaceIssueViewVariant(t *testing.T) {++ // Save from the Agents tab: variant persists.+ view, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Agent work",+ "scope_type": "workspace",+ "scope_variant": "agents",+ "query": map[string]any{},+ })+ if code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", code, body)+ }+ if view.ScopeVariant == nil || *view.ScopeVariant != "agents" {+ t.Fatalf("workspace variant not persisted: %+v", view.ScopeVariant)+ }++ // "all" normalizes to NULL (no restriction).+ view2, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Everything",+ "scope_type": "workspace",+ "scope_variant": "all",+ "query": map[string]any{},+ })+ if code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", code, body)+ }+ if view2.ScopeVariant != nil {+ t.Fatalf("'all' must normalize to NULL, got %v", *view2.ScopeVariant)+ }++ // My-only variants are rejected on workspace views.+ _, code, _ = createIssueViewForTest(t, map[string]any{+ "name": "Bad variant",+ "scope_type": "workspace",+ "scope_variant": "assigned",+ "query": map[string]any{},+ })+ if code != http.StatusBadRequest {+ t.Fatalf("expected 400 for my-variant on workspace view, got %d", code)+ }++ // Switching the variant via PATCH works; the scope_type stays fixed.+ w := httptest.NewRecorder()+ req := newRequest("PATCH", "/api/issue-views/"+view.ID, map[string]any{+ "scope_variant": "members",+ "expected_revision": 1,+ })+ req = withURLParam(req, "id", view.ID)+ testHandler.UpdateIssueView(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("patch variant: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var updated IssueViewResponse+ json.NewDecoder(w.Body).Decode(&updated)+ if updated.ScopeVariant == nil || *updated.ScopeVariant != "members" {+ t.Fatalf("variant switch lost: %+v", updated.ScopeVariant)+ }+}++func TestProjectIssueViewVariant(t *testing.T) {++ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{+ "title": "variant project",+ })+ testHandler.CreateProject(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("create project: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var project ProjectResponse+ if err := json.NewDecoder(w.Body).Decode(&project); err != nil {+ t.Fatalf("decode CreateProject: %v", err)+ }+ t.Cleanup(func() {+ req := newRequest("DELETE", "/api/projects/"+project.ID, nil)+ req = withURLParam(req, "id", project.ID)+ testHandler.DeleteProject(httptest.NewRecorder(), req)+ })++ // Save from the project page's Members tab: variant persists.+ view, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Member work",+ "scope_type": "project",+ "scope_id": project.ID,+ "scope_variant": "members",+ "query": map[string]any{},+ })+ if code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", code, body)+ }+ if view.ScopeVariant == nil || *view.ScopeVariant != "members" {+ t.Fatalf("project variant not persisted: %+v", view.ScopeVariant)+ }++ // "all" normalizes to NULL, same as workspace views.+ view2, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Whole project",+ "scope_type": "project",+ "scope_id": project.ID,+ "scope_variant": "all",+ "query": map[string]any{},+ })+ if code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", code, body)+ }+ if view2.ScopeVariant != nil {+ t.Fatalf("'all' must normalize to NULL, got %v", *view2.ScopeVariant)+ }++ // My-only variants are rejected on project views.+ _, code, _ = createIssueViewForTest(t, map[string]any{+ "name": "Bad variant",+ "scope_type": "project",+ "scope_id": project.ID,+ "scope_variant": "involved",+ "query": map[string]any{},+ })+ if code != http.StatusBadRequest {+ t.Fatalf("expected 400 for my-variant on project view, got %d", code)+ }+}++func TestPinIssueView(t *testing.T) {++ shared, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Pinnable",+ "scope_type": "workspace",+ "visibility": "workspace",+ "query": map[string]any{},+ })+ if code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", code, body)+ }+ private, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Secret",+ "scope_type": "workspace",+ "visibility": "private",+ "query": map[string]any{},+ })+ if code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", code, body)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM pinned_item WHERE item_type = 'view'`)+ })++ pinView := func(userID, viewID string) int {+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/pins", map[string]any{+ "item_type": "view",+ "item_id": viewID,+ })+ if userID != "" {+ req.Header.Set("X-User-ID", userID)+ }+ testHandler.CreatePin(w, req)+ return w.Code+ }++ // Shared view: any member can pin it.+ if got := pinView("", shared.ID); got != http.StatusCreated {+ t.Fatalf("pin shared view: expected 201, got %d", got)+ }+ // Own private view: pinnable by its owner.+ if got := pinView("", private.ID); got != http.StatusCreated {+ t.Fatalf("pin own private view: expected 201, got %d", got)+ }+ // Foreign private view: 404 — a pin must not confirm its existence.+ otherID := createSecondWorkspaceMember(t)+ if got := pinView(otherID, private.ID); got != http.StatusNotFound {+ t.Fatalf("pin foreign private view: expected 404, got %d", got)+ }+ // Unknown type still rejected.+ w := httptest.NewRecorder()+ testHandler.CreatePin(w, newRequest("POST", "/api/pins", map[string]any{+ "item_type": "label",+ "item_id": shared.ID,+ }))+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for unknown item_type, got %d", w.Code)+ }+}++// Old clients (built before saved views) classify every non-issue pin as a+// project pin and permanently auto-unpin it on a 404 — the legacy list+// contract must therefore never expose view pins without the capability+// opt-in.+func TestListPinsHidesViewPinsWithoutOptIn(t *testing.T) {++ view, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Pinned for compat",+ "scope_type": "workspace",+ "visibility": "workspace",+ "query": map[string]any{},+ })+ if code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", code, body)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM pinned_item WHERE item_type = 'view'`)+ })++ w := httptest.NewRecorder()+ testHandler.CreatePin(w, newRequest("POST", "/api/pins", map[string]any{+ "item_type": "view",+ "item_id": view.ID,+ }))+ if w.Code != http.StatusCreated {+ t.Fatalf("pin view: expected 201, got %d: %s", w.Code, w.Body.String())+ }++ listPins := func(path string) []PinnedItemResponse {+ rec := httptest.NewRecorder()+ testHandler.ListPins(rec, newRequest("GET", path, nil))+ if rec.Code != http.StatusOK {+ t.Fatalf("list pins: expected 200, got %d: %s", rec.Code, rec.Body.String())+ }+ var pins []PinnedItemResponse+ json.NewDecoder(rec.Body).Decode(&pins)+ return pins+ }++ // Legacy contract: the view pin must be invisible.+ for _, p := range listPins("/api/pins") {+ if p.ItemType == "view" {+ t.Fatalf("view pin leaked into the legacy list contract")+ }+ }+ // Opted-in contract: the view pin is present.+ found := false+ for _, p := range listPins("/api/pins?include=view") {+ if p.ItemType == "view" && p.ItemID == view.ID {+ found = true+ }+ }+ if !found {+ t.Fatal("view pin missing from the opted-in list")+ }+}++func TestIssueViewWriteLimits(t *testing.T) {++ // JSON null for a definition blob is rejected up front, not left to+ // become a DB CHECK 500.+ _, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Null query",+ "scope_type": "workspace",+ "query": nil,+ })+ if code != http.StatusBadRequest {+ t.Fatalf("null query: expected 400, got %d: %s", code, body)+ }++ // Oversized body: a query blob past the byte cap is a 400.+ big := strings.Repeat("x", issueViewBodyMaxBytes)+ _, code, _ = createIssueViewForTest(t, map[string]any{+ "name": "Huge",+ "scope_type": "workspace",+ "query": map[string]any{"blob": big},+ })+ if code != http.StatusBadRequest {+ t.Fatalf("oversized body: expected 400, got %d", code)+ }++ // Per-owner quota: fill to the cap directly, then one more create fails.+ ctx := context.Background()+ if _, err := testPool.Exec(ctx, `+ INSERT INTO issue_view (workspace_id, owner_id, name, scope_type, visibility, definition_version, query, display)+ SELECT $1::uuid, $2::uuid, 'quota filler ' || g, 'workspace', 'private', 1, '{}', '{}'+ FROM generate_series(1, $3::int) AS g+ `, testWorkspaceID, testUserID, issueViewsPerOwnerMax); err != nil {+ t.Fatalf("seed quota rows: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue_view WHERE name LIKE 'quota filler %'`)+ })+ _, code, body = createIssueViewForTest(t, map[string]any{+ "name": "One too many",+ "scope_type": "workspace",+ "query": map[string]any{},+ })+ if code != http.StatusBadRequest {+ t.Fatalf("quota: expected 400, got %d: %s", code, body)+ }+ if !strings.Contains(body, "limit") {+ t.Fatalf("quota error should mention the limit, got: %s", body)+ }+}++// Member removal must sweep the departed member's private views and their+// view-bar preferences in the revoke transaction; shared views stay for the+// workspace. (The migration comments promise exactly this.)+func TestRevokeMemberSweepsPrivateViewsAndPreferences(t *testing.T) {++ ctx := context.Background()+ otherID := createSecondWorkspaceMember(t)++ seedView := func(name, visibility string) {+ if _, err := testPool.Exec(ctx, `+ INSERT INTO issue_view (workspace_id, owner_id, name, scope_type, visibility, definition_version, query, display)+ VALUES ($1, $2, $3, 'workspace', $4, 1, '{}', '{}')+ `, testWorkspaceID, otherID, name, visibility); err != nil {+ t.Fatalf("seed view: %v", err)+ }+ }+ seedView("revoke private", "private")+ seedView("revoke shared", "workspace")+ if _, err := testPool.Exec(ctx, `+ INSERT INTO issue_view_preference (workspace_id, user_id, scope_type, scope_id, prefs)+ VALUES ($1, $2, 'workspace', $1, '{"order": []}')+ ON CONFLICT (workspace_id, user_id, scope_type, scope_id) DO UPDATE SET prefs = EXCLUDED.prefs+ `, testWorkspaceID, otherID); err != nil {+ t.Fatalf("seed preference: %v", err)+ }+ if _, err := testPool.Exec(ctx, `+ INSERT INTO pinned_item (workspace_id, user_id, item_type, item_id, position)+ SELECT $1::uuid, $2::uuid, 'view', id, 1 FROM issue_view WHERE name = 'revoke private'+ `, testWorkspaceID, otherID); err != nil {+ t.Fatalf("seed pin: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM issue_view WHERE name LIKE 'revoke %'`)+ testPool.Exec(ctx, `DELETE FROM issue_view_preference WHERE user_id = $1`, otherID)+ })++ var memberID string+ if err := testPool.QueryRow(ctx, `+ SELECT id FROM member WHERE workspace_id = $1 AND user_id = $2+ `, testWorkspaceID, otherID).Scan(&memberID); err != nil {+ t.Fatalf("load member id: %v", err)+ }+ if _, err := testHandler.revokeAndRemoveMember(+ ctx, parseUUID(testWorkspaceID), parseUUID(otherID), parseUUID(memberID), parseUUID(testUserID),+ ); err != nil {+ t.Fatalf("revoke: %v", err)+ }++ var privateCount, sharedCount, prefCount, pinCount int+ testPool.QueryRow(ctx, `SELECT COUNT(*) FROM issue_view WHERE name = 'revoke private'`).Scan(&privateCount)+ testPool.QueryRow(ctx, `SELECT COUNT(*) FROM issue_view WHERE name = 'revoke shared'`).Scan(&sharedCount)+ testPool.QueryRow(ctx, `SELECT COUNT(*) FROM issue_view_preference WHERE user_id = $1`, otherID).Scan(&prefCount)+ if privateCount != 0 {+ t.Fatal("private view survived member removal")+ }+ if sharedCount != 1 {+ t.Fatal("shared view must survive member removal")+ }+ if prefCount != 0 {+ t.Fatal("view-bar preferences survived member removal")+ }+ testPool.QueryRow(ctx, `SELECT COUNT(*) FROM pinned_item WHERE item_type = 'view' AND user_id = $1`, otherID).Scan(&pinCount)+ if pinCount != 0 {+ t.Fatal("pins on the removed member's private views survived")+ }+}++// Deleting a view — directly, or via its project's deletion — must sweep the+// sidebar pins that point at it: view pins never auto-unpin client-side, so a+// surviving row would be invisible and unremovable forever.+func TestDeletingViewsSweepsTheirPins(t *testing.T) {++ ctx := context.Background()+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM pinned_item WHERE item_type = 'view'`)+ })+ countViewPins := func() int {+ var n int+ testPool.QueryRow(ctx, `SELECT COUNT(*) FROM pinned_item WHERE item_type = 'view'`).Scan(&n)+ return n+ }+ pinView := func(viewID string) {+ w := httptest.NewRecorder()+ testHandler.CreatePin(w, newRequest("POST", "/api/pins", map[string]any{+ "item_type": "view",+ "item_id": viewID,+ }))+ if w.Code != http.StatusCreated {+ t.Fatalf("pin view: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ }++ // 1) Direct handler delete.+ view, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Sweep on delete",+ "scope_type": "workspace",+ "query": map[string]any{},+ })+ if code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", code, body)+ }+ pinView(view.ID)+ w := httptest.NewRecorder()+ req := withURLParam(newRequest("DELETE", "/api/issue-views/"+view.ID, nil), "id", view.ID)+ testHandler.DeleteIssueView(w, req)+ if w.Code != http.StatusNoContent {+ t.Fatalf("delete view: expected 204, got %d: %s", w.Code, w.Body.String())+ }+ if n := countViewPins(); n != 0 {+ t.Fatalf("pin survived direct view delete: %d rows", n)+ }++ // 2) Project deletion cascades through its scoped views.+ w = httptest.NewRecorder()+ testHandler.CreateProject(w, newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{+ "title": "pin sweep project",+ }))+ if w.Code != http.StatusCreated {+ t.Fatalf("create project: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var project ProjectResponse+ json.NewDecoder(w.Body).Decode(&project)++ projView, code, body := createIssueViewForTest(t, map[string]any{+ "name": "Project pinned view",+ "scope_type": "project",+ "scope_id": project.ID,+ "query": map[string]any{},+ })+ if code != http.StatusCreated {+ t.Fatalf("expected 201, got %d: %s", code, body)+ }+ pinView(projView.ID)++ w = httptest.NewRecorder()+ req = withURLParam(newRequest("DELETE", "/api/projects/"+project.ID, nil), "id", project.ID)+ testHandler.DeleteProject(w, req)+ if w.Code >= 300 {+ t.Fatalf("delete project: got %d: %s", w.Code, w.Body.String())+ }+ if n := countViewPins(); n != 0 {+ t.Fatalf("pin survived project deletion: %d rows", n)+ }+}diff --git a/server/internal/handler/pin.go b/server/internal/handler/pin.goindex ab4a84ca1c..578efab375 100644--- a/server/internal/handler/pin.go+++ b/server/internal/handler/pin.go@@ -3,6 +3,7 @@ package handlerimport ("encoding/json""net/http"+ "strings""github.com/go-chi/chi/v5"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -65,8 +66,19 @@ func (h *Handler) ListPins(w http.ResponseWriter, r *http.Request) {return}+ // Capability opt-in: clients built before saved views classified every+ // non-issue pin as a project pin, fetched its detail, got 404, and+ // permanently auto-unpinned it. Exposing item_type=view through the old+ // contract would let an old Desktop DESTROY the user's view pins just by+ // opening the sidebar — so view rows only ship to clients that declare+ // they understand them (?include=view).+ includeViews := strings.Contains(r.URL.Query().Get("include"), "view")+resp := make([]PinnedItemResponse, 0, len(pins))for _, p := range pins {+ if p.ItemType == "view" && !includeViews {+ continue+ }resp = append(resp, pinnedItemToResponse(p))}writeJSON(w, http.StatusOK, resp)@@ -84,8 +96,8 @@ func (h *Handler) CreatePin(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, "invalid request body")return}- if req.ItemType != "issue" && req.ItemType != "project" {- writeError(w, http.StatusBadRequest, "item_type must be 'issue' or 'project'")+ if req.ItemType != "issue" && req.ItemType != "project" && req.ItemType != "view" {+ writeError(w, http.StatusBadRequest, "item_type must be 'issue', 'project' or 'view'")return}if req.ItemID == "" {@@ -118,6 +130,17 @@ func (h *Handler) CreatePin(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "project not found")return}+ case "view":+ // Same read rule as the view endpoints: your own views, or views+ // shared to the workspace. Foreign private views 404 — a pin must+ // never confirm their existence.+ view, err := h.Queries.GetIssueView(r.Context(), db.GetIssueViewParams{+ ID: itemUUID, WorkspaceID: wsUUID,+ })+ if err != nil || !canReadIssueView(view, parseUUID(userID)) {+ writeError(w, http.StatusNotFound, "view not found")+ return+ }}// Get max position to append at enddiff --git a/server/internal/handler/project.go b/server/internal/handler/project.goindex 049c4a3d1d..3a9bf6f5d0 100644--- a/server/internal/handler/project.go+++ b/server/internal/handler/project.go@@ -613,6 +613,15 @@ func (h *Handler) DeleteProject(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to clear project chat context")return}+ // Project-scoped saved views live on the project page; once the project+ // is gone they are unreachable, so they go in the same transaction.+ if err := qtx.DeleteIssueViewsByProjectScope(r.Context(), db.DeleteIssueViewsByProjectScopeParams{+ WorkspaceID: project.WorkspaceID,+ ScopeID: project.ID,+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete project views")+ return+ }if err := qtx.DeleteProject(r.Context(), db.DeleteProjectParams{ID: project.ID,WorkspaceID: project.WorkspaceID,diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex ce439fadaf..ff6eadf285 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -61,6 +61,8 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"github_pull_request_check_suite": workspaceDelete,"inbox_item": workspaceDelete,"issue": workspaceDelete,+ "issue_view": workspaceDelete,+ "issue_view_preference": workspaceDelete,"issue_dependency": workspaceDelete,"issue_label": workspaceDelete,"issue_property": workspaceDelete,diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.goindex 5ef3886072..2a433b84b2 100644--- a/server/internal/handler/workspace_revoke.go+++ b/server/internal/handler/workspace_revoke.go@@ -164,6 +164,24 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userIDreturn empty, err}+ // Saved views follow the private-quick-action rule above: a departed+ // member's PRIVATE views are invisible to everyone left yet still count+ // against quota, and a re-invite must not resurrect them. Shared views+ // stay — they are workspace furniture other members may rely on. The+ // per-user view-bar preferences are meaningless without the member.+ if err := qtx.DeletePrivateIssueViewsByOwner(ctx, db.DeletePrivateIssueViewsByOwnerParams{+ WorkspaceID: workspaceID,+ OwnerID: userID,+ }); err != nil {+ return empty, err+ }+ if err := qtx.DeleteIssueViewPreferencesByUser(ctx, db.DeleteIssueViewPreferencesByUserParams{+ WorkspaceID: workspaceID,+ UserID: userID,+ }); err != nil {+ return empty, err+ }+// issue_subscriber carries no FK either (same MUL-3515 rule as the two// prunes above), and MUL-5483 gave agents a path that writes member// subscriber rows on their own initiative. Dropping them in this tx is whatdiff --git a/server/migrations/265_issue_view.down.sql b/server/migrations/265_issue_view.down.sqlnew file mode 100644index 0000000000..726cf24eaa--- /dev/null+++ b/server/migrations/265_issue_view.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS issue_view;diff --git a/server/migrations/265_issue_view.up.sql b/server/migrations/265_issue_view.up.sqlnew file mode 100644index 0000000000..49143614d8--- /dev/null+++ b/server/migrations/265_issue_view.up.sql@@ -0,0 +1,35 @@+-- Saved issue views: named, server-backed filter definitions with display+-- defaults. `query` (filters) is the shared identity of the view; `display`+-- (layout/grouping/sort/card fields) only seeds the first open and is+-- overridden per user locally. No FKs or cascades by repository policy —+-- lifecycle cleanup is handled in application transactions (project delete,+-- member removal).+CREATE TABLE issue_view (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ workspace_id UUID NOT NULL,+ owner_id UUID NOT NULL,+ name TEXT NOT NULL CHECK (char_length(name) BETWEEN 1 AND 80),+ scope_type TEXT NOT NULL CHECK (scope_type IN ('workspace', 'my', 'project')),+ scope_id UUID,+ scope_variant TEXT CHECK (scope_variant IN ('assigned', 'created', 'involved', 'any')),+ visibility TEXT NOT NULL DEFAULT 'private' CHECK (visibility IN ('private', 'workspace')),+ definition_version INTEGER NOT NULL DEFAULT 1,+ query JSONB NOT NULL CHECK (jsonb_typeof(query) = 'object'),+ display JSONB NOT NULL DEFAULT '{}'::jsonb CHECK (jsonb_typeof(display) = 'object'),+ revision INTEGER NOT NULL DEFAULT 1,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ -- scope_id carries the project id for project views and must be absent+ -- elsewhere; scope_variant is meaningful only for My Issues views.+ CHECK (+ (scope_type = 'project' AND scope_id IS NOT NULL)+ OR (scope_type IN ('workspace', 'my') AND scope_id IS NULL)+ ),+ CHECK (+ (scope_type = 'my' AND scope_variant IS NOT NULL)+ OR (scope_type <> 'my' AND scope_variant IS NULL)+ ),+ -- My Issues is inherently personal; sharing it would leak a per-user+ -- perspective that renders differently for every member.+ CHECK (scope_type <> 'my' OR visibility = 'private')+);diff --git a/server/migrations/266_issue_view_owner_index.down.sql b/server/migrations/266_issue_view_owner_index.down.sqlnew file mode 100644index 0000000000..2e245ae2d7--- /dev/null+++ b/server/migrations/266_issue_view_owner_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_view_owner;diff --git a/server/migrations/266_issue_view_owner_index.up.sql b/server/migrations/266_issue_view_owner_index.up.sqlnew file mode 100644index 0000000000..18d31d08ee--- /dev/null+++ b/server/migrations/266_issue_view_owner_index.up.sql@@ -0,0 +1,7 @@+-- List query shape: workspace_id + scope columns, then either "mine" or+-- "shared with workspace" (OR of two branches — see 256 for the shared+-- branch; the planner combines them via BitmapOr). Kept as its own+-- single-statement file: concurrent index builds cannot run inside a+-- transaction or a multi-command migration.+CREATE INDEX CONCURRENTLY idx_issue_view_owner+ ON issue_view (workspace_id, scope_type, scope_id, owner_id);diff --git a/server/migrations/267_issue_view_shared_index.down.sql b/server/migrations/267_issue_view_shared_index.down.sqlnew file mode 100644index 0000000000..04eb2b06f2--- /dev/null+++ b/server/migrations/267_issue_view_shared_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_view_shared;diff --git a/server/migrations/267_issue_view_shared_index.up.sql b/server/migrations/267_issue_view_shared_index.up.sqlnew file mode 100644index 0000000000..cc15eae330--- /dev/null+++ b/server/migrations/267_issue_view_shared_index.up.sql@@ -0,0 +1,4 @@+-- Partial index for the "shared with workspace" branch of the list query.+CREATE INDEX CONCURRENTLY idx_issue_view_shared+ ON issue_view (workspace_id, scope_type, scope_id)+ WHERE visibility = 'workspace';diff --git a/server/migrations/268_issue_view_preference.down.sql b/server/migrations/268_issue_view_preference.down.sqlnew file mode 100644index 0000000000..0fc9672d87--- /dev/null+++ b/server/migrations/268_issue_view_preference.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS issue_view_preference;diff --git a/server/migrations/268_issue_view_preference.up.sql b/server/migrations/268_issue_view_preference.up.sqlnew file mode 100644index 0000000000..1e2839580f--- /dev/null+++ b/server/migrations/268_issue_view_preference.up.sql@@ -0,0 +1,17 @@+-- Per-user view-bar preferences for one surface container: which items+-- (built-in tabs and saved views) are hidden and in what order they render.+-- `prefs` is a small client-owned doc: { "hidden": [...], "order": [...] }+-- with item ids like "builtin:all" / "view:<uuid>". Single-user data —+-- last-write-wins, no revision. scope_id is backfilled (workspace id for+-- workspace scope, user id for my scope, project id for project scope) so+-- the composite primary key never depends on NULL. No FKs by repository+-- policy; the member-revoke transaction deletes these rows explicitly.+CREATE TABLE issue_view_preference (+ workspace_id UUID NOT NULL,+ user_id UUID NOT NULL,+ scope_type TEXT NOT NULL CHECK (scope_type IN ('workspace', 'my', 'project')),+ scope_id UUID NOT NULL,+ prefs JSONB NOT NULL DEFAULT '{}'::jsonb CHECK (jsonb_typeof(prefs) = 'object'),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (workspace_id, user_id, scope_type, scope_id)+);diff --git a/server/migrations/269_issue_view_workspace_variant.down.sql b/server/migrations/269_issue_view_workspace_variant.down.sqlnew file mode 100644index 0000000000..f2dc74e466--- /dev/null+++ b/server/migrations/269_issue_view_workspace_variant.down.sql@@ -0,0 +1,22 @@+-- Rolling back to the my-only variant vocabulary: workspace/project rows+-- that adopted the assignee-type variants must be normalized FIRST, or the+-- restored constraints reject the data and the rollback dies half-applied.+-- NULL is the correct downgrade — the previous version has no assignee-type+-- axis, so these views fall back to the unrestricted tab.+UPDATE issue_view+SET scope_variant = NULL+WHERE scope_type IN ('workspace', 'project')+ AND scope_variant IS NOT NULL;++ALTER TABLE issue_view+ DROP CONSTRAINT issue_view_scope_variant_check,+ DROP CONSTRAINT issue_view_scope_variant_pairing;++ALTER TABLE issue_view+ ADD CONSTRAINT issue_view_scope_variant_check CHECK (+ scope_variant IN ('assigned', 'created', 'involved', 'any')+ ),+ ADD CONSTRAINT issue_view_check1 CHECK (+ (scope_type = 'my' AND scope_variant IS NOT NULL)+ OR (scope_type <> 'my' AND scope_variant IS NULL)+ );diff --git a/server/migrations/269_issue_view_workspace_variant.up.sql b/server/migrations/269_issue_view_workspace_variant.up.sqlnew file mode 100644index 0000000000..83fdf42e5e--- /dev/null+++ b/server/migrations/269_issue_view_workspace_variant.up.sql@@ -0,0 +1,19 @@+-- Workspace views gain an optional scope_variant mirroring the built-in+-- Members / Agents tabs — the same "which tab" concept my-views already+-- persist. NULL means the unrestricted All tab; a set value narrows the+-- view's scope to that assignee type (injected as scope-level+-- assignee_types at query time). Project views share the same optional+-- vocabulary: the project pages carry the same Members / Agents tabs.+ALTER TABLE issue_view+ DROP CONSTRAINT issue_view_scope_variant_check,+ DROP CONSTRAINT issue_view_check1;++ALTER TABLE issue_view+ ADD CONSTRAINT issue_view_scope_variant_check CHECK (+ scope_variant IN ('assigned', 'created', 'involved', 'any', 'members', 'agents')+ ),+ ADD CONSTRAINT issue_view_scope_variant_pairing CHECK (+ (scope_type = 'my' AND scope_variant IN ('assigned', 'created', 'involved', 'any'))+ OR (scope_type = 'workspace' AND (scope_variant IS NULL OR scope_variant IN ('members', 'agents')))+ OR (scope_type = 'project' AND (scope_variant IS NULL OR scope_variant IN ('members', 'agents')))+ );diff --git a/server/migrations/270_pinned_item_view.down.sql b/server/migrations/270_pinned_item_view.down.sqlnew file mode 100644index 0000000000..3d90b4e0d2--- /dev/null+++ b/server/migrations/270_pinned_item_view.down.sql@@ -0,0 +1,4 @@+DELETE FROM pinned_item WHERE item_type = 'view';+ALTER TABLE pinned_item DROP CONSTRAINT pinned_item_item_type_check;+ALTER TABLE pinned_item ADD CONSTRAINT pinned_item_item_type_check+ CHECK (item_type IN ('issue', 'project'));diff --git a/server/migrations/270_pinned_item_view.up.sql b/server/migrations/270_pinned_item_view.up.sqlnew file mode 100644index 0000000000..158c3246e7--- /dev/null+++ b/server/migrations/270_pinned_item_view.up.sql@@ -0,0 +1,6 @@+-- Saved issue views become pinnable to the sidebar alongside issues and+-- projects. The pin row stores only (item_type, item_id); display data is+-- resolved client-side from the view detail endpoint.+ALTER TABLE pinned_item DROP CONSTRAINT pinned_item_item_type_check;+ALTER TABLE pinned_item ADD CONSTRAINT pinned_item_item_type_check+ CHECK (item_type IN ('issue', 'project', 'view'));diff --git a/server/pkg/db/generated/issue_view.sql.go b/server/pkg/db/generated/issue_view.sql.gonew file mode 100644index 0000000000..88679cd124--- /dev/null+++ b/server/pkg/db/generated/issue_view.sql.go@@ -0,0 +1,335 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: issue_view.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const countIssueViewsByOwner = `-- name: CountIssueViewsByOwner :one+SELECT COUNT(*) FROM issue_view+WHERE workspace_id = $1 AND owner_id = $2+`++type CountIssueViewsByOwnerParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ OwnerID pgtype.UUID `json:"owner_id"`+}++func (q *Queries) CountIssueViewsByOwner(ctx context.Context, arg CountIssueViewsByOwnerParams) (int64, error) {+ row := q.db.QueryRow(ctx, countIssueViewsByOwner, arg.WorkspaceID, arg.OwnerID)+ var count int64+ err := row.Scan(&count)+ return count, err+}++const createIssueView = `-- name: CreateIssueView :one+INSERT INTO issue_view (+ workspace_id, owner_id, name, scope_type, scope_id, scope_variant,+ visibility, definition_version, query, display+)+VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)+RETURNING id, workspace_id, owner_id, name, scope_type, scope_id, scope_variant, visibility, definition_version, query, display, revision, created_at, updated_at+`++type CreateIssueViewParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ OwnerID pgtype.UUID `json:"owner_id"`+ Name string `json:"name"`+ ScopeType string `json:"scope_type"`+ ScopeID pgtype.UUID `json:"scope_id"`+ ScopeVariant pgtype.Text `json:"scope_variant"`+ Visibility string `json:"visibility"`+ DefinitionVersion int32 `json:"definition_version"`+ Query []byte `json:"query"`+ Display []byte `json:"display"`+}++func (q *Queries) CreateIssueView(ctx context.Context, arg CreateIssueViewParams) (IssueView, error) {+ row := q.db.QueryRow(ctx, createIssueView,+ arg.WorkspaceID,+ arg.OwnerID,+ arg.Name,+ arg.ScopeType,+ arg.ScopeID,+ arg.ScopeVariant,+ arg.Visibility,+ arg.DefinitionVersion,+ arg.Query,+ arg.Display,+ )+ var i IssueView+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.OwnerID,+ &i.Name,+ &i.ScopeType,+ &i.ScopeID,+ &i.ScopeVariant,+ &i.Visibility,+ &i.DefinitionVersion,+ &i.Query,+ &i.Display,+ &i.Revision,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const deleteIssueView = `-- name: DeleteIssueView :one+WITH deleted AS (+ DELETE FROM issue_view+ WHERE issue_view.id = $1 AND issue_view.workspace_id = $2+ RETURNING issue_view.id+),+swept_pins AS (+ DELETE FROM pinned_item+ WHERE pinned_item.item_type = 'view'+ AND pinned_item.workspace_id = $2+ AND pinned_item.item_id IN (SELECT deleted.id FROM deleted)+)+SELECT deleted.id FROM deleted+`++type DeleteIssueViewParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Every view delete sweeps its sidebar pins in the same statement: a pin+// whose view is gone is invisible in the UI (view pins never auto-unpin)+// and would otherwise be unremovable forever.+func (q *Queries) DeleteIssueView(ctx context.Context, arg DeleteIssueViewParams) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, deleteIssueView, arg.ID, arg.WorkspaceID)+ var id pgtype.UUID+ err := row.Scan(&id)+ return id, err+}++const deleteIssueViewPreferencesByUser = `-- name: DeleteIssueViewPreferencesByUser :exec+DELETE FROM issue_view_preference+WHERE workspace_id = $1 AND user_id = $2+`++type DeleteIssueViewPreferencesByUserParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+}++func (q *Queries) DeleteIssueViewPreferencesByUser(ctx context.Context, arg DeleteIssueViewPreferencesByUserParams) error {+ _, err := q.db.Exec(ctx, deleteIssueViewPreferencesByUser, arg.WorkspaceID, arg.UserID)+ return err+}++const deleteIssueViewsByProjectScope = `-- name: DeleteIssueViewsByProjectScope :exec+WITH deleted AS (+ DELETE FROM issue_view+ WHERE issue_view.workspace_id = $1 AND issue_view.scope_type = 'project' AND issue_view.scope_id = $2+ RETURNING issue_view.id+)+DELETE FROM pinned_item+WHERE pinned_item.item_type = 'view'+ AND pinned_item.workspace_id = $1+ AND pinned_item.item_id IN (SELECT deleted.id FROM deleted)+`++type DeleteIssueViewsByProjectScopeParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ScopeID pgtype.UUID `json:"scope_id"`+}++// Project deletion cleanup: called inside DeleteProject's application+// transaction so project views never outlive their surface. Their sidebar+// pins fall in the same statement (see DeleteIssueView).+func (q *Queries) DeleteIssueViewsByProjectScope(ctx context.Context, arg DeleteIssueViewsByProjectScopeParams) error {+ _, err := q.db.Exec(ctx, deleteIssueViewsByProjectScope, arg.WorkspaceID, arg.ScopeID)+ return err+}++const deletePrivateIssueViewsByOwner = `-- name: DeletePrivateIssueViewsByOwner :exec+WITH deleted AS (+ DELETE FROM issue_view+ WHERE issue_view.workspace_id = $1 AND issue_view.owner_id = $2 AND issue_view.visibility = 'private'+ RETURNING issue_view.id+)+DELETE FROM pinned_item+WHERE pinned_item.item_type = 'view'+ AND pinned_item.workspace_id = $1+ AND pinned_item.item_id IN (SELECT deleted.id FROM deleted)+`++type DeletePrivateIssueViewsByOwnerParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ OwnerID pgtype.UUID `json:"owner_id"`+}++// Member removal: a departed member's private views are unreachable by every+// remaining member while still consuming their quota — same rule as private+// quick actions. Shared views are workspace furniture and survive. Pins on+// the deleted views fall in the same statement (see DeleteIssueView).+func (q *Queries) DeletePrivateIssueViewsByOwner(ctx context.Context, arg DeletePrivateIssueViewsByOwnerParams) error {+ _, err := q.db.Exec(ctx, deletePrivateIssueViewsByOwner, arg.WorkspaceID, arg.OwnerID)+ return err+}++const getIssueView = `-- name: GetIssueView :one+SELECT id, workspace_id, owner_id, name, scope_type, scope_id, scope_variant, visibility, definition_version, query, display, revision, created_at, updated_at FROM issue_view+WHERE id = $1 AND workspace_id = $2+`++type GetIssueViewParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Defense-in-depth: workspace_id is a SQL-layer tenant guard. Authorization+// (owner vs shared) happens in the handler so unauthorized reads 404.+func (q *Queries) GetIssueView(ctx context.Context, arg GetIssueViewParams) (IssueView, error) {+ row := q.db.QueryRow(ctx, getIssueView, arg.ID, arg.WorkspaceID)+ var i IssueView+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.OwnerID,+ &i.Name,+ &i.ScopeType,+ &i.ScopeID,+ &i.ScopeVariant,+ &i.Visibility,+ &i.DefinitionVersion,+ &i.Query,+ &i.Display,+ &i.Revision,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const listIssueViewsForUser = `-- name: ListIssueViewsForUser :many+SELECT id, workspace_id, owner_id, name, scope_type, scope_id, scope_variant, visibility, definition_version, query, display, revision, created_at, updated_at FROM issue_view+WHERE workspace_id = $1+ AND scope_type = $2+ AND scope_id IS NOT DISTINCT FROM $4::uuid+ AND (owner_id = $3 OR visibility = 'workspace')+ORDER BY created_at ASC+LIMIT 200+`++type ListIssueViewsForUserParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ScopeType string `json:"scope_type"`+ OwnerID pgtype.UUID `json:"owner_id"`+ ScopeID pgtype.UUID `json:"scope_id"`+}++// One surface's selector list: the caller's own views plus workspace-shared+// ones, for a single (scope_type, scope_id) container. scope_id is NULL for+// workspace and my scopes, so compare NULL-safely.+// Hard response cap: the bar/panel are not built for more than this, and+// every row carries full query/display JSON. The create quota keeps real+// data far below it; the LIMIT is the abuse backstop.+func (q *Queries) ListIssueViewsForUser(ctx context.Context, arg ListIssueViewsForUserParams) ([]IssueView, error) {+ rows, err := q.db.Query(ctx, listIssueViewsForUser,+ arg.WorkspaceID,+ arg.ScopeType,+ arg.OwnerID,+ arg.ScopeID,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []IssueView{}+ for rows.Next() {+ var i IssueView+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.OwnerID,+ &i.Name,+ &i.ScopeType,+ &i.ScopeID,+ &i.ScopeVariant,+ &i.Visibility,+ &i.DefinitionVersion,+ &i.Query,+ &i.Display,+ &i.Revision,+ &i.CreatedAt,+ &i.UpdatedAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const updateIssueView = `-- name: UpdateIssueView :one+UPDATE issue_view SET+ name = $3,+ visibility = $4,+ scope_variant = $5,+ query = $6,+ display = $7,+ revision = revision + 1,+ updated_at = now()+WHERE id = $1 AND workspace_id = $2 AND revision = $8+RETURNING id, workspace_id, owner_id, name, scope_type, scope_id, scope_variant, visibility, definition_version, query, display, revision, created_at, updated_at+`++type UpdateIssueViewParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Name string `json:"name"`+ Visibility string `json:"visibility"`+ ScopeVariant pgtype.Text `json:"scope_variant"`+ Query []byte `json:"query"`+ Display []byte `json:"display"`+ Revision int32 `json:"revision"`+}++// Optimistic concurrency: the row only updates when the caller's revision+// matches; zero rows back means either a stale revision (409) or a vanished+// view (404) — the handler re-reads to tell them apart.+func (q *Queries) UpdateIssueView(ctx context.Context, arg UpdateIssueViewParams) (IssueView, error) {+ row := q.db.QueryRow(ctx, updateIssueView,+ arg.ID,+ arg.WorkspaceID,+ arg.Name,+ arg.Visibility,+ arg.ScopeVariant,+ arg.Query,+ arg.Display,+ arg.Revision,+ )+ var i IssueView+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.OwnerID,+ &i.Name,+ &i.ScopeType,+ &i.ScopeID,+ &i.ScopeVariant,+ &i.Visibility,+ &i.DefinitionVersion,+ &i.Query,+ &i.Display,+ &i.Revision,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/issue_view_preference.sql.go b/server/pkg/db/generated/issue_view_preference.sql.gonew file mode 100644index 0000000000..66a9f14aa6--- /dev/null+++ b/server/pkg/db/generated/issue_view_preference.sql.go@@ -0,0 +1,80 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: issue_view_preference.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const getIssueViewPreference = `-- name: GetIssueViewPreference :one+SELECT workspace_id, user_id, scope_type, scope_id, prefs, updated_at FROM issue_view_preference+WHERE workspace_id = $1 AND user_id = $2 AND scope_type = $3 AND scope_id = $4+`++type GetIssueViewPreferenceParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+ ScopeType string `json:"scope_type"`+ ScopeID pgtype.UUID `json:"scope_id"`+}++func (q *Queries) GetIssueViewPreference(ctx context.Context, arg GetIssueViewPreferenceParams) (IssueViewPreference, error) {+ row := q.db.QueryRow(ctx, getIssueViewPreference,+ arg.WorkspaceID,+ arg.UserID,+ arg.ScopeType,+ arg.ScopeID,+ )+ var i IssueViewPreference+ err := row.Scan(+ &i.WorkspaceID,+ &i.UserID,+ &i.ScopeType,+ &i.ScopeID,+ &i.Prefs,+ &i.UpdatedAt,+ )+ return i, err+}++const upsertIssueViewPreference = `-- name: UpsertIssueViewPreference :one+INSERT INTO issue_view_preference (workspace_id, user_id, scope_type, scope_id, prefs)+VALUES ($1, $2, $3, $4, $5)+ON CONFLICT (workspace_id, user_id, scope_type, scope_id)+DO UPDATE SET prefs = EXCLUDED.prefs, updated_at = now()+RETURNING workspace_id, user_id, scope_type, scope_id, prefs, updated_at+`++type UpsertIssueViewPreferenceParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+ ScopeType string `json:"scope_type"`+ ScopeID pgtype.UUID `json:"scope_id"`+ Prefs []byte `json:"prefs"`+}++// Whole-document replace: single-user data, last-write-wins.+func (q *Queries) UpsertIssueViewPreference(ctx context.Context, arg UpsertIssueViewPreferenceParams) (IssueViewPreference, error) {+ row := q.db.QueryRow(ctx, upsertIssueViewPreference,+ arg.WorkspaceID,+ arg.UserID,+ arg.ScopeType,+ arg.ScopeID,+ arg.Prefs,+ )+ var i IssueViewPreference+ err := row.Scan(+ &i.WorkspaceID,+ &i.UserID,+ &i.ScopeType,+ &i.ScopeID,+ &i.Prefs,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 3d9cf5b771..c6ada1dc78 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -728,6 +728,32 @@ type IssueVcsPullRequest struct {LinkedAt pgtype.Timestamptz `json:"linked_at"`}+type IssueView struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ OwnerID pgtype.UUID `json:"owner_id"`+ Name string `json:"name"`+ ScopeType string `json:"scope_type"`+ ScopeID pgtype.UUID `json:"scope_id"`+ ScopeVariant pgtype.Text `json:"scope_variant"`+ Visibility string `json:"visibility"`+ DefinitionVersion int32 `json:"definition_version"`+ Query []byte `json:"query"`+ Display []byte `json:"display"`+ Revision int32 `json:"revision"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}++type IssueViewPreference struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+ ScopeType string `json:"scope_type"`+ ScopeID pgtype.UUID `json:"scope_id"`+ Prefs []byte `json:"prefs"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type LarkBindingToken struct {TokenHash string `json:"token_hash"`WorkspaceID pgtype.UUID `json:"workspace_id"`diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex 6c37572f6d..9c75c72881 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -153,6 +153,13 @@ deleted_labels AS (),deleted_properties AS (DELETE FROM issue_property WHERE issue_property.workspace_id = $1+),+deleted_issue_views AS (+ DELETE FROM issue_view WHERE issue_view.workspace_id = $1+),+deleted_issue_view_preferences AS (+ DELETE FROM issue_view_preference+ WHERE issue_view_preference.workspace_id = $1)DELETE FROM quick_action WHERE quick_action.workspace_id = $1`diff --git a/server/pkg/db/queries/issue_view.sql b/server/pkg/db/queries/issue_view.sqlnew file mode 100644index 0000000000..7ca2b41f17--- /dev/null+++ b/server/pkg/db/queries/issue_view.sql@@ -0,0 +1,97 @@+-- name: CreateIssueView :one+INSERT INTO issue_view (+ workspace_id, owner_id, name, scope_type, scope_id, scope_variant,+ visibility, definition_version, query, display+)+VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)+RETURNING *;++-- name: ListIssueViewsForUser :many+-- One surface's selector list: the caller's own views plus workspace-shared+-- ones, for a single (scope_type, scope_id) container. scope_id is NULL for+-- workspace and my scopes, so compare NULL-safely.+SELECT * FROM issue_view+WHERE workspace_id = $1+ AND scope_type = $2+ AND scope_id IS NOT DISTINCT FROM sqlc.narg('scope_id')::uuid+ AND (owner_id = $3 OR visibility = 'workspace')+ORDER BY created_at ASC+-- Hard response cap: the bar/panel are not built for more than this, and+-- every row carries full query/display JSON. The create quota keeps real+-- data far below it; the LIMIT is the abuse backstop.+LIMIT 200;++-- name: CountIssueViewsByOwner :one+SELECT COUNT(*) FROM issue_view+WHERE workspace_id = $1 AND owner_id = $2;++-- name: GetIssueView :one+-- Defense-in-depth: workspace_id is a SQL-layer tenant guard. Authorization+-- (owner vs shared) happens in the handler so unauthorized reads 404.+SELECT * FROM issue_view+WHERE id = $1 AND workspace_id = $2;++-- name: UpdateIssueView :one+-- Optimistic concurrency: the row only updates when the caller's revision+-- matches; zero rows back means either a stale revision (409) or a vanished+-- view (404) — the handler re-reads to tell them apart.+UPDATE issue_view SET+ name = $3,+ visibility = $4,+ scope_variant = $5,+ query = $6,+ display = $7,+ revision = revision + 1,+ updated_at = now()+WHERE id = $1 AND workspace_id = $2 AND revision = $8+RETURNING *;++-- name: DeleteIssueView :one+-- Every view delete sweeps its sidebar pins in the same statement: a pin+-- whose view is gone is invisible in the UI (view pins never auto-unpin)+-- and would otherwise be unremovable forever.+WITH deleted AS (+ DELETE FROM issue_view+ WHERE issue_view.id = $1 AND issue_view.workspace_id = $2+ RETURNING issue_view.id+),+swept_pins AS (+ DELETE FROM pinned_item+ WHERE pinned_item.item_type = 'view'+ AND pinned_item.workspace_id = $2+ AND pinned_item.item_id IN (SELECT deleted.id FROM deleted)+)+SELECT deleted.id FROM deleted;++-- name: DeleteIssueViewsByProjectScope :exec+-- Project deletion cleanup: called inside DeleteProject's application+-- transaction so project views never outlive their surface. Their sidebar+-- pins fall in the same statement (see DeleteIssueView).+WITH deleted AS (+ DELETE FROM issue_view+ WHERE issue_view.workspace_id = $1 AND issue_view.scope_type = 'project' AND issue_view.scope_id = $2+ RETURNING issue_view.id+)+DELETE FROM pinned_item+WHERE pinned_item.item_type = 'view'+ AND pinned_item.workspace_id = $1+ AND pinned_item.item_id IN (SELECT deleted.id FROM deleted);++-- name: DeletePrivateIssueViewsByOwner :exec+-- Member removal: a departed member's private views are unreachable by every+-- remaining member while still consuming their quota — same rule as private+-- quick actions. Shared views are workspace furniture and survive. Pins on+-- the deleted views fall in the same statement (see DeleteIssueView).+WITH deleted AS (+ DELETE FROM issue_view+ WHERE issue_view.workspace_id = $1 AND issue_view.owner_id = $2 AND issue_view.visibility = 'private'+ RETURNING issue_view.id+)+DELETE FROM pinned_item+WHERE pinned_item.item_type = 'view'+ AND pinned_item.workspace_id = $1+ AND pinned_item.item_id IN (SELECT deleted.id FROM deleted);++-- name: DeleteIssueViewPreferencesByUser :exec+DELETE FROM issue_view_preference+WHERE workspace_id = $1 AND user_id = $2;diff --git a/server/pkg/db/queries/issue_view_preference.sql b/server/pkg/db/queries/issue_view_preference.sqlnew file mode 100644index 0000000000..c0924b60fc--- /dev/null+++ b/server/pkg/db/queries/issue_view_preference.sql@@ -0,0 +1,11 @@+-- name: GetIssueViewPreference :one+SELECT * FROM issue_view_preference+WHERE workspace_id = $1 AND user_id = $2 AND scope_type = $3 AND scope_id = $4;++-- name: UpsertIssueViewPreference :one+-- Whole-document replace: single-user data, last-write-wins.+INSERT INTO issue_view_preference (workspace_id, user_id, scope_type, scope_id, prefs)+VALUES ($1, $2, $3, $4, $5)+ON CONFLICT (workspace_id, user_id, scope_type, scope_id)+DO UPDATE SET prefs = EXCLUDED.prefs, updated_at = now()+RETURNING *;diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex d5ee620c7f..eedff86a9b 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -339,6 +339,13 @@ deleted_labels AS (),deleted_properties AS (DELETE FROM issue_property WHERE issue_property.workspace_id = $1+),+deleted_issue_views AS (+ DELETE FROM issue_view WHERE issue_view.workspace_id = $1+),+deleted_issue_view_preferences AS (+ DELETE FROM issue_view_preference+ WHERE issue_view_preference.workspace_id = $1)DELETE FROM quick_action WHERE quick_action.workspace_id = $1;