Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(MUL-6243): custom issue status UI — picker, board, filters, settings (#7103)

Bohan Jiange3a40b0b8d7b
diff --git a/apps/web/features/landing/components/features-section.tsx b/apps/web/features/landing/components/features-section.tsx
index 96950c550f..03ba240b04 100644
--- a/apps/web/features/landing/components/features-section.tsx
+++ b/apps/web/features/landing/components/features-section.tsx
@@ -25,7 +25,7 @@ import type { LandingDict } from "../i18n";
import { StatusIcon, PriorityIcon } from "@multica/views/issues/components";
import { STATUS_CONFIG } from "@multica/core/issues/config/status";
import { PRIORITY_CONFIG } from "@multica/core/issues/config/priority";
-import type { IssueStatus, IssuePriority } from "@multica/core/types";
+import type { IssueStatusCategory, IssuePriority } from "@multica/core/types";
/* ------------------------------------------------------------------ */
/* Mock ActorAvatar — mirrors the real ActorAvatar styling exactly */
@@ -137,11 +137,11 @@ const allAssignees: Assignee[] = [
{ type: "agent", id: "tina", name: "Tina-dev" },
];
-const statusCycle: IssueStatus[] = ["backlog", "todo", "in_progress", "in_review", "done"];
+const statusCycle: IssueStatusCategory[] = ["backlog", "todo", "in_progress", "in_review", "done"];
const priorityCycle: IssuePriority[] = ["none", "low", "medium", "high", "urgent"];
function TeammatesVisual() {
- const [status, setStatus] = useState<IssueStatus>("in_progress");
+ const [status, setStatus] = useState<IssueStatusCategory>("in_progress");
const [priority, setPriority] = useState<IssuePriority>("medium");
const [assignee, setAssignee] = useState<Assignee>(allAssignees[3]!); // Claude
const [pickerOpen, setPickerOpen] = useState(true);
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 24ad1cebd8..d404c45947 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -117,6 +117,7 @@ import type {
UpdateLabelRequest,
ListLabelsResponse,
ListIssueStatusesResponse,
+ IssueStatusCategory,
IssueStatusEntry,
CreateIssueStatusRequest,
UpdateIssueStatusRequest,
@@ -3284,6 +3285,25 @@ export class ApiClient {
});
}
+ /**
+ * Rewrites one category's custom-status order in a single server-side
+ * statement. Not expressible as a sequence of `updateIssueStatus` calls: a
+ * row rejected mid-sequence would leave the earlier rows already reordered
+ * while the caller sees a failure. (MUL-6243)
+ */
+ async reorderIssueStatuses(
+ category: IssueStatusCategory,
+ ids: string[],
+ ): Promise<ListIssueStatusesResponse> {
+ const raw = await this.fetch<unknown>(`/api/issue-statuses/reorder`, {
+ method: "PATCH",
+ body: JSON.stringify({ category, ids }),
+ });
+ return parseWithFallback(raw, ListIssueStatusesResponseSchema, EMPTY_LIST_ISSUE_STATUSES_RESPONSE, {
+ endpoint: "PATCH /api/issue-statuses/reorder",
+ });
+ }
+
/**
* Archives a custom status, retiring it from future use. Issues already on it
* keep it and keep behaving as their category prescribes; only new
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index cf73a52b34..c42aed90af 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -1534,6 +1534,19 @@ describe("issue status catalog schemas", () => {
expect(parsed.archived_at).toBeNull();
});
+ // PATCH /api/issue-statuses/reorder returns the same catalog shape as the
+ // list endpoint, so a malformed reorder response degrades the same way rather
+ // than leaving the settings page holding an unparsed blob. (MUL-6243)
+ it("falls back on a malformed reorder response", () => {
+ const parsed = parseWithFallback(
+ { statuses: [{ id: 1 }], total: "many" },
+ ListIssueStatusesResponseSchema,
+ EMPTY_LIST_ISSUE_STATUSES_RESPONSE,
+ { endpoint: "PATCH /api/issue-statuses/reorder" },
+ );
+ expect(parsed).toEqual(EMPTY_LIST_ISSUE_STATUSES_RESPONSE);
+ });
+
it("keeps an unknown category as a string instead of failing the whole catalog", () => {
// A newer server could report a category this build does not know. Dropping
// the entry (or throwing) would leave the board unable to render issues
diff --git a/packages/core/issue-statuses/hooks.ts b/packages/core/issue-statuses/hooks.ts
index 48281ee0de..d8ccdbc396 100644
--- a/packages/core/issue-statuses/hooks.ts
+++ b/packages/core/issue-statuses/hooks.ts
@@ -1,5 +1,5 @@
import { useQuery } from "@tanstack/react-query";
-import { useMemo } from "react";
+import { useCallback, useMemo } from "react";
import { buildIssueStatusCatalog, issueStatusListOptions, type IssueStatusCatalog } from "./queries";
/**
@@ -10,6 +10,23 @@ import { buildIssueStatusCatalog, issueStatusListOptions, type IssueStatusCatalo
* remount the app, so a module-level snapshot would go stale.
*/
export function useIssueStatuses(wsId: string): IssueStatusCatalog {
- const { data } = useQuery({ ...issueStatusListOptions(wsId), enabled: Boolean(wsId) });
- return useMemo(() => buildIssueStatusCatalog(data), [data]);
+ const { data, isPending, isError, refetch } = useQuery({
+ ...issueStatusListOptions(wsId),
+ enabled: Boolean(wsId),
+ });
+ // `refetch` travels with the catalog, not just its failure flag: a surface
+ // that blocks on a failed catalog needs something to offer the user, and
+ // reaching back into React Query from the view layer would duplicate the
+ // query key. (MUL-6243)
+ const retry = useCallback(() => {
+ void refetch();
+ }, [refetch]);
+ // pending/error are carried through, not dropped: a surface that routes a
+ // CUSTOM status key cannot distinguish "catalog not here yet" from "catalog
+ // failed" without them, and both need different UI — a spinner and a retry.
+ // (MUL-6243)
+ return useMemo(
+ () => buildIssueStatusCatalog(data, { isPending, isError, retry }),
+ [data, isPending, isError, retry],
+ );
}
diff --git a/packages/core/issue-statuses/index.ts b/packages/core/issue-statuses/index.ts
index 028dbddd8a..fa6334e7e9 100644
--- a/packages/core/issue-statuses/index.ts
+++ b/packages/core/issue-statuses/index.ts
@@ -5,4 +5,11 @@ export {
isIssueStatusCategory,
type IssueStatusCatalog,
} from "./queries";
+export { compareIssueStatusEntries } from "./queries";
export { useIssueStatuses } from "./hooks";
+export {
+ useCreateIssueStatus,
+ useUpdateIssueStatus,
+ useArchiveIssueStatus,
+ useReorderIssueStatuses,
+} from "./mutations";
diff --git a/packages/core/issue-statuses/mutations.ts b/packages/core/issue-statuses/mutations.ts
new file mode 100644
index 0000000000..565a01b65e
--- /dev/null
+++ b/packages/core/issue-statuses/mutations.ts
@@ -0,0 +1,146 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { api } from "../api";
+import { useWorkspaceId } from "../hooks";
+import { compareIssueStatusEntries, issueStatusKeys } from "./queries";
+import { issueKeys } from "../issues/queries";
+import type {
+ CreateIssueStatusRequest,
+ IssueStatusCategory,
+ IssueStatusEntry,
+ ListIssueStatusesResponse,
+ UpdateIssueStatusRequest,
+} from "../types";
+
+/**
+ * Catalog mutations (MUL-6243).
+ *
+ * The catalog query is cached for 5 minutes and read by every surface that
+ * renders a status label, so each mutation invalidates it explicitly rather
+ * than waiting for staleness. A rename or recolor also invalidates the issues
+ * scope: a status's name is resolved from the catalog at render time, but the
+ * board/list caches hold the rows whose labels have to re-render.
+ */
+
+function useCatalogInvalidation() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return {
+ qc,
+ wsId,
+ invalidate: () => {
+ qc.invalidateQueries({ queryKey: issueStatusKeys.all(wsId) });
+ },
+ };
+}
+
+export function useCreateIssueStatus() {
+ const { qc, wsId, invalidate } = useCatalogInvalidation();
+ return useMutation({
+ mutationFn: (data: CreateIssueStatusRequest) => api.createIssueStatus(data),
+ onSuccess: (entry) => {
+ qc.setQueryData<ListIssueStatusesResponse>(issueStatusKeys.list(wsId), (old) =>
+ old && !old.statuses.some((s) => s.id === entry.id)
+ ? { ...old, statuses: [...old.statuses, entry], total: old.total + 1 }
+ : old,
+ );
+ },
+ onSettled: invalidate,
+ });
+}
+
+/**
+ * Optimistic rename / recolor / reorder — the same shape as `useUpdateLabel`.
+ * Without it, dragging a row to reorder would snap back for the round-trip.
+ */
+export function useUpdateIssueStatus() {
+ const { qc, wsId, invalidate } = useCatalogInvalidation();
+ return useMutation({
+ mutationFn: ({ id, ...data }: { id: string } & UpdateIssueStatusRequest) =>
+ api.updateIssueStatus(id, data),
+ onMutate: async ({ id, ...data }) => {
+ const listKey = issueStatusKeys.list(wsId);
+ await qc.cancelQueries({ queryKey: listKey });
+ const previous = qc.getQueryData<ListIssueStatusesResponse>(listKey);
+ qc.setQueryData<ListIssueStatusesResponse>(listKey, (old) =>
+ old
+ ? {
+ ...old,
+ statuses: old.statuses.map((s) => (s.id === id ? { ...s, ...data } : s)),
+ }
+ : old,
+ );
+ return { previous, listKey };
+ },
+ onError: (_err, _vars, ctx) => {
+ if (ctx?.previous && ctx.listKey) qc.setQueryData(ctx.listKey, ctx.previous);
+ },
+ onSettled: () => {
+ invalidate();
+ // Issue rows render the catalog's name/color, so a rename has to reach
+ // the cached lists too.
+ qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });
+ },
+ });
+}
+
+/**
+ * Archives a custom status. Deliberately NOT optimistic: the server refuses to
+ * archive a built-in, and a row silently vanishing before that refusal arrives
+ * would read as success.
+ */
+export function useArchiveIssueStatus() {
+ const { invalidate } = useCatalogInvalidation();
+ return useMutation({
+ mutationFn: (id: string) => api.archiveIssueStatus(id),
+ onSettled: invalidate,
+ });
+}
+
+/**
+ * Commits a drag-reorder within ONE category.
+ *
+ * Sent as a single request, not a PATCH per row: a sequence of writes is not
+ * atomic, so a row rejected part-way (an archived status, a concurrent archive)
+ * would leave the rows before it already reordered while the caller is told the
+ * whole operation failed. `ordered` is that category's ACTIVE custom statuses;
+ * the server assigns positions from 1 because the category's built-in is seeded
+ * at 0 and never moves.
+ */
+export function useReorderIssueStatuses() {
+ const { qc, wsId, invalidate } = useCatalogInvalidation();
+ return useMutation({
+ mutationFn: ({
+ category,
+ ordered,
+ }: {
+ category: IssueStatusCategory;
+ ordered: IssueStatusEntry[];
+ }) => api.reorderIssueStatuses(category, ordered.map((entry) => entry.id)),
+ onMutate: async ({ ordered }) => {
+ const listKey = issueStatusKeys.list(wsId);
+ await qc.cancelQueries({ queryKey: listKey });
+ const previous = qc.getQueryData<ListIssueStatusesResponse>(listKey);
+ const positionById = new Map(ordered.map((e, index) => [e.id, index + 1]));
+ qc.setQueryData<ListIssueStatusesResponse>(listKey, (old) =>
+ old
+ ? {
+ ...old,
+ // Re-sorted, not just re-positioned: consumers render the array in
+ // order, so writing positions alone would leave the drag visually
+ // undone until the refetch lands.
+ statuses: old.statuses
+ .map((s) =>
+ positionById.has(s.id) ? { ...s, position: positionById.get(s.id)! } : s,
+ )
+ .sort(compareIssueStatusEntries),
+ }
+ : old,
+ );
+ return { previous, listKey };
+ },
+ onError: (_err, _vars, ctx) => {
+ if (ctx?.previous && ctx.listKey) qc.setQueryData(ctx.listKey, ctx.previous);
+ },
+ onSettled: invalidate,
+ });
+}
diff --git a/packages/core/issue-statuses/queries.test.ts b/packages/core/issue-statuses/queries.test.ts
index 4c0383f60f..15248e7c2c 100644
--- a/packages/core/issue-statuses/queries.test.ts
+++ b/packages/core/issue-statuses/queries.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
-import { buildIssueStatusCatalog, isIssueStatusCategory } from "./queries";
+import { buildIssueStatusCatalog, compareIssueStatusEntries, isIssueStatusCategory } from "./queries";
import type { IssueStatusEntry } from "../types";
function entry(key: string, category: string, name = key, archivedAt: string | null = null): IssueStatusEntry {
@@ -87,3 +87,45 @@ describe("archived statuses stay resolvable", () => {
expect(c.inCategory("in_review").map((e) => e.key)).toEqual(["human_review"]);
});
});
+
+describe("compareIssueStatusEntries", () => {
+ function at(key: string, category: string, position: number): IssueStatusEntry {
+ return { ...entry(key, category), position };
+ }
+
+ // Mirrors ListIssueStatusEntries in issue_status.sql. An optimistic reorder
+ // re-sorts the cached array with this, so a drift from the server's ORDER BY
+ // would show one order until the refetch lands and a different one after.
+ it("orders by category rank before position", () => {
+ const sorted = [at("qa", "done", 1), at("review", "in_review", 9)].sort(
+ compareIssueStatusEntries,
+ );
+ expect(sorted.map((e) => e.key)).toEqual(["review", "qa"]);
+ });
+
+ it("orders by position within a category", () => {
+ const sorted = [at("b", "in_review", 2), at("a", "in_review", 1)].sort(
+ compareIssueStatusEntries,
+ );
+ expect(sorted.map((e) => e.key)).toEqual(["a", "b"]);
+ });
+
+ // Positions collide while a reorder is mid-flight; without the key tiebreak
+ // the list order would depend on the sort's stability.
+ it("falls back to key when positions tie", () => {
+ const sorted = [at("zeta", "todo", 1), at("alpha", "todo", 1)].sort(
+ compareIssueStatusEntries,
+ );
+ expect(sorted.map((e) => e.key)).toEqual(["alpha", "zeta"]);
+ });
+
+ // The built-in is seeded at position 0 and cannot be PATCHed, so it is
+ // permanently the head of its category. Reorder writes start at 1 for that
+ // reason; if the comparator ever let a custom status sort ahead of it, the
+ // picker would open on a status the workspace never chose as its default.
+ it("keeps the built-in ahead of custom statuses in its category", () => {
+ const builtIn = { ...at("in_review", "in_review", 0), is_system: true };
+ const sorted = [at("qa", "in_review", 1), builtIn].sort(compareIssueStatusEntries);
+ expect(sorted.map((e) => e.key)).toEqual(["in_review", "qa"]);
+ });
+});
diff --git a/packages/core/issue-statuses/queries.ts b/packages/core/issue-statuses/queries.ts
index a0fba556c5..1f78ea96d6 100644
--- a/packages/core/issue-statuses/queries.ts
+++ b/packages/core/issue-statuses/queries.ts
@@ -60,10 +60,69 @@ export interface IssueStatusCatalog {
inCategory: (category: IssueStatusCategory) => IssueStatusEntry[];
/** True once the catalog has loaded; false while it is still in flight. */
isLoaded: boolean;
+ /**
+ * The catalog is still in flight and nothing has resolved yet.
+ *
+ * A surface that routes on a CUSTOM status key has to hold its loading state
+ * while this is true. `isLoaded === false` alone is not enough to act on:
+ * the difference between "not here yet" and "the request failed" decides
+ * whether the user sees a spinner or a retryable error, and the first cut
+ * showed neither — just a silently empty board. (MUL-6243)
+ */
+ isPending: boolean;
+ /**
+ * The catalog request failed AND there is no usable snapshot to fall back on.
+ *
+ * Narrower than "the query errored" on purpose: a BACKGROUND refetch can fail
+ * while the last successful catalog is still cached, and blocking a surface
+ * then would throw away data that is perfectly serviceable. Only a failure
+ * with nothing behind it is worth stopping for. (MUL-6243)
+ */
+ isError: boolean;
+ /** Re-runs the catalog request. Wired to the surface's retry affordance. */
+ retry: () => void;
+ /**
+ * True when the catalog is LOADED and holds at least one custom status.
+ *
+ * This is the switch for the category-grouped surface contract. Two reasons
+ * it has to be both conditions:
+ *
+ * - Rolling deploy. `group.kind=status_category` is a server contract this
+ * feature introduced, so a client that sends it unconditionally 400s
+ * against any pod that has not been updated yet. A workspace only HAS a
+ * custom status once the creation flag was on, which means the fleet was
+ * already serving this version.
+ * - Cold load. Until the catalog lands, `categoryOf` cannot tell a custom key
+ * from an unknown one and falls back to `todo`. Routing on that guess sends
+ * a saved `qa` filter to the todo column and renders an empty board.
+ *
+ * A workspace with no custom statuses therefore keeps the exact request it
+ * made before this feature — which is also what keeps its board off the extra
+ * catalog reads the category contract needs. (MUL-6243)
+ */
+ hasCustomStatuses: boolean;
}
const BUILT_IN = new Set<string>(STATUS_ORDER);
+const CATEGORY_RANK = new Map<string, number>(STATUS_ORDER.map((c, i) => [c, i]));
+
+/**
+ * The server's catalog ordering, mirrored for client-side re-sorts.
+ * Category rank, then intra-category position, then key as a stable tiebreak —
+ * see `ListIssueStatusEntries` in `issue_status.sql`. An optimistic reorder has
+ * to re-sort with this or the new positions land in the cache while the list
+ * still renders in the old order.
+ */
+export function compareIssueStatusEntries(a: IssueStatusEntry, b: IssueStatusEntry): number {
+ const rank =
+ (CATEGORY_RANK.get(a.category) ?? STATUS_ORDER.length) -
+ (CATEGORY_RANK.get(b.category) ?? STATUS_ORDER.length);
+ if (rank !== 0) return rank;
+ if (a.position !== b.position) return a.position - b.position;
+ return a.key.localeCompare(b.key);
+}
+
export function isIssueStatusCategory(value: string): value is IssueStatusCategory {
return BUILT_IN.has(value);
}
@@ -74,6 +133,7 @@ export function isIssueStatusCategory(value: string): value is IssueStatusCatego
*/
export function buildIssueStatusCatalog(
entries: IssueStatusEntry[] | undefined,
+ status: { isPending?: boolean; isError?: boolean; retry?: () => void } = {},
): IssueStatusCatalog {
const list = entries ?? [];
const byKey = new Map(list.map((e) => [e.key, e]));
@@ -102,5 +162,14 @@ export function buildIssueStatusCatalog(
},
inCategory: (category) => list.filter((e) => e.category === category && !e.archived_at),
isLoaded: entries !== undefined,
+ // Defaults describe a non-React caller holding a list it already has:
+ // resolved when entries are present, still pending when they are not.
+ isPending: status.isPending ?? entries === undefined,
+ // A failure that still has entries behind it is a stale-data situation, not
+ // a blocking one.
+ isError: (status.isError ?? false) && entries === undefined,
+ retry: status.retry ?? (() => {}),
+ hasCustomStatuses:
+ entries !== undefined && list.some((e) => e.is_system !== true),
};
}
diff --git a/packages/core/issue-views/baseline.ts b/packages/core/issue-views/baseline.ts
index 86e15217e4..5aa7a48351 100644
--- a/packages/core/issue-views/baseline.ts
+++ b/packages/core/issue-views/baseline.ts
@@ -1,6 +1,6 @@
import type { ActorFilterValue, FilterSnapshot } from "../issues/stores/view-store";
import type { IssuePriority, IssueStatus } from "../types";
-import { ALL_STATUSES, PRIORITY_DISPLAY_ORDER } from "../issues/config";
+import { PRIORITY_DISPLAY_ORDER } from "../issues/config";
/**
* The open saved view's query, normalized for two jobs:
@@ -46,8 +46,14 @@ function actorArray(v: unknown): ActorFilterValue[] {
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.
+ //
+ // Status is the exception: since MUL-6243 a status filter holds a status KEY,
+ // and a workspace's custom keys are not enumerable from a constant. Filtering
+ // against ALL_STATUSES here silently deleted every custom status filter the
+ // moment a saved view was reopened, so the view came back showing more than
+ // it was saved with. Any non-empty string is a representable status key.
const statusFilters = stringArray(query.statusFilters).filter(
- (s): s is IssueStatus => (ALL_STATUSES as readonly string[]).includes(s),
+ (s): s is IssueStatus => s.length > 0,
);
const priorityFilters = stringArray(query.priorityFilters).filter(
(p): p is IssuePriority => (PRIORITY_DISPLAY_ORDER as readonly string[]).includes(p),
diff --git a/packages/core/issues/index.ts b/packages/core/issues/index.ts
index 28b892e095..8909468607 100644
--- a/packages/core/issues/index.ts
+++ b/packages/core/issues/index.ts
@@ -6,4 +6,12 @@ export * from "./ws-updaters";
export * from "./config";
export * from "./stores";
-export { issueStatusCategory, statusCategoryOfKey, normalizeStatusPatch } from "./status-category";
+export {
+ issueBehavesAs,
+ issueBehavesAsAny,
+ issueStatusCategory,
+ statusCategoryOfKey,
+ statusFilterColumns,
+ type StatusFilterColumnsResult,
+ normalizeStatusPatch,
+} from "./status-category";
diff --git a/packages/core/issues/status-behavior.test.ts b/packages/core/issues/status-behavior.test.ts
new file mode 100644
index 0000000000..5a12bf71f4
--- /dev/null
+++ b/packages/core/issues/status-behavior.test.ts
@@ -0,0 +1,141 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { buildIssueStatusCatalog } from "../issue-statuses";
+import type { Issue, IssueStatusEntry } from "../types";
+import { issueBehavesAs, issueBehavesAsAny, statusFilterColumns } from "./status-category";
+
+function issue(status: string, statusCategory?: string): Pick<Issue, "status" | "status_category"> {
+ return { status, status_category: statusCategory } as Pick<Issue, "status" | "status_category">;
+}
+
+function entry(key: string, category: string, isSystem = false): IssueStatusEntry {
+ return {
+ id: key,
+ workspace_id: "ws-1",
+ key,
+ name: key,
+ description: "",
+ category: category as IssueStatusEntry["category"],
+ color: "#000000",
+ is_system: isSystem,
+ position: 0,
+ archived_at: null,
+ created_at: "",
+ updated_at: "",
+ };
+}
+
+/**
+ * Every status-coupled product rule asks "does this issue behave as X". These
+ * are the cases where comparing the raw key gives the wrong answer.
+ */
+describe("issueBehavesAs", () => {
+ it("answers for a built-in with no catalog and no server hint", () => {
+ expect(issueBehavesAs(issue("done"), "done")).toBe(true);
+ expect(issueBehavesAs(issue("todo"), "done")).toBe(false);
+ });
+
+ // The regression: a custom status in the done category is finished work.
+ // Code comparing `status === "done"` kept it visible under "hide completed",
+ // left it out of sub-issue progress, and ranked it as live in search.
+ it("answers for a custom status from the payload's category", () => {
+ expect(issueBehavesAs(issue("shipped", "done"), "done")).toBe(true);
+ expect(issueBehavesAs(issue("shipped", "done"), "in_review")).toBe(false);
+ });
+
+ it("treats a custom backlog status as backlog", () => {
+ expect(issueBehavesAs(issue("someday", "backlog"), "backlog")).toBe(true);
+ });
+
+ // Fails toward showing more / asking more, never toward hiding work or
+ // starting an agent without confirmation.
+ it("answers false for a custom key this response did not resolve", () => {
+ expect(issueBehavesAs(issue("shipped"), "done")).toBe(false);
+ expect(issueBehavesAs(issue("someday"), "backlog")).toBe(false);
+ });
+
+ it("matches any of several categories", () => {
+ expect(issueBehavesAsAny(issue("qa", "cancelled"), ["done", "cancelled"])).toBe(true);
+ expect(issueBehavesAsAny(issue("qa", "in_review"), ["done", "cancelled"])).toBe(false);
+ });
+});
+
+describe("statusFilterColumns", () => {
+ const loaded = buildIssueStatusCatalog([entry("in_review", "in_review", true), entry("qa", "in_review")]);
+ const pending = buildIssueStatusCatalog(undefined, { isPending: true });
+ const failed = buildIssueStatusCatalog(undefined, { isPending: false, isError: true });
+
+ function columns(result: ReturnType<typeof statusFilterColumns>): string[] {
+ if (result.state !== "resolved") throw new Error(`expected resolved, got ${result.state}`);
+ return [...result.columns];
+ }
+
+ it("resolves built-ins without waiting for the catalog", () => {
+ expect(columns(statusFilterColumns(["todo", "done"], pending))).toEqual(["todo", "done"]);
+ });
+
+ it("maps a custom key to its category once the catalog is loaded", () => {
+ expect(columns(statusFilterColumns(["qa"], loaded))).toEqual(["in_review"]);
+ });
+
+ // The regression: `categoryOf` answers `todo` for anything it has not loaded,
+ // which is indistinguishable from a real `todo`. Routing on that guess paged
+ // the todo column for a saved `qa` filter while the query still restricted
+ // `status=qa`.
+ //
+ // Returning an EMPTY column set was equally wrong: the caller could not tell
+ // "narrow to nothing" from "cannot answer yet", so it fetched no branches and
+ // rendered an empty board with no spinner. Hence the explicit pending state.
+ it("reports pending — not an empty result — while the catalog is in flight", () => {
+ expect(statusFilterColumns(["qa"], pending)).toEqual({ state: "pending" });
+ });
+
+ it("reports error when the catalog request failed, so the surface can retry", () => {
+ expect(statusFilterColumns(["qa"], failed)).toEqual({ state: "error" });
+ });
+
+ // A BACKGROUND refetch can fail while the last successful catalog is still
+ // cached. Blocking then would discard data that is perfectly serviceable and
+ // put a retry screen in front of a surface that could render fine.
+ it("keeps resolving from a cached catalog when a refetch fails", () => {
+ const stale = buildIssueStatusCatalog(
+ [entry("in_review", "in_review", true), entry("qa", "in_review")],
+ { isPending: false, isError: true },
+ );
+
+ expect(stale.isError).toBe(false);
+ expect(columns(statusFilterColumns(["qa"], stale))).toEqual(["in_review"]);
+ });
+
+ // A LOADED catalog that does not know the key is authoritative: the status was
+ // deleted, or belongs to another workspace. That is a resolved answer.
+ it("resolves to no column for a key the loaded catalog has never heard of", () => {
+ expect(columns(statusFilterColumns(["gone"], loaded))).toEqual([]);
+ });
+
+ // A built-in alongside an unresolved custom key still cannot be routed: the
+ // surface would show the built-in column and silently omit the custom one.
+ it("reports pending when any custom key in the filter is unresolved", () => {
+ expect(statusFilterColumns(["todo", "qa"], pending)).toEqual({ state: "pending" });
+ });
+});
+
+describe("IssueStatusCatalog.hasCustomStatuses", () => {
+ // This is the switch for the category-grouped server contract, so it has to
+ // be false in BOTH unsafe states: catalog in flight (cold load), and a
+ // workspace that has none (a backend that may predate the contract).
+ it("is false while the catalog is in flight", () => {
+ expect(buildIssueStatusCatalog(undefined).hasCustomStatuses).toBe(false);
+ });
+
+ it("is false for a workspace holding only the built-ins", () => {
+ const builtInsOnly = ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"].map(
+ (key) => entry(key, key, true),
+ );
+ expect(buildIssueStatusCatalog(builtInsOnly).hasCustomStatuses).toBe(false);
+ });
+
+ it("is true once a custom status exists", () => {
+ expect(buildIssueStatusCatalog([entry("qa", "in_review")]).hasCustomStatuses).toBe(true);
+ });
+});
diff --git a/packages/core/issues/status-category.ts b/packages/core/issues/status-category.ts
index d65601ed87..4324ab6d9f 100644
--- a/packages/core/issues/status-category.ts
+++ b/packages/core/issues/status-category.ts
@@ -1,5 +1,7 @@
import type { Issue, IssueStatusCategory } from "../types";
import { isIssueStatusCategory } from "../issue-statuses";
+import type { IssueStatusCatalog } from "../issue-statuses";
+import { ALL_STATUSES } from "./config";
/**
* The category an issue's status belongs to — the bucket it occupies on the
@@ -62,3 +64,80 @@ export function normalizeStatusPatch(patch: Partial<Issue>): Partial<Issue> {
// silently keep the previous category.
return { ...patch, status_category: category ?? undefined };
}
+
+/**
+ * How an exact status-key filter resolves to board/list COLUMNS (MUL-6243).
+ *
+ * Three states, not two. Built-in keys resolve with no catalog at all, because
+ * a built-in key IS its own category. A CUSTOM key does not — and `categoryOf`
+ * answers `todo` for anything it has not loaded, which is indistinguishable
+ * from a real `todo`. Routing on that guess paged the todo column for a saved
+ * `qa` filter while the query still restricted `status=qa`.
+ *
+ * Returning an empty column set for that case is equally wrong: the caller
+ * cannot tell "narrow to nothing" from "cannot answer yet", so it fetched no
+ * branches and rendered an empty board with no spinner and no error. Hence the
+ * explicit state:
+ *
+ * - `resolved` — every key answered; `columns` is authoritative.
+ * - `pending` — a custom key needs a catalog that is still in flight. Hold the
+ * surface's loading state; do not fetch and do not render empty.
+ * - `error` — the catalog request failed. Show a retryable error; a custom
+ * filter cannot be honoured without it.
+ */
+export type StatusFilterColumnsResult =
+ | { state: "resolved"; columns: Set<IssueStatusCategory> }
+ | { state: "pending" }
+ | { state: "error" };
+
+export function statusFilterColumns(
+ statusFilters: readonly string[],
+ catalog: Pick<IssueStatusCatalog, "entryOf" | "isLoaded" | "isPending" | "isError">,
+): StatusFilterColumnsResult {
+ const columns = new Set<IssueStatusCategory>();
+ for (const key of statusFilters) {
+ if (isIssueStatusCategory(key)) {
+ columns.add(key);
+ continue;
+ }
+ // A custom key. Without an authoritative catalog there is no honest answer.
+ if (catalog.isError) return { state: "error" };
+ if (!catalog.isLoaded) return { state: "pending" };
+ const category = catalog.entryOf(key)?.category;
+ // A LOADED catalog that does not know the key is authoritative too: the
+ // status was deleted, or belongs to another workspace. Contributing no
+ // column is the resolved answer, not a pending one.
+ if (category && ALL_STATUSES.includes(category)) columns.add(category);
+ }
+ return { state: "resolved", columns };
+}
+
+/**
+ * Whether an issue BEHAVES as a given category (MUL-6243).
+ *
+ * The one question every status-coupled product rule actually asks. Comparing
+ * `issue.status` to a built-in key answers it only for a workspace with no
+ * custom statuses: a custom status in the `done` category is done, and code
+ * that checks `status === "done"` silently disagrees.
+ *
+ * An unresolved custom key answers `false`, and that direction is deliberate —
+ * every caller of this fails safe that way. "Is it done/cancelled?" false keeps
+ * a row VISIBLE rather than hiding it; "is it backlog?" false keeps the
+ * agent-run confirmation rather than skipping it. Guessing the other way would
+ * hide work or start an agent without asking.
+ */
+export function issueBehavesAs(
+ issue: Pick<Issue, "status" | "status_category">,
+ category: IssueStatusCategory,
+): boolean {
+ return issueStatusCategory(issue) === category;
+}
+
+/** True when the issue behaves as any of the given categories. */
+export function issueBehavesAsAny(
+ issue: Pick<Issue, "status" | "status_category">,
+ categories: readonly IssueStatusCategory[],
+): boolean {
+ const resolved = issueStatusCategory(issue);
+ return resolved !== null && categories.includes(resolved);
+}
diff --git a/packages/core/issues/stores/view-store-status.test.ts b/packages/core/issues/stores/view-store-status.test.ts
new file mode 100644
index 0000000000..23090fa40a
--- /dev/null
+++ b/packages/core/issues/stores/view-store-status.test.ts
@@ -0,0 +1,76 @@
+// @vitest-environment node
+import { describe, expect, it, beforeEach } from "vitest";
+import { createStore, type StoreApi } from "zustand/vanilla";
+import { viewStoreSlice, type IssueViewState } from "./view-store";
+import { baselineFromQuery } from "../../issue-views/baseline";
+
+/**
+ * Column visibility and the status filter used to be the same field. That was
+ * only ever correct while a category held exactly one status; since MUL-6243 a
+ * category can hold several, and the two questions have different answers.
+ */
+describe("column visibility vs status filter", () => {
+ let store: StoreApi<IssueViewState>;
+ beforeEach(() => {
+ store = createStore<IssueViewState>()((set) => viewStoreSlice(set));
+ });
+
+ // The regression: hiding one column wrote the OTHER six built-in keys into
+ // statusFilters, so the query then excluded every custom status too — hiding
+ // Backlog silently dropped a QA card sitting in the In Review column.
+ it("hiding a column does not touch the status filter", () => {
+ store.getState().hideStatus("backlog");
+
+ expect(store.getState().hiddenStatusCategories).toEqual(["backlog"]);
+ expect(store.getState().statusFilters).toEqual([]);
+ });
+
+ it("showing a column restores it without inventing a filter", () => {
+ store.getState().hideStatus("backlog");
+ store.getState().hideStatus("done");
+ store.getState().showStatus("backlog");
+
+ expect(store.getState().hiddenStatusCategories).toEqual(["done"]);
+ expect(store.getState().statusFilters).toEqual([]);
+ });
+
+ it("hiding the same column twice is idempotent", () => {
+ store.getState().hideStatus("backlog");
+ store.getState().hideStatus("backlog");
+
+ expect(store.getState().hiddenStatusCategories).toEqual(["backlog"]);
+ });
+
+ it("a custom status filter survives hiding and showing a column", () => {
+ store.getState().toggleStatusFilter("qa");
+ store.getState().hideStatus("backlog");
+ store.getState().showStatus("backlog");
+
+ expect(store.getState().statusFilters).toEqual(["qa"]);
+ });
+
+ it("reset restores every column", () => {
+ store.getState().hideStatus("backlog");
+ store.getState().clearFilters();
+
+ expect(store.getState().hiddenStatusCategories).toEqual([]);
+ });
+});
+
+describe("saved view baseline", () => {
+ // The regression: the baseline dropped any status filter that was not one of
+ // the 7 built-ins, so reopening a view saved with a custom status filter came
+ // back showing MORE than it was saved with.
+ it("keeps a custom status filter", () => {
+ const baseline = baselineFromQuery({ statusFilters: ["in_review", "qa"] });
+
+ expect(baseline.status.has("qa")).toBe(true);
+ expect(baseline.status.has("in_review")).toBe(true);
+ });
+
+ it("still drops values it cannot represent", () => {
+ const baseline = baselineFromQuery({ statusFilters: ["", "qa"] });
+
+ expect([...baseline.status]).toEqual(["qa"]);
+ });
+});
diff --git a/packages/core/issues/stores/view-store.ts b/packages/core/issues/stores/view-store.ts
index e9d0be47e4..756300df00 100644
--- a/packages/core/issues/stores/view-store.ts
+++ b/packages/core/issues/stores/view-store.ts
@@ -4,8 +4,7 @@ import { useEffect, useRef } from "react";
import { create } from "zustand";
import { createStore, type StoreApi } from "zustand/vanilla";
import { createJSONStorage, persist } from "zustand/middleware";
-import type { IssueStatus, IssuePriority } from "../../types";
-import { ALL_STATUSES } from "../config";
+import type { IssueStatus, IssueStatusCategory, IssuePriority } from "../../types";
import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";
import { defaultStorage } from "../../platform/storage";
@@ -203,7 +202,18 @@ export interface IssueViewState {
// board / list / swimlane so users can focus on top-level parent issues.
// Purely a display filter — it never touches the parent/child relationship.
showSubIssues: boolean;
- listCollapsedStatuses: IssueStatus[];
+ listCollapsedStatuses: IssueStatusCategory[];
+ /**
+ * Board / list columns the user hid, as CATEGORIES.
+ *
+ * Column visibility used to be expressed by writing the surviving statuses
+ * into `statusFilters`, which stopped being correct once a category can hold
+ * more than one status: hiding Backlog wrote the other 6 built-in keys and
+ * so silently filtered out every CUSTOM status too. Display state and the
+ * exact-key filter are different questions and now have different fields.
+ * (MUL-6243)
+ */
+ hiddenStatusCategories: IssueStatusCategory[];
ganttZoom: GanttZoom;
ganttShowCompleted: boolean;
/** Active swimlane grouping dimension. */
@@ -237,8 +247,8 @@ export interface IssueViewState {
togglePropertyFilter: (propertyId: string, optionId: string) => void;
setDateFilter: (filter: IssueDateFilter | null) => void;
toggleAgentRunningFilter: () => void;
- hideStatus: (status: IssueStatus) => void;
- showStatus: (status: IssueStatus) => void;
+ hideStatus: (category: IssueStatusCategory) => void;
+ showStatus: (category: IssueStatusCategory) => void;
clearFilters: () => void;
/** Clear one filter dimension (a filter-bar chip). `property:<id>` clears
* that definition's entry only. Paired boolean flags (no-assignee /
@@ -252,7 +262,7 @@ export interface IssueViewState {
toggleCardProperty: (key: keyof CardProperties) => void;
toggleCardPropertyId: (propertyId: string) => void;
toggleShowSubIssues: () => void;
- toggleListCollapsed: (status: IssueStatus) => void;
+ toggleListCollapsed: (category: IssueStatusCategory) => void;
setSwimlaneGrouping: (grouping: SwimlaneGrouping) => void;
/** Update the lane order for the currently active swimlane grouping. */
setSwimlaneOrder: (order: string[]) => void;
@@ -297,6 +307,7 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
cardPropertyIds: [],
showSubIssues: true,
listCollapsedStatuses: [],
+ hiddenStatusCategories: [],
ganttZoom: "week",
ganttShowCompleted: false,
swimlaneGrouping: "assignee",
@@ -382,22 +393,16 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
setDateFilter: (filter) => set({ dateFilter: filter }),
toggleAgentRunningFilter: () =>
set((state) => ({ agentRunningFilter: !state.agentRunningFilter })),
- hideStatus: (status) =>
- set((state) => {
- // If no filter active, activate filter with all EXCEPT this one
- if (state.statusFilters.length === 0) {
- return { statusFilters: ALL_STATUSES.filter((s) => s !== status) };
- }
- return {
- statusFilters: state.statusFilters.filter((s) => s !== status),
- };
- }),
- showStatus: (status) =>
- set((state) => {
- if (state.statusFilters.length === 0) return state;
- if (state.statusFilters.includes(status)) return state;
- return { statusFilters: [...state.statusFilters, status] };
- }),
+ hideStatus: (category) =>
+ set((state) =>
+ state.hiddenStatusCategories.includes(category)
+ ? state
+ : { hiddenStatusCategories: [...state.hiddenStatusCategories, category] },
+ ),
+ showStatus: (category) =>
+ set((state) => ({
+ hiddenStatusCategories: state.hiddenStatusCategories.filter((c) => c !== category),
+ })),
clearFilters: () =>
set({
statusFilters: [],
@@ -411,6 +416,9 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
propertyFilters: {},
dateFilter: null,
agentRunningFilter: false,
+ // Reset restores every column, matching what it did when hiding a column
+ // was expressed as a status filter.
+ hiddenStatusCategories: [],
}),
resetFiltersTo: (snapshot) => set({ ...snapshot }),
clearFilterDimension: (dimension) =>
@@ -551,6 +559,7 @@ export const viewStorePersistOptions = (name: string) => ({
cardPropertyIds: state.cardPropertyIds,
showSubIssues: state.showSubIssues,
listCollapsedStatuses: state.listCollapsedStatuses,
+ hiddenStatusCategories: state.hiddenStatusCategories,
ganttZoom: state.ganttZoom,
ganttShowCompleted: state.ganttShowCompleted,
swimlaneGrouping: state.swimlaneGrouping,
diff --git a/packages/core/package.json b/packages/core/package.json
index 9c4f528559..9463ad2763 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -29,6 +29,10 @@
"./workspace/hooks": "./workspace/hooks.ts",
"./workspace/workspace-url": "./workspace/workspace-url.ts",
"./workspace/avatar-url": "./workspace/avatar-url.ts",
+ "./issue-statuses": "./issue-statuses/index.ts",
+ "./issue-statuses/queries": "./issue-statuses/queries.ts",
+ "./issue-statuses/hooks": "./issue-statuses/hooks.ts",
+ "./issue-statuses/mutations": "./issue-statuses/mutations.ts",
"./issues": "./issues/index.ts",
"./issues/batch": "./issues/batch.ts",
"./issues/canonical-id": "./issues/canonical-id.ts",
diff --git a/packages/core/paths/tab-presentation.test.ts b/packages/core/paths/tab-presentation.test.ts
index 7b9f4ee44a..46816e27ea 100644
--- a/packages/core/paths/tab-presentation.test.ts
+++ b/packages/core/paths/tab-presentation.test.ts
@@ -37,7 +37,9 @@ describe("resolveTabPresentation — direct resources", () => {
issue: { identifier: "MUL-1", title: "Fix", status: "in_progress" },
}),
).toEqual({
- visual: { kind: "issue-status", status: "in_progress" },
+ // `category` travels with the visual so the tab strip never has to guess
+ // the glyph for a custom status key. (MUL-6243)
+ visual: { kind: "issue-status", status: "in_progress", category: "in_progress" },
title: { kind: "text", text: "MUL-1: Fix" },
});
});
diff --git a/packages/core/paths/tab-presentation.ts b/packages/core/paths/tab-presentation.ts
index 49c055ee45..c24fb1334c 100644
--- a/packages/core/paths/tab-presentation.ts
+++ b/packages/core/paths/tab-presentation.ts
@@ -16,7 +16,8 @@
* loaded yet renders a stable type icon and a type label, never a wrong or
* empty identity, and never borrows the Issues icon.
*/
-import type { IssueStatus } from "../types";
+import type { IssueStatus, IssueStatusCategory } from "../types";
+import { issueStatusCategory } from "../issues/status-category";
import {
WORKSPACE_PAGES,
type NavLabelKey,
@@ -28,8 +29,10 @@ import type { TabActorType, TabSubject } from "./tab-subject";
export type TabVisual =
/** A static Lucide icon (page icon or resourceless type icon). */
| { kind: "icon"; icon: RouteIconName }
- /** An issue's live status glyph. `null` while the issue is loading. */
- | { kind: "issue-status"; status: IssueStatus | null }
+ /** An issue's live status glyph. `null` while the issue is loading.
+ * `category` is what selects the glyph — carried here so the tab strip
+ * never has to resolve a custom status key on its own. (MUL-6243) */
+ | { kind: "issue-status"; status: IssueStatus | null; category?: IssueStatusCategory }
/** A project's own icon. `null` falls back to the default project glyph. */
| { kind: "project-icon"; icon: string | null }
/** An actor's avatar, resolved by the view layer from `actorType`+`id`. */
@@ -154,7 +157,11 @@ export function resolveTabPresentation(
}
case "issue":
return {
- visual: { kind: "issue-status", status: data.issue?.status ?? null },
+ visual: {
+ kind: "issue-status",
+ status: data.issue?.status ?? null,
+ ...(data.issue ? { category: issueStatusCategory(data.issue) ?? undefined } : {}),
+ },
title: data.issue
? { kind: "text", text: `${data.issue.identifier}: ${data.issue.title}` }
: { kind: "tab", tabKey: "issue" },
diff --git a/packages/core/search/cancelled-rank.ts b/packages/core/search/cancelled-rank.ts
index 502eca6737..394d9ee8e1 100644
--- a/packages/core/search/cancelled-rank.ts
+++ b/packages/core/search/cancelled-rank.ts
@@ -20,6 +20,7 @@
*/
import type { SearchIssueResult, SearchProjectResult } from "../types/api";
+import { issueBehavesAs } from "../issues/status-category";
/**
* Mirrors the server's identifier pattern (parseQueryNumber in
@@ -153,7 +154,9 @@ export function partitionAggregatedSearchResults({
}): AggregatedSearchPartition {
const issueParts = partitionStable(
issues,
- (issue) => issue.status === "cancelled" && !isIssueDirectHit(issue, query),
+ // By CATEGORY: a custom status in the cancelled category is cancelled
+ // work and has to sink the same way. (MUL-6243)
+ (issue) => issueBehavesAs(issue, "cancelled") && !isIssueDirectHit(issue, query),
);
const projectParts = partitionStable(
projects,
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index d2ef26319c..9749980d66 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -305,17 +305,30 @@ export interface IssueTableQuerySpec {
export type IssueTableGroupSpec =
| { kind: "none" }
| { kind: "status" }
+ /**
+ * Group by the CATEGORY a status behaves as, not by the status key.
+ *
+ * Board columns, list sections and swimlane cells are categories, so a custom
+ * status folds into the column it behaves as instead of getting one of its
+ * own — which is what keeps the surface's fan-out pinned at 7 no matter how
+ * many statuses a workspace defines. The descriptor still reports
+ * `value.kind === "status"` because a category's value IS its canonical
+ * status key; the group KEY is what distinguishes the two contracts.
+ * (MUL-6243)
+ */
+ | { kind: "status_category" }
| { kind: "assignee" }
| { kind: "project" }
| { kind: "parent" }
| {
kind: "compound";
primary: "assignee" | "project" | "parent";
- secondary: "status";
+ /** `status_category` folds custom statuses into their category's cell. */
+ secondary: "status" | "status_category";
/** Optional visible secondary buckets. When present, the server pages
* only primary groups that contain at least one matching card and
* returns `total` for that complete visible result set. */
- secondary_values?: IssueStatus[];
+ secondary_values?: IssueStatus[] | IssueStatusCategory[];
}
| { kind: "property"; property_id: string; include_empty?: boolean };
diff --git a/packages/core/types/issue.ts b/packages/core/types/issue.ts
index 289ae1786b..2681184ae4 100644
--- a/packages/core/types/issue.ts
+++ b/packages/core/types/issue.ts
@@ -19,16 +19,16 @@ export type IssueStatusCategory =
| "cancelled";
/**
- * A status KEY as stored on the issue.
+ * A status KEY as stored on the issue: one of the 7 built-ins, or a custom key
+ * an admin defined for this workspace.
*
- * STILL the closed 7-value union. Widening it to `string` — so a workspace's
- * CUSTOM statuses are representable — is the first task of the follow-up PR,
- * because it forces every `Record<IssueStatus, …>` presentation lookup in
- * `packages/views` to resolve a key to its category first. The catalog module
- * and the category type below exist so that change is mechanical rather than
- * exploratory. (MUL-6243)
+ * OPEN by design. `(string & {})` keeps editor autocomplete for the 7 built-ins
+ * while accepting any catalog key, which is what the server has always been
+ * able to send. Anything that needs presentation (label, colour, board column)
+ * must resolve the key to its CATEGORY first — `useIssueStatuses(wsId)` in a
+ * component, `statusCategoryOfKey` in a pure path. (MUL-6243)
*/
-export type IssueStatus = IssueStatusCategory;
+export type IssueStatus = IssueStatusCategory | (string & {});
export type IssuePriority = "urgent" | "high" | "medium" | "low" | "none";
diff --git a/packages/views/chat/components/use-chat-context-items.ts b/packages/views/chat/components/use-chat-context-items.ts
index 8540febcd4..e9a2a5eedb 100644
--- a/packages/views/chat/components/use-chat-context-items.ts
+++ b/packages/views/chat/components/use-chat-context-items.ts
@@ -1,5 +1,6 @@
"use client";
+import { issueStatusCategory } from "@multica/core/issues";
import { useMemo } from "react";
import { useQueries, useQuery } from "@tanstack/react-query";
import { selectRecentContexts, useRecentContextStore, type RecentContextEntry } from "@multica/core/chat";
@@ -15,13 +16,20 @@ function mentionKey(item: Pick<MentionItem, "type" | "id">): string {
return `${item.type}:${item.id}`;
}
-function issueToMentionItem(issue: Pick<Issue, "id" | "identifier" | "title" | "status">, group: "current" | "recent"): MentionItem {
+function issueToMentionItem(
+ issue: Pick<Issue, "id" | "identifier" | "title" | "status"> & Partial<Pick<Issue, "status_category">>,
+ group: "current" | "recent",
+): MentionItem {
return {
id: issue.id,
label: issue.identifier,
type: "issue",
description: issue.title,
status: issue.status,
+ // Carried, not dropped: the list picks its glyph and its dimming from the
+ // category, so losing it here made a custom done status in Current/Recent
+ // render as an active Todo. (MUL-6243)
+ statusCategory: issueStatusCategory(issue) ?? undefined,
group,
};
}
diff --git a/packages/views/editor/extensions/mention-suggestion.test.tsx b/packages/views/editor/extensions/mention-suggestion.test.tsx
index de0a701930..c050a3e455 100644
--- a/packages/views/editor/extensions/mention-suggestion.test.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.test.tsx
@@ -4,7 +4,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { workspaceKeys } from "@multica/core/workspace/queries";
import { issueKeys, PAGINATED_CATEGORIES } from "@multica/core/issues/queries";
import { I18nProvider } from "@multica/core/i18n/react";
-import type { IssueStatus, ListIssuesCache } from "@multica/core/types";
+import type { IssueStatusCategory, ListIssuesCache } from "@multica/core/types";
import type { QueryClient } from "@tanstack/react-query";
import enCommon from "../../locales/en/common.json";
import enAuth from "../../locales/en/auth.json";
@@ -117,7 +117,7 @@ function fakeQc(data: {
const byStatus: ListIssuesCache["byStatus"] = {};
for (const status of PAGINATED_CATEGORIES) {
const bucket = (data.issues ?? []).filter((i) => i.status === status);
- byStatus[status as IssueStatus] = { issues: bucket as never, total: bucket.length };
+ byStatus[status as IssueStatusCategory] = { issues: bucket as never, total: bucket.length };
}
map.set(
JSON.stringify(issueKeys.list("ws-1")),
@@ -906,9 +906,9 @@ describe("MentionList cancelled demotion", () => {
it("sorts cancelled issues below live ones regardless of input order", () => {
const items: MentionItem[] = [
- { id: "i-1", label: "MUL-1", type: "issue", status: "cancelled" },
+ { id: "i-1", label: "MUL-1", type: "issue", status: "cancelled", statusCategory: "cancelled" },
{ id: "i-2", label: "MUL-2", type: "issue", status: "in_progress" },
- { id: "i-3", label: "MUL-3", type: "issue", status: "cancelled" },
+ { id: "i-3", label: "MUL-3", type: "issue", status: "cancelled", statusCategory: "cancelled" },
{ id: "i-4", label: "MUL-4", type: "issue", status: "backlog" },
];
@@ -927,6 +927,7 @@ describe("MentionList cancelled demotion", () => {
label: `MUL-${100 + n}`,
type: "issue" as const,
status: "cancelled" as const,
+ statusCategory: "cancelled" as const,
})),
{ id: "i-live", label: "MUL-9", type: "issue", status: "todo" },
];
@@ -944,7 +945,7 @@ describe("MentionList cancelled demotion", () => {
// "Current" is explicit context, not a relevance hit — demoting it past the
// truncation would make the issue on screen vanish from its own picker.
const items: MentionItem[] = [
- { id: "i-cur", label: "MUL-7", type: "issue", status: "cancelled", group: "current" },
+ { id: "i-cur", label: "MUL-7", type: "issue", status: "cancelled", statusCategory: "cancelled", group: "current" },
{ id: "i-live", label: "MUL-8", type: "issue", status: "in_progress" },
];
@@ -984,7 +985,7 @@ describe("MentionList cancelled demotion", () => {
// The cached row is merged first; without the demotion it would render on
// top of the server's higher-ranked live match.
const items: MentionItem[] = [
- { id: "i-cached", label: "MUL-20", type: "issue", status: "cancelled", description: "Cancelled match" },
+ { id: "i-cached", label: "MUL-20", type: "issue", status: "cancelled", statusCategory: "cancelled", description: "Cancelled match" },
];
render(<I18nWrapper><MentionList items={items} query="match" command={vi.fn()} /></I18nWrapper>);
diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsx
index ba0c045699..2791187ee1 100644
--- a/packages/views/editor/extensions/mention-suggestion.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.tsx
@@ -13,6 +13,7 @@ import {
import type { QueryClient } from "@tanstack/react-query";
import { getCurrentWsId } from "@multica/core/platform";
import { flattenIssueBuckets, issueKeys } from "@multica/core/issues/queries";
+import { issueStatusCategory } from "@multica/core/issues";
import { workspaceKeys } from "@multica/core/workspace/queries";
import { useAuthStore } from "@multica/core/auth";
import { canAssignAgentToIssue } from "@multica/core/permissions";
@@ -42,7 +43,7 @@ import {
TooltipTrigger,
} from "@multica/ui/components/ui/tooltip";
import { cn } from "@multica/ui/lib/utils";
-import type { IssueStatus, ProjectStatus } from "@multica/core/types";
+import type { IssueStatus, IssueStatusCategory, ProjectStatus } from "@multica/core/types";
import { PROJECT_STATUS_CONFIG } from "@multica/core/projects/config";
import type { SuggestionOptions } from "@tiptap/suggestion";
import { PluginKey } from "@tiptap/pm/state";
@@ -76,6 +77,13 @@ export interface MentionItem {
description?: string;
/** Issue status for StatusIcon rendering */
status?: IssueStatus;
+ /**
+ * The category that status behaves as, carried from the issue payload so the
+ * list never has to resolve a custom key itself. Both the glyph and the
+ * "closed / demoted" rules read this — comparing the raw key left a custom
+ * done status looking and ranking like active work. (MUL-6243)
+ */
+ statusCategory?: IssueStatusCategory;
/** Project emoji/icon snapshot for ProjectIcon rendering */
icon?: string | null;
/** Project status snapshot for recent/current project rendering */
@@ -194,7 +202,7 @@ function mergeMentionItems(
*/
function isDemotedCancelled(item: MentionItem, query: string): boolean {
if (isPinnedAboveTruncation(item, query)) return false;
- if (item.type === "issue") return item.status === "cancelled";
+ if (item.type === "issue") return item.statusCategory === "cancelled";
if (item.type === "project") return item.projectStatus === "cancelled";
return false;
}
@@ -523,7 +531,8 @@ function MentionRow({
if (item.type === "issue") {
// Visually dim closed issues (done/cancelled) so they're distinguishable
// from active ones in the suggestion list — they're still selectable.
- const isClosed = item.status === "done" || item.status === "cancelled";
+ const isClosed =
+ item.statusCategory === "done" || item.statusCategory === "cancelled";
return (
<button
type="button"
@@ -535,7 +544,11 @@ function MentionRow({
>
<span className="flex h-7 w-7 shrink-0 items-center justify-center">
{item.status ? (
- <StatusIcon status={item.status} className="h-3.5 w-3.5" />
+ <StatusIcon
+ status={item.status}
+ category={item.statusCategory}
+ className="h-3.5 w-3.5"
+ />
) : (
<ListTodo className="h-3.5 w-3.5 text-muted-foreground" />
)}
@@ -639,13 +652,16 @@ function MentionRow({
// Suggestion config factory
// ---------------------------------------------------------------------------
-function issueToMention(i: Pick<Issue, "id" | "identifier" | "title" | "status">): MentionItem {
+function issueToMention(
+ i: Pick<Issue, "id" | "identifier" | "title" | "status"> & Partial<Pick<Issue, "status_category">>,
+): MentionItem {
return {
id: i.id,
label: i.identifier,
type: "issue" as const,
description: i.title,
status: i.status as IssueStatus,
+ statusCategory: issueStatusCategory(i) ?? undefined,
};
}
diff --git a/packages/views/inbox/components/inbox-context-menu.test.tsx b/packages/views/inbox/components/inbox-context-menu.test.tsx
index e8c586022c..e0d8cabb11 100644
--- a/packages/views/inbox/components/inbox-context-menu.test.tsx
+++ b/packages/views/inbox/components/inbox-context-menu.test.tsx
@@ -7,6 +7,21 @@ import { NavigationProvider } from "../../navigation";
import { I18nProvider } from "@multica/core/i18n/react";
import enInbox from "../../locales/en/inbox.json";
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ // The catalog is server state; these suites render leaves without a
+ // QueryClientProvider, so it is stubbed like the other data hooks. Built-in
+ // keys are their own category, which is what this fixture asserts on.
+ useIssueStatuses: () => ({
+ statuses: [],
+ activeStatuses: [],
+ categoryOf: (key: string) => key,
+ labelOf: (key: string) => key,
+ entryOf: () => undefined,
+ inCategory: () => [],
+ isLoaded: true,
+ }),
+}));
+
vi.mock("../../issues/components", () => ({ StatusIcon: () => null }));
vi.mock("../../issues/components/issue-agent-activity-indicator", () => ({
IssueAgentActivityIndicator: () => null,
diff --git a/packages/views/inbox/components/inbox-detail-label.test.tsx b/packages/views/inbox/components/inbox-detail-label.test.tsx
index 4400bbbd3e..3a85c5a492 100644
--- a/packages/views/inbox/components/inbox-detail-label.test.tsx
+++ b/packages/views/inbox/components/inbox-detail-label.test.tsx
@@ -11,6 +11,19 @@ vi.mock("../../issues/components", () => ({
vi.mock("@multica/core/workspace/hooks", () => ({
useActorName: () => ({ getActorName: () => "Someone" }),
}));
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ // Leaf render test: stub the catalog the same way the other data hooks are
+ // stubbed, so the component can be mounted without a QueryClientProvider.
+ useIssueStatuses: () => ({
+ statuses: [],
+ activeStatuses: [],
+ categoryOf: (key: string) => key,
+ labelOf: (key: string) => key,
+ entryOf: () => undefined,
+ inCategory: () => [],
+ isLoaded: true,
+ }),
+}));
// Resolve accessors against the REAL en locale rather than a stub, so this
// test fails if the unconfirmed case is ever re-pointed at a label that
diff --git a/packages/views/inbox/components/inbox-detail-label.tsx b/packages/views/inbox/components/inbox-detail-label.tsx
index 2e7a39b105..c3a3f5b657 100644
--- a/packages/views/inbox/components/inbox-detail-label.tsx
+++ b/packages/views/inbox/components/inbox-detail-label.tsx
@@ -1,7 +1,7 @@
"use client";
-import { statusCategoryOfKey } from "@multica/core/issues";
-import { STATUS_CONFIG, PRIORITY_CONFIG } from "@multica/core/issues/config";
+import { PRIORITY_CONFIG } from "@multica/core/issues/config";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { formatDateOnly } from "@multica/core/issues/date";
import { useActorName } from "@multica/core/workspace/hooks";
import { StatusIcon, PriorityIcon } from "../../issues/components";
@@ -47,17 +47,25 @@ export function InboxDetailLabel({ item }: { item: InboxItem }) {
const { t } = useT("inbox");
const typeLabels = useTypeLabels();
const { getActorName } = useActorName();
+ // Inbox is a cross-workspace surface, so the catalog is read per item's own
+ // workspace rather than from the route. (MUL-6243)
+ const { categoryOf, entryOf } = useIssueStatuses(item.workspace_id);
const details = item.details ?? {};
switch (item.type) {
case "status_changed": {
if (!details.to) return <span>{typeLabels[item.type]}</span>;
- const label = STATUS_CONFIG[statusCategoryOfKey(details.to)]?.label ?? details.to;
+ const entry = entryOf(details.to);
return (
<span className="inline-flex items-center gap-1">
{t(($) => $.labels.set_status_to)}
- <StatusIcon status={details.to as IssueStatus} className="h-3 w-3" />
- {label}
+ <StatusIcon
+ status={details.to as IssueStatus}
+ category={categoryOf(details.to)}
+ color={entry?.is_system === true ? null : entry?.color}
+ className="h-3 w-3"
+ />
+ {entry?.name ?? details.to}
</span>
);
}
diff --git a/packages/views/inbox/components/inbox-list-item.test.tsx b/packages/views/inbox/components/inbox-list-item.test.tsx
index 99ccd074bc..a28c9f0743 100644
--- a/packages/views/inbox/components/inbox-list-item.test.tsx
+++ b/packages/views/inbox/components/inbox-list-item.test.tsx
@@ -6,6 +6,21 @@ import { NavigationProvider } from "../../navigation";
import type { NavigationAdapter } from "../../navigation";
import { InboxListItem } from "./inbox-list-item";
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ // The catalog is server state; these suites render leaves without a
+ // QueryClientProvider, so it is stubbed like the other data hooks. Built-in
+ // keys are their own category, which is what this fixture asserts on.
+ useIssueStatuses: () => ({
+ statuses: [],
+ activeStatuses: [],
+ categoryOf: (key: string) => key,
+ labelOf: (key: string) => key,
+ entryOf: () => undefined,
+ inCategory: () => [],
+ isLoaded: true,
+ }),
+}));
+
vi.mock("../../issues/components", () => ({ StatusIcon: () => null }));
vi.mock("../../issues/components/issue-agent-activity-indicator", () => ({
IssueAgentActivityIndicator: ({
diff --git a/packages/views/inbox/components/inbox-list-item.tsx b/packages/views/inbox/components/inbox-list-item.tsx
index 6a58efc9a9..8fe5f43ba2 100644
--- a/packages/views/inbox/components/inbox-list-item.tsx
+++ b/packages/views/inbox/components/inbox-list-item.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { StatusIcon } from "../../issues/components";
import {
IssueAgentActivityIndicator,
@@ -51,6 +52,9 @@ export function InboxListItem({
}) {
const { t } = useT("inbox");
const timeAgo = useTimeAgo();
+ // Inbox is a cross-workspace surface, so the catalog is read against the
+ // item's OWN workspace rather than the route's. (MUL-6243)
+ const { categoryOf: statusCategoryOf } = useIssueStatuses(item.workspace_id);
const openContextMenu = useInboxContextMenu();
// Null-safe slug (not useWorkspacePaths, which throws): the row renders in
// tests and could render outside a workspace route; without a slug the
@@ -148,7 +152,11 @@ export function InboxListItem({
</button>
<InboxRowMenu item={item} view={view} />
{item.issue_status && (
- <StatusIcon status={item.issue_status} className="h-3.5 w-3.5 shrink-0" />
+ <StatusIcon
+ status={item.issue_status}
+ category={statusCategoryOf(item.issue_status)}
+ className="h-3.5 w-3.5 shrink-0"
+ />
)}
</div>
</div>
diff --git a/packages/views/issues/actions/issue-actions-menu-items.tsx b/packages/views/issues/actions/issue-actions-menu-items.tsx
index 5928f4ec83..e22265c0fa 100644
--- a/packages/views/issues/actions/issue-actions-menu-items.tsx
+++ b/packages/views/issues/actions/issue-actions-menu-items.tsx
@@ -23,10 +23,12 @@ import type { AgentTask, Issue } from "@multica/core/types";
import { todayDateOnly, addDaysDateOnly } from "@multica/core/issues/date";
import { api } from "@multica/core/api";
import {
- ALL_STATUSES,
PRIORITY_DISPLAY_ORDER,
PRIORITY_CONFIG,
} from "@multica/core/issues/config";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { useStatusOptions } from "../utils/status-options";
import { issueKeys } from "@multica/core/issues/queries";
import { StatusIcon } from "../components/status-icon";
import { PriorityIcon } from "../components/priority-icon";
@@ -102,6 +104,9 @@ export function IssueActionsMenuItems({
onDeletedFallbackPath,
}: IssueActionsMenuItemsProps) {
const { t } = useT("issues");
+ const wsId = useWorkspaceId();
+ const { options: statusOptions } = useStatusOptions(wsId);
+ const { categoryOf, entryOf } = useIssueStatuses(wsId);
const {
isPinned,
updateField,
@@ -151,15 +156,33 @@ export function IssueActionsMenuItems({
{/* Status */}
<P.Sub>
<P.SubTrigger>
- <StatusIcon status={issue.status} className="h-3.5 w-3.5" />
+ <StatusIcon
+ status={issue.status}
+ category={categoryOf(issue.status)}
+ color={entryOf(issue.status)?.color}
+ className="h-3.5 w-3.5"
+ />
{t(($) => $.actions.status)}
</P.SubTrigger>
<P.SubContent>
- {ALL_STATUSES.map((s) => (
- <P.Item key={s} onClick={() => updateField({ status: s })}>
- <StatusIcon status={s} className="h-3.5 w-3.5" />
- {t(($) => $.status[s])}
- {issue.status === s && (
+ {/* Catalog-driven, like the picker and the filter: every entry point
+ that can change a status must offer the same set, or a custom
+ status is unreachable from the board's right-click menu. Flat
+ rather than grouped — these primitives have no label item — but
+ already in canonical category order. (MUL-6243) */}
+ {statusOptions.map((option) => (
+ <P.Item
+ key={option.key}
+ onClick={() => updateField({ status: option.key })}
+ >
+ <StatusIcon
+ status={option.key}
+ category={categoryOf(option.key)}
+ color={option.color}
+ className="h-3.5 w-3.5"
+ />
+ {option.label}
+ {issue.status === option.key && (
<span className="ml-auto text-caption text-muted-foreground">{"✓"}</span>
)}
</P.Item>
diff --git a/packages/views/issues/components/batch-action-toolbar.tsx b/packages/views/issues/components/batch-action-toolbar.tsx
index 79ad530170..7d51ac5d68 100644
--- a/packages/views/issues/components/batch-action-toolbar.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.tsx
@@ -17,6 +17,7 @@ import {
} from "@multica/ui/components/ui/alert-dialog";
import type { Issue, UpdateIssueRequest } from "@multica/core/types";
import { commonIssueFields } from "@multica/core/issues/batch";
+import { issueBehavesAs } from "@multica/core/issues";
import { useBatchUpdateIssues, useBatchDeleteIssues } from "@multica/core/issues/mutations";
import { useModalStore } from "@multica/core/modals";
import { StatusPicker, PriorityPicker, AssigneePicker } from "./pickers";
@@ -131,7 +132,9 @@ export function BatchActionToolbar({
// start" box — apply directly, matching handleBatchStatus's backlog short-
// circuit. A mixed selection still routes through the modal: the non-backlog
// issues will trigger and need confirmation.
- const allBacklog = selectedIssues.every((i) => i.status === "backlog");
+ // Category, not key: a custom status in the backlog category is a parking
+ // lot too, and assigning into it never starts a run. (MUL-6243)
+ const allBacklog = selectedIssues.every((i) => issueBehavesAs(i, "backlog"));
if (!allBacklog) {
openModal("issue-run-confirm", {
issueIds: ids,
diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsx
index 88ef7be1eb..017b6a23c8 100644
--- a/packages/views/issues/components/board-card.tsx
+++ b/packages/views/issues/components/board-card.tsx
@@ -27,6 +27,7 @@ import type { ChildProgress } from "./list-row";
import { IssueActionsContextMenu } from "../actions";
import { LabelChip } from "../../labels/label-chip";
import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";
+import { CustomStatusChip, useIsCustomStatus } from "./custom-status-chip";
import { useIssueSurfaceActionsOptional } from "../surface/actions-context";
import { useT } from "../../i18n";
@@ -91,6 +92,9 @@ export const BoardCardContent = memo(function BoardCardContent({
const showProject = storeProperties.project && project;
const showChildProgress = storeProperties.childProgress && childProgress;
const showLabels = storeProperties.labels && labels.length > 0;
+ // Keeps the chip row from rendering an empty flex container when the status
+ // chip is the only thing in it and it decides to render nothing.
+ const showCustomStatus = useIsCustomStatus(issue.status);
const showAssigneeName = showAssigneeSection && hasAssignee && !showStartDate && !showDueDate;
const showUpdatedHint = showAssigneeName && !showChildProgress;
@@ -196,9 +200,12 @@ export const BoardCardContent = memo(function BoardCardContent({
);
})()}
- {/* Chip row: project + labels + custom property values */}
- {(showProject || showLabels || cardCustomProperties.length > 0) && (
+ {/* Chip row: status + project + labels + custom property values.
+ The status chip renders only for a CUSTOM status — the column header
+ already names the category. (MUL-6243) */}
+ {(showCustomStatus || showProject || showLabels || cardCustomProperties.length > 0) && (
<div className="mt-1.5 flex items-center gap-1.5 flex-wrap">
+ <CustomStatusChip status={issue.status} />
{showProject && (
<span className="inline-flex items-center gap-1 rounded-full bg-muted/60 px-1.5 py-0.5 text-micro text-muted-foreground max-w-[160px]">
<ProjectIcon project={project} size="sm" />
diff --git a/packages/views/issues/components/board-column.tsx b/packages/views/issues/components/board-column.tsx
index 4c1c651e58..062a9888a9 100644
--- a/packages/views/issues/components/board-column.tsx
+++ b/packages/views/issues/components/board-column.tsx
@@ -1,6 +1,5 @@
"use client";
-import { statusCategoryOfKey } from "@multica/core/issues";
import { memo, useCallback, useMemo, useState, type ReactNode } from "react";
import { Virtuoso } from "react-virtuoso";
import { EyeOff, MoreHorizontal, Plus, UserMinus } from "lucide-react";
@@ -9,7 +8,7 @@ import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable"
import type {
Issue,
IssueAssigneeType,
- IssueStatus,
+ IssueStatusCategory,
Project,
} from "@multica/core/types";
import { Button } from "@multica/ui/components/ui/button";
@@ -75,7 +74,8 @@ const EMPTY_VIRTUOSO_COMPONENTS = {};
export interface BoardColumnGroup {
id: string;
title: string;
- status?: IssueStatus;
+ /** Board columns are CATEGORIES, never raw status keys. (MUL-6243) */
+ status?: IssueStatusCategory;
assigneeType?: IssueAssigneeType | null;
assigneeId?: string | null;
/** Set when the board is grouped by a select-type custom property. */
@@ -112,7 +112,7 @@ export const BoardColumn = memo(function BoardColumn({
sortLabel?: string | null;
}) {
const status = group.status;
- const cfg = status ? STATUS_CONFIG[statusCategoryOfKey(status)] : null;
+ 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 —
diff --git a/packages/views/issues/components/board-view.tsx b/packages/views/issues/components/board-view.tsx
index b3c70ca2ce..90e78fa653 100644
--- a/packages/views/issues/components/board-view.tsx
+++ b/packages/views/issues/components/board-view.tsx
@@ -17,7 +17,7 @@ import { toast } from "sonner";
import type {
Issue,
IssueAssigneeType,
- IssueStatus,
+ IssueStatusCategory,
Project,
IssueProperty,
} from "@multica/core/types";
@@ -62,13 +62,13 @@ import {
function isStatusGroup(
group: BoardColumnGroup,
-): group is BoardColumnGroup & { status: IssueStatus } {
+): group is BoardColumnGroup & { status: IssueStatusCategory } {
return group.status !== undefined;
}
function buildGroups(
issues: Issue[],
- visibleStatuses: IssueStatus[],
+ visibleStatuses: IssueStatusCategory[],
grouping: IssueGrouping,
getActorName: (type: string, id: string) => string,
noAssigneeLabel: string,
@@ -168,8 +168,8 @@ function BoardViewImpl({
groupBranches,
}: {
issues: Issue[];
- visibleStatuses: IssueStatus[];
- hiddenStatuses: IssueStatus[];
+ visibleStatuses: IssueStatusCategory[];
+ hiddenStatuses: IssueStatusCategory[];
onMoveIssue: (issueId: string, updates: DragMoveUpdates, onSettled?: () => void) => void;
childProgressMap?: Map<string, ChildProgress>;
projectMap?: Map<string, Project>;
@@ -731,7 +731,7 @@ function BoardHiddenColumnsPanel({
hiddenStatuses,
statusPagination,
}: {
- hiddenStatuses: IssueStatus[];
+ hiddenStatuses: IssueStatusCategory[];
statusPagination?: IssueStatusPagination;
}) {
return (
diff --git a/packages/views/issues/components/custom-status-chip.test.tsx b/packages/views/issues/components/custom-status-chip.test.tsx
new file mode 100644
index 0000000000..e6bfc382a5
--- /dev/null
+++ b/packages/views/issues/components/custom-status-chip.test.tsx
@@ -0,0 +1,80 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { buildIssueStatusCatalog } from "@multica/core/issue-statuses";
+import type { IssueStatusEntry } from "@multica/core/types";
+import { CustomStatusChip } from "./custom-status-chip";
+
+let catalogEntries: IssueStatusEntry[] | undefined;
+
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "workspace-1",
+}));
+
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ useIssueStatuses: () => buildIssueStatusCatalog(catalogEntries),
+}));
+
+function entry(overrides: Partial<IssueStatusEntry>): IssueStatusEntry {
+ return {
+ id: overrides.key ?? "id",
+ workspace_id: "workspace-1",
+ key: "custom",
+ name: "Custom",
+ description: "",
+ category: "in_review",
+ color: "#ff0000",
+ is_system: false,
+ position: 1,
+ archived_at: null,
+ created_at: "",
+ updated_at: "",
+ ...overrides,
+ };
+}
+
+const IN_REVIEW_BUILT_IN = entry({
+ id: "in_review",
+ key: "in_review",
+ name: "In Review",
+ category: "in_review",
+ is_system: true,
+ position: 0,
+});
+
+describe("CustomStatusChip", () => {
+ // The column header already says "In Review". Repeating it on every card
+ // would add a chip to every issue in a workspace that never customized
+ // anything — the change has to be invisible to those workspaces.
+ it("renders nothing for a built-in status", () => {
+ catalogEntries = [IN_REVIEW_BUILT_IN];
+ const { container } = render(<CustomStatusChip status="in_review" />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ // Board columns and list sections are categories, so this chip is the only
+ // thing distinguishing two statuses that share one column.
+ it("names a custom status", () => {
+ catalogEntries = [IN_REVIEW_BUILT_IN, entry({ key: "qa", name: "QA Review" })];
+ render(<CustomStatusChip status="qa" />);
+ expect(screen.getByText("QA Review")).toBeInTheDocument();
+ });
+
+ // An issue can carry a status this client has not fetched yet. Rendering a
+ // chip from a guessed category would be worse than rendering none.
+ it("renders nothing while the catalog is still loading", () => {
+ catalogEntries = undefined;
+ const { container } = render(<CustomStatusChip status="qa" />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ // Archiving retires a status from new assignment; issues already on it keep
+ // it, and those issues still need it named.
+ it("still names an archived custom status", () => {
+ catalogEntries = [
+ IN_REVIEW_BUILT_IN,
+ entry({ key: "qa", name: "QA Review", archived_at: "2026-01-01T00:00:00Z" }),
+ ];
+ render(<CustomStatusChip status="qa" />);
+ expect(screen.getByText("QA Review")).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/issues/components/custom-status-chip.tsx b/packages/views/issues/components/custom-status-chip.tsx
new file mode 100644
index 0000000000..17498f24d6
--- /dev/null
+++ b/packages/views/issues/components/custom-status-chip.tsx
@@ -0,0 +1,75 @@
+"use client";
+
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import type { IssueStatusCatalog } from "@multica/core/issue-statuses";
+import { useWorkspaceId } from "@multica/core/hooks";
+import type { IssueStatus } from "@multica/core/types";
+import { StatusIcon } from "./status-icon";
+
+/**
+ * Whether {@link CustomStatusChip} would render something for this status.
+ *
+ * Layouts that wrap the chip in a container need this: without it a card whose
+ * only chip is the status chip would render an empty flex row with its own
+ * margin whenever the chip decides to stay silent.
+ */
+export function useIsCustomStatus(status: IssueStatus): boolean {
+ const wsId = useWorkspaceId();
+ return isCustomStatus(useIssueStatuses(wsId), status);
+}
+
+/**
+ * Pure predicate behind {@link useIsCustomStatus}, so a component that already
+ * holds the catalog does not open a second observer for the same question.
+ */
+function isCustomStatus(catalog: IssueStatusCatalog, status: IssueStatus): boolean {
+ const entry = catalog.entryOf(status);
+ if (!entry) return false;
+ // `is_system` is the authority; the key comparison covers the window before
+ // the catalog lands, where a built-in must still stay silent.
+ return entry.is_system !== true && status !== catalog.categoryOf(status);
+}
+
+/**
+ * Names an issue's status when the surface around it only shows the CATEGORY
+ * (MUL-6243).
+ *
+ * Board columns and list sections are categories, so two issues sitting in the
+ * same "In Review" column can be on different statuses — "Code Review" and "QA"
+ * — with nothing on the card to tell them apart. This chip is that missing
+ * signal.
+ *
+ * It renders NOTHING for a status that already is its category's built-in: the
+ * column header says "In Review" and a chip repeating it is pure noise. So a
+ * workspace that never defined a custom status sees no visual change at all.
+ */
+export function CustomStatusChip({
+ status,
+ className = "",
+}: {
+ status: IssueStatus;
+ className?: string;
+}) {
+ const wsId = useWorkspaceId();
+ // ONE catalog observer for both the predicate and the entry — subscribing
+ // twice per card is free on the network (React Query dedupes the request) but
+ // not on re-renders.
+ const catalog = useIssueStatuses(wsId);
+ const entry = catalog.entryOf(status);
+
+ if (!isCustomStatus(catalog, status) || !entry) return null;
+
+ return (
+ <span
+ className={`inline-flex max-w-[160px] items-center gap-1 rounded-full bg-muted/60 px-1.5 py-0.5 text-micro text-muted-foreground ${className}`}
+ >
+ <StatusIcon
+ status={status}
+ category={entry.category}
+ color={entry.color}
+ className="size-3"
+ />
+ <span className="truncate">{entry.name}</span>
+ </span>
+ );
+}
diff --git a/packages/views/issues/components/filter-chips-bar.tsx b/packages/views/issues/components/filter-chips-bar.tsx
index 6ebf02a3f2..3f1159c083 100644
--- a/packages/views/issues/components/filter-chips-bar.tsx
+++ b/packages/views/issues/components/filter-chips-bar.tsx
@@ -1,6 +1,7 @@
"use client";
-import { statusCategoryOfKey } from "@multica/core/issues";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { useStatusLabel } from "../utils/status-label";
import { useMemo, type ReactNode } from "react";
import {
CalendarDays,
@@ -179,6 +180,8 @@ function useFilterChips(
) {
const { t } = useT("issues");
const wsId = useWorkspaceId();
+ const resolveStatusLabel = useStatusLabel(wsId);
+ const { categoryOf, entryOf } = useIssueStatuses(wsId);
const statusFilters = useViewStore((s) => s.statusFilters);
const priorityFilters = useViewStore((s) => s.priorityFilters);
@@ -344,13 +347,19 @@ function useFilterChips(
valueIcons: (
<IconStack>
{deltaStatus.slice(0, 3).map((s) => (
- <StatusIcon key={s} status={s} className="size-3" />
+ <StatusIcon
+ key={s}
+ status={s}
+ category={categoryOf(s)}
+ color={entryOf(s)?.is_system === true ? null : entryOf(s)?.color}
+ className="size-3"
+ />
))}
</IconStack>
),
value:
onlyStatus !== undefined && deltaStatus.length === 1
- ? t(($) => $.status[statusCategoryOfKey(onlyStatus)])
+ ? resolveStatusLabel(onlyStatus)
: t(($) => $.filters.chip_status_count, { count: deltaStatus.length }),
onRemove: () => clearDimension("status"),
});
diff --git a/packages/views/issues/components/gantt-view.tsx b/packages/views/issues/components/gantt-view.tsx
index cb3f5d8658..419bd4a336 100644
--- a/packages/views/issues/components/gantt-view.tsx
+++ b/packages/views/issues/components/gantt-view.tsx
@@ -7,7 +7,8 @@ import { useWorkspacePaths } from "@multica/core/paths";
import { useViewStore, useViewStoreApi } from "@multica/core/issues/stores/view-store-context";
import type { GanttZoom } from "@multica/core/issues/stores/view-store";
import { projectListOptions } from "@multica/core/projects/queries";
-import type { Issue, IssueStatus } from "@multica/core/types";
+import type { Issue, IssueStatusCategory } from "@multica/core/types";
+import { issueStatusCategory } from "@multica/core/issues";
import { dateOnlyToUTCDate } from "@multica/core/issues/date";
import { cn } from "@multica/ui/lib/utils";
import {
@@ -290,7 +291,11 @@ function BackgroundLayer({
// Bar color by status (uses semantic Tailwind tokens, not hardcoded colors).
// ---------------------------------------------------------------------------
-const STATUS_BAR_BG: Record<IssueStatus, string> = {
+// Keyed by CATEGORY, not by status key: an issue on a custom status draws in
+// the color of the category it behaves as. Keying this by IssueStatus made the
+// lookup `undefined` for every custom key, so the bar lost its color entirely.
+// (MUL-6243)
+const STATUS_BAR_BG: Record<IssueStatusCategory, string> = {
backlog: "bg-muted-foreground/60",
todo: "bg-muted-foreground/70",
in_progress: "bg-warning",
@@ -371,7 +376,11 @@ function ScheduledRow({
className="sticky left-0 z-[1] flex shrink-0 items-center gap-2 border-r bg-background px-3 text-body min-w-0"
style={{ width: LEFT_COL_WIDTH }}
>
- <StatusIcon status={issue.status} className="h-3.5 w-3.5" />
+ <StatusIcon
+ status={issue.status}
+ category={issueStatusCategory(issue) ?? undefined}
+ className="h-3.5 w-3.5"
+ />
<PriorityIcon priority={issue.priority} />
<span className="w-14 shrink-0 text-caption text-muted-foreground tabular-nums truncate">
{issue.identifier}
@@ -404,7 +413,7 @@ function ScheduledRow({
bar.isMarker
? "h-3 w-3 rotate-45 rounded-[2px]"
: "h-5 rounded-md",
- STATUS_BAR_BG[issue.status],
+ STATUS_BAR_BG[issueStatusCategory(issue) ?? "todo"],
inverted && "ring-2 ring-destructive ring-offset-1 ring-offset-background",
)}
style={{ left: bar.left, width: bar.width }}
diff --git a/packages/views/issues/components/hidden-columns-panel.tsx b/packages/views/issues/components/hidden-columns-panel.tsx
index 6a9b0f4bec..fe33491a80 100644
--- a/packages/views/issues/components/hidden-columns-panel.tsx
+++ b/packages/views/issues/components/hidden-columns-panel.tsx
@@ -2,7 +2,7 @@
import { statusCategoryOfKey } from "@multica/core/issues";
import { Eye, MoreHorizontal } from "lucide-react";
-import type { IssueStatus } from "@multica/core/types";
+import type { IssueStatusCategory } from "@multica/core/types";
import { Button } from "@multica/ui/components/ui/button";
import {
DropdownMenu,
@@ -28,8 +28,8 @@ export function HiddenColumnsPanel({
hiddenStatuses,
renderRow,
}: {
- hiddenStatuses: IssueStatus[];
- renderRow: (status: IssueStatus) => React.ReactNode;
+ hiddenStatuses: IssueStatusCategory[];
+ renderRow: (status: IssueStatusCategory) => React.ReactNode;
}) {
const { t } = useT("issues");
return (
@@ -54,7 +54,7 @@ export function HiddenColumnRow({
status,
total,
}: {
- status: IssueStatus;
+ status: IssueStatusCategory;
total?: number;
}) {
const { t } = useT("issues");
diff --git a/packages/views/issues/components/issue-chip.tsx b/packages/views/issues/components/issue-chip.tsx
index 90c1c6af89..65ab3dd694 100644
--- a/packages/views/issues/components/issue-chip.tsx
+++ b/packages/views/issues/components/issue-chip.tsx
@@ -1,5 +1,6 @@
"use client";
+import { issueStatusCategory } from "@multica/core/issues";
import type { ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { issueListOptions, issueDetailOptions } from "@multica/core/issues/queries";
@@ -84,7 +85,11 @@ export function IssueChip({
return (
<span className={cls}>
- <StatusIcon status={issue.status} className="h-3.5 w-3.5 shrink-0" />
+ <StatusIcon
+ status={issue.status}
+ category={issueStatusCategory(issue) ?? undefined}
+ className="h-3.5 w-3.5 shrink-0"
+ />
<span className="font-medium text-muted-foreground shrink-0">
{issue.identifier}
</span>
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 2b90095c6d..8ea3be2736 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -1,5 +1,13 @@
"use client";
+import {
+ issueBehavesAs,
+ issueBehavesAsAny,
+ issueStatusCategory,
+ statusCategoryOfKey,
+} from "@multica/core/issues";
+import { useStatusLabel } from "../utils/status-label";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { useState, useEffect, useCallback, useMemo, useRef, Fragment, type ReactNode } from "react";
import { Virtuoso, type VirtuosoHandle } from "react-virtuoso";
import { useDefaultLayout, usePanelRef } from "react-resizable-panels";
@@ -52,7 +60,7 @@ import { AvatarGroup, AvatarGroupCount } from "@multica/ui/components/ui/avatar"
import { ActorAvatar } from "../../common/actor-avatar";
import { PropRow } from "../../common/prop-row";
import { PropertyIcon } from "../../common/property-icon";
-import type { Attachment, Issue, IssueProperty, IssueStatus, IssuePriority, TimelineEntry, UpdateIssueRequest } from "@multica/core/types";
+import type { Attachment, Issue, IssueProperty, IssueStatus, IssueStatusCategory, IssuePriority, TimelineEntry, UpdateIssueRequest } from "@multica/core/types";
import { contentReferencesAttachment } from "@multica/core/types";
import { STATUS_CONFIG, PRIORITY_CONFIG } from "@multica/core/issues/config";
import { formatDateOnly, isPastDateOnly } from "@multica/core/issues/date";
@@ -253,9 +261,20 @@ function shortDate(date: string | null): string {
type ActivityT = ReturnType<typeof useT<"issues">>["t"];
-function statusLabel(status: string, t: ActivityT): string {
+/**
+ * Labels a status key from the activity feed. `resolveLabel` is the workspace
+ * catalog resolver, which names custom statuses; without it — or for a status
+ * since deleted — a built-in still gets its i18n name and anything else falls
+ * back to the raw key. (MUL-6243)
+ */
+function statusLabel(
+ status: string,
+ t: ActivityT,
+ resolveLabel?: (statusKey: string) => string,
+): string {
+ if (resolveLabel) return resolveLabel(status);
if (status in STATUS_CONFIG) {
- return t(($) => $.status[status as IssueStatus]);
+ return t(($) => $.status[statusCategoryOfKey(status)]);
}
return status;
}
@@ -271,6 +290,7 @@ function formatActivity(
entry: TimelineEntry,
t: ActivityT,
resolveActorName?: (type: string, id: string) => string,
+ resolveStatusLabel?: (statusKey: string) => string,
): string {
const details = (entry.details ?? {}) as Record<string, string>;
switch (entry.action) {
@@ -278,8 +298,8 @@ function formatActivity(
return t(($) => $.activity.created);
case "status_changed":
return t(($) => $.activity.status_changed, {
- from: statusLabel(details.from ?? "?", t),
- to: statusLabel(details.to ?? "?", t),
+ from: statusLabel(details.from ?? "?", t, resolveStatusLabel),
+ to: statusLabel(details.to ?? "?", t, resolveStatusLabel),
});
case "priority_changed":
return t(($) => $.activity.priority_changed, {
@@ -507,6 +527,8 @@ function ActivityBlock({
showOlder,
onToggleShowOlder,
getActorName,
+ resolveStatusLabel,
+ resolveStatusCategory,
t,
timeAgo,
}: {
@@ -520,6 +542,8 @@ function ActivityBlock({
showOlder: boolean;
onToggleShowOlder: () => void;
getActorName: (type: string, id: string) => string;
+ resolveStatusLabel: (statusKey: string) => string;
+ resolveStatusCategory: (statusKey: string) => IssueStatusCategory;
t: ActivityT;
timeAgo: (dateStr: string) => string;
}) {
@@ -582,7 +606,13 @@ function ActivityBlock({
let leadIcon: React.ReactNode;
if (isStatusChange && details.to) {
- leadIcon = <StatusIcon status={details.to as IssueStatus} className="h-4 w-4 shrink-0" />;
+ leadIcon = (
+ <StatusIcon
+ status={details.to as IssueStatus}
+ category={resolveStatusCategory(details.to ?? "")}
+ className="h-4 w-4 shrink-0"
+ />
+ );
} else if (isPriorityChange && details.to) {
leadIcon = <PriorityIcon priority={details.to as IssuePriority} className="h-4 w-4 shrink-0" />;
} else if (isStartDateChange) {
@@ -600,7 +630,7 @@ function ActivityBlock({
</div>
<div className="flex min-w-0 flex-1 items-center gap-1">
<span className="shrink-0 font-medium">{getActorName(entry.actor_type, entry.actor_id)}</span>
- <span className="truncate">{formatActivity(entry, t, getActorName)}</span>
+ <span className="truncate">{formatActivity(entry, t, getActorName, resolveStatusLabel)}</span>
{(entry.coalesced_count ?? 1) > 1 &&
entry.action !== "task_completed" &&
entry.action !== "task_failed" && (
@@ -651,7 +681,9 @@ function SubIssueRow({
const updateIssue = useUpdateIssue();
const selected = useIssueSelectionStore((s) => s.selectedIds.has(child.id));
const toggleSelected = useIssueSelectionStore((s) => s.toggle);
- const isDone = child.status === "done" || child.status === "cancelled";
+ // Category, not key: a custom status in the done/cancelled categories is
+ // finished work and has to strike through like any other. (MUL-6243)
+ const isDone = issueBehavesAsAny(child, ["done", "cancelled"]);
const labels = rowProps.labels ? (child.labels ?? []) : [];
const customPropsWithValue = customProperties.filter(
(p) => child.properties?.[p.id] !== undefined,
@@ -1095,6 +1127,8 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
currentUserRole === "owner" || currentUserRole === "admin";
const { data: allIssues = [] } = useQuery(issueListOptions(wsId));
const { getActorName } = useActorName();
+ const resolveStatusLabel = useStatusLabel(wsId);
+ const { categoryOf: resolveStatusCategory } = useIssueStatuses(wsId);
// Description autosave is deliberately NOT gated (no explicit submit; the
// editor already strips `blob:` before serializing and binds ids on the
// later save). It still needs the failure toast, or a failed upload just
@@ -2300,7 +2334,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
href={paths.issueDetail(parentIssue.id)}
className="flex flex-1 min-w-0 items-center gap-1.5 py-1.5 text-caption"
>
- <StatusIcon status={parentIssue.status} className="h-3.5 w-3.5 shrink-0" />
+ <StatusIcon
+ status={parentIssue.status}
+ category={issueStatusCategory(parentIssue) ?? undefined}
+ className="h-3.5 w-3.5 shrink-0"
+ />
<span className="text-muted-foreground shrink-0">{parentIssue.identifier}</span>
<span className="truncate group-hover:text-foreground">{parentIssue.title}</span>
</AppLink>
@@ -2463,6 +2501,8 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
showOlder={showOlder}
onToggleShowOlder={() => showOlderActivities(item.id)}
getActorName={getActorName}
+ resolveStatusLabel={resolveStatusLabel}
+ resolveStatusCategory={resolveStatusCategory}
t={t}
timeAgo={timeAgo}
/>
@@ -2548,7 +2588,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
onOpenChange={handleThreadNavOpenChange}
/>
)}
- {onDone && issue.status !== "done" && issue.status !== "cancelled" && (
+ {onDone && !issueBehavesAsAny(issue, ["done", "cancelled"]) && (
<Tooltip>
<TooltipTrigger
render={
@@ -2565,7 +2605,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
<TooltipContent side="bottom">{t(($) => $.detail.mark_done_tooltip)}</TooltipContent>
</Tooltip>
)}
- {onDone && issue.status === "done" && (
+ {onDone && issueBehavesAs(issue, "done") && (
<Tooltip>
<TooltipTrigger
render={
@@ -2691,13 +2731,17 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
className="mt-2 inline-flex max-w-full items-center gap-1.5 text-caption text-muted-foreground hover:text-foreground transition-colors group/parent"
>
<span className="font-medium shrink-0">{t(($) => $.detail.sub_issue_of)}</span>
- <StatusIcon status={parentIssue.status} className="h-3.5 w-3.5 shrink-0" />
+ <StatusIcon
+ status={parentIssue.status}
+ category={issueStatusCategory(parentIssue) ?? undefined}
+ className="h-3.5 w-3.5 shrink-0"
+ />
<span className="tabular-nums shrink-0">{parentIssue.identifier}</span>
<span className="truncate group-hover/parent:text-foreground">
{parentIssue.title}
</span>
{parentChildIssues.length > 0 && (() => {
- const done = parentChildIssues.filter((c) => c.status === "done").length;
+ const done = parentChildIssues.filter((c) => issueBehavesAs(c, "done")).length;
return (
<span className="ml-1 inline-flex items-center gap-1 rounded-full bg-muted/60 px-1.5 py-0.5 shrink-0">
<ProgressRing done={done} total={parentChildIssues.length} size={11} />
@@ -2783,7 +2827,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
</div>
)}
{childIssues.length > 0 && (() => {
- const doneCount = childIssues.filter((c) => c.status === "done").length;
+ const doneCount = childIssues.filter((c) => issueBehavesAs(c, "done")).length;
return (
// Provider hosts the shared right-click actions menu the rows
// delegate to (one singleton menu, not one per row).
diff --git a/packages/views/issues/components/issue-hover-card.test.tsx b/packages/views/issues/components/issue-hover-card.test.tsx
index 9a5724e552..ea8271ee9d 100644
--- a/packages/views/issues/components/issue-hover-card.test.tsx
+++ b/packages/views/issues/components/issue-hover-card.test.tsx
@@ -13,6 +13,20 @@ vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "workspace-1",
}));
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ // This suite replaces useQuery wholesale, so the catalog hook is stubbed
+ // rather than left to fall through the shared useQuery mock.
+ useIssueStatuses: () => ({
+ statuses: [],
+ activeStatuses: [],
+ categoryOf: (key: string) => key,
+ labelOf: (key: string) => key,
+ entryOf: () => undefined,
+ inCategory: () => [],
+ isLoaded: true,
+ }),
+}));
+
vi.mock("@multica/core/issues/queries", () => ({
issueDetailOptions: (_workspaceId: string, issueId: string) => ({
queryKey: ["issue", issueId],
diff --git a/packages/views/issues/components/issue-hover-card.tsx b/packages/views/issues/components/issue-hover-card.tsx
index 43734f1dd5..550880ce2d 100644
--- a/packages/views/issues/components/issue-hover-card.tsx
+++ b/packages/views/issues/components/issue-hover-card.tsx
@@ -1,6 +1,7 @@
"use client";
-import { statusCategoryOfKey } from "@multica/core/issues";
+import { issueStatusCategory } from "@multica/core/issues";
+import { useStatusLabel } from "./../utils/status-label";
import type { ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
import { childIssueProgressOptions, issueDetailOptions } from "@multica/core/issues/queries";
@@ -117,6 +118,7 @@ function IssueHoverCardBody({
fallbackLabel?: string;
}) {
const wsId = useWorkspaceId();
+ const resolveStatusLabel = useStatusLabel(wsId);
const detail = useQuery(issueDetailOptions(wsId, issueId));
// One workspace-wide progress snapshot shared with the issues list and issue
// detail, not a per-issue children fetch: opening a card reuses the cache.
@@ -181,10 +183,14 @@ function IssueHoverCardBody({
)}
<span
role="img"
- aria-label={t(($) => $.status[statusCategoryOfKey(issue.status)])}
+ aria-label={resolveStatusLabel(issue.status)}
className="flex shrink-0"
>
- <StatusIcon status={issue.status} className="h-3.5 w-3.5 shrink-0" />
+ <StatusIcon
+ status={issue.status}
+ category={issueStatusCategory(issue) ?? undefined}
+ className="h-3.5 w-3.5 shrink-0"
+ />
</span>
<span className="text-caption font-medium text-muted-foreground">
{issue.identifier}
diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsx
index 835b6a3497..6334606f61 100644
--- a/packages/views/issues/components/issues-header.tsx
+++ b/packages/views/issues/components/issues-header.tsx
@@ -1,6 +1,6 @@
"use client";
-import { cloneElement, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { cloneElement, Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ArrowDown,
ArrowUp,
@@ -57,7 +57,6 @@ import {
} from "@multica/ui/components/ui/select";
import { Toggle } from "@multica/ui/components/ui/toggle";
import {
- ALL_STATUSES,
PRIORITY_DISPLAY_ORDER,
} from "@multica/core/issues/config";
import { StatusIcon, PriorityIcon } from ".";
@@ -116,6 +115,7 @@ import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/
import { cn } from "@multica/ui/lib/utils";
import { PAGE_GUTTER } from "../../layout/page-header";
import { useT } from "../../i18n";
+import { useStatusOptions } from "../utils/status-options";
import { matchesPinyin } from "../../editor/extensions/pinyin-match";
import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
import { WorkspaceAgentWorkingChip } from "./workspace-agent-working-chip";
@@ -1212,6 +1212,7 @@ export function IssueFilterMenu({
const viewStoreApi = useViewStoreApi();
const act = viewStoreApi.getState();
const wsId = useWorkspaceId();
+ const { groups: statusGroups, hasCustom: showStatusGroupLabels } = useStatusOptions(wsId);
const { data: workspaceProperties = [] } = useQuery(propertyListOptions(wsId));
const filterableProperties = useMemo(
() =>
@@ -1306,30 +1307,50 @@ export function IssueFilterMenu({
)}
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-auto min-w-48">
- {ALL_STATUSES.map((s) => {
- const checked = statusFilters.includes(s);
- const count = counts.status.get(s) ?? 0;
- const fixed = viewBaseline?.status.has(s) === true;
- return (
- <DropdownMenuCheckboxItem
- key={s}
- checked={checked}
- disabled={fixed}
- title={fixed ? fixedTitle : undefined}
- onCheckedChange={() => act.toggleStatusFilter(s)}
- className={FILTER_ITEM_CLASS}
- >
- <HoverCheck checked={checked} />
- <StatusIcon status={s} className="h-3.5 w-3.5" />
- {t(($) => $.status[s])}
- {count > 0 && (
- <span className="ml-auto text-caption text-muted-foreground">
- {t(($) => $.filters.issue_count, { count })}
- </span>
- )}
- </DropdownMenuCheckboxItem>
- );
- })}
+ {/* Options come from the workspace catalog, so a custom status
+ is filterable — otherwise an issue moved onto one could not
+ be narrowed to. Grouped by category, and headings appear
+ only once a category holds more than one status, so a
+ workspace that never customized anything sees the same flat
+ 7-row list. (MUL-6243) */}
+ {statusGroups.map((group) => (
+ <Fragment key={group.category}>
+ {showStatusGroupLabels && (
+ <DropdownMenuLabel className="text-caption text-muted-foreground">
+ {t(($) => $.status[group.category])}
+ </DropdownMenuLabel>
+ )}
+ {group.options.map((option) => {
+ const checked = statusFilters.includes(option.key);
+ const count = counts.status.get(option.key) ?? 0;
+ const fixed = viewBaseline?.status.has(option.key) === true;
+ return (
+ <DropdownMenuCheckboxItem
+ key={option.key}
+ checked={checked}
+ disabled={fixed}
+ title={fixed ? fixedTitle : undefined}
+ onCheckedChange={() => act.toggleStatusFilter(option.key)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={checked} />
+ <StatusIcon
+ status={option.key}
+ category={group.category}
+ color={option.color}
+ className="h-3.5 w-3.5"
+ />
+ {option.label}
+ {count > 0 && (
+ <span className="ml-auto text-caption text-muted-foreground">
+ {t(($) => $.filters.issue_count, { count })}
+ </span>
+ )}
+ </DropdownMenuCheckboxItem>
+ );
+ })}
+ </Fragment>
+ ))}
</DropdownMenuSubContent>
</DropdownMenuSub>
diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsx
index c55d69b837..71f893fc57 100644
--- a/packages/views/issues/components/issues-page.test.tsx
+++ b/packages/views/issues/components/issues-page.test.tsx
@@ -117,7 +117,9 @@ const mockListIssueTableRows = vi.hoisted(() =>
next_cursor: null,
};
}
- const status = request.group_key?.replace(/^status:/, "");
+ // Board / list surfaces page by CATEGORY since MUL-6243. This fixture
+ // holds only built-in statuses, where a key IS its own category.
+ const status = request.group_key?.replace(/^status(_category)?:/, "");
const response = await mockListIssues({
status,
limit: 50,
@@ -318,6 +320,7 @@ const mockViewState = {
{ key: "labels", width: 220 },
],
listCollapsedStatuses: [] as string[],
+ hiddenStatusCategories: [] as string[],
setViewMode: vi.fn(),
setGrouping: vi.fn(),
toggleStatusFilter: vi.fn(),
diff --git a/packages/views/issues/components/list-row.tsx b/packages/views/issues/components/list-row.tsx
index 918e2d3b76..00525307b5 100644
--- a/packages/views/issues/components/list-row.tsx
+++ b/packages/views/issues/components/list-row.tsx
@@ -22,6 +22,7 @@ import { PriorityIcon } from "./priority-icon";
import { ProgressRing } from "./progress-ring";
import { IssueActionsContextMenu } from "../actions";
import { LabelChip } from "../../labels/label-chip";
+import { CustomStatusChip } from "./custom-status-chip";
import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";
import { useIssueSurfaceSelection } from "../surface/selection-context";
@@ -114,6 +115,9 @@ function ListRowContent({
<span className="flex min-w-0 flex-1 items-center gap-1.5">
<span className="truncate">{issue.title}</span>
+ {/* List sections are categories, so a custom status needs to name
+ itself on the row. Silent for built-ins. (MUL-6243) */}
+ <CustomStatusChip status={issue.status} className="shrink-0" />
{showChildProgress && (
<span className="inline-flex shrink-0 items-center gap-1 rounded-full bg-muted/60 px-1.5 py-0.5">
<ProgressRing done={childProgress!.done} total={childProgress!.total} size={14} />
diff --git a/packages/views/issues/components/list-view.tsx b/packages/views/issues/components/list-view.tsx
index 0481190d90..fa3105a7e9 100644
--- a/packages/views/issues/components/list-view.tsx
+++ b/packages/views/issues/components/list-view.tsx
@@ -17,7 +17,7 @@ import {
import { SortableContext, verticalListSortingStrategy, arrayMove } from "@dnd-kit/sortable";
import { Virtuoso } from "react-virtuoso";
import { Button } from "@multica/ui/components/ui/button";
-import type { Issue, IssueStatus, Project } from "@multica/core/types";
+import type { Issue, IssueStatusCategory, Project } from "@multica/core/types";
import { useViewStore } from "@multica/core/issues/stores/view-store-context";
import { StatusHeading } from "./status-heading";
import { ListRow, DraggableListRow, type ChildProgress } from "./list-row";
@@ -57,7 +57,7 @@ const LIST_ROW_ESTIMATED_HEIGHT = 36;
const EMPTY_PROGRESS_MAP = new Map<string, ChildProgress>();
const EMPTY_IDS: string[] = [];
-function buildListGroups(visibleStatuses: IssueStatus[]): BoardColumnGroup[] {
+function buildListGroups(visibleStatuses: IssueStatusCategory[]): BoardColumnGroup[] {
return visibleStatuses.map((status) => ({
id: statusGroupId(status),
title: status,
@@ -77,7 +77,7 @@ function ListViewImpl({
onCreateIssue,
}: {
issues: Issue[];
- visibleStatuses: IssueStatus[];
+ visibleStatuses: IssueStatusCategory[];
childProgressMap?: Map<string, ChildProgress>;
projectMap?: Map<string, Project>;
statusPagination: IssueStatusPagination;
@@ -357,7 +357,7 @@ function ListViewImpl({
const wasExpanded = expandedStatuses.includes(status);
const isExpanded = value.includes(status);
if (wasExpanded !== isExpanded) {
- toggleListCollapsed(status as IssueStatus);
+ toggleListCollapsed(status as IssueStatusCategory);
}
}
}}
@@ -432,7 +432,7 @@ function StatusAccordionItem({
sortLabel,
scrollParent,
}: {
- status: IssueStatus;
+ status: IssueStatusCategory;
issueIds: string[];
issueMap: Map<string, Issue>;
childProgressMap: Map<string, ChildProgress>;
diff --git a/packages/views/issues/components/pickers/property-picker.tsx b/packages/views/issues/components/pickers/property-picker.tsx
index f0326d7d3f..52f9e17c1f 100644
--- a/packages/views/issues/components/pickers/property-picker.tsx
+++ b/packages/views/issues/components/pickers/property-picker.tsx
@@ -229,6 +229,19 @@ export function PropertyPicker({
// PickerItem — single selectable row
// ---------------------------------------------------------------------------
+/**
+ * Non-interactive section heading inside a picker list. Rendered as a plain
+ * element, not a button, so `ITEM_SELECTOR` skips it and arrow-key navigation
+ * moves between real options only.
+ */
+export function PickerGroupLabel({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="px-2 pb-1 pt-2 text-caption font-medium text-muted-foreground first:pt-1">
+ {children}
+ </div>
+ );
+}
+
export function PickerItem({
selected,
disabled,
diff --git a/packages/views/issues/components/pickers/status-picker.tsx b/packages/views/issues/components/pickers/status-picker.tsx
index 9d4ec1ab9d..4a6aedddd8 100644
--- a/packages/views/issues/components/pickers/status-picker.tsx
+++ b/packages/views/issues/components/pickers/status-picker.tsx
@@ -1,12 +1,18 @@
"use client";
-import { statusCategoryOfKey } from "@multica/core/issues";
-import { useState } from "react";
+import { useMemo, useState } from "react";
import type { IssueStatus, UpdateIssueRequest } from "@multica/core/types";
-import { ALL_STATUSES, STATUS_CONFIG } from "@multica/core/issues/config";
+import { STATUS_CONFIG } from "@multica/core/issues/config";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { useWorkspaceId } from "@multica/core/hooks";
import { StatusIcon } from "../status-icon";
-import { PropertyPicker, PickerItem } from "./property-picker";
+import { PropertyPicker, PickerItem, PickerGroupLabel } from "./property-picker";
import { useT } from "../../../i18n";
+import { useStatusLabel } from "../../utils/status-label";
+import { useStatusOptions } from "../../utils/status-options";
+
+/** Above this many options the flat list stops being scannable. */
+const SEARCH_THRESHOLD = 9;
export function StatusPicker({
status,
@@ -34,42 +40,97 @@ export function StatusPicker({
const [internalOpen, setInternalOpen] = useState(false);
const open = controlledOpen ?? internalOpen;
const setOpen = controlledOnOpenChange ?? setInternalOpen;
+ const [query, setQuery] = useState("");
const { t } = useT("issues");
+ // Every StatusPicker call site lives inside the workspace shell (issue
+ // detail, table, board batch toolbar, create-issue modal), so the provider
+ // is guaranteed here.
+ const wsId = useWorkspaceId();
+ const { categoryOf, entryOf } = useIssueStatuses(wsId);
+ const labelOf = useStatusLabel(wsId);
+
+ /**
+ * Offerable statuses grouped by category, in canonical category order.
+ *
+ * Archived statuses are excluded: archiving retires a status from future
+ * assignment while leaving the issues already on it untouched. Falls back to
+ * the 7 built-ins until the catalog lands, so a cold render offers exactly
+ * what it always did instead of an empty popover. (MUL-6243)
+ */
+ const { groups: allGroups, options: allOptions, hasCustom } = useStatusOptions(wsId);
+
+ const groups = useMemo(() => {
+ const q = query.trim().toLowerCase();
+ if (!q) return allGroups;
+ return allGroups
+ .map((g) => ({
+ ...g,
+ options: g.options.filter((o) => o.label.toLowerCase().includes(q)),
+ }))
+ .filter((g) => g.options.length > 0);
+ }, [allGroups, query]);
+
+ // Category headings only earn their space once a category holds more than
+ // one status. A workspace that never customized anything sees the same flat
+ // 7-row list as before.
+ const showGroupLabels = hasCustom;
+ const searchable = allOptions.length > SEARCH_THRESHOLD;
return (
<PropertyPicker
open={open}
- onOpenChange={setOpen}
- width="w-44"
+ onOpenChange={(v) => {
+ if (!v) setQuery("");
+ setOpen(v);
+ }}
+ width="w-52"
align={align}
triggerRender={triggerRender}
+ searchable={searchable}
+ searchPlaceholder={t(($) => $.filters.search_status)}
+ onSearchChange={setQuery}
trigger={
customTrigger ??
(status != null ? (
<>
- <StatusIcon status={status} className="h-3.5 w-3.5 shrink-0" />
- <span className="truncate">{t(($) => $.status[statusCategoryOfKey(status)])}</span>
+ <StatusIcon
+ status={status}
+ category={categoryOf(status)}
+ color={entryOf(status)?.color}
+ className="h-3.5 w-3.5 shrink-0"
+ />
+ <span className="truncate">{labelOf(status)}</span>
</>
) : null)
}
>
- {ALL_STATUSES.map((s) => {
- const c = STATUS_CONFIG[s];
- return (
- <PickerItem
- key={s}
- selected={s === status}
- hoverClassName={c.hoverBg}
- onClick={() => {
- onUpdate({ status: s });
- setOpen(false);
- }}
- >
- <StatusIcon status={s} className="h-3.5 w-3.5" />
- <span>{t(($) => $.status[statusCategoryOfKey(s)])}</span>
- </PickerItem>
- );
- })}
+ {groups.map((group) => (
+ <div key={group.category}>
+ {showGroupLabels && (
+ <PickerGroupLabel>{t(($) => $.status[group.category])}</PickerGroupLabel>
+ )}
+ {group.options.map((option) => (
+ <PickerItem
+ key={option.key}
+ selected={option.key === status}
+ hoverClassName={STATUS_CONFIG[group.category].hoverBg}
+ onClick={() => {
+ onUpdate({ status: option.key });
+ setOpen(false);
+ setQuery("");
+ }}
+ >
+ <StatusIcon
+ status={option.key}
+ category={group.category}
+ color={option.color}
+ className="h-3.5 w-3.5"
+ />
+ <span className="truncate">{option.label}</span>
+ </PickerItem>
+ ))}
+ </div>
+ ))}
</PropertyPicker>
);
}
diff --git a/packages/views/issues/components/status-icon.tsx b/packages/views/issues/components/status-icon.tsx
index e18e3108c2..7419aa5c2e 100644
--- a/packages/views/issues/components/status-icon.tsx
+++ b/packages/views/issues/components/status-icon.tsx
@@ -1,5 +1,5 @@
import { statusCategoryOfKey } from "@multica/core/issues";
-import type { IssueStatus } from "@multica/core/types";
+import type { IssueStatus, IssueStatusCategory } from "@multica/core/types";
import { STATUS_CONFIG } from "@multica/core/issues/config";
// ---------------------------------------------------------------------------
@@ -144,7 +144,7 @@ function CancelledIcon() {
// Renderer map
// ---------------------------------------------------------------------------
-const STATUS_RENDERERS: Record<IssueStatus, () => React.ReactNode> = {
+const STATUS_RENDERERS: Record<IssueStatusCategory, () => React.ReactNode> = {
backlog: BacklogIcon,
todo: TodoIcon,
in_progress: InProgressIcon,
@@ -160,22 +160,40 @@ const STATUS_RENDERERS: Record<IssueStatus, () => React.ReactNode> = {
export function StatusIcon({
status,
+ category: categoryProp,
+ color,
className = "h-4 w-4",
inheritColor = false,
}: {
status: IssueStatus | string;
+ /**
+ * Resolved category, for callers that hold the workspace catalog. Without it
+ * the key resolves on its own, which is exact for the 7 built-ins and falls
+ * back to `todo` for a custom key this render has no catalog for.
+ */
+ category?: IssueStatusCategory;
+ /** A custom status's `#rrggbb`. Built-ins keep their semantic token color. */
+ color?: string | null;
className?: string;
inheritColor?: boolean;
}) {
- const knownStatus = status in STATUS_RENDERERS ? (status as IssueStatus) : null;
- const cfg = knownStatus ? STATUS_CONFIG[statusCategoryOfKey(knownStatus)] : null;
- const Renderer = knownStatus ? STATUS_RENDERERS[knownStatus] : TodoIcon;
+ // The glyph set is per CATEGORY: a custom status renders with its category's
+ // icon, which is what makes it read as "the same kind of thing". (MUL-6243)
+ const category = categoryProp ?? statusCategoryOfKey(status);
+ const cfg = STATUS_CONFIG[category];
+ const Renderer = STATUS_RENDERERS[category] ?? TodoIcon;
+ // A custom color wins over the category's token, but only when the caller
+ // isn't already forcing the glyph to inherit (selected rows, dark chips).
+ const useCustomColor = !inheritColor && Boolean(color);
return (
<svg
viewBox="0 0 14 14"
fill="none"
- className={`${className} ${inheritColor ? "" : cfg?.iconColor ?? "text-muted-foreground"} shrink-0`}
+ style={useCustomColor ? { color: color ?? undefined } : undefined}
+ className={`${className} ${
+ inheritColor || useCustomColor ? "" : cfg?.iconColor ?? "text-muted-foreground"
+ } shrink-0`}
>
<Renderer />
</svg>
diff --git a/packages/views/issues/components/swimlane-view.tsx b/packages/views/issues/components/swimlane-view.tsx
index 153e678f5f..5c482c4c07 100644
--- a/packages/views/issues/components/swimlane-view.tsx
+++ b/packages/views/issues/components/swimlane-view.tsx
@@ -1,5 +1,6 @@
"use client";
+import { issueStatusCategory, statusCategoryOfKey } from "@multica/core/issues";
import { memo, useState, useCallback, useMemo, useEffect, useRef } from "react";
import {
DndContext,
@@ -24,6 +25,7 @@ import type {
Issue,
IssueAssigneeType,
IssueStatus,
+ IssueStatusCategory,
IssueTableGroupDescriptor,
Project,
UpdateIssueRequest,
@@ -35,6 +37,7 @@ 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 { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { useActorName } from "@multica/core/workspace/hooks";
import { childrenByParentsOptions, issueKeys } from "@multica/core/issues/queries";
import {
@@ -624,8 +627,8 @@ function SwimLaneViewImpl({
*/
unfilteredIssues?: Issue[];
activeFilters?: Omit<IssueFilters, "statusFilters">;
- visibleStatuses?: IssueStatus[];
- hiddenStatuses?: IssueStatus[];
+ visibleStatuses?: IssueStatusCategory[];
+ hiddenStatuses?: IssueStatusCategory[];
onMoveIssue: (
issueId: string,
updates: SwimLaneMoveUpdates,
@@ -649,6 +652,7 @@ function SwimLaneViewImpl({
const swimlaneOrder = swimlaneOrders[swimlaneGrouping];
const wsId = useWorkspaceId();
+ const { categoryOf } = useIssueStatuses(wsId);
const activeFilters = useMemo(() => ({
// Status is enforced by visible-column rendering, not by filterIssues
@@ -926,21 +930,24 @@ function SwimLaneViewImpl({
// parent gets promoted to a lane header and the count for that status
// drops by 1. Tracked as a follow-up.
const statusTotals = useMemo(() => {
+ // Columns are CATEGORIES, so totals bucket by category: a custom status
+ // contributes to the column it behaves as, never to a column of its own.
if (groupBranches?.enabled) {
- const totals = new Map<IssueStatus, number>();
+ const totals = new Map<IssueStatusCategory, number>();
for (const lane of groupBranches.descriptors) {
for (const cell of lane.secondary_groups ?? []) {
if (cell.value.kind !== "status") continue;
- const status = cell.value.status as IssueStatus;
- totals.set(status, (totals.get(status) ?? 0) + cell.count);
+ const category = categoryOf(cell.value.status as IssueStatus);
+ totals.set(category, (totals.get(category) ?? 0) + cell.count);
}
}
return totals;
}
- const totals = new Map<IssueStatus, number>();
+ const totals = new Map<IssueStatusCategory, number>();
for (const issue of laneSourceIssues) {
if (headerIssueIds.has(issue.id)) continue;
- totals.set(issue.status, (totals.get(issue.status) ?? 0) + 1);
+ const category = categoryOf(issue.status);
+ totals.set(category, (totals.get(category) ?? 0) + 1);
}
return totals;
}, [groupBranches, laneSourceIssues, headerIssueIds]);
@@ -1395,7 +1402,7 @@ function SwimLaneViewImpl({
<div className="sticky top-0 z-10 mb-2 bg-background/95 pb-2 backdrop-blur supports-[backdrop-filter]:bg-background/75">
<div style={gridStyle}>
{sortedStatuses.map((status) => {
- const cfg = STATUS_CONFIG[status];
+ const cfg = STATUS_CONFIG[statusCategoryOfKey(status)];
const total = statusTotals.get(status) ?? 0;
return (
<div
@@ -1612,7 +1619,11 @@ function DraggableSwimLane({
className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${isCollapsed ? "" : "rotate-90"}`}
/>
{lane.parentIssue && (
- <StatusIcon status={lane.parentIssue.status} className="size-3.5" />
+ <StatusIcon
+ status={lane.parentIssue.status}
+ category={issueStatusCategory(lane.parentIssue) ?? undefined}
+ className="size-3.5"
+ />
)}
{lane.project && <ProjectIcon project={lane.project} size="sm" />}
{lane.actor && (
@@ -1720,7 +1731,7 @@ function SwimLaneCell({
// reject the drop, so visual confirmation would be misleading.
const isOver = readOnly ? false : droppableIsOver;
const { t } = useT("issues");
- const cfg = STATUS_CONFIG[status];
+ const cfg = STATUS_CONFIG[statusCategoryOfKey(status)];
const resolvedIssues = useMemo(
() =>
@@ -1803,8 +1814,8 @@ function SwimLaneHiddenColumnsPanel({
hiddenStatuses,
statusTotals,
}: {
- hiddenStatuses: IssueStatus[];
- statusTotals: Map<IssueStatus, number>;
+ hiddenStatuses: IssueStatusCategory[];
+ statusTotals: Map<IssueStatusCategory, number>;
}) {
return (
<HiddenColumnsPanel
diff --git a/packages/views/issues/components/table-view.tsx b/packages/views/issues/components/table-view.tsx
index d229ae3335..037cf22547 100644
--- a/packages/views/issues/components/table-view.tsx
+++ b/packages/views/issues/components/table-view.tsx
@@ -1,5 +1,6 @@
"use client";
+import { useStatusLabel } from "../utils/status-label";
import {
useCallback,
useEffect,
@@ -72,7 +73,6 @@ import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { cn } from "@multica/ui/lib/utils";
import { ApiError } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
-import { ALL_STATUSES } from "@multica/core/issues/config";
import {
issueKeys,
issueTableGroupsOptions,
@@ -98,7 +98,6 @@ import type {
Issue,
IssueProperty,
IssuePropertyValue,
- IssueStatus,
IssueTableGroupDescriptor,
IssueTableGroupSpec,
IssueTableQuerySpec,
@@ -1281,6 +1280,7 @@ export function TableView({
}: TableViewProps) {
const { t } = useT("issues");
const wsId = useWorkspaceId();
+ const resolveStatusLabel = useStatusLabel(wsId);
const queryClient = useQueryClient();
const intentNavigate = useIntentNavigate();
const paths = useWorkspacePaths();
@@ -1752,13 +1752,12 @@ export function TableView({
(descriptor: IssueTableGroupDescriptor) => {
const value = descriptor.value;
if (value.kind === "status") {
- if (ALL_STATUSES.includes(value.status as IssueStatus)) {
- return t(($) => $.status[value.status as IssueStatus]);
- }
- // Installed clients can receive a status introduced by a newer
- // backend. Keep the group usable instead of collapsing the response
- // to the schema fallback or rendering an empty label.
- return value.status;
+ // A group is one status KEY, so it shows that status's own name — a
+ // custom status must not read as its category. `resolveStatusLabel`
+ // falls back to the raw key, which is also what keeps a status
+ // introduced by a NEWER backend usable on an installed client instead
+ // of collapsing to the schema fallback or an empty label. (MUL-6243)
+ return resolveStatusLabel(value.status);
}
if (value.kind === "assignee") {
return value.actor
@@ -2309,7 +2308,7 @@ export function TableView({
case "identifier":
return issue.identifier;
case "status":
- return t(($) => $.status[issue.status]);
+ return resolveStatusLabel(issue.status);
case "priority":
return t(($) => $.priority[issue.priority]);
case "assignee":
diff --git a/packages/views/issues/surface/issue-surface.test.tsx b/packages/views/issues/surface/issue-surface.test.tsx
index e1cf9dc490..918304bee5 100644
--- a/packages/views/issues/surface/issue-surface.test.tsx
+++ b/packages/views/issues/surface/issue-surface.test.tsx
@@ -163,6 +163,10 @@ describe("IssueSurface — scope switch loading semantics", () => {
return Promise.resolve({ issues, total: issues.length });
});
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
...statusTableMethodsFromLegacy(listIssues),
listGroupedIssues: vi.fn(() => never()),
@@ -250,6 +254,10 @@ describe("IssueSurface — scope switch loading semantics", () => {
return Promise.resolve({ issues, total: issues.length });
});
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
...statusTableMethodsFromLegacy(listIssues),
listGroupedIssues: vi.fn(() => never()),
@@ -325,6 +333,10 @@ describe("IssueSurface — table pagination ownership", () => {
}));
const listIssueTableRows = vi.fn(() => never());
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
listIssueTableRows,
listIssueTableFacets: vi.fn(() => never()),
@@ -422,6 +434,10 @@ describe("IssueSurface — table pagination ownership", () => {
),
);
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
listIssueTableRows,
listIssueTableFacets: vi.fn(() => never()),
@@ -490,6 +506,10 @@ describe("IssueSurface — table pagination ownership", () => {
const issue = makeIssue("table-selected", "Loaded Table issue", "pt-batch");
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
listIssueTableRows: vi.fn(() =>
Promise.resolve({
@@ -558,6 +578,10 @@ describe("IssueSurface — table pagination ownership", () => {
: never(),
);
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
listIssueTableRows,
listIssueTableFacets: vi.fn(() => never()),
@@ -626,6 +650,10 @@ describe("IssueSurface — table pagination ownership", () => {
);
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
listIssueTableGroups: vi.fn(() =>
Promise.resolve({
@@ -715,6 +743,10 @@ describe("IssueSurface — filtered empty state", () => {
Promise.resolve({ issues: [], total: 0 } satisfies ListIssuesResponse),
);
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
...statusTableMethodsFromLegacy(listIssues),
listGroupedIssues: vi.fn(() => never()),
@@ -782,3 +814,150 @@ describe("IssueSurface — filtered empty state", () => {
expect(screen.queryByText("filtered_empty.title")).toBeNull();
});
});
+
+/**
+ * The status catalog is server state, so it can fail. A CUSTOM status filter
+ * cannot be routed to a column without it, so row fetching is suspended — which
+ * means every other branch of the surface would render an unexplained empty
+ * view. The user has to see WHY and be able to do something about it.
+ */
+describe("IssueSurface — status catalog failure", () => {
+ let qc: QueryClient;
+
+ function installApi(listIssueStatuses: () => Promise<unknown>) {
+ rowRequests.length = 0;
+ const listIssues = vi.fn(() => Promise.resolve({ issues: [], total: 0 }));
+ const tableMethods = statusTableMethodsFromLegacy(listIssues);
+ setApiInstance({
+ listIssueStatuses,
+ listIssues,
+ ...tableMethods,
+ listIssueTableRows: vi.fn((request: IssueTableRowsRequest) => {
+ rowRequests.push(request);
+ return tableMethods.listIssueTableRows(request);
+ }),
+ listGroupedIssues: vi.fn(() => never()),
+ listProjects: vi.fn(() => never()),
+ getAgentTaskSnapshot: vi.fn(() => never<AgentTask[]>()),
+ getChildIssueProgress: vi.fn(() => never()),
+ } as unknown as ApiClient);
+ }
+
+ const rowRequests: IssueTableRowsRequest[] = [];
+
+ const QA_ENTRY = {
+ id: "s-qa",
+ workspace_id: "ws-1",
+ key: "qa",
+ name: "QA",
+ description: "",
+ category: "in_review" as const,
+ color: "#ff0000",
+ is_system: false,
+ position: 1,
+ archived_at: null,
+ created_at: "",
+ updated_at: "",
+ };
+
+ beforeEach(() => {
+ mockWsId.current = "ws-1";
+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ pruneIssueSurfaceViewStates([]);
+ });
+
+ afterEach(() => {
+ cleanup();
+ qc.clear();
+ pruneIssueSurfaceViewStates([]);
+ vi.restoreAllMocks();
+ });
+
+ it("shows a retryable error, and recovers fetching when the retry succeeds", async () => {
+ let attempt = 0;
+ installApi(() => {
+ attempt += 1;
+ return attempt === 1
+ ? Promise.reject(new Error("catalog unavailable"))
+ // The retry answers with the entry the `qa` filter needs, so a
+ // recovered catalog routes it to the in_review column and fetches.
+ : Promise.resolve({ statuses: [QA_ENTRY], categories: [], total: 1 });
+ });
+
+ const store = getIssueSurfaceViewStore("project:cat-fail");
+ act(() => store.getState().toggleStatusFilter("qa"));
+
+ render(
+ <QueryClientProvider client={qc}>
+ <IssueSurface
+ scope={{ type: "project", projectId: "cat-fail" }}
+ modes={["list"]}
+ renderHeader={() => null}
+ renderLoading={() => <div data-testid="surface-loading" />}
+ batchToolbar="never"
+ />
+ </QueryClientProvider>,
+ );
+
+ // The regression: row fetching is suspended, isLoading/isEmpty are both
+ // false, and the surface fell straight through to the content branch — an
+ // empty view with no explanation and no way out.
+ const alert = await screen.findByRole("alert");
+ expect(rowRequests).toEqual([]);
+ expect(screen.queryByTestId("surface-loading")).toBeNull();
+
+ const retry = alert.querySelector("button");
+ expect(retry).not.toBeNull();
+
+ fireEvent.click(retry!);
+
+ // Retry succeeds → the error clears and the surface resumes fetching.
+ await waitFor(() => expect(screen.queryByRole("alert")).toBeNull());
+ await waitFor(() => expect(rowRequests.length).toBeGreaterThan(0));
+ });
+
+ // The stale-data RULE lives in status-behavior.test.ts ("keeps resolving from
+ // a cached catalog when a refetch fails"); this is the wiring check that the
+ // surface actually honours it end to end.
+ it("keeps using the last successful catalog when a refetch fails", async () => {
+ let attempt = 0;
+ installApi(() => {
+ attempt += 1;
+ return attempt === 1
+ ? Promise.resolve({ statuses: [QA_ENTRY], categories: [], total: 1 })
+ : Promise.reject(new Error("refetch failed"));
+ });
+
+ const store = getIssueSurfaceViewStore("project:cat-stale");
+ act(() => store.getState().toggleStatusFilter("qa"));
+
+ render(
+ <QueryClientProvider client={qc}>
+ <IssueSurface
+ scope={{ type: "project", projectId: "cat-stale" }}
+ modes={["list"]}
+ renderHeader={() => null}
+ renderLoading={() => <div data-testid="surface-loading" />}
+ batchToolbar="never"
+ />
+ </QueryClientProvider>,
+ );
+
+ await waitFor(() => expect(rowRequests.length).toBeGreaterThan(0));
+ const before = rowRequests.length;
+
+ await act(async () => {
+ await qc.refetchQueries({ queryKey: ["issue-statuses", "ws-1"] }).catch(() => {});
+ });
+
+ // Precondition: the refetch really did fail, and the cached catalog
+ // survived it. Without this the assertions below would pass vacuously.
+ const state = qc.getQueryState(["issue-statuses", "ws-1", "list"]);
+ expect(state?.status).toBe("error");
+ expect(state?.data).toBeDefined();
+
+ // Still no blocking error, and the surface never stopped fetching.
+ expect(screen.queryByRole("alert")).toBeNull();
+ expect(rowRequests.length).toBeGreaterThanOrEqual(before);
+ });
+});
diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsx
index 074136bc6a..f86efc7f35 100644
--- a/packages/views/issues/surface/issue-surface.tsx
+++ b/packages/views/issues/surface/issue-surface.tsx
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
-import { FilterX, ListTodo, Plus } from "lucide-react";
+import { AlertTriangle, FilterX, ListTodo, Plus } from "lucide-react";
import { Button } from "@multica/ui/components/ui/button";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { cn } from "@multica/ui/lib/utils";
@@ -261,7 +261,13 @@ function IssueSurfaceContent({
}
/>
)}
- {controller.isLoading ? (
+ {/* A failed status catalog precedes loading/empty/content on purpose.
+ Row fetching is suspended while it is down (a custom status filter
+ cannot be routed without it), so every branch below would render an
+ unexplained empty surface with no way out. (MUL-6243) */}
+ {controller.isStatusCatalogError ? (
+ <StatusCatalogErrorState onRetry={controller.retryStatusCatalog} />
+ ) : controller.isLoading ? (
renderLoading ? (
renderLoading(renderContext)
) : (
@@ -373,6 +379,23 @@ function IssueSurfaceContent({
* copy only describes the unfiltered case. The action clears exactly the
* filters this state tests for, so it always restores content.
*/
+function StatusCatalogErrorState({ onRetry }: { onRetry: () => void }) {
+ const { t } = useT("issues");
+ return (
+ <div
+ role="alert"
+ className="flex flex-1 min-h-0 flex-col items-center justify-center gap-3 text-muted-foreground"
+ >
+ <AlertTriangle className="h-10 w-10 text-faint-foreground" />
+ <p className="text-body">{t(($) => $.status_catalog_error.title)}</p>
+ <p className="text-caption">{t(($) => $.status_catalog_error.hint)}</p>
+ <Button variant="outline" size="sm" className="mt-1" onClick={onRetry}>
+ {t(($) => $.status_catalog_error.retry)}
+ </Button>
+ </div>
+ );
+}
+
function FilteredEmptyState() {
const { t } = useT("issues");
const clearFilters = useViewStore((s) => s.clearFilters);
diff --git a/packages/views/issues/surface/status-table-test-api.ts b/packages/views/issues/surface/status-table-test-api.ts
index 46435af6eb..7d94eb864a 100644
--- a/packages/views/issues/surface/status-table-test-api.ts
+++ b/packages/views/issues/surface/status-table-test-api.ts
@@ -34,6 +34,21 @@ export interface WorkingAgentsFixture {
agents: () => readonly WorkingTaskFixture[];
}
+/**
+ * Group-key axis for a status grouping. Board / list / swimlane surfaces page by
+ * CATEGORY (`status_category:<category>`); the table still groups by concrete
+ * status key. This fixture holds only built-in statuses, where a key IS its own
+ * category, so the two axes select the same rows — only the key shape differs.
+ * (MUL-6243)
+ */
+function statusAxis(group: { kind: string }): string {
+ return group.kind === "status_category" ? "status_category" : "status";
+}
+
+function secondaryAxis(group: { kind: string; secondary?: string }): string {
+ return group.secondary === "status_category" ? "status_category" : "status";
+}
+
function legacyParamsForStatus(
query: IssueTableQuerySpec,
status: IssueStatus,
@@ -221,7 +236,7 @@ export function statusTableMethodsFromLegacy(
const count = issues.filter((issue) => issue.status === status).length;
return count
? [{
- key: `compound:${descriptor.key}:status:${status}`,
+ key: `compound:${descriptor.key}:${secondaryAxis(request.group)}:${status}`,
value: { kind: "status" as const, status },
count,
}]
@@ -242,7 +257,7 @@ export function statusTableMethodsFromLegacy(
query_fingerprint: "test",
total: nonEmpty.reduce((sum, group) => sum + group.issues.length, 0),
groups: nonEmpty.map(({ status, issues }) => ({
- key: `status:${status}`,
+ key: `${statusAxis(request.group)}:${status}`,
value: { kind: "status" as const, status },
count: issues.length,
})),
@@ -252,11 +267,10 @@ export function statusTableMethodsFromLegacy(
listIssueTableRows: async (request: IssueTableRowsRequest) => {
if (request.group.kind === "compound") {
const primary = request.group.primary;
- const marker = request.group_key?.lastIndexOf(":status:") ?? -1;
+ const axis = `:${secondaryAxis(request.group)}:`;
+ const marker = request.group_key?.lastIndexOf(axis) ?? -1;
const status =
- marker >= 0
- ? request.group_key?.slice(marker + ":status:".length)
- : undefined;
+ marker >= 0 ? request.group_key?.slice(marker + axis.length) : undefined;
const primaryKey =
marker >= 0
? request.group_key?.slice("compound:".length, marker)
@@ -284,7 +298,7 @@ export function statusTableMethodsFromLegacy(
next_cursor: null,
};
}
- const rawStatus = request.group_key?.replace(/^status:/, "");
+ const rawStatus = request.group_key?.replace(/^status(_category)?:/, "");
const status = ALL_STATUSES.find((value) => value === rawStatus);
const issues = status
? await rowsForStatus(listIssues, request.query, status)
diff --git a/packages/views/issues/surface/use-issue-group-branches.category.test.tsx b/packages/views/issues/surface/use-issue-group-branches.category.test.tsx
new file mode 100644
index 0000000000..5dfda81356
--- /dev/null
+++ b/packages/views/issues/surface/use-issue-group-branches.category.test.tsx
@@ -0,0 +1,150 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { setApiInstance } from "@multica/core/api";
+import type { ApiClient } from "@multica/core/api/client";
+import type {
+ Issue,
+ IssueStatusCategory,
+ IssueTableGroupsRequest,
+ IssueTableRowsRequest,
+} from "@multica/core/types";
+import { useIssueGroupBranches } from "./use-issue-group-branches";
+
+/**
+ * Swimlane cells are CATEGORIES when the compound secondary axis says so. The
+ * server returning a custom `qa` row into the `in_review` cell is only half the
+ * job — the client re-checks each row against its descriptor, and matching the
+ * raw key there (`qa !== "in_review"`) threw the card away again.
+ */
+
+function makeIssue(id: string, status: string, category: IssueStatusCategory): Issue {
+ return {
+ id,
+ workspace_id: "ws-1",
+ number: 1,
+ identifier: `MUL-${id}`,
+ title: id,
+ description: null,
+ status,
+ status_category: category,
+ priority: "none",
+ assignee_type: null,
+ assignee_id: null,
+ creator_type: "member",
+ creator_id: "u-1",
+ project_id: "p1",
+ parent_issue_id: null,
+ stage: null,
+ position: 1,
+ start_date: null,
+ due_date: null,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ } as Issue;
+}
+
+const QUERY = {
+ scope: { kind: "workspace" as const },
+ filters: {},
+ sort: { field: "position" as const, direction: "asc" as const },
+};
+
+const CELL_KEY = "compound:project:p1:status_category:in_review";
+
+function wrapper(qc: QueryClient) {
+ return function Wrapper({ children }: { children: ReactNode }) {
+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe("useIssueGroupBranches — category secondary axis", () => {
+ function setup(secondary: "status" | "status_category") {
+ const listIssueTableGroups = vi.fn(async (_request: IssueTableGroupsRequest) => ({
+ query_fingerprint: "test",
+ total: 2,
+ groups: [
+ {
+ key: "project:p1",
+ value: { kind: "project" as const, project_id: "p1" },
+ count: 2,
+ secondary_groups: [
+ {
+ key: CELL_KEY,
+ value: { kind: "status" as const, status: "in_review" },
+ count: 2,
+ },
+ ],
+ },
+ ],
+ next_cursor: null,
+ }));
+ const listIssueTableRows = vi.fn(async (request: IssueTableRowsRequest) => ({
+ query_fingerprint: "test",
+ group_key: request.group_key ?? null,
+ parent_id: null,
+ total: 2,
+ rows: [
+ { issue: makeIssue("qa-1", "qa", "in_review"), direct_child_count: 0 },
+ { issue: makeIssue("std-1", "in_review", "in_review"), direct_child_count: 0 },
+ ],
+ branch_total: 2,
+ next_cursor: null,
+ }));
+ setApiInstance({ listIssueTableGroups, listIssueTableRows } as unknown as ApiClient);
+
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ });
+ return renderHook(
+ () =>
+ useIssueGroupBranches({
+ wsId: "ws-1",
+ query: QUERY,
+ group: {
+ kind: "compound",
+ primary: "project",
+ secondary,
+ secondary_values: ["in_review"],
+ },
+ secondaryValues: ["in_review"],
+ enabled: true,
+ }),
+ { wrapper: wrapper(qc) },
+ );
+ }
+
+ // The regression: the server correctly folded `qa` into the in_review cell,
+ // and the client then dropped the card because `qa !== "in_review"`.
+ it("keeps a custom-status row in its category cell", async () => {
+ const { result } = setup("status_category");
+
+ // Branches are lazy: the lane activates its cell when it scrolls into view.
+ await waitFor(() => expect(result.current.pagination[CELL_KEY]).toBeDefined());
+ act(() => result.current.pagination[CELL_KEY]!.loadMore());
+
+ await waitFor(() => expect(result.current.issues.length).toBe(2));
+ expect(result.current.issues.map((i) => i.id).sort()).toEqual(["qa-1", "std-1"]);
+ });
+
+ // The key axis is still exact: on the `status` contract a `qa` row does NOT
+ // belong to an `in_review` cell, and must still be dropped.
+ it("still matches on the exact key when the axis is the status key", async () => {
+ const { result } = setup("status");
+
+ await waitFor(() => expect(result.current.pagination[CELL_KEY]).toBeDefined());
+ act(() => result.current.pagination[CELL_KEY]!.loadMore());
+
+ await waitFor(() => expect(result.current.issues.length).toBe(1));
+ expect(result.current.issues.map((i) => i.id)).toEqual(["std-1"]);
+ });
+});
diff --git a/packages/views/issues/surface/use-issue-group-branches.ts b/packages/views/issues/surface/use-issue-group-branches.ts
index 1a696aec07..bd96783caa 100644
--- a/packages/views/issues/surface/use-issue-group-branches.ts
+++ b/packages/views/issues/surface/use-issue-group-branches.ts
@@ -18,6 +18,7 @@ import {
issueTableGroupsOptions,
issueTableRowPageOptions,
} from "@multica/core/issues/queries";
+import { issueStatusCategory } from "@multica/core/issues";
import type {
Issue,
IssueTableGroupDescriptor,
@@ -90,10 +91,23 @@ function branchDescriptors(
function issueMatchesDescriptor(
issue: Issue,
descriptor: IssueTableGroupDescriptor,
- primary?: IssueTableGroupDescriptor,
+ primary: IssueTableGroupDescriptor | undefined,
+ /**
+ * Whether the secondary axis is the CATEGORY a status behaves as rather than
+ * the status key itself. A category cell holds every custom status in it, so
+ * matching on the raw key would drop exactly the cards the category contract
+ * exists to deliver — `qa !== "in_review"` threw the QA card away after the
+ * server correctly returned it. (MUL-6243)
+ */
+ secondaryIsCategory: boolean,
) {
const value = descriptor.value;
- if (value.kind === "status" && issue.status !== value.status) return false;
+ if (value.kind === "status") {
+ const resolved = secondaryIsCategory
+ ? issueStatusCategory(issue)
+ : issue.status;
+ if (resolved !== value.status) return false;
+ }
const owner = primary?.value ?? value;
switch (owner.kind) {
case "assignee":
@@ -144,6 +158,8 @@ export function useIssueGroupBranches({
enabled: boolean;
}): IssueGroupBranches {
const queryClient = useQueryClient();
+ const secondaryIsCategory =
+ group.kind === "compound" && group.secondary === "status_category";
const identity = useMemo(
() => JSON.stringify({ query, group }),
[group, query],
@@ -291,6 +307,7 @@ export function useIssueGroupBranches({
row.issue,
descriptor,
primaryByBranch.get(target.key),
+ secondaryIsCategory,
) ||
seen.has(row.issue.id)
) {
diff --git a/packages/views/issues/surface/use-issue-status-branches.category.test.tsx b/packages/views/issues/surface/use-issue-status-branches.category.test.tsx
new file mode 100644
index 0000000000..1d2b5ffef9
--- /dev/null
+++ b/packages/views/issues/surface/use-issue-status-branches.category.test.tsx
@@ -0,0 +1,254 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { setApiInstance } from "@multica/core/api";
+import type { ApiClient } from "@multica/core/api/client";
+import type { Issue, IssueStatusCategory, IssueTableRowsRequest } from "@multica/core/types";
+import { useIssueStatusBranches } from "./use-issue-status-branches";
+
+/**
+ * Board and list columns are CATEGORIES (MUL-6243). Before this, the hook asked
+ * the server for a concrete status key AND re-checked `row.issue.status` against
+ * the column key, so a card on a custom status was dropped twice over: it never
+ * came back from the server, and it would have been filtered out if it had.
+ */
+
+function makeIssue(id: string, status: string, category: IssueStatusCategory): Issue {
+ return {
+ id,
+ workspace_id: "ws-1",
+ number: 1,
+ identifier: `MUL-${id}`,
+ title: id,
+ description: null,
+ status,
+ status_category: category,
+ priority: "none",
+ assignee_type: null,
+ assignee_id: null,
+ creator_type: "member",
+ creator_id: "u-1",
+ project_id: null,
+ parent_issue_id: null,
+ stage: null,
+ position: 1,
+ start_date: null,
+ due_date: null,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ } as Issue;
+}
+
+const QA_ENTRY = {
+ id: "s-qa",
+ workspace_id: "ws-1",
+ key: "qa",
+ name: "QA",
+ description: "",
+ category: "in_review" as const,
+ color: "#ff0000",
+ is_system: false,
+ position: 1,
+ archived_at: null,
+ created_at: "",
+ updated_at: "",
+};
+
+const QUERY = {
+ scope: { kind: "workspace" as const },
+ filters: {},
+ sort: { field: "position" as const, direction: "asc" as const },
+};
+
+function wrapper(qc: QueryClient) {
+ return function Wrapper({ children }: { children: ReactNode }) {
+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe("useIssueStatusBranches — category columns", () => {
+ it("pages each column by category and keeps custom-status rows in it", async () => {
+ const requests: IssueTableRowsRequest[] = [];
+ const listIssueTableRows = vi.fn(async (request: IssueTableRowsRequest) => {
+ requests.push(request);
+ const rows =
+ request.group_key === "status_category:in_review"
+ ? [
+ { issue: makeIssue("qa-1", "qa", "in_review"), direct_child_count: 0 },
+ { issue: makeIssue("std-1", "in_review", "in_review"), direct_child_count: 0 },
+ ]
+ : [];
+ return {
+ query_fingerprint: "test",
+ group_key: request.group_key ?? null,
+ parent_id: null,
+ total: rows.length,
+ rows,
+ branch_total: rows.length,
+ next_cursor: null,
+ };
+ });
+ setApiInstance({
+ listIssueTableRows,
+ // The category contract only switches on for a workspace that HAS a
+ // custom status — see IssueStatusCatalog.hasCustomStatuses.
+ listIssueStatuses: async () => ({ statuses: [QA_ENTRY], categories: [], total: 1 }),
+ } as unknown as ApiClient);
+
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ });
+ const { result } = renderHook(
+ () =>
+ useIssueStatusBranches({
+ wsId: "ws-1",
+ query: QUERY,
+ statuses: ["in_review"],
+ facets: undefined,
+ facetsPending: false,
+ facetsFetching: false,
+ enabled: true,
+ }),
+ { wrapper: wrapper(qc) },
+ );
+
+ await waitFor(() => expect(result.current.issues.length).toBe(2));
+
+ // The FIRST request is the pre-feature contract: the catalog has not landed
+ // yet, so the hook cannot know this workspace has custom statuses and must
+ // not send a group kind an un-upgraded backend would reject. (MUL-6243)
+ expect(requests[0]?.group).toEqual({ kind: "status" });
+ expect(requests[0]?.group_key).toBe("status:in_review");
+ // Once the catalog confirms a custom status, it switches to the CATEGORY
+ // contract — which is what actually returns the QA card.
+ expect(requests.at(-1)?.group).toEqual({ kind: "status_category" });
+ expect(requests.at(-1)?.group_key).toBe("status_category:in_review");
+ // Both rows land in the column: the custom one is not dropped for failing
+ // to equal the column key.
+ expect(result.current.issues.map((i) => i.id).sort()).toEqual(["qa-1", "std-1"]);
+ });
+
+ it("folds a custom status's facet count into its category's column total", async () => {
+ setApiInstance({
+ listIssueTableRows: async (request: IssueTableRowsRequest) => ({
+ query_fingerprint: "test",
+ group_key: request.group_key ?? null,
+ parent_id: null,
+ total: 0,
+ rows: [],
+ branch_total: 0,
+ next_cursor: null,
+ }),
+ listIssueStatuses: async () => ({ statuses: [QA_ENTRY], categories: [], total: 1 }),
+ } as unknown as ApiClient);
+
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ });
+ const { result } = renderHook(
+ () =>
+ useIssueStatusBranches({
+ wsId: "ws-1",
+ query: QUERY,
+ statuses: ["in_review"],
+ facets: {
+ query_fingerprint: "test",
+ total: 5,
+ facets: [
+ {
+ kind: "status",
+ // The facet is keyed by concrete status KEY. Discarding the
+ // custom key made the column header disagree with its cards.
+ values: [
+ { key: "in_review", count: 2 },
+ { key: "qa", count: 3 },
+ ],
+ },
+ ],
+ },
+ facetsPending: false,
+ facetsFetching: false,
+ enabled: true,
+ }),
+ { wrapper: wrapper(qc) },
+ );
+
+ await waitFor(() =>
+ expect(result.current.pagination.in_review?.total).toBe(5),
+ );
+ });
+});
+
+/**
+ * Rolling-deploy safety (MUL-6243).
+ *
+ * `group.kind=status_category` is a server contract this feature introduced.
+ * A new Web build hitting a backend pod that has not been updated yet gets a
+ * 400 — and unlike the creation flag, which is deployment-wide and default off,
+ * nothing else guards this request path. So the contract may only be sent once
+ * the catalog has confirmed the workspace HAS a custom status, which can only
+ * be true if the fleet was already serving this version.
+ */
+describe("useIssueStatusBranches — mixed-version safety", () => {
+ it("never sends the new group kind for a workspace with no custom statuses", async () => {
+ const requests: IssueTableRowsRequest[] = [];
+ const listIssueStatuses = vi.fn(async () => ({
+ // Built-ins only — the state of every workspace until an admin creates
+ // a custom status, which the rollout flag gates.
+ statuses: [
+ { ...QA_ENTRY, id: "s-in-review", key: "in_review", name: "In Review", is_system: true, position: 0 },
+ ],
+ categories: [],
+ total: 1,
+ }));
+ setApiInstance({
+ listIssueTableRows: async (request: IssueTableRowsRequest) => {
+ requests.push(request);
+ return {
+ query_fingerprint: "test",
+ group_key: request.group_key ?? null,
+ parent_id: null,
+ total: 0,
+ rows: [],
+ branch_total: 0,
+ next_cursor: null,
+ };
+ },
+ listIssueStatuses,
+ } as unknown as ApiClient);
+
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ });
+ renderHook(
+ () =>
+ useIssueStatusBranches({
+ wsId: "ws-1",
+ query: QUERY,
+ statuses: ["in_review"],
+ facets: undefined,
+ facetsPending: false,
+ facetsFetching: false,
+ enabled: true,
+ }),
+ { wrapper: wrapper(qc) },
+ );
+
+ await waitFor(() => expect(listIssueStatuses).toHaveBeenCalled());
+ await waitFor(() => expect(requests.length).toBeGreaterThan(0));
+
+ for (const request of requests) {
+ expect(request.group).toEqual({ kind: "status" });
+ expect(request.group_key).toBe("status:in_review");
+ }
+ });
+})
diff --git a/packages/views/issues/surface/use-issue-status-branches.test.tsx b/packages/views/issues/surface/use-issue-status-branches.test.tsx
index ef4988126a..20a9ed59d0 100644
--- a/packages/views/issues/surface/use-issue-status-branches.test.tsx
+++ b/packages/views/issues/surface/use-issue-status-branches.test.tsx
@@ -9,7 +9,7 @@ import { setApiInstance } from "@multica/core/api";
import type { ApiClient } from "@multica/core/api/client";
import type {
Issue,
- IssueStatus,
+ IssueStatusCategory,
IssueTableQuerySpec,
IssueTableRowsRequest,
} from "@multica/core/types";
@@ -79,7 +79,12 @@ describe("useIssueStatusBranches", () => {
};
},
);
- setApiInstance({ listIssueTableRows } as unknown as ApiClient);
+ setApiInstance({
+ listIssueTableRows,
+ // The hook pages by category, so it reads the catalog. Empty is the real
+ // shape for a workspace with no custom statuses. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
+ } as unknown as ApiClient);
// Mirror the production client (createQueryClient): row pages stay fresh
// until explicitly invalidated, so re-expanding a collapsed section reuses
// settled cursor pages instead of refetching them on observer reattach.
@@ -88,7 +93,7 @@ describe("useIssueStatusBranches", () => {
});
const { result, rerender } = renderHook(
- ({ statuses }: { statuses: IssueStatus[] }) =>
+ ({ statuses }: { statuses: IssueStatusCategory[] }) =>
useIssueStatusBranches({
wsId: "ws-1",
query,
@@ -133,6 +138,9 @@ describe("useIssueStatusBranches", () => {
expect(listIssueTableRows).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
+ // No custom statuses in this fixture, so the hook keeps the
+ // pre-feature contract. See use-issue-status-branches.category.test.tsx
+ // for the category contract. (MUL-6243)
group_key: "status:todo",
page: { limit: 50, cursor: "cursor-2" },
}),
diff --git a/packages/views/issues/surface/use-issue-status-branches.ts b/packages/views/issues/surface/use-issue-status-branches.ts
index 655d3a5342..d100e68dd3 100644
--- a/packages/views/issues/surface/use-issue-status-branches.ts
+++ b/packages/views/issues/surface/use-issue-status-branches.ts
@@ -13,13 +13,16 @@ import {
type UseQueryResult,
} from "@tanstack/react-query";
import { ALL_STATUSES } from "@multica/core/issues/config";
+import { statusCategoryOfKey } from "@multica/core/issues";
+import type { IssueStatusCatalog } from "@multica/core/issue-statuses";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import {
issueKeys,
issueTableRowPageOptions,
} from "@multica/core/issues/queries";
import type {
Issue,
- IssueStatus,
+ IssueStatusCategory,
IssueTableFacetsResponse,
IssueTableQuerySpec,
IssueTableRowsResponse,
@@ -37,17 +40,17 @@ export interface IssueStatusPageState {
}
export type IssueStatusPagination = Record<
- IssueStatus,
+ IssueStatusCategory,
IssueStatusPageState
>;
interface StatusCursorState {
identity: string;
- cursors: Record<IssueStatus, Array<string | null>>;
+ cursors: Record<IssueStatusCategory, Array<string | null>>;
}
interface StatusPageTarget {
- status: IssueStatus;
+ status: IssueStatusCategory;
cursor: string | null;
}
@@ -65,13 +68,28 @@ interface StatusBranchData {
headPending: boolean;
}
-function statusGroupKey(status: IssueStatus) {
- return `status:${status}`;
+// Every "status" in this hook is a board COLUMN, and columns are categories:
+// a workspace's custom statuses live inside their category's column rather than
+// adding one of their own. (MUL-6243)
+function statusGroupKey(status: IssueStatusCategory, byCategory: boolean) {
+ return byCategory ? `status_category:${status}` : `status:${status}`;
}
+/**
+ * The grouping contract this hook pages with.
+ *
+ * `status_category` is a server contract this feature introduced, so it is only
+ * sent once the workspace is KNOWN to have custom statuses — see
+ * `IssueStatusCatalog.hasCustomStatuses` for why that is both the
+ * rolling-deploy guard and the cold-load guard. Everyone else keeps the exact
+ * request they made before. (MUL-6243)
+ */
+const CATEGORY_GROUP = { kind: "status_category" } as const;
+const STATUS_GROUP = { kind: "status" } as const;
+
function initialCursorState(
identity: string,
- statuses: readonly IssueStatus[],
+ statuses: readonly IssueStatusCategory[],
): StatusCursorState {
const cursors = Object.fromEntries(
ALL_STATUSES.map((status) => [
@@ -85,7 +103,7 @@ function initialCursorState(
function rebaseCursorState(
state: StatusCursorState,
identity: string,
- statuses: readonly IssueStatus[],
+ statuses: readonly IssueStatusCategory[],
) {
const current =
state.identity === identity ? state : initialCursorState(identity, statuses);
@@ -98,15 +116,44 @@ function rebaseCursorState(
return cursors ? { ...current, cursors } : current;
}
+/**
+ * The column an issue belongs to.
+ *
+ * `status_category` is filled by the server for every issue payload, so this is
+ * a plain read in the normal case. The fallback covers a row that predates the
+ * field (an older backend, or an optimistic client-side patch): a built-in key
+ * IS its own category, so it still resolves exactly, and a custom key with no
+ * category lands in `todo` rather than disappearing.
+ */
+function rowCategory(issue: Issue): IssueStatusCategory {
+ return issue.status_category ?? statusCategoryOfKey(issue.status);
+}
+
+/**
+ * Per-column totals from the server's status facet.
+ *
+ * The facet is keyed by concrete status KEY, while columns are categories, so
+ * custom keys are folded into their category instead of being discarded —
+ * dropping them made a column's total disagree with the cards it rendered.
+ *
+ * A key the LOADED catalog does not know is dropped rather than guessed into
+ * `todo`: `categoryOf` cannot distinguish "custom status created seconds ago
+ * elsewhere" from "not a status at all", and inflating an arbitrary column's
+ * header is worse than a total that is briefly one card short. Before the
+ * catalog loads there is nothing to fold, so only built-ins are counted — which
+ * is exactly the pre-feature behavior. (MUL-6243)
+ */
function statusCountsFromFacets(
facets: IssueTableFacetsResponse | undefined,
+ catalog: Pick<IssueStatusCatalog, "entryOf" | "isLoaded">,
) {
- const counts = new Map<IssueStatus, number>();
+ const counts = new Map<IssueStatusCategory, number>();
const statusFacet = facets?.facets.find((facet) => facet.kind === "status");
for (const value of statusFacet?.values ?? []) {
- if (ALL_STATUSES.includes(value.key as IssueStatus)) {
- counts.set(value.key as IssueStatus, value.count);
- }
+ const builtIn = ALL_STATUSES.find((category) => category === value.key);
+ const category = builtIn ?? (catalog.isLoaded ? catalog.entryOf(value.key)?.category : undefined);
+ if (!category || !ALL_STATUSES.includes(category)) continue;
+ counts.set(category, (counts.get(category) ?? 0) + value.count);
}
return counts;
}
@@ -138,14 +185,25 @@ export function useIssueStatusBranches({
}: {
wsId: string;
query: IssueTableQuerySpec;
- statuses: readonly IssueStatus[];
+ statuses: readonly IssueStatusCategory[];
facets: IssueTableFacetsResponse | undefined;
facetsPending: boolean;
facetsFetching: boolean;
enabled: boolean;
}): IssueStatusBranches {
const queryClient = useQueryClient();
- const identity = useMemo(() => JSON.stringify(query), [query]);
+ const catalog = useIssueStatuses(wsId);
+ const { hasCustomStatuses } = catalog;
+ const group = hasCustomStatuses ? CATEGORY_GROUP : STATUS_GROUP;
+ // The grouping contract is part of the cursor identity, not just the query:
+ // it flips from `status` to `status_category` the moment the catalog lands,
+ // and a cursor minted against the old contract is meaningless to the new one.
+ // Without this, catalog arrival carried stale `status:` cursors into
+ // `status_category:` requests. (MUL-6243)
+ const identity = useMemo(
+ () => JSON.stringify({ query, group: group.kind }),
+ [group.kind, query],
+ );
const [cursorState, setCursorState] = useState<StatusCursorState>(() =>
initialCursorState(identity, statuses),
);
@@ -174,7 +232,7 @@ export function useIssueStatusBranches({
[activeCursorState.cursors, enabled, statuses],
);
const headPlaceholderRef = useRef(
- new Map<IssueStatus, IssueTableRowsResponse>(),
+ new Map<IssueStatusCategory, IssueTableRowsResponse>(),
);
const pageQueries = useMemo(
() =>
@@ -184,8 +242,8 @@ export function useIssueStatusBranches({
return {
...issueTableRowPageOptions(wsId, {
query,
- group: { kind: "status" },
- group_key: statusGroupKey(status),
+ group,
+ group_key: statusGroupKey(status, hasCustomStatuses),
hierarchy: { enabled: false },
parent_id: null,
page: { limit: 50, cursor },
@@ -198,7 +256,7 @@ export function useIssueStatusBranches({
enabled,
};
}),
- [enabled, pageTargets, query, wsId],
+ [enabled, group, hasCustomStatuses, pageTargets, query, wsId],
);
const pageResults = useQueries({ queries: pageQueries }) as Array<
UseQueryResult<IssueTableRowsResponse, Error>
@@ -222,7 +280,7 @@ export function useIssueStatusBranches({
}, [pageResults, pageTargets]);
const branchData = useMemo(() => {
- const result = new Map<IssueStatus, StatusBranchData>();
+ const result = new Map<IssueStatusCategory, StatusBranchData>();
for (const status of statuses) {
result.set(status, {
rows: [],
@@ -236,7 +294,7 @@ export function useIssueStatusBranches({
});
}
- const headFetching = new Set<IssueStatus>();
+ const headFetching = new Set<IssueStatusCategory>();
for (let index = 0; index < pageTargets.length; index += 1) {
const target = pageTargets[index];
const queryResult = pageResults[index];
@@ -249,7 +307,7 @@ export function useIssueStatusBranches({
}
}
- const seenByStatus = new Map<IssueStatus, Set<string>>();
+ const seenByStatus = new Map<IssueStatusCategory, Set<string>>();
for (let index = 0; index < pageTargets.length; index += 1) {
const target = pageTargets[index];
const queryResult = pageResults[index];
@@ -267,8 +325,10 @@ export function useIssueStatusBranches({
for (const row of page.rows) {
// Realtime can patch an issue's status before the broad query
// invalidation has moved it between branch caches. Never render a
- // patched card under a status it no longer belongs to.
- if (row.issue.status !== target.status) continue;
+ // patched card under a column it no longer belongs to. The comparison
+ // is against the CATEGORY, so a custom status stays in its column
+ // instead of being dropped for not equalling the column key.
+ if (rowCategory(row.issue) !== target.status) continue;
if (seen.has(row.issue.id)) continue;
seen.add(row.issue.id);
current.rows.push(row.issue);
@@ -297,15 +357,15 @@ export function useIssueStatusBranches({
// current snapshot. Match Table's branch behavior by dropping every tail.
const headRevisionRef = useRef<{
identity: string;
- revisions: Partial<Record<IssueStatus, number>>;
+ revisions: Partial<Record<IssueStatusCategory, number>>;
}>({ identity, revisions: {} });
useEffect(() => {
const previous =
headRevisionRef.current.identity === identity
? headRevisionRef.current.revisions
: {};
- const next: Partial<Record<IssueStatus, number>> = {};
- const trim = new Set<IssueStatus>();
+ const next: Partial<Record<IssueStatusCategory, number>> = {};
+ const trim = new Set<IssueStatusCategory>();
for (const status of statuses) {
const branch = branchData.get(status);
if (!branch || branch.headUpdatedAt === 0) continue;
@@ -334,9 +394,12 @@ export function useIssueStatusBranches({
statuses,
]);
- const counts = useMemo(() => statusCountsFromFacets(facets), [facets]);
+ const counts = useMemo(
+ () => statusCountsFromFacets(facets, catalog),
+ [facets, catalog],
+ );
const loadMore = useCallback(
- (status: IssueStatus) => {
+ (status: IssueStatusCategory) => {
const cursor = branchData.get(status)?.nextCursor;
if (!cursor) return;
setCursorState((previous) => {
@@ -355,13 +418,13 @@ export function useIssueStatusBranches({
[branchData, identity],
);
const retry = useCallback(
- (status: IssueStatus) => {
+ (status: IssueStatusCategory) => {
void queryClient.refetchQueries({
queryKey: issueKeys.tableRows(
wsId,
query,
- { kind: "status" },
- statusGroupKey(status),
+ group,
+ statusGroupKey(status, hasCustomStatuses),
false,
null,
),
@@ -369,7 +432,7 @@ export function useIssueStatusBranches({
type: "active",
});
},
- [query, queryClient, wsId],
+ [group, hasCustomStatuses, query, queryClient, wsId],
);
const pagination = useMemo<IssueStatusPagination>(() => {
diff --git a/packages/views/issues/surface/use-issue-surface-catalog.test.tsx b/packages/views/issues/surface/use-issue-surface-catalog.test.tsx
new file mode 100644
index 0000000000..11718fcf31
--- /dev/null
+++ b/packages/views/issues/surface/use-issue-surface-catalog.test.tsx
@@ -0,0 +1,223 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { setApiInstance } from "@multica/core/api";
+import type { ApiClient } from "@multica/core/api/client";
+import {
+ getIssueSurfaceViewStore,
+ pruneIssueSurfaceViewStates,
+} from "@multica/core/issues/stores/surface-view-store";
+import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";
+import type { IssueStatusEntry, IssueTableGroupsRequest, IssueTableRowsRequest } from "@multica/core/types";
+import { useIssueSurfaceController } from "./use-issue-surface-controller";
+
+/**
+ * The catalog is server state, so it can be late or absent. Two behaviours
+ * depend on that and neither is expressible with a boolean "loaded" flag:
+ *
+ * - A CUSTOM status filter cannot be routed to a column until the catalog
+ * answers. Fetching zero branches meanwhile renders an empty board with no
+ * spinner; failing renders one permanently, with no way to retry.
+ * - `status_category` is a server contract this feature introduced, so it must
+ * not be sent until the catalog proves this workspace has a custom status.
+ */
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+
+const QA_ENTRY: IssueStatusEntry = {
+ id: "s-qa",
+ workspace_id: "ws-1",
+ key: "qa",
+ name: "QA",
+ description: "",
+ category: "in_review",
+ color: "#ff0000",
+ is_system: false,
+ position: 1,
+ archived_at: null,
+ created_at: "",
+ updated_at: "",
+};
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+let groupRequests: IssueTableGroupsRequest[] = [];
+let rowRequests: IssueTableRowsRequest[] = [];
+
+function installApi(listIssueStatuses: () => Promise<unknown>) {
+ groupRequests = [];
+ rowRequests = [];
+ setApiInstance({
+ listIssueStatuses,
+ listIssueTableGroups: async (request: IssueTableGroupsRequest) => {
+ groupRequests.push(request);
+ return { query_fingerprint: "test", total: 0, groups: [], next_cursor: null };
+ },
+ listIssueTableRows: async (request: IssueTableRowsRequest) => {
+ rowRequests.push(request);
+ return {
+ query_fingerprint: "test",
+ group_key: request.group_key ?? null,
+ parent_id: null,
+ total: 0,
+ rows: [],
+ branch_total: 0,
+ next_cursor: null,
+ };
+ },
+ listIssueTableFacets: async () => ({ query_fingerprint: "test", total: 0, facets: [] }),
+ listIssues: async () => ({ issues: [], total: 0 }),
+ listProjects: async () => ({ projects: [], total: 0 }),
+ getWorkspaceWorkingAgents: async () => [],
+ getChildIssueProgress: async () => ({ progress: [] }),
+ getAgentTaskSnapshot: async () => ({ tasks: [] }),
+ } as unknown as ApiClient);
+}
+
+function makeWrapper(qc: QueryClient, surfaceKey: string) {
+ const store = getIssueSurfaceViewStore(surfaceKey);
+ return {
+ store,
+ Wrapper: function Wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={qc}>
+ <ViewStoreProvider store={store}>{children}</ViewStoreProvider>
+ </QueryClientProvider>
+ );
+ },
+ };
+}
+
+let qc: QueryClient;
+beforeEach(() => {
+ qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
+ pruneIssueSurfaceViewStates([]);
+});
+afterEach(() => {
+ cleanup();
+ qc.clear();
+ vi.restoreAllMocks();
+});
+
+describe("useIssueSurfaceController — custom status filter vs a late catalog", () => {
+ it("stays loading while the catalog a custom filter depends on is in flight", async () => {
+ const catalog = deferred<{ statuses: IssueStatusEntry[]; categories: never[]; total: number }>();
+ installApi(() => catalog.promise);
+ const { store, Wrapper } = makeWrapper(qc, "workspace:catalog-pending");
+ act(() => store.getState().toggleStatusFilter("qa"));
+
+ const { result } = renderHook(
+ () =>
+ useIssueSurfaceController({
+ scope: { type: "workspace", actorKind: "all" },
+ modes: ["list"],
+ }),
+ { wrapper: Wrapper },
+ );
+
+ // The regression: the surface reported "loaded, zero results" and rendered
+ // an empty board for the whole cold-load window.
+ await waitFor(() => expect(result.current.isLoading).toBe(true));
+ expect(result.current.isEmpty).toBe(false);
+ // And nothing is fetched: with the filter unresolved the visible column set
+ // falls back to ALL categories, so fetching would briefly show the
+ // UNFILTERED board to someone who opened a saved `qa` view.
+ expect(rowRequests).toEqual([]);
+
+ await act(async () => {
+ catalog.resolve({ statuses: [QA_ENTRY], categories: [], total: 1 });
+ await catalog.promise;
+ });
+
+ // Once the catalog answers, the filter routes to the column `qa` behaves as.
+ await waitFor(() => expect(result.current.visibleStatuses).toEqual(["in_review"]));
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+ });
+
+ it("surfaces a retryable error instead of a silent empty board when the catalog fails", async () => {
+ const catalog = deferred<never>();
+ installApi(() => catalog.promise);
+ const { store, Wrapper } = makeWrapper(qc, "workspace:catalog-failed");
+ act(() => store.getState().toggleStatusFilter("qa"));
+
+ const { result } = renderHook(
+ () =>
+ useIssueSurfaceController({
+ scope: { type: "workspace", actorKind: "all" },
+ modes: ["list"],
+ }),
+ { wrapper: Wrapper },
+ );
+
+ await act(async () => {
+ catalog.reject(new Error("catalog unavailable"));
+ await catalog.promise.catch(() => {});
+ });
+
+ await waitFor(() => expect(result.current.isStatusCatalogError).toBe(true));
+ // Not "no issues" — the surface cannot answer the question that was asked.
+ expect(result.current.isEmpty).toBe(false);
+ });
+});
+
+describe("useIssueSurfaceController — swimlane protocol", () => {
+ it("keeps the swimlane on the original contract with no custom statuses", async () => {
+ installApi(async () => ({ statuses: [], categories: [], total: 0 }));
+ const { store, Wrapper } = makeWrapper(qc, "workspace:swimlane-plain");
+ act(() => store.getState().setViewMode("swimlane"));
+
+ renderHook(
+ () =>
+ useIssueSurfaceController({
+ scope: { type: "workspace", actorKind: "all" },
+ modes: ["swimlane"],
+ }),
+ { wrapper: Wrapper },
+ );
+
+ await waitFor(() => expect(groupRequests.length).toBeGreaterThan(0));
+ // Every request, not just the first: a new Web build must never send a
+ // group kind an un-upgraded backend would reject.
+ for (const request of groupRequests) {
+ expect(request.group).toMatchObject({ kind: "compound", secondary: "status" });
+ }
+ for (const request of rowRequests) {
+ expect(request.group).toMatchObject({ kind: "compound", secondary: "status" });
+ }
+ });
+
+ it("upgrades the swimlane to the category axis once a custom status exists", async () => {
+ installApi(async () => ({ statuses: [QA_ENTRY], categories: [], total: 1 }));
+ const { store, Wrapper } = makeWrapper(qc, "workspace:swimlane-custom");
+ act(() => store.getState().setViewMode("swimlane"));
+
+ renderHook(
+ () =>
+ useIssueSurfaceController({
+ scope: { type: "workspace", actorKind: "all" },
+ modes: ["swimlane"],
+ }),
+ { wrapper: Wrapper },
+ );
+
+ await waitFor(() =>
+ expect(
+ groupRequests.some((request) =>
+ request.group.kind === "compound" && request.group.secondary === "status_category",
+ ),
+ ).toBe(true),
+ );
+ });
+});
diff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsx
index ce0f4412c6..dae7eea7b7 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx
+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx
@@ -179,6 +179,10 @@ describe("useIssueSurfaceController", () => {
listIssueTableRows = vi.fn(tableMethods.listIssueTableRows);
listIssueTableFacets = vi.fn(tableMethods.listIssueTableFacets);
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
...tableMethods,
listIssueTableRows,
@@ -234,6 +238,8 @@ describe("useIssueSurfaceController", () => {
query: expect.objectContaining({
scope: { kind: "project", project_id: "p1" },
}),
+ // A workspace with no custom statuses keeps the original contract —
+ // that is what makes this safe across a rolling deploy. (MUL-6243)
group: { kind: "status" },
}),
);
@@ -248,6 +254,10 @@ describe("useIssueSurfaceController", () => {
// all of them.
it("keeps the table query spec identity while its source queries are still pending", async () => {
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
listIssueTableRows,
listIssueTableFacets,
@@ -330,6 +340,10 @@ describe("useIssueSurfaceController", () => {
facets: [{ kind: "status" as const, values: [] }],
}));
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues: legacyListIssues,
listIssueTableRows: tableRows,
listIssueTableFacets: tableFacets,
@@ -644,6 +658,10 @@ describe("useIssueSurfaceController", () => {
facets: [{ kind: "status", values: [{ key: "todo", count: 2 }] }],
});
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
listIssueTableFacets,
listGroupedIssues: vi.fn(() => never()),
@@ -729,6 +747,10 @@ describe("useIssueSurfaceController", () => {
});
const tableMethods = statusTableMethodsFromLegacy(listIssues);
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
...tableMethods,
listIssueTableFacets,
@@ -790,6 +812,10 @@ describe("useIssueSurfaceController", () => {
}),
);
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
listIssueTableRows,
listIssueTableFacets: vi.fn(() => never()),
@@ -840,6 +866,10 @@ describe("useIssueSurfaceController", () => {
next_cursor: null,
});
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
listIssueTableRows,
listIssueTableFacets: vi.fn(() => never()),
@@ -893,6 +923,10 @@ describe("useIssueSurfaceController", () => {
] satisfies WorkspaceWorkingAgent[]),
);
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
listGroupedIssues: vi.fn(() => never()),
listProjects: vi.fn(() => never()),
@@ -934,6 +968,10 @@ describe("useIssueSurfaceController", () => {
Promise.resolve([] satisfies WorkspaceWorkingAgent[]),
);
setApiInstance({
+ // The board pages by category, so every surface stub answers the catalog
+ // read. Empty is the real shape for a workspace with no custom statuses:
+ // a built-in key IS its own category. (MUL-6243)
+ listIssueStatuses: async () => ({ statuses: [], categories: [], total: 0 }),
listIssues,
listGroupedIssues: vi.fn(() => never()),
listProjects: vi.fn(() => never()),
diff --git a/packages/views/issues/surface/use-issue-surface-controller.ts b/packages/views/issues/surface/use-issue-surface-controller.ts
index d9ff88c57d..a9f621dfb5 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.ts
+++ b/packages/views/issues/surface/use-issue-surface-controller.ts
@@ -5,7 +5,7 @@ import { hashKey, keepPreviousData, useQuery } from "@tanstack/react-query";
import { api } from "@multica/core/api";
import type {
Issue,
- IssueStatus,
+ IssueStatusCategory,
IssueTableFacetSpec,
IssueTableFacetsResponse,
IssueTableGroupsRequest,
@@ -16,6 +16,8 @@ import type {
import { workspaceWorkingAgentsOptions } from "@multica/core/agents";
import { useWorkspaceId } from "@multica/core/hooks";
import { ALL_STATUSES } from "@multica/core/issues/config";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { statusFilterColumns } from "@multica/core/issues";
import { dateOnlyToLocalDate } from "@multica/core/issues/date";
import type { IssueSortParam } from "@multica/core/issues/queries";
import { issueTableFacetsOptions } from "@multica/core/issues/queries";
@@ -81,8 +83,8 @@ export interface IssueSurfaceController {
filteredGanttIssues: Issue[];
sort: IssueSortParam;
ganttIssues: Issue[];
- visibleStatuses: IssueStatus[];
- hiddenStatuses: IssueStatus[];
+ visibleStatuses: IssueStatusCategory[];
+ hiddenStatuses: IssueStatusCategory[];
/** Exact server counts plus cursor controls for List/status Board. */
statusPagination?: IssueStatusPagination;
/** Exact group catalog plus independent row cursors for Assignee/Property
@@ -118,6 +120,14 @@ export interface IssueSurfaceController {
/** See IssueSurfaceData.isRefreshing — placeholder-backed revalidation. */
isRefreshing: boolean;
isEmpty: boolean;
+ /**
+ * The status catalog a CUSTOM status filter depends on failed to load. The
+ * filter cannot be honoured, so the surface shows a retryable error rather
+ * than an unexplained empty board. (MUL-6243)
+ */
+ isStatusCatalogError: boolean;
+ /** Re-runs the failed catalog request behind {@link isStatusCatalogError}. */
+ retryStatusCatalog: () => void;
openCreateIssue: (defaults?: IssueCreateDefaults) => void;
moveIssue: (
issueId: string,
@@ -224,6 +234,9 @@ export function useIssueSurfaceController({
const swimlaneGrouping = useViewStore((s) => s.swimlaneGrouping);
const tableColumns = useViewStore((s) => s.tableColumns);
const listCollapsedStatuses = useViewStore((s) => s.listCollapsedStatuses);
+ const hiddenStatusCategories = useViewStore((s) => s.hiddenStatusCategories);
+ const catalog = useIssueStatuses(wsId);
+ const { hasCustomStatuses } = catalog;
const [tableSearch, setTableSearch] = useState("");
const allowedModes = useMemo(() => new Set<IssueSurfaceMode>(modes), [modes]);
@@ -319,17 +332,54 @@ export function useIssueSurfaceController({
effectiveViewMode === "swimlane";
const usesServerFacets =
usesTable || usesServerStatusSurface || usesServerGroupSurface;
- const serverStatuses = useMemo<IssueStatus[]>(
+ const statusColumnsForFilters = useMemo(
+ () => statusFilterColumns(statusFilters, catalog),
+ [catalog, statusFilters],
+ );
+ /**
+ * A custom-status filter cannot be routed until the catalog answers. While it
+ * is pending the surface must HOLD ITS LOADING STATE, and on failure it must
+ * surface a retryable error — not fetch zero branches and render an empty
+ * board, which is what "return no columns" alone produced. (MUL-6243)
+ */
+ const statusFilterPending = statusColumnsForFilters.state === "pending";
+ const statusFilterError = statusColumnsForFilters.state === "error";
+ /**
+ * Fetching is suspended until the filter resolves. Not just "narrow to
+ * nothing": with the filter unresolved the visible column set falls back to
+ * ALL categories, so fetching anyway would briefly show the UNFILTERED board
+ * to someone who opened a saved `qa` view. Holding both the request and the
+ * loading state is the only honest option.
+ */
+ const statusFilterUnresolved = statusFilterPending || statusFilterError;
+
+ // Columns are CATEGORIES. Two independent things narrow them, and conflating
+ // them is what let "hide the Backlog column" also drop every custom status in
+ // other categories: `hiddenStatusCategories` is display state, `statusFilters`
+ // is a filter over concrete status KEYS which we map back to the columns those
+ // keys land in. (MUL-6243)
+ const serverStatuses = useMemo<IssueStatusCategory[]>(
() => {
- const visible =
- statusFilters.length > 0
- ? ALL_STATUSES.filter((status) => statusFilters.includes(status))
- : [...ALL_STATUSES];
+ const selected =
+ statusFilters.length > 0 && statusColumnsForFilters.state === "resolved"
+ ? statusColumnsForFilters.columns
+ : null;
+ const visible = ALL_STATUSES.filter(
+ (category) =>
+ !hiddenStatusCategories.includes(category) &&
+ (selected === null || selected.has(category)),
+ );
return effectiveViewMode === "list"
? visible.filter((status) => !listCollapsedStatuses.includes(status))
: visible;
},
- [effectiveViewMode, listCollapsedStatuses, statusFilters],
+ [
+ effectiveViewMode,
+ hiddenStatusCategories,
+ listCollapsedStatuses,
+ statusColumnsForFilters,
+ statusFilters,
+ ],
);
const projectFilterState = useMemo(
@@ -574,14 +624,19 @@ export function useIssueSurfaceController({
facets: tableFacetsQuery.data,
facetsPending: tableFacetsQuery.isPending,
facetsFetching: tableFacetsQuery.isFetching,
- enabled: usesServerStatusSurface,
+ enabled: usesServerStatusSurface && !statusFilterUnresolved,
});
const serverGroupSpec = useMemo<IssueTableGroupsRequest["group"]>(() => {
if (effectiveViewMode === "swimlane") {
return {
kind: "compound",
primary: swimlaneGrouping,
- secondary: "status",
+ // Same rollout switch as the board/list branches: `status_category` is
+ // a contract this feature introduced, so it is only sent once the
+ // catalog confirms this workspace HAS a custom status — which can only
+ // be true if the fleet already serves this version. Otherwise the
+ // swimlane keeps the exact request it made before. (MUL-6243)
+ secondary: hasCustomStatuses ? "status_category" : "status",
secondary_values: serverStatuses,
};
}
@@ -597,6 +652,7 @@ export function useIssueSurfaceController({
}, [
effectiveGrouping,
effectiveViewMode,
+ hasCustomStatuses,
serverStatuses,
swimlaneGrouping,
]);
@@ -614,7 +670,7 @@ export function useIssueSurfaceController({
observeEmptyBranches:
effectiveViewMode === "swimlane" ||
(effectiveViewMode === "board" && activeGroupingProperty !== null),
- enabled: usesServerGroupSurface,
+ enabled: usesServerGroupSurface && !statusFilterUnresolved,
});
// Selection is only meaningful within the current membership window: batch
@@ -673,6 +729,9 @@ export function useIssueSurfaceController({
serverGroupBranches,
ganttShowCompleted,
statusFilters,
+ hiddenStatusCategories,
+ statusFilterPending,
+ statusFilterError,
priorityFilters,
assigneeFilters,
includeNoAssignee,
@@ -790,6 +849,8 @@ export function useIssueSurfaceController({
data.isEmpty &&
!data.isRefreshing &&
!(usesTable && (tableSearch.trim() || debouncedActiveSearch)),
+ isStatusCatalogError: data.isStatusCatalogError,
+ retryStatusCatalog: catalog.retry,
sort,
actions,
selection,
diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.ts
index a7e541ad97..19af3b1dac 100644
--- a/packages/views/issues/surface/use-issue-surface-data.ts
+++ b/packages/views/issues/surface/use-issue-surface-data.ts
@@ -8,7 +8,9 @@ import { projectListOptions } from "@multica/core/projects/queries";
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 type { IssueStatus, IssueStatusCategory } from "@multica/core/types";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import { issueBehavesAsAny, statusFilterColumns } from "@multica/core/issues";
import {
applyIssueFilters,
type IssueFilterState,
@@ -44,7 +46,9 @@ const EMPTY_PROJECTS: Project[] = [];
function ganttCanvasRows(issues: Issue[], showCompleted: boolean): Issue[] {
const dated = issues.filter((i) => i.start_date || i.due_date);
if (showCompleted) return dated;
- return dated.filter((i) => i.status !== "done" && i.status !== "cancelled");
+ // By CATEGORY: a custom status in done/cancelled is completed work, and
+ // "show completed" has to hide it too. (MUL-6243)
+ return dated.filter((i) => !issueBehavesAsAny(i, ["done", "cancelled"]));
}
export interface IssueSurfaceData {
@@ -58,8 +62,8 @@ export interface IssueSurfaceData {
ganttWorkingScopeIssues: Issue[] | undefined;
filteredGanttIssues: Issue[];
ganttIssues: Issue[];
- visibleStatuses: IssueStatus[];
- hiddenStatuses: IssueStatus[];
+ visibleStatuses: IssueStatusCategory[];
+ hiddenStatuses: IssueStatusCategory[];
statusPagination: IssueStatusPagination;
activeFilters: Omit<IssueFilters, "statusFilters">;
childProgressMap: Map<string, ChildProgress>;
@@ -72,6 +76,12 @@ export interface IssueSurfaceData {
childProgressMap: Map<string, ChildProgress>;
}>;
isLoading: boolean;
+ /**
+ * The catalog request a CUSTOM status filter depends on failed. The filter
+ * cannot be honoured without it, so the surface shows a retryable error
+ * rather than an unexplained empty board. (MUL-6243)
+ */
+ isStatusCatalogError: boolean;
/** The window's data is being revalidated while the previous snapshot is
* shown as a placeholder (sort/date change, or any grouped-board filter
* change). Drives the header's deferred refresh indicator — content stays
@@ -90,6 +100,9 @@ export function useIssueSurfaceData({
serverGroupBranches,
ganttShowCompleted,
statusFilters,
+ hiddenStatusCategories,
+ statusFilterPending,
+ statusFilterError,
priorityFilters,
assigneeFilters,
includeNoAssignee,
@@ -114,6 +127,11 @@ export function useIssueSurfaceData({
* rows without it, so the working scope has to honour it too. */
ganttShowCompleted: boolean;
statusFilters: IssueStatus[];
+ hiddenStatusCategories: IssueStatusCategory[];
+ /** A custom status filter is waiting on the catalog — hold loading. */
+ statusFilterPending: boolean;
+ /** The catalog failed, so a custom status filter cannot be honoured. */
+ statusFilterError: boolean;
priorityFilters: IssueFilterState["priorityFilters"];
assigneeFilters: IssueFilterState["assigneeFilters"];
includeNoAssignee: boolean;
@@ -316,20 +334,32 @@ export function useIssueSurfaceData({
],
);
- const visibleStatuses = useMemo<IssueStatus[]>(() => {
- // Default view shows every lifecycle status, `cancelled` last (its
- // canonical position in ALL_STATUSES). An active status filter narrows to
- // the selected subset while preserving that order.
- if (statusFilters.length > 0) {
- return ALL_STATUSES.filter((s) => statusFilters.includes(s));
- }
- return ALL_STATUSES;
- }, [statusFilters]);
+ const catalog = useIssueStatuses(wsId);
+
+ const visibleStatuses = useMemo<IssueStatusCategory[]>(() => {
+ // Board columns are CATEGORIES, not status keys — adding a custom status
+ // must never add a column. Two independent things narrow them: hidden
+ // columns (display state) and the status filter, which is expressed in
+ // concrete KEYS and so has to be mapped back to the columns those keys land
+ // in. Default view shows every category, `cancelled` last (its canonical
+ // position in ALL_STATUSES). (MUL-6243)
+ const resolved =
+ statusFilters.length > 0 ? statusFilterColumns(statusFilters, catalog) : null;
+ // Pending/error contribute no narrowing here; the surface's loading and
+ // error states (statusFilterPending / statusFilterError) are what stop it
+ // rendering as though the empty result were the answer.
+ const selected = resolved?.state === "resolved" ? resolved.columns : null;
+ return ALL_STATUSES.filter(
+ (s) =>
+ !hiddenStatusCategories.includes(s) &&
+ (selected === null || selected.has(s)),
+ );
+ }, [statusFilters, hiddenStatusCategories, catalog]);
// Hidden columns are the lifecycle statuses not currently visible, so
// `cancelled` participates in the board show/hide controls exactly like the
// rest of the statuses.
- const hiddenStatuses = useMemo<IssueStatus[]>(
+ const hiddenStatuses = useMemo<IssueStatusCategory[]>(
() => ALL_STATUSES.filter((s) => !visibleStatuses.includes(s)),
[visibleStatuses],
);
@@ -363,13 +393,19 @@ export function useIssueSurfaceData({
],
);
- const isLoading = serverGroupBranches.enabled
- ? serverGroupBranches.isLoading
- : usesGantt
- ? ganttIssuesQuery.isLoading
- : serverStatusBranches.enabled
- ? serverStatusBranches.isLoading
- : false;
+ // `statusFilterPending` holds the surface in loading while a CUSTOM status
+ // filter waits for the catalog to say which column it belongs to. Without it
+ // the surface reported "loaded, zero results" — an empty board with no
+ // spinner — for the whole cold-load window. (MUL-6243)
+ const isLoading =
+ statusFilterPending ||
+ (serverGroupBranches.enabled
+ ? serverGroupBranches.isLoading
+ : usesGantt
+ ? ganttIssuesQuery.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
@@ -407,6 +443,7 @@ export function useIssueSurfaceData({
// so this shared legacy surface projection never asserts Table empty.
isEmpty:
!isLoading &&
+ !statusFilterError &&
!usesGantt &&
!usesTable &&
(serverStatusBranches.enabled
@@ -415,5 +452,6 @@ export function useIssueSurfaceData({
: serverGroupBranches.enabled &&
!serverGroupBranches.isError &&
serverGroupBranches.total === 0),
+ isStatusCatalogError: statusFilterError,
};
}
diff --git a/packages/views/issues/utils/status-label.ts b/packages/views/issues/utils/status-label.ts
new file mode 100644
index 0000000000..fae35df300
--- /dev/null
+++ b/packages/views/issues/utils/status-label.ts
@@ -0,0 +1,35 @@
+"use client";
+
+import { useCallback } from "react";
+import { isIssueStatusCategory } from "@multica/core/issue-statuses";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import type { IssueStatusCategory } from "@multica/core/types";
+import { useT } from "../../i18n";
+
+/**
+ * Resolves a status KEY to the label the UI should show (MUL-6243).
+ *
+ * The catalog carries a `name` for every status including the 7 built-ins, but
+ * those built-in names are seeded in English by the server. Rendering them
+ * verbatim would turn "进行中" into "In Progress" for every non-English
+ * workspace, so built-ins always resolve through i18n and only custom statuses
+ * — whose names the workspace authored and which are not translatable — use
+ * the catalog's `name`.
+ *
+ * A key the catalog has never heard of (created seconds ago elsewhere, or a
+ * fetch still in flight) falls back to the raw key rather than rendering blank.
+ */
+export function useStatusLabel(wsId: string) {
+ const { t } = useT("issues");
+ const { entryOf } = useIssueStatuses(wsId);
+
+ return useCallback(
+ (statusKey: string): string => {
+ if (isIssueStatusCategory(statusKey)) {
+ return t(($) => $.status[statusKey as IssueStatusCategory]);
+ }
+ return entryOf(statusKey)?.name ?? statusKey;
+ },
+ [t, entryOf],
+ );
+}
diff --git a/packages/views/issues/utils/status-options.test.tsx b/packages/views/issues/utils/status-options.test.tsx
new file mode 100644
index 0000000000..4553f8e2b3
--- /dev/null
+++ b/packages/views/issues/utils/status-options.test.tsx
@@ -0,0 +1,144 @@
+import { renderHook } from "@testing-library/react";
+import { describe, expect, it, vi } from "vitest";
+import { buildIssueStatusCatalog } from "@multica/core/issue-statuses";
+import type { IssueStatusEntry } from "@multica/core/types";
+import en from "../../locales/en/issues.json";
+import { useStatusOptions } from "./status-options";
+import { useStatusLabel } from "./status-label";
+
+// The catalog itself is server state; this suite is about what the picker and
+// the filter are allowed to offer, so the catalog is fed in directly.
+let catalogEntries: IssueStatusEntry[] | undefined;
+
+vi.mock("@multica/core/hooks", () => ({
+ useWorkspaceId: () => "workspace-1",
+}));
+
+vi.mock("@multica/core/issue-statuses/hooks", () => ({
+ useIssueStatuses: () => buildIssueStatusCatalog(catalogEntries),
+}));
+
+// The REAL en locale, not a stub: the whole point of useStatusLabel is that a
+// built-in resolves through i18n rather than through the catalog's
+// server-seeded English name, and a stub would not prove the difference.
+vi.mock("../../i18n", () => ({
+ useT: () => ({
+ t: (accessor: (dict: unknown) => string) => accessor(en),
+ }),
+}));
+
+function entry(overrides: Partial<IssueStatusEntry>): IssueStatusEntry {
+ return {
+ id: overrides.key ?? "id",
+ workspace_id: "workspace-1",
+ key: "custom",
+ name: "Custom",
+ description: "",
+ category: "in_review",
+ color: "#ff0000",
+ is_system: false,
+ position: 1,
+ archived_at: null,
+ created_at: "",
+ updated_at: "",
+ ...overrides,
+ };
+}
+
+const BUILT_INS: IssueStatusEntry[] = (
+ ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"] as const
+).map((key) =>
+ entry({
+ id: key,
+ key,
+ // Seeded in English by the server on purpose — a label resolved from here
+ // instead of i18n is the regression this fixture exists to catch.
+ name: key === "in_progress" ? "In Progress" : key,
+ category: key,
+ is_system: true,
+ position: 0,
+ }),
+);
+
+describe("useStatusOptions", () => {
+ // A cold render must offer the same 7 statuses it always did, or the picker
+ // opens empty on first paint and on any workspace whose catalog fetch failed.
+ it("offers the 7 built-ins when the catalog has not loaded", () => {
+ catalogEntries = undefined;
+ const { result } = renderHook(() => useStatusOptions("workspace-1"));
+
+ expect(result.current.options.map((o) => o.key)).toEqual([
+ "backlog",
+ "todo",
+ "in_progress",
+ "in_review",
+ "done",
+ "blocked",
+ "cancelled",
+ ]);
+ expect(result.current.hasCustom).toBe(false);
+ });
+
+ it("groups a custom status under the category it behaves as", () => {
+ catalogEntries = [...BUILT_INS, entry({ key: "qa", name: "QA", category: "in_review" })];
+ const { result } = renderHook(() => useStatusOptions("workspace-1"));
+
+ const inReview = result.current.groups.find((g) => g.category === "in_review");
+ expect(inReview?.options.map((o) => o.key)).toEqual(["in_review", "qa"]);
+ // Still 7 groups: a custom status must never create an eighth board column.
+ expect(result.current.groups).toHaveLength(7);
+ expect(result.current.hasCustom).toBe(true);
+ });
+
+ // Archiving retires a status from FUTURE assignment. Offering it here would
+ // hand the user a value the server rejects.
+ it("does not offer an archived status", () => {
+ catalogEntries = [
+ ...BUILT_INS,
+ entry({ key: "qa", name: "QA", archived_at: "2026-01-01T00:00:00Z" }),
+ ];
+ const { result } = renderHook(() => useStatusOptions("workspace-1"));
+
+ expect(result.current.options.map((o) => o.key)).not.toContain("qa");
+ });
+
+ // Built-ins keep their semantic token color; a hex here would override it.
+ it("carries a color for custom statuses only", () => {
+ catalogEntries = [...BUILT_INS, entry({ key: "qa", name: "QA", color: "#ff0000" })];
+ const { result } = renderHook(() => useStatusOptions("workspace-1"));
+
+ const byKey = new Map(result.current.options.map((o) => [o.key, o.color]));
+ expect(byKey.get("qa")).toBe("#ff0000");
+ expect(byKey.get("in_review")).toBeNull();
+ });
+});
+
+describe("useStatusLabel", () => {
+ // The server seeds built-in names in English. Reading them back verbatim
+ // would show "In Progress" to every workspace that has picked another
+ // language, silently undoing the whole i18n layer for status names.
+ it("labels a built-in from i18n, not from the catalog's seeded name", () => {
+ catalogEntries = BUILT_INS.map((e) =>
+ e.key === "in_progress" ? { ...e, name: "SEEDED-ENGLISH" } : e,
+ );
+ const { result } = renderHook(() => useStatusLabel("workspace-1"));
+
+ expect(result.current("in_progress")).toBe(en.status.in_progress);
+ });
+
+ it("labels a custom status from the catalog", () => {
+ catalogEntries = [...BUILT_INS, entry({ key: "qa", name: "QA Review" })];
+ const { result } = renderHook(() => useStatusLabel("workspace-1"));
+
+ expect(result.current("qa")).toBe("QA Review");
+ });
+
+ // A status created seconds ago in another session, or one since deleted.
+ // Showing the raw key beats showing nothing.
+ it("falls back to the raw key for a status the catalog does not know", () => {
+ catalogEntries = BUILT_INS;
+ const { result } = renderHook(() => useStatusLabel("workspace-1"));
+
+ expect(result.current("never-seen")).toBe("never-seen");
+ });
+});
diff --git a/packages/views/issues/utils/status-options.ts b/packages/views/issues/utils/status-options.ts
new file mode 100644
index 0000000000..08fb68ac2d
--- /dev/null
+++ b/packages/views/issues/utils/status-options.ts
@@ -0,0 +1,66 @@
+"use client";
+
+import { useMemo } from "react";
+import { ALL_STATUSES } from "@multica/core/issues/config";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
+import type { IssueStatus, IssueStatusCategory } from "@multica/core/types";
+import { useStatusLabel } from "./status-label";
+
+export interface StatusOption {
+ key: IssueStatus;
+ label: string;
+ /** `#rrggbb` for a custom status; null for a built-in, which keeps its token color. */
+ color: string | null;
+}
+
+export interface StatusOptionGroup {
+ category: IssueStatusCategory;
+ options: StatusOption[];
+}
+
+/**
+ * The statuses a user can pick or filter by, grouped by category in canonical
+ * category order (MUL-6243).
+ *
+ * Shared by the status picker and the status filter so the two can never drift
+ * — a status offered in one and missing from the other is exactly how an issue
+ * becomes unfindable.
+ *
+ * Archived statuses are excluded: archiving retires a status from future
+ * assignment. Issues already on one keep it, and `useStatusLabel` still names
+ * it, because the catalog query keeps archived rows.
+ */
+export function useStatusOptions(wsId: string): {
+ groups: StatusOptionGroup[];
+ /** Flat list in the same order, for surfaces without grouping. */
+ options: StatusOption[];
+ /** True once any category holds more than one status — i.e. group headings earn their space. */
+ hasCustom: boolean;
+} {
+ const { activeStatuses } = useIssueStatuses(wsId);
+ const labelOf = useStatusLabel(wsId);
+
+ return useMemo(() => {
+ const groups = ALL_STATUSES.map((category) => {
+ const entries = activeStatuses.filter((e) => e.category === category);
+ const options: StatusOption[] =
+ entries.length > 0
+ ? entries.map((e) => ({
+ key: e.key as IssueStatus,
+ label: labelOf(e.key),
+ color: e.is_system ? null : e.color,
+ }))
+ : // No catalog row for this category: the fetch is still in flight,
+ // or this workspace predates the seed. Offer the built-in, whose
+ // key IS the category, so a lifecycle step is never missing.
+ [{ key: category as IssueStatus, label: labelOf(category), color: null }];
+ return { category, options };
+ });
+
+ return {
+ groups,
+ options: groups.flatMap((g) => g.options),
+ hasCustom: groups.some((g) => g.options.length > 1),
+ };
+ }, [activeStatuses, labelOf]);
+}
diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsx
index 345192373c..bf1903e34a 100644
--- a/packages/views/layout/app-sidebar.tsx
+++ b/packages/views/layout/app-sidebar.tsx
@@ -1,5 +1,6 @@
"use client";
+import { issueStatusCategory } from "@multica/core/issues";
import React, { useCallback, useEffect, useRef, useState } from "react";
import { cn } from "@multica/ui/lib/utils";
import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";
@@ -365,7 +366,11 @@ function PinRow({
const label = issue.title;
const iconNode = (
/* Override parent [&_svg]:size-4 — pinned items need smaller icons to match sm size */
- <StatusIcon status={issue.status} className="!size-3.5 shrink-0" />
+ <StatusIcon
+ status={issue.status}
+ category={issueStatusCategory(issue) ?? undefined}
+ className="!size-3.5 shrink-0"
+ />
);
return (
<SortablePinItem
diff --git a/packages/views/layout/tab-presentation.test.tsx b/packages/views/layout/tab-presentation.test.tsx
index 733acd3d19..bdbc604b21 100644
--- a/packages/views/layout/tab-presentation.test.tsx
+++ b/packages/views/layout/tab-presentation.test.tsx
@@ -109,7 +109,9 @@ describe("useTabPresentation — live from cache", () => {
it("issue: live status glyph + identifier:title", () => {
expect(presentationOf("/acme/issues/i1")).toEqual({
- visual: { kind: "issue-status", status: "in_progress" },
+ // `category` travels with the visual so the tab strip never resolves a
+ // custom status key itself. (MUL-6243)
+ visual: { kind: "issue-status", status: "in_progress", category: "in_progress" },
title: "MUL-1: Fix login",
});
});
diff --git a/packages/views/layout/tab-presentation.tsx b/packages/views/layout/tab-presentation.tsx
index 300d987b89..bc19989358 100644
--- a/packages/views/layout/tab-presentation.tsx
+++ b/packages/views/layout/tab-presentation.tsx
@@ -282,7 +282,13 @@ export function ResourceLeadingVisual({
}
case "issue-status":
// A null status (loading) renders StatusIcon's neutral fallback glyph.
- inner = <StatusIcon status={visual.status ?? ""} className="size-3.5" />;
+ inner = (
+ <StatusIcon
+ status={visual.status ?? ""}
+ category={visual.category}
+ className="size-3.5"
+ />
+ );
break;
case "project-icon":
inner = <ProjectIcon project={{ icon: visual.icon }} size="sm" />;
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index d88f87017d..d80e983158 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -1,4 +1,9 @@
{
+ "status_catalog_error": {
+ "title": "Couldn't load the status list",
+ "hint": "Issues are hidden until it loads, because a status filter can't be applied without it.",
+ "retry": "Try again"
+ },
"page": {
"breadcrumb_title": "Issues",
"breadcrumb_workspace_fallback": "Workspace",
@@ -37,6 +42,7 @@
"filters": {
"tooltip": "Filter",
"placeholder": "Filter...",
+ "search_status": "Search status...",
"no_results": "No results",
"no_labels": "No labels yet",
"no_assignee": "No assignee",
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 6f39934da1..ce4faeaf66 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -1,4 +1,54 @@
{
+ "issue_statuses": {
+ "title": "Issue Statuses",
+ "description": "Add statuses of your own on top of the seven built-in ones. Every status belongs to a category, and the category is what determines its behavior.",
+ "loading": "Loading statuses…",
+ "add": "Add status",
+ "show_archived": "Show archived ({{count}})",
+ "archived_badge": "Archived",
+ "archived_hint": "Retired from new assignments. Issues already on it keep it.",
+ "built_in_locked": "Built-in status. Name, color and category are fixed.",
+ "flag_off": "Custom statuses are not enabled for this deployment yet. The built-in statuses below work as usual.",
+ "reorder_failed": "Could not save the new order.",
+ "actions": {
+ "open": "Actions for {{name}}",
+ "edit": "Edit",
+ "archive": "Archive",
+ "reorder": "Reorder {{name}}"
+ },
+ "editor": {
+ "create_title": "New status",
+ "edit_title": "Edit status",
+ "behavior_hint": "This status behaves exactly like {{category}}.",
+ "name": "Name",
+ "name_placeholder": "e.g. Code Review",
+ "category": "Category",
+ "category_locked": "Category cannot be changed — issues already on this status depend on it.",
+ "description": "Description",
+ "description_placeholder": "What this status means for your team",
+ "color": "Color",
+ "cancel": "Cancel",
+ "save": "Save",
+ "saving": "Saving…",
+ "save_failed": "Could not save the status."
+ },
+ "archive_dialog": {
+ "title": "Archive this status?",
+ "description": "\"{{name}}\" stops being available for new issues. Issues already on it keep it and keep behaving exactly as they do now.",
+ "cancel": "Cancel",
+ "confirm": "Archive",
+ "failed": "Could not archive the status."
+ },
+ "categories": {
+ "backlog": "Parked. Assigning an issue here never starts an agent run.",
+ "todo": "Queued. Moving an issue here starts the assigned agent.",
+ "in_progress": "Actively being worked on.",
+ "in_review": "Delivered, waiting on human review. Finalizes the autopilot run.",
+ "done": "Completed.",
+ "blocked": "Stalled on an external dependency.",
+ "cancelled": "Decided not to do."
+ }
+ },
"quick_actions": {
"title": "Quick Actions",
"description": "Preset an agent and a prompt once, then trigger it from any issue's sidebar with a single click.",
@@ -205,6 +255,7 @@
"labs": "Labs",
"members": "Members",
"labels": "Labels",
+ "issue_statuses": "Issue Statuses",
"properties": "Properties",
"quick_actions": "Quick Actions",
"plugins": "Plugins",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 77f08791f6..71a4f5b550 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -1,4 +1,9 @@
{
+ "status_catalog_error": {
+ "title": "ステータス一覧を読み込めませんでした",
+ "hint": "これがないとステータスの絞り込みを適用できないため、イシューは表示されません。",
+ "retry": "再試行"
+ },
"page": {
"breadcrumb_title": "タスク",
"breadcrumb_workspace_fallback": "ワークスペース",
@@ -37,6 +42,7 @@
"filters": {
"tooltip": "フィルター",
"placeholder": "フィルター...",
+ "search_status": "ステータスを検索...",
"no_results": "結果なし",
"no_labels": "まだラベルがありません",
"no_assignee": "担当者なし",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 335bcae2a2..f993b67816 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -1,4 +1,54 @@
{
+ "issue_statuses": {
+ "title": "イシューステータス",
+ "description": "組み込みの 7 つのステータスに加えて独自のステータスを追加できます。各ステータスはカテゴリに属し、カテゴリが挙動を決めます。",
+ "loading": "ステータスを読み込み中…",
+ "add": "ステータスを追加",
+ "show_archived": "アーカイブ済みを表示({{count}})",
+ "archived_badge": "アーカイブ済み",
+ "archived_hint": "新規の割り当てには使えません。すでにこのステータスのイシューはそのままです。",
+ "built_in_locked": "組み込みステータス。名前・色・カテゴリは変更できません。",
+ "flag_off": "このデプロイではカスタムステータスがまだ有効化されていません。下の組み込みステータスは通常どおり使えます。",
+ "reorder_failed": "並び順を保存できませんでした。",
+ "actions": {
+ "open": "{{name}} の操作",
+ "edit": "編集",
+ "archive": "アーカイブ",
+ "reorder": "{{name}} を並べ替え"
+ },
+ "editor": {
+ "create_title": "新しいステータス",
+ "edit_title": "ステータスを編集",
+ "behavior_hint": "このステータスは「{{category}}」とまったく同じ挙動になります。",
+ "name": "名前",
+ "name_placeholder": "例: Code Review",
+ "category": "カテゴリ",
+ "category_locked": "カテゴリは変更できません。すでにこのステータスのイシューが依存しています。",
+ "description": "説明",
+ "description_placeholder": "チームにとってこのステータスが意味すること",
+ "color": "色",
+ "cancel": "キャンセル",
+ "save": "保存",
+ "saving": "保存中…",
+ "save_failed": "ステータスを保存できませんでした。"
+ },
+ "archive_dialog": {
+ "title": "このステータスをアーカイブしますか?",
+ "description": "「{{name}}」は新しいイシューに割り当てられなくなります。すでにこのステータスのイシューはそのまま残り、挙動も変わりません。",
+ "cancel": "キャンセル",
+ "confirm": "アーカイブ",
+ "failed": "アーカイブできませんでした。"
+ },
+ "categories": {
+ "backlog": "保留。ここに移動してもエージェントは起動しません。",
+ "todo": "待機中。ここに移動すると担当エージェントが起動します。",
+ "in_progress": "作業中。",
+ "in_review": "納品済み、レビュー待ち。オートパイロットの実行を完了します。",
+ "done": "完了。",
+ "blocked": "外部依存でブロック中。",
+ "cancelled": "見送り。"
+ }
+ },
"quick_actions": {
"title": "クイックアクション",
"description": "実行するエージェントとプロンプトを事前に設定し、任意のタスクのサイドバーからワンクリックで実行します。",
@@ -205,6 +255,7 @@
"labs": "ラボ",
"members": "メンバー",
"labels": "ラベル",
+ "issue_statuses": "ステータス",
"properties": "プロパティ",
"quick_actions": "クイックアクション",
"plugins": "Plugins",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 0ae914eb1e..53785955b2 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -1,4 +1,9 @@
{
+ "status_catalog_error": {
+ "title": "상태 목록을 불러오지 못했습니다",
+ "hint": "이것 없이는 상태 필터를 적용할 수 없어 이슈를 표시하지 않습니다.",
+ "retry": "다시 시도"
+ },
"page": {
"breadcrumb_title": "태스크",
"breadcrumb_workspace_fallback": "워크스페이스",
@@ -37,6 +42,7 @@
"filters": {
"tooltip": "필터",
"placeholder": "필터...",
+ "search_status": "상태 검색...",
"no_results": "결과 없음",
"no_labels": "아직 라벨이 없습니다",
"no_assignee": "담당자 없음",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index cf57ae489b..f3c309eb3e 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -1,4 +1,54 @@
{
+ "issue_statuses": {
+ "title": "이슈 상태",
+ "description": "기본 제공되는 7개 상태에 더해 직접 상태를 추가할 수 있습니다. 모든 상태는 카테고리에 속하며, 동작은 카테고리가 결정합니다.",
+ "loading": "상태를 불러오는 중…",
+ "add": "상태 추가",
+ "show_archived": "보관됨 표시 ({{count}})",
+ "archived_badge": "보관됨",
+ "archived_hint": "새로 지정할 수 없습니다. 이미 이 상태인 이슈는 그대로 유지됩니다.",
+ "built_in_locked": "기본 제공 상태입니다. 이름, 색상, 카테고리를 바꿀 수 없습니다.",
+ "flag_off": "이 배포에서는 사용자 지정 상태가 아직 활성화되지 않았습니다. 아래 기본 상태는 평소대로 동작합니다.",
+ "reorder_failed": "새 순서를 저장하지 못했습니다.",
+ "actions": {
+ "open": "{{name}} 작업",
+ "edit": "편집",
+ "archive": "보관",
+ "reorder": "{{name}} 순서 변경"
+ },
+ "editor": {
+ "create_title": "새 상태",
+ "edit_title": "상태 편집",
+ "behavior_hint": "이 상태는 \"{{category}}\"와 정확히 같게 동작합니다.",
+ "name": "이름",
+ "name_placeholder": "예: Code Review",
+ "category": "카테고리",
+ "category_locked": "카테고리는 변경할 수 없습니다. 이미 이 상태인 이슈가 이에 의존합니다.",
+ "description": "설명",
+ "description_placeholder": "팀에게 이 상태가 의미하는 것",
+ "color": "색상",
+ "cancel": "취소",
+ "save": "저장",
+ "saving": "저장 중…",
+ "save_failed": "상태를 저장하지 못했습니다."
+ },
+ "archive_dialog": {
+ "title": "이 상태를 보관할까요?",
+ "description": "\"{{name}}\"은(는) 새 이슈에 지정할 수 없게 됩니다. 이미 이 상태인 이슈는 그대로 유지되며 동작도 달라지지 않습니다.",
+ "cancel": "취소",
+ "confirm": "보관",
+ "failed": "보관하지 못했습니다."
+ },
+ "categories": {
+ "backlog": "보류. 여기로 옮겨도 에이전트가 시작되지 않습니다.",
+ "todo": "대기 중. 여기로 옮기면 담당 에이전트가 시작됩니다.",
+ "in_progress": "진행 중.",
+ "in_review": "전달 완료, 리뷰 대기. 오토파일럿 실행을 마무리합니다.",
+ "done": "완료.",
+ "blocked": "외부 의존성으로 중단됨.",
+ "cancelled": "진행하지 않기로 함."
+ }
+ },
"quick_actions": {
"title": "퀵 액션",
"description": "실행할 에이전트와 프롬프트를 미리 설정한 뒤, 어떤 태스크의 사이드바에서든 한 번의 클릭으로 실행합니다.",
@@ -205,6 +255,7 @@
"labs": "실험실",
"members": "멤버",
"labels": "레이블",
+ "issue_statuses": "이슈 상태",
"properties": "속성",
"quick_actions": "퀵 액션",
"plugins": "Plugins",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 2b0bfa596b..0ea113a251 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -1,4 +1,9 @@
{
+ "status_catalog_error": {
+ "title": "状态列表加载失败",
+ "hint": "没有它就无法应用状态筛选,因此暂时不显示议题。",
+ "retry": "重试"
+ },
"page": {
"breadcrumb_title": "任务",
"breadcrumb_workspace_fallback": "工作区",
@@ -37,6 +42,7 @@
"filters": {
"tooltip": "筛选",
"placeholder": "筛选...",
+ "search_status": "搜索状态...",
"no_results": "无结果",
"no_labels": "还没有标签",
"no_assignee": "无负责人",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index f9b1ccdf41..e7f51980d4 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -1,4 +1,54 @@
{
+ "issue_statuses": {
+ "title": "议题状态",
+ "description": "在内置的 7 个状态之外添加自己的状态。每个状态都属于一个分类,分类决定了它的行为。",
+ "loading": "正在加载状态…",
+ "add": "添加状态",
+ "show_archived": "显示已归档({{count}})",
+ "archived_badge": "已归档",
+ "archived_hint": "已停止用于新的指派,已经在该状态上的议题保持不变。",
+ "built_in_locked": "内置状态,名称、颜色和分类均不可修改。",
+ "flag_off": "当前部署尚未开启自定义状态,下面的内置状态照常使用。",
+ "reorder_failed": "排序保存失败。",
+ "actions": {
+ "open": "{{name}} 的操作",
+ "edit": "编辑",
+ "archive": "归档",
+ "reorder": "拖动排序 {{name}}"
+ },
+ "editor": {
+ "create_title": "新建状态",
+ "edit_title": "编辑状态",
+ "behavior_hint": "该状态的行为与「{{category}}」完全一致。",
+ "name": "名称",
+ "name_placeholder": "例如:Code Review",
+ "category": "分类",
+ "category_locked": "分类不可修改 —— 已经处于该状态的议题依赖它。",
+ "description": "描述",
+ "description_placeholder": "这个状态对团队意味着什么",
+ "color": "颜色",
+ "cancel": "取消",
+ "save": "保存",
+ "saving": "保存中…",
+ "save_failed": "状态保存失败。"
+ },
+ "archive_dialog": {
+ "title": "归档这个状态?",
+ "description": "「{{name}}」将不再能被指派给新的议题。已经处于该状态的议题保持不变,行为也完全不变。",
+ "cancel": "取消",
+ "confirm": "归档",
+ "failed": "归档失败。"
+ },
+ "categories": {
+ "backlog": "搁置。把议题移到这里不会启动 agent。",
+ "todo": "排队中。把议题移到这里会启动指派的 agent。",
+ "in_progress": "正在进行。",
+ "in_review": "已交付,等待人工 review。会结束 autopilot 运行。",
+ "done": "已完成。",
+ "blocked": "被外部依赖阻塞。",
+ "cancelled": "决定不做。"
+ }
+ },
"quick_actions": {
"title": "快捷操作",
"description": "预先配置好执行的 Agent 和提示词,之后在任意任务侧边栏一键触发。",
@@ -205,6 +255,7 @@
"labs": "实验室",
"members": "成员",
"labels": "标签",
+ "issue_statuses": "议题状态",
"properties": "属性",
"quick_actions": "快捷操作",
"plugins": "Plugins",
diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsx
index 359cef0096..fbd0a87671 100644
--- a/packages/views/modals/create-issue.tsx
+++ b/packages/views/modals/create-issue.tsx
@@ -1,5 +1,6 @@
"use client";
+import { issueStatusCategory } from "@multica/core/issues";
import { useState, useRef, useEffect, useLayoutEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { AppLink, resolveClickIntent, useNavigation } from "../navigation";
@@ -60,6 +61,7 @@ import { useIssueTriggerPreview } from "../issues/hooks/use-issue-trigger-previe
import { useActorName } from "@multica/core/workspace/hooks";
import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
import { useWorkspaceId } from "@multica/core/hooks";
+import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { useIssueDraftStore, type IssueCreateDraft } from "@multica/core/issues/stores/draft-store";
import { useCreateModeStore } from "@multica/core/issues/stores/create-mode-store";
import { useQuickCreateStore } from "@multica/core/issues/stores/quick-create-store";
@@ -296,6 +298,7 @@ export function ManualCreatePanel({
// Fetch parent issue details for the chip (status/identifier/title).
// List cache usually has it already, so this resolves synchronously.
const wsId = useWorkspaceId();
+ const { categoryOf: draftStatusCategory } = useIssueStatuses(wsId);
const { data: workspaceProperties = [] } = useQuery(propertyListOptions(wsId));
const { data: parentIssue } = useQuery({
...issueDetailOptions(wsId, parentIssueId ?? ""),
@@ -581,7 +584,11 @@ export function ManualCreatePanel({
<span className="text-body font-medium">{t(($) => $.create_issue.toast_created)}</span>
</div>
<div className="flex items-center gap-2 text-body text-muted-foreground ml-7">
- <StatusIcon status={issue.status} className="size-3.5 shrink-0" />
+ <StatusIcon
+ status={issue.status}
+ category={issueStatusCategory(issue) ?? undefined}
+ className="size-3.5 shrink-0"
+ />
<span className="truncate">{issue.identifier} – {issue.title}</span>
</div>
{/* Not an AppLink: sonner renders toast content under <Toaster />,
@@ -1099,7 +1106,11 @@ export function ManualCreatePanel({
the picker inline (mounting the pill as its anchor). */}
{!showField.status && (
<DropdownMenuItem onClick={() => setFieldPickerOpen("status")}>
- <StatusIcon status={status} className="h-3.5 w-3.5" />
+ <StatusIcon
+ status={status}
+ category={draftStatusCategory(status)}
+ className="h-3.5 w-3.5"
+ />
{t(($) => $.create_issue.set_status)}
</DropdownMenuItem>
)}
diff --git a/packages/views/modals/issue-picker-modal.tsx b/packages/views/modals/issue-picker-modal.tsx
index 3a263924ea..3eaf16d737 100644
--- a/packages/views/modals/issue-picker-modal.tsx
+++ b/packages/views/modals/issue-picker-modal.tsx
@@ -1,5 +1,6 @@
"use client";
+import { issueStatusCategory } from "@multica/core/issues";
import { useState, useEffect, useCallback, useRef } from "react";
import type { Issue } from "@multica/core/types";
import { api } from "@multica/core/api";
@@ -124,7 +125,11 @@ export function IssuePickerModal({
onOpenChange(false);
}}
>
- <StatusIcon status={issue.status} className="h-3.5 w-3.5 shrink-0" />
+ <StatusIcon
+ status={issue.status}
+ category={issueStatusCategory(issue) ?? undefined}
+ className="h-3.5 w-3.5 shrink-0"
+ />
<span className="text-muted-foreground shrink-0">{issue.identifier}</span>
<span className="truncate">{issue.title}</span>
</CommandItem>
diff --git a/packages/views/onboarding/steps/step-welcome.tsx b/packages/views/onboarding/steps/step-welcome.tsx
index b946ffa91f..24b96bc2a1 100644
--- a/packages/views/onboarding/steps/step-welcome.tsx
+++ b/packages/views/onboarding/steps/step-welcome.tsx
@@ -1,5 +1,6 @@
"use client";
+import { statusCategoryOfKey } from "@multica/core/issues";
import { useState } from "react";
import { ArrowRight, Download, Loader2 } from "lucide-react";
import { Button, buttonVariants } from "@multica/ui/components/ui/button";
@@ -364,7 +365,7 @@ function StatusFooter({
status: IssueStatus;
timestamp?: string;
}) {
- const cfg = STATUS_CONFIG[status];
+ const cfg = STATUS_CONFIG[statusCategoryOfKey(status)];
return (
<div className="mt-3 flex items-center gap-2 text-caption">
<span
diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsx
index 8323c34b35..a288e4ae66 100644
--- a/packages/views/search/search-command.tsx
+++ b/packages/views/search/search-command.tsx
@@ -1,5 +1,6 @@
"use client";
+import { issueStatusCategory } from "@multica/core/issues";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Check,
@@ -233,7 +234,11 @@ function IssueResultRow({
className="flex cursor-default select-none flex-col gap-1 rounded-lg px-3 py-2.5 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"
>
<div className="flex items-center gap-2.5">
- <StatusIcon status={issue.status} className="size-4 shrink-0" />
+ <StatusIcon
+ status={issue.status}
+ category={issueStatusCategory(issue) ?? undefined}
+ className="size-4 shrink-0"
+ />
<span className="text-caption text-muted-foreground shrink-0">
{issue.identifier}
</span>
@@ -937,6 +942,7 @@ export function SearchCommand() {
>
<StatusIcon
status={item.status}
+ category={issueStatusCategory(item) ?? undefined}
className="size-4 shrink-0"
/>
<span className="text-caption text-muted-foreground shrink-0">
diff --git a/packages/views/settings/components/issue-statuses-tab.test.tsx b/packages/views/settings/components/issue-statuses-tab.test.tsx
new file mode 100644
index 0000000000..146ebdd00b
--- /dev/null
+++ b/packages/views/settings/components/issue-statuses-tab.test.tsx
@@ -0,0 +1,162 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render, screen } from "@testing-library/react";
+import type { IssueStatusEntry } from "@multica/core/types";
+import en from "../../locales/en/settings.json";
+import { IssueStatusesTab } from "./issue-statuses-tab";
+
+const reorderMutate = vi.hoisted(() => vi.fn());
+let catalog: IssueStatusEntry[] = [];
+let role: string = "owner";
+let flagOn = true;
+
+vi.mock("@tanstack/react-query", () => ({
+ useQuery: (options: { queryKey: readonly unknown[] }) => ({
+ data: options.queryKey[0] === "issue-statuses" ? catalog : members(),
+ isLoading: false,
+ }),
+}));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (selector: (s: unknown) => unknown) => selector({ user: { id: "u-1" } }),
+}));
+vi.mock("@multica/core/config", () => ({ useFeatureEnabled: () => flagOn }));
+vi.mock("@multica/core/workspace/queries", () => ({
+ memberListOptions: () => ({ queryKey: ["members", "ws-1"] }),
+}));
+vi.mock("@multica/core/issue-statuses/queries", () => ({
+ issueStatusListOptions: () => ({ queryKey: ["issue-statuses", "ws-1"] }),
+}));
+vi.mock("@multica/core/issue-statuses/mutations", () => ({
+ useCreateIssueStatus: () => ({ mutate: vi.fn(), isPending: false }),
+ useUpdateIssueStatus: () => ({ mutate: vi.fn(), isPending: false }),
+ useArchiveIssueStatus: () => ({ mutate: vi.fn() }),
+ useReorderIssueStatuses: () => ({ mutate: reorderMutate }),
+}));
+vi.mock("../../issues/utils/status-label", () => ({
+ useStatusLabel: () => (key: string) => key,
+}));
+vi.mock("../../i18n", () => ({
+ useT: () => ({
+ t: (accessor: (dict: unknown) => string, params?: Record<string, unknown>) => {
+ const template = accessor(en);
+ if (!params) return template;
+ return template.replace(/\{\{(\w+)\}\}/g, (_, k: string) => String(params[k] ?? ""));
+ },
+ }),
+}));
+
+function members() {
+ return [{ user_id: "u-1", role }];
+}
+
+function entry(overrides: Partial<IssueStatusEntry>): IssueStatusEntry {
+ return {
+ id: overrides.key ?? "id",
+ workspace_id: "ws-1",
+ key: "custom",
+ name: "Custom",
+ description: "",
+ category: "in_review",
+ color: "#ff0000",
+ is_system: false,
+ position: 1,
+ archived_at: null,
+ created_at: "",
+ updated_at: "",
+ ...overrides,
+ };
+}
+
+const BUILT_IN_IN_REVIEW = entry({
+ id: "in_review",
+ key: "in_review",
+ name: "In Review",
+ is_system: true,
+ position: 0,
+});
+
+afterEach(() => {
+ cleanup();
+ reorderMutate.mockClear();
+ catalog = [];
+ role = "owner";
+ flagOn = true;
+});
+
+describe("IssueStatusesTab", () => {
+ it("offers status creation to an owner when the rollout flag is on", () => {
+ catalog = [BUILT_IN_IN_REVIEW];
+ render(<IssueStatusesTab />);
+
+ expect(screen.getAllByText(en.issue_statuses.add).length).toBeGreaterThan(0);
+ expect(screen.queryByText(en.issue_statuses.flag_off)).toBeNull();
+ });
+
+ // The flag gates CREATION only. Existing statuses stay fully readable, which
+ // is what makes the flag safe to leave off after the backend ships.
+ it("hides creation and explains why when the flag is off", () => {
+ catalog = [BUILT_IN_IN_REVIEW, entry({ key: "qa", name: "QA" })];
+ flagOn = false;
+ render(<IssueStatusesTab />);
+
+ expect(screen.queryByText(en.issue_statuses.add)).toBeNull();
+ expect(screen.getByText(en.issue_statuses.flag_off)).toBeInTheDocument();
+ expect(screen.getByText("QA")).toBeInTheDocument();
+ });
+
+ it("hides creation and row actions from a non-admin member", () => {
+ catalog = [BUILT_IN_IN_REVIEW, entry({ key: "qa", name: "QA" })];
+ role = "member";
+ render(<IssueStatusesTab />);
+
+ expect(screen.queryByText(en.issue_statuses.add)).toBeNull();
+ expect(screen.getByText("QA")).toBeInTheDocument();
+ expect(
+ screen.queryByLabelText(
+ en.issue_statuses.actions.open.replace("{{name}}", "QA"),
+ ),
+ ).toBeNull();
+ });
+
+ // Archiving retires a status from FUTURE assignment; the row has to stay
+ // legible so an admin can tell what a lingering status on an old issue is.
+ it("keeps an archived status visible but not actionable", () => {
+ catalog = [
+ BUILT_IN_IN_REVIEW,
+ entry({ key: "qa", name: "QA", archived_at: "2026-01-01T00:00:00Z" }),
+ ];
+ render(<IssueStatusesTab />);
+
+ // Hidden until the toggle is on, but the toggle itself is enabled because
+ // the workspace has one.
+ expect(screen.queryByText("QA")).toBeNull();
+ expect(screen.getByRole("switch")).toBeEnabled();
+ });
+
+ it("does not offer reorder when a category holds a single custom status", () => {
+ catalog = [BUILT_IN_IN_REVIEW, entry({ key: "qa", name: "QA" })];
+ render(<IssueStatusesTab />);
+
+ expect(
+ screen.queryByLabelText(
+ en.issue_statuses.actions.reorder.replace("{{name}}", "QA"),
+ ),
+ ).toBeNull();
+ });
+
+ it("offers reorder once a category holds two", () => {
+ catalog = [
+ BUILT_IN_IN_REVIEW,
+ entry({ id: "qa", key: "qa", name: "QA", position: 1 }),
+ entry({ id: "uat", key: "uat", name: "UAT", position: 2 }),
+ ];
+ render(<IssueStatusesTab />);
+
+ expect(
+ screen.getByLabelText(en.issue_statuses.actions.reorder.replace("{{name}}", "QA")),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/settings/components/issue-statuses-tab.tsx b/packages/views/settings/components/issue-statuses-tab.tsx
new file mode 100644
index 0000000000..4a3023adf1
--- /dev/null
+++ b/packages/views/settings/components/issue-statuses-tab.tsx
@@ -0,0 +1,678 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import {
+ Archive,
+ ArchiveRestore,
+ GripVertical,
+ Lock,
+ MoreHorizontal,
+ Pencil,
+ Plus,
+} from "lucide-react";
+import { toast } from "sonner";
+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 { useWorkspaceId } from "@multica/core/hooks";
+import { useAuthStore } from "@multica/core/auth";
+import { useFeatureEnabled } from "@multica/core/config";
+import { memberListOptions } from "@multica/core/workspace/queries";
+import { issueStatusListOptions } from "@multica/core/issue-statuses/queries";
+import {
+ useArchiveIssueStatus,
+ useCreateIssueStatus,
+ useReorderIssueStatuses,
+ useUpdateIssueStatus,
+} from "@multica/core/issue-statuses/mutations";
+import { ALL_STATUSES } from "@multica/core/issues/config";
+import type { IssueStatusCategory, IssueStatusEntry } from "@multica/core/types";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import { Textarea } from "@multica/ui/components/ui/textarea";
+import { Label as FieldLabel } from "@multica/ui/components/ui/label";
+import { Switch } from "@multica/ui/components/ui/switch";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@multica/ui/components/ui/tooltip";
+import { ColorPicker, COLOR_PICKER_PRESETS } from "../../common/color-picker";
+import { StatusIcon } from "../../issues/components/status-icon";
+import { useStatusLabel } from "../../issues/utils/status-label";
+import { useT } from "../../i18n";
+import { SettingsTab } from "./settings-layout";
+
+/**
+ * Workspace issue status catalog management (MUL-6243).
+ *
+ * The page is organised by CATEGORY rather than as one flat list, because a
+ * category is not decoration here — it is the behavior a status inherits. A
+ * status in `todo` starts the assigned agent; one in `in_review` finalizes an
+ * autopilot run. Grouping is what makes that consequence visible at the moment
+ * the admin picks a category, which is also the only moment they can: category
+ * is immutable after creation, since changing it would silently rewrite the
+ * machine semantics of every issue already on the status.
+ *
+ * Built-ins are shown but locked. Each one is its category's canonical
+ * definition, and the default workspace has to look identical for every user
+ * who never opens this page.
+ */
+
+interface StatusDraft {
+ name: string;
+ description: string;
+ category: IssueStatusCategory;
+ color: string;
+}
+
+const EMPTY_DRAFT: StatusDraft = {
+ name: "",
+ description: "",
+ category: "todo",
+ color: COLOR_PICKER_PRESETS[6]!,
+};
+
+export function IssueStatusesTab() {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const canCreate = useFeatureEnabled("custom_issue_statuses");
+
+ const [showArchived, setShowArchived] = useState(false);
+ const [createCategory, setCreateCategory] = useState<IssueStatusCategory | null>(null);
+ const [editing, setEditing] = useState<IssueStatusEntry | null>(null);
+ const [pendingArchive, setPendingArchive] = useState<IssueStatusEntry | null>(null);
+
+ const { data: statuses = [], isLoading } = useQuery(issueStatusListOptions(wsId));
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const currentUser = useAuthStore((s) => s.user);
+ const myRole = useMemo(() => {
+ if (!currentUser) return null;
+ return members.find((m) => m.user_id === currentUser.id)?.role ?? null;
+ }, [members, currentUser]);
+ const isAdmin = myRole === "owner" || myRole === "admin";
+
+ const groups = useMemo(
+ () =>
+ ALL_STATUSES.map((category) => {
+ const inCategory = statuses.filter((s) => s.category === category);
+ return {
+ category,
+ builtIn: inCategory.find((s) => s.is_system),
+ // Archived rows are hidden behind a toggle rather than dropped: an
+ // admin needs to see what a lingering status on an old issue is.
+ custom: inCategory.filter(
+ (s) => !s.is_system && (showArchived || !s.archived_at),
+ ),
+ };
+ }),
+ [statuses, showArchived],
+ );
+
+ const archivedCount = statuses.filter((s) => !s.is_system && s.archived_at).length;
+
+ return (
+ <SettingsTab
+ title={t(($) => $.issue_statuses.title)}
+ description={t(($) => $.issue_statuses.description)}
+ >
+ <div className="space-y-5">
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <label className="flex items-center gap-2 text-body text-muted-foreground">
+ <Switch
+ checked={showArchived}
+ onCheckedChange={setShowArchived}
+ disabled={archivedCount === 0}
+ />
+ {t(($) => $.issue_statuses.show_archived, { count: archivedCount })}
+ </label>
+ </div>
+
+ {!canCreate && (
+ <p className="rounded-lg border border-surface-border bg-muted/20 px-4 py-3 text-caption text-muted-foreground">
+ {t(($) => $.issue_statuses.flag_off)}
+ </p>
+ )}
+
+ {isLoading ? (
+ <div className="rounded-lg border border-surface-border bg-card px-4 py-12 text-center text-body text-muted-foreground">
+ {t(($) => $.issue_statuses.loading)}
+ </div>
+ ) : (
+ <div className="space-y-4">
+ {groups.map((group) => (
+ <CategorySection
+ key={group.category}
+ category={group.category}
+ builtIn={group.builtIn}
+ custom={group.custom}
+ canManage={isAdmin}
+ canCreate={isAdmin && canCreate}
+ onCreate={() => setCreateCategory(group.category)}
+ onEdit={setEditing}
+ onArchive={setPendingArchive}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+
+ <StatusEditorDialog
+ open={createCategory !== null}
+ onOpenChange={(open) => !open && setCreateCategory(null)}
+ category={createCategory}
+ />
+ <StatusEditorDialog
+ open={Boolean(editing)}
+ onOpenChange={(open) => !open && setEditing(null)}
+ category={editing?.category ?? null}
+ status={editing}
+ />
+ <ArchiveStatusDialog status={pendingArchive} onClose={() => setPendingArchive(null)} />
+ </SettingsTab>
+ );
+}
+
+function CategorySection({
+ category,
+ builtIn,
+ custom,
+ canManage,
+ canCreate,
+ onCreate,
+ onEdit,
+ onArchive,
+}: {
+ category: IssueStatusCategory;
+ builtIn: IssueStatusEntry | undefined;
+ custom: IssueStatusEntry[];
+ canManage: boolean;
+ canCreate: boolean;
+ onCreate: () => void;
+ onEdit: (status: IssueStatusEntry) => void;
+ onArchive: (status: IssueStatusEntry) => void;
+}) {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const labelOf = useStatusLabel(wsId);
+ const reorder = useReorderIssueStatuses();
+
+ // Local order so the drag reads as instant even before the optimistic cache
+ // write settles; resynced whenever the server list changes.
+ const [order, setOrder] = useState(custom);
+ useEffect(() => setOrder(custom), [custom]);
+
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
+ );
+
+ const handleDragEnd = (event: DragEndEvent) => {
+ const { active, over } = event;
+ if (!over || active.id === over.id) return;
+ const from = order.findIndex((s) => s.id === active.id);
+ const to = order.findIndex((s) => s.id === over.id);
+ if (from < 0 || to < 0) return;
+ const next = arrayMove(order, from, to);
+ setOrder(next);
+ // ACTIVE rows only. With "show archived" on, `order` also holds archived
+ // rows; sending those made the server reject the request, and before the
+ // write became atomic that rejection landed AFTER the active rows had
+ // already been reordered. Archived rows are frozen, so their absence from
+ // the payload is also what the user sees.
+ reorder.mutate(
+ { category, ordered: next.filter((entry) => !entry.archived_at) },
+ {
+ onError: (error) => {
+ setOrder(custom);
+ toast.error(
+ error instanceof Error ? error.message : t(($) => $.issue_statuses.reorder_failed),
+ );
+ },
+ },
+ );
+ };
+
+ // Only rows that can actually move are draggable. A single custom status has
+ // nothing to swap with, and archived rows are frozen.
+ const sortableIds = order.filter((s) => !s.archived_at).map((s) => s.id);
+ const canReorder = canManage && sortableIds.length > 1;
+
+ return (
+ <div className="overflow-hidden rounded-lg border border-surface-border bg-card">
+ <div className="flex items-center gap-2 border-b border-surface-border bg-muted/20 px-4 py-2.5">
+ <StatusIcon status={category} category={category} className="size-3.5" />
+ <span className="text-caption font-medium">{labelOf(category)}</span>
+ <span className="flex-1 text-caption text-muted-foreground">
+ {t(($) => $.issue_statuses.categories[category])}
+ </span>
+ {canCreate && (
+ <Button variant="ghost" size="sm" className="gap-1.5" onClick={onCreate}>
+ <Plus className="size-3.5" />
+ {t(($) => $.issue_statuses.add)}
+ </Button>
+ )}
+ </div>
+
+ <div className="divide-y divide-surface-border">
+ {builtIn && <BuiltInRow entry={builtIn} label={labelOf(builtIn.key)} />}
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
+ <SortableContext items={sortableIds} strategy={verticalListSortingStrategy}>
+ {order.map((entry) => (
+ <CustomStatusRow
+ key={entry.id}
+ entry={entry}
+ canManage={canManage}
+ canReorder={canReorder && !entry.archived_at}
+ onEdit={() => onEdit(entry)}
+ onArchive={() => onArchive(entry)}
+ />
+ ))}
+ </SortableContext>
+ </DndContext>
+ </div>
+ </div>
+ );
+}
+
+function BuiltInRow({ entry, label }: { entry: IssueStatusEntry; label: string }) {
+ const { t } = useT("settings");
+ return (
+ <div className="flex items-center gap-3 px-4 py-3">
+ <span className="w-4 shrink-0" />
+ <StatusIcon status={entry.key} category={entry.category} className="size-3.5" />
+ <span className="min-w-0 truncate text-body font-medium">{label}</span>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span className="inline-flex items-center text-muted-foreground">
+ <Lock className="size-3.5" />
+ </span>
+ }
+ />
+ <TooltipContent>{t(($) => $.issue_statuses.built_in_locked)}</TooltipContent>
+ </Tooltip>
+ <span className="ml-auto truncate text-caption text-muted-foreground">
+ {entry.description || "—"}
+ </span>
+ </div>
+ );
+}
+
+function CustomStatusRow({
+ entry,
+ canManage,
+ canReorder,
+ onEdit,
+ onArchive,
+}: {
+ entry: IssueStatusEntry;
+ canManage: boolean;
+ canReorder: boolean;
+ onEdit: () => void;
+ onArchive: () => void;
+}) {
+ const { t } = useT("settings");
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
+ id: entry.id,
+ disabled: !canReorder,
+ });
+
+ const archived = Boolean(entry.archived_at);
+
+ return (
+ <div
+ ref={setNodeRef}
+ style={{ transform: CSS.Transform.toString(transform), transition }}
+ className={`flex items-center gap-3 bg-card px-4 py-3 ${isDragging ? "relative z-10 shadow-[var(--surface-shadow)]" : ""} ${archived ? "opacity-60" : ""}`}
+ >
+ {canReorder ? (
+ <button
+ type="button"
+ aria-label={t(($) => $.issue_statuses.actions.reorder, { name: entry.name })}
+ className="w-4 shrink-0 cursor-grab text-muted-foreground active:cursor-grabbing"
+ {...attributes}
+ {...listeners}
+ >
+ <GripVertical className="size-4" />
+ </button>
+ ) : (
+ <span className="w-4 shrink-0" />
+ )}
+ <StatusIcon
+ status={entry.key}
+ category={entry.category}
+ color={entry.color}
+ className="size-3.5"
+ />
+ <span className="min-w-0 truncate text-body font-medium">{entry.name}</span>
+ <code className="shrink-0 rounded bg-muted/60 px-1.5 py-0.5 text-micro text-muted-foreground">
+ {entry.key}
+ </code>
+ {archived && (
+ <span className="shrink-0 rounded-full bg-muted/60 px-1.5 py-0.5 text-micro text-muted-foreground">
+ {t(($) => $.issue_statuses.archived_badge)}
+ </span>
+ )}
+ <span className="ml-auto min-w-0 flex-1 truncate text-right text-caption text-muted-foreground">
+ {entry.description || "—"}
+ </span>
+ {canManage && !archived && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.issue_statuses.actions.open, { name: entry.name })}
+ >
+ <MoreHorizontal className="size-4" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={onEdit}>
+ <Pencil className="size-4" />
+ {t(($) => $.issue_statuses.actions.edit)}
+ </DropdownMenuItem>
+ <DropdownMenuItem variant="destructive" onClick={onArchive}>
+ <Archive className="size-4" />
+ {t(($) => $.issue_statuses.actions.archive)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ {archived && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span className="inline-flex size-8 items-center justify-center text-muted-foreground">
+ <ArchiveRestore className="size-4" />
+ </span>
+ }
+ />
+ <TooltipContent>{t(($) => $.issue_statuses.archived_hint)}</TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ );
+}
+
+function StatusEditorDialog({
+ open,
+ onOpenChange,
+ category,
+ status,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ category: IssueStatusCategory | null;
+ status?: IssueStatusEntry | null;
+}) {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const labelOf = useStatusLabel(wsId);
+ const create = useCreateIssueStatus();
+ const update = useUpdateIssueStatus();
+ const [draft, setDraft] = useState<StatusDraft>(EMPTY_DRAFT);
+
+ const categoryItems = ALL_STATUSES.map((c) => ({
+ value: c,
+ label: (
+ <span className="flex items-center gap-2">
+ <StatusIcon status={c} category={c} className="size-3.5" />
+ {labelOf(c)}
+ </span>
+ ),
+ }));
+
+ useEffect(() => {
+ if (!open) return;
+ setDraft(
+ status
+ ? {
+ name: status.name,
+ description: status.description ?? "",
+ category: status.category,
+ color: status.color,
+ }
+ : { ...EMPTY_DRAFT, category: category ?? "todo" },
+ );
+ }, [status, category, open]);
+
+ const submit = () => {
+ const name = draft.name.trim();
+ if (!name) return;
+ const onError = (error: unknown) =>
+ toast.error(
+ error instanceof Error ? error.message : t(($) => $.issue_statuses.editor.save_failed),
+ );
+
+ if (status) {
+ update.mutate(
+ {
+ id: status.id,
+ name,
+ description: draft.description.trim(),
+ color: draft.color,
+ },
+ { onSuccess: () => onOpenChange(false), onError },
+ );
+ return;
+ }
+ create.mutate(
+ {
+ name,
+ description: draft.description.trim(),
+ category: draft.category,
+ color: draft.color,
+ },
+ { onSuccess: () => onOpenChange(false), onError },
+ );
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>
+ {status
+ ? t(($) => $.issue_statuses.editor.edit_title)
+ : t(($) => $.issue_statuses.editor.create_title)}
+ </DialogTitle>
+ <DialogDescription>
+ {t(($) => $.issue_statuses.editor.behavior_hint, {
+ category: labelOf(draft.category),
+ })}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-5 py-2">
+ <div className="space-y-2">
+ <FieldLabel htmlFor="status-name">
+ {t(($) => $.issue_statuses.editor.name)}
+ </FieldLabel>
+ <Input
+ id="status-name"
+ autoFocus
+ maxLength={64}
+ value={draft.name}
+ onChange={(event) =>
+ setDraft((current) => ({ ...current, name: event.target.value }))
+ }
+ placeholder={t(($) => $.issue_statuses.editor.name_placeholder)}
+ />
+ </div>
+ <div className="space-y-2">
+ <FieldLabel>{t(($) => $.issue_statuses.editor.category)}</FieldLabel>
+ {/* Immutable after creation: changing it would silently rewrite the
+ platform behavior of every issue already on this status. */}
+ <Select
+ items={categoryItems}
+ value={draft.category}
+ onValueChange={(value) =>
+ value &&
+ setDraft((current) => ({ ...current, category: value as IssueStatusCategory }))
+ }
+ disabled={Boolean(status)}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {categoryItems.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-caption text-muted-foreground">
+ {status
+ ? t(($) => $.issue_statuses.editor.category_locked)
+ : t(($) => $.issue_statuses.categories[draft.category])}
+ </p>
+ </div>
+ <div className="space-y-2">
+ <FieldLabel htmlFor="status-description">
+ {t(($) => $.issue_statuses.editor.description)}
+ </FieldLabel>
+ <Textarea
+ id="status-description"
+ rows={3}
+ maxLength={256}
+ value={draft.description}
+ onChange={(event) =>
+ setDraft((current) => ({ ...current, description: event.target.value }))
+ }
+ placeholder={t(($) => $.issue_statuses.editor.description_placeholder)}
+ />
+ </div>
+ <div className="space-y-2">
+ <FieldLabel>{t(($) => $.issue_statuses.editor.color)}</FieldLabel>
+ <ColorPicker
+ value={draft.color}
+ onChange={(color) => setDraft((current) => ({ ...current, color }))}
+ trigger={
+ <button
+ type="button"
+ aria-label={t(($) => $.issue_statuses.editor.color)}
+ className="flex h-9 items-center gap-2.5 rounded-md border border-surface-border px-2.5 transition-colors hover:bg-surface-hover"
+ >
+ <span className="size-5 rounded-full" style={{ backgroundColor: draft.color }} />
+ <span className="font-mono text-caption uppercase text-muted-foreground">
+ {draft.color}
+ </span>
+ </button>
+ }
+ />
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ {t(($) => $.issue_statuses.editor.cancel)}
+ </Button>
+ <Button
+ onClick={submit}
+ disabled={!draft.name.trim() || create.isPending || update.isPending}
+ >
+ {create.isPending || update.isPending
+ ? t(($) => $.issue_statuses.editor.saving)
+ : t(($) => $.issue_statuses.editor.save)}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function ArchiveStatusDialog({
+ status,
+ onClose,
+}: {
+ status: IssueStatusEntry | null;
+ onClose: () => void;
+}) {
+ const { t } = useT("settings");
+ const archive = useArchiveIssueStatus();
+ return (
+ <AlertDialog open={Boolean(status)} onOpenChange={(open) => !open && onClose()}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t(($) => $.issue_statuses.archive_dialog.title)}</AlertDialogTitle>
+ {/* Archiving retires a status from FUTURE assignment. Issues already
+ on it keep it and keep behaving as their category prescribes —
+ say so, or this reads like a delete. */}
+ <AlertDialogDescription>
+ {t(($) => $.issue_statuses.archive_dialog.description, {
+ name: status?.name ?? "",
+ })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>
+ {t(($) => $.issue_statuses.archive_dialog.cancel)}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => {
+ if (!status) return;
+ archive.mutate(status.id, {
+ onSuccess: onClose,
+ onError: (error) =>
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.issue_statuses.archive_dialog.failed),
+ ),
+ });
+ }}
+ >
+ {t(($) => $.issue_statuses.archive_dialog.confirm)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsx
index 640abdf9a4..f379bc5ec7 100644
--- a/packages/views/settings/components/settings-page.tsx
+++ b/packages/views/settings/components/settings-page.tsx
@@ -13,6 +13,7 @@ import {
Plug,
MessageCircle,
Tags,
+ CircleDot,
Keyboard,
ListTodo,
Zap,
@@ -43,6 +44,7 @@ import { IntegrationsTab } from "./integrations-tab";
import { LabsTab } from "./labs-tab";
import { NotificationsTab } from "./notifications-tab";
import { LabelsTab } from "./labels-tab";
+import { IssueStatusesTab } from "./issue-statuses-tab";
import { PropertiesTab } from "./properties-tab";
import { QuickActionsTab } from "./quick-actions-tab";
import { KeyboardShortcutsTab } from "./keyboard-shortcuts-tab";
@@ -72,6 +74,7 @@ const WORKSPACE_TAB_KEYS = [
"members",
"billing",
"labels",
+ "issue_statuses",
"properties",
"quick_actions",
"mcp",
@@ -86,6 +89,7 @@ const WORKSPACE_TAB_VALUES = {
members: "members",
billing: "billing",
labels: "labels",
+ issue_statuses: "issue-statuses",
properties: "properties",
quick_actions: "quick-actions",
mcp: "mcp",
@@ -100,6 +104,7 @@ const WORKSPACE_TAB_ICONS = {
members: Users,
billing: CreditCard,
labels: Tags,
+ issue_statuses: CircleDot,
properties: SlidersHorizontal,
quick_actions: Zap,
mcp: Server,
@@ -259,7 +264,7 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
{/* Right content */}
<div className="min-w-0 flex-1 md:overflow-y-auto">
- <div className={`mx-auto w-full p-4 sm:p-6 md:p-8 ${activeTab === "labels" || activeTab === "properties" || activeTab === "quick-actions"
+ <div className={`mx-auto w-full p-4 sm:p-6 md:p-8 ${activeTab === "labels" || activeTab === "issue-statuses" || activeTab === "properties" || activeTab === "quick-actions"
? "max-w-5xl"
: "max-w-3xl"}`}>
<TabsContent value="profile"><AccountTab /></TabsContent>
@@ -279,6 +284,7 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
<TabsContent value="billing"><BillingTab /></TabsContent>
) : null}
<TabsContent value="labels"><LabelsTab /></TabsContent>
+ <TabsContent value="issue-statuses"><IssueStatusesTab /></TabsContent>
<TabsContent value="properties"><PropertiesTab /></TabsContent>
<TabsContent value="quick-actions"><QuickActionsTab /></TabsContent>
<TabsContent value="mcp"><McpTab /></TabsContent>
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index ca95af719d..68ae30249c 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1645,6 +1645,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Route("/api/issue-statuses", func(r chi.Router) {
r.Get("/", h.ListIssueStatuses)
r.Post("/", h.CreateIssueStatus)
+ r.Patch("/reorder", h.ReorderIssueStatuses)
r.Route("/{id}", func(r chi.Router) {
r.Patch("/", h.UpdateIssueStatus)
r.Delete("/", h.ArchiveIssueStatus)
diff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.go
index 0343812468..bf0d4670d5 100644
--- a/server/internal/featureflags/keys.go
+++ b/server/internal/featureflags/keys.go
@@ -62,6 +62,9 @@ var frontendPublicFlags = []string{
BillingWorkspaceSubscriptions,
ComposioMCPApps,
PluginsV1,
+ // The settings UI needs this to decide whether to offer status creation at
+ // all. Without it the tab would show a "New status" button that 403s.
+ CustomIssueStatuses,
}
func BillingWorkspaceSubscriptionsEnabled(ctx context.Context, flags *featureflag.Service) bool {
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 61b099269d..1f65994624 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -30,6 +30,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/lark"
"github.com/multica-ai/multica/server/internal/integrations/slack"
"github.com/multica-ai/multica/server/internal/integrations/wecom"
+ "github.com/multica-ai/multica/server/internal/issuestatus"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/realtime"
@@ -172,11 +173,17 @@ type Handler struct {
LocalSkillListStore LocalSkillListStore
LocalSkillImportStore LocalSkillImportStore
FeatureFlags *featureflag.Service
- LivenessStore LivenessStore
- HeartbeatScheduler HeartbeatScheduler
- Storage storage.Storage
- CFSigner *auth.CloudFrontSigner
- Analytics analytics.Client
+ // IssueStatusCatalog reads the workspace status catalog. Defaults to
+ // Queries; a test can substitute a counting wrapper to assert HOW MANY
+ // catalog reads a request performs, which is the only property that
+ // distinguishes the current one-read derivation from the N+1 it replaced.
+ // (MUL-6243)
+ IssueStatusCatalog issuestatus.Querier
+ LivenessStore LivenessStore
+ HeartbeatScheduler HeartbeatScheduler
+ Storage storage.Storage
+ CFSigner *auth.CloudFrontSigner
+ Analytics analytics.Client
// DaemonPendingWork pushes "heartbeat now" hints for queued
// heartbeat-carried requests (MUL-5444). Optional: when nil,
// requestDaemonPendingWork falls back to the local DaemonHub, which is the
diff --git a/server/internal/handler/issue_status.go b/server/internal/handler/issue_status.go
index 975332a7bb..79a58005eb 100644
--- a/server/internal/handler/issue_status.go
+++ b/server/internal/handler/issue_status.go
@@ -13,6 +13,7 @@ import (
"github.com/multica-ai/multica/server/internal/featureflags"
"github.com/multica-ai/multica/server/internal/issuestatus"
"github.com/multica-ai/multica/server/internal/logger"
+ "github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -372,3 +373,184 @@ func (h *Handler) loadIssueStatusForAdmin(w http.ResponseWriter, r *http.Request
}
return entry, wsUUID, true
}
+
+// ReorderIssueStatusesRequest carries one category's custom statuses in their
+// new order. Reordering is scoped to a category because position is
+// intra-category: a status can only move relative to its own column.
+//
+// `ids` must name EVERY active custom status in the category. A partial order
+// is rejected rather than applied, because positions are assigned from the
+// array index: reordering a subset would write positions that collide with the
+// rows left out of it.
+type ReorderIssueStatusesRequest struct {
+ Category string `json:"category"`
+ IDs []string `json:"ids"`
+}
+
+// ReorderIssueStatuses rewrites the intra-category order of a category's custom
+// statuses, atomically.
+//
+// Everything happens inside ONE transaction holding the catalog's SHARED lock,
+// which is the archive path's counterpart. That is not decoration:
+//
+// - Validating outside the transaction leaves a window. "Validate A and B →
+// another request archives B → reorder runs" would write A's new position
+// and silently skip B (the UPDATE excludes archived rows), then report 200
+// on a half-applied order.
+// - The affected-row count is checked against the payload, so any row the
+// UPDATE declines to touch fails the whole request instead of committing a
+// prefix.
+func (h *Handler) ReorderIssueStatuses(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ if _, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin"); !ok {
+ return
+ }
+
+ var req ReorderIssueStatusesRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if !issuestatus.IsCategory(req.Category) {
+ writeError(w, http.StatusBadRequest, "category must be one of: "+strings.Join(issuestatus.Canonical(), ", "))
+ return
+ }
+ if len(req.IDs) == 0 {
+ writeError(w, http.StatusBadRequest, "ids must not be empty")
+ return
+ }
+ ids := make([]pgtype.UUID, 0, len(req.IDs))
+ seen := make(map[string]struct{}, len(req.IDs))
+ for _, raw := range req.IDs {
+ if _, duplicate := seen[raw]; duplicate {
+ writeError(w, http.StatusBadRequest, "duplicate ids")
+ return
+ }
+ seen[raw] = struct{}{}
+ idUUID, err := util.ParseUUID(raw)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid issue status id")
+ return
+ }
+ ids = append(ids, idUUID)
+ }
+
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ slog.Warn("ReorderIssueStatuses begin failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to reorder issue statuses")
+ return
+ }
+ defer tx.Rollback(r.Context())
+ qtx := h.Queries.WithTx(tx)
+
+ // SHARED side of the catalog lock: it does not block other reorders or
+ // issue writes, only the EXCLUSIVE archive path. That is what closes the
+ // validate-then-write window.
+ if err := qtx.LockIssueStatusCatalogShared(r.Context(), wsUUID); err != nil {
+ slog.Warn("ReorderIssueStatuses lock failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to reorder issue statuses")
+ return
+ }
+
+ // The authoritative set, read under the lock. Comparing the payload against
+ // it covers every rejection case at once: a built-in, an archived status,
+ // another category's status, another workspace's row, and — the case a
+ // per-id check misses — an active status the payload simply left out.
+ active, err := qtx.ListActiveCustomIssueStatusEntries(r.Context(), db.ListActiveCustomIssueStatusEntriesParams{
+ WorkspaceID: wsUUID,
+ Category: req.Category,
+ })
+ if err != nil {
+ slog.Warn("ReorderIssueStatuses list failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to reorder issue statuses")
+ return
+ }
+ activeIDs := make(map[string]struct{}, len(active))
+ for _, entry := range active {
+ activeIDs[util.UUIDToString(entry.ID)] = struct{}{}
+ }
+ for i, raw := range req.IDs {
+ if _, isActive := activeIDs[raw]; isActive {
+ continue
+ }
+ // Still inside the lock, so this diagnosis cannot go stale. Reported
+ // per-reason rather than as one opaque conflict, because "you sent a
+ // built-in" and "someone archived it while you dragged" are different
+ // problems for the caller.
+ entry, err := qtx.GetIssueStatusEntryByID(r.Context(), db.GetIssueStatusEntryByIDParams{
+ ID: ids[i],
+ WorkspaceID: wsUUID,
+ })
+ switch {
+ case errors.Is(err, pgx.ErrNoRows):
+ writeError(w, http.StatusNotFound, "issue status not found")
+ case err != nil:
+ slog.Warn("load issue status for reorder failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to reorder issue statuses")
+ case entry.IsSystem:
+ writeError(w, http.StatusForbidden, "built-in statuses cannot be reordered")
+ case entry.ArchivedAt.Valid:
+ writeError(w, http.StatusConflict, "archived statuses cannot be reordered")
+ case entry.Category != req.Category:
+ writeError(w, http.StatusBadRequest, "ids must all belong to the requested category")
+ default:
+ writeError(w, http.StatusConflict, "issue status catalog changed during reorder")
+ }
+ return
+ }
+ // Every id is active — so a length mismatch means the payload LEFT ONE OUT.
+ // Applying it would assign positions from the array index and collide with
+ // the omitted row, so the whole request is refused.
+ if len(active) != len(ids) {
+ writeError(w, http.StatusConflict, "ids must name every active custom status in the category")
+ return
+ }
+
+ affected, err := qtx.ReorderIssueStatusEntries(r.Context(), db.ReorderIssueStatusEntriesParams{
+ Ids: ids,
+ WorkspaceID: wsUUID,
+ })
+ if err != nil {
+ slog.Warn("ReorderIssueStatuses failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to reorder issue statuses")
+ return
+ }
+ if affected != int64(len(ids)) {
+ // Belt and braces behind the lock: if the UPDATE declined a row anyway,
+ // roll the whole order back rather than commit a prefix.
+ slog.Warn("ReorderIssueStatuses touched an unexpected row count",
+ append(logger.RequestAttrs(r), "affected", affected, "expected", len(ids))...)
+ writeError(w, http.StatusConflict, "issue status catalog changed during reorder")
+ return
+ }
+
+ entries, err := qtx.ListIssueStatusEntries(r.Context(), db.ListIssueStatusEntriesParams{
+ WorkspaceID: wsUUID,
+ IncludeArchived: true,
+ })
+ if err != nil {
+ slog.Warn("list issue statuses after reorder failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to list issue statuses")
+ return
+ }
+ if err := tx.Commit(r.Context()); err != nil {
+ slog.Warn("ReorderIssueStatuses commit failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to reorder issue statuses")
+ return
+ }
+
+ resp := make([]IssueStatusResponse, len(entries))
+ for i, e := range entries {
+ resp[i] = issueStatusToResponse(e)
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "statuses": resp,
+ "categories": issuestatus.Canonical(),
+ "total": len(resp),
+ })
+}
diff --git a/server/internal/handler/issue_status_reorder_test.go b/server/internal/handler/issue_status_reorder_test.go
new file mode 100644
index 0000000000..de1aa7a0ca
--- /dev/null
+++ b/server/internal/handler/issue_status_reorder_test.go
@@ -0,0 +1,251 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/issuestatus"
+)
+
+// insertCustomStatus adds one custom status directly, returning its id.
+func insertCustomStatus(t *testing.T, key, category string, position int, archived bool) string {
+ t.Helper()
+ var id string
+ archivedAt := "NULL"
+ if archived {
+ archivedAt = "now()"
+ }
+ err := testPool.QueryRow(context.Background(), fmt.Sprintf(`
+ INSERT INTO issue_status (workspace_id, key, name, description, category, color, position, archived_at)
+ VALUES ($1, $2, $3, '', $4, '#ff0000', $5, %s)
+ RETURNING id
+ `, archivedAt), testWorkspaceID, key, key, category, position).Scan(&id)
+ if err != nil {
+ t.Fatalf("insert custom status %q: %v", key, err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue_status WHERE id = $1`, id)
+ })
+ return id
+}
+
+func reorderVia(t *testing.T, category string, ids []string) *httptest.ResponseRecorder {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ testHandler.ReorderIssueStatuses(rec, newRequest(http.MethodPatch, "/api/issue-statuses/reorder", ReorderIssueStatusesRequest{
+ Category: category,
+ IDs: ids,
+ }))
+ return rec
+}
+
+func positionsByID(t *testing.T, ids ...string) map[string]int {
+ t.Helper()
+ out := make(map[string]int, len(ids))
+ for _, id := range ids {
+ var position int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT position FROM issue_status WHERE id = $1`, id).Scan(&position); err != nil {
+ t.Fatalf("read position for %s: %v", id, err)
+ }
+ out[id] = position
+ }
+ return out
+}
+
+func TestReorderIssueStatusesWritesIntraCategoryPositionsFromOne(t *testing.T) {
+ suffix := time.Now().UnixNano()
+ first := insertCustomStatus(t, fmt.Sprintf("qa_a_%d", suffix), "in_review", 1, false)
+ second := insertCustomStatus(t, fmt.Sprintf("qa_b_%d", suffix), "in_review", 2, false)
+
+ rec := reorderVia(t, "in_review", []string{second, first})
+ if rec.Code != http.StatusOK {
+ t.Fatalf("reorder status = %d: %s", rec.Code, rec.Body.String())
+ }
+
+ positions := positionsByID(t, first, second)
+ // Positions start at 1: the category's built-in is seeded at 0 and never
+ // moves, so it stays at the head of its column.
+ if positions[second] != 1 || positions[first] != 2 {
+ t.Fatalf("positions = %#v, want second=1 first=2", positions)
+ }
+
+ var response struct {
+ Statuses []IssueStatusResponse `json:"statuses"`
+ }
+ if err := json.NewDecoder(rec.Body).Decode(&response); err != nil {
+ t.Fatalf("decode reorder response: %v", err)
+ }
+ if len(response.Statuses) == 0 {
+ t.Fatal("reorder response carried no catalog")
+ }
+}
+
+// The regression Elon caught: with "show archived" on, the client used to hand
+// the whole rendered order — archived rows included — to a PATCH-per-row loop.
+// The archived row rejected AFTER the rows before it had already been written,
+// so the user saw a failure toast over a database that had partly reordered.
+func TestReorderIssueStatusesRejectsArchivedWithoutPartialWrite(t *testing.T) {
+ suffix := time.Now().UnixNano()
+ first := insertCustomStatus(t, fmt.Sprintf("qa_c_%d", suffix), "in_review", 1, false)
+ second := insertCustomStatus(t, fmt.Sprintf("qa_d_%d", suffix), "in_review", 2, false)
+ archived := insertCustomStatus(t, fmt.Sprintf("qa_e_%d", suffix), "in_review", 3, true)
+
+ before := positionsByID(t, first, second, archived)
+
+ rec := reorderVia(t, "in_review", []string{second, archived, first})
+ if rec.Code != http.StatusConflict {
+ t.Fatalf("reorder status = %d, want 409: %s", rec.Code, rec.Body.String())
+ }
+
+ after := positionsByID(t, first, second, archived)
+ for id, position := range before {
+ if after[id] != position {
+ t.Fatalf("position of %s moved from %d to %d despite the rejection: %#v",
+ id, position, after[id], after)
+ }
+ }
+}
+
+func TestReorderIssueStatusesRejectsForeignInputs(t *testing.T) {
+ suffix := time.Now().UnixNano()
+ inReview := insertCustomStatus(t, fmt.Sprintf("qa_f_%d", suffix), "in_review", 1, false)
+ inTodo := insertCustomStatus(t, fmt.Sprintf("qa_g_%d", suffix), "todo", 1, false)
+
+ // The built-ins are seeded lazily on the first catalog read.
+ if err := issuestatus.Ensure(context.Background(), testHandler.Queries, parseUUID(testWorkspaceID)); err != nil {
+ t.Fatalf("seed built-ins: %v", err)
+ }
+ var builtInID string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT id FROM issue_status WHERE workspace_id = $1 AND key = 'in_review' AND is_system`,
+ testWorkspaceID).Scan(&builtInID); err != nil {
+ t.Fatalf("load built-in: %v", err)
+ }
+
+ cases := []struct {
+ name string
+ category string
+ ids []string
+ want int
+ }{
+ {"a built-in cannot be reordered", "in_review", []string{builtInID}, http.StatusForbidden},
+ {"ids must belong to the named category", "in_review", []string{inReview, inTodo}, http.StatusBadRequest},
+ {"duplicate ids are rejected", "in_review", []string{inReview, inReview}, http.StatusBadRequest},
+ {"an empty order is rejected", "in_review", nil, http.StatusBadRequest},
+ {"the category must be one of the seven", "nope", []string{inReview}, http.StatusBadRequest},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if rec := reorderVia(t, tc.category, tc.ids); rec.Code != tc.want {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, tc.want, rec.Body.String())
+ }
+ })
+ }
+}
+
+// TestReorderIssueStatusesSerializesAgainstConcurrentArchive is the sharp
+// counterexample for "atomic".
+//
+// It reproduces the real interleaving rather than a sequential one: the reorder
+// must be IN FLIGHT and parked on the catalog lock when the archive commits.
+// A test that archives first and then calls reorder proves nothing — the
+// active-set check would catch that even with the lock deleted, because the
+// archive is already visible by the time the handler reads anything.
+//
+// Verified by deleting the LockIssueStatusCatalogShared call: the reorder then
+// reads the catalog before the archive commits, sees both rows active, and
+// commits a reorder that includes a row archived underneath it.
+func TestReorderIssueStatusesSerializesAgainstConcurrentArchive(t *testing.T) {
+ ctx := context.Background()
+ suffix := time.Now().UnixNano()
+ first := insertCustomStatus(t, fmt.Sprintf("qa_h_%d", suffix), "in_review", 1, false)
+ second := insertCustomStatus(t, fmt.Sprintf("qa_i_%d", suffix), "in_review", 2, false)
+
+ before := positionsByID(t, first, second)
+
+ // Hold the archive side first so the reorder is guaranteed to park on the
+ // lock BEFORE it reads the catalog.
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin: %v", err)
+ }
+ defer tx.Rollback(ctx)
+ if _, err := tx.Exec(ctx,
+ `SELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text || ':issue_status', 0))`,
+ parseUUID(testWorkspaceID)); err != nil {
+ t.Fatalf("take exclusive lock: %v", err)
+ }
+
+ done := make(chan int, 1)
+ go func() { done <- reorderVia(t, "in_review", []string{second, first}).Code }()
+
+ select {
+ case code := <-done:
+ t.Fatalf("reorder completed (%d) before the archive released the lock — it never took the shared lock", code)
+ case <-time.After(400 * time.Millisecond):
+ // Parked on the lock, as required.
+ }
+
+ // Archive inside the held lock and commit: from the reorder's point of view
+ // both rows were active when it was called, and one is archived by the time
+ // it can read anything.
+ if _, err := tx.Exec(ctx,
+ `UPDATE issue_status SET archived_at = now() WHERE id = $1`, second); err != nil {
+ t.Fatalf("archive inside the window: %v", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatalf("commit archive: %v", err)
+ }
+
+ select {
+ case code := <-done:
+ if code != http.StatusConflict {
+ t.Fatalf("reorder status = %d, want 409 against a status archived inside the race window", code)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("reorder never completed after the archive committed")
+ }
+
+ after := positionsByID(t, first, second)
+ for id, position := range before {
+ if after[id] != position {
+ t.Fatalf("position of %s moved from %d to %d despite the conflict: %#v",
+ id, position, after[id], after)
+ }
+ }
+}
+
+// A payload that names only SOME of a category's active custom statuses cannot
+// be applied: positions come from the array index, so reordering a subset
+// writes positions that collide with the rows left out of it.
+func TestReorderIssueStatusesRejectsAPartialSet(t *testing.T) {
+ suffix := time.Now().UnixNano()
+ first := insertCustomStatus(t, fmt.Sprintf("qa_j_%d", suffix), "in_review", 1, false)
+ second := insertCustomStatus(t, fmt.Sprintf("qa_k_%d", suffix), "in_review", 2, false)
+
+ before := positionsByID(t, first, second)
+
+ rec := reorderVia(t, "in_review", []string{second})
+ if rec.Code != http.StatusConflict {
+ t.Fatalf("reorder status = %d, want 409: %s", rec.Code, rec.Body.String())
+ }
+
+ after := positionsByID(t, first, second)
+ for id, position := range before {
+ if after[id] != position {
+ t.Fatalf("position of %s moved from %d to %d on a partial payload: %#v",
+ id, position, after[id], after)
+ }
+ }
+ // Specifically: `second` must NOT have been written to position 1, which is
+ // what would have collided with `first`.
+ if after[second] != before[second] {
+ t.Fatalf("partial payload still rewrote a position: %#v", after)
+ }
+}
diff --git a/server/internal/handler/issue_table_group.go b/server/internal/handler/issue_table_group.go
index c533fe305c..a844583623 100644
--- a/server/internal/handler/issue_table_group.go
+++ b/server/internal/handler/issue_table_group.go
@@ -8,11 +8,13 @@ import (
"fmt"
"log/slog"
"net/http"
+ "sort"
"strconv"
"strings"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/issuestatus"
"github.com/multica-ai/multica/server/internal/logger"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -67,6 +69,75 @@ type resolvedIssueTableGroup struct {
primary *resolvedIssueTableGroup
secondaryValues []string
secondaryFiltered bool
+ // secondaryCategory marks a compound whose secondary axis is the CATEGORY
+ // of the status rather than the status key itself — the swimlane contract.
+ secondaryCategory bool
+ // categoryKeys maps each of the 7 categories to the concrete status keys
+ // that belong to it, resolved ONCE per request. Category predicates expand
+ // through this into `i.status = ANY(...)` so the (workspace_id, status)
+ // index stays usable — see issuestatus.ExpandCategories. (MUL-6243)
+ categoryKeys map[string][]string
+ // statusCustomKeys is the CUSTOM key -> category map behind
+ // statusCategoryExpr. Empty for a workspace with no custom statuses.
+ statusCustomKeys map[string]string
+}
+
+// statusCategoryExpr builds the scalar `status key -> category` rewrite used as
+// a GROUP BY expression. Built-ins fall through the ELSE untouched because a
+// built-in key IS its own category, so a workspace with no custom statuses gets
+// exactly `i.status`. (MUL-6243)
+func statusCategoryExpr(customKeys map[string]string, addArg func(any) string) string {
+ if len(customKeys) == 0 {
+ return "i.status"
+ }
+ keys := make([]string, 0, len(customKeys))
+ for key := range customKeys {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ var b strings.Builder
+ b.WriteString("CASE i.status")
+ for _, key := range keys {
+ fmt.Fprintf(&b, " WHEN %s::text THEN %s::text", addArg(key), addArg(customKeys[key]))
+ }
+ b.WriteString(" ELSE i.status END")
+ return b.String()
+}
+
+// resolveStatusCategoryMaps derives BOTH shapes a category grouping needs from
+// ONE catalog read: the custom key -> category map behind the GROUP BY rewrite,
+// and the category -> concrete keys expansion that predicate() looks up (it has
+// no context or Querier of its own).
+//
+// One read, not three. A board loads seven column branches as seven separate
+// HTTP requests, so a per-call `ExpandCategories` + `CustomKeyCategories` pair
+// meant 21 extra catalog SELECTs behind one surface load.
+func (h *Handler) resolveStatusCategoryMaps(
+ ctx context.Context,
+ workspaceID pgtype.UUID,
+) (customKeys map[string]string, categoryKeys map[string][]string, err error) {
+ customKeys, err = issuestatus.CustomKeyCategories(ctx, h.issueStatusCatalog(), workspaceID)
+ if err != nil {
+ return nil, nil, err
+ }
+ categoryKeys = make(map[string][]string, len(validIssueStatuses))
+ for _, category := range validIssueStatuses {
+ // A category always contains at least its own canonical key, even on an
+ // unseeded workspace — a built-in key IS its own category.
+ categoryKeys[category] = []string{category}
+ }
+ // Sorted so the expansion — and therefore the query's argument list — is
+ // deterministic for the same catalog.
+ keys := make([]string, 0, len(customKeys))
+ for key := range customKeys {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ for _, key := range keys {
+ category := customKeys[key]
+ categoryKeys[category] = append(categoryKeys[category], key)
+ }
+ return customKeys, categoryKeys, nil
}
func issueTableGroupIdentity(group issueTableGroupSpec) string {
@@ -97,6 +168,21 @@ func (h *Handler) resolveIssueTableGroup(w http.ResponseWriter, r *http.Request,
return resolvedIssueTableGroup{kind: "none"}, true
case "status":
return resolvedIssueTableGroup{kind: "status", groupExpr: "i.status"}, true
+ case "status_category":
+ // Board / list / swimlane columns are CATEGORIES, so a custom status
+ // groups into the column it behaves as instead of getting a column of
+ // its own — that is what keeps the fan-out pinned at 7. (MUL-6243)
+ customKeys, categoryKeys, err := h.resolveStatusCategoryMaps(r.Context(), workspaceID)
+ if err != nil {
+ slog.Warn("resolve status category group failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to resolve table group")
+ return resolvedIssueTableGroup{}, false
+ }
+ return resolvedIssueTableGroup{
+ kind: "status_category",
+ categoryKeys: categoryKeys,
+ statusCustomKeys: customKeys,
+ }, true
case "assignee":
return resolvedIssueTableGroup{
kind: "assignee",
@@ -129,10 +215,11 @@ END, ''))`,
)) END`,
}, true
case "compound":
- if group.Secondary != "status" {
+ if group.Secondary != "status" && group.Secondary != "status_category" {
writeIssueTableUnsupportedGroup(w, "secondary_group_unsupported", "Only status is supported as a secondary group.")
return resolvedIssueTableGroup{}, false
}
+ secondaryCategory := group.Secondary == "status_category"
if group.Primary != "assignee" && group.Primary != "project" && group.Primary != "parent" {
writeIssueTableUnsupportedGroup(w, "primary_group_unsupported", "This primary group is not supported.")
return resolvedIssueTableGroup{}, false
@@ -153,12 +240,24 @@ END, ''))`,
if !ok {
return resolvedIssueTableGroup{}, false
}
- return resolvedIssueTableGroup{
+ resolved := resolvedIssueTableGroup{
kind: "compound",
primary: &primary,
secondaryValues: append([]string(nil), group.SecondaryValues...),
secondaryFiltered: group.SecondaryValues != nil,
- }, true
+ secondaryCategory: secondaryCategory,
+ }
+ if secondaryCategory {
+ customKeys, categoryKeys, err := h.resolveStatusCategoryMaps(r.Context(), workspaceID)
+ if err != nil {
+ slog.Warn("resolve compound status category group failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to resolve table group")
+ return resolvedIssueTableGroup{}, false
+ }
+ resolved.statusCustomKeys = customKeys
+ resolved.categoryKeys = categoryKeys
+ }
+ return resolved, true
case "property":
propertyUUID, err := util.ParseUUID(group.PropertyID)
if err != nil {
@@ -233,6 +332,9 @@ func (group resolvedIssueTableGroup) expression(addArg func(any) string) string
if group.kind == "compound" && group.primary != nil {
return group.primary.expression(addArg)
}
+ if group.kind == "status_category" {
+ return statusCategoryExpr(group.statusCustomKeys, addArg)
+ }
if group.kind == "property" && group.propertyType == "select" {
active := make([]string, 0, len(group.activeOptions))
for value := range group.activeOptions {
@@ -258,7 +360,7 @@ func (group resolvedIssueTableGroup) orderExpression(addArg func(any) string) st
return group.primary.orderExpression(addArg)
}
switch group.kind {
- case "status":
+ case "status", "status_category":
return "CASE group_value WHEN 'backlog' THEN 0 WHEN 'todo' THEN 1 WHEN 'in_progress' THEN 2 WHEN 'in_review' THEN 3 WHEN 'done' THEN 4 WHEN 'blocked' THEN 5 WHEN 'cancelled' THEN 6 ELSE 7 END"
case "assignee":
return "CASE split_part(group_value, ':', 1) WHEN 'member' THEN 0 WHEN 'agent' THEN 1 WHEN 'squad' THEN 2 ELSE 3 END"
@@ -298,8 +400,40 @@ func (group resolvedIssueTableGroup) contextExpression(addArg func(any) string,
), '{}'::jsonb) END`, prefixRef)
}
-func compoundCellGroupKey(primaryKey, status string) string {
- return "compound:" + base64.RawURLEncoding.EncodeToString([]byte(primaryKey)) + ":status:" + status
+const statusCategoryGroupKeyPrefix = "status_category:"
+
+func statusCategoryGroupKey(category string) string {
+ return statusCategoryGroupKeyPrefix + category
+}
+
+func parseStatusCategoryGroupKey(key string) (string, bool) {
+ if !strings.HasPrefix(key, statusCategoryGroupKeyPrefix) {
+ return "", false
+ }
+ category := strings.TrimPrefix(key, statusCategoryGroupKeyPrefix)
+ if !issueTableContainsString(validIssueStatuses, category) {
+ return "", false
+ }
+ return category, true
+}
+
+// categoryKeysFor returns the concrete status keys in a category. It falls back
+// to the category itself, which is always correct because a built-in key IS its
+// own category — so a catalog read that failed degrades to pre-feature behavior
+// instead of an empty result set.
+func (group resolvedIssueTableGroup) categoryKeysFor(category string) []string {
+ if keys := group.categoryKeys[category]; len(keys) > 0 {
+ return keys
+ }
+ return []string{category}
+}
+
+func compoundCellGroupKey(primaryKey, status string, category bool) string {
+ axis := ":status:"
+ if category {
+ axis = ":status_category:"
+ }
+ return "compound:" + base64.RawURLEncoding.EncodeToString([]byte(primaryKey)) + axis + status
}
func (group resolvedIssueTableGroup) descriptor(raw string, count int64, context issueTableGroupContext, secondaryCounts map[string]int64) (issueTableGroupDescriptorResponse, error) {
@@ -312,7 +446,7 @@ func (group resolvedIssueTableGroup) descriptor(raw string, count int64, context
for _, status := range validIssueStatuses {
statusCount := secondaryCounts[status]
descriptor.SecondaryGroups = append(descriptor.SecondaryGroups, issueTableGroupDescriptorResponse{
- Key: compoundCellGroupKey(descriptor.Key, status),
+ Key: compoundCellGroupKey(descriptor.Key, status, group.secondaryCategory),
Value: issueTableGroupValueResponse{
Kind: "status",
Status: status,
@@ -325,11 +459,25 @@ func (group resolvedIssueTableGroup) descriptor(raw string, count int64, context
descriptor := issueTableGroupDescriptorResponse{Count: count}
switch group.kind {
case "status":
- if !issueTableContainsString(validIssueStatuses, raw) {
+ // Any non-empty status KEY, not just the 7 built-ins. Since MUL-6243 a
+ // workspace can hold custom statuses, and rejecting one here failed the
+ // WHOLE grouped response with a 500 — one custom status made "group by
+ // status" unusable for the entire workspace.
+ if raw == "" {
return descriptor, fmt.Errorf("unexpected status group value %q", raw)
}
descriptor.Key = "status:" + raw
descriptor.Value = issueTableGroupValueResponse{Kind: "status", Status: raw}
+ case "status_category":
+ if !issueTableContainsString(validIssueStatuses, raw) {
+ return descriptor, fmt.Errorf("unexpected status category group value %q", raw)
+ }
+ descriptor.Key = statusCategoryGroupKey(raw)
+ // value.kind stays "status": a category's value IS its canonical status
+ // key, so this is exact rather than a compatibility shim, and every
+ // existing consumer of a status group keeps working. The KEY is what
+ // distinguishes the two contracts. (MUL-6243)
+ descriptor.Value = issueTableGroupValueResponse{Kind: "status", Status: raw}
case "assignee":
descriptor.Value.Kind = "assignee"
if raw == "__unassigned__" {
@@ -421,7 +569,11 @@ func (group resolvedIssueTableGroup) predicate(w http.ResponseWriter, key string
return "", false
}
encodedAndStatus := strings.TrimPrefix(key, prefix)
- encoded, status, ok := strings.Cut(encodedAndStatus, ":status:")
+ axis := ":status:"
+ if group.secondaryCategory {
+ axis = ":status_category:"
+ }
+ encoded, status, ok := strings.Cut(encodedAndStatus, axis)
if !ok || !issueTableContainsString(validIssueStatuses, status) {
writeError(w, http.StatusBadRequest, "invalid group_key")
return "", false
@@ -435,6 +587,9 @@ func (group resolvedIssueTableGroup) predicate(w http.ResponseWriter, key string
if !ok {
return "", false
}
+ if group.secondaryCategory {
+ return fmt.Sprintf("(%s) AND i.status = ANY(%s::text[])", primaryPredicate, addArg(group.categoryKeysFor(status))), true
+ }
return fmt.Sprintf("(%s) AND i.status = %s::text", primaryPredicate, addArg(status)), true
}
switch group.kind {
@@ -446,11 +601,25 @@ func (group resolvedIssueTableGroup) predicate(w http.ResponseWriter, key string
return "TRUE", true
case "status":
const prefix = "status:"
- if !strings.HasPrefix(key, prefix) || !issueTableContainsString(validIssueStatuses, strings.TrimPrefix(key, prefix)) {
+ status, found := strings.CutPrefix(key, prefix)
+ // A custom status is a valid group here too; the predicate is an exact
+ // key match either way. Length-bounded so an arbitrary blob cannot ride
+ // in as a status key.
+ if !found || status == "" || len(status) > 64 {
+ writeError(w, http.StatusBadRequest, "invalid group_key")
+ return "", false
+ }
+ return fmt.Sprintf("i.status = %s::text", addArg(status)), true
+ case "status_category":
+ category, ok := parseStatusCategoryGroupKey(key)
+ if !ok {
writeError(w, http.StatusBadRequest, "invalid group_key")
return "", false
}
- return fmt.Sprintf("i.status = %s::text", addArg(strings.TrimPrefix(key, prefix))), true
+ // Expanded to concrete keys rather than wrapping the column in a
+ // category function: `status = ANY(...)` keeps the (workspace_id,
+ // status) index, a function wrapper would force a workspace scan.
+ return fmt.Sprintf("i.status = ANY(%s::text[])", addArg(group.categoryKeysFor(category))), true
case "assignee":
const prefix = "assignee:"
if !strings.HasPrefix(key, prefix) {
@@ -660,8 +829,15 @@ func (h *Handler) ListIssueTableGroups(w http.ResponseWriter, r *http.Request) {
)`, groupExpr, compiled.where, expectedRef, expectedRef)
}
if group.kind == "compound" {
+ // The secondary axis is either the status key itself or the CATEGORY it
+ // behaves as. In the category case a custom status counts into the cell
+ // of the column it renders in, never a cell of its own. (MUL-6243)
+ secondaryExpr := "i.status"
+ if group.secondaryCategory {
+ secondaryExpr = statusCategoryExpr(group.statusCustomKeys, addArg)
+ }
groupedCTE = fmt.Sprintf(`cells AS (
- SELECT %s AS group_value, i.status AS secondary_value, COUNT(*)::bigint AS cell_count
+ SELECT %s AS group_value, %s AS secondary_value, COUNT(*)::bigint AS cell_count
FROM issue i
WHERE %s
GROUP BY 1, 2
@@ -672,9 +848,20 @@ func (h *Handler) ListIssueTableGroups(w http.ResponseWriter, r *http.Request) {
jsonb_object_agg(secondary_value, cell_count)::jsonb AS secondary_counts
FROM cells
GROUP BY group_value
-)`, groupExpr, compiled.where)
+)`, groupExpr, secondaryExpr, compiled.where)
if group.secondaryFiltered {
visibleRef := addArg(group.secondaryValues)
+ // promoted_parents matches raw `child.status`, so a category axis has
+ // to expand back to concrete keys there; the cell filters compare
+ // against secondary_value, which is already a category.
+ visibleKeysRef := visibleRef
+ if group.secondaryCategory {
+ expanded := make([]string, 0, len(group.secondaryValues))
+ for _, category := range group.secondaryValues {
+ expanded = append(expanded, group.categoryKeysFor(category)...)
+ }
+ visibleKeysRef = addArg(expanded)
+ }
headerPredicate := "TRUE"
promotedParentsCTE := ""
if group.primary != nil && group.primary.kind == "parent" {
@@ -687,14 +874,14 @@ func (h *Handler) ListIssueTableGroups(w http.ResponseWriter, r *http.Request) {
FROM membership child
WHERE child.parent_issue_id IS NOT NULL
AND child.status = ANY(%s::text[])
-)`, visibleRef)
+)`, visibleKeysRef)
}
groupedCTE = fmt.Sprintf(`membership AS NOT MATERIALIZED (
SELECT i.*
FROM issue i
WHERE %s
)%s, cells AS (
- SELECT %s AS group_value, i.status AS secondary_value,
+ SELECT %s AS group_value, %s AS secondary_value,
COUNT(*) FILTER (WHERE %s)::bigint AS cell_count
FROM membership i
GROUP BY 1, 2
@@ -712,7 +899,7 @@ func (h *Handler) ListIssueTableGroups(w http.ResponseWriter, r *http.Request) {
SUM(cell_count) FILTER (WHERE secondary_value = ANY(%s::text[])),
0
) > 0
-)`, compiled.where, promotedParentsCTE, groupExpr, headerPredicate, visibleRef, visibleRef)
+)`, compiled.where, promotedParentsCTE, groupExpr, secondaryExpr, headerPredicate, visibleRef, visibleRef)
}
}
query := fmt.Sprintf(`WITH %s, sorted AS (
@@ -814,3 +1001,12 @@ func (h *Handler) ListIssueTableGroups(w http.ResponseWriter, r *http.Request) {
committed = true
writeJSON(w, http.StatusOK, response)
}
+
+// issueStatusCatalog is the querier catalog reads go through. Defaults to
+// Queries; tests substitute a counting wrapper.
+func (h *Handler) issueStatusCatalog() issuestatus.Querier {
+ if h.IssueStatusCatalog != nil {
+ return h.IssueStatusCatalog
+ }
+ return h.Queries
+}
diff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.go
index 881d874ce5..8e5259892d 100644
--- a/server/internal/handler/issue_table_query.go
+++ b/server/internal/handler/issue_table_query.go
@@ -413,8 +413,14 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,
return "$" + strconv.Itoa(len(args))
}
+ // Any non-empty status KEY, not just the 7 built-ins. A status filter names
+ // the exact statuses the user picked, and since MUL-6243 those can be custom
+ // — rejecting them here 400'd the entire request, so filtering a board by a
+ // custom status errored the surface instead of narrowing it. The predicate
+ // below is a parameterized `status = ANY(...)`, so an unknown key simply
+ // matches nothing; length-bounded so an arbitrary blob cannot ride in.
for _, status := range spec.Filters.Statuses {
- if !issueTableContainsString(validIssueStatuses, status) {
+ if status == "" || len(status) > 64 {
writeError(w, http.StatusBadRequest, "invalid filters.statuses")
return issueTableSQL{}, false
}
diff --git a/server/internal/handler/issue_table_query_test.go b/server/internal/handler/issue_table_query_test.go
index 799846dcd2..3fbc6c2ef1 100644
--- a/server/internal/handler/issue_table_query_test.go
+++ b/server/internal/handler/issue_table_query_test.go
@@ -480,6 +480,7 @@ func TestIssueTableCompoundCellKeyResolvesPrimaryAndStatus(t *testing.T) {
key := compoundCellGroupKey(
"parent:00000000-0000-4000-8000-000000000001",
"todo",
+ false,
)
args := make([]any, 0, 2)
predicate, ok := compound.predicate(
diff --git a/server/internal/handler/issue_table_status_category_test.go b/server/internal/handler/issue_table_status_category_test.go
new file mode 100644
index 0000000000..462bc2c486
--- /dev/null
+++ b/server/internal/handler/issue_table_status_category_test.go
@@ -0,0 +1,513 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/issuestatus"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Board, list and swimlane columns are CATEGORIES, not status keys (MUL-6243).
+// These tests pin the server half of that contract: a custom status must land
+// in its category's column, count toward it, and be reachable through the
+// paginated row query — the exact path where the first cut of the UI dropped
+// every custom-status card on the floor.
+func seedStatusCategoryFixture(t *testing.T) (projectID, customKey string) {
+ t.Helper()
+ ctx := context.Background()
+ suffix := time.Now().UnixNano()
+ customKey = fmt.Sprintf("qa_%d", suffix)
+
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO project (workspace_id, title)
+ VALUES ($1, $2)
+ RETURNING id
+ `, testWorkspaceID, fmt.Sprintf("Status category %d", suffix)).Scan(&projectID); err != nil {
+ t.Fatalf("create project: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO issue_status (workspace_id, key, name, description, category, color, position)
+ VALUES ($1, $2, 'QA', '', 'in_review', '#ff0000', 1)
+ `, testWorkspaceID, customKey); err != nil {
+ t.Fatalf("create custom status: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE project_id = $1`, projectID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue_status WHERE workspace_id = $1 AND key = $2`, testWorkspaceID, customKey)
+ })
+
+ var firstNumber int
+ if err := testPool.QueryRow(ctx, `
+ UPDATE workspace
+ SET issue_counter = GREATEST(
+ issue_counter,
+ (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)
+ ) + 4
+ WHERE id = $1
+ RETURNING issue_counter - 3
+ `, testWorkspaceID).Scan(&firstNumber); err != nil {
+ t.Fatalf("reserve issue numbers: %v", err)
+ }
+ // Two on the custom status, one on the built-in it behaves as, one elsewhere.
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id, position, number, project_id)
+ VALUES
+ ($1, 'cat-a', $2, 'none', 'member', $3, 1, $4, $5),
+ ($1, 'cat-b', $2, 'none', 'member', $3, 2, $4 + 1, $5),
+ ($1, 'cat-c', 'in_review', 'none', 'member', $3, 3, $4 + 2, $5),
+ ($1, 'cat-d', 'todo', 'none', 'member', $3, 4, $4 + 3, $5)
+ `, testWorkspaceID, customKey, testUserID, firstNumber, projectID); err != nil {
+ t.Fatalf("seed issues: %v", err)
+ }
+ return projectID, customKey
+}
+
+func statusCategoryQuery(projectID string) issueTableQuerySpec {
+ return issueTableQuerySpec{
+ Scope: issueTableScope{Kind: "project", ProjectID: projectID},
+ Filters: issueTableFiltersRequest{},
+ Sort: issueTableSortRequest{Field: "title", Direction: "asc"},
+ }
+}
+
+func TestIssueTableStatusCategoryGroupsFoldCustomStatuses(t *testing.T) {
+ projectID, _ := seedStatusCategoryFixture(t)
+
+ w := httptest.NewRecorder()
+ testHandler.ListIssueTableGroups(w, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{
+ Query: statusCategoryQuery(projectID),
+ Group: issueTableGroupSpec{Kind: "status_category"},
+ Page: issueTablePageRequest{Limit: 100},
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("groups status = %d: %s", w.Code, w.Body.String())
+ }
+ var groups issueTableGroupsResponse
+ if err := json.NewDecoder(w.Body).Decode(&groups); err != nil {
+ t.Fatalf("decode groups: %v", err)
+ }
+
+ counts := map[string]int64{}
+ for _, group := range groups.Groups {
+ counts[group.Key] = group.Count
+ // A custom status must never surface a column of its own.
+ if group.Key != statusCategoryGroupKey(group.Value.Status) {
+ t.Fatalf("group %q is not a category column: %#v", group.Key, group.Value)
+ }
+ }
+ if got := counts[statusCategoryGroupKey("in_review")]; got != 3 {
+ t.Fatalf("in_review category count = %d, want 3 (2 custom + 1 built-in): %#v", got, counts)
+ }
+ if got := counts[statusCategoryGroupKey("todo")]; got != 1 {
+ t.Fatalf("todo category count = %d, want 1: %#v", got, counts)
+ }
+ if groups.Total != 4 {
+ t.Fatalf("total = %d, want 4", groups.Total)
+ }
+}
+
+func TestIssueTableStatusCategoryRowsReturnCustomStatusIssues(t *testing.T) {
+ projectID, customKey := seedStatusCategoryFixture(t)
+
+ groupKey := statusCategoryGroupKey("in_review")
+ w := httptest.NewRecorder()
+ testHandler.ListIssueTableRows(w, newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{
+ Query: statusCategoryQuery(projectID),
+ Group: issueTableGroupSpec{Kind: "status_category"},
+ GroupKey: &groupKey,
+ Page: issueTablePageRequest{Limit: 50},
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("rows status = %d: %s", w.Code, w.Body.String())
+ }
+ var rows issueTableRowsResponse
+ if err := json.NewDecoder(w.Body).Decode(&rows); err != nil {
+ t.Fatalf("decode rows: %v", err)
+ }
+
+ byStatus := map[string]int{}
+ for _, row := range rows.Rows {
+ byStatus[row.Issue.Status]++
+ }
+ // The regression: paging the in_review column by concrete key returned only
+ // the built-in row, so both QA cards vanished from the board.
+ if byStatus[customKey] != 2 {
+ t.Fatalf("custom-status rows = %d, want 2: %#v", byStatus[customKey], byStatus)
+ }
+ if byStatus["in_review"] != 1 {
+ t.Fatalf("built-in rows = %d, want 1: %#v", byStatus["in_review"], byStatus)
+ }
+ if len(rows.Rows) != 3 {
+ t.Fatalf("rows = %d, want 3", len(rows.Rows))
+ }
+ // Every row carries its category, so the client can render the column
+ // without a second catalog round-trip.
+ for _, row := range rows.Rows {
+ if row.Issue.StatusCategory != "in_review" {
+ t.Fatalf("row %q status_category = %q, want in_review", row.Issue.Title, row.Issue.StatusCategory)
+ }
+ }
+}
+
+func TestIssueTableCompoundStatusCategoryCellsFoldCustomStatuses(t *testing.T) {
+ projectID, customKey := seedStatusCategoryFixture(t)
+
+ w := httptest.NewRecorder()
+ testHandler.ListIssueTableGroups(w, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{
+ Query: statusCategoryQuery(projectID),
+ Group: issueTableGroupSpec{
+ Kind: "compound",
+ Primary: "project",
+ Secondary: "status_category",
+ },
+ Page: issueTablePageRequest{Limit: 100},
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("groups status = %d: %s", w.Code, w.Body.String())
+ }
+ var groups issueTableGroupsResponse
+ if err := json.NewDecoder(w.Body).Decode(&groups); err != nil {
+ t.Fatalf("decode groups: %v", err)
+ }
+ if len(groups.Groups) != 1 {
+ t.Fatalf("groups = %d, want 1 project lane", len(groups.Groups))
+ }
+
+ cells := map[string]int64{}
+ for _, cell := range groups.Groups[0].SecondaryGroups {
+ cells[cell.Value.Status] = cell.Count
+ }
+ // Swimlane cells are categories too: 2 QA + 1 In Review in one cell, and no
+ // cell keyed by the custom status.
+ if cells["in_review"] != 3 {
+ t.Fatalf("in_review cell = %d, want 3: %#v", cells["in_review"], cells)
+ }
+ if _, exists := cells[customKey]; exists {
+ t.Fatalf("custom status got its own swimlane cell: %#v", cells)
+ }
+
+ // And the cell's own group_key has to page back the same three rows.
+ cellKey := compoundCellGroupKey(groups.Groups[0].Key, "in_review", true)
+ rowsRecorder := httptest.NewRecorder()
+ testHandler.ListIssueTableRows(rowsRecorder, newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{
+ Query: statusCategoryQuery(projectID),
+ Group: issueTableGroupSpec{
+ Kind: "compound",
+ Primary: "project",
+ Secondary: "status_category",
+ },
+ GroupKey: &cellKey,
+ Page: issueTablePageRequest{Limit: 50},
+ }))
+ if rowsRecorder.Code != http.StatusOK {
+ t.Fatalf("cell rows status = %d: %s", rowsRecorder.Code, rowsRecorder.Body.String())
+ }
+ var cellRows issueTableRowsResponse
+ if err := json.NewDecoder(rowsRecorder.Body).Decode(&cellRows); err != nil {
+ t.Fatalf("decode cell rows: %v", err)
+ }
+ if len(cellRows.Rows) != 3 {
+ t.Fatalf("cell rows = %d, want 3", len(cellRows.Rows))
+ }
+}
+
+// A workspace with no custom statuses must produce byte-identical grouping to
+// the plain status contract — that is what makes this safe to ship default-on.
+func TestIssueTableStatusCategoryMatchesStatusWithoutCustomStatuses(t *testing.T) {
+ ctx := context.Background()
+ suffix := time.Now().UnixNano()
+ var projectID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO project (workspace_id, title) VALUES ($1, $2) RETURNING id
+ `, testWorkspaceID, fmt.Sprintf("Status category parity %d", suffix)).Scan(&projectID); err != nil {
+ t.Fatalf("create project: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE project_id = $1`, projectID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID)
+ })
+ var firstNumber int
+ if err := testPool.QueryRow(ctx, `
+ UPDATE workspace
+ SET issue_counter = GREATEST(issue_counter, (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)) + 2
+ WHERE id = $1
+ RETURNING issue_counter - 1
+ `, testWorkspaceID).Scan(&firstNumber); err != nil {
+ t.Fatalf("reserve issue numbers: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id, position, number, project_id)
+ VALUES ($1, 'parity-a', 'todo', 'none', 'member', $2, 1, $3, $4),
+ ($1, 'parity-b', 'done', 'none', 'member', $2, 2, $3 + 1, $4)
+ `, testWorkspaceID, testUserID, firstNumber, projectID); err != nil {
+ t.Fatalf("seed issues: %v", err)
+ }
+
+ collect := func(kind string) map[string]int64 {
+ t.Helper()
+ w := httptest.NewRecorder()
+ testHandler.ListIssueTableGroups(w, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{
+ Query: statusCategoryQuery(projectID),
+ Group: issueTableGroupSpec{Kind: kind},
+ Page: issueTablePageRequest{Limit: 100},
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("%s groups status = %d: %s", kind, w.Code, w.Body.String())
+ }
+ var groups issueTableGroupsResponse
+ if err := json.NewDecoder(w.Body).Decode(&groups); err != nil {
+ t.Fatalf("decode %s groups: %v", kind, err)
+ }
+ out := map[string]int64{}
+ for _, group := range groups.Groups {
+ out[group.Value.Status] = group.Count
+ }
+ return out
+ }
+
+ byStatus := collect("status")
+ byCategory := collect("status_category")
+ if len(byStatus) != len(byCategory) {
+ t.Fatalf("group counts differ: status=%#v category=%#v", byStatus, byCategory)
+ }
+ for status, count := range byStatus {
+ if byCategory[status] != count {
+ t.Fatalf("group %q: status=%d category=%d", status, count, byCategory[status])
+ }
+ }
+}
+
+// countingCatalogQuerier wraps the real querier and counts catalog reads. This
+// is the injection point the read-count assertions use: it is deterministic,
+// unlike pg_stat_user_tables, whose counters are flushed asynchronously and so
+// can report zero for a request that really did query — which is exactly why
+// the previous `delta <= 1` assertion was vacuous.
+type countingCatalogQuerier struct {
+ issuestatus.Querier
+ entryReads int
+ categoryReads int
+}
+
+func (c *countingCatalogQuerier) ListIssueStatusEntries(
+ ctx context.Context, arg db.ListIssueStatusEntriesParams,
+) ([]db.IssueStatus, error) {
+ c.entryReads++
+ return c.Querier.ListIssueStatusEntries(ctx, arg)
+}
+
+func (c *countingCatalogQuerier) ListIssueStatusKeysByCategories(
+ ctx context.Context, arg db.ListIssueStatusKeysByCategoriesParams,
+) ([]string, error) {
+ c.categoryReads++
+ return c.Querier.ListIssueStatusKeysByCategories(ctx, arg)
+}
+
+// withCountingCatalog installs the counter for the duration of a test.
+func withCountingCatalog(t *testing.T) *countingCatalogQuerier {
+ t.Helper()
+ counter := &countingCatalogQuerier{Querier: testHandler.Queries}
+ previous := testHandler.IssueStatusCatalog
+ testHandler.IssueStatusCatalog = counter
+ t.Cleanup(func() { testHandler.IssueStatusCatalog = previous })
+ return counter
+}
+
+// A board loads seven column branches as seven separate HTTP requests, so a
+// catalog read that looks cheap per request is multiplied by seven. The first
+// cut ran ExpandCategories AND CustomKeyCategories per resolve — two reads
+// where one suffices, i.e. 14 catalog reads behind one board load instead of 7.
+func TestIssueTableStatusCategoryReadsCatalogOncePerRequest(t *testing.T) {
+ projectID, _ := seedStatusCategoryFixture(t)
+ counter := withCountingCatalog(t)
+
+ w := httptest.NewRecorder()
+ testHandler.ListIssueTableGroups(w, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{
+ Query: statusCategoryQuery(projectID),
+ Group: issueTableGroupSpec{Kind: "status_category"},
+ Page: issueTablePageRequest{Limit: 100},
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("groups status = %d: %s", w.Code, w.Body.String())
+ }
+
+ // Exactly one, not "at most one": a zero would mean the counter never saw
+ // the request and the assertion proved nothing.
+ if counter.entryReads != 1 {
+ t.Fatalf("catalog entry reads = %d, want exactly 1", counter.entryReads)
+ }
+ // Both maps are derived from that single read; the category expansion must
+ // not issue a second query of its own.
+ if counter.categoryReads != 0 {
+ t.Fatalf("category-expansion reads = %d, want 0 (derived from the entry read)", counter.categoryReads)
+ }
+}
+
+func TestIssueTableCompoundStatusCategoryReadsCatalogOncePerRequest(t *testing.T) {
+ projectID, _ := seedStatusCategoryFixture(t)
+ counter := withCountingCatalog(t)
+
+ w := httptest.NewRecorder()
+ testHandler.ListIssueTableGroups(w, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{
+ Query: statusCategoryQuery(projectID),
+ Group: issueTableGroupSpec{
+ Kind: "compound",
+ Primary: "project",
+ Secondary: "status_category",
+ },
+ Page: issueTablePageRequest{Limit: 100},
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("groups status = %d: %s", w.Code, w.Body.String())
+ }
+ if counter.entryReads != 1 {
+ t.Fatalf("catalog entry reads = %d, want exactly 1", counter.entryReads)
+ }
+ if counter.categoryReads != 0 {
+ t.Fatalf("category-expansion reads = %d, want 0", counter.categoryReads)
+ }
+}
+
+// The common case: no custom statuses means the client never asks for the
+// category contract, so a default board pays nothing for this feature. This
+// pins the SERVER half — plain `status` grouping reads no catalog at all.
+func TestIssueTableStatusGroupingReadsNoCatalog(t *testing.T) {
+ projectID, _ := seedStatusCategoryFixture(t)
+ counter := withCountingCatalog(t)
+
+ w := httptest.NewRecorder()
+ testHandler.ListIssueTableGroups(w, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{
+ Query: statusCategoryQuery(projectID),
+ Group: issueTableGroupSpec{Kind: "status"},
+ Page: issueTablePageRequest{Limit: 100},
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("groups status = %d: %s", w.Code, w.Body.String())
+ }
+ if counter.entryReads != 0 || counter.categoryReads != 0 {
+ t.Fatalf("plain status grouping read the catalog (%d entry, %d category), want 0",
+ counter.entryReads, counter.categoryReads)
+ }
+}
+
+// Plain `status` grouping — what the Table view uses, and what every client
+// falls back to before its catalog lands — must survive a workspace that has
+// custom statuses. The descriptor used to reject any non-built-in raw value,
+// which failed the WHOLE grouped response: one custom status made "group by
+// status" 500 for the entire workspace.
+func TestIssueTableStatusGroupingCarriesCustomStatusGroups(t *testing.T) {
+ projectID, customKey := seedStatusCategoryFixture(t)
+
+ w := httptest.NewRecorder()
+ testHandler.ListIssueTableGroups(w, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{
+ Query: statusCategoryQuery(projectID),
+ Group: issueTableGroupSpec{Kind: "status"},
+ Page: issueTablePageRequest{Limit: 100},
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("groups status = %d: %s", w.Code, w.Body.String())
+ }
+ var groups issueTableGroupsResponse
+ if err := json.NewDecoder(w.Body).Decode(&groups); err != nil {
+ t.Fatalf("decode groups: %v", err)
+ }
+
+ counts := map[string]int64{}
+ for _, group := range groups.Groups {
+ counts[group.Value.Status] = group.Count
+ }
+ if counts[customKey] != 2 {
+ t.Fatalf("custom status group = %d, want 2: %#v", counts[customKey], counts)
+ }
+ if counts["in_review"] != 1 {
+ t.Fatalf("built-in group = %d, want 1: %#v", counts["in_review"], counts)
+ }
+
+ // And its group_key has to page back its own rows.
+ groupKey := "status:" + customKey
+ rowsRecorder := httptest.NewRecorder()
+ testHandler.ListIssueTableRows(rowsRecorder, newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{
+ Query: statusCategoryQuery(projectID),
+ Group: issueTableGroupSpec{Kind: "status"},
+ GroupKey: &groupKey,
+ Page: issueTablePageRequest{Limit: 50},
+ }))
+ if rowsRecorder.Code != http.StatusOK {
+ t.Fatalf("rows status = %d: %s", rowsRecorder.Code, rowsRecorder.Body.String())
+ }
+ var rows issueTableRowsResponse
+ if err := json.NewDecoder(rowsRecorder.Body).Decode(&rows); err != nil {
+ t.Fatalf("decode rows: %v", err)
+ }
+ if len(rows.Rows) != 2 {
+ t.Fatalf("custom status rows = %d, want 2", len(rows.Rows))
+ }
+}
+
+// The surface sends the user's EXACT status keys in `filters.statuses` — that
+// is what "filter by QA" means, and it is the whole point of a custom status.
+// Validating that list against the 7 built-ins 400s the entire request, so the
+// board, list and table all error out instead of filtering.
+func TestIssueTableFiltersAcceptCustomStatusKeys(t *testing.T) {
+ projectID, customKey := seedStatusCategoryFixture(t)
+
+ query := statusCategoryQuery(projectID)
+ query.Filters = issueTableFiltersRequest{Statuses: []string{customKey}}
+
+ w := httptest.NewRecorder()
+ testHandler.ListIssueTableGroups(w, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{
+ Query: query,
+ Group: issueTableGroupSpec{Kind: "status_category"},
+ Page: issueTablePageRequest{Limit: 100},
+ }))
+ if w.Code != http.StatusOK {
+ t.Fatalf("groups status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ var groups issueTableGroupsResponse
+ if err := json.NewDecoder(w.Body).Decode(&groups); err != nil {
+ t.Fatalf("decode groups: %v", err)
+ }
+ if groups.Total != 2 {
+ t.Fatalf("total = %d, want 2 (only the QA rows)", groups.Total)
+ }
+
+ groupKey := statusCategoryGroupKey("in_review")
+ rowsRecorder := httptest.NewRecorder()
+ testHandler.ListIssueTableRows(rowsRecorder, newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{
+ Query: query,
+ Group: issueTableGroupSpec{Kind: "status_category"},
+ GroupKey: &groupKey,
+ Page: issueTablePageRequest{Limit: 50},
+ }))
+ if rowsRecorder.Code != http.StatusOK {
+ t.Fatalf("rows status = %d, want 200: %s", rowsRecorder.Code, rowsRecorder.Body.String())
+ }
+ var rows issueTableRowsResponse
+ if err := json.NewDecoder(rowsRecorder.Body).Decode(&rows); err != nil {
+ t.Fatalf("decode rows: %v", err)
+ }
+ // The in_review column holds 3 issues, but only the 2 on `qa` match the filter.
+ if len(rows.Rows) != 2 {
+ t.Fatalf("rows = %d, want 2", len(rows.Rows))
+ }
+ for _, row := range rows.Rows {
+ if row.Issue.Status != customKey {
+ t.Fatalf("row %q status = %q, want %q", row.Issue.Title, row.Issue.Status, customKey)
+ }
+ }
+
+ facetsRecorder := httptest.NewRecorder()
+ testHandler.ListIssueTableFacets(facetsRecorder, newRequest(http.MethodPost, "/api/issues/table/facets", issueTableFacetsRequest{
+ Query: query,
+ Facets: []issueTableFacetSpec{{Kind: "status"}},
+ }))
+ if facetsRecorder.Code != http.StatusOK {
+ t.Fatalf("facets status = %d, want 200: %s", facetsRecorder.Code, facetsRecorder.Body.String())
+ }
+}
diff --git a/server/internal/issuestatus/issuestatus.go b/server/internal/issuestatus/issuestatus.go
index a3c0c3673d..ba3c465157 100644
--- a/server/internal/issuestatus/issuestatus.go
+++ b/server/internal/issuestatus/issuestatus.go
@@ -370,3 +370,34 @@ func ExpandCategories(ctx context.Context, q Querier, workspaceID pgtype.UUID, c
}
return out, nil
}
+
+// CustomKeyCategories returns the workspace's CUSTOM status keys mapped to the
+// category each belongs to. Built-ins are deliberately absent: a built-in key IS
+// its own category, so a caller mapping key -> category only needs the
+// exceptions.
+//
+// Callers use this to build a static `CASE i.status WHEN ... ELSE i.status END`
+// scalar expression for GROUP BY. That keeps category grouping a plain column
+// rewrite rather than a per-row function call or a join, and for a workspace
+// with no custom statuses the map is empty and the CASE collapses to `i.status`
+// — byte-for-byte the expression that ran before this feature.
+//
+// Archived statuses are included, for the same reason ExpandCategories includes
+// them: issues left on one must still group into their category.
+func CustomKeyCategories(ctx context.Context, q Querier, workspaceID pgtype.UUID) (map[string]string, error) {
+ entries, err := q.ListIssueStatusEntries(ctx, db.ListIssueStatusEntriesParams{
+ WorkspaceID: workspaceID,
+ IncludeArchived: true,
+ })
+ if err != nil {
+ return nil, err
+ }
+ out := make(map[string]string, len(entries))
+ for _, e := range entries {
+ if IsBuiltIn(e.Key) || !IsCategory(e.Category) {
+ continue
+ }
+ out[e.Key] = e.Category
+ }
+ return out, nil
+}
diff --git a/server/pkg/db/generated/issue_status.sql.go b/server/pkg/db/generated/issue_status.sql.go
index 254224591f..3e1c9c4d27 100644
--- a/server/pkg/db/generated/issue_status.sql.go
+++ b/server/pkg/db/generated/issue_status.sql.go
@@ -203,6 +203,56 @@ func (q *Queries) GetIssueStatusEntryByKey(ctx context.Context, arg GetIssueStat
return i, err
}
+const listActiveCustomIssueStatusEntries = `-- name: ListActiveCustomIssueStatusEntries :many
+SELECT id, workspace_id, key, name, description, category, color, is_system, position, archived_at, created_at, updated_at FROM issue_status
+WHERE workspace_id = $1::uuid
+ AND category = $2::text
+ AND is_system = FALSE
+ AND archived_at IS NULL
+ORDER BY position, key
+`
+
+type ListActiveCustomIssueStatusEntriesParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Category string `json:"category"`
+}
+
+// One category's ACTIVE custom statuses — the exact set a reorder must cover.
+// Read inside the reorder transaction, under the catalog lock, so a status
+// archived concurrently cannot slip in or out between validation and write.
+func (q *Queries) ListActiveCustomIssueStatusEntries(ctx context.Context, arg ListActiveCustomIssueStatusEntriesParams) ([]IssueStatus, error) {
+ rows, err := q.db.Query(ctx, listActiveCustomIssueStatusEntries, arg.WorkspaceID, arg.Category)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []IssueStatus{}
+ for rows.Next() {
+ var i IssueStatus
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Key,
+ &i.Name,
+ &i.Description,
+ &i.Category,
+ &i.Color,
+ &i.IsSystem,
+ &i.Position,
+ &i.ArchivedAt,
+ &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 listIssueStatusEntries = `-- name: ListIssueStatusEntries :many
SELECT id, workspace_id, key, name, description, category, color, is_system, position, archived_at, created_at, updated_at FROM issue_status
WHERE workspace_id = $1::uuid
@@ -331,6 +381,38 @@ func (q *Queries) LockIssueStatusCatalogShared(ctx context.Context, workspaceID
return err
}
+const reorderIssueStatusEntries = `-- name: ReorderIssueStatusEntries :execrows
+UPDATE issue_status s
+SET position = v.ordinality::int,
+ updated_at = now()
+FROM unnest($2::uuid[]) WITH ORDINALITY AS v(id, ordinality)
+WHERE s.id = v.id
+ AND s.workspace_id = $1::uuid
+ AND s.is_system = FALSE
+ AND s.archived_at IS NULL
+`
+
+type ReorderIssueStatusEntriesParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Ids []pgtype.UUID `json:"ids"`
+}
+
+// Atomic intra-category reorder. One statement, so a failure leaves the whole
+// order untouched instead of the partially-applied prefix a per-row PATCH loop
+// produces.
+//
+// Positions start at 1 because the category's built-in is seeded at 0 and can
+// never move (is_system rows are excluded here, as they are in every write).
+// Archived rows are excluded too: they are frozen, and letting one into the
+// write sequence is exactly what made a drag past an archived row half-commit.
+func (q *Queries) ReorderIssueStatusEntries(ctx context.Context, arg ReorderIssueStatusEntriesParams) (int64, error) {
+ result, err := q.db.Exec(ctx, reorderIssueStatusEntries, arg.WorkspaceID, arg.Ids)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const seedIssueStatusEntries = `-- name: SeedIssueStatusEntries :exec
INSERT INTO issue_status (workspace_id, key, name, description, category, color, is_system, position)
diff --git a/server/pkg/db/queries/issue_status.sql b/server/pkg/db/queries/issue_status.sql
index 5412ddff16..21d6087e96 100644
--- a/server/pkg/db/queries/issue_status.sql
+++ b/server/pkg/db/queries/issue_status.sql
@@ -143,3 +143,32 @@ SELECT pg_advisory_xact_lock_shared(hashtextextended(sqlc.arg('workspace_id')::u
SELECT key FROM issue_status
WHERE workspace_id = sqlc.arg('workspace_id')::uuid
AND category = ANY(sqlc.arg('categories')::text[]);
+
+-- name: ListActiveCustomIssueStatusEntries :many
+-- One category's ACTIVE custom statuses — the exact set a reorder must cover.
+-- Read inside the reorder transaction, under the catalog lock, so a status
+-- archived concurrently cannot slip in or out between validation and write.
+SELECT * FROM issue_status
+WHERE workspace_id = sqlc.arg('workspace_id')::uuid
+ AND category = sqlc.arg('category')::text
+ AND is_system = FALSE
+ AND archived_at IS NULL
+ORDER BY position, key;
+
+-- name: ReorderIssueStatusEntries :execrows
+-- Atomic intra-category reorder. One statement, so a failure leaves the whole
+-- order untouched instead of the partially-applied prefix a per-row PATCH loop
+-- produces.
+--
+-- Positions start at 1 because the category's built-in is seeded at 0 and can
+-- never move (is_system rows are excluded here, as they are in every write).
+-- Archived rows are excluded too: they are frozen, and letting one into the
+-- write sequence is exactly what made a drag past an archived row half-commit.
+UPDATE issue_status s
+SET position = v.ordinality::int,
+ updated_at = now()
+FROM unnest(sqlc.arg('ids')::uuid[]) WITH ORDINALITY AS v(id, ordinality)
+WHERE s.id = v.id
+ AND s.workspace_id = sqlc.arg('workspace_id')::uuid
+ AND s.is_system = FALSE
+ AND s.archived_at IS NULL;