Skip to content

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

Go

MUL-7379 fix: restore per-status sort order and the delegated handoff signal (#8435)

Bohan Jiangff60b2f25a02
diff --git a/packages/views/issues/components/gantt-view.tsx b/packages/views/issues/components/gantt-view.tsx
index 4ab3b2a7a7..d626f67d5e 100644
--- a/packages/views/issues/components/gantt-view.tsx
+++ b/packages/views/issues/components/gantt-view.tsx
@@ -9,7 +9,7 @@ import { useViewStore, useViewStoreApi } from "@multica/core/issues/stores/view-
import type { GanttZoom } from "@multica/core/issues/stores/view-store";
import { projectListOptions } from "@multica/core/projects/queries";
import type { Issue, IssueStatusCategory } from "@multica/core/types";
-import { issueStatusCategory } from "@multica/core/issues";
+import { issueStatusCategory, statusColumnKeys } from "@multica/core/issues";
import { dateOnlyToUTCDate } from "@multica/core/issues/date";
import { cn } from "@multica/ui/lib/utils";
import {
@@ -459,6 +459,10 @@ export function GanttView({ issues }: { issues: Issue[] }) {
const sortBy = useViewStore((s) => s.sortBy);
const sortDirection = useViewStore((s) => s.sortDirection);
const act = useViewStoreApi().getState();
+ // Board order for `sort=status`, archived included: an issue can still sit on
+ // an archived status and has to rank with the rest (MUL-7379).
+ const statusCatalog = useIssueStatuses(useWorkspaceId());
+ const statusOrder = useMemo(() => statusColumnKeys(statusCatalog, true), [statusCatalog]);
const today = useMemo(() => startOfDayUTC(new Date()), []);
const dayPx = DAY_PX_BY_ZOOM[zoom];
@@ -473,8 +477,8 @@ export function GanttView({ issues }: { issues: Issue[] }) {
// "position" makes no sense on a gantt — default to start_date asc when
// the user hasn't picked a more specific sort.
const sortField = sortBy === "position" ? "start_date" : sortBy;
- return sortIssues(issues, sortField, sortDirection);
- }, [issues, sortBy, sortDirection]);
+ return sortIssues(issues, sortField, sortDirection, statusOrder);
+ }, [issues, sortBy, sortDirection, statusOrder]);
const range = useMemo(
() => computeRange(scheduled, today, zoom),
diff --git a/packages/views/issues/components/swimlane-view.tsx b/packages/views/issues/components/swimlane-view.tsx
index 941f0419be..96491beb52 100644
--- a/packages/views/issues/components/swimlane-view.tsx
+++ b/packages/views/issues/components/swimlane-view.tsx
@@ -2,6 +2,7 @@
import {
issueStatusCategory,
+ statusColumnKeys,
} from "@multica/core/issues";
import { memo, useState, useCallback, useMemo, useEffect, useRef } from "react";
import {
@@ -656,6 +657,9 @@ function SwimLaneViewImpl({
const wsId = useWorkspaceId();
const statusCatalog = useIssueStatuses(wsId);
const { categoryOf, entryOf } = statusCatalog;
+ // Board order for `sort=status`, archived included: an issue can still sit
+ // on an archived status and has to rank with the rest (MUL-7379).
+ const statusSortOrder = useMemo(() => statusColumnKeys(statusCatalog, true), [statusCatalog]);
const activeFilters = useMemo(() => ({
// Status is enforced by visible-column rendering, not by filterIssues
@@ -867,7 +871,7 @@ function SwimLaneViewImpl({
: null;
const issueSource = swimlaneGrouping === "parent" ? mergedIssues : issues;
- const sorted = sortIssues(issueSource, sortBy, sortDirection);
+ const sorted = sortIssues(issueSource, sortBy, sortDirection, statusSortOrder);
for (const issue of sorted) {
let placed = false;
for (const lane of laneGroups) {
@@ -903,7 +907,7 @@ function SwimLaneViewImpl({
}
}
return result;
- }, [issues, mergedIssues, laneGroups, sortedStatuses, sortBy, sortDirection, headerIssueIds, swimlaneGrouping]);
+ }, [issues, mergedIssues, laneGroups, sortedStatuses, sortBy, sortDirection, statusSortOrder, headerIssueIds, swimlaneGrouping]);
const laneByKey = useMemo(() => {
const map = new Map<string, LaneGroup>();
diff --git a/packages/views/issues/utils/sort.test.ts b/packages/views/issues/utils/sort.test.ts
index 7729965bb9..e26cca31cc 100644
--- a/packages/views/issues/utils/sort.test.ts
+++ b/packages/views/issues/utils/sort.test.ts
@@ -83,19 +83,57 @@ describe("sortIssues property sorts", () => {
expect(sorted.map((i) => i.id)).toEqual(["newer", "older"]);
});
- it("sorts custom statuses by their effective category", () => {
+ // MUL-7379: ranking on the four lifecycle categories made every status in one
+ // category tie, so a list the user sorted by status came back ordered by the
+ // created_at tiebreak instead.
+ it("keeps the built-ins distinct inside one lifecycle category", () => {
+ const sorted = sortIssues(
+ [
+ staticIssue("blocked", { status: "blocked" }),
+ staticIssue("todo", { status: "todo" }),
+ staticIssue("in_progress", { status: "in_progress" }),
+ staticIssue("backlog", { status: "backlog" }),
+ staticIssue("in_review", { status: "in_review" }),
+ ],
+ "status",
+ "asc",
+ );
+ expect(sorted.map((i) => i.id)).toEqual([
+ "backlog",
+ "todo",
+ "in_progress",
+ "in_review",
+ "blocked",
+ ]);
+ });
+
+ it("ranks custom statuses where the catalog puts them", () => {
const sorted = sortIssues(
[
staticIssue("done", { status: "done" }),
- staticIssue("blocked", {
- status: "waiting_on_vendor",
- status_category: "started",
- }),
+ staticIssue("gate", { status: "waiting_on_vendor" }),
+ staticIssue("in_progress", { status: "in_progress" }),
+ ],
+ "status",
+ "asc",
+ // Catalog order: the gate sits between in_progress and done, which no
+ // ordering of the seven built-ins alone could produce.
+ ["backlog", "todo", "in_progress", "waiting_on_vendor", "in_review", "blocked", "done", "cancelled"],
+ );
+ expect(sorted.map((i) => i.id)).toEqual(["in_progress", "gate", "done"]);
+ });
+
+ it("falls back to built-in order when the catalog has not loaded", () => {
+ const sorted = sortIssues(
+ [
+ staticIssue("custom", { status: "waiting_on_vendor" }),
+ staticIssue("in_review", { status: "in_review" }),
],
"status",
"asc",
);
- expect(sorted.map((i) => i.id)).toEqual(["blocked", "done"]);
+ // Unknown keys rank last rather than being guessed into a category.
+ expect(sorted.map((i) => i.id)).toEqual(["in_review", "custom"]);
});
it("keeps missing dates last in descending order", () => {
diff --git a/packages/views/issues/utils/sort.ts b/packages/views/issues/utils/sort.ts
index 337bc33cbe..ff9e6a9666 100644
--- a/packages/views/issues/utils/sort.ts
+++ b/packages/views/issues/utils/sort.ts
@@ -1,14 +1,19 @@
-import type { Issue } from "@multica/core/types";
-import { issueColumnCategory } from "@multica/core/issues";
-import { PRIORITY_ORDER, STATUS_ORDER } from "@multica/core/issues/config";
+import type { Issue, IssueStatus } from "@multica/core/types";
+import { BUILT_IN_STATUS_ORDER, PRIORITY_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]),
+
+/**
+ * Ranks used when the caller has no catalog yet. The seven built-ins in board
+ * order — never the four lifecycle categories, which would tie Backlog with
+ * Todo and In Progress with In Review and Blocked.
+ */
+const BUILT_IN_STATUS_RANK: Record<string, number> = Object.fromEntries(
+ BUILT_IN_STATUS_ORDER.map((status, index) => [status, index]),
);
function compareOptionalDate(
@@ -23,11 +28,32 @@ function compareOptionalDate(
return dir * (new Date(a).getTime() - new Date(b).getTime());
}
+/**
+ * `statusOrder` is the workspace's status keys in catalog (board) order, from
+ * `statusColumnKeys(catalog, true)`. Sorting by status is a DISPLAY question,
+ * so it ranks on the concrete key; only behavior decisions aggregate on the
+ * four lifecycle categories (MUL-7379).
+ *
+ * Ranking on the category instead collapses seven built-ins into four buckets,
+ * so Blocked interleaves with In Progress and Backlog with Todo in a list the
+ * user explicitly asked to sort by status. Pass the catalog order and custom
+ * statuses also land where the admin put them, matching the board.
+ *
+ * Omit it and the seven built-ins still sort correctly; custom keys fall to the
+ * end. That is the right shape while the catalog query is still loading.
+ */
export function sortIssues(
issues: Issue[],
field: SortField,
- direction: SortDirection
+ direction: SortDirection,
+ statusOrder?: readonly IssueStatus[]
): Issue[] {
+ // Built once per call, not once per comparison: toSorted runs the comparator
+ // O(n log n) times and a linear indexOf inside it would make status sorting
+ // quadratic on a long list.
+ const statusRank = statusOrder
+ ? new Map(statusOrder.map((status, index) => [status, index]))
+ : null;
// `property:<id>` sorts by the custom-property value. Number values sort
// numerically; date values are date-only "YYYY-MM-DD" strings, which sort
// correctly lexically. Direction applies to the VALUE comparison only —
@@ -57,11 +83,13 @@ export function sortIssues(
(PRIORITY_RANK[a.priority] ?? 99) -
(PRIORITY_RANK[b.priority] ?? 99)
);
- case "status":
- return dir * (
- (STATUS_RANK[issueColumnCategory(a)] ?? STATUS_ORDER.length) -
- (STATUS_RANK[issueColumnCategory(b)] ?? STATUS_ORDER.length)
- );
+ case "status": {
+ const rank = (status: string) => {
+ if (statusRank) return statusRank.get(status) ?? statusRank.size;
+ return BUILT_IN_STATUS_RANK[status] ?? BUILT_IN_STATUS_ORDER.length;
+ };
+ return dir * (rank(a.status) - rank(b.status));
+ }
case "start_date":
return compareOptionalDate(a.start_date, b.start_date, direction);
case "due_date":
diff --git a/server/cmd/server/delegated_subscriber_test.go b/server/cmd/server/delegated_subscriber_test.go
index fbeaaf58ec..2fd5a83ba6 100644
--- a/server/cmd/server/delegated_subscriber_test.go
+++ b/server/cmd/server/delegated_subscriber_test.go
@@ -9,6 +9,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/internal/issuestatus"
"github.com/multica-ai/multica/server/internal/testutil"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -454,42 +455,122 @@ func TestUnsubscribeIsDurableAgainstAutoRules(t *testing.T) {
// synthesized "whole batch finished" roll-up; that machinery is gone (see the
// MUL-5483 thread), and the tree-level signal comes from the parent's own status
// transition, which this same rule delivers.
+//
+// Which statuses ARE handoffs is issueStatusIsHandoff's job and is covered by
+// TestIssueStatusIsHandoff; this table covers the routing on top of that answer.
func TestDeliverToSubscriber_DelegatedTier(t *testing.T) {
cases := []struct {
- name string
- reason string
- notifType string
- issueStatus string
- want bool
+ name string
+ reason string
+ notifType string
+ handoff bool
+ want bool
}{
- {"direct subscriber keeps every event", "creator", "status_changed", "in_progress", true},
- {"direct subscriber keeps comments", "assignee", "new_comment", "todo", true},
+ {"direct subscriber keeps every event", "creator", "status_changed", false, true},
+ {"direct subscriber keeps comments", "assignee", "new_comment", false, true},
+
+ {"delegated skips routine progress", "delegated", "status_changed", false, false},
+ {"delegated skips comment churn", "delegated", "new_comment", false, false},
+ {"delegated skips assignee churn", "delegated", "assignee_changed", false, false},
+ {"delegated skips date churn", "delegated", "due_date_changed", false, false},
+ {"delegated skips non-status events even on a handoff", "delegated", "due_date_changed", true, false},
+
+ {"delegated gets the handoff", "delegated", "status_changed", true, true},
+
+ {"delegated always gets direct mentions", "delegated", "mentioned", false, true},
+ {"delegated always gets failures", "delegated", "task_failed", false, true},
+ {"delegated always gets agent_blocked", "delegated", "agent_blocked", false, true},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := deliverToSubscriber(tc.reason, tc.notifType, tc.handoff); got != tc.want {
+ t.Fatalf("deliverToSubscriber(%q, %q, %v) = %v, want %v",
+ tc.reason, tc.notifType, tc.handoff, got, tc.want)
+ }
+ })
+ }
+}
- {"delegated skips routine progress", "delegated", "status_changed", "in_progress", false},
- {"delegated skips backlog parking", "delegated", "status_changed", "backlog", false},
- {"delegated skips todo", "delegated", "status_changed", "todo", false},
- {"delegated skips comment churn", "delegated", "new_comment", "in_progress", false},
- {"delegated skips assignee churn", "delegated", "assignee_changed", "in_progress", false},
- {"delegated skips date churn", "delegated", "due_date_changed", "in_progress", false},
+// TestIssueStatusIsHandoff pins the predicate behind BOTH the delegated tier and
+// the stale task_failed dismissal (MUL-7379).
+//
+// The built-in rows reproduce, exactly, the two hand-kept allowlists this
+// replaced. The custom rows are the regression: before MUL-7240 every custom
+// status projected onto a built-in key, so a custom review gate notified
+// because it "was" in_review; collapsing to four categories left those keys raw
+// and silently stopped them.
+func TestIssueStatusIsHandoff(t *testing.T) {
+ ctx := context.Background()
+ queries := db.New(testPool)
+ workspaceID := util.MustParseUUID(testWorkspaceID)
- {"delegated gets the review handoff", "delegated", "status_changed", "in_review", true},
- {"delegated gets completion", "delegated", "status_changed", "done", true},
- {"delegated gets cancellation", "delegated", "status_changed", "cancelled", true},
- {"delegated gets blocked", "delegated", "status_changed", "blocked", true},
+ custom := func(key, category string) string {
+ t.Helper()
+ suffixed := fmt.Sprintf("%s_%d", key, time.Now().UnixNano()%1_000_000)
+ entry, err := queries.CreateIssueStatusEntry(ctx, db.CreateIssueStatusEntryParams{
+ WorkspaceID: workspaceID,
+ Key: suffixed,
+ Name: suffixed,
+ Description: "",
+ Category: category,
+ Color: "#123456",
+ })
+ if err != nil {
+ t.Fatalf("create custom status %q in %q: %v", suffixed, category, err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM issue_status WHERE id = $1`, entry.ID)
+ })
+ return entry.Key
+ }
- {"delegated always gets direct mentions", "delegated", "mentioned", "in_progress", true},
- {"delegated always gets failures", "delegated", "task_failed", "in_progress", true},
- {"delegated always gets agent_blocked", "delegated", "agent_blocked", "in_progress", true},
+ cases := []struct {
+ name string
+ status string
+ want bool
+ }{
+ // The seven built-ins: identical to the pre-MUL-7379 allowlists.
+ {"backlog is parked, nobody waits", issuestatus.Backlog, false},
+ {"todo is queued, nobody waits", issuestatus.Todo, false},
+ {"in_progress is the platform's own 'working' key", issuestatus.InProgress, false},
+ {"in_review hands over", issuestatus.InReview, true},
+ {"blocked hands over", issuestatus.Blocked, true},
+ {"done is terminal", issuestatus.Done, true},
+ {"cancelled is terminal", issuestatus.Cancelled, true},
+
+ // One custom status per lifecycle category.
+ {"custom unstarted is queued work", custom("later", issuestatus.CategoryUnstarted), false},
+ {"custom started is a review gate", custom("awaiting_response", issuestatus.CategoryStarted), true},
+ {"custom done is terminal", custom("shipped", issuestatus.CategoryDone), true},
+ {"custom closed is terminal", custom("wont_do", issuestatus.CategoryClosed), true},
+
+ // Reserved intake key: its own category, and nobody is waiting on an
+ // issue that has not been accepted yet.
+ {"triage is not a handoff", issuestatus.Triage, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- if got := deliverToSubscriber(tc.reason, tc.notifType, tc.issueStatus); got != tc.want {
- t.Fatalf("deliverToSubscriber(%q, %q, %q) = %v, want %v",
- tc.reason, tc.notifType, tc.issueStatus, got, tc.want)
+ got, err := issueStatusIsHandoff(ctx, queries, workspaceID, tc.status)
+ if err != nil {
+ t.Fatalf("issueStatusIsHandoff(%q): unexpected error: %v", tc.status, err)
+ }
+ if got != tc.want {
+ t.Fatalf("issueStatusIsHandoff(%q) = %v, want %v", tc.status, got, tc.want)
}
})
}
+
+ t.Run("a catalog miss is reported, never guessed", func(t *testing.T) {
+ got, err := issueStatusIsHandoff(ctx, queries, workspaceID, "status_that_was_never_created")
+ if err == nil {
+ t.Fatal("an unresolvable custom key must return an error so each caller picks its own failure direction")
+ }
+ if got {
+ t.Fatal("the error return must not also claim a handoff")
+ }
+ })
}
// TestDelegatedTier_ChildCompletionDeliversExactlyOnce is the case a unit test of
@@ -571,7 +652,7 @@ func TestDelegatedTier_ChildCompletionDeliversExactlyOnce(t *testing.T) {
// unrecognized reason must fall back to FULL delivery — silently dropping a
// user's notifications is the worse failure.
func TestDeliverToSubscriber_UnknownReasonIsDirect(t *testing.T) {
- if !deliverToSubscriber("some_future_reason", "new_comment", "in_progress") {
+ if !deliverToSubscriber("some_future_reason", "new_comment", false) {
t.Fatal("an unrecognized subscription reason must default to full delivery")
}
}
diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.go
index f683ff10f1..2b38a2a2fa 100644
--- a/server/cmd/server/notification_listeners.go
+++ b/server/cmd/server/notification_listeners.go
@@ -87,22 +87,54 @@ var delegatedAlwaysNotifTypes = map[string]bool{
"agent_blocked": true,
}
-// delegatedStatusNotify are the statuses whose ARRIVAL is worth an inbox item
-// for a delegated subscriber — someone whose agent filed this issue on their
-// behalf.
+// issueStatusIsHandoff reports whether ARRIVING on this status hands the issue
+// back to a human. It is the one predicate behind both the delegated-subscriber
+// tier and the stale task_failed dismissal, which used to be two hand-kept
+// allowlists that drifted apart (MUL-7379).
//
-// in_review is the important one: in Multica's agent flow an agent parks
-// completed work in in_review, so that is the dominant "this needs you now"
-// transition, not done.
+// It decides on LIFECYCLE plus one exact key, the split MUL-7364 established:
//
-// Everything absent from this set is churn for someone who never asked for this
-// specific issue: routine forward progress (todo, in_progress), deliberate
-// parking (backlog), comment traffic, and field edits.
-var delegatedStatusNotify = map[string]bool{
- "in_review": true,
- "done": true,
- "cancelled": true,
- "blocked": true,
+// - done / closed are terminal, so arriving there always ends someone's wait;
+// - started is a handoff EXCEPT on the fixed in_progress key. in_progress is
+// the one status the platform itself writes to mean "an agent is working"
+// — the brief tells agents to write it, and failure recovery, the sweeper
+// and the webhook repair all key off it — so arriving there is routine
+// forward progress, not a handoff;
+// - unstarted is never a handoff: nobody is waiting on queued or parked work.
+//
+// That makes a CUSTOM started status a handoff. This is deliberate. A workspace
+// does not mint "Awaiting Response" or "Code Review" to describe an agent
+// typing; it mints one to mark the point where a person has to look. Before
+// MUL-7240 those statuses carried the in_review/blocked category and notified
+// for that reason; collapsing to four categories silently stopped them, which
+// is the regression this restores. A custom status that really is an
+// in_progress synonym now notifies where it did not — an accepted cost, since a
+// missed handoff strands the issue while a spare inbox row costs one dismissal.
+//
+// Triage resolves to its own category and is not a handoff: intake nobody has
+// accepted is not work anybody is waiting on.
+//
+// The error is preserved rather than swallowed so each caller can choose its
+// own failure direction; built-ins answer without touching the catalog, so only
+// custom statuses can fail here at all.
+func issueStatusIsHandoff(
+ ctx context.Context,
+ queries *db.Queries,
+ workspaceID pgtype.UUID,
+ status string,
+) (bool, error) {
+ category, err := issuestatus.CategoryWithError(ctx, queries, workspaceID, status)
+ if err != nil {
+ return false, err
+ }
+ switch category {
+ case issuestatus.CategoryDone, issuestatus.CategoryClosed:
+ return true, nil
+ case issuestatus.CategoryStarted:
+ return status != issuestatus.InProgress, nil
+ default:
+ return false, nil
+ }
}
// deliverToSubscriber reports whether a subscriber row should receive this
@@ -119,7 +151,11 @@ var delegatedStatusNotify = map[string]bool{
// as well, so when the agent moves the parent to in_review/done that transition
// delivers here — which is the natural "the tree is done" signal. Deriving it
// from children was reinventing a notification the platform already sends.
-func deliverToSubscriber(reason, notifType, issueStatus string) bool {
+//
+// statusIsHandoff is the resolved issueStatusIsHandoff answer for the issue's
+// current status, so the catalog is read once per notification rather than once
+// per subscriber row.
+func deliverToSubscriber(reason, notifType string, statusIsHandoff bool) bool {
if reason != "delegated" {
return true
}
@@ -129,7 +165,7 @@ func deliverToSubscriber(reason, notifType, issueStatus string) bool {
if notifType != "status_changed" {
return false
}
- return delegatedStatusNotify[issueStatus]
+ return statusIsHandoff
}
// notifTypeToGroup maps each InboxItemType to a user-configurable preference
@@ -197,19 +233,6 @@ func loadUserPrefs(
return result
}
-// terminalStatusForTaskFailedDismiss is the set of issue statuses that mark
-// the issue as "the user no longer needs to triage past failures." When a
-// status change lands on one of these, any pre-existing task_failed inbox
-// rows for the issue are archived so the inbox stays a fresh-signal surface.
-// `in_review` is included because in Multica's agent flow that's the most
-// reliable "work delivered" handoff — and a status flip back to in_progress
-// will simply produce new task_failed rows that surface normally.
-var terminalStatusForTaskFailedDismiss = map[string]bool{
- "in_review": true,
- "done": true,
- "cancelled": true,
-}
-
// archiveStaleTaskFailedInbox archives all task_failed inbox rows for the
// given issue and notifies each affected member recipient via
// inbox:batch-archived so connected clients self-heal.
@@ -362,11 +385,20 @@ func notifyIssueSubscribers(
notified := map[string]bool{}
tierSuppressed := map[string]bool{}
- // Normalize a custom status to the canonical status it inherits, so the
- // delegated tier's status allowlist below keys off behavior rather than a
- // literal. A built-in key returns itself without a query, so the common
- // path is unchanged. (MUL-6243)
- issueStatus = issuestatus.Effective(ctx, queries, parseUUID(workspaceID), issueStatus)
+ // Resolve the handoff question once for the whole subscriber list, rather
+ // than per row. A built-in key answers without a query, so the common path
+ // still performs no I/O. (MUL-7379)
+ //
+ // FAIL OPEN. A catalog read can only fail for a CUSTOM status, and the two
+ // outcomes are not symmetric: a spare inbox row costs one dismissal, while
+ // a dropped one silently strands the issue on a status whose whole purpose
+ // is to be waited on, with no other signal to the delegated subscriber.
+ statusIsHandoff, err := issueStatusIsHandoff(ctx, queries, parseUUID(workspaceID), issueStatus)
+ if err != nil {
+ slog.Warn("resolve issue status handoff for delegated delivery; delivering",
+ "issue_id", subscriberIssueID, "status", issueStatus, "error", err)
+ statusIsHandoff = true
+ }
subs, err := queries.ListIssueSubscribers(ctx, parseUUID(subscriberIssueID))
if err != nil {
@@ -409,7 +441,7 @@ func notifyIssueSubscribers(
// Delegated subscriptions deliver a narrower event set than direct
// ones — see deliverToSubscriber.
- if !deliverToSubscriber(sub.Reason, notifType, issueStatus) {
+ if !deliverToSubscriber(sub.Reason, notifType, statusIsHandoff) {
tierSuppressed[subID] = true
continue
}
@@ -763,13 +795,25 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {
issue.Title, "",
statusDetails)
- // When the issue progresses past the failure (in_review / done /
- // cancelled), retire any stale task_failed inbox rows so the
- // inbox reflects the current state of the work, not its history.
- // The activity log keeps the full failure history for audit.
- if terminalStatusForTaskFailedDismiss[issuestatus.Effective(
- ctx, queries, parseUUID(e.WorkspaceID), issue.Status,
- )] {
+ // When the issue progresses past the failure, retire any stale
+ // task_failed inbox rows so the inbox reflects the current state of
+ // the work, not its history. The activity log keeps the full
+ // failure history for audit.
+ //
+ // Same handoff predicate as the delegated tier, minus Blocked:
+ // blocked hands the issue to a human, but it hands over work that
+ // is still stuck, so the past failures remain worth triaging.
+ // Blocked is excluded by its exact key — a custom started status is
+ // a review gate, not a stall. (MUL-7379)
+ //
+ // FAIL CLOSED here, unlike delivery: hiding a failure notice on a
+ // guess is worse than leaving a stale one the user can dismiss.
+ handoff, handoffErr := issueStatusIsHandoff(ctx, queries, parseUUID(e.WorkspaceID), issue.Status)
+ switch {
+ case handoffErr != nil:
+ slog.Warn("resolve issue status handoff for task_failed dismissal; keeping rows",
+ "issue_id", issue.ID, "status", issue.Status, "error", handoffErr)
+ case handoff && issue.Status != issuestatus.Blocked:
archiveStaleTaskFailedInbox(ctx, queries, bus, e.WorkspaceID, issue.ID)
}
}
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index 7b84c508a2..8715f05e3a 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -706,12 +706,15 @@ func broadcastFailedTasks(ctx context.Context, queries *db.Queries, taskSvc *ser
workspaceID = util.UUIDToString(issue.WorkspaceID)
issueKey := util.UUIDToString(t.IssueID)
// Only issues whose status means "an agent is actively working"
- // get reset. in_review and blocked are deliberately excluded —
- // they mean a human or an external dependency owns the issue
- // now, and resetting those to todo would re-trigger an agent on
- // work someone else is holding. A custom status resolves to the
- // canonical status it inherits, so a custom review gate is
- // excluded for the same reason In Review is. (MUL-6243)
+ // get reset, which since MUL-7240 is the fixed in_progress key
+ // alone. in_review and blocked are deliberately excluded — they
+ // mean a human or an external dependency owns the issue now,
+ // and resetting those to todo would re-trigger an agent on work
+ // someone else is holding. A CUSTOM started status is excluded
+ // because custom statuses inherit lifecycle only, not the
+ // active-status recovery rule; Effective() no longer projects a
+ // nonterminal custom key onto a built-in, so this is a key
+ // comparison on purpose. (MUL-6243, MUL-7240)
effectiveStatus := issuestatus.Effective(ctx, queries, issue.WorkspaceID, issue.Status)
if effectiveStatus == "in_progress" && !processedIssues[issueKey] {
processedIssues[issueKey] = true
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 8d04795b79..bd020e62b2 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -120,8 +120,22 @@ var validIssuePriorities = []string{"urgent", "high", "medium", "low", "none"}
var validIssueStatuses = issuestatus.Canonical()
var validIssueStatusCategories = issuestatus.Categories()
-// Status sort follows the board's category order and resolves custom keys to
-// their effective category with one catalog read plus a parameterized CASE.
+// Status sort ranks by the CONCRETE status key, in the catalog's own display
+// order. Sorting is a display question, so it resolves on status; only behavior
+// decisions aggregate on the four lifecycle categories (MUL-7379).
+//
+// Ranking by category instead collapses the seven built-ins into four buckets —
+// Backlog ties with Todo, and In Progress / In Review / Blocked all tie — which
+// leaves the created_at tiebreak deciding the visible order of a list the user
+// explicitly asked to sort by status.
+//
+// issueTableStatusOrder is the same "board order" the status GROUPING path
+// already builds, so sorting and grouping now share one source of truth instead
+// of drifting apart. Archived statuses are included because issues stay on them
+// after archival and still have to rank somewhere real. Triage leads: it has no
+// catalog row and no board column, matching the rank statusOrderExpression
+// gives it.
+//
// 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(
@@ -129,15 +143,18 @@ func (h *Handler) issueStatusSortExpression(
workspaceID pgtype.UUID,
addArg func(any) string,
) (string, error) {
- customKeys, err := issuestatus.CustomKeyCategories(
- ctx,
- h.issueStatusCatalog(),
- workspaceID,
- )
+ entries, err := h.issueStatusCatalog().ListIssueStatusEntries(ctx, db.ListIssueStatusEntriesParams{
+ WorkspaceID: workspaceID,
+ IncludeArchived: true,
+ })
if err != nil {
return "", err
}
- return statusOrderExpression(statusCategoryExpr(customKeys, addArg)), nil
+ order := append([]string{issuestatus.Triage}, issueTableStatusOrder(entries)...)
+ return fmt.Sprintf(
+ "COALESCE(array_position(%s::text[], i.status), 100000)",
+ addArg(order),
+ ), nil
}
// resolveIssueStatusKey checks a status against the workspace's catalog and
diff --git a/server/internal/handler/issue_sort_test.go b/server/internal/handler/issue_sort_test.go
index 83ea996c1b..c9867c246e 100644
--- a/server/internal/handler/issue_sort_test.go
+++ b/server/internal/handler/issue_sort_test.go
@@ -188,3 +188,123 @@ func TestListIssuesSortsByStatusAndUpdatedAt(t *testing.T) {
"sort-done",
})
}
+
+// TestListIssuesStatusSortFollowsCatalogOrder pins that `sort=status` ranks by
+// the CONCRETE status key in catalog order, not by lifecycle category
+// (MUL-7379).
+//
+// Sibling test TestListIssuesSortsByStatusAndUpdatedAt cannot catch the
+// regression this guards: it uses one issue per lifecycle category, so a
+// four-bucket ranking and a per-status ranking produce the same output. Here
+// the unstarted group holds backlog AND todo, and the started group holds
+// in_progress, in_review and blocked — collapsing to categories ties every one
+// of those and lets the created_at tiebreak decide.
+//
+// The custom Started status is wedged BETWEEN two built-ins by position, which
+// is what separates "ranks by the catalog" from "ranks by a hardcoded list of
+// the seven built-ins": no static ordering of the built-ins can produce it.
+func TestListIssuesStatusSortFollowsCatalogOrder(t *testing.T) {
+ ctx := context.Background()
+ suffix := time.Now().UnixNano()
+
+ customKey := fmt.Sprintf("sort_gate_%d", suffix%1_000_000)
+ createTestCustomStatus(t, customKey, "started")
+
+ // Built-ins all seed at position 0 and tie-break on their fixed rank, so the
+ // custom status can only land before or after the whole group until the
+ // Started positions are spread out. Restore them afterwards: the workspace
+ // catalog is shared with every other test in this package.
+ setPosition := func(key string, position float64) {
+ t.Helper()
+ if _, err := testPool.Exec(ctx,
+ `UPDATE issue_status SET position = $3 WHERE workspace_id = $1 AND key = $2`,
+ testWorkspaceID, key, position,
+ ); err != nil {
+ t.Fatalf("set position for %q: %v", key, err)
+ }
+ }
+ for _, key := range []string{"in_progress", "in_review", "blocked"} {
+ t.Cleanup(func() { setPosition(key, 0) })
+ }
+ setPosition("in_progress", 10)
+ setPosition("in_review", 20)
+ setPosition(customKey, 30)
+ setPosition("blocked", 40)
+
+ var projectID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO project (workspace_id, title) VALUES ($1, $2) RETURNING id
+ `, testWorkspaceID, fmt.Sprintf("Status sort order %d", suffix)).Scan(&projectID); err != nil {
+ t.Fatalf("create project: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID)
+ })
+
+ // Inserted newest-first so created_at DESC — the tiebreak a category
+ // ranking would fall through to — is the REVERSE of the expected order.
+ // A four-bucket ranking therefore cannot accidentally pass this.
+ boardOrder := []string{
+ "backlog", "todo", "in_progress", "in_review", customKey, "blocked", "done", "cancelled",
+ }
+ titles := make([]string, 0, len(boardOrder))
+ for i, status := range boardOrder {
+ title := fmt.Sprintf("order-%02d-%s", i, status)
+ titles = append(titles, title)
+ var number int
+ if err := testPool.QueryRow(ctx, `
+ UPDATE workspace
+ SET issue_counter = GREATEST(issue_counter, (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)) + 1
+ WHERE id = $1 RETURNING issue_counter
+ `, testWorkspaceID).Scan(&number); err != nil {
+ t.Fatalf("next issue number: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO issue (
+ workspace_id, title, status, priority, creator_type, creator_id,
+ position, number, project_id, created_at, updated_at, last_activity_at
+ )
+ VALUES ($1, $2, $3, 'none', 'member', $4, $5, $6, $7, $8, $8, $8)
+ `, testWorkspaceID, title, status, testUserID, i, number, projectID,
+ time.Now().Add(-time.Duration(i)*time.Minute),
+ ); err != nil {
+ t.Fatalf("create issue %q: %v", title, err)
+ }
+ }
+
+ got := func(direction string) []string {
+ t.Helper()
+ path := fmt.Sprintf(
+ "/api/issues?workspace_id=%s&project_id=%s&limit=50&sort=status&direction=%s",
+ testWorkspaceID, projectID, direction,
+ )
+ w := httptest.NewRecorder()
+ testHandler.ListIssues(w, newRequest("GET", path, nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("ListIssues: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var response struct {
+ Issues []IssueResponse `json:"issues"`
+ }
+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ out := make([]string, 0, len(response.Issues))
+ for _, issue := range response.Issues {
+ out = append(out, issue.Title)
+ }
+ return out
+ }
+
+ if asc := got("asc"); fmt.Sprint(asc) != fmt.Sprint(titles) {
+ t.Fatalf("sort=status asc\n got %v\n want %v", asc, titles)
+ }
+
+ reversed := make([]string, len(titles))
+ for i, title := range titles {
+ reversed[len(titles)-1-i] = title
+ }
+ if desc := got("desc"); fmt.Sprint(desc) != fmt.Sprint(reversed) {
+ t.Fatalf("sort=status desc\n got %v\n want %v", desc, reversed)
+ }
+}
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index f34e32a51a..670e4a12e9 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -332,7 +332,33 @@ func (s *AutopilotService) ensureWebhookCreateIssueTask(ctx context.Context, aut
if err != nil {
return fmt.Errorf("dispatch for webhook delivery: load linked issue: %w", err)
}
- if effective := issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status); effective != "todo" && effective != "in_progress" {
+ // Repair only work that is still waiting to be picked up. Decided on
+ // lifecycle plus the two exact keys whose behavior does not generalize,
+ // the split MUL-7364 established (MUL-7379):
+ //
+ // - the fixed in_progress key means an agent is already working, so the
+ // lost task is still the right thing to create;
+ // - an unstarted status other than the fixed backlog key is queued work.
+ // Backlog is parked, and only the literal key parks — a custom
+ // unstarted status does not inherit parking, exactly as WillEnqueueRun
+ // treats it;
+ // - anything else — in_review, blocked, a CUSTOM started status, or a
+ // terminal one — means a human took the issue over during the crash
+ // window. Starting an agent on it then is the surprise this guard
+ // exists to prevent.
+ //
+ // Before MUL-7240 this read Effective() and compared against todo /
+ // in_progress, which also matched custom statuses because every one of them
+ // projected onto a built-in key. Collapsing to four categories left those
+ // custom keys raw, so the guard silently stopped repairing any workspace
+ // with a custom status and the run sat in issue_created with no task.
+ category, err := issuestatus.CategoryWithError(ctx, s.Queries, issue.WorkspaceID, issue.Status)
+ if err != nil {
+ return fmt.Errorf("dispatch for webhook delivery: resolve issue lifecycle: %w", err)
+ }
+ runnable := issue.Status == issuestatus.InProgress ||
+ (category == issuestatus.CategoryUnstarted && issue.Status != issuestatus.Backlog)
+ if !runnable {
return nil
}
if autopilot.AssigneeType == "squad" {
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 90371b40fc..0dc03c40f3 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -5861,11 +5861,14 @@ func (s *TaskService) HandleFailedTasks(ctx context.Context, tasks []db.AgentTas
// Reset stuck in_progress issues only when no other active
// task exists for the issue and no retry was just enqueued.
issueKey := util.UUIDToString(t.IssueID)
- // Only "an agent is actively working" resets. in_review and
- // blocked are excluded — a human or an external dependency owns
- // the issue then — and a custom status resolves to the canonical
- // status it inherits, so a custom review gate is excluded for
- // the same reason In Review is. (MUL-6243)
+ // Only "an agent is actively working" resets, and since
+ // MUL-7240 that is the fixed in_progress key alone. in_review
+ // and blocked are excluded because a human or an external
+ // dependency owns the issue then; a CUSTOM started status is
+ // excluded because custom statuses inherit lifecycle only, not
+ // the active-status recovery rule. Effective() no longer
+ // projects a nonterminal custom key onto a built-in, so this is
+ // a key comparison on purpose. (MUL-6243, MUL-7240)
effectiveStatus := issuestatus.Effective(ctx, s.Queries, issue.WorkspaceID, issue.Status)
if effectiveStatus == "in_progress" && !processedIssues[issueKey] && !retriedIssues[issueKey] {
processedIssues[issueKey] = true