Skip to content

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

Go

feat(issues): simplify board defaults and sorting (#8256)

Jiayuan Zhang3dcfdaea412c
diff --git a/apps/mobile/lib/issue-status.test.ts b/apps/mobile/lib/issue-status.test.ts
index f23c6ae60b..021b30df02 100644
--- a/apps/mobile/lib/issue-status.test.ts
+++ b/apps/mobile/lib/issue-status.test.ts
@@ -158,8 +158,8 @@ describe("statusOptions", () => {
"todo",
"in_progress",
"in_review",
- "done",
"blocked",
+ "done",
"cancelled",
]);
expect(options.every((o) => o.color === null)).toBe(true);
diff --git a/apps/mobile/lib/issue-status.ts b/apps/mobile/lib/issue-status.ts
index 48aaa29929..0fb63f06f0 100644
--- a/apps/mobile/lib/issue-status.ts
+++ b/apps/mobile/lib/issue-status.ts
@@ -33,8 +33,8 @@ export const STATUS_CATEGORIES: IssueStatusCategory[] = [
"todo",
"in_progress",
"in_review",
- "done",
"blocked",
+ "done",
"cancelled",
];
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 8ed605826e..ea8f025052 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -2071,7 +2071,7 @@ describe("issue status catalog schemas", () => {
it("parses a full catalog response", () => {
const parsed = ListIssueStatusesResponseSchema.parse({
statuses: [baseStatus],
- categories: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],
+ categories: ["backlog", "todo", "in_progress", "in_review", "blocked", "done", "cancelled"],
total: 1,
});
expect(parsed.statuses[0]?.key).toBe("human_review");
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 2df1fbc617..9c47e6f6f8 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -516,7 +516,7 @@ export const ListIssueStatusesResponseSchema = z.object({
// to a server that predates this endpoint still has the canonical list.
export const EMPTY_LIST_ISSUE_STATUSES_RESPONSE: ListIssueStatusesResponse = {
statuses: [],
- categories: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],
+ categories: ["backlog", "todo", "in_progress", "in_review", "blocked", "done", "cancelled"],
total: 0,
};
diff --git a/packages/core/issues/config/status.ts b/packages/core/issues/config/status.ts
index 40addeee7c..2cec46ea2a 100644
--- a/packages/core/issues/config/status.ts
+++ b/packages/core/issues/config/status.ts
@@ -12,8 +12,8 @@ export const STATUS_ORDER: IssueStatusCategory[] = [
"todo",
"in_progress",
"in_review",
- "done",
"blocked",
+ "done",
"cancelled",
];
@@ -22,8 +22,8 @@ export const ALL_STATUSES: IssueStatusCategory[] = [
"todo",
"in_progress",
"in_review",
- "done",
"blocked",
+ "done",
"cancelled",
];
diff --git a/packages/core/issues/index.ts b/packages/core/issues/index.ts
index 60979f3e78..5fb1d09f06 100644
--- a/packages/core/issues/index.ts
+++ b/packages/core/issues/index.ts
@@ -14,6 +14,7 @@ export {
issueStatusCategory,
statusCategoryOfKey,
statusFilterColumns,
+ visibleStatusCategories,
type StatusFilterColumnsResult,
normalizeStatusPatch,
} from "./status-category";
diff --git a/packages/core/issues/status-behavior.test.ts b/packages/core/issues/status-behavior.test.ts
index 7fbf7d21a8..4f9d72aab2 100644
--- a/packages/core/issues/status-behavior.test.ts
+++ b/packages/core/issues/status-behavior.test.ts
@@ -7,6 +7,7 @@ import {
issueBehavesAsAny,
issueColumnCategory,
statusFilterColumns,
+ visibleStatusCategories,
} from "./status-category";
function issue(status: string, statusCategory?: string): Pick<Issue, "status" | "status_category"> {
@@ -151,6 +152,31 @@ describe("statusFilterColumns", () => {
});
});
+describe("visibleStatusCategories", () => {
+ const loaded = buildIssueStatusCatalog([
+ entry("in_review", "in_review", true),
+ entry("qa", "in_review"),
+ ]);
+
+ it("uses hidden preferences when there is no explicit status filter", () => {
+ expect(visibleStatusCategories([], ["cancelled"], loaded)).not.toContain(
+ "cancelled",
+ );
+ });
+
+ it("lets an explicit filter restore a hidden category", () => {
+ expect(visibleStatusCategories(["cancelled"], ["cancelled"], loaded)).toEqual([
+ "cancelled",
+ ]);
+ });
+
+ it("maps a custom filter to its category", () => {
+ expect(visibleStatusCategories(["qa"], ["in_review"], loaded)).toEqual([
+ "in_review",
+ ]);
+ });
+});
+
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
diff --git a/packages/core/issues/status-category.ts b/packages/core/issues/status-category.ts
index eb26f491b7..676be3eff2 100644
--- a/packages/core/issues/status-category.ts
+++ b/packages/core/issues/status-category.ts
@@ -134,6 +134,27 @@ export function statusFilterColumns(
return { state: "resolved", columns };
}
+/**
+ * Resolve the category columns a surface may display. An explicit status
+ * filter wins over hidden-column preferences so selecting a hidden status
+ * always provides a recovery path. Pending/error custom-status resolution is
+ * handled by the caller's loading/error state, so it does not narrow here.
+ */
+export function visibleStatusCategories(
+ statusFilters: readonly string[],
+ hiddenCategories: readonly IssueStatusCategory[],
+ catalog: Pick<IssueStatusCatalog, "entryOf" | "isLoaded" | "isPending" | "isError">,
+): IssueStatusCategory[] {
+ const resolved =
+ statusFilters.length > 0 ? statusFilterColumns(statusFilters, catalog) : null;
+ const selected = resolved?.state === "resolved" ? resolved.columns : null;
+ return ALL_STATUSES.filter((category) =>
+ selected !== null
+ ? selected.has(category)
+ : !hiddenCategories.includes(category),
+ );
+}
+
/**
* Whether an issue BEHAVES as a given category (MUL-6243).
*
diff --git a/packages/core/issues/stores/surface-view-store.test.tsx b/packages/core/issues/stores/surface-view-store.test.tsx
index 73aea89900..41eb1bcc49 100644
--- a/packages/core/issues/stores/surface-view-store.test.tsx
+++ b/packages/core/issues/stores/surface-view-store.test.tsx
@@ -59,6 +59,75 @@ afterEach(async () => {
});
describe("issue surface view store registry", () => {
+ it("migrates legacy defaults without rewriting explicit preferences", async () => {
+ localStorage.setItem(
+ `${ISSUE_SURFACE_VIEW_STORAGE_KEY}:acme`,
+ JSON.stringify({
+ version: 0,
+ state: {
+ surfaces: {
+ "workspace:legacy": {
+ state: {
+ sortBy: "position",
+ sortDirection: "asc",
+ cardProperties: {
+ priority: true,
+ description: true,
+ assignee: true,
+ startDate: true,
+ dueDate: true,
+ project: true,
+ childProgress: true,
+ labels: true,
+ },
+ hiddenStatusCategories: [],
+ },
+ updatedAt: "2026-01-01T00:00:00Z",
+ },
+ "workspace:custom": {
+ state: {
+ sortBy: "title",
+ sortDirection: "desc",
+ cardProperties: { description: false },
+ hiddenStatusCategories: ["done"],
+ },
+ updatedAt: "2026-01-01T00:00:00Z",
+ },
+ },
+ },
+ }),
+ );
+ setCurrentWorkspace("acme", "ws_a");
+ await flush();
+
+ const legacy = getIssueSurfaceViewStore("workspace:legacy").getState();
+ expect([legacy.sortBy, legacy.sortDirection]).toEqual([
+ "created_at",
+ "desc",
+ ]);
+ expect(legacy.cardProperties.description).toBe(false);
+ expect(legacy.hiddenStatusCategories).toEqual(["cancelled"]);
+
+ const custom = getIssueSurfaceViewStore("workspace:custom").getState();
+ expect([custom.sortBy, custom.sortDirection]).toEqual(["title", "desc"]);
+ expect(custom.cardProperties.description).toBe(false);
+ expect(custom.hiddenStatusCategories).toEqual(["done"]);
+ });
+
+ it("omits the redundant project property only on fresh project surfaces", async () => {
+ setCurrentWorkspace("acme", "ws_a");
+ await flush();
+
+ expect(
+ getIssueSurfaceViewStore("project:compact-card").getState().cardProperties
+ .project,
+ ).toBe(false);
+ expect(
+ getIssueSurfaceViewStore("workspace:compact-card").getState().cardProperties
+ .project,
+ ).toBe(true);
+ });
+
it("isolates view state by surface key inside one workspace registry", async () => {
setCurrentWorkspace("acme", "ws_a");
await flush();
diff --git a/packages/core/issues/stores/surface-view-store.ts b/packages/core/issues/stores/surface-view-store.ts
index 7424f3fb7b..32c1dc91cd 100644
--- a/packages/core/issues/stores/surface-view-store.ts
+++ b/packages/core/issues/stores/surface-view-store.ts
@@ -5,6 +5,8 @@ import { createJSONStorage, persist } from "zustand/middleware";
import { createWorkspaceAwareStorage, registerForWorkspaceRehydration } from "../../platform/workspace-storage";
import { defaultStorage } from "../../platform/storage";
import {
+ DEFAULT_CARD_PROPERTIES,
+ DEFAULT_HIDDEN_STATUS_CATEGORIES,
type IssueViewState,
mergeViewStatePersisted,
viewStorePersistOptions,
@@ -33,6 +35,61 @@ const basePersist = viewStorePersistOptions(ISSUE_SURFACE_VIEW_STORAGE_KEY);
const surfaceStores = new Map<string, StoreApi<IssueViewState>>();
const suppressSurfacePersist = new Set<string>();
+const SURFACE_DEFAULTS_VERSION = 1;
+
+function defaultsForSurface(
+ surfaceKey: string,
+ set: StoreApi<IssueViewState>["setState"],
+): IssueViewState {
+ const defaults = viewStoreSlice(set);
+ if (!surfaceKey.startsWith("project:")) return defaults;
+ return {
+ ...defaults,
+ cardProperties: { ...defaults.cardProperties, project: false },
+ };
+}
+
+function isLegacyCardDefault(cardProperties: unknown): boolean {
+ if (!cardProperties || typeof cardProperties !== "object") return true;
+ return Object.keys(DEFAULT_CARD_PROPERTIES).every(
+ (key) =>
+ (cardProperties as Partial<Record<keyof typeof DEFAULT_CARD_PROPERTIES, boolean>>)[
+ key as keyof typeof DEFAULT_CARD_PROPERTIES
+ ] !== false,
+ );
+}
+
+function migrateLegacySurfaceState(
+ surfaceKey: string,
+ state: PersistedIssueViewState,
+): PersistedIssueViewState {
+ // Saved-view definitions are explicit user-authored defaults; never rewrite
+ // their local copy as though it were an untouched built-in surface.
+ if (surfaceKey.startsWith("view:")) return state;
+
+ const next = { ...state };
+ if (
+ (state.sortBy === undefined || state.sortBy === "position") &&
+ (state.sortDirection === undefined || state.sortDirection === "asc")
+ ) {
+ next.sortBy = "created_at";
+ next.sortDirection = "desc";
+ }
+ if (isLegacyCardDefault(state.cardProperties)) {
+ next.cardProperties = {
+ ...DEFAULT_CARD_PROPERTIES,
+ ...(surfaceKey.startsWith("project:") ? { project: false } : {}),
+ };
+ }
+ if (
+ state.hiddenStatusCategories === undefined ||
+ state.hiddenStatusCategories.length === 0
+ ) {
+ next.hiddenStatusCategories = [...DEFAULT_HIDDEN_STATUS_CATEGORIES];
+ }
+ return next;
+}
+
function persistedIssueViewState(state: IssueViewState): PersistedIssueViewState {
return basePersist.partialize(state);
}
@@ -72,6 +129,23 @@ const issueSurfaceViewRegistryStore = createStore<IssueSurfaceViewRegistryState>
{
name: ISSUE_SURFACE_VIEW_STORAGE_KEY,
storage: createJSONStorage(() => createWorkspaceAwareStorage(defaultStorage)),
+ version: SURFACE_DEFAULTS_VERSION,
+ migrate: (persisted, version) => {
+ const current = (persisted ?? {}) as Partial<IssueSurfaceViewRegistryState>;
+ if (version >= SURFACE_DEFAULTS_VERSION) return current;
+ return {
+ ...current,
+ surfaces: Object.fromEntries(
+ Object.entries(current.surfaces ?? {}).map(([surfaceKey, entry]) => [
+ surfaceKey,
+ {
+ ...entry,
+ state: migrateLegacySurfaceState(surfaceKey, entry.state),
+ },
+ ]),
+ ),
+ };
+ },
partialize: (state) => ({ surfaces: state.surfaces }),
merge: (persisted, current) => {
const p = (persisted ?? {}) as Partial<IssueSurfaceViewRegistryState>;
@@ -87,7 +161,7 @@ const issueSurfaceViewRegistryStore = createStore<IssueSurfaceViewRegistryState>
function resetStoreFromRegistry(surfaceKey: string, store: StoreApi<IssueViewState>) {
const persisted =
issueSurfaceViewRegistryStore.getState().surfaces[surfaceKey]?.state;
- const defaults = viewStoreSlice(store.setState);
+ const defaults = defaultsForSurface(surfaceKey, store.setState);
suppressSurfacePersist.add(surfaceKey);
try {
store.setState(mergeViewStatePersisted(persisted, defaults), true);
@@ -114,7 +188,9 @@ export function getIssueSurfaceViewStore(
const existing = surfaceStores.get(surfaceKey);
if (existing) return existing;
- const store = createStore<IssueViewState>()((set) => viewStoreSlice(set));
+ const store = createStore<IssueViewState>()((set) =>
+ defaultsForSurface(surfaceKey, set),
+ );
resetStoreFromRegistry(surfaceKey, store);
store.subscribe((state) => {
if (suppressSurfacePersist.has(surfaceKey)) return;
diff --git a/packages/core/issues/stores/view-store-status.test.ts b/packages/core/issues/stores/view-store-status.test.ts
index 23090fa40a..52a4186037 100644
--- a/packages/core/issues/stores/view-store-status.test.ts
+++ b/packages/core/issues/stores/view-store-status.test.ts
@@ -1,7 +1,12 @@
// @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 {
+ cardPropertyOptionsForView,
+ sortOptionsForView,
+ viewStoreSlice,
+ type IssueViewState,
+} from "./view-store";
import { baselineFromQuery } from "../../issue-views/baseline";
/**
@@ -21,7 +26,10 @@ describe("column visibility vs status filter", () => {
it("hiding a column does not touch the status filter", () => {
store.getState().hideStatus("backlog");
- expect(store.getState().hiddenStatusCategories).toEqual(["backlog"]);
+ expect(store.getState().hiddenStatusCategories).toEqual([
+ "cancelled",
+ "backlog",
+ ]);
expect(store.getState().statusFilters).toEqual([]);
});
@@ -30,7 +38,10 @@ describe("column visibility vs status filter", () => {
store.getState().hideStatus("done");
store.getState().showStatus("backlog");
- expect(store.getState().hiddenStatusCategories).toEqual(["done"]);
+ expect(store.getState().hiddenStatusCategories).toEqual([
+ "cancelled",
+ "done",
+ ]);
expect(store.getState().statusFilters).toEqual([]);
});
@@ -38,7 +49,10 @@ describe("column visibility vs status filter", () => {
store.getState().hideStatus("backlog");
store.getState().hideStatus("backlog");
- expect(store.getState().hiddenStatusCategories).toEqual(["backlog"]);
+ expect(store.getState().hiddenStatusCategories).toEqual([
+ "cancelled",
+ "backlog",
+ ]);
});
it("a custom status filter survives hiding and showing a column", () => {
@@ -49,11 +63,84 @@ describe("column visibility vs status filter", () => {
expect(store.getState().statusFilters).toEqual(["qa"]);
});
- it("reset restores every column", () => {
+ it("clearing filters preserves column visibility", () => {
store.getState().hideStatus("backlog");
+ store.getState().showStatus("cancelled");
store.getState().clearFilters();
- expect(store.getState().hiddenStatusCategories).toEqual([]);
+ expect(store.getState().hiddenStatusCategories).toEqual(["backlog"]);
+ });
+});
+
+describe("issue view defaults", () => {
+ let store: StoreApi<IssueViewState>;
+ beforeEach(() => {
+ store = createStore<IssueViewState>()((set) => viewStoreSlice(set));
+ });
+
+ it("starts with newest-created issues first and a compact card", () => {
+ const state = store.getState();
+
+ expect([state.sortBy, state.sortDirection]).toEqual(["created_at", "desc"]);
+ expect(state.cardProperties).toEqual({
+ priority: true,
+ description: false,
+ assignee: true,
+ startDate: false,
+ dueDate: true,
+ project: true,
+ childProgress: true,
+ labels: false,
+ });
+ });
+
+ it("uses the semantic default direction when changing sort fields", () => {
+ store.getState().setSortBy("updated_at");
+ expect(store.getState().sortDirection).toBe("desc");
+
+ store.getState().setSortBy("priority");
+ expect(store.getState().sortDirection).toBe("asc");
+ });
+
+ it("remembers an explicit direction for each sort field", () => {
+ store.getState().setSortBy("priority");
+ store.getState().setSortDirection("desc");
+ store.getState().setSortBy("created_at");
+ store.getState().setSortBy("priority");
+
+ expect(store.getState().sortDirection).toBe("desc");
+ });
+
+ it("leaves manual order when the board stops grouping by status", () => {
+ store.getState().setSortBy("position");
+ store.getState().setGrouping("assignee");
+
+ expect(store.getState().sortBy).toBe("created_at");
+ expect(store.getState().sortDirection).toBe("desc");
+ });
+
+ it("cannot restore manual order through a list-view round trip", () => {
+ store.getState().setGrouping("assignee");
+ store.getState().setViewMode("list");
+ store.getState().setSortBy("position");
+ store.getState().setViewMode("board");
+
+ expect(store.getState().grouping).toBe("assignee");
+ expect(store.getState().sortBy).toBe("created_at");
+ expect(store.getState().sortDirection).toBe("desc");
+ });
+
+ it("only offers controls the active view can apply", () => {
+ expect(
+ cardPropertyOptionsForView("list").map((option) => option.key),
+ ).not.toContain("description");
+ expect(cardPropertyOptionsForView("gantt")).toEqual([]);
+ expect(
+ sortOptionsForView("board", "assignee").map((option) => option.value),
+ ).not.toContain("position");
+ expect(
+ sortOptionsForView("list", "assignee").map((option) => option.value),
+ ).not.toContain("position");
});
});
diff --git a/packages/core/issues/stores/view-store.ts b/packages/core/issues/stores/view-store.ts
index 0bd493d788..730b50bef0 100644
--- a/packages/core/issues/stores/view-store.ts
+++ b/packages/core/issues/stores/view-store.ts
@@ -178,6 +178,61 @@ export const CARD_PROPERTY_OPTIONS: { key: keyof CardProperties; label: string }
{ key: "childProgress", label: "Sub-issue progress" },
];
+export const DEFAULT_CARD_PROPERTIES: Readonly<CardProperties> = {
+ priority: true,
+ description: false,
+ assignee: true,
+ startDate: false,
+ dueDate: true,
+ project: true,
+ childProgress: true,
+ labels: false,
+};
+
+export const DEFAULT_HIDDEN_STATUS_CATEGORIES: readonly IssueStatusCategory[] = [
+ "cancelled",
+];
+
+export function defaultSortDirection(field: SortField): SortDirection {
+ return field === "created_at" || field === "updated_at" ? "desc" : "asc";
+}
+
+/** Only expose card controls that the active renderer can honor. */
+export function cardPropertyOptionsForView(viewMode: ViewMode) {
+ if (viewMode === "table" || viewMode === "gantt") return [];
+ if (viewMode === "list") {
+ return CARD_PROPERTY_OPTIONS.filter((option) => option.key !== "description");
+ }
+ return CARD_PROPERTY_OPTIONS;
+}
+
+export function sortOptionsForView(
+ _viewMode: ViewMode,
+ grouping: IssueGrouping,
+) {
+ if (grouping !== "status") {
+ return SORT_OPTIONS.filter((option) => option.value !== "position");
+ }
+ return SORT_OPTIONS;
+}
+
+/**
+ * Manual order is one shared `issue.position` sequence per status column. It
+ * has no honest meaning while another grouping is active: reordering an
+ * assignee/project column would otherwise rewrite the status board behind the
+ * user's back. Keep this invariant at every store boundary (actions and
+ * persisted-state hydration), not only in the display menu.
+ */
+export function normalizeSortForGrouping(
+ grouping: IssueGrouping,
+ sortBy: SortField,
+ sortDirection: SortDirection,
+): Pick<IssueViewState, "sortBy" | "sortDirection"> {
+ return grouping !== "status" && sortBy === "position"
+ ? { sortBy: "created_at", sortDirection: "desc" }
+ : { sortBy, sortDirection };
+}
+
export interface IssueViewState {
viewMode: ViewMode;
grouping: IssueGrouping;
@@ -207,6 +262,8 @@ export interface IssueViewState {
agentRunningFilter: boolean;
sortBy: SortField;
sortDirection: SortDirection;
+ /** Last explicit direction per field, so switching fields is reversible. */
+ sortDirections: Partial<Record<SortField, SortDirection>>;
cardProperties: CardProperties;
/** Custom property definition ids whose values render on board/list cards. */
cardPropertyIds: string[];
@@ -307,22 +364,14 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
propertyFilters: {},
dateFilter: null,
agentRunningFilter: false,
- sortBy: "position",
- sortDirection: "asc",
- cardProperties: {
- priority: true,
- description: true,
- assignee: true,
- startDate: true,
- dueDate: true,
- project: true,
- childProgress: true,
- labels: true,
- },
+ sortBy: "created_at",
+ sortDirection: "desc",
+ sortDirections: { created_at: "desc" },
+ cardProperties: { ...DEFAULT_CARD_PROPERTIES },
cardPropertyIds: [],
showSubIssues: true,
listCollapsedStatuses: [],
- hiddenStatusCategories: [],
+ hiddenStatusCategories: [...DEFAULT_HIDDEN_STATUS_CATEGORIES],
ganttZoom: "week",
ganttShowCompleted: false,
swimlaneGrouping: "assignee",
@@ -335,11 +384,27 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
tableHierarchy: true,
tableCalculation: "none",
- setViewMode: (mode) => set({ viewMode: mode }),
+ setViewMode: (mode) =>
+ set((state) => ({
+ viewMode: mode,
+ ...normalizeSortForGrouping(
+ state.grouping,
+ state.sortBy,
+ state.sortDirection,
+ ),
+ })),
setGanttZoom: (zoom) => set({ ganttZoom: zoom }),
toggleGanttShowCompleted: () =>
set((state) => ({ ganttShowCompleted: !state.ganttShowCompleted })),
- setGrouping: (grouping) => set({ grouping }),
+ setGrouping: (grouping) =>
+ set((state) => ({
+ grouping,
+ ...normalizeSortForGrouping(
+ grouping,
+ state.sortBy,
+ state.sortDirection,
+ ),
+ })),
toggleStatusFilter: (status) =>
set((state) => ({
statusFilters: state.statusFilters.includes(status)
@@ -438,9 +503,6 @@ 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) =>
@@ -467,8 +529,26 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
}
}
}),
- setSortBy: (field) => set({ sortBy: field }),
- setSortDirection: (dir) => set({ sortDirection: dir }),
+ setSortBy: (field) =>
+ set((state) => {
+ const next = normalizeSortForGrouping(
+ state.grouping,
+ field,
+ state.sortDirections[field] ?? defaultSortDirection(field),
+ );
+ return {
+ ...next,
+ sortDirections: {
+ ...state.sortDirections,
+ [next.sortBy]: next.sortDirection,
+ },
+ };
+ }),
+ setSortDirection: (dir) =>
+ set((state) => ({
+ sortDirection: dir,
+ sortDirections: { ...state.sortDirections, [state.sortBy]: dir },
+ })),
toggleCardProperty: (key) =>
set((state) => ({
cardProperties: {
@@ -577,6 +657,7 @@ export const viewStorePersistOptions = (name: string) => ({
propertyFilters: state.propertyFilters,
sortBy: state.sortBy,
sortDirection: state.sortDirection,
+ sortDirections: state.sortDirections,
cardProperties: state.cardProperties,
cardPropertyIds: state.cardPropertyIds,
showSubIssues: state.showSubIssues,
@@ -619,6 +700,14 @@ export function mergeViewStatePersisted<T extends IssueViewState>(
// persisted value isn't a plain object.
const isRecord = (v: unknown): v is Record<string, unknown> =>
v !== null && typeof v === "object" && !Array.isArray(v);
+ const persistedSortDirections = isRecord(p.sortDirections)
+ ? Object.fromEntries(
+ Object.entries(p.sortDirections).filter(
+ (entry): entry is [string, SortDirection] =>
+ entry[1] === "asc" || entry[1] === "desc",
+ ),
+ )
+ : {};
const persistedTableColumns = Array.isArray(p.tableColumns)
? p.tableColumns.filter(
(column): column is TableColumnConfig =>
@@ -633,13 +722,17 @@ export function mergeViewStatePersisted<T extends IssueViewState>(
const persistedTitle = persistedTableColumns.find(
(column) => column.key === "title",
);
- return {
+ const merged = {
...current,
...p,
cardProperties: {
...current.cardProperties,
...(p.cardProperties ?? {}),
},
+ sortDirections: {
+ ...current.sortDirections,
+ ...persistedSortDirections,
+ },
swimlaneOrders: isRecord(p.swimlaneOrders)
? { ...current.swimlaneOrders, ...p.swimlaneOrders }
: current.swimlaneOrders,
@@ -657,6 +750,14 @@ export function mergeViewStatePersisted<T extends IssueViewState>(
? p.tableCollapsedParents
: current.tableCollapsedParents,
};
+ return {
+ ...merged,
+ ...normalizeSortForGrouping(
+ merged.grouping,
+ merged.sortBy,
+ merged.sortDirection,
+ ),
+ };
}
/** Factory: creates a vanilla StoreApi for use with React Context. */
diff --git a/packages/views/issues/components/board-card-assignee-picker.test.tsx b/packages/views/issues/components/board-card-assignee-picker.test.tsx
index 9576dec9d9..39c9ddbaff 100644
--- a/packages/views/issues/components/board-card-assignee-picker.test.tsx
+++ b/packages/views/issues/components/board-card-assignee-picker.test.tsx
@@ -41,6 +41,9 @@ vi.mock("@multica/core/paths", () => ({
}));
const viewState = vi.hoisted(() => ({
+ viewMode: "board",
+ grouping: "status",
+ swimlaneGrouping: "assignee",
cardProperties: {
priority: false,
description: false,
@@ -162,4 +165,56 @@ describe("BoardCardContent assignee picker", () => {
expect(navigation.push).not.toHaveBeenCalled();
},
);
+
+ it("does not repeat the assignee inside an assignee-grouped board", () => {
+ viewState.grouping = "assignee";
+ const issue = makeIssue("member");
+ const { container } = render(
+ <NavigationProvider value={navigation}>
+ <IssueSurfaceActionsProvider actions={actions}>
+ <BoardCardContent issue={issue} editable />
+ </IssueSurfaceActionsProvider>
+ </NavigationProvider>,
+ );
+
+ expect(container.querySelector('[data-slot="avatar"]')).toBeNull();
+ viewState.grouping = "status";
+ });
+
+ it("does not repeat the assignee inside an assignee-grouped swimlane", () => {
+ viewState.viewMode = "swimlane";
+ const issue = makeIssue("member");
+ const { container } = render(
+ <NavigationProvider value={navigation}>
+ <IssueSurfaceActionsProvider actions={actions}>
+ <BoardCardContent issue={issue} editable />
+ </IssueSurfaceActionsProvider>
+ </NavigationProvider>,
+ );
+
+ expect(container.querySelector('[data-slot="avatar"]')).toBeNull();
+ viewState.viewMode = "board";
+ });
+
+ it("keeps empty priority and assignee fields visually silent", () => {
+ viewState.cardProperties.priority = true;
+ const issue = {
+ ...makeIssue("member"),
+ assignee_type: null,
+ assignee_id: null,
+ start_date: null,
+ due_date: null,
+ };
+ const { container } = render(
+ <NavigationProvider value={navigation}>
+ <IssueSurfaceActionsProvider actions={actions}>
+ <BoardCardContent issue={issue} editable />
+ </IssueSurfaceActionsProvider>
+ </NavigationProvider>,
+ );
+
+ expect(container.querySelector("svg")).toBeNull();
+ expect(screen.queryByText("Translated")).not.toBeInTheDocument();
+ viewState.cardProperties.priority = false;
+ });
});
diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsx
index 7d9b8fdd63..a49daf629d 100644
--- a/packages/views/issues/components/board-card.tsx
+++ b/packages/views/issues/components/board-card.tsx
@@ -22,6 +22,7 @@ import { ProjectIcon } from "../../projects/components/project-icon";
import { PriorityIcon } from "./priority-icon";
import { PriorityPicker, AssigneePicker, StartDatePicker, DueDatePicker } from "./pickers";
import { useViewStore } from "@multica/core/issues/stores/view-store-context";
+import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";
import { ProgressRing } from "./progress-ring";
import type { ChildProgress } from "./list-row";
import { IssueActionsContextMenu } from "../actions";
@@ -62,11 +63,24 @@ export const BoardCardContent = memo(function BoardCardContent({
const timeAgo = useTimeAgo();
const storeProperties = useViewStore((s) => s.cardProperties);
const cardPropertyIds = useViewStore((s) => s.cardPropertyIds);
+ const viewMode = useViewStore((s) => s.viewMode);
+ const grouping = useViewStore((s) => s.grouping);
+ const swimlaneGrouping = useViewStore((s) => s.swimlaneGrouping);
+ const cardGrouping =
+ viewMode === "board"
+ ? grouping
+ : viewMode === "swimlane"
+ ? swimlaneGrouping
+ : null;
+ const groupedPropertyId = cardGrouping
+ ? propertyIdFromViewKey(cardGrouping)
+ : null;
const cardWsId = useWorkspaceId();
const { data: workspaceProperties = [] } = useQuery(propertyListOptions(cardWsId));
// Custom properties toggled on in Display options, in toggle order, only
// when this issue actually carries a value.
const cardCustomProperties = cardPropertyIds
+ .filter((id) => id !== groupedPropertyId)
.map((id) => workspaceProperties.find((p) => p.id === id))
.filter((p): p is IssueProperty => !!p && issue.properties?.[p.id] !== undefined);
const labels = issue.labels ?? [];
@@ -82,13 +96,15 @@ export const BoardCardContent = memo(function BoardCardContent({
);
const canEdit = editable && !!surfaceActions;
- const showPriority = storeProperties.priority;
- const showDescription = storeProperties.description && issue.description;
- const showAssigneeSection = storeProperties.assignee;
const hasAssignee = !!issue.assignee_type && !!issue.assignee_id;
+ const showPriority = storeProperties.priority && issue.priority !== "none";
+ const showDescription = storeProperties.description && issue.description;
+ const showAssigneeSection =
+ storeProperties.assignee && cardGrouping !== "assignee" && hasAssignee;
const showStartDate = storeProperties.startDate && issue.start_date;
const showDueDate = storeProperties.dueDate && issue.due_date;
- const showProject = storeProperties.project && project;
+ const showProject =
+ storeProperties.project && cardGrouping !== "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
@@ -211,9 +227,14 @@ export const BoardCardContent = memo(function BoardCardContent({
<span className="truncate">{project!.title}</span>
</span>
)}
- {showLabels && labels.map((label) => (
+ {showLabels && labels.slice(0, 2).map((label) => (
<LabelChip key={label.id} label={label} />
))}
+ {showLabels && labels.length > 2 && (
+ <span className="text-micro text-muted-foreground">
+ +{labels.length - 2}
+ </span>
+ )}
{cardCustomProperties.map((property) => (
<span
key={property.id}
diff --git a/packages/views/issues/components/board-view.tsx b/packages/views/issues/components/board-view.tsx
index bed53175e6..3bdf0038e0 100644
--- a/packages/views/issues/components/board-view.tsx
+++ b/packages/views/issues/components/board-view.tsx
@@ -607,6 +607,11 @@ function BoardViewImpl({
const currentIssue = map.get(activeId);
if (!currentIssue || issueMatchesGroup(currentIssue, finalGroup)) {
resetColumns();
+ if (activeId !== overId) {
+ toast.info(t(($) => $.board.manual_reorder_hint), {
+ id: "issue-manual-reorder-hint",
+ });
+ }
return;
}
// Optimistically move the card into the target column *now*. Without
@@ -665,7 +670,7 @@ function BoardViewImpl({
);
applyPropertyGroupValue(finalGroup, activeId);
},
- [groupedIssues, groups, grouping, groupingOptionIds, onMoveIssue, groupIds, groupMap, sortBy, beginSettle, columnsRef, isDraggingRef, setColumns, applyPropertyGroupValue],
+ [groupedIssues, groups, grouping, groupingOptionIds, onMoveIssue, groupIds, groupMap, sortBy, beginSettle, columnsRef, isDraggingRef, setColumns, applyPropertyGroupValue, t],
);
// An aborted drag (pointercancel, window resize, tab hide, Escape) fires
diff --git a/packages/views/issues/components/issues-header.status-filter.test.tsx b/packages/views/issues/components/issues-header.status-filter.test.tsx
index cf714a5af6..016380f157 100644
--- a/packages/views/issues/components/issues-header.status-filter.test.tsx
+++ b/packages/views/issues/components/issues-header.status-filter.test.tsx
@@ -134,8 +134,8 @@ describe("IssueFilterMenu status section", () => {
"In Progress",
"In Review",
"Human Review",
- "Done",
"Blocked",
+ "Done",
"Cancelled",
]);
});
diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsx
index c78c825622..fd00806d8e 100644
--- a/packages/views/issues/components/issues-header.tsx
+++ b/packages/views/issues/components/issues-header.tsx
@@ -2,8 +2,6 @@
import { cloneElement, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
- ArrowDown,
- ArrowUp,
CalendarDays,
ChartGantt,
ChevronDown,
@@ -79,12 +77,15 @@ import { formatActorRef, isActorPropertyType, isFilterablePropertyType, isScalar
import { ProjectIcon } from "../../projects/components/project-icon";
import { ActorAvatar } from "../../common/actor-avatar";
import { PropertyIcon } from "../../common/property-icon";
+import { sortDirectionLabelKey } from "../utils/sort-direction";
import { LabelChip } from "../../labels/label-chip";
import {
SORT_OPTIONS,
GROUPING_OPTIONS,
SWIMLANE_GROUPINGS,
CARD_PROPERTY_OPTIONS,
+ cardPropertyOptionsForView,
+ sortOptionsForView,
type ActorFilterValue,
type IssueDateField,
type IssueDateFilter,
@@ -1949,6 +1950,8 @@ export function IssueDisplayControls({
labels: "card_labels",
childProgress: "card_child_progress",
};
+ const availableCardPropertyOptions = cardPropertyOptionsForView(viewMode);
+ const availableSortOptions = sortOptionsForView(viewMode, grouping);
const sortPropertyId = propertyIdFromViewKey(sortBy);
const groupingPropertyId = propertyIdFromViewKey(grouping);
const tableGroupingPropertyId = propertyIdFromViewKey(tableGrouping);
@@ -1958,6 +1961,9 @@ export function IssueDisplayControls({
const sortLabel = sortPropertyId
? propertyById.get(sortPropertyId)?.name ?? t(($) => $.display.sort_manual)
: t(($) => $.display[SORT_LABEL_KEY[sortBy as keyof typeof SORT_LABEL_KEY]]);
+ const sortDirectionLabel = t(
+ ($) => $.display[sortDirectionLabelKey(sortBy, sortDirection)],
+ );
const groupingLabel = groupingPropertyId
? propertyById.get(groupingPropertyId)?.name ?? t(($) => $.display.group_status)
: t(($) => $.display[GROUPING_LABEL_KEY[grouping as keyof typeof GROUPING_LABEL_KEY]]);
@@ -2208,7 +2214,7 @@ export function IssueDisplayControls({
<div className="flex items-center gap-1.5">
<Select
items={[
- ...SORT_OPTIONS.map((opt) => ({
+ ...availableSortOptions.map((opt) => ({
value: opt.value as string,
label: t(($) => $.display[SORT_LABEL_KEY[opt.value as keyof typeof SORT_LABEL_KEY]]),
})),
@@ -2227,7 +2233,7 @@ export function IssueDisplayControls({
</SelectTrigger>
<SelectContent align="end">
<SelectGroup>
- {SORT_OPTIONS.map((opt) => (
+ {availableSortOptions.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{t(($) => $.display[SORT_LABEL_KEY[opt.value as keyof typeof SORT_LABEL_KEY]])}
</SelectItem>
@@ -2243,17 +2249,14 @@ export function IssueDisplayControls({
{sortBy !== "position" && (
<Button
variant="outline"
- size="icon-sm"
+ size="sm"
onClick={() =>
act.setSortDirection(sortDirection === "asc" ? "desc" : "asc")
}
- title={sortDirection === "asc" ? t(($) => $.display.ascending_title) : t(($) => $.display.descending_title)}
+ aria-label={sortDirectionLabel}
+ title={sortDirectionLabel}
>
- {sortDirection === "asc" ? (
- <ArrowUp className="size-3.5" />
- ) : (
- <ArrowDown className="size-3.5" />
- )}
+ {sortDirectionLabel}
</Button>
)}
</div>
@@ -2268,7 +2271,7 @@ export function IssueDisplayControls({
onCheckedChange={() => act.toggleShowSubIssues()}
/>
</label>
- {viewMode !== "table" && (
+ {availableCardPropertyOptions.length > 0 && (
<div>
<span className="text-caption font-medium text-muted-foreground">
{t(($) => $.display.card_properties_section)}
@@ -2276,7 +2279,7 @@ export function IssueDisplayControls({
{/* Chip toggles (pressed = shown on cards). Unpressed chips
dim so the active set reads at a glance. */}
<div className="mt-2 flex flex-wrap gap-1">
- {CARD_PROPERTY_OPTIONS.map((opt) => (
+ {availableCardPropertyOptions.map((opt) => (
<Toggle
key={opt.key}
size="sm"
diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsx
index 71f893fc57..5efca5ad8f 100644
--- a/packages/views/issues/components/issues-page.test.tsx
+++ b/packages/views/issues/components/issues-page.test.tsx
@@ -272,8 +272,8 @@ vi.mock("@multica/core/api", () => ({
// Mock issue config
vi.mock("@multica/core/issues/config", () => ({
- ALL_STATUSES: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],
- STATUS_ORDER: ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"],
+ ALL_STATUSES: ["backlog", "todo", "in_progress", "in_review", "blocked", "done", "cancelled"],
+ STATUS_ORDER: ["backlog", "todo", "in_progress", "in_review", "blocked", "done", "cancelled"],
STATUS_CONFIG: {
backlog: { label: "Backlog", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
todo: { label: "Todo", iconColor: "text-muted-foreground", hoverBg: "hover:bg-accent" },
@@ -379,6 +379,22 @@ vi.mock("@multica/core/issues/stores/view-store", () => ({
{ key: "labels", label: "Labels" },
{ key: "childProgress", label: "Sub-issue progress" },
],
+ cardPropertyOptionsForView: () => [
+ { key: "priority", label: "Priority" },
+ { key: "description", label: "Description" },
+ { key: "assignee", label: "Assignee" },
+ { key: "dueDate", label: "Due date" },
+ { key: "project", label: "Project" },
+ { key: "labels", label: "Labels" },
+ { key: "childProgress", label: "Sub-issue progress" },
+ ],
+ sortOptionsForView: () => [
+ { value: "position", label: "Manual" },
+ { value: "priority", label: "Priority" },
+ { value: "due_date", label: "Due date" },
+ { value: "created_at", label: "Created date" },
+ { value: "title", label: "Title" },
+ ],
}));
vi.mock("@multica/core/issues/stores/view-store-context", () => ({
diff --git a/packages/views/issues/components/list-row.tsx b/packages/views/issues/components/list-row.tsx
index 6e184071a7..e2bc7f9352 100644
--- a/packages/views/issues/components/list-row.tsx
+++ b/packages/views/issues/components/list-row.tsx
@@ -92,10 +92,12 @@ function ListRowContent({
className="relative flex shrink-0 items-center justify-center w-4 h-4"
{...checkboxProps}
>
- <PriorityIcon
- priority={issue.priority}
- className={selected ? "hidden" : "group-hover/row:hidden"}
- />
+ {storeProperties.priority && issue.priority !== "none" && (
+ <PriorityIcon
+ priority={issue.priority}
+ className={selected ? "hidden" : "group-hover/row:hidden"}
+ />
+ )}
<input
type="checkbox"
checked={selected}
diff --git a/packages/views/issues/components/list-view.test.tsx b/packages/views/issues/components/list-view.test.tsx
index 60dc7c1273..e846564685 100644
--- a/packages/views/issues/components/list-view.test.tsx
+++ b/packages/views/issues/components/list-view.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { render, screen, act } from "@testing-library/react";
+import { render, screen, act, fireEvent } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@multica/core/i18n/react";
@@ -13,6 +13,9 @@ import enIssues from "../../locales/en/issues.json";
const TEST_RESOURCES = { en: { common: enCommon, issues: enIssues } };
+const mockToastInfo = vi.hoisted(() => vi.fn());
+vi.mock("sonner", () => ({ toast: { info: mockToastInfo } }));
+
vi.mock("@multica/core/hooks", () => ({
useWorkspaceId: () => "ws-1",
}));
@@ -69,6 +72,7 @@ const mockViewState: {
cardPropertyIds: string[];
listCollapsedStatuses: IssueStatus[];
toggleListCollapsed: (status: IssueStatus) => void;
+ showStatus: (status: IssueStatusCategory) => void;
} = {
sortBy: "position",
sortDirection: "asc",
@@ -81,6 +85,7 @@ const mockViewState: {
? mockViewState.listCollapsedStatuses.filter((s) => s !== status)
: [...mockViewState.listCollapsedStatuses, status];
}),
+ showStatus: vi.fn(),
};
vi.mock("@multica/core/issues/stores/view-store-context", () => ({
@@ -100,16 +105,22 @@ vi.mock("@multica/core/modals", () => ({
),
}));
+vi.mock("./priority-icon", () => ({
+ PriorityIcon: () => <span data-testid="priority-icon" />,
+}));
+
// Capture the DndContext callbacks so a test can drive dnd-kit's real
// lifecycle — including the cancel path, which never calls onDragEnd.
let lastOnDragStart: any = null;
let lastOnDragCancel: any = null;
+let lastOnDragEnd: any = null;
const stableSetNodeRef = () => {};
vi.mock("@dnd-kit/core", () => ({
- DndContext: ({ children, onDragStart, onDragCancel }: any) => {
+ DndContext: ({ children, onDragStart, onDragCancel, onDragEnd }: any) => {
lastOnDragStart = onDragStart;
lastOnDragCancel = onDragCancel;
+ lastOnDragEnd = onDragEnd;
return children;
},
DragOverlay: () => null,
@@ -188,11 +199,13 @@ const emptyPage = {
const PAGINATION = {
todo: { ...emptyPage, total: 2 },
in_review: { ...emptyPage, total: 1 },
+ cancelled: { ...emptyPage, total: 1 },
} as unknown as IssueStatusPagination;
function renderListView(
issues: Issue[] = ISSUES,
visibleStatuses: IssueStatusCategory[] = ["todo"],
+ hiddenStatuses: IssueStatusCategory[] = [],
) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: 0 } },
@@ -205,6 +218,7 @@ function renderListView(
<ListView
issues={issues}
visibleStatuses={visibleStatuses}
+ hiddenStatuses={hiddenStatuses}
statusPagination={PAGINATION}
onMoveIssue={vi.fn()}
/>
@@ -217,9 +231,51 @@ function renderListView(
describe("ListView status header collapse", () => {
beforeEach(() => {
+ mockViewState.sortBy = "position";
+ mockViewState.sortDirection = "asc";
mockViewState.listCollapsedStatuses = [];
+ mockViewState.cardProperties = { priority: true };
+ vi.mocked(mockViewState.showStatus).mockClear();
+ mockToastInfo.mockClear();
lastOnDragStart = null;
lastOnDragCancel = null;
+ lastOnDragEnd = null;
+ });
+
+ it("honors the priority card-property toggle", () => {
+ mockViewState.cardProperties = { priority: false };
+ renderListView();
+
+ expect(screen.queryByTestId("priority-icon")).not.toBeInTheDocument();
+ });
+
+ it("shows hidden statuses with a recovery action", async () => {
+ const user = userEvent.setup();
+ renderListView(ISSUES, ["todo"], ["cancelled"]);
+
+ expect(screen.getByText("Hidden columns")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Show column" }));
+ await user.click(await screen.findByRole("menuitem", { name: "Show column" }));
+
+ expect(mockViewState.showStatus).toHaveBeenCalledWith("cancelled");
+ });
+
+ it("explains why same-status reordering is ignored under an automatic sort", () => {
+ mockViewState.sortBy = "created_at";
+ renderListView();
+
+ act(() => {
+ lastOnDragStart({ active: { id: "issue-1" } });
+ lastOnDragEnd({
+ active: { id: "issue-1" },
+ over: { id: "issue-2" },
+ });
+ });
+
+ expect(mockToastInfo).toHaveBeenCalledWith(
+ "Switch to Manual ordering to rearrange issues within a column.",
+ { id: "issue-manual-reorder-hint" },
+ );
});
it("collapses a status group when its header is clicked", async () => {
diff --git a/packages/views/issues/components/list-view.tsx b/packages/views/issues/components/list-view.tsx
index 43a5b67988..ca3eeb48c8 100644
--- a/packages/views/issues/components/list-view.tsx
+++ b/packages/views/issues/components/list-view.tsx
@@ -46,6 +46,8 @@ import type {
import { VirtuosoSeed, VIRTUOSO_SEED_COUNT } from "../../common/virtuoso-seed";
import { DeferredTooltip } from "../../common/deferred-tooltip";
import { useRestoredScrollRef } from "../../platform";
+import { HiddenColumnsPanel, HiddenColumnRow } from "./hidden-columns-panel";
+import { toast } from "sonner";
// List rows are a fixed 36px (h-9). Sharing the estimate between the seed's
// trailing spacer and Virtuoso's defaultItemHeight keeps the shared
@@ -69,6 +71,7 @@ function buildListGroups(visibleStatuses: IssueStatusCategory[]): BoardColumnGro
function ListViewImpl({
issues,
visibleStatuses,
+ hiddenStatuses = [],
childProgressMap = EMPTY_PROGRESS_MAP,
projectMap,
statusPagination,
@@ -78,6 +81,7 @@ function ListViewImpl({
}: {
issues: Issue[];
visibleStatuses: IssueStatusCategory[];
+ hiddenStatuses?: IssueStatusCategory[];
childProgressMap?: Map<string, ChildProgress>;
projectMap?: Map<string, Project>;
statusPagination: IssueStatusPagination;
@@ -257,6 +261,11 @@ function ListViewImpl({
const currentIssue = map.get(activeId);
if (!currentIssue || issueMatchesGroup(currentIssue, finalGroup)) {
resetColumns();
+ if (activeId !== overId) {
+ toast.info(t(($) => $.board.manual_reorder_hint), {
+ id: "issue-manual-reorder-hint",
+ });
+ }
return;
}
// Optimistically move the row into the target group *now*. Without this
@@ -310,7 +319,7 @@ function ListViewImpl({
beginSettle(),
);
},
- [issues, groups, onMoveIssue, groupIds, groupMap, sortBy, beginSettle, setColumns, columnsRef, isDraggingRef],
+ [issues, groups, onMoveIssue, groupIds, groupMap, sortBy, beginSettle, setColumns, columnsRef, isDraggingRef, t],
);
// dnd-kit fires onDragCancel — never onDragEnd — when an active drag is
@@ -347,42 +356,58 @@ function ListViewImpl({
);
const content = (
- <Accordion.Root
- multiple
- className="space-y-1"
- value={expandedStatuses}
- onValueChange={(value: string[]) => {
- if (isDraggingRef.current) return;
- for (const status of visibleStatuses) {
- const wasExpanded = expandedStatuses.includes(status);
- const isExpanded = value.includes(status);
- if (wasExpanded !== isExpanded) {
- toggleListCollapsed(status as IssueStatusCategory);
+ <>
+ <Accordion.Root
+ multiple
+ className="space-y-1"
+ value={expandedStatuses}
+ onValueChange={(value: string[]) => {
+ if (isDraggingRef.current) return;
+ for (const status of visibleStatuses) {
+ const wasExpanded = expandedStatuses.includes(status);
+ const isExpanded = value.includes(status);
+ if (wasExpanded !== isExpanded) {
+ toggleListCollapsed(status as IssueStatusCategory);
+ }
}
- }
- }}
- >
- {visibleStatuses.map((status) => {
- const isExpanded = expandedStatuses.includes(status);
- return (
- <StatusAccordionItem
- key={status}
- status={status}
- issueIds={columns[statusGroupId(status)] ?? EMPTY_IDS}
- issueMap={issueMapRef.current}
- childProgressMap={childProgressMap}
- projectMap={projectMap}
- page={statusPagination[status]}
- projectId={projectId}
- onCreateIssue={onCreateIssue}
- dragEnabled={dragEnabled}
- isExpanded={isExpanded}
- sortLabel={sortLabel}
- scrollParent={scrollEl}
+ }}
+ >
+ {visibleStatuses.map((status) => {
+ const isExpanded = expandedStatuses.includes(status);
+ return (
+ <StatusAccordionItem
+ key={status}
+ status={status}
+ issueIds={columns[statusGroupId(status)] ?? EMPTY_IDS}
+ issueMap={issueMapRef.current}
+ childProgressMap={childProgressMap}
+ projectMap={projectMap}
+ page={statusPagination[status]}
+ projectId={projectId}
+ onCreateIssue={onCreateIssue}
+ dragEnabled={dragEnabled}
+ isExpanded={isExpanded}
+ sortLabel={sortLabel}
+ scrollParent={scrollEl}
+ />
+ );
+ })}
+ </Accordion.Root>
+ {hiddenStatuses.length > 0 && (
+ <div className="mt-4 px-1 pb-4">
+ <HiddenColumnsPanel
+ hiddenStatuses={hiddenStatuses}
+ renderRow={(status) => (
+ <HiddenColumnRow
+ key={status}
+ status={status}
+ total={statusPagination[status]?.total}
+ />
+ )}
/>
- );
- })}
- </Accordion.Root>
+ </div>
+ )}
+ </>
);
if (!dragEnabled) {
diff --git a/packages/views/issues/components/save-view-dialog.test.tsx b/packages/views/issues/components/save-view-dialog.test.tsx
index 288c707239..2f88edef91 100644
--- a/packages/views/issues/components/save-view-dialog.test.tsx
+++ b/packages/views/issues/components/save-view-dialog.test.tsx
@@ -44,10 +44,10 @@ describe("DraftDefinitionFields ordering", () => {
const store = renderFields("created_at");
await user.click(screen.getByRole("button", { name: /Default display/ }));
- await user.click(screen.getByRole("button", { name: "Ascending" }));
+ await user.click(screen.getByRole("button", { name: "Oldest first" }));
expect(store.getState().sortDirection).toBe("desc");
- expect(screen.getByRole("button", { name: "Descending" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Newest first" })).toBeInTheDocument();
});
it("hides direction for manual ordering, where direction has no effect", async () => {
@@ -56,7 +56,9 @@ describe("DraftDefinitionFields ordering", () => {
await user.click(screen.getByRole("button", { name: /Default display/ }));
- expect(screen.queryByRole("button", { name: "Ascending" })).not.toBeInTheDocument();
- expect(screen.queryByRole("button", { name: "Descending" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Workflow order" })).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Reverse workflow order" }),
+ ).not.toBeInTheDocument();
});
});
diff --git a/packages/views/issues/components/save-view-dialog.tsx b/packages/views/issues/components/save-view-dialog.tsx
index fede0ea214..8052e0a29b 100644
--- a/packages/views/issues/components/save-view-dialog.tsx
+++ b/packages/views/issues/components/save-view-dialog.tsx
@@ -3,7 +3,8 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { createStore, type StoreApi } from "zustand/vanilla";
import { useQuery } from "@tanstack/react-query";
-import { ArrowDown, ArrowUp, ChevronRight, Plus } from "lucide-react";
+import { ChevronRight, Plus } from "lucide-react";
+import { sortDirectionLabelKey } from "../utils/sort-direction";
import { Button } from "@multica/ui/components/ui/button";
import { Input } from "@multica/ui/components/ui/input";
import { Label } from "@multica/ui/components/ui/label";
@@ -45,9 +46,9 @@ import {
viewStorePersistOptions,
mergeViewStatePersisted,
GROUPING_OPTIONS,
- SORT_OPTIONS,
SWIMLANE_GROUPINGS,
- CARD_PROPERTY_OPTIONS,
+ cardPropertyOptionsForView,
+ sortOptionsForView,
type IssueGrouping,
type IssueViewState,
type SortField,
@@ -159,6 +160,8 @@ export function DraftDefinitionFields() {
const cardProperties = useViewStore((s) => s.cardProperties);
const cardPropertyIds = useViewStore((s) => s.cardPropertyIds);
const act = useViewStoreApi().getState();
+ const availableSortOptions = sortOptionsForView(viewMode, grouping);
+ const availableCardPropertyOptions = cardPropertyOptionsForView(viewMode);
const { data: workspaceProperties = [] } = useQuery(propertyListOptions(wsId));
const groupableProperties = useMemo(
@@ -189,9 +192,7 @@ export function DraftDefinitionFields() {
const sortDirectionLabel =
sortBy === "position"
? null
- : sortDirection === "asc"
- ? t(($) => $.display.ascending_title)
- : t(($) => $.display.descending_title);
+ : t(($) => $.display[sortDirectionLabelKey(sortBy, sortDirection)]);
const displaySummary = [
layoutLabel,
groupingLabel,
@@ -351,7 +352,7 @@ export function DraftDefinitionFields() {
<div className="flex items-center gap-1.5">
<Select
items={[
- ...SORT_OPTIONS.map((opt) => ({
+ ...availableSortOptions.map((opt) => ({
value: opt.value as string,
label: t(($) => $.display[SORT_LABEL_KEY[opt.value as keyof typeof SORT_LABEL_KEY]]),
})),
@@ -370,7 +371,7 @@ export function DraftDefinitionFields() {
</SelectTrigger>
<SelectContent align="start">
<SelectGroup>
- {SORT_OPTIONS.map((opt) => (
+ {availableSortOptions.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{t(($) => $.display[SORT_LABEL_KEY[opt.value as keyof typeof SORT_LABEL_KEY]])}
</SelectItem>
@@ -387,7 +388,7 @@ export function DraftDefinitionFields() {
<Button
type="button"
variant="outline"
- size="icon-sm"
+ size="sm"
onClick={() =>
act.setSortDirection(
sortDirection === "asc" ? "desc" : "asc",
@@ -396,22 +397,18 @@ export function DraftDefinitionFields() {
aria-label={sortDirectionLabel ?? undefined}
title={sortDirectionLabel ?? undefined}
>
- {sortDirection === "asc" ? (
- <ArrowUp className="size-3.5" />
- ) : (
- <ArrowDown className="size-3.5" />
- )}
+ {sortDirectionLabel}
</Button>
)}
</div>
</div>
- {viewMode !== "table" && (
+ {availableCardPropertyOptions.length > 0 && (
<div className="flex items-start gap-3">
<Label className={`${ROW_LABEL} pt-1`}>
{t(($) => $.display.card_properties_section)}
</Label>
<div className="flex min-w-0 flex-1 flex-wrap gap-1">
- {CARD_PROPERTY_OPTIONS.map((opt) => (
+ {availableCardPropertyOptions.map((opt) => (
<Toggle
key={opt.key}
size="sm"
diff --git a/packages/views/issues/surface/issue-surface.test.tsx b/packages/views/issues/surface/issue-surface.test.tsx
index 7c506f2b42..60a30762b5 100644
--- a/packages/views/issues/surface/issue-surface.test.tsx
+++ b/packages/views/issues/surface/issue-surface.test.tsx
@@ -566,7 +566,7 @@ describe("IssueSurface — table pagination ownership", () => {
"pt-sort-transition",
);
const listIssueTableRows = vi.fn((request: IssueTableRowsRequest) =>
- request.query.sort.field === "position"
+ request.query.sort.field === "created_at"
? Promise.resolve({
query_fingerprint: "sha256:initial-sort",
group_key: null,
diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsx
index f86efc7f35..ca6cd991ad 100644
--- a/packages/views/issues/surface/issue-surface.tsx
+++ b/packages/views/issues/surface/issue-surface.tsx
@@ -320,6 +320,7 @@ function IssueSurfaceContent({
<ListView
issues={issues}
visibleStatuses={controller.visibleStatuses}
+ hiddenStatuses={controller.hiddenStatuses}
childProgressMap={controller.childProgressMap}
projectMap={controller.projectMap}
projectId={controller.projectId}
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 b5ef1d98b7..c2a9a065a4 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx
+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx
@@ -1185,10 +1185,9 @@ describe("useIssueSurfaceController", () => {
expect(result.current.isEmpty).toBe(true);
});
- // --- cancelled as a default status (MUL-4290) ------------------------
- // Cancelled is a first-class default lifecycle status: fetched into the
- // cache, surfaced by default, narrowed (not unlocked) by the status filter,
- // and hideable like any other status.
+ // --- cancelled as a hidden-by-default status -------------------------
+ // Cancelled remains fetched and filterable, but stays out of the default
+ // presentation until the user explicitly asks for it.
function mockListByStatus(byStatus: Partial<Record<IssueStatus, Issue[]>>) {
fixtureRows = Object.values(byStatus).flatMap((issues) => issues ?? []);
@@ -1207,7 +1206,7 @@ describe("useIssueSurfaceController", () => {
getWorkspaceWorkingAgents.mockResolvedValue(agents);
}
- it("fetches and surfaces the cancelled bucket as a default status", async () => {
+ it("fetches the cancelled bucket but hides it by default", async () => {
const { result } = renderHook(
() =>
useIssueSurfaceController({
@@ -1223,12 +1222,11 @@ describe("useIssueSurfaceController", () => {
expect(listIssues).toHaveBeenCalledWith(
expect.objectContaining({ status: "cancelled", limit: 50, offset: 0 }),
);
- // …and with no status filter it is a visible column, ordered last.
- expect(result.current.visibleStatuses).toContain("cancelled");
- expect(result.current.visibleStatuses.at(-1)).toBe("cancelled");
+ expect(result.current.visibleStatuses).not.toContain("cancelled");
+ expect(result.current.hiddenStatuses).toContain("cancelled");
});
- it("includes cancelled issues in the default surface and visible statuses", async () => {
+ it("keeps cancelled issues out of the default visible surface", async () => {
mockListByStatus({
todo: [makeIssue({ id: "todo-1", status: "todo" })],
cancelled: [makeIssue({ id: "cancelled-1", status: "cancelled" })],
@@ -1245,11 +1243,10 @@ describe("useIssueSurfaceController", () => {
await waitFor(() => expect(result.current.isLoading).toBe(false));
- expect(result.current.visibleStatuses).toContain("cancelled");
+ expect(result.current.visibleStatuses).not.toContain("cancelled");
const surfaceIds = result.current.surfaceIssues.map((i) => i.id);
expect(surfaceIds).toContain("todo-1");
- expect(surfaceIds).toContain("cancelled-1");
- expect(result.current.issues.map((i) => i.id)).toContain("cancelled-1");
+ expect(surfaceIds).not.toContain("cancelled-1");
});
it("narrows the visible set to the selected statuses, dropping cancelled when it is not selected", async () => {
diff --git a/packages/views/issues/surface/use-issue-surface-controller.ts b/packages/views/issues/surface/use-issue-surface-controller.ts
index b48a93d58d..cb4cbadbe2 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.ts
+++ b/packages/views/issues/surface/use-issue-surface-controller.ts
@@ -15,9 +15,8 @@ import type {
} from "@multica/core/types";
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 { statusFilterColumns, visibleStatusCategories } 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";
@@ -361,14 +360,10 @@ export function useIssueSurfaceController({
// keys land in. (MUL-6243)
const serverStatuses = useMemo<IssueStatusCategory[]>(
() => {
- 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)),
+ const visible = visibleStatusCategories(
+ statusFilters,
+ hiddenStatusCategories,
+ catalog,
);
return effectiveViewMode === "list"
? visible.filter((status) => !listCollapsedStatuses.includes(status))
@@ -378,7 +373,7 @@ export function useIssueSurfaceController({
effectiveViewMode,
hiddenStatusCategories,
listCollapsedStatuses,
- statusColumnsForFilters,
+ catalog,
statusFilters,
],
);
diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.ts
index 016d325122..da5c9e43fa 100644
--- a/packages/views/issues/surface/use-issue-surface-data.ts
+++ b/packages/views/issues/surface/use-issue-surface-data.ts
@@ -10,7 +10,7 @@ import { issueSurfaceGanttOptions } from "@multica/core/issues/surface/repositor
import type { IssueSurfaceQueryPlan } from "@multica/core/issues/surface/query-plan";
import type { IssueStatus, IssueStatusCategory, PropertyFilterValue } from "@multica/core/types";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
-import { issueBehavesAsAny, statusFilterColumns } from "@multica/core/issues";
+import { issueBehavesAsAny, visibleStatusCategories } from "@multica/core/issues";
import {
applyIssueFilters,
type IssueFilterState,
@@ -160,11 +160,10 @@ export function useIssueSurfaceData({
? serverGroupBranches.issues
: EMPTY_ISSUES;
- // `cancelled` is a first-class default status (MUL-4290): it is fetched into
- // the cache like every other status and flows straight through to list /
- // board / swimlane columns, header facet counts, batch selection, and the
- // isEmpty check. The status filter narrows this set like any other status —
- // it no longer unlocks an otherwise-hidden bucket.
+ // Status branches already reflect the visible category set chosen by the
+ // controller. Cancelled is hidden for a new view, but remains a first-class
+ // branch once the user restores it or selects it explicitly in a status
+ // filter; no client-only exclusion happens here.
const ganttIssues = ganttIssuesQuery.data ?? EMPTY_ISSUES;
const surfaceIssues = usesGantt
? ganttIssues
@@ -341,18 +340,12 @@ export function useIssueSurfaceData({
// 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)),
+ // in. An explicit filter wins over hidden defaults so selecting Cancelled
+ // cannot produce an empty surface. (MUL-6243)
+ return visibleStatusCategories(
+ statusFilters,
+ hiddenStatusCategories,
+ catalog,
);
}, [statusFilters, hiddenStatusCategories, catalog]);
diff --git a/packages/views/issues/utils/sort-direction.test.ts b/packages/views/issues/utils/sort-direction.test.ts
new file mode 100644
index 0000000000..fd95226abf
--- /dev/null
+++ b/packages/views/issues/utils/sort-direction.test.ts
@@ -0,0 +1,19 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { sortDirectionLabelKey } from "./sort-direction";
+
+describe("sortDirectionLabelKey", () => {
+ it("describes date and priority order in user terms", () => {
+ expect(sortDirectionLabelKey("created_at", "desc")).toBe("newest_first");
+ expect(sortDirectionLabelKey("due_date", "asc")).toBe("earliest_first");
+ expect(sortDirectionLabelKey("priority", "asc")).toBe(
+ "highest_priority_first",
+ );
+ });
+
+ it("falls back to generic direction for a custom property", () => {
+ expect(sortDirectionLabelKey("property:score", "desc")).toBe(
+ "descending_title",
+ );
+ });
+});
diff --git a/packages/views/issues/utils/sort-direction.ts b/packages/views/issues/utils/sort-direction.ts
new file mode 100644
index 0000000000..cc92049304
--- /dev/null
+++ b/packages/views/issues/utils/sort-direction.ts
@@ -0,0 +1,45 @@
+import type {
+ SortDirection,
+ SortField,
+} from "@multica/core/issues/stores/view-store";
+
+export type SortDirectionLabelKey =
+ | "ascending_title"
+ | "descending_title"
+ | "newest_first"
+ | "oldest_first"
+ | "highest_priority_first"
+ | "lowest_priority_first"
+ | "earliest_first"
+ | "latest_first"
+ | "workflow_order"
+ | "reverse_workflow_order"
+ | "alphabetical_order"
+ | "reverse_alphabetical_order";
+
+/** Human meaning for a direction, rather than an unexplained arrow. */
+export function sortDirectionLabelKey(
+ field: SortField,
+ direction: SortDirection,
+): SortDirectionLabelKey {
+ if (field === "created_at" || field === "updated_at") {
+ return direction === "desc" ? "newest_first" : "oldest_first";
+ }
+ if (field === "start_date" || field === "due_date") {
+ return direction === "asc" ? "earliest_first" : "latest_first";
+ }
+ if (field === "priority") {
+ return direction === "asc"
+ ? "highest_priority_first"
+ : "lowest_priority_first";
+ }
+ if (field === "status") {
+ return direction === "asc" ? "workflow_order" : "reverse_workflow_order";
+ }
+ if (field === "title") {
+ return direction === "asc"
+ ? "alphabetical_order"
+ : "reverse_alphabetical_order";
+ }
+ return direction === "asc" ? "ascending_title" : "descending_title";
+}
diff --git a/packages/views/issues/utils/sort.test.ts b/packages/views/issues/utils/sort.test.ts
index 3fb8dac78b..4dd151d834 100644
--- a/packages/views/issues/utils/sort.test.ts
+++ b/packages/views/issues/utils/sort.test.ts
@@ -12,6 +12,19 @@ function issueWith(id: string, value?: number | string, position = 0): Issue {
} as unknown as Issue;
}
+function staticIssue(id: string, overrides: Partial<Issue> = {}): Issue {
+ return {
+ id,
+ title: id,
+ status: "todo",
+ priority: "none",
+ position: 0,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+ } as Issue;
+}
+
describe("sortIssues property sorts", () => {
it("sorts number values numerically, missing values last", () => {
const sorted = sortIssues(
@@ -48,4 +61,53 @@ describe("sortIssues property sorts", () => {
);
expect(sorted.map((i) => i.id)).toEqual(["a", "b"]);
});
+
+ it("keeps manual position ascending even with a stale desc direction", () => {
+ const sorted = sortIssues(
+ [issueWith("b", undefined, 2), issueWith("a", undefined, 1)],
+ "position",
+ "desc",
+ );
+ expect(sorted.map((i) => i.id)).toEqual(["a", "b"]);
+ });
+
+ it("sorts updated timestamps newest first", () => {
+ const sorted = sortIssues(
+ [
+ staticIssue("older", { updated_at: "2026-01-01T00:00:00Z" }),
+ staticIssue("newer", { updated_at: "2026-02-01T00:00:00Z" }),
+ ],
+ "updated_at",
+ "desc",
+ );
+ expect(sorted.map((i) => i.id)).toEqual(["newer", "older"]);
+ });
+
+ it("sorts custom statuses by their effective category", () => {
+ const sorted = sortIssues(
+ [
+ staticIssue("done", { status: "done" }),
+ staticIssue("blocked", {
+ status: "waiting_on_vendor",
+ status_category: "blocked",
+ }),
+ ],
+ "status",
+ "asc",
+ );
+ expect(sorted.map((i) => i.id)).toEqual(["blocked", "done"]);
+ });
+
+ it("keeps missing dates last in descending order", () => {
+ const sorted = sortIssues(
+ [
+ staticIssue("missing", { due_date: null }),
+ staticIssue("earlier", { due_date: "2026-01-01" }),
+ staticIssue("later", { due_date: "2026-02-01" }),
+ ],
+ "due_date",
+ "desc",
+ );
+ expect(sorted.map((i) => i.id)).toEqual(["later", "earlier", "missing"]);
+ });
});
diff --git a/packages/views/issues/utils/sort.ts b/packages/views/issues/utils/sort.ts
index 9b6c574a01..337bc33cbe 100644
--- a/packages/views/issues/utils/sort.ts
+++ b/packages/views/issues/utils/sort.ts
@@ -1,11 +1,27 @@
import type { Issue } from "@multica/core/types";
-import { PRIORITY_ORDER } from "@multica/core/issues/config";
+import { issueColumnCategory } from "@multica/core/issues";
+import { PRIORITY_ORDER, STATUS_ORDER } from "@multica/core/issues/config";
import type { SortField, SortDirection } from "@multica/core/issues/stores/view-store";
import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";
const PRIORITY_RANK: Record<string, number> = Object.fromEntries(
PRIORITY_ORDER.map((p, i) => [p, i])
);
+const STATUS_RANK: Record<string, number> = Object.fromEntries(
+ STATUS_ORDER.map((status, index) => [status, index]),
+);
+
+function compareOptionalDate(
+ a: string | null | undefined,
+ b: string | null | undefined,
+ direction: SortDirection,
+): number {
+ if (!a && !b) return 0;
+ if (!a) return 1;
+ if (!b) return -1;
+ const dir = direction === "desc" ? -1 : 1;
+ return dir * (new Date(a).getTime() - new Date(b).getTime());
+}
export function sortIssues(
issues: Issue[],
@@ -33,39 +49,38 @@ export function sortIssues(
});
}
- const sorted = issues.toSorted((a, b) => {
+ const dir = direction === "desc" ? -1 : 1;
+ return issues.toSorted((a, b) => {
switch (field) {
case "priority":
- return (
+ return dir * (
(PRIORITY_RANK[a.priority] ?? 99) -
(PRIORITY_RANK[b.priority] ?? 99)
);
- case "start_date": {
- if (!a.start_date && !b.start_date) return 0;
- if (!a.start_date) return 1;
- if (!b.start_date) return -1;
- return (
- new Date(a.start_date).getTime() - new Date(b.start_date).getTime()
+ case "status":
+ return dir * (
+ (STATUS_RANK[issueColumnCategory(a)] ?? STATUS_ORDER.length) -
+ (STATUS_RANK[issueColumnCategory(b)] ?? STATUS_ORDER.length)
);
- }
- case "due_date": {
- if (!a.due_date && !b.due_date) return 0;
- if (!a.due_date) return 1;
- if (!b.due_date) return -1;
- return (
- new Date(a.due_date).getTime() - new Date(b.due_date).getTime()
- );
- }
+ case "start_date":
+ return compareOptionalDate(a.start_date, b.start_date, direction);
+ case "due_date":
+ return compareOptionalDate(a.due_date, b.due_date, direction);
case "created_at":
- return (
+ return dir * (
new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
);
+ case "updated_at":
+ return dir * (
+ new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime()
+ );
case "title":
- return a.title.localeCompare(b.title);
+ return dir * a.title.localeCompare(b.title);
case "position":
default:
+ // Manual order is user-defined and always ascending. The server also
+ // ignores direction for this field.
return a.position - b.position;
}
});
- return direction === "desc" ? sorted.reverse() : sorted;
}
diff --git a/packages/views/issues/utils/status-options.test.tsx b/packages/views/issues/utils/status-options.test.tsx
index dfaffa55ee..9958b46636 100644
--- a/packages/views/issues/utils/status-options.test.tsx
+++ b/packages/views/issues/utils/status-options.test.tsx
@@ -72,8 +72,8 @@ describe("useStatusOptions", () => {
"todo",
"in_progress",
"in_review",
- "done",
"blocked",
+ "done",
"cancelled",
]);
});
@@ -91,8 +91,8 @@ describe("useStatusOptions", () => {
"in_progress",
"in_review",
"qa",
- "done",
"blocked",
+ "done",
"cancelled",
]);
});
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 0dfe540fc1..7725555998 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -184,6 +184,16 @@
"card_properties_section": "Card properties",
"ascending_title": "Ascending",
"descending_title": "Descending",
+ "newest_first": "Newest first",
+ "oldest_first": "Oldest first",
+ "highest_priority_first": "Highest priority first",
+ "lowest_priority_first": "Lowest priority first",
+ "earliest_first": "Earliest first",
+ "latest_first": "Latest first",
+ "workflow_order": "Workflow order",
+ "reverse_workflow_order": "Reverse workflow order",
+ "alphabetical_order": "A to Z",
+ "reverse_alphabetical_order": "Z to A",
"group_status": "Status",
"group_assignee": "Assignee",
"group_parent": "Parent issue",
@@ -338,7 +348,8 @@
"empty_column": "No issues",
"empty_grouping": "No matching issues",
"no_value": "No value",
- "ordered_by": "Board ordered by {{field}}"
+ "ordered_by": "Board ordered by {{field}}",
+ "manual_reorder_hint": "Switch to Manual ordering to rearrange issues within a column."
},
"detail": {
"not_found": "This issue does not exist or has been deleted in this workspace.",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 54cc916978..8e377631ef 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -180,6 +180,16 @@
"card_properties_section": "カードのプロパティ",
"ascending_title": "昇順",
"descending_title": "降順",
+ "newest_first": "新しい順",
+ "oldest_first": "古い順",
+ "highest_priority_first": "優先度の高い順",
+ "lowest_priority_first": "優先度の低い順",
+ "earliest_first": "日付の早い順",
+ "latest_first": "日付の遅い順",
+ "workflow_order": "ワークフロー順",
+ "reverse_workflow_order": "ワークフローの逆順",
+ "alphabetical_order": "A から Z",
+ "reverse_alphabetical_order": "Z から A",
"group_status": "ステータス",
"group_assignee": "担当者",
"group_parent": "親タスク",
@@ -334,7 +344,8 @@
"empty_column": "タスクなし",
"empty_grouping": "一致するタスクがありません",
"no_value": "値なし",
- "ordered_by": "{{field}} 順に並べたボード"
+ "ordered_by": "{{field}} 順に並べたボード",
+ "manual_reorder_hint": "列内の順序を変更するには、並び順を「手動」に切り替えてください。"
},
"detail": {
"not_found": "このタスクはこのワークスペースに存在しないか、削除されています。",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 011263b399..ca6f7a1fda 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -180,6 +180,16 @@
"card_properties_section": "카드 속성",
"ascending_title": "오름차순",
"descending_title": "내림차순",
+ "newest_first": "최신순",
+ "oldest_first": "오래된순",
+ "highest_priority_first": "높은 우선순위부터",
+ "lowest_priority_first": "낮은 우선순위부터",
+ "earliest_first": "빠른 날짜부터",
+ "latest_first": "늦은 날짜부터",
+ "workflow_order": "워크플로 순서",
+ "reverse_workflow_order": "워크플로 역순",
+ "alphabetical_order": "A에서 Z",
+ "reverse_alphabetical_order": "Z에서 A",
"group_status": "상태",
"group_assignee": "담당자",
"group_parent": "상위 태스크",
@@ -334,7 +344,8 @@
"empty_column": "태스크 없음",
"empty_grouping": "일치하는 태스크가 없습니다",
"no_value": "값 없음",
- "ordered_by": "{{field}} 기준으로 정렬된 보드"
+ "ordered_by": "{{field}} 기준으로 정렬된 보드",
+ "manual_reorder_hint": "열 안의 순서를 바꾸려면 정렬을 '수동'으로 전환하세요."
},
"detail": {
"not_found": "이 워크스페이스에 해당 태스크가 없거나 삭제되었습니다.",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index cc18261f5a..bb60771583 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -180,6 +180,16 @@
"card_properties_section": "卡片属性",
"ascending_title": "升序",
"descending_title": "降序",
+ "newest_first": "最新优先",
+ "oldest_first": "最早优先",
+ "highest_priority_first": "最高优先级优先",
+ "lowest_priority_first": "最低优先级优先",
+ "earliest_first": "最早日期优先",
+ "latest_first": "最晚日期优先",
+ "workflow_order": "按工作流顺序",
+ "reverse_workflow_order": "按工作流倒序",
+ "alphabetical_order": "A 到 Z",
+ "reverse_alphabetical_order": "Z 到 A",
"group_status": "状态",
"group_assignee": "负责人",
"group_parent": "父级任务",
@@ -334,7 +344,8 @@
"empty_column": "无任务",
"empty_grouping": "没有匹配的任务",
"no_value": "未设置",
- "ordered_by": "按{{field}}排序"
+ "ordered_by": "按{{field}}排序",
+ "manual_reorder_hint": "切换到“手动”排序后,才能调整同一列内的顺序。"
},
"detail": {
"not_found": "这个任务不存在或已在该工作区被删除。",
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 99121bfd4d..07384cc9db 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -121,6 +121,26 @@ var validIssuePriorities = []string{"urgent", "high", "medium", "low", "none"}
// workspaces that have no custom statuses.
var validIssueStatuses = issuestatus.Canonical()
+// Status sort follows the board's category order and resolves custom keys to
+// their effective category with one catalog read plus a parameterized CASE.
+// Keeping the indexed column bare avoids the per-row issue_effective_status()
+// call that would otherwise turn a bounded page into a workspace scan.
+func (h *Handler) issueStatusSortExpression(
+ ctx context.Context,
+ workspaceID pgtype.UUID,
+ addArg func(any) string,
+) (string, error) {
+ customKeys, err := issuestatus.CustomKeyCategories(
+ ctx,
+ h.issueStatusCatalog(),
+ workspaceID,
+ )
+ if err != nil {
+ return "", err
+ }
+ return statusOrderExpression(statusCategoryExpr(customKeys, addArg)), nil
+}
+
// resolveIssueStatusKey checks a status against the workspace's catalog and
// returns the CANONICAL key to store. This is the application-layer replacement
// for the enum CHECK that migration 337 dropped, so every write path must route
@@ -1290,6 +1310,7 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
sortCol := "position"
sortIsExpr := false
sortIsProperty := false
+ sortByStatus := false
if s := r.URL.Query().Get("sort"); s != "" {
switch s {
case "position", "title", "created_at", "updated_at", "start_date", "due_date":
@@ -1297,8 +1318,9 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
case "last_activity":
sortCol = "last_activity_at"
case "status":
- sortCol = "CASE i.status 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"
+ sortCol = "status"
sortIsExpr = true
+ sortByStatus = true
case "priority":
sortCol = "CASE i.priority WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END"
sortIsExpr = true
@@ -1352,6 +1374,15 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
args = append(args, v)
return "$" + strconv.Itoa(len(args))
}
+ if sortByStatus {
+ var err error
+ sortCol, err = h.issueStatusSortExpression(r.Context(), wsUUID, addArg)
+ if err != nil {
+ slog.Warn("resolve status sort failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to resolve sort")
+ return
+ }
+ }
if len(statusCategoriesFilter) > 0 {
// Expanded to concrete status keys rather than filtered through
@@ -2065,7 +2096,13 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {
case "last_activity":
sortCol = "last_activity_at"
case "status":
- sortCol = "CASE i.status 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"
+ var err error
+ sortCol, err = h.issueStatusSortExpression(r.Context(), wsUUID, addArg)
+ if err != nil {
+ slog.Warn("resolve grouped status sort failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to resolve sort")
+ return
+ }
sortIsExpr = true
case "priority":
sortCol = "CASE i.priority WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END"
diff --git a/server/internal/handler/issue_status_test.go b/server/internal/handler/issue_status_test.go
index 424b96a541..79f6808c1a 100644
--- a/server/internal/handler/issue_status_test.go
+++ b/server/internal/handler/issue_status_test.go
@@ -89,10 +89,8 @@ func TestEnsureIsIdempotent(t *testing.T) {
}
}
-// TestCatalogOrderMatchesHistoricalStatusOrder pins the default board order.
-// A workspace with no custom statuses must list exactly as it did before this
-// feature, or every existing user's board silently rearranges.
-func TestCatalogOrderMatchesHistoricalStatusOrder(t *testing.T) {
+// TestCatalogOrderMatchesBoardStatusOrder pins the default board order.
+func TestCatalogOrderMatchesBoardStatusOrder(t *testing.T) {
seedTestCatalog(t)
entries, err := testHandler.Queries.ListIssueStatusEntries(context.Background(), db.ListIssueStatusEntriesParams{
WorkspaceID: parseUUID(testWorkspaceID),
@@ -107,7 +105,7 @@ func TestCatalogOrderMatchesHistoricalStatusOrder(t *testing.T) {
gotSystem = append(gotSystem, e.Key)
}
}
- want := []string{"backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"}
+ want := []string{"backlog", "todo", "in_progress", "in_review", "blocked", "done", "cancelled"}
for i := range want {
if i >= len(gotSystem) || gotSystem[i] != want[i] {
t.Fatalf("built-in order = %v, want %v (frontend STATUS_ORDER)", gotSystem, want)
diff --git a/server/internal/handler/issue_table_group.go b/server/internal/handler/issue_table_group.go
index a844583623..c4023851ca 100644
--- a/server/internal/handler/issue_table_group.go
+++ b/server/internal/handler/issue_table_group.go
@@ -87,8 +87,16 @@ type resolvedIssueTableGroup struct {
// 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 {
+ return statusValueCategoryExpr("i.status", customKeys, addArg)
+}
+
+func statusValueCategoryExpr(
+ valueExpr string,
+ customKeys map[string]string,
+ addArg func(any) string,
+) string {
if len(customKeys) == 0 {
- return "i.status"
+ return valueExpr
}
keys := make([]string, 0, len(customKeys))
for key := range customKeys {
@@ -96,14 +104,18 @@ func statusCategoryExpr(customKeys map[string]string, addArg func(any) string) s
}
sort.Strings(keys)
var b strings.Builder
- b.WriteString("CASE i.status")
+ b.WriteString("CASE " + valueExpr)
for _, key := range keys {
fmt.Fprintf(&b, " WHEN %s::text THEN %s::text", addArg(key), addArg(customKeys[key]))
}
- b.WriteString(" ELSE i.status END")
+ b.WriteString(" ELSE " + valueExpr + " END")
return b.String()
}
+func statusOrderExpression(categoryExpr string) string {
+ return "CASE " + categoryExpr + " WHEN 'backlog' THEN 0 WHEN 'todo' THEN 1 WHEN 'in_progress' THEN 2 WHEN 'in_review' THEN 3 WHEN 'blocked' THEN 4 WHEN 'done' THEN 5 WHEN 'cancelled' THEN 6 ELSE 7 END"
+}
+
// 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
@@ -167,7 +179,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
+ customKeys, err := issuestatus.CustomKeyCategories(
+ r.Context(),
+ h.issueStatusCatalog(),
+ workspaceID,
+ )
+ if err != nil {
+ slog.Warn("resolve status group order failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to resolve table group")
+ return resolvedIssueTableGroup{}, false
+ }
+ return resolvedIssueTableGroup{
+ kind: "status",
+ groupExpr: "i.status",
+ statusCustomKeys: customKeys,
+ }, 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
@@ -361,7 +387,9 @@ func (group resolvedIssueTableGroup) orderExpression(addArg func(any) string) st
}
switch group.kind {
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"
+ return statusOrderExpression(
+ statusValueCategoryExpr("group_value", group.statusCustomKeys, addArg),
+ )
case "assignee":
return "CASE split_part(group_value, ':', 1) WHEN 'member' THEN 0 WHEN 'agent' THEN 1 WHEN 'squad' THEN 2 ELSE 3 END"
case "project":
diff --git a/server/internal/handler/issue_table_query_test.go b/server/internal/handler/issue_table_query_test.go
index e5f664f879..c7a621706e 100644
--- a/server/internal/handler/issue_table_query_test.go
+++ b/server/internal/handler/issue_table_query_test.go
@@ -467,8 +467,9 @@ func TestIssueTableLastActivityDefaultsToIndexedOrder(t *testing.T) {
sort, ok := testHandler.issueTableOrderBy(
w,
newRequest(http.MethodPost, "/api/issues/table/rows", nil),
- testWorkspaceID,
+ parseUUID(testWorkspaceID),
issueTableSortRequest{Field: "last_activity"},
+ func(any) string { return "$1" },
)
if !ok {
t.Fatalf("last_activity sort rejected: status=%d body=%s", w.Code, w.Body.String())
diff --git a/server/internal/handler/issue_table_rows.go b/server/internal/handler/issue_table_rows.go
index 6bda9b8ab9..72aa2125f2 100644
--- a/server/internal/handler/issue_table_rows.go
+++ b/server/internal/handler/issue_table_rows.go
@@ -127,7 +127,13 @@ func (sort resolvedIssueTableSort) cursorPredicate(w http.ResponseWriter, cursor
return predicate, true
}
-func (h *Handler) issueTableOrderBy(w http.ResponseWriter, r *http.Request, workspaceID string, sortRequest issueTableSortRequest) (resolvedIssueTableSort, bool) {
+func (h *Handler) issueTableOrderBy(
+ w http.ResponseWriter,
+ r *http.Request,
+ workspaceID pgtype.UUID,
+ sortRequest issueTableSortRequest,
+ addArg func(any) string,
+) (resolvedIssueTableSort, bool) {
sortField := strings.TrimSpace(sortRequest.Field)
if sortField == "" {
sortField = "position"
@@ -155,13 +161,19 @@ func (h *Handler) issueTableOrderBy(w http.ResponseWriter, r *http.Request, work
resolved.castType = "date"
resolved.nullsLast = true
case "status":
- resolved.expression = "CASE i.status 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"
+ expr, err := h.issueStatusSortExpression(r.Context(), workspaceID, addArg)
+ if err != nil {
+ slog.Warn("resolve table status sort failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeIssueTableQueryFailure(w, r, "failed to resolve table sort")
+ return resolvedIssueTableSort{}, false
+ }
+ resolved.expression = expr
resolved.castType = "integer"
case "priority":
resolved.expression = "CASE i.priority WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END"
resolved.castType = "integer"
default:
- expr, handled, err := h.propertySortExpr(r, workspaceID, sortField)
+ expr, handled, err := h.propertySortExpr(r, util.UUIDToString(workspaceID), sortField)
if !handled {
writeError(w, http.StatusBadRequest, "invalid query.sort.field")
return resolvedIssueTableSort{}, false
@@ -274,16 +286,21 @@ func (h *Handler) ListIssueTableRows(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- resolvedSort, ok := h.issueTableOrderBy(w, r, util.UUIDToString(compiled.workspaceID), request.Query.Sort)
- if !ok {
- return
- }
-
args := append([]any(nil), compiled.args...)
addArg := func(value any) string {
args = append(args, value)
return "$" + strconv.Itoa(len(args))
}
+ resolvedSort, ok := h.issueTableOrderBy(
+ w,
+ r,
+ compiled.workspaceID,
+ request.Query.Sort,
+ addArg,
+ )
+ if !ok {
+ return
+ }
predicateKey := ""
if groupKey != nil {
predicateKey = *groupKey
diff --git a/server/internal/handler/issue_table_status_category_test.go b/server/internal/handler/issue_table_status_category_test.go
index 4ea2105895..3dfe5258b5 100644
--- a/server/internal/handler/issue_table_status_category_test.go
+++ b/server/internal/handler/issue_table_status_category_test.go
@@ -385,10 +385,10 @@ func TestIssueTableCompoundStatusCategoryReadsCatalogOncePerRequest(t *testing.T
}
}
-// 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) {
+// Plain status groups keep their concrete keys, but their order still follows
+// each key's effective category. Resolve that map once per request rather than
+// running issue_effective_status() for every row or doing a second catalog read.
+func TestIssueTableStatusGroupingReadsCatalogOnce(t *testing.T) {
projectID, _ := seedStatusCategoryFixture(t)
counter := withCountingCatalog(t)
@@ -401,8 +401,8 @@ func TestIssueTableStatusGroupingReadsNoCatalog(t *testing.T) {
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",
+ if counter.entryReads != 1 || counter.categoryReads != 0 {
+ t.Fatalf("plain status grouping read the catalog (%d entry, %d category), want 1 entry and 0 category",
counter.entryReads, counter.categoryReads)
}
}
@@ -414,6 +414,22 @@ func TestIssueTableStatusGroupingReadsNoCatalog(t *testing.T) {
// status" 500 for the entire workspace.
func TestIssueTableStatusGroupingCarriesCustomStatusGroups(t *testing.T) {
projectID, customKey := seedStatusCategoryFixture(t)
+ ctx := context.Background()
+ var cancelledNumber int
+ if err := testPool.QueryRow(ctx, `
+ UPDATE workspace
+ SET issue_counter = issue_counter + 1
+ WHERE id = $1
+ RETURNING issue_counter
+ `, testWorkspaceID).Scan(&cancelledNumber); err != nil {
+ t.Fatalf("reserve cancelled issue number: %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, 'cat-cancelled', 'cancelled', 'none', 'member', $2, 5, $3, $4)
+ `, testWorkspaceID, testUserID, cancelledNumber, projectID); err != nil {
+ t.Fatalf("seed cancelled issue: %v", err)
+ }
w := httptest.NewRecorder()
testHandler.ListIssueTableGroups(w, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{
@@ -439,6 +455,16 @@ func TestIssueTableStatusGroupingCarriesCustomStatusGroups(t *testing.T) {
if counts["in_review"] != 1 {
t.Fatalf("built-in group = %d, want 1: %#v", counts["in_review"], counts)
}
+ if counts["cancelled"] != 1 {
+ t.Fatalf("cancelled group = %d, want 1: %#v", counts["cancelled"], counts)
+ }
+ indexes := map[string]int{}
+ for i, group := range groups.Groups {
+ indexes[group.Value.Status] = i
+ }
+ if indexes[customKey] >= indexes["cancelled"] {
+ t.Fatalf("custom in-review status sorted after cancelled: %#v", groups.Groups)
+ }
// And its group_key has to page back its own rows.
groupKey := "status:" + customKey
diff --git a/server/internal/issuestatus/issuestatus.go b/server/internal/issuestatus/issuestatus.go
index c28c698758..d30d679260 100644
--- a/server/internal/issuestatus/issuestatus.go
+++ b/server/internal/issuestatus/issuestatus.go
@@ -47,20 +47,15 @@ const (
Cancelled = "cancelled"
)
-// canonicalOrder is the historical STATUS_ORDER from the frontend's static
-// status config. Category ranking copies it verbatim so a workspace with no
-// custom statuses sees a board and picker identical to before this feature.
-//
-// Note the order is NOT grouped by lifecycle: in_review and done sit between
-// in_progress and blocked. That is the shipped order, and reordering it to look
-// tidier would visibly rearrange every existing user's board.
+// canonicalOrder mirrors the frontend board order. Blocked precedes Done so an
+// actionable exception is not pushed beyond the completed column.
var canonicalOrder = []string{
Backlog,
Todo,
InProgress,
InReview,
- Done,
Blocked,
+ Done,
Cancelled,
}
diff --git a/server/internal/issuestatus/issuestatus_test.go b/server/internal/issuestatus/issuestatus_test.go
index d688164321..43cfab0a09 100644
--- a/server/internal/issuestatus/issuestatus_test.go
+++ b/server/internal/issuestatus/issuestatus_test.go
@@ -202,11 +202,10 @@ func TestCategoriesAndBuiltInsAreTheSameSet(t *testing.T) {
}
}
-// The display order is copied from the frontend's historical STATUS_ORDER.
-// Reordering it would visibly rearrange every existing user's board, so it is
-// pinned here rather than left to look tidy.
-func TestCategoryRankPreservesHistoricalStatusOrder(t *testing.T) {
- want := []string{"backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"}
+// The display order is shared with the frontend board and keeps actionable
+// Blocked work before the completed column.
+func TestCategoryRankMatchesBoardStatusOrder(t *testing.T) {
+ want := []string{"backlog", "todo", "in_progress", "in_review", "blocked", "done", "cancelled"}
got := Canonical()
for i := range want {
if got[i] != want[i] {
diff --git a/server/pkg/db/generated/issue_status.sql.go b/server/pkg/db/generated/issue_status.sql.go
index 3e1c9c4d27..56ab963b79 100644
--- a/server/pkg/db/generated/issue_status.sql.go
+++ b/server/pkg/db/generated/issue_status.sql.go
@@ -263,8 +263,8 @@ ORDER BY
WHEN 'todo' THEN 1
WHEN 'in_progress' THEN 2
WHEN 'in_review' THEN 3
- WHEN 'done' THEN 4
- WHEN 'blocked' THEN 5
+ WHEN 'blocked' THEN 4
+ WHEN 'done' THEN 5
WHEN 'cancelled' THEN 6
ELSE 7
END,
@@ -277,9 +277,8 @@ type ListIssueStatusEntriesParams struct {
IncludeArchived bool `json:"include_archived"`
}
-// Ordered by category rank (the historical STATUS_ORDER, so the default board
-// and picker stay pixel-identical for a workspace with no custom statuses),
-// then intra-category position, then key as a stable tiebreak.
+// Ordered by the canonical board category rank, then intra-category position,
+// then key as a stable tiebreak.
func (q *Queries) ListIssueStatusEntries(ctx context.Context, arg ListIssueStatusEntriesParams) ([]IssueStatus, error) {
rows, err := q.db.Query(ctx, listIssueStatusEntries, arg.WorkspaceID, arg.IncludeArchived)
if err != nil {
diff --git a/server/pkg/db/queries/issue_status.sql b/server/pkg/db/queries/issue_status.sql
index 21d6087e96..05e36cbf3e 100644
--- a/server/pkg/db/queries/issue_status.sql
+++ b/server/pkg/db/queries/issue_status.sql
@@ -20,9 +20,8 @@ VALUES
ON CONFLICT DO NOTHING;
-- name: ListIssueStatusEntries :many
--- Ordered by category rank (the historical STATUS_ORDER, so the default board
--- and picker stay pixel-identical for a workspace with no custom statuses),
--- then intra-category position, then key as a stable tiebreak.
+-- Ordered by the canonical board category rank, then intra-category position,
+-- then key as a stable tiebreak.
SELECT * FROM issue_status
WHERE workspace_id = sqlc.arg('workspace_id')::uuid
AND (sqlc.arg('include_archived')::bool OR archived_at IS NULL)
@@ -32,8 +31,8 @@ ORDER BY
WHEN 'todo' THEN 1
WHEN 'in_progress' THEN 2
WHEN 'in_review' THEN 3
- WHEN 'done' THEN 4
- WHEN 'blocked' THEN 5
+ WHEN 'blocked' THEN 4
+ WHEN 'done' THEN 5
WHEN 'cancelled' THEN 6
ELSE 7
END,