Skip to content

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

Go

feat(issues): server-side sort + fix drag position corruption (#3228)

Naiyuan Qing612ac8f28e05
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 8924c783cc..cb84074e5f 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -448,6 +448,8 @@ export class ApiClient {
}
if (params?.open_only) search.set("open_only", "true");
if (params?.scheduled) search.set("scheduled", "true");
+ if (params?.sort_by) search.set("sort", params.sort_by);
+ if (params?.sort_direction) search.set("direction", params.sort_direction);
const path = `/api/issues?${search}`;
const raw = await this.fetch<unknown>(path);
return parseWithFallback(raw, ListIssuesResponseSchema, EMPTY_LIST_ISSUES_RESPONSE, {
@@ -483,6 +485,8 @@ export class ApiClient {
if (params.label_ids?.length) search.set("label_ids", params.label_ids.join(","));
if (params.group_assignee_type) search.set("group_assignee_type", params.group_assignee_type);
if (params.group_assignee_id) search.set("group_assignee_id", params.group_assignee_id);
+ if (params.sort_by) search.set("sort", params.sort_by);
+ if (params.sort_direction) search.set("direction", params.sort_direction);
const raw = await this.fetch<unknown>(`/api/issues/grouped?${search}`);
return parseWithFallback(raw, GroupedIssuesResponseSchema, EMPTY_GROUPED_ISSUES_RESPONSE, {
endpoint: "GET /api/issues/grouped",
diff --git a/packages/core/issues/delete-cache.ts b/packages/core/issues/delete-cache.ts
index 64ff34c282..5955512d41 100644
--- a/packages/core/issues/delete-cache.ts
+++ b/packages/core/issues/delete-cache.ts
@@ -47,11 +47,11 @@ export function collectDeletedIssueCacheMetadata(
const detail = qc.getQueryData<Issue>(issueKeys.detail(wsId, issueId));
collectParentId(parentIssueIds, detail?.parent_issue_id);
- collectParentFromListCache(
- parentIssueIds,
- qc.getQueryData<ListIssuesCache>(issueKeys.list(wsId)),
- issueId,
- );
+ for (const [, data] of qc.getQueriesData<ListIssuesCache>({
+ queryKey: issueKeys.list(wsId),
+ })) {
+ collectParentFromListCache(parentIssueIds, data, issueId);
+ }
for (const [, data] of qc.getQueriesData<ListIssuesCache>({
queryKey: issueKeys.myAll(wsId),
@@ -76,9 +76,13 @@ export function pruneDeletedIssueFromListCaches(
wsId: string,
issueId: string,
) {
- qc.setQueryData<ListIssuesCache>(issueKeys.list(wsId), (old) =>
- old ? removeIssueFromBuckets(old, issueId) : old,
- );
+ for (const [key] of qc.getQueriesData<ListIssuesCache>({
+ queryKey: issueKeys.list(wsId),
+ })) {
+ qc.setQueryData<ListIssuesCache>(key, (old) =>
+ old ? removeIssueFromBuckets(old, issueId) : old,
+ );
+ }
for (const [key] of qc.getQueriesData<ListIssuesCache>({
queryKey: issueKeys.myAll(wsId),
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index b17a01a4c8..33e2fc2108 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -67,17 +67,18 @@ export function useLoadMoreByStatus(
const wsId = useWorkspaceId();
const [isLoading, setIsLoading] = useState(false);
- const queryKey = myIssues
+ const prefixKey = myIssues
? issueKeys.myList(wsId, myIssues.scope, myIssues.filter)
: issueKeys.list(wsId);
- const cache = qc.getQueryData<ListIssuesCache>(queryKey);
+ const queries = qc.getQueriesData<ListIssuesCache>({ queryKey: prefixKey });
+ const [activeKey, cache] = queries[0] ?? [undefined, undefined];
const bucket = cache?.byStatus[status];
const loaded = bucket?.issues.length ?? 0;
const total = bucket?.total ?? 0;
const hasMore = loaded < total;
const loadMore = useCallback(async () => {
- if (isLoading || !hasMore) return;
+ if (isLoading || !hasMore || !activeKey) return;
setIsLoading(true);
try {
const res = await api.listIssues({
@@ -86,7 +87,7 @@ export function useLoadMoreByStatus(
offset: loaded,
...myIssues?.filter,
});
- qc.setQueryData<ListIssuesCache>(queryKey, (old) => {
+ qc.setQueryData<ListIssuesCache>(activeKey, (old) => {
if (!old) return old;
const prev = getBucket(old, status);
const existingIds = new Set(prev.issues.map((i) => i.id));
@@ -99,7 +100,7 @@ export function useLoadMoreByStatus(
} finally {
setIsLoading(false);
}
- }, [qc, queryKey, status, loaded, hasMore, isLoading, myIssues?.filter]);
+ }, [qc, activeKey, status, loaded, hasMore, isLoading, myIssues?.filter]);
return { loadMore, hasMore, isLoading, total };
}
@@ -166,9 +167,9 @@ export function useCreateIssue() {
return useMutation({
mutationFn: (data: CreateIssueRequest) => api.createIssue(data),
onSuccess: (newIssue) => {
- qc.setQueryData<ListIssuesCache>(issueKeys.list(wsId), (old) =>
- old ? addIssueToBuckets(old, newIssue) : old,
- );
+ for (const [key, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) })) {
+ if (data) qc.setQueryData<ListIssuesCache>(key, addIssueToBuckets(data, newIssue));
+ }
// Surface the just-created issue in cmd+k's Recent list without
// requiring the user to open it first.
useRecentIssuesStore.getState().recordVisit(wsId, newIssue.id);
@@ -199,7 +200,8 @@ export function useUpdateIssue() {
// yield to the event loop, letting @dnd-kit reset its visual state
// before the optimistic update lands.
qc.cancelQueries({ queryKey: issueKeys.list(wsId) });
- const prevList = qc.getQueryData<ListIssuesCache>(issueKeys.list(wsId));
+ const prevLists = qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) });
+ const firstListData = prevLists[0]?.[1];
const prevDetail = qc.getQueryData<Issue>(issueKeys.detail(wsId, id));
// Resolve parent_issue_id from the freshest source so we can keep the
@@ -209,7 +211,7 @@ export function useUpdateIssue() {
// child may live only there, not in detail/list.
let parentId: string | null =
prevDetail?.parent_issue_id ??
- (prevList ? findIssueLocation(prevList, id)?.issue.parent_issue_id : null) ??
+ (firstListData ? findIssueLocation(firstListData, id)?.issue.parent_issue_id : null) ??
null;
if (!parentId) {
const childrenCaches = qc.getQueriesData<Issue[]>({
@@ -228,9 +230,9 @@ export function useUpdateIssue() {
? qc.getQueryData<Issue[]>(issueKeys.children(wsId, parentId))
: undefined;
- qc.setQueryData<ListIssuesCache>(issueKeys.list(wsId), (old) =>
- old ? patchIssueInBuckets(old, id, data) : old,
- );
+ for (const [key, cached] of prevLists) {
+ if (cached) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(cached, id, data));
+ }
qc.setQueryData<Issue>(issueKeys.detail(wsId, id), (old) =>
old ? { ...old, ...data } : old,
);
@@ -241,10 +243,14 @@ export function useUpdateIssue() {
old?.map((c) => (c.id === id ? { ...c, ...data } : c)),
);
}
- return { prevList, prevDetail, prevChildren, parentId, id };
+ return { prevLists, prevDetail, prevChildren, parentId, id };
},
onError: (_err, _vars, ctx) => {
- if (ctx?.prevList) qc.setQueryData(issueKeys.list(wsId), ctx.prevList);
+ if (ctx?.prevLists) {
+ for (const [key, snapshot] of ctx.prevLists) {
+ qc.setQueryData(key, snapshot);
+ }
+ }
if (ctx?.prevDetail)
qc.setQueryData(issueKeys.detail(wsId, ctx.id), ctx.prevDetail);
if (ctx?.parentId && ctx.prevChildren !== undefined) {
@@ -302,7 +308,7 @@ export function useDeleteIssue() {
qc.cancelQueries({ queryKey: issueKeys.children(wsId, parentId) }),
),
);
- const prevList = qc.getQueryData<ListIssuesCache>(issueKeys.list(wsId));
+ const prevLists = qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) });
const prevMyLists = qc.getQueriesData<ListIssuesCache>({
queryKey: issueKeys.myAll(wsId),
});
@@ -318,10 +324,14 @@ export function useDeleteIssue() {
pruneDeletedIssueFromListCaches(qc, wsId, id);
pruneDeletedIssueFromParentChildrenCaches(qc, wsId, id, metadata);
qc.removeQueries({ queryKey: issueKeys.detail(wsId, id) });
- return { id, metadata, prevList, prevMyLists, prevDetail, prevChildren };
+ return { id, metadata, prevLists, prevMyLists, prevDetail, prevChildren };
},
onError: (_err, _id, ctx) => {
- if (ctx?.prevList) qc.setQueryData(issueKeys.list(wsId), ctx.prevList);
+ if (ctx?.prevLists) {
+ for (const [key, snapshot] of ctx.prevLists) {
+ qc.setQueryData(key, snapshot);
+ }
+ }
if (ctx?.prevMyLists) {
for (const [key, snapshot] of ctx.prevMyLists) {
qc.setQueryData(key, snapshot);
@@ -362,13 +372,13 @@ export function useBatchUpdateIssues() {
}) => api.batchUpdateIssues(ids, updates),
onMutate: async ({ ids, updates }) => {
await qc.cancelQueries({ queryKey: issueKeys.list(wsId) });
- const prevList = qc.getQueryData<ListIssuesCache>(issueKeys.list(wsId));
- qc.setQueryData<ListIssuesCache>(issueKeys.list(wsId), (old) => {
- if (!old) return old;
- let next = old;
+ const prevLists = qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) });
+ for (const [key, cached] of prevLists) {
+ if (!cached) continue;
+ let next = cached;
for (const id of ids) next = patchIssueInBuckets(next, id, updates);
- return next;
- });
+ qc.setQueryData<ListIssuesCache>(key, next);
+ }
// Mirror the optimistic patch into any loaded children cache so
// sub-issue rows on a parent's detail page reflect the change too.
@@ -389,10 +399,14 @@ export function useBatchUpdateIssues() {
);
}
- return { prevList, prevChildren, affectedParentIds };
+ return { prevLists, prevChildren, affectedParentIds };
},
onError: (_err, _vars, ctx) => {
- if (ctx?.prevList) qc.setQueryData(issueKeys.list(wsId), ctx.prevList);
+ if (ctx?.prevLists) {
+ for (const [key, snapshot] of ctx.prevLists) {
+ qc.setQueryData(key, snapshot);
+ }
+ }
if (ctx?.prevChildren) {
for (const [parentId, snapshot] of ctx.prevChildren) {
qc.setQueryData(issueKeys.children(wsId, parentId), snapshot);
@@ -443,7 +457,7 @@ export function useBatchDeleteIssues() {
qc.cancelQueries({ queryKey: issueKeys.children(wsId, parentId) }),
),
);
- const prevList = qc.getQueryData<ListIssuesCache>(issueKeys.list(wsId));
+ const prevLists = qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) });
const prevMyLists = qc.getQueriesData<ListIssuesCache>({
queryKey: issueKeys.myAll(wsId),
});
@@ -462,10 +476,14 @@ export function useBatchDeleteIssues() {
pruneDeletedIssueFromParentChildrenCaches(qc, wsId, id, metadata);
}
}
- return { prevList, prevMyLists, prevChildren, parentIssueIds, metadataById };
+ return { prevLists, prevMyLists, prevChildren, parentIssueIds, metadataById };
},
onError: (_err, _ids, ctx) => {
- if (ctx?.prevList) qc.setQueryData(issueKeys.list(wsId), ctx.prevList);
+ if (ctx?.prevLists) {
+ for (const [key, snapshot] of ctx.prevLists) {
+ qc.setQueryData(key, snapshot);
+ }
+ }
if (ctx?.prevMyLists) {
for (const [key, snapshot] of ctx.prevMyLists) {
qc.setQueryData(key, snapshot);
@@ -485,7 +503,11 @@ export function useBatchDeleteIssues() {
return;
}
- if (ctx?.prevList) qc.setQueryData(issueKeys.list(wsId), ctx.prevList);
+ if (ctx?.prevLists) {
+ for (const [key, snapshot] of ctx.prevLists) {
+ qc.setQueryData(key, snapshot);
+ }
+ }
if (ctx?.prevMyLists) {
for (const [key, snapshot] of ctx.prevMyLists) {
qc.setQueryData(key, snapshot);
diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.ts
index f1d96bc242..a8504c05a4 100644
--- a/packages/core/issues/queries.ts
+++ b/packages/core/issues/queries.ts
@@ -1,4 +1,4 @@
-import { queryOptions } from "@tanstack/react-query";
+import { keepPreviousData, queryOptions } from "@tanstack/react-query";
import { api } from "../api";
import type {
GroupedIssuesResponse,
@@ -10,18 +10,30 @@ import type {
} from "../types";
import { BOARD_STATUSES } from "./config";
+export interface IssueSortParam {
+ sort_by?: ListIssuesParams["sort_by"];
+ sort_direction?: ListIssuesParams["sort_direction"];
+}
+
export const issueKeys = {
all: (wsId: string) => ["issues", wsId] as const,
+ /** PREFIX for invalidation — no sort. */
list: (wsId: string) => [...issueKeys.all(wsId), "list"] as const,
+ /** FULL KEY for queryOptions — includes sort. */
+ listSorted: (wsId: string, sort?: IssueSortParam) =>
+ [...issueKeys.list(wsId), sort ?? {}] as const,
assigneeGroupsAll: (wsId: string) =>
[...issueKeys.all(wsId), "assignee-groups"] as const,
assigneeGroups: (wsId: string, filter: AssigneeGroupedIssuesFilter) =>
[...issueKeys.assigneeGroupsAll(wsId), filter] as const,
/** All "my issues" queries — use for bulk invalidation. */
myAll: (wsId: string) => [...issueKeys.all(wsId), "my"] as const,
- /** Per-scope "my issues" list with filter identity baked into the key. */
+ /** PREFIX for per-scope invalidation — no sort. */
myList: (wsId: string, scope: string, filter: MyIssuesFilter) =>
[...issueKeys.myAll(wsId), scope, filter] as const,
+ /** FULL KEY for queryOptions — includes sort. */
+ myListSorted: (wsId: string, scope: string, filter: MyIssuesFilter, sort?: IssueSortParam) =>
+ [...issueKeys.myList(wsId, scope, filter), sort ?? {}] as const,
myAssigneeGroupsAll: (wsId: string) =>
[...issueKeys.myAll(wsId), "assignee-groups"] as const,
myAssigneeGroups: (
@@ -91,10 +103,10 @@ export function flattenIssueBuckets(data: ListIssuesCache) {
return out;
}
-async function fetchFirstPages(filter: MyIssuesFilter = {}): Promise<ListIssuesCache> {
+async function fetchFirstPages(filter: MyIssuesFilter = {}, sort?: IssueSortParam): Promise<ListIssuesCache> {
const responses = await Promise.all(
PAGINATED_STATUSES.map((status) =>
- api.listIssues({ status, limit: ISSUE_PAGE_SIZE, offset: 0, ...filter }),
+ api.listIssues({ status, limit: ISSUE_PAGE_SIZE, offset: 0, ...sort, ...filter }),
),
);
const byStatus: ListIssuesCache["byStatus"] = {};
@@ -124,11 +136,11 @@ async function fetchFirstPages(filter: MyIssuesFilter = {}): Promise<ListIssuesC
* total — pagination on the "All" scope is out of scope; the first
* 50-per-status × 3 widening (deduped) is what the page renders.
*/
-async function fetchAllMyFirstPages(userId: string): Promise<ListIssuesCache> {
+async function fetchAllMyFirstPages(userId: string, sort?: IssueSortParam): Promise<ListIssuesCache> {
const [byAssignee, byCreator, byInvolves] = await Promise.all([
- fetchFirstPages({ assignee_id: userId }),
- fetchFirstPages({ creator_id: userId }),
- fetchFirstPages({ involves_user_id: userId }),
+ fetchFirstPages({ assignee_id: userId }, sort),
+ fetchFirstPages({ creator_id: userId }, sort),
+ fetchFirstPages({ involves_user_id: userId }, sort),
]);
const byStatus: ListIssuesCache["byStatus"] = {};
for (const status of PAGINATED_STATUSES) {
@@ -158,6 +170,7 @@ async function fetchAllMyFirstPages(userId: string): Promise<ListIssuesCache> {
async function fetchAllMyAssigneeGroups(
userId: string,
filter: AssigneeGroupedIssuesFilter,
+ sort?: IssueSortParam,
): Promise<GroupedIssuesResponse> {
const variants: AssigneeGroupedIssuesFilter[] = [
{ ...filter, assignee_id: userId },
@@ -170,6 +183,7 @@ async function fetchAllMyAssigneeGroups(
group_by: "assignee",
limit: ISSUE_PAGE_SIZE,
offset: 0,
+ ...sort,
...f,
}),
),
@@ -210,27 +224,31 @@ async function fetchAllMyAssigneeGroups(
* Fetches the first page of each paginated status in parallel. Use
* {@link useLoadMoreByStatus} to paginate a specific status into the cache.
*/
-export function issueListOptions(wsId: string) {
+export function issueListOptions(wsId: string, sort?: IssueSortParam) {
return queryOptions({
- queryKey: issueKeys.list(wsId),
- queryFn: () => fetchFirstPages(),
+ queryKey: issueKeys.listSorted(wsId, sort),
+ queryFn: () => fetchFirstPages({}, sort),
select: flattenIssueBuckets,
+ placeholderData: keepPreviousData,
});
}
export function issueAssigneeGroupsOptions(
wsId: string,
filter: AssigneeGroupedIssuesFilter,
+ sort?: IssueSortParam,
) {
return queryOptions<GroupedIssuesResponse>({
- queryKey: issueKeys.assigneeGroups(wsId, filter),
+ queryKey: issueKeys.assigneeGroups(wsId, { ...filter, ...sort }),
queryFn: () =>
api.listGroupedIssues({
group_by: "assignee",
limit: ISSUE_PAGE_SIZE,
offset: 0,
+ ...sort,
...filter,
}),
+ placeholderData: keepPreviousData,
});
}
@@ -247,14 +265,16 @@ export function myIssueListOptions(
// scope the filter object already carries the relevant id and userId
// is ignored.
userId?: string,
+ sort?: IssueSortParam,
) {
return queryOptions({
- queryKey: issueKeys.myList(wsId, scope, filter),
+ queryKey: issueKeys.myListSorted(wsId, scope, filter, sort),
queryFn: () =>
scope === "all" && userId
- ? fetchAllMyFirstPages(userId)
- : fetchFirstPages(filter),
+ ? fetchAllMyFirstPages(userId, sort)
+ : fetchFirstPages(filter, sort),
select: flattenIssueBuckets,
+ placeholderData: keepPreviousData,
});
}
@@ -318,18 +338,21 @@ export function myIssueAssigneeGroupsOptions(
// See myIssueListOptions for the userId contract — only consulted when
// scope === "all", and powers the 3-fetch grouped union.
userId?: string,
+ sort?: IssueSortParam,
) {
return queryOptions<GroupedIssuesResponse>({
- queryKey: issueKeys.myAssigneeGroups(wsId, scope, filter),
+ queryKey: issueKeys.myAssigneeGroups(wsId, scope, { ...filter, ...sort }),
queryFn: () =>
scope === "all" && userId
- ? fetchAllMyAssigneeGroups(userId, filter)
+ ? fetchAllMyAssigneeGroups(userId, filter, sort)
: api.listGroupedIssues({
group_by: "assignee",
limit: ISSUE_PAGE_SIZE,
offset: 0,
+ ...sort,
...filter,
}),
+ placeholderData: keepPreviousData,
});
}
diff --git a/packages/core/issues/ws-updaters.ts b/packages/core/issues/ws-updaters.ts
index afc837234b..535e1784d8 100644
--- a/packages/core/issues/ws-updaters.ts
+++ b/packages/core/issues/ws-updaters.ts
@@ -15,9 +15,9 @@ export function onIssueCreated(
wsId: string,
issue: Issue,
) {
- qc.setQueryData<ListIssuesCache>(issueKeys.list(wsId), (old) =>
- old ? addIssueToBuckets(old, issue) : old,
- );
+ for (const [key, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) })) {
+ if (data) qc.setQueryData<ListIssuesCache>(key, addIssueToBuckets(data, issue));
+ }
qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });
@@ -40,20 +40,24 @@ export function onIssueUpdated(
// Look up the OLD parent before mutating list state, so we can keep
// the parent's children cache in sync (powers the sub-issues list
// shown on the parent issue page).
- const listData = qc.getQueryData<ListIssuesCache>(issueKeys.list(wsId));
+ const listQueries = qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) });
+ const firstListData = listQueries[0]?.[1];
const detailData = qc.getQueryData<Issue>(issueKeys.detail(wsId, issue.id));
const oldParentId =
detailData?.parent_issue_id ??
- (listData ? findIssueLocation(listData, issue.id)?.issue.parent_issue_id : null) ??
+ (firstListData ? findIssueLocation(firstListData, issue.id)?.issue.parent_issue_id : null) ??
null;
// The NEW parent comes from the WS payload when parent_issue_id changed
const newParentId = issue.parent_issue_id ?? null;
const parentChanged =
issue.parent_issue_id !== undefined && newParentId !== oldParentId;
- qc.setQueryData<ListIssuesCache>(issueKeys.list(wsId), (old) =>
- old ? patchIssueInBuckets(old, issue.id, issue) : old,
- );
+ for (const [key, data] of listQueries) {
+ if (data) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(data, issue.id, issue));
+ }
+ if (issue.position !== undefined) {
+ qc.invalidateQueries({ queryKey: issueKeys.list(wsId) });
+ }
qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });
qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });
@@ -105,9 +109,9 @@ export function onIssueLabelsChanged(
issueId: string,
labels: Label[],
) {
- qc.setQueryData<ListIssuesCache>(issueKeys.list(wsId), (old) =>
- old ? patchIssueInBuckets(old, issueId, { labels }) : old,
- );
+ for (const [key, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) })) {
+ if (data) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(data, issueId, { labels }));
+ }
qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) =>
old ? { ...old, labels } : old,
);
@@ -148,9 +152,9 @@ export function onIssueMetadataChanged(
issueId: string,
metadata: IssueMetadata,
) {
- qc.setQueryData<ListIssuesCache>(issueKeys.list(wsId), (old) =>
- old ? patchIssueInBuckets(old, issueId, { metadata }) : old,
- );
+ for (const [key, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) })) {
+ if (data) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(data, issueId, { metadata }));
+ }
qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) =>
old ? { ...old, metadata } : old,
);
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index 3daa98845f..98c02639b9 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -64,6 +64,8 @@ export interface ListIssuesParams {
* majority on the client.
*/
scheduled?: boolean;
+ sort_by?: "position" | "priority" | "title" | "created_at" | "start_date" | "due_date";
+ sort_direction?: "asc" | "desc";
}
export interface IssueActorRef {
@@ -95,6 +97,8 @@ export interface ListGroupedIssuesParams {
label_ids?: string[];
group_assignee_type?: IssueAssigneeType | "none";
group_assignee_id?: string;
+ sort_by?: "position" | "priority" | "title" | "created_at" | "start_date" | "due_date";
+ sort_direction?: "asc" | "desc";
}
/** Raw backend response shape for `GET /api/issues`. */
diff --git a/packages/views/editor/extensions/mention-suggestion.test.tsx b/packages/views/editor/extensions/mention-suggestion.test.tsx
index eb2ba8825b..c4659a7bb0 100644
--- a/packages/views/editor/extensions/mention-suggestion.test.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.test.tsx
@@ -83,6 +83,17 @@ function fakeQc(data: {
);
return {
getQueryData: (key: readonly unknown[]) => map.get(JSON.stringify(key)),
+ getQueriesData: <T,>(filter: { queryKey: readonly unknown[] }) => {
+ const prefix = filter.queryKey as unknown[];
+ const results: [readonly unknown[], T][] = [];
+ for (const [k, v] of map) {
+ const parsed = JSON.parse(k) as unknown[];
+ if (parsed.length >= prefix.length && prefix.every((seg, i) => JSON.stringify(seg) === JSON.stringify(parsed[i]))) {
+ results.push([parsed, v as T]);
+ }
+ }
+ return results;
+ },
} as unknown as QueryClient;
}
diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsx
index 604f519bb7..24acd1184e 100644
--- a/packages/views/editor/extensions/mention-suggestion.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.tsx
@@ -388,7 +388,8 @@ export function createMentionSuggestion(qc: QueryClient): Omit<
const members: MemberWithUser[] = qc.getQueryData(workspaceKeys.members(wsId)) ?? [];
const agents: Agent[] = qc.getQueryData(workspaceKeys.agents(wsId)) ?? [];
const squads: Squad[] = qc.getQueryData(workspaceKeys.squads(wsId)) ?? [];
- const cachedResponse = qc.getQueryData<ListIssuesCache>(issueKeys.list(wsId));
+ const listQueries = qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) });
+ const cachedResponse = listQueries[0]?.[1];
const cachedIssues: Issue[] = cachedResponse ? flattenIssueBuckets(cachedResponse) : [];
// Read current user identity imperatively — this factory runs outside
diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsx
index a60f0eb7b0..3a85bd255d 100644
--- a/packages/views/issues/components/board-card.tsx
+++ b/packages/views/issues/components/board-card.tsx
@@ -312,7 +312,7 @@ const animateLayoutChanges: AnimateLayoutChanges = (args) => {
return defaultAnimateLayoutChanges(args);
};
-export const DraggableBoardCard = memo(function DraggableBoardCard({ issue, childProgress }: { issue: Issue; childProgress?: ChildProgress }) {
+export const DraggableBoardCard = memo(function DraggableBoardCard({ issue, childProgress, disableSorting }: { issue: Issue; childProgress?: ChildProgress; disableSorting?: boolean }) {
const p = useWorkspacePaths();
const {
attributes,
@@ -325,6 +325,7 @@ export const DraggableBoardCard = memo(function DraggableBoardCard({ issue, chil
id: issue.id,
data: { status: issue.status },
animateLayoutChanges,
+ disabled: disableSorting ? { droppable: true } : undefined,
});
const style = {
diff --git a/packages/views/issues/components/board-column.tsx b/packages/views/issues/components/board-column.tsx
index 96068f1f97..0dda2b73a9 100644
--- a/packages/views/issues/components/board-column.tsx
+++ b/packages/views/issues/components/board-column.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useMemo, type ReactNode } from "react";
+import { memo, useMemo, type ReactNode } from "react";
import { EyeOff, MoreHorizontal, Plus, UserMinus } from "lucide-react";
import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";
import { useDroppable } from "@dnd-kit/core";
@@ -22,6 +22,14 @@ import type { ChildProgress } from "./list-row";
import { useT } from "../../i18n";
import { ActorAvatar } from "../../common/actor-avatar";
+// Insertion-position prediction intentionally omitted. The server's
+// ORDER BY uses PostgreSQL's en_US.utf8 collation (glibc), which
+// cannot be faithfully replicated in JavaScript (ICU/V8). Showing an
+// inaccurate indicator is worse than showing none.
+
+export const BOARD_COL_WIDTH = 280;
+export const BOARD_CARD_WIDTH = BOARD_COL_WIDTH - 16 - 8; // col(280) - col p-2(16) - droppable p-1(8)
+
export interface BoardColumnGroup {
id: string;
title: string;
@@ -32,7 +40,7 @@ export interface BoardColumnGroup {
createData?: Record<string, unknown>;
}
-export function BoardColumn({
+export const BoardColumn = memo(function BoardColumn({
group,
issueIds,
issueMap,
@@ -40,6 +48,7 @@ export function BoardColumn({
totalCount,
footer,
projectId,
+ sortLabel,
}: {
group: BoardColumnGroup;
issueIds: string[];
@@ -49,6 +58,7 @@ export function BoardColumn({
footer?: ReactNode;
/** When set, the per-column "+" pre-fills the project on the create form. */
projectId?: string;
+ sortLabel?: string | null;
}) {
const status = group.status;
const cfg = status ? STATUS_CONFIG[status] : null;
@@ -67,7 +77,7 @@ export function BoardColumn({
);
return (
- <div className={`flex w-[280px] shrink-0 flex-col rounded-xl ${cfg?.columnBg ?? "bg-muted/40"} p-2`}>
+ <div style={{ width: BOARD_COL_WIDTH }} className={`flex shrink-0 flex-col rounded-xl ${cfg?.columnBg ?? "bg-muted/40"} p-2`}>
<div className="mb-2 flex items-center justify-between px-1.5">
<BoardGroupHeading group={group} count={totalCount ?? issueIds.length} />
@@ -115,13 +125,24 @@ export function BoardColumn({
</div>
<div
ref={setNodeRef}
- className={`min-h-[200px] flex-1 space-y-2 overflow-y-auto rounded-lg p-1 transition-colors ${
- isOver ? "bg-accent/60" : ""
+ className={`relative min-h-[200px] flex-1 space-y-2 overflow-y-auto rounded-lg p-1 transition-colors ${
+ isOver && sortLabel
+ ? "ring-2 ring-brand/25 bg-accent/15"
+ : isOver
+ ? "bg-accent/60"
+ : ""
}`}
>
+ {isOver && sortLabel && (
+ <div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-lg bg-background/40">
+ <span className="rounded-md bg-popover px-2.5 py-1 text-xs font-medium text-popover-foreground shadow-sm border border-border">
+ {sortLabel}
+ </span>
+ </div>
+ )}
<SortableContext items={issueIds} strategy={verticalListSortingStrategy}>
{resolvedIssues.map((issue) => (
- <DraggableBoardCard key={issue.id} issue={issue} childProgress={childProgressMap?.get(issue.id)} />
+ <DraggableBoardCard key={issue.id} issue={issue} childProgress={childProgressMap?.get(issue.id)} disableSorting={!!sortLabel} />
))}
</SortableContext>
{issueIds.length === 0 && (
@@ -133,7 +154,7 @@ export function BoardColumn({
</div>
</div>
);
-}
+});
function BoardGroupHeading({
group,
diff --git a/packages/views/issues/components/board-view.tsx b/packages/views/issues/components/board-view.tsx
index f25334fcda..d52c43c0a4 100644
--- a/packages/views/issues/components/board-view.tsx
+++ b/packages/views/issues/components/board-view.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useCallback, useMemo, useEffect, useRef } from "react";
+import { useState, useCallback, useMemo, useEffect, useRef, memo } from "react";
import {
DndContext,
DragOverlay,
@@ -28,11 +28,10 @@ import {
DropdownMenuItem,
} from "@multica/ui/components/ui/dropdown-menu";
import { useViewStoreApi, useViewStore } from "@multica/core/issues/stores/view-store-context";
-import type { IssueGrouping, SortField, SortDirection } from "@multica/core/issues/stores/view-store";
+import type { IssueGrouping } from "@multica/core/issues/stores/view-store";
import { useActorName } from "@multica/core/workspace/hooks";
-import { sortIssues } from "../utils/sort";
import { StatusIcon } from "./status-icon";
-import { BoardColumn, type BoardColumnGroup } from "./board-column";
+import { BoardColumn, BOARD_CARD_WIDTH, type BoardColumnGroup } from "./board-column";
import { BoardCardContent } from "./board-card";
import { InfiniteScrollSentinel } from "./infinite-scroll-sentinel";
import type { ChildProgress } from "./list-row";
@@ -49,14 +48,10 @@ function makeKanbanCollision(columnIds: Set<string>): CollisionDetection {
return (args) => {
const pointer = pointerWithin(args);
if (pointer.length > 0) {
- // Prefer card collisions over column collisions so that
- // dragging down within a column finds the target card
- // instead of the column droppable.
const cards = pointer.filter((c) => !columnIds.has(c.id as string));
if (cards.length > 0) return cards;
+ return pointer;
}
- // Fallback: closestCenter finds the nearest card even when
- // the pointer is in a gap between cards (common when dragging down).
return closestCenter(args);
};
}
@@ -145,22 +140,17 @@ function buildGroups(
});
}
-/** Build column ID arrays from TQ issue data, respecting current sort. */
+/** Build column ID arrays from TQ issue data (server-sorted). */
function buildColumns(
issues: Issue[],
groups: BoardColumnGroup[],
grouping: IssueGrouping,
- sortBy: SortField,
- sortDirection: SortDirection,
): Record<string, string[]> {
const cols: Record<string, string[]> = {};
- for (const group of groups) {
- const sorted = sortIssues(
- issues.filter((i) => getIssueGroupId(i, grouping) === group.id),
- sortBy,
- sortDirection,
- );
- cols[group.id] = sorted.map((i) => i.id);
+ for (const group of groups) cols[group.id] = [];
+ for (const issue of issues) {
+ const gid = getIssueGroupId(issue, grouping);
+ if (cols[gid]) cols[gid].push(issue.id);
}
return cols;
}
@@ -210,6 +200,7 @@ function getMoveUpdates(
}
const EMPTY_PROGRESS_MAP = new Map<string, ChildProgress>();
+const EMPTY_IDS: string[] = [];
export function BoardView({
issues,
@@ -230,7 +221,7 @@ export function BoardView({
assigneeGroupFilter?: AssigneeGroupedIssuesFilter;
visibleStatuses: IssueStatus[];
hiddenStatuses: IssueStatus[];
- onMoveIssue: (issueId: string, updates: BoardMoveUpdates) => void;
+ onMoveIssue: (issueId: string, updates: BoardMoveUpdates, onSettled?: () => void) => void;
childProgressMap?: Map<string, ChildProgress>;
/** When set, per-status load-more targets the scoped cache instead of the workspace one. */
myIssuesScope?: string;
@@ -239,9 +230,12 @@ export function BoardView({
projectId?: string;
}) {
const { t } = useT("issues");
- const sortBy = useViewStore((s) => s.sortBy);
- const sortDirection = useViewStore((s) => s.sortDirection);
const grouping = useViewStore((s) => s.grouping);
+ const sortBy = useViewStore((s) => s.sortBy);
+ const sortFieldKey = sortBy === "created_at" ? "created" : sortBy;
+ const sortLabel = sortBy !== "position"
+ ? t(($) => $.board.ordered_by, { field: t(($) => $.display[`sort_${sortFieldKey}` as keyof typeof $.display]) })
+ : null;
const { getActorName } = useActorName();
const myIssuesOpts = myIssuesScope
? { scope: myIssuesScope, filter: myIssuesFilter ?? {} }
@@ -311,21 +305,23 @@ export function BoardView({
// --- Drag state ---
const [activeIssue, setActiveIssue] = useState<Issue | null>(null);
const isDraggingRef = useRef(false);
+ const isSettlingRef = useRef(false);
+ const [settleVersion, setSettleVersion] = useState(0);
// --- Local columns state ---
// Between drags: follows TQ via useEffect.
// During drag: local-only, driven by onDragOver/onDragEnd.
const [columns, setColumns] = useState<Record<string, string[]>>(() =>
- buildColumns(groupedIssues, groups, grouping, sortBy, sortDirection),
+ buildColumns(groupedIssues, groups, grouping),
);
const columnsRef = useRef(columns);
columnsRef.current = columns;
useEffect(() => {
- if (!isDraggingRef.current) {
- setColumns(buildColumns(groupedIssues, groups, grouping, sortBy, sortDirection));
+ if (!isDraggingRef.current && !isSettlingRef.current) {
+ setColumns(buildColumns(groupedIssues, groups, grouping));
}
- }, [groupedIssues, groups, grouping, sortBy, sortDirection]);
+ }, [groupedIssues, groups, grouping, settleVersion]);
// After a cross-column move, lock for one animation frame so dnd-kit's
// collision detection can stabilize before processing the next move.
@@ -348,7 +344,7 @@ export function BoardView({
}, [groupedIssues]);
const issueMapRef = useRef(issueMap);
- if (!isDraggingRef.current) {
+ if (!isDraggingRef.current && !isSettlingRef.current) {
issueMapRef.current = issueMap;
}
@@ -380,6 +376,8 @@ export function BoardView({
const overCol = findColumn(prev, overId, groupIds);
if (!activeCol || !overCol || activeCol === overCol) return prev;
+ if (sortBy !== "position") return prev;
+
recentlyMovedRef.current = true;
const oldIds = prev[activeCol]!.filter((id) => id !== activeId);
const newIds = [...prev[overCol]!];
@@ -389,7 +387,7 @@ export function BoardView({
return { ...prev, [activeCol]: oldIds, [overCol]: newIds };
});
},
- [groupIds],
+ [groupIds, sortBy],
);
const handleDragEnd = useCallback(
@@ -399,7 +397,7 @@ export function BoardView({
setActiveIssue(null);
const resetColumns = () =>
- setColumns(buildColumns(groupedIssues, groups, grouping, sortBy, sortDirection));
+ setColumns(buildColumns(groupedIssues, groups, grouping));
if (!over) {
resetColumns();
@@ -417,9 +415,9 @@ export function BoardView({
return;
}
- // Same-column reorder
+ // Same-column reorder (manual sort only)
let finalColumns = cols;
- if (activeCol === overCol) {
+ if (activeCol === overCol && sortBy === "position") {
const ids = cols[activeCol]!;
const oldIndex = ids.indexOf(activeId);
const newIndex = ids.indexOf(overId);
@@ -430,7 +428,9 @@ export function BoardView({
}
}
- const finalCol = findColumn(finalColumns, activeId, groupIds);
+ const finalCol = sortBy === "position"
+ ? findColumn(finalColumns, activeId, groupIds)
+ : overCol;
if (!finalCol) {
resetColumns();
return;
@@ -442,6 +442,22 @@ export function BoardView({
}
const map = issueMapRef.current;
+
+ if (sortBy !== "position") {
+ // Cross-column: only update group (status/assignee), keep original position.
+ const currentIssue = map.get(activeId);
+ if (!currentIssue || issueMatchesGroup(currentIssue, finalGroup)) {
+ resetColumns();
+ return;
+ }
+ isSettlingRef.current = true;
+ onMoveIssue(activeId, getMoveUpdates(finalGroup, currentIssue.position), () => {
+ isSettlingRef.current = false;
+ setSettleVersion((v) => v + 1);
+ });
+ return;
+ }
+
const finalIds = finalColumns[finalCol]!;
const newPosition = computePosition(finalIds, activeId, map);
const currentIssue = map.get(activeId);
@@ -454,9 +470,12 @@ export function BoardView({
return;
}
- onMoveIssue(activeId, getMoveUpdates(finalGroup, newPosition));
+ isSettlingRef.current = true;
+ onMoveIssue(activeId, getMoveUpdates(finalGroup, newPosition), () => {
+ isSettlingRef.current = false;
+ });
},
- [groupedIssues, groups, grouping, sortBy, sortDirection, onMoveIssue, groupIds, groupMap],
+ [groupedIssues, groups, grouping, onMoveIssue, groupIds, groupMap, sortBy],
);
return (
@@ -478,33 +497,36 @@ export function BoardView({
<PaginatedBoardColumn
key={group.id}
group={group}
- issueIds={columns[group.id] ?? []}
+ issueIds={columns[group.id] ?? EMPTY_IDS}
issueMap={issueMapRef.current}
childProgressMap={childProgressMap}
myIssuesOpts={myIssuesOpts}
projectId={projectId}
+ sortLabel={sortLabel}
/>
) : (
assigneeGroupQueryKey && assigneeGroupFilter ? (
<PaginatedAssigneeBoardColumn
key={group.id}
group={group}
- issueIds={columns[group.id] ?? []}
+ issueIds={columns[group.id] ?? EMPTY_IDS}
issueMap={issueMapRef.current}
childProgressMap={childProgressMap}
queryKey={assigneeGroupQueryKey}
filter={assigneeGroupFilter}
projectId={projectId}
+ sortLabel={sortLabel}
/>
) : (
<BoardColumn
key={group.id}
group={group}
- issueIds={columns[group.id] ?? []}
+ issueIds={columns[group.id] ?? EMPTY_IDS}
issueMap={issueMapRef.current}
childProgressMap={childProgressMap}
projectId={projectId}
totalCount={group.totalCount}
+ sortLabel={sortLabel}
/>
)
),
@@ -521,7 +543,7 @@ export function BoardView({
<DragOverlay dropAnimation={null}>
{activeIssue ? (
- <div className="w-[280px] rotate-2 scale-105 cursor-grabbing opacity-90 shadow-lg shadow-black/10">
+ <div style={{ width: BOARD_CARD_WIDTH }} className="rotate-1 cursor-grabbing opacity-90 shadow-lg shadow-black/10">
<BoardCardContent issue={activeIssue} childProgress={childProgressMap.get(activeIssue.id)} />
</div>
) : null}
@@ -530,7 +552,7 @@ export function BoardView({
);
}
-function PaginatedAssigneeBoardColumn({
+const PaginatedAssigneeBoardColumn = memo(function PaginatedAssigneeBoardColumn({
group,
issueIds,
issueMap,
@@ -538,6 +560,7 @@ function PaginatedAssigneeBoardColumn({
queryKey,
filter,
projectId,
+ sortLabel,
}: {
group: BoardColumnGroup;
issueIds: string[];
@@ -546,6 +569,7 @@ function PaginatedAssigneeBoardColumn({
queryKey: QueryKey;
filter: AssigneeGroupedIssuesFilter;
projectId?: string;
+ sortLabel?: string | null;
}) {
const { loadMore, hasMore, isLoading, total } = useLoadMoreByAssigneeGroup(
{
@@ -564,6 +588,7 @@ function PaginatedAssigneeBoardColumn({
childProgressMap={childProgressMap}
totalCount={total}
projectId={projectId}
+ sortLabel={sortLabel}
footer={
hasMore ? (
<InfiniteScrollSentinel onVisible={loadMore} loading={isLoading} />
@@ -571,15 +596,16 @@ function PaginatedAssigneeBoardColumn({
}
/>
);
-}
+});
-function PaginatedBoardColumn({
+const PaginatedBoardColumn = memo(function PaginatedBoardColumn({
group,
issueIds,
issueMap,
childProgressMap,
myIssuesOpts,
projectId,
+ sortLabel,
}: {
group: BoardColumnGroup & { status: IssueStatus };
issueIds: string[];
@@ -587,6 +613,7 @@ function PaginatedBoardColumn({
childProgressMap?: Map<string, ChildProgress>;
myIssuesOpts?: { scope: string; filter: MyIssuesFilter };
projectId?: string;
+ sortLabel?: string | null;
}) {
const { loadMore, hasMore, isLoading, total } = useLoadMoreByStatus(
group.status,
@@ -600,6 +627,7 @@ function PaginatedBoardColumn({
childProgressMap={childProgressMap}
totalCount={total}
projectId={projectId}
+ sortLabel={sortLabel}
footer={
hasMore ? (
<InfiniteScrollSentinel onVisible={loadMore} loading={isLoading} />
@@ -607,7 +635,7 @@ function PaginatedBoardColumn({
}
/>
);
-}
+});
function HiddenColumnsPanel({
hiddenStatuses,
diff --git a/packages/views/issues/components/issue-agent-activity-indicator.tsx b/packages/views/issues/components/issue-agent-activity-indicator.tsx
index a2a3a6e350..b2dea3498e 100644
--- a/packages/views/issues/components/issue-agent-activity-indicator.tsx
+++ b/packages/views/issues/components/issue-agent-activity-indicator.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useMemo } from "react";
+import { memo, useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import {
HoverCard,
@@ -46,7 +46,7 @@ interface IssueAgentActivityIndicatorProps {
* Re-renders on every snapshot invalidation (WS task:* events drive it
* via use-realtime-sync). 30s staleTime is the offline fallback only.
*/
-export function IssueAgentActivityIndicator({
+export const IssueAgentActivityIndicator = memo(function IssueAgentActivityIndicator({
issueId,
size = 12,
}: IssueAgentActivityIndicatorProps) {
@@ -113,4 +113,4 @@ export function IssueAgentActivityIndicator({
</HoverCardContent>
</HoverCard>
);
-}
+});
diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsx
index 440ad4a0b7..50bb9e974e 100644
--- a/packages/views/issues/components/issues-header.tsx
+++ b/packages/views/issues/components/issues-header.tsx
@@ -14,7 +14,7 @@ import {
FolderMinus,
List,
SignalHigh,
- SlidersHorizontal,
+ X,
Tag,
User,
UserMinus,
@@ -603,17 +603,17 @@ export function IssueDisplayControls({
const counts = useIssueCounts(scopedIssues);
- const hasActiveFilters =
- getActiveFilterCount({
- statusFilters,
- priorityFilters,
- assigneeFilters,
- includeNoAssignee,
- creatorFilters,
- projectFilters,
- includeNoProject,
- labelFilters,
- }) > 0;
+ const activeFilterCount = getActiveFilterCount({
+ statusFilters,
+ priorityFilters,
+ assigneeFilters,
+ includeNoAssignee,
+ creatorFilters,
+ projectFilters,
+ includeNoProject,
+ labelFilters,
+ });
+ const hasActiveFilters = activeFilterCount > 0;
const SORT_LABEL_KEY: Record<typeof SORT_OPTIONS[number]["value"], "sort_manual" | "sort_priority" | "sort_start_date" | "sort_due_date" | "sort_created" | "sort_title"> = {
position: "sort_manual",
@@ -649,10 +649,29 @@ export function IssueDisplayControls({
render={
<TooltipTrigger
render={
- <Button variant="outline" size="icon-sm" className="relative text-muted-foreground">
- <Filter className="size-4" />
+ <Button
+ variant={hasActiveFilters ? "default" : "outline"}
+ size="sm"
+ className={
+ hasActiveFilters
+ ? "gap-1 bg-brand text-white hover:bg-brand/90"
+ : "gap-1 text-muted-foreground"
+ }
+ >
+ <Filter className="size-3.5" />
+ {hasActiveFilters
+ ? t(($) => $.filters.active_count, { count: activeFilterCount })
+ : t(($) => $.filters.tooltip)}
{hasActiveFilters && (
- <span className="absolute top-0 right-0 size-1.5 rounded-full bg-brand" />
+ <span
+ role="button"
+ tabIndex={-1}
+ className="-mr-1 ml-0.5 rounded-sm p-0.5 hover:bg-white/20"
+ onClick={(e) => { e.preventDefault(); e.stopPropagation(); act.clearFilters(); }}
+ onPointerDown={(e) => e.stopPropagation()}
+ >
+ <X className="size-3" />
+ </span>
)}
</Button>
}
@@ -841,8 +860,13 @@ export function IssueDisplayControls({
render={
<TooltipTrigger
render={
- <Button variant="outline" size="icon-sm" className="text-muted-foreground">
- <SlidersHorizontal className="size-4" />
+ <Button variant="outline" size="sm" className="gap-1 text-muted-foreground">
+ {sortBy !== "position" && (
+ sortDirection === "asc"
+ ? <ArrowUp className="size-3.5" />
+ : <ArrowDown className="size-3.5" />
+ )}
+ {sortLabel}
</Button>
}
/>
@@ -914,20 +938,22 @@ export function IssueDisplayControls({
))}
</DropdownMenuContent>
</DropdownMenu>
- <Button
- variant="outline"
- size="icon-sm"
- onClick={() =>
- act.setSortDirection(sortDirection === "asc" ? "desc" : "asc")
- }
- title={sortDirection === "asc" ? t(($) => $.display.ascending_title) : t(($) => $.display.descending_title)}
- >
- {sortDirection === "asc" ? (
- <ArrowUp className="size-3.5" />
- ) : (
- <ArrowDown className="size-3.5" />
- )}
- </Button>
+ {sortBy !== "position" && (
+ <Button
+ variant="outline"
+ size="icon-sm"
+ onClick={() =>
+ act.setSortDirection(sortDirection === "asc" ? "desc" : "asc")
+ }
+ title={sortDirection === "asc" ? t(($) => $.display.ascending_title) : t(($) => $.display.descending_title)}
+ >
+ {sortDirection === "asc" ? (
+ <ArrowUp className="size-3.5" />
+ ) : (
+ <ArrowDown className="size-3.5" />
+ )}
+ </Button>
+ )}
</div>
</div>
@@ -964,14 +990,19 @@ export function IssueDisplayControls({
render={
<TooltipTrigger
render={
- <Button variant="outline" size="icon-sm" className="text-muted-foreground">
+ <Button variant="outline" size="sm" className="gap-1 text-muted-foreground">
{viewMode === "board" ? (
- <Columns3 className="size-4" />
+ <Columns3 className="size-3.5" />
) : viewMode === "gantt" && allowGantt ? (
- <ChartGantt className="size-4" />
+ <ChartGantt className="size-3.5" />
) : (
- <List className="size-4" />
+ <List className="size-3.5" />
)}
+ {viewMode === "board"
+ ? t(($) => $.view.board)
+ : viewMode === "gantt" && allowGantt
+ ? t(($) => $.view.gantt)
+ : t(($) => $.view.list)}
</Button>
}
/>
diff --git a/packages/views/issues/components/issues-page.tsx b/packages/views/issues/components/issues-page.tsx
index eea1e2636a..aa1b8be9cc 100644
--- a/packages/views/issues/components/issues-page.tsx
+++ b/packages/views/issues/components/issues-page.tsx
@@ -23,8 +23,11 @@ import { IssuesHeader } from "./issues-header";
import { BoardView } from "./board-view";
import { ListView } from "./list-view";
import { BatchActionToolbar } from "./batch-action-toolbar";
+import type { ChildProgress } from "./list-row";
import { useT } from "../../i18n";
+const EMPTY_CHILD_PROGRESS = new Map<string, ChildProgress>();
+
export function IssuesPage() {
const { t } = useT("issues");
const wsId = useWorkspaceId();
@@ -41,9 +44,19 @@ export function IssuesPage() {
const projectFilters = useIssueViewStore((s) => s.projectFilters);
const includeNoProject = useIssueViewStore((s) => s.includeNoProject);
const labelFilters = useIssueViewStore((s) => s.labelFilters);
+ const sortBy = useIssueViewStore((s) => s.sortBy);
+ const sortDirection = useIssueViewStore((s) => s.sortDirection);
const agentRunningFilter = useIssueViewStore((s) => s.agentRunningFilter);
const usesAssigneeBoard = viewMode === "board" && grouping === "assignee";
+ const sort = useMemo(
+ () => ({
+ sort_by: sortBy,
+ sort_direction: sortBy !== "position" ? sortDirection : undefined,
+ } as const),
+ [sortBy, sortDirection],
+ );
+
// Derive the set of issue ids that currently have at least one
// `running` agent task. Used by the workspace agents-working filter
// chip. Subscribing the page here (not deep in filter.ts) keeps the
@@ -75,9 +88,9 @@ export function IssuesPage() {
return filter;
}, [assigneeFilters, creatorFilters, includeNoAssignee, includeNoProject, labelFilters, priorityFilters, projectFilters, scope, statusFilters]);
- const assigneeGroupsOptions = issueAssigneeGroupsOptions(wsId, assigneeGroupFilter);
+ const assigneeGroupsOptions = issueAssigneeGroupsOptions(wsId, assigneeGroupFilter, sort);
const statusIssuesQuery = useQuery({
- ...issueListOptions(wsId),
+ ...issueListOptions(wsId, sort),
enabled: !usesAssigneeBoard,
});
const assigneeGroupsQuery = useQuery({
@@ -121,7 +134,7 @@ export function IssuesPage() {
// Fetch sub-issue progress from the backend so counts are accurate
// regardless of client-side pagination or filtering of done issues.
- const { data: childProgressMap = new Map() } = useQuery(childIssueProgressOptions(wsId));
+ const { data: childProgressMap = EMPTY_CHILD_PROGRESS } = useQuery(childIssueProgressOptions(wsId));
const visibleStatuses = useMemo(() => {
if (statusFilters.length > 0)
@@ -135,7 +148,7 @@ export function IssuesPage() {
const updateIssueMutation = useUpdateIssue();
const handleMoveIssue = useCallback(
- (issueId: string, updates: Pick<UpdateIssueRequest, "status" | "assignee_type" | "assignee_id" | "position">) => {
+ (issueId: string, updates: Pick<UpdateIssueRequest, "status" | "assignee_type" | "assignee_id" | "position">, onSettled?: () => void) => {
updateIssueMutation.mutate(
{ id: issueId, ...updates },
{
@@ -145,55 +158,33 @@ export function IssuesPage() {
? err.message
: t(($) => $.page.move_failed),
),
+ onSettled: () => onSettled?.(),
},
);
},
[updateIssueMutation, t],
);
- if (loading) {
- return (
- <div className="flex flex-1 min-h-0 flex-col">
- <div className="flex h-12 shrink-0 items-center gap-2 border-b px-4">
- <Skeleton className="h-5 w-5 rounded" />
- <Skeleton className="h-4 w-32" />
- </div>
- <div className="flex h-12 shrink-0 items-center justify-between px-4">
- <div className="flex items-center gap-1">
- <Skeleton className="h-8 w-14 rounded-md" />
- <Skeleton className="h-8 w-20 rounded-md" />
- <Skeleton className="h-8 w-16 rounded-md" />
- </div>
- <div className="flex items-center gap-1">
- <Skeleton className="h-8 w-8 rounded-md" />
- <Skeleton className="h-8 w-8 rounded-md" />
- <Skeleton className="h-8 w-8 rounded-md" />
- </div>
+ const contentSkeleton = viewMode === "list" ? (
+ <div className="flex-1 min-h-0 overflow-y-auto p-2 space-y-1">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <Skeleton key={i} className="h-10 w-full rounded-lg" />
+ ))}
+ </div>
+ ) : (
+ <div className="flex flex-1 min-h-0 gap-4 overflow-x-auto p-4">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <div key={i} className="flex min-w-52 flex-1 flex-col gap-2">
+ <Skeleton className="h-4 w-20" />
+ <Skeleton className="h-24 w-full rounded-lg" />
+ <Skeleton className="h-24 w-full rounded-lg" />
</div>
- {viewMode === "list" ? (
- <div className="flex-1 min-h-0 overflow-y-auto p-2 pt-0 space-y-1">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-10 w-full rounded-lg" />
- ))}
- </div>
- ) : (
- <div className="flex flex-1 min-h-0 gap-4 overflow-x-auto p-4">
- {Array.from({ length: 5 }).map((_, i) => (
- <div key={i} className="flex min-w-52 flex-1 flex-col gap-2">
- <Skeleton className="h-4 w-20" />
- <Skeleton className="h-24 w-full rounded-lg" />
- <Skeleton className="h-24 w-full rounded-lg" />
- </div>
- ))}
- </div>
- )}
- </div>
- );
- }
+ ))}
+ </div>
+ );
return (
<div className="flex flex-1 min-h-0 flex-col">
- {/* Header 1: Workspace breadcrumb */}
<PageHeader className="gap-1.5">
<WorkspaceAvatar name={workspace?.name ?? "W"} size="sm" />
<span className="text-sm text-muted-foreground">
@@ -204,11 +195,9 @@ export function IssuesPage() {
</PageHeader>
<ViewStoreProvider store={useIssueViewStore}>
- {/* Header 2: Scope tabs + filters */}
<IssuesHeader scopedIssues={headerIssues} />
- {/* Content: scrollable */}
- {headerIssues.length === 0 ? (
+ {loading ? contentSkeleton : headerIssues.length === 0 ? (
<div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-2 text-muted-foreground">
<ListTodo className="h-10 w-10 text-muted-foreground/40" />
<p className="text-sm">{t(($) => $.page.empty_title)}</p>
diff --git a/packages/views/issues/components/list-view.tsx b/packages/views/issues/components/list-view.tsx
index e88a832fb4..17de60d61d 100644
--- a/packages/views/issues/components/list-view.tsx
+++ b/packages/views/issues/components/list-view.tsx
@@ -11,7 +11,6 @@ import type { MyIssuesFilter } from "@multica/core/issues/queries";
import { useModalStore } from "@multica/core/modals";
import { useViewStore } from "@multica/core/issues/stores/view-store-context";
import { useIssueSelectionStore } from "@multica/core/issues/stores/selection-store";
-import { sortIssues } from "../utils/sort";
import { StatusHeading } from "./status-heading";
import { ListRow, type ChildProgress } from "./list-row";
import { InfiniteScrollSentinel } from "./infinite-scroll-sentinel";
@@ -36,8 +35,6 @@ export function ListView({
/** When set, the per-section "+" pre-fills the project on the create form. */
projectId?: string;
}) {
- const sortBy = useViewStore((s) => s.sortBy);
- const sortDirection = useViewStore((s) => s.sortDirection);
const listCollapsedStatuses = useViewStore(
(s) => s.listCollapsedStatuses
);
@@ -49,10 +46,10 @@ export function ListView({
const map = new Map<IssueStatus, Issue[]>();
for (const status of visibleStatuses) {
const filtered = issues.filter((i) => i.status === status);
- map.set(status, sortIssues(filtered, sortBy, sortDirection));
+ map.set(status, filtered);
}
return map;
- }, [issues, visibleStatuses, sortBy, sortDirection]);
+ }, [issues, visibleStatuses]);
const expandedStatuses = useMemo(
() =>
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 4368e55646..8adbf5fe88 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -48,7 +48,9 @@
"squads_group": "Squads",
"issue_count_one": "{{count}} issue",
"issue_count_other": "{{count}} issues",
- "reset": "Reset all filters"
+ "reset": "Reset all filters",
+ "active_count_one": "{{count}} filter",
+ "active_count_other": "{{count}} filters"
},
"display": {
"tooltip": "Display settings",
@@ -126,7 +128,8 @@
"show_column": "Show column",
"add_issue_tooltip": "Add issue",
"empty_column": "No issues",
- "empty_grouping": "No matching issues"
+ "empty_grouping": "No matching issues",
+ "ordered_by": "Board ordered by {{field}}"
},
"detail": {
"not_found": "This issue does not exist or has been deleted in this workspace.",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index b217840ed2..58d4bc7ec4 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -47,7 +47,8 @@
"agents_group": "智能体",
"squads_group": "小队",
"issue_count_other": "{{count}} 个 issue",
- "reset": "重置全部筛选"
+ "reset": "重置全部筛选",
+ "active_count_other": "{{count}} 个筛选"
},
"display": {
"tooltip": "显示设置",
@@ -125,7 +126,8 @@
"show_column": "显示列",
"add_issue_tooltip": "新建 issue",
"empty_column": "无 issue",
- "empty_grouping": "没有匹配的 issue"
+ "empty_grouping": "没有匹配的 issue",
+ "ordered_by": "按{{field}}排序"
},
"detail": {
"not_found": "这个 issue 不存在或已在该工作区被删除。",
diff --git a/packages/views/my-issues/components/my-issues-page.tsx b/packages/views/my-issues/components/my-issues-page.tsx
index 4c08d796d7..f06dae14a4 100644
--- a/packages/views/my-issues/components/my-issues-page.tsx
+++ b/packages/views/my-issues/components/my-issues-page.tsx
@@ -37,9 +37,19 @@ export function MyIssuesPage() {
const priorityFilters = useStore(myIssuesViewStore, (s) => s.priorityFilters);
const scope = useStore(myIssuesViewStore, (s) => s.scope);
const grouping = useStore(myIssuesViewStore, (s) => s.grouping);
+ const sortBy = useStore(myIssuesViewStore, (s) => s.sortBy);
+ const sortDirection = useStore(myIssuesViewStore, (s) => s.sortDirection);
const agentRunningFilter = useStore(myIssuesViewStore, (s) => s.agentRunningFilter);
const usesAssigneeBoard = viewMode === "board" && grouping === "assignee";
+ const sort = useMemo(
+ () => ({
+ sort_by: sortBy,
+ sort_direction: sortBy !== "position" ? sortDirection : undefined,
+ } as const),
+ [sortBy, sortDirection],
+ );
+
// See issues-page.tsx for the rationale — derive a workspace-wide set
// of issue ids with at least one running task, drive the "agents
// working" quick-filter from it.
@@ -97,9 +107,10 @@ export function MyIssuesPage() {
scope,
assigneeGroupFilter,
user?.id,
+ sort,
);
const statusIssuesQuery = useQuery({
- ...myIssueListOptions(wsId, scope, filter, user?.id),
+ ...myIssueListOptions(wsId, scope, filter, user?.id, sort),
enabled: !usesAssigneeBoard,
});
const assigneeGroupsQuery = useQuery({
@@ -149,7 +160,7 @@ export function MyIssuesPage() {
const updateIssueMutation = useUpdateIssue();
const handleMoveIssue = useCallback(
- (issueId: string, updates: Pick<UpdateIssueRequest, "status" | "assignee_type" | "assignee_id" | "position">) => {
+ (issueId: string, updates: Pick<UpdateIssueRequest, "status" | "assignee_type" | "assignee_id" | "position">, onSettled?: () => void) => {
updateIssueMutation.mutate(
{ id: issueId, ...updates },
{
@@ -159,6 +170,7 @@ export function MyIssuesPage() {
? err.message
: t(($) => $.errors.move_failed),
),
+ onSettled: () => onSettled?.(),
},
);
},
diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsx
index 3ab624467a..1c0faa4e09 100644
--- a/packages/views/projects/components/project-detail.tsx
+++ b/packages/views/projects/components/project-detail.tsx
@@ -164,7 +164,7 @@ function ProjectIssuesContent({
const updateIssueMutation = useUpdateIssue();
const handleMoveIssue = useCallback(
- (issueId: string, updates: Pick<UpdateIssueRequest, "status" | "assignee_type" | "assignee_id" | "position">) => {
+ (issueId: string, updates: Pick<UpdateIssueRequest, "status" | "assignee_type" | "assignee_id" | "position">, onSettled?: () => void) => {
updateIssueMutation.mutate(
{ id: issueId, ...updates },
{
@@ -174,6 +174,7 @@ function ProjectIssuesContent({
? err.message
: t(($) => $.detail.toast_move_issue_failed),
),
+ onSettled: () => onSettled?.(),
},
);
},
@@ -250,6 +251,8 @@ function ProjectIssuesSurface({
const wsId = useWorkspaceId();
const viewMode = useViewStore((s) => s.viewMode);
const grouping = useViewStore((s) => s.grouping);
+ const sortBy = useViewStore((s) => s.sortBy);
+ const sortDirection = useViewStore((s) => s.sortDirection);
const statusFilters = useViewStore((s) => s.statusFilters);
const priorityFilters = useViewStore((s) => s.priorityFilters);
const assigneeFilters = useViewStore((s) => s.assigneeFilters);
@@ -258,6 +261,15 @@ function ProjectIssuesSurface({
const labelFilters = useViewStore((s) => s.labelFilters);
const usesAssigneeBoard = viewMode === "board" && grouping === "assignee";
const usesGantt = viewMode === "gantt";
+
+ const sort = useMemo(
+ () => ({
+ sort_by: sortBy,
+ sort_direction: sortBy !== "position" ? sortDirection : undefined,
+ } as const),
+ [sortBy, sortDirection],
+ );
+
const assigneeGroupFilter = useMemo<AssigneeGroupedIssuesFilter>(
() => ({
...filter,
@@ -274,6 +286,8 @@ function ProjectIssuesSurface({
wsId,
scope,
assigneeGroupFilter,
+ undefined,
+ sort,
);
// Each view owns exactly one data source. Board/List ride the bucketed
// `myIssueListOptions` cache; the assignee-grouped board uses the grouped
@@ -281,7 +295,7 @@ function ProjectIssuesSurface({
// the current view so switching to Gantt doesn't re-trigger the full
// per-status fetch in the background.
const statusIssuesQuery = useQuery({
- ...myIssueListOptions(wsId, scope, filter),
+ ...myIssueListOptions(wsId, scope, filter, undefined, sort),
enabled: !usesAssigneeBoard && !usesGantt,
});
const assigneeGroupsQuery = useQuery({
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 8e362c82a0..3c9beb34ab 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -833,39 +833,178 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
scheduledFilter = pgtype.Bool{Bool: true, Valid: true}
}
- issues, err := h.Queries.ListIssues(ctx, db.ListIssuesParams{
- WorkspaceID: wsUUID,
- Limit: int32(limit),
- Offset: int32(offset),
- Status: statusFilter,
- Priority: priorityFilter,
- AssigneeID: assigneeFilter,
- AssigneeIds: assigneeIdsFilter,
- CreatorID: creatorFilter,
- ProjectID: projectFilter,
- InvolvesUserID: involvesUserFilter,
- Scheduled: scheduledFilter,
- MetadataFilter: metadataFilter,
- })
+ // Parse sort and direction params for dynamic ORDER BY.
+ // Manual sort (position) is always ASC — direction is ignored because
+ // the user defines order through drag-and-drop, reversing it has no
+ // product meaning.
+ sortCol := "position"
+ if s := r.URL.Query().Get("sort"); s != "" {
+ switch s {
+ case "position", "title", "created_at", "start_date", "due_date":
+ sortCol = s
+ 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"
+ default:
+ writeError(w, http.StatusBadRequest, "invalid sort value")
+ return
+ }
+ }
+ sortDir := "ASC"
+ if sortCol != "position" {
+ if d := r.URL.Query().Get("direction"); d != "" {
+ switch strings.ToLower(d) {
+ case "asc":
+ sortDir = "ASC"
+ case "desc":
+ sortDir = "DESC"
+ default:
+ writeError(w, http.StatusBadRequest, "invalid direction value")
+ return
+ }
+ }
+ }
+
+ // Build dynamic SQL — same approach as ListGroupedIssues.
+ where := []string{"i.workspace_id = $1"}
+ args := []any{wsUUID}
+ addArg := func(v any) string {
+ args = append(args, v)
+ return "$" + strconv.Itoa(len(args))
+ }
+
+ if statusFilter.Valid {
+ where = append(where, fmt.Sprintf("i.status = %s", addArg(statusFilter.String)))
+ }
+ if priorityFilter.Valid {
+ where = append(where, fmt.Sprintf("i.priority = %s", addArg(priorityFilter.String)))
+ }
+ if assigneeFilter.Valid {
+ where = append(where, fmt.Sprintf("i.assignee_id = %s::uuid", addArg(assigneeFilter)))
+ }
+ if len(assigneeIdsFilter) > 0 {
+ where = append(where, fmt.Sprintf("i.assignee_id = ANY(%s::uuid[])", addArg(assigneeIdsFilter)))
+ }
+ if creatorFilter.Valid {
+ where = append(where, fmt.Sprintf("i.creator_id = %s::uuid", addArg(creatorFilter)))
+ }
+ if projectFilter.Valid {
+ where = append(where, fmt.Sprintf("i.project_id = %s::uuid", addArg(projectFilter)))
+ }
+ if scheduledFilter.Valid {
+ where = append(where, "(i.start_date IS NOT NULL OR i.due_date IS NOT NULL)")
+ }
+ if metadataFilter != nil {
+ where = append(where, fmt.Sprintf("i.metadata @> %s::jsonb", addArg(string(metadataFilter))))
+ }
+ if involvesUserFilter.Valid {
+ ref := addArg(involvesUserFilter)
+ where = append(where, fmt.Sprintf(`(
+ (i.assignee_type = 'agent' AND i.assignee_id IN (
+ SELECT a.id FROM agent a
+ WHERE a.workspace_id = $1
+ AND a.owner_id = %[1]s::uuid
+ ))
+ OR (i.assignee_type = 'squad' AND i.assignee_id IN (
+ SELECT sm.squad_id
+ FROM squad_member sm
+ JOIN squad s ON s.id = sm.squad_id
+ WHERE s.workspace_id = $1
+ AND sm.member_type = 'member'
+ AND sm.member_id = %[1]s::uuid
+ UNION
+ SELECT s.id
+ FROM squad s
+ JOIN agent a ON a.id = s.leader_id
+ WHERE s.workspace_id = $1
+ AND a.workspace_id = $1
+ AND a.owner_id = %[1]s::uuid
+ UNION
+ SELECT sm.squad_id
+ FROM squad_member sm
+ JOIN squad s ON s.id = sm.squad_id
+ JOIN agent a ON a.id = sm.member_id
+ WHERE s.workspace_id = $1
+ AND sm.member_type = 'agent'
+ AND a.workspace_id = $1
+ AND a.owner_id = %[1]s::uuid
+ ))
+)`, ref))
+ }
+
+ whereSql := strings.Join(where, " AND ")
+
+ // Build ORDER BY clause.
+ orderBy := sortCol
+ if !strings.HasPrefix(sortCol, "CASE") {
+ orderBy = "i." + sortCol
+ }
+ orderBy += " " + sortDir
+ if sortCol == "start_date" || sortCol == "due_date" {
+ orderBy += " NULLS LAST"
+ }
+ orderBy += ", i.created_at DESC"
+
+ offsetRef := addArg(int64(offset))
+ limitRef := addArg(int64(limit))
+
+ query := fmt.Sprintf(`SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
+ i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata
+FROM issue i
+WHERE %s
+ORDER BY %s
+LIMIT %s OFFSET %s`, whereSql, orderBy, limitRef, offsetRef)
+
+ rows, err := h.DB.Query(ctx, query, args...)
if err != nil {
+ slog.Warn("ListIssues query failed", "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to list issues")
+ return
+ }
+ defer rows.Close()
+
+ var issues []db.ListIssuesRow
+ for rows.Next() {
+ var row db.ListIssuesRow
+ if err := rows.Scan(
+ &row.ID,
+ &row.WorkspaceID,
+ &row.Title,
+ &row.Description,
+ &row.Status,
+ &row.Priority,
+ &row.AssigneeType,
+ &row.AssigneeID,
+ &row.CreatorType,
+ &row.CreatorID,
+ &row.ParentIssueID,
+ &row.Position,
+ &row.StartDate,
+ &row.DueDate,
+ &row.CreatedAt,
+ &row.UpdatedAt,
+ &row.Number,
+ &row.ProjectID,
+ &row.Metadata,
+ ); err != nil {
+ slog.Warn("ListIssues scan failed", "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to list issues")
+ return
+ }
+ issues = append(issues, row)
+ }
+ if err := rows.Err(); err != nil {
+ slog.Warn("ListIssues rows failed", "error", err)
writeError(w, http.StatusInternalServerError, "failed to list issues")
return
}
// Get the true total count for pagination awareness.
- total, err := h.Queries.CountIssues(ctx, db.CountIssuesParams{
- WorkspaceID: wsUUID,
- Status: statusFilter,
- Priority: priorityFilter,
- AssigneeID: assigneeFilter,
- AssigneeIds: assigneeIdsFilter,
- CreatorID: creatorFilter,
- ProjectID: projectFilter,
- InvolvesUserID: involvesUserFilter,
- Scheduled: scheduledFilter,
- MetadataFilter: metadataFilter,
- })
- if err != nil {
+ countQuery := fmt.Sprintf(`SELECT COUNT(*) FROM issue i WHERE %s`, whereSql)
+ // Count query uses the same args minus the OFFSET and LIMIT params (last two added).
+ countArgs := args[:len(args)-2]
+ var total int64
+ if err := h.DB.QueryRow(ctx, countQuery, countArgs...).Scan(&total); err != nil {
total = int64(len(issues))
}
@@ -1194,6 +1333,43 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {
}
}
+ sortCol := "position"
+ if s := r.URL.Query().Get("sort"); s != "" {
+ switch s {
+ case "position", "title", "created_at", "start_date", "due_date":
+ sortCol = s
+ 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"
+ default:
+ writeError(w, http.StatusBadRequest, "invalid sort value")
+ return
+ }
+ }
+ sortDir := "ASC"
+ if sortCol != "position" {
+ if d := r.URL.Query().Get("direction"); d != "" {
+ switch strings.ToLower(d) {
+ case "asc":
+ sortDir = "ASC"
+ case "desc":
+ sortDir = "DESC"
+ default:
+ writeError(w, http.StatusBadRequest, "invalid direction value")
+ return
+ }
+ }
+ }
+
+ intraGroupOrder := sortCol
+ if !strings.HasPrefix(sortCol, "CASE") {
+ intraGroupOrder = "i." + sortCol
+ }
+ intraGroupOrder += " " + sortDir
+ if sortCol == "start_date" || sortCol == "due_date" {
+ intraGroupOrder += " NULLS LAST"
+ }
+ intraGroupOrder += ", i.created_at DESC"
+
offsetRef := addArg(int64(offset))
limitRef := addArg(int64(limit))
query := fmt.Sprintf(`
@@ -1206,7 +1382,7 @@ WITH ranked AS (
COUNT(*) OVER (PARTITION BY i.assignee_type, i.assignee_id) AS group_total,
ROW_NUMBER() OVER (
PARTITION BY i.assignee_type, i.assignee_id
- ORDER BY i.position ASC, i.created_at DESC
+ ORDER BY %s
) AS rn
FROM issue i
WHERE %s
@@ -1227,7 +1403,7 @@ ORDER BY
END,
assignee_type NULLS LAST,
assignee_id NULLS LAST,
- rn`, strings.Join(where, " AND "), offsetRef, offsetRef, limitRef)
+ rn`, intraGroupOrder, strings.Join(where, " AND "), offsetRef, offsetRef, limitRef)
rows, err := h.DB.Query(ctx, query, args...)
if err != nil {