Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5824 fix(search): demote cancelled issues and projects below live work (#6515)
Jiayuan Zhang45027c1db6cf
diff --git a/apps/mobile/app/(app)/[workspace]/search.tsx b/apps/mobile/app/(app)/[workspace]/search.tsxindex 91a33637fb..9d9cb48d7e 100644--- a/apps/mobile/app/(app)/[workspace]/search.tsx+++ b/apps/mobile/app/(app)/[workspace]/search.tsx@@ -6,8 +6,9 @@* workspace switching in Settings, so a command-palette here would* duplicate them (see feedback_mobile_ia_main_vs_more).*- * Result categories, ordering (projects first, issues second), debounce- * (300ms), abort policy, and Recent rendering mirror the web source.+ * Result categories, ordering (live projects, then live issues, then a+ * trailing Cancelled section — see lib/search-rows.ts), debounce (300ms),+ * abort policy, and Recent rendering mirror the web source.* Highlight + snippet line for `match_source` matches preserves the* "why did this match" signal users rely on when scanning results.*/@@ -46,6 +47,7 @@ import {import { issueDetailOptions } from "@/data/queries/issues";import { STATUS_LABEL } from "@/lib/issue-status";import { projectStatusLabel } from "@/lib/project-status";+import { buildSearchRows, type RowItem } from "@/lib/search-rows";const DEBOUNCE_MS = 300;const ISSUE_LIMIT = 20;@@ -115,12 +117,8 @@ function HighlightText({// =====================================================// Row item types — drives the single FlatList render// =====================================================--type RowItem =- | { kind: "header"; key: string; title: string }- | { kind: "issue"; key: string; issue: SearchIssueResult; query: string }- | { kind: "project"; key: string; project: SearchProjectResult; query: string }- | { kind: "recent"; key: string; issue: Issue };+// RowItem + buildSearchRows live in lib/search-rows.ts so the ordering rules+// (including the cancelled partition) are testable without mounting the screen.function issueIconColor(status: IssueStatus): string {// Tag color for the status label at the end of an issue row.@@ -389,35 +387,19 @@ export default function SearchModal() {results.issues.length > 0 || results.projects.length > 0;// Build the FlatList data. One flat array of discriminated rows means a- // single virtualised list covers Recent (empty-state) and (Projects +- // Issues) results without nesting SectionList inside another scroller.- const data = useMemo<RowItem[]>(() => {- if (!trimmedQuery) {- if (recentIssues.length === 0) return [];- return [- { kind: "header", key: "h-recent", title: "Recent" },- ...recentIssues.map<RowItem>((issue) => ({- kind: "recent",- key: `r-${issue.id}`,- issue,- })),- ];- }- const items: RowItem[] = [];- if (results.projects.length > 0) {- items.push({ kind: "header", key: "h-projects", title: "Projects" });- for (const p of results.projects) {- items.push({ kind: "project", key: `p-${p.id}`, project: p, query: trimmedQuery });- }- }- if (results.issues.length > 0) {- items.push({ kind: "header", key: "h-issues", title: "Issues" });- for (const it of results.issues) {- items.push({ kind: "issue", key: `i-${it.id}`, issue: it, query: trimmedQuery });- }- }- return items;- }, [trimmedQuery, recentIssues, results]);+ // single virtualised list covers Recent (empty-state) and the search results+ // without nesting SectionList inside another scroller. Ordering lives in+ // buildSearchRows (lib/search-rows.ts).+ const data = useMemo<RowItem[]>(+ () =>+ buildSearchRows({+ query,+ issues: results.issues,+ projects: results.projects,+ recentIssues,+ }),+ [query, results, recentIssues],+ );const renderItem = useCallback<ListRenderItem<RowItem>>(({ item }) => {diff --git a/apps/mobile/lib/search-rows.test.ts b/apps/mobile/lib/search-rows.test.tsnew file mode 100644index 0000000000..9e2dc344c8--- /dev/null+++ b/apps/mobile/lib/search-rows.test.ts@@ -0,0 +1,120 @@+import { describe, it, expect } from "vitest";+import type {+ Issue,+ SearchIssueResult,+ SearchProjectResult,+} from "@multica/core/types";+import { buildSearchRows } from "./search-rows";++function issue(+ partial: Partial<SearchIssueResult> & { id: string },+): SearchIssueResult {+ return {+ id: partial.id,+ number: partial.number ?? 1,+ identifier: partial.identifier ?? `MUL-${partial.number ?? 1}`,+ title: partial.title ?? "Untitled",+ status: partial.status ?? "todo",+ match_source: partial.match_source ?? "title",+ } as SearchIssueResult;+}++function project(+ partial: Partial<SearchProjectResult> & { id: string },+): SearchProjectResult {+ return {+ id: partial.id,+ title: partial.title ?? "Untitled",+ status: partial.status ?? "in_progress",+ match_source: partial.match_source ?? "title",+ } as SearchProjectResult;+}++/** Header titles and row keys, top to bottom — what the user actually sees. */+const shape = (rows: ReturnType<typeof buildSearchRows>) =>+ rows.map((r) => (r.kind === "header" ? `#${r.title}` : r.key));++describe("buildSearchRows", () => {+ it("renders Recent for an empty query", () => {+ const rows = buildSearchRows({+ query: " ",+ issues: [],+ projects: [],+ recentIssues: [{ id: "r1" } as Issue, { id: "r2" } as Issue],+ });+ expect(shape(rows)).toEqual(["#Recent", "r-r1", "r-r2"]);+ });++ it("returns nothing when there is neither a query nor recent history", () => {+ expect(+ buildSearchRows({ query: "", issues: [], projects: [], recentIssues: [] }),+ ).toEqual([]);+ });++ // MUL-5824 regression: this screen renders every project before every issue,+ // so a cancelled project used to be the first row even next to a live issue.+ it("puts a cancelled project below a live issue instead of first", () => {+ const rows = buildSearchRows({+ query: "search",+ issues: [issue({ id: "i-live", title: "search live", status: "in_progress" })],+ projects: [project({ id: "p-dead", title: "search dead", status: "cancelled" })],+ recentIssues: [],+ });++ expect(shape(rows)).toEqual([+ "#Issues",+ "i-i-live",+ "#Cancelled",+ "p-p-dead",+ ]);+ });++ it("keeps live rows of both types above every cancelled row", () => {+ const rows = buildSearchRows({+ query: "search",+ issues: [+ issue({ id: "i-dead", number: 1, title: "search a", status: "cancelled" }),+ issue({ id: "i-live", number: 2, title: "search b", status: "todo" }),+ issue({ id: "i-done", number: 3, title: "search c", status: "done" }),+ ],+ projects: [+ project({ id: "p-dead", title: "search p1", status: "cancelled" }),+ project({ id: "p-live", title: "search p2", status: "planned" }),+ ],+ recentIssues: [],+ });++ expect(shape(rows)).toEqual([+ "#Projects",+ "p-p-live",+ "#Issues",+ // 'done' stays live — only cancelled work is demoted.+ "i-i-live",+ "i-i-done",+ "#Cancelled",+ "p-p-dead",+ "i-i-dead",+ ]);+ });++ it("keeps a cancelled direct hit at the top", () => {+ const rows = buildSearchRows({+ query: "MUL-7",+ issues: [issue({ id: "i-hit", number: 7, identifier: "MUL-7", status: "cancelled" })],+ projects: [],+ recentIssues: [],+ });++ expect(shape(rows)).toEqual(["#Issues", "i-i-hit"]);+ });++ it("omits the Cancelled section when nothing is demoted", () => {+ const rows = buildSearchRows({+ query: "search",+ issues: [issue({ id: "i1", status: "todo" })],+ projects: [project({ id: "p1", status: "completed" })],+ recentIssues: [],+ });+ expect(shape(rows)).toEqual(["#Projects", "p-p1", "#Issues", "i-i1"]);+ });+});diff --git a/apps/mobile/lib/search-rows.ts b/apps/mobile/lib/search-rows.tsnew file mode 100644index 0000000000..0006f07697--- /dev/null+++ b/apps/mobile/lib/search-rows.ts@@ -0,0 +1,88 @@+/**+ * Row model for the workspace search screen's single FlatList.+ *+ * Extracted from app/(app)/[workspace]/search.tsx so the ordering rules — in+ * particular the cross-type cancelled demotion (MUL-5824) — are unit-testable+ * without mounting the screen.+ */+import type {+ Issue,+ SearchIssueResult,+ SearchProjectResult,+} from "@multica/core/types";+import { partitionAggregatedSearchResults } from "@multica/core/search/cancelled-rank";++export type RowItem =+ | { kind: "header"; key: string; title: string }+ | { kind: "issue"; key: string; issue: SearchIssueResult; query: string }+ | { kind: "project"; key: string; project: SearchProjectResult; query: string }+ | { kind: "recent"; key: string; issue: Issue };++/**+ * Builds the flat row list. Empty query → the Recent section; otherwise the+ * search results in cancelled-partition order:+ *+ * Projects (live) → Issues (live) → Cancelled (projects then issues)+ *+ * Projects and issues come from two independently ranked responses, and this+ * screen renders every project before every issue — so per-type ranking alone+ * let a single cancelled project be the first row of the list. One trailing+ * Cancelled section is the only arrangement in which no cancelled row of either+ * type can precede a live row of the other. Direct hits (exact identifier,+ * number, or title) stay in their live section.+ */+export function buildSearchRows({+ query,+ issues,+ projects,+ recentIssues,+}: {+ query: string;+ issues: SearchIssueResult[];+ projects: SearchProjectResult[];+ recentIssues: Issue[];+}): RowItem[] {+ const trimmedQuery = query.trim();++ if (!trimmedQuery) {+ if (recentIssues.length === 0) return [];+ return [+ { kind: "header", key: "h-recent", title: "Recent" },+ ...recentIssues.map<RowItem>((issue) => ({+ kind: "recent",+ key: `r-${issue.id}`,+ issue,+ })),+ ];+ }++ const parts = partitionAggregatedSearchResults({+ issues,+ projects,+ query: trimmedQuery,+ });++ const rows: RowItem[] = [];+ if (parts.liveProjects.length > 0) {+ rows.push({ kind: "header", key: "h-projects", title: "Projects" });+ for (const project of parts.liveProjects) {+ rows.push({ kind: "project", key: `p-${project.id}`, project, query: trimmedQuery });+ }+ }+ if (parts.liveIssues.length > 0) {+ rows.push({ kind: "header", key: "h-issues", title: "Issues" });+ for (const issue of parts.liveIssues) {+ rows.push({ kind: "issue", key: `i-${issue.id}`, issue, query: trimmedQuery });+ }+ }+ if (parts.hasCancelled) {+ rows.push({ kind: "header", key: "h-cancelled", title: "Cancelled" });+ for (const project of parts.cancelledProjects) {+ rows.push({ kind: "project", key: `p-${project.id}`, project, query: trimmedQuery });+ }+ for (const issue of parts.cancelledIssues) {+ rows.push({ kind: "issue", key: `i-${issue.id}`, issue, query: trimmedQuery });+ }+ }+ return rows;+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex ebcea46715..61bfad1634 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -73,6 +73,7 @@"./squads": "./squads/index.ts","./squads/stores": "./squads/stores/index.ts","./permissions": "./permissions/index.ts",+ "./search/cancelled-rank": "./search/cancelled-rank.ts","./projects": "./projects/index.ts","./projects/queries": "./projects/queries.ts","./projects/mutations": "./projects/mutations.ts",diff --git a/packages/core/search/cancelled-rank.test.ts b/packages/core/search/cancelled-rank.test.tsnew file mode 100644index 0000000000..f80d79c64c--- /dev/null+++ b/packages/core/search/cancelled-rank.test.ts@@ -0,0 +1,159 @@+import { describe, it, expect } from "vitest";+import type { SearchIssueResult, SearchProjectResult } from "../types/api";+import {+ isIssueDirectHit,+ isProjectDirectHit,+ parseSearchQueryNumber,+ partitionAggregatedSearchResults,+ partitionStable,+} from "./cancelled-rank";++function issue(+ partial: Partial<SearchIssueResult> & { id: string },+): SearchIssueResult {+ return {+ id: partial.id,+ number: partial.number ?? 1,+ identifier: partial.identifier ?? `MUL-${partial.number ?? 1}`,+ title: partial.title ?? "Untitled",+ status: partial.status ?? "todo",+ match_source: partial.match_source ?? "title",+ } as SearchIssueResult;+}++function project(+ partial: Partial<SearchProjectResult> & { id: string },+): SearchProjectResult {+ return {+ id: partial.id,+ title: partial.title ?? "Untitled",+ status: partial.status ?? "in_progress",+ match_source: partial.match_source ?? "title",+ } as SearchProjectResult;+}++describe("parseSearchQueryNumber", () => {+ it("reads an identifier and a bare number, like the server does", () => {+ expect(parseSearchQueryNumber("MUL-123")).toBe(123);+ expect(parseSearchQueryNumber("mul-123")).toBe(123);+ expect(parseSearchQueryNumber(" 123 ")).toBe(123);+ });++ it("returns null for anything that is not a target", () => {+ expect(parseSearchQueryNumber("search")).toBeNull();+ expect(parseSearchQueryNumber("MUL-")).toBeNull();+ expect(parseSearchQueryNumber("0")).toBeNull();+ expect(parseSearchQueryNumber("")).toBeNull();+ });+});++describe("direct hits", () => {+ it("treats an exact identifier, number, or title as targeting the issue", () => {+ const it1 = issue({ id: "i1", number: 42, identifier: "MUL-42", title: "Ship it" });+ expect(isIssueDirectHit(it1, "MUL-42")).toBe(true);+ expect(isIssueDirectHit(it1, "42")).toBe(true);+ expect(isIssueDirectHit(it1, " ship IT ")).toBe(true);+ expect(isIssueDirectHit(it1, "ship")).toBe(false);+ });++ it("treats only an exact title as targeting the project", () => {+ const p = project({ id: "p1", title: "Search revamp" });+ expect(isProjectDirectHit(p, "search revamp")).toBe(true);+ expect(isProjectDirectHit(p, "search")).toBe(false);+ expect(isProjectDirectHit(p, "")).toBe(false);+ });++ // The @mention picker holds the identifier and title but no `number`, so the+ // number has to be derived from the identifier for it to share this rule.+ it("derives the issue number from the identifier when number is absent", () => {+ const row = { identifier: "MUL-77", title: "Abandoned plan" };+ expect(isIssueDirectHit(row, "77")).toBe(true);+ expect(isIssueDirectHit(row, "MUL-77")).toBe(true);+ expect(isIssueDirectHit(row, "mul-77")).toBe(true);+ expect(isIssueDirectHit(row, "Abandoned plan")).toBe(true);+ expect(isIssueDirectHit(row, "plan")).toBe(false);+ expect(isIssueDirectHit(row, "78")).toBe(false);+ });++ it("prefers an explicit number over the identifier", () => {+ // Defensive: if the two ever disagree, `number` is the authoritative field.+ const row = { number: 42, identifier: "MUL-77", title: "t" };+ expect(isIssueDirectHit(row, "42")).toBe(true);+ expect(isIssueDirectHit(row, "77")).toBe(false);+ });++ it("is not a direct hit when nothing identifies the row", () => {+ expect(isIssueDirectHit({}, "MUL-1")).toBe(false);+ expect(isProjectDirectHit({}, "anything")).toBe(false);+ });+});++describe("partitionStable", () => {+ it("preserves relative order on both sides", () => {+ const { live, cancelled } = partitionStable(+ [1, 2, 3, 4, 5, 6],+ (n) => n % 2 === 0,+ );+ expect(live).toEqual([1, 3, 5]);+ expect(cancelled).toEqual([2, 4, 6]);+ });+});++describe("partitionAggregatedSearchResults", () => {+ it("keeps a cancelled project out of the leading slot a live issue deserves", () => {+ // The regression Sol-Boy flagged: the palette renders every project before+ // every issue, so one cancelled project used to be the first row overall.+ const parts = partitionAggregatedSearchResults({+ issues: [issue({ id: "i-live", number: 2, title: "search live", status: "in_progress" })],+ projects: [project({ id: "p-cancelled", title: "search cancelled", status: "cancelled" })],+ query: "search",+ });++ expect(parts.liveProjects).toEqual([]);+ expect(parts.liveIssues.map((i) => i.id)).toEqual(["i-live"]);+ expect(parts.cancelledProjects.map((p) => p.id)).toEqual(["p-cancelled"]);+ expect(parts.hasCancelled).toBe(true);+ });++ it("demotes cancelled rows of both types while keeping server order within each side", () => {+ const parts = partitionAggregatedSearchResults({+ issues: [+ issue({ id: "i1", number: 1, title: "search a", status: "cancelled" }),+ issue({ id: "i2", number: 2, title: "search b", status: "todo" }),+ issue({ id: "i3", number: 3, title: "search c", status: "cancelled" }),+ issue({ id: "i4", number: 4, title: "search d", status: "done" }),+ ],+ projects: [+ project({ id: "p1", title: "search p1", status: "cancelled" }),+ project({ id: "p2", title: "search p2", status: "planned" }),+ ],+ query: "search",+ });++ expect(parts.liveProjects.map((p) => p.id)).toEqual(["p2"]);+ // 'done' is live: finished work is still worth referencing.+ expect(parts.liveIssues.map((i) => i.id)).toEqual(["i2", "i4"]);+ expect(parts.cancelledProjects.map((p) => p.id)).toEqual(["p1"]);+ expect(parts.cancelledIssues.map((i) => i.id)).toEqual(["i1", "i3"]);+ });++ it("exempts direct hits of either type", () => {+ const parts = partitionAggregatedSearchResults({+ issues: [issue({ id: "i-hit", number: 7, identifier: "MUL-7", status: "cancelled" })],+ projects: [project({ id: "p-other", title: "MUL-7 cleanup", status: "cancelled" })],+ query: "MUL-7",+ });++ expect(parts.liveIssues.map((i) => i.id)).toEqual(["i-hit"]);+ expect(parts.cancelledProjects.map((p) => p.id)).toEqual(["p-other"]);+ });++ it("reports no cancelled rows when nothing is demoted", () => {+ const parts = partitionAggregatedSearchResults({+ issues: [issue({ id: "i1", status: "todo" })],+ projects: [project({ id: "p1", status: "completed" })],+ query: "x",+ });+ expect(parts.hasCancelled).toBe(false);+ });+});diff --git a/packages/core/search/cancelled-rank.ts b/packages/core/search/cancelled-rank.tsnew file mode 100644index 0000000000..502eca6737--- /dev/null+++ b/packages/core/search/cancelled-rank.ts@@ -0,0 +1,172 @@+/**+ * Cross-type cancelled demotion for aggregated search results (MUL-5824).+ *+ * The search API already ranks cancelled work below live work — but only+ * *within one result set*. Every client that renders issues and projects+ * together aggregates two independent responses, so a cancelled row from one+ * response still lands above a live row from the other: the command palette+ * and the mobile search screen both render the whole Projects list before the+ * whole Issues list, so a single cancelled project outranks every live issue.+ *+ * The fix has to live at the aggregation point, and it has to be a *stable*+ * partition across BOTH types: relative order inside each side is preserved, so+ * the server's ranking still decides everything except "live before cancelled".+ * Applying it before any truncation is what makes cancelled rows give up their+ * slot rather than merely their position.+ *+ * Direct hits are exempt, matching the server: an exact identifier, an exact+ * bare number, or an exact title means the user is targeting that one record+ * and demoting it would hide exactly what they asked for.+ */++import type { SearchIssueResult, SearchProjectResult } from "../types/api";++/**+ * Mirrors the server's identifier pattern (parseQueryNumber in+ * server/internal/handler/issue.go): "MUL-123" or a bare "123".+ */+const IDENTIFIER_NUMBER_RE = /^[a-z]+-(\d+)$/i;++/** Extracts the issue number a query targets, or null when it targets none. */+export function parseSearchQueryNumber(query: string): number | null {+ const q = query.trim();+ const m = IDENTIFIER_NUMBER_RE.exec(q);+ if (m) {+ const n = Number.parseInt(m[1]!, 10);+ if (Number.isInteger(n) && n > 0) return n;+ }+ if (/^\d+$/.test(q)) {+ const n = Number.parseInt(q, 10);+ if (Number.isInteger(n) && n > 0) return n;+ }+ return null;+}++function isExactTitle(title: string | null | undefined, query: string): boolean {+ if (!title) return false;+ const q = query.trim();+ if (!q) return false;+ return title.trim().toLowerCase() === q.toLowerCase();+}++/**+ * A query targets this specific issue: exact identifier / bare number, or the+ * full title.+ *+ * Every field is optional so callers holding only part of a row can share the+ * one rule — the @mention picker, for instance, carries the identifier and the+ * title but no `number`, which is then derived from the identifier.+ *+ * Note: the server compares the title against an escapeLike'd parameter, so a+ * title containing `_` or `%` never counts as a direct hit there (a pre-existing+ * tier-1 escaping quirk, see buildSearchQuery). Client-side we compare the raw+ * strings, which can only ever *keep* such an issue in the live partition —+ * never demote something the server kept up — so the two stay compatible.+ */+export function isIssueDirectHit(+ issue: {+ title?: string | null;+ number?: number | null;+ identifier?: string | null;+ },+ query: string,+): boolean {+ const targetNumber = parseSearchQueryNumber(query);+ if (targetNumber !== null) {+ const issueNumber =+ issue.number ??+ (issue.identifier ? parseSearchQueryNumber(issue.identifier) : null);+ if (issueNumber === targetNumber) return true;+ }+ if (+ issue.identifier &&+ issue.identifier.trim().toLowerCase() === query.trim().toLowerCase()+ ) {+ return true;+ }+ return isExactTitle(issue.title, query);+}++/** A query targets this specific project: its full title. */+export function isProjectDirectHit(+ project: { title?: string | null },+ query: string,+): boolean {+ return isExactTitle(project.title, query);+}++export interface CancelledPartition<T> {+ /** Everything that is not demoted, in its original relative order. */+ live: T[];+ /** Demoted cancelled rows, in their original relative order. */+ cancelled: T[];+}++/**+ * Stable partition on an arbitrary predicate. Split out so the caller decides+ * what "cancelled and not exempt" means for its own row shape, while the+ * order-preserving guarantee lives in one place.+ */+export function partitionStable<T>(+ items: readonly T[],+ demote: (item: T) => boolean,+): CancelledPartition<T> {+ const live: T[] = [];+ const cancelled: T[] = [];+ for (const item of items) {+ if (demote(item)) cancelled.push(item);+ else live.push(item);+ }+ return { live, cancelled };+}++export interface AggregatedSearchPartition {+ /** Projects to render first, minus the demoted ones. */+ liveProjects: SearchProjectResult[];+ /** Issues to render after the live projects, minus the demoted ones. */+ liveIssues: SearchIssueResult[];+ /**+ * Cancelled projects then cancelled issues — one trailing bucket, so no+ * cancelled row of either type can precede a live row of the other.+ */+ cancelledProjects: SearchProjectResult[];+ cancelledIssues: SearchIssueResult[];+ /** True when anything was demoted; lets callers skip an empty section. */+ hasCancelled: boolean;+}++/**+ * Partitions a global-search result pair (issues + projects) for rendering.+ *+ * Render order must be: live projects → live issues → cancelled (projects then+ * issues). Callers that truncate must truncate the concatenation in that order,+ * so the cancelled tail is what gets dropped.+ */+export function partitionAggregatedSearchResults({+ issues,+ projects,+ query,+}: {+ issues: readonly SearchIssueResult[];+ projects: readonly SearchProjectResult[];+ query: string;+}): AggregatedSearchPartition {+ const issueParts = partitionStable(+ issues,+ (issue) => issue.status === "cancelled" && !isIssueDirectHit(issue, query),+ );+ const projectParts = partitionStable(+ projects,+ (project) =>+ project.status === "cancelled" && !isProjectDirectHit(project, query),+ );++ return {+ liveProjects: projectParts.live,+ liveIssues: issueParts.live,+ cancelledProjects: projectParts.cancelled,+ cancelledIssues: issueParts.cancelled,+ hasCancelled:+ projectParts.cancelled.length > 0 || issueParts.cancelled.length > 0,+ };+}diff --git a/packages/views/editor/extensions/mention-suggestion.test.tsx b/packages/views/editor/extensions/mention-suggestion.test.tsxindex 789f671a5e..94652aa506 100644--- a/packages/views/editor/extensions/mention-suggestion.test.tsx+++ b/packages/views/editor/extensions/mention-suggestion.test.tsx@@ -884,3 +884,376 @@ describe("createMentionSuggestion", () => {expect(items.some((i) => i.type === "agent" && i.label === "魏和尚")).toBe(true);});});++// MUL-5824: the search API already demotes cancelled issues, but the picker+// merges its local cache AHEAD of the server results and only then truncates to+// MAX_ITEMS — so a cached cancelled row could both outrank and crowd out live+// work the backend had deliberately ranked above it.+describe("MentionList cancelled demotion", () => {+ beforeEach(() => {+ searchIssuesMock.mockReset();+ searchProjectsMock.mockReset();+ searchIssuesMock.mockResolvedValue({ issues: [], total: 0 });+ searchProjectsMock.mockResolvedValue({ projects: [], total: 0 });+ });++ // Rendered top-to-bottom order of the issue rows. textContent runs the+ // identifier straight into the title, so match the identifier off the front.+ const issueLabels = () =>+ Array.from(document.querySelectorAll<HTMLButtonElement>("button"))+ .map((b) => (b.textContent ?? "").match(/^MUL-\d+/)?.[0])+ .filter((label): label is string => !!label);++ it("sorts cancelled issues below live ones regardless of input order", () => {+ const items: MentionItem[] = [+ { id: "i-1", label: "MUL-1", type: "issue", status: "cancelled" },+ { id: "i-2", label: "MUL-2", type: "issue", status: "in_progress" },+ { id: "i-3", label: "MUL-3", type: "issue", status: "cancelled" },+ { id: "i-4", label: "MUL-4", type: "issue", status: "backlog" },+ ];++ render(<I18nWrapper><MentionList items={items} query="" command={vi.fn()} /></I18nWrapper>);++ // Live rows keep their relative order; cancelled rows keep theirs too.+ expect(issueLabels()).toEqual(["MUL-2", "MUL-4", "MUL-1", "MUL-3"]);+ });++ it("gives up the slot, not just the position, when the list overflows", () => {+ // 20 cancelled rows ahead of one live row: with only 20 slots the live row+ // is invisible unless the demotion runs BEFORE the truncation.+ const items: MentionItem[] = [+ ...Array.from({ length: 20 }, (_, n) => ({+ id: `i-c${n}`,+ label: `MUL-${100 + n}`,+ type: "issue" as const,+ status: "cancelled" as const,+ })),+ { id: "i-live", label: "MUL-9", type: "issue", status: "todo" },+ ];++ render(<I18nWrapper><MentionList items={items} query="" command={vi.fn()} /></I18nWrapper>);++ const labels = issueLabels();+ expect(labels).toHaveLength(20);+ expect(labels[0]).toBe("MUL-9");+ // One cancelled row was dropped to make room, not the live one.+ expect(labels).not.toContain("MUL-119");+ });++ it("keeps a cancelled issue you are currently viewing in its Current section", () => {+ // "Current" is explicit context, not a relevance hit — demoting it past the+ // truncation would make the issue on screen vanish from its own picker.+ const items: MentionItem[] = [+ { id: "i-cur", label: "MUL-7", type: "issue", status: "cancelled", group: "current" },+ { id: "i-live", label: "MUL-8", type: "issue", status: "in_progress" },+ ];++ render(+ <I18nWrapper>+ <MentionList items={items} query="" command={vi.fn()} includeProjectSearch />+ </I18nWrapper>,+ );++ expect(screen.getByText("Current page")).toBeInTheDocument();+ expect(issueLabels()).toEqual(["MUL-7", "MUL-8"]);+ });++ it("does not reorder server results, which the API already ranked", async () => {+ searchIssuesMock.mockResolvedValue({+ issues: [+ { id: "i-a", identifier: "MUL-11", title: "Live match", status: "todo" },+ { id: "i-b", identifier: "MUL-12", title: "Cancelled match", status: "cancelled" },+ ],+ total: 2,+ });++ render(<I18nWrapper><MentionList items={[]} query="match" command={vi.fn()} /></I18nWrapper>);++ await waitFor(() => {+ expect(screen.getByText("MUL-11")).toBeInTheDocument();+ });+ expect(issueLabels()).toEqual(["MUL-11", "MUL-12"]);+ });++ it("demotes a cached cancelled row below a server-ranked live one", async () => {+ searchIssuesMock.mockResolvedValue({+ issues: [{ id: "i-live", identifier: "MUL-21", title: "Live match", status: "in_progress" }],+ total: 1,+ });++ // The cached row is merged first; without the demotion it would render on+ // top of the server's higher-ranked live match.+ const items: MentionItem[] = [+ { id: "i-cached", label: "MUL-20", type: "issue", status: "cancelled", description: "Cancelled match" },+ ];++ render(<I18nWrapper><MentionList items={items} query="match" command={vi.fn()} /></I18nWrapper>);++ await waitFor(() => {+ expect(screen.getByText("MUL-21")).toBeInTheDocument();+ });+ expect(issueLabels()).toEqual(["MUL-21", "MUL-20"]);+ });++ // Cross-type half of MUL-5824. Context mentions aggregate two independently+ // ranked responses — issues then projects, both tagged `search` — so per-type+ // ranking alone left a cancelled project above a live issue, and cancelled+ // search rows were exempted from the client partition entirely.+ describe("mixed issue/project results", () => {+ // Rendered order of every result row: issue rows put their identifier in+ // the leading font-medium span, project rows their title.+ const rowLabels = () =>+ Array.from(document.querySelectorAll<HTMLButtonElement>("button"))+ .map((b) => b.querySelector("span.font-medium")?.textContent ?? "")+ .filter((label) => label !== "");++ const headings = () =>+ Array.from(+ document.querySelectorAll<HTMLElement>("div.uppercase"),+ ).map((el) => el.textContent ?? "");++ it("keeps a cancelled project below a live issue in the search results", async () => {+ searchIssuesMock.mockResolvedValue({+ issues: [+ { id: "i-live", identifier: "MUL-31", title: "Live issue", status: "todo" },+ ],+ total: 1,+ });+ searchProjectsMock.mockResolvedValue({+ projects: [+ { id: "p-dead", title: "Dead project", description: null, icon: null, status: "cancelled" },+ ],+ total: 1,+ });++ render(+ <I18nWrapper>+ <MentionList items={[]} query="thing" command={vi.fn()} includeProjectSearch />+ </I18nWrapper>,+ );++ await waitFor(() => {+ expect(screen.getByText("Dead project")).toBeInTheDocument();+ });+ expect(rowLabels()).toEqual(["MUL-31", "Dead project"]);+ expect(headings()).toEqual(["Search results", "Cancelled"]);+ });++ it("demotes cancelled search results of both types below every live row", async () => {+ searchIssuesMock.mockResolvedValue({+ issues: [+ { id: "i-dead", identifier: "MUL-41", title: "Dead issue", status: "cancelled" },+ { id: "i-live", identifier: "MUL-42", title: "Live issue", status: "in_review" },+ ],+ total: 2,+ });+ searchProjectsMock.mockResolvedValue({+ projects: [+ { id: "p-dead", title: "Dead project", description: null, icon: null, status: "cancelled" },+ { id: "p-live", title: "Live project", description: null, icon: null, status: "planned" },+ ],+ total: 2,+ });++ render(+ <I18nWrapper>+ <MentionList items={[]} query="thing" command={vi.fn()} includeProjectSearch />+ </I18nWrapper>,+ );++ await waitFor(() => {+ expect(screen.getByText("Live project")).toBeInTheDocument();+ });+ // Live rows keep their server order; both cancelled types land last.+ expect(rowLabels()).toEqual([+ "MUL-42",+ "Live project",+ "MUL-41",+ "Dead project",+ ]);+ });++ it("keeps a cancelled project you are currently viewing in its Current section", async () => {+ searchIssuesMock.mockResolvedValue({ issues: [], total: 0 });+ searchProjectsMock.mockResolvedValue({ projects: [], total: 0 });++ const items: MentionItem[] = [+ {+ id: "p-cur",+ label: "Current project",+ type: "project",+ projectStatus: "cancelled",+ group: "current",+ },+ { id: "i-live", label: "MUL-51", type: "issue", status: "todo" },+ ];++ render(+ <I18nWrapper>+ <MentionList items={items} query="" command={vi.fn()} includeProjectSearch />+ </I18nWrapper>,+ );++ expect(rowLabels()).toEqual(["Current project", "MUL-51"]);+ expect(headings()).toEqual(["Current page", "Issues"]);+ });++ it("gives up slots to live rows across both types when the list overflows", async () => {+ // 20 cancelled projects ahead of one live issue: with only 20 slots the+ // live row is invisible unless the cross-type demotion runs BEFORE the+ // truncation.+ searchIssuesMock.mockResolvedValue({ issues: [], total: 0 });+ searchProjectsMock.mockResolvedValue({ projects: [], total: 0 });++ const items: MentionItem[] = [+ ...Array.from({ length: 20 }, (_, n) => ({+ id: `p-c${n}`,+ label: `Dead project ${n}`,+ type: "project" as const,+ projectStatus: "cancelled" as const,+ })),+ { id: "i-live", label: "MUL-61", type: "issue", status: "todo" },+ ];++ render(+ <I18nWrapper>+ <MentionList items={items} query="" command={vi.fn()} includeProjectSearch />+ </I18nWrapper>,+ );++ const labels = rowLabels();+ expect(labels).toHaveLength(20);+ expect(labels[0]).toBe("MUL-61");+ // One cancelled project was dropped to make room, not the live issue.+ expect(labels).not.toContain("Dead project 19");+ });+ });++ // A direct hit — exact identifier, bare number, or full title — is the record+ // the user typed out in full. The backend ranks it first and exempts it from+ // the cancelled demotion; the picker has to agree, and exemption alone is not+ // enough: slice(0, MAX_ITEMS) runs on the merged list, so a direct hit sitting+ // behind a full window of cached candidates would still be cut.+ describe("direct hits", () => {+ const rowLabels = () =>+ Array.from(document.querySelectorAll<HTMLButtonElement>("button"))+ .map((b) => b.querySelector("span.font-medium")?.textContent ?? "")+ .filter((label) => label !== "");++ const headings = () =>+ Array.from(+ document.querySelectorAll<HTMLElement>("div.uppercase"),+ ).map((el) => el.textContent ?? "");++ it("keeps a cancelled issue matched by exact identifier out of the Cancelled group", async () => {+ searchIssuesMock.mockResolvedValue({+ issues: [+ { id: "i-hit", identifier: "MUL-77", title: "Abandoned plan", status: "cancelled" },+ { id: "i-other", identifier: "MUL-78", title: "MUL-77 follow-up", status: "todo" },+ ],+ total: 2,+ });++ render(<I18nWrapper><MentionList items={[]} query="MUL-77" command={vi.fn()} /></I18nWrapper>);++ await waitFor(() => {+ expect(screen.getByText("MUL-77")).toBeInTheDocument();+ });+ // The target the user spelled out stays on top; no demotion, no section.+ expect(rowLabels()).toEqual(["MUL-77", "MUL-78"]);+ expect(headings()).not.toContain("Cancelled");+ });++ it("treats a bare number as targeting the issue with that number", async () => {+ searchIssuesMock.mockResolvedValue({+ issues: [+ { id: "i-live", identifier: "MUL-800", title: "Mentions 77 in passing", status: "todo" },+ { id: "i-hit", identifier: "MUL-77", title: "Abandoned plan", status: "cancelled" },+ ],+ total: 2,+ });++ render(<I18nWrapper><MentionList items={[]} query="77" command={vi.fn()} /></I18nWrapper>);++ await waitFor(() => {+ expect(screen.getByText("MUL-77")).toBeInTheDocument();+ });+ expect(rowLabels()).toEqual(["MUL-77", "MUL-800"]);+ });++ it("keeps a cancelled project matched by its full title with the live rows", async () => {+ searchIssuesMock.mockResolvedValue({+ issues: [{ id: "i-live", identifier: "MUL-81", title: "Search revamp notes", status: "todo" }],+ total: 1,+ });+ searchProjectsMock.mockResolvedValue({+ projects: [+ { id: "p-hit", title: "Search revamp", description: null, icon: null, status: "cancelled" },+ ],+ total: 1,+ });++ render(+ <I18nWrapper>+ <MentionList items={[]} query="Search revamp" command={vi.fn()} includeProjectSearch />+ </I18nWrapper>,+ );++ await waitFor(() => {+ expect(screen.getByText("Search revamp")).toBeInTheDocument();+ });+ expect(rowLabels()).toEqual(["Search revamp", "MUL-81"]);+ expect(headings()).not.toContain("Cancelled");+ });++ it("keeps a cancelled direct hit visible behind a full window of live candidates", async () => {+ // 20 non-cancelled cached candidates already fill every slot. Exempting+ // the direct hit from the demotion would leave it at position 21 and the+ // truncation would still delete it, so it has to be pinned to the front.+ searchIssuesMock.mockResolvedValue({+ issues: [+ { id: "i-hit", identifier: "MUL-99", title: "Abandoned plan", status: "cancelled" },+ ],+ total: 1,+ });++ const items: MentionItem[] = Array.from({ length: 20 }, (_, n) => ({+ id: `i-live${n}`,+ label: `MUL-${200 + n}`,+ type: "issue" as const,+ status: "todo" as const,+ }));++ render(<I18nWrapper><MentionList items={items} query="MUL-99" command={vi.fn()} /></I18nWrapper>);++ await waitFor(() => {+ expect(screen.getByText("MUL-99")).toBeInTheDocument();+ });++ const labels = rowLabels();+ expect(labels).toHaveLength(20);+ expect(labels[0]).toBe("MUL-99");+ // A live candidate gave up the last slot, not the record the user typed.+ expect(labels).not.toContain("MUL-219");+ });++ it("still demotes a cancelled row that merely contains the query", async () => {+ // Guard against over-exempting: a partial match is not a direct hit.+ searchIssuesMock.mockResolvedValue({+ issues: [+ { id: "i-dead", identifier: "MUL-91", title: "Abandoned plan", status: "cancelled" },+ { id: "i-live", identifier: "MUL-92", title: "Active plan", status: "todo" },+ ],+ total: 2,+ });++ render(<I18nWrapper><MentionList items={[]} query="plan" command={vi.fn()} /></I18nWrapper>);++ await waitFor(() => {+ expect(screen.getByText("MUL-92")).toBeInTheDocument();+ });+ expect(rowLabels()).toEqual(["MUL-92", "MUL-91"]);+ expect(headings()).toContain("Cancelled");+ });+ });+});diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsxindex 6e8a8e61f5..ba0c045699 100644--- a/packages/views/editor/extensions/mention-suggestion.tsx+++ b/packages/views/editor/extensions/mention-suggestion.tsx@@ -18,6 +18,10 @@ import { useAuthStore } from "@multica/core/auth";import { canAssignAgentToIssue } from "@multica/core/permissions";import { isAgentRuntimeBound } from "@multica/core/agents";import { api } from "@multica/core/api";+import {+ isIssueDirectHit,+ isProjectDirectHit,+} from "@multica/core/search/cancelled-rank";import { isImeComposing } from "@multica/core/utils";import type {Issue,@@ -100,15 +104,18 @@ interface MentionGroup {items: MentionItem[];}-function groupItems(items: MentionItem[]): MentionGroup[] {+function groupItems(items: MentionItem[], query: string): MentionGroup[] {const current: MentionItem[] = [];const recent: MentionItem[] = [];const search: MentionItem[] = [];const users: MentionItem[] = [];const issues: MentionItem[] = [];+ const cancelled: MentionItem[] = [];for (const item of items) {- if (item.group === "current") {+ if (isDemotedCancelled(item, query)) {+ cancelled.push(item);+ } else if (item.group === "current") {current.push(item);} else if (item.group === "recent") {recent.push(item);@@ -127,6 +134,8 @@ function groupItems(items: MentionItem[]): MentionGroup[] {if (search.length > 0) groups.push({ label: "Search", items: search });if (users.length > 0) groups.push({ label: "Users", items: users });if (issues.length > 0) groups.push({ label: "Issues", items: issues });+ // Always last: no cancelled row of any type may precede a live one.+ if (cancelled.length > 0) groups.push({ label: "Cancelled", items: cancelled });return groups;}@@ -159,6 +168,89 @@ function mergeMentionItems(return merged;}+/**+ * Cancelled work is abandoned work: keep it reachable, but never ahead of a+ * live match and never at the cost of a live match's slot.+ *+ * Two independent reasons the picker needs this even though the search API+ * already ranks cancelled results last:+ *+ * 1. Cached rows are merged BEFORE the server rows and the list is only then+ * truncated to MAX_ITEMS, so a locally cached cancelled issue outranks every+ * backend-ranked result and can push active work out of the window.+ * 2. Context mentions aggregate two independently ranked responses — issues+ * then projects, both tagged `search` — so a cancelled project still lands+ * above a live issue. Per-type ranking cannot fix a cross-type list.+ *+ * Exempt, matching the server and the other search surfaces:+ *+ * - Direct hits. An exact identifier, a bare number, or a full title means the+ * user is targeting that one record; demoting it hides exactly what they+ * asked for. Shared with the backend rule via isIssueDirectHit /+ * isProjectDirectHit so the three surfaces cannot drift.+ * - The curated `current` / `recent` groups. They are explicit context rather+ * than relevance hits, and "Current" has to survive the truncation even when+ * the issue being viewed is itself cancelled.+ */+function isDemotedCancelled(item: MentionItem, query: string): boolean {+ if (isPinnedAboveTruncation(item, query)) return false;+ if (item.type === "issue") return item.status === "cancelled";+ if (item.type === "project") return item.projectStatus === "cancelled";+ return false;+}++/**+ * Rows that must survive the MAX_ITEMS truncation: curated context and direct+ * hits. Exempting a direct hit from the demotion is not enough on its own —+ * `slice(0, MAX_ITEMS)` runs on the merged list, so a direct hit sitting behind+ * 20 cached candidates would still be cut. Pinning it to the front is what+ * actually keeps the record the user typed in full reachable, and it mirrors the+ * server, which already ranks direct hits first.+ *+ * Issue mention rows carry the identifier in `label` and the title in+ * `description`; project rows carry the title in `label`.+ */+function isPinnedAboveTruncation(item: MentionItem, query: string): boolean {+ if (item.group === "current" || item.group === "recent") return true;+ if (!query) return false;+ if (item.type === "issue") {+ return isIssueDirectHit(+ { identifier: item.label, title: item.description },+ query,+ );+ }+ if (item.type === "project") {+ return isProjectDirectHit({ title: item.label }, query);+ }+ return false;+}++/**+ * Stable three-tier partition applied BEFORE the MAX_ITEMS truncation, so+ * cancelled rows give up their slot rather than merely their position:+ *+ * pinned (curated context + direct hits) → live → cancelled+ *+ * Relative order within each tier is untouched, leaving the backend ranking in+ * charge of everything else. groupItems() then renders the cancelled tier as the+ * trailing section.+ */+function demoteCancelledItems(items: MentionItem[], query: string): MentionItem[] {+ const pinned: MentionItem[] = [];+ const live: MentionItem[] = [];+ const cancelled: MentionItem[] = [];++ for (const item of items) {+ if (isPinnedAboveTruncation(item, query)) pinned.push(item);+ else if (isDemotedCancelled(item, query)) cancelled.push(item);+ else live.push(item);+ }++ return pinned.length > 0 || cancelled.length > 0+ ? [...pinned, ...live, ...cancelled]+ : items;+}+export const MentionList = forwardRef<MentionListRef, MentionListProps>(function MentionList({ items, query, command, includeProjectSearch = false }, ref) {const { t } = useT("editor");@@ -252,7 +344,10 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(const displayItems = useMemo(() => {const currentServerItems = searchedQuery === normalizedQuery ? serverItems : [];- return mergeMentionItems(items, currentServerItems).slice(0, MAX_ITEMS);+ return demoteCancelledItems(+ mergeMentionItems(items, currentServerItems),+ normalizedQuery,+ ).slice(0, MAX_ITEMS);}, [items, normalizedQuery, searchedQuery, serverItems]);// The single index space for selection. groupItems() re-buckets displayItems@@ -260,7 +355,10 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(// the popup renders, top to bottom. Keyboard nav, Enter, clicks, highlight,// and scroll all index THIS, so the highlighted row always equals the// committed item — there is no second "data order" to drift against.- const groups = useMemo(() => groupItems(displayItems), [displayItems]);+ const groups = useMemo(+ () => groupItems(displayItems, normalizedQuery),+ [displayItems, normalizedQuery],+ );const orderedItems = useMemo(() => groups.flatMap((g) => g.items), [groups]);// Derive the numeric index from the pinned identity. If the selected item@@ -349,6 +447,7 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(if (label === "Search") return t(($) => $.mention.group_search);if (label === "Users") return t(($) => $.mention.group_users);if (label === "Issues") return t(($) => $.mention.group_issues);+ if (label === "Cancelled") return t(($) => $.mention.group_cancelled);return label;};diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.jsonindex 0646a7221f..db505ead51 100644--- a/packages/views/locales/en/editor.json+++ b/packages/views/locales/en/editor.json@@ -72,7 +72,8 @@"no_results": "No results","group_current": "Current page","group_recent": "Recently viewed",- "group_search": "Search results"+ "group_search": "Search results",+ "group_cancelled": "Cancelled"},"slash_command": {"no_skills_configured": "No skills configured",diff --git a/packages/views/locales/en/search.json b/packages/views/locales/en/search.jsonindex cc5500de81..1d776ff85a 100644--- a/packages/views/locales/en/search.json+++ b/packages/views/locales/en/search.json@@ -8,6 +8,7 @@"members": "Members","projects": "Projects","issues": "Issues",+ "cancelled": "Cancelled","recent": "Recent"},"pages": {diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.jsonindex b91d72713d..0e0b11940f 100644--- a/packages/views/locales/ja/editor.json+++ b/packages/views/locales/ja/editor.json@@ -72,7 +72,8 @@"no_results": "結果なし","group_current": "現在のページ","group_recent": "最近見た項目",- "group_search": "検索結果"+ "group_search": "検索結果",+ "group_cancelled": "キャンセル済み"},"code_block": {"copy_code": "コードをコピー",diff --git a/packages/views/locales/ja/search.json b/packages/views/locales/ja/search.jsonindex bb983273db..7a972e6e97 100644--- a/packages/views/locales/ja/search.json+++ b/packages/views/locales/ja/search.json@@ -8,6 +8,7 @@"members": "メンバー","projects": "プロジェクト","issues": "タスク",+ "cancelled": "キャンセル済み","recent": "最近の項目"},"pages": {diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.jsonindex 2c7ce3dcdc..6fefbe8a1e 100644--- a/packages/views/locales/ko/editor.json+++ b/packages/views/locales/ko/editor.json@@ -72,7 +72,8 @@"no_results": "결과 없음","group_current": "현재 페이지","group_recent": "최근 본 항목",- "group_search": "검색 결과"+ "group_search": "검색 결과",+ "group_cancelled": "취소됨"},"code_block": {"copy_code": "코드 복사",diff --git a/packages/views/locales/ko/search.json b/packages/views/locales/ko/search.jsonindex a68ddef9e2..22bc358abc 100644--- a/packages/views/locales/ko/search.json+++ b/packages/views/locales/ko/search.json@@ -8,6 +8,7 @@"members": "멤버","projects": "프로젝트","issues": "태스크",+ "cancelled": "취소됨","recent": "최근 항목"},"pages": {diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.jsonindex 7ba4edd179..a659f4965a 100644--- a/packages/views/locales/zh-Hans/editor.json+++ b/packages/views/locales/zh-Hans/editor.json@@ -72,7 +72,8 @@"no_results": "无结果","group_current": "当前页面","group_recent": "最近浏览",- "group_search": "搜索结果"+ "group_search": "搜索结果",+ "group_cancelled": "已取消"},"slash_command": {"no_skills_configured": "暂无配置的技能",diff --git a/packages/views/locales/zh-Hans/search.json b/packages/views/locales/zh-Hans/search.jsonindex 48a2ce11fe..4d6ce3bc83 100644--- a/packages/views/locales/zh-Hans/search.json+++ b/packages/views/locales/zh-Hans/search.json@@ -8,6 +8,7 @@"members": "成员","projects": "项目","issues": "任务",+ "cancelled": "已取消","recent": "最近"},"pages": {diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsxindex 28fd55f2ae..c8420c07ea 100644--- a/packages/views/search/search-command.test.tsx+++ b/packages/views/search/search-command.test.tsx@@ -830,4 +830,201 @@ describe("SearchCommand", () => {expect(input.selectionEnd).toBe(input.value.length);expect(selectedValue()).toBe(first);});++ // MUL-5824: the two searches are ranked independently server-side and the+ // palette renders the whole Projects group before the whole Issues group, so+ // per-type ranking let one cancelled project be the very first row. The+ // partition has to be cross-type and applied here, where results aggregate.+ describe("mixed issue/project cancelled demotion", () => {+ const fixtureIssue = (+ over: Partial<Record<string, unknown>> & { id: string },+ ) => ({+ workspace_id: "ws-test",+ number: 1,+ identifier: "MUL-1",+ title: "Untitled",+ description: null,+ status: "todo",+ priority: "none",+ assignee_type: null,+ assignee_id: null,+ creator_type: "member",+ creator_id: "user-1",+ parent_issue_id: null,+ project_id: null,+ position: 0,+ start_date: null,+ due_date: null,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ match_source: "title",+ ...over,+ });++ const fixtureProject = (+ over: Partial<Record<string, unknown>> & { id: string },+ ) => ({+ workspace_id: "ws-test",+ title: "Untitled",+ description: null,+ icon: null,+ status: "in_progress",+ priority: "none",+ lead_type: null,+ lead_id: null,+ start_date: null,+ due_date: null,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ issue_count: 0,+ match_source: "title",+ ...over,+ });++ /** Rendered result rows, top to bottom, by their cmdk value. */+ const renderedValues = () =>+ Array.from(+ document.querySelectorAll<HTMLElement>('[cmdk-item=""]'),+ )+ .map((el) => el.getAttribute("data-value") ?? "")+ .filter((v) => v.startsWith("project:") || v.startsWith("issue-"));++ /**+ * Group headings, top to bottom. Queried structurally rather than by text:+ * a cancelled project also renders "Cancelled" as its status label.+ */+ const renderedHeadings = () =>+ Array.from(+ document.querySelectorAll<HTMLElement>("[cmdk-group-heading]"),+ ).map((el) => el.textContent ?? "");++ it("keeps a cancelled project below a live issue instead of first", async () => {+ const user = userEvent.setup();+ mockSearchIssues.mockResolvedValue({+ issues: [+ fixtureIssue({+ id: "issue-live",+ number: 10,+ identifier: "MUL-10",+ title: "search live issue",+ status: "in_progress",+ }),+ ],+ total: 1,+ });+ mockSearchProjects.mockResolvedValue({+ projects: [+ fixtureProject({+ id: "proj-dead",+ title: "search dead project",+ status: "cancelled",+ }),+ ],+ total: 1,+ });++ renderSearch();+ await user.type(+ screen.getByPlaceholderText("Type a command or search..."),+ "search",+ );++ await waitFor(+ () => {+ expect(renderedValues()).toEqual(["issue-live", "project:proj-dead"]);+ },+ { timeout: 2000 },+ );+ // Still discoverable, just under its own heading at the bottom.+ expect(renderedHeadings()).toEqual(["Issues", "Cancelled"]);+ });++ it("keeps live rows of both types above every cancelled row", async () => {+ const user = userEvent.setup();+ mockSearchIssues.mockResolvedValue({+ issues: [+ fixtureIssue({+ id: "issue-dead",+ number: 11,+ identifier: "MUL-11",+ title: "search a",+ status: "cancelled",+ }),+ fixtureIssue({+ id: "issue-live",+ number: 12,+ identifier: "MUL-12",+ title: "search b",+ status: "todo",+ }),+ fixtureIssue({+ id: "issue-done",+ number: 13,+ identifier: "MUL-13",+ title: "search c",+ status: "done",+ }),+ ],+ total: 3,+ });+ mockSearchProjects.mockResolvedValue({+ projects: [+ fixtureProject({ id: "proj-dead", title: "search p1", status: "cancelled" }),+ fixtureProject({ id: "proj-live", title: "search p2", status: "planned" }),+ ],+ total: 2,+ });++ renderSearch();+ await user.type(+ screen.getByPlaceholderText("Type a command or search..."),+ "search",+ );++ await waitFor(+ () => {+ expect(renderedValues()).toEqual([+ "project:proj-live",+ // 'done' is live — only cancelled work is demoted.+ "issue-live",+ "issue-done",+ "project:proj-dead",+ "issue-dead",+ ]);+ },+ { timeout: 2000 },+ );+ });++ it("exempts a cancelled issue the query targets by identifier", async () => {+ const user = userEvent.setup();+ mockSearchIssues.mockResolvedValue({+ issues: [+ fixtureIssue({+ id: "issue-hit",+ number: 7,+ identifier: "MUL-7",+ title: "Direct hit",+ status: "cancelled",+ }),+ ],+ total: 1,+ });+ mockSearchProjects.mockResolvedValue({ projects: [], total: 0 });++ renderSearch();+ await user.type(+ screen.getByPlaceholderText("Type a command or search..."),+ "MUL-7",+ );++ await waitFor(+ () => {+ expect(renderedValues()).toEqual(["issue-hit"]);+ },+ { timeout: 2000 },+ );+ expect(renderedHeadings()).not.toContain("Cancelled");+ });+ });});diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsxindex f2b67c6f6b..17e784cce9 100644--- a/packages/views/search/search-command.tsx+++ b/packages/views/search/search-command.tsx@@ -27,6 +27,7 @@ import type {SearchProjectResult,} from "@multica/core/types";import { api } from "@multica/core/api";+import { partitionAggregatedSearchResults } from "@multica/core/search/cancelled-rank";import {openCreateIssueWithPreference,selectRecentIssues,@@ -127,6 +128,99 @@ function IssueAssigneeAvatar({);}+// Project / issue rows are rendered from three groups (Projects, Issues,+// Cancelled — see the partition note on the results list), so the row markup+// lives in one component each instead of being duplicated per group.+function ProjectResultRow({+ project,+ query,+ onSelect,+}: {+ project: SearchProjectResult;+ query: string;+ onSelect: (value: string) => void;+}) {+ return (+ <CommandPrimitive.Item+ key={`project:${project.id}`}+ value={`project:${project.id}`}+ onSelect={onSelect}+ className="flex cursor-default select-none flex-col gap-1 rounded-lg px-3 py-2.5 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"+ >+ <div className="flex items-center gap-2.5">+ <ProjectIcon project={project} size="md" />+ <span className="truncate">+ <HighlightText text={project.title} query={query} />+ </span>+ <span+ className={`ml-auto text-caption shrink-0 ${PROJECT_STATUS_CONFIG[project.status as ProjectStatus]?.color ?? "text-muted-foreground"}`}+ >+ {PROJECT_STATUS_CONFIG[project.status as ProjectStatus]?.label ?? project.status}+ </span>+ </div>+ {project.match_source === "description" && project.matched_snippet && (+ <div className="flex items-start gap-2 pl-[26px]">+ <span className="text-caption text-muted-foreground truncate">+ <HighlightText text={project.matched_snippet} query={query} />+ </span>+ </div>+ )}+ </CommandPrimitive.Item>+ );+}++function IssueResultRow({+ issue,+ query,+ onSelect,+}: {+ issue: SearchIssueResult;+ query: string;+ onSelect: (value: string) => void;+}) {+ return (+ <CommandPrimitive.Item+ key={issue.id}+ value={issue.id}+ onSelect={onSelect}+ className="flex cursor-default select-none flex-col gap-1 rounded-lg px-3 py-2.5 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"+ >+ <div className="flex items-center gap-2.5">+ <StatusIcon status={issue.status} className="size-4 shrink-0" />+ <span className="text-caption text-muted-foreground shrink-0">+ {issue.identifier}+ </span>+ <span className="min-w-0 flex-1 truncate">+ <HighlightText text={issue.title} query={query} />+ </span>+ <IssueAssigneeAvatar+ assigneeType={issue.assignee_type}+ assigneeId={issue.assignee_id}+ />+ </div>+ {issue.matched_description_snippet && (+ <div className="flex items-start gap-2 pl-[26px]">+ <FileText className="size-3 shrink-0 text-muted-foreground mt-0.5" />+ <span className="text-caption text-muted-foreground truncate">+ <HighlightText+ text={issue.matched_description_snippet}+ query={query}+ />+ </span>+ </div>+ )}+ {issue.matched_comment_snippet && (+ <div className="flex items-start gap-2 pl-[26px]">+ <MessageSquare className="size-3 shrink-0 text-muted-foreground mt-0.5" />+ <span className="text-caption text-muted-foreground truncate">+ <HighlightText text={issue.matched_comment_snippet} query={query} />+ </span>+ </div>+ )}+ </CommandPrimitive.Item>+ );+}+interface CommandItem {key: string;label: string;@@ -377,6 +471,19 @@ export function SearchCommand() {results.projects.length > 0 ||filteredMembers.length > 0;+ // Cross-type cancelled demotion (MUL-5824). The two searches are ranked+ // independently server-side, so the partition has to happen here, where they+ // are aggregated for display. See the render note on the results list.+ const partitionedResults = useMemo(+ () =>+ partitionAggregatedSearchResults({+ issues: results.issues,+ projects: results.projects,+ query,+ }),+ [results, query],+ );+// Close on single ESC — capture phase fires before base-ui Dialog's handlersuseEffect(() => {if (!open) return;@@ -625,96 +732,70 @@ export function SearchCommand() {</CommandPrimitive.Empty>)}- {!isLoading && results.projects.length > 0 && (+ {/*+ Render order is the cross-type cancelled partition (MUL-5824):+ live projects → live issues → one trailing Cancelled section+ holding cancelled projects then cancelled issues. Projects and+ issues arrive as two independently ranked responses, so per-type+ ordering is not enough — the whole Projects group used to render+ above the whole Issues group, letting one cancelled project be the+ first row of the list. Keeping cancelled rows in a single trailing+ section is the only arrangement where no cancelled row of either+ type can precede a live row of the other. Direct hits stay in+ their live section (see partitionAggregatedSearchResults).+ */}+ {!isLoading && partitionedResults.liveProjects.length > 0 && (<CommandPrimitive.Groupheading={t(($) => $.groups.projects)}className="p-2 [&_[cmdk-group-heading]]:px-3 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-caption [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground">- {results.projects.map((project) => (- <CommandPrimitive.Item+ {partitionedResults.liveProjects.map((project) => (+ <ProjectResultRowkey={`project:${project.id}`}- value={`project:${project.id}`}+ project={project}+ query={query}onSelect={handleSelect}- className="flex cursor-default select-none flex-col gap-1 rounded-lg px-3 py-2.5 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"- >- <div className="flex items-center gap-2.5">- <ProjectIcon project={project} size="md" />- <span className="truncate">- <HighlightText text={project.title} query={query} />- </span>- <span- className={`ml-auto text-caption shrink-0 ${PROJECT_STATUS_CONFIG[project.status as ProjectStatus]?.color ?? "text-muted-foreground"}`}- >- {PROJECT_STATUS_CONFIG[project.status as ProjectStatus]?.label ?? project.status}- </span>- </div>- {project.match_source === "description" &&- project.matched_snippet && (- <div className="flex items-start gap-2 pl-[26px]">- <span className="text-caption text-muted-foreground truncate">- <HighlightText- text={project.matched_snippet}- query={query}- />- </span>- </div>- )}- </CommandPrimitive.Item>+ />))}</CommandPrimitive.Group>)}- {!isLoading && results.issues.length > 0 && (+ {!isLoading && partitionedResults.liveIssues.length > 0 && (<CommandPrimitive.Groupheading={t(($) => $.groups.issues)}className="p-2 [&_[cmdk-group-heading]]:px-3 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-caption [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground">- {results.issues.map((issue) => (- <CommandPrimitive.Item+ {partitionedResults.liveIssues.map((issue) => (+ <IssueResultRowkey={issue.id}- value={issue.id}+ issue={issue}+ query={query}onSelect={handleSelect}- className="flex cursor-default select-none flex-col gap-1 rounded-lg px-3 py-2.5 text-body outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"- >- <div className="flex items-center gap-2.5">- <StatusIcon- status={issue.status}- className="size-4 shrink-0"- />- <span className="text-caption text-muted-foreground shrink-0">- {issue.identifier}- </span>- <span className="min-w-0 flex-1 truncate">- <HighlightText text={issue.title} query={query} />- </span>- <IssueAssigneeAvatar- assigneeType={issue.assignee_type}- assigneeId={issue.assignee_id}- />- </div>- {issue.matched_description_snippet && (- <div className="flex items-start gap-2 pl-[26px]">- <FileText className="size-3 shrink-0 text-muted-foreground mt-0.5" />- <span className="text-caption text-muted-foreground truncate">- <HighlightText- text={issue.matched_description_snippet}- query={query}- />- </span>- </div>- )}- {issue.matched_comment_snippet && (- <div className="flex items-start gap-2 pl-[26px]">- <MessageSquare className="size-3 shrink-0 text-muted-foreground mt-0.5" />- <span className="text-caption text-muted-foreground truncate">- <HighlightText- text={issue.matched_comment_snippet}- query={query}- />- </span>- </div>- )}- </CommandPrimitive.Item>+ />+ ))}+ </CommandPrimitive.Group>+ )}++ {!isLoading && partitionedResults.hasCancelled && (+ <CommandPrimitive.Group+ heading={t(($) => $.groups.cancelled)}+ className="p-2 [&_[cmdk-group-heading]]:px-3 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-caption [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground"+ >+ {partitionedResults.cancelledProjects.map((project) => (+ <ProjectResultRow+ key={`project:${project.id}`}+ project={project}+ query={query}+ onSelect={handleSelect}+ />+ ))}+ {partitionedResults.cancelledIssues.map((issue) => (+ <IssueResultRow+ key={issue.id}+ issue={issue}+ query={query}+ onSelect={handleSelect}+ />))}</CommandPrimitive.Group>)}diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 55640da068..d4935b4de4 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -543,6 +543,32 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,ELSE 7END`+ // Cancelled issues are abandoned work. statusRank alone cannot keep them+ // down because it is only a tie-breaker within one relevance tier: a+ // cancelled issue whose title matches the phrase exactly (tier 1) still+ // outranks an in_progress issue that merely contains it (tier 3), and a+ // workspace with many cancelled issues can fill the whole LIMIT window and+ // push live work off the page entirely. So demote cancelled ahead of+ // rankExpr — they sort after every other match and are the first rows the+ // LIMIT drops. Unlike 'done', which is finished work worth referencing,+ // cancelled work was thrown away. The exception is a direct hit: an exact+ // identifier or exact title means the user is targeting that one issue and+ // knows what they asked for.+ //+ // The title half reuses tier 1's predicate verbatim, including its quirk:+ // phraseParam is escapeLike'd, so a title containing _ or % never compares+ // equal and is not treated as a direct hit. Such an issue is still returned+ // by number; keeping the two predicates identical matters more than working+ // around an escaping bug that belongs with tier 1.+ directHitParts := []string{fmt.Sprintf("LOWER(i.title) = %s", phraseParam)}+ if hasNum {+ directHitParts = append(directHitParts, fmt.Sprintf("i.number = %s", numParam))+ }+ cancelledRank := fmt.Sprintf(+ "CASE WHEN i.status = 'cancelled' AND NOT (%s) THEN 1 ELSE 0 END",+ strings.Join(directHitParts, " OR "),+ )+// --- match_source expression ---matchSourceExpr := fmt.Sprintf(`CASEWHEN LOWER(i.title) LIKE %s THEN 'title'@@ -608,12 +634,13 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,%s AS matched_comment_contentFROM issue iWHERE i.workspace_id = %s AND %s- ORDER BY %s, %s, i.updated_at DESC+ ORDER BY %s, %s, %s, i.updated_at DESCLIMIT %s OFFSET %s`,matchSourceExpr,commentSubquery,wsParam,whereClause,+ cancelledRank,rankExpr,statusRank,limitParam,diff --git a/server/internal/handler/project.go b/server/internal/handler/project.goindex e27da79a5f..049c4a3d1d 100644--- a/server/internal/handler/project.go+++ b/server/internal/handler/project.go@@ -721,6 +721,17 @@ func buildProjectSearchQuery(phrase string, terms []string, includeClosed bool)rankExpr := "CASE " + strings.Join(rankCases, " ") + " ELSE 5 END"+ // Cancelled projects are abandoned work. Project search has no other status+ // ranking, and the command palette renders projects above issues, so+ // without this a cancelled project can be the very first row of the result+ // list. Demote ahead of rankExpr, with the same direct-hit exception as+ // issue search (see buildSearchQuery): an exact title means the user is+ // targeting that one project.+ cancelledRank := fmt.Sprintf(+ "CASE WHEN p.status = 'cancelled' AND LOWER(p.title) <> %s THEN 1 ELSE 0 END",+ phraseParam,+ )+// --- match_source expression ---matchSourceExpr := fmt.Sprintf(`CASEWHEN LOWER(p.title) LIKE %s THEN 'title'@@ -752,11 +763,12 @@ func buildProjectSearchQuery(phrase string, terms []string, includeClosed bool)%s AS match_sourceFROM project pWHERE p.workspace_id = %s AND %s- ORDER BY %s, p.updated_at DESC+ ORDER BY %s, %s, p.updated_at DESCLIMIT %s OFFSET %s`,matchSourceExpr,wsParam,whereClause,+ cancelledRank,rankExpr,limitParam,offsetParam,diff --git a/server/internal/handler/search_cancelled_rank_test.go b/server/internal/handler/search_cancelled_rank_test.gonew file mode 100644index 0000000000..59bb06baaa--- /dev/null+++ b/server/internal/handler/search_cancelled_rank_test.go@@ -0,0 +1,173 @@+package handler++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "net/url"+ "testing"+ "time"+)++// MUL-5824: cancelled work is abandoned work. It stays reachable, but it must+// never sit above a live issue on relevance alone — and it must be what the+// LIMIT window drops first, not what pushes live work off the page.+//+// These run the real handler against the real SQL. The string assertions in+// search_test.go only prove the ORDER BY was assembled in the intended shape;+// they cannot show Postgres actually sorts this way.++// seedRankIssue inserts one issue in the handler test workspace and returns its+// title. Titles carry a per-run token so each case searches only its own rows.+func seedRankIssue(t *testing.T, title, status string) string {+ t.Helper()+ ctx := context.Background()++ 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)+ }++ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, title, status, priority, creator_type, creator_id,+ position, number, created_at, updated_at+ )+ VALUES ($1, $2, $3, 'none', 'member', $4, 0, $5, now(), now())+ RETURNING id+ `, testWorkspaceID, title, status, testUserID, number).Scan(&id); err != nil {+ t.Fatalf("create issue %q (%s): %v", title, status, err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, id)+ })++ return title+}++// searchTitles runs SearchIssues with include_closed=true, which is what every+// caller that can surface cancelled work sends: the web command palette, the web+// mention picker, the issue picker, and the mobile search screen. (The mobile+// mention picker at apps/mobile/components/issue/pickers/mention-picker-body.tsx+// sends include_closed=false, so it never sees cancelled issues at all and the+// ranking below cannot apply to it.) The closed-exclusion branch is therefore+// not what keeps cancelled work down on the surfaces that do include it.+func searchTitles(t *testing.T, q string) []string {+ t.Helper()++ path := fmt.Sprintf(+ "/api/issues/search?workspace_id=%s&q=%s&limit=50&include_closed=true",+ testWorkspaceID, url.QueryEscape(q),+ )+ w := httptest.NewRecorder()+ testHandler.SearchIssues(w, newRequest("GET", path, nil))+ if w.Code != http.StatusOK {+ t.Fatalf("SearchIssues(%q): expected 200, got %d: %s", q, w.Code, w.Body.String())+ }++ var response struct {+ Issues []SearchIssueResponse `json:"issues"`+ }+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {+ t.Fatalf("decode search response: %v", err)+ }++ titles := make([]string, 0, len(response.Issues))+ for _, issue := range response.Issues {+ titles = append(titles, issue.Title)+ }+ return titles+}++func assertOrder(t *testing.T, q string, got, want []string) {+ t.Helper()+ if fmt.Sprint(got) != fmt.Sprint(want) {+ t.Fatalf("search(%q) order = %v, want %v", q, got, want)+ }+}++// A cancelled issue that matches BETTER than a live one still loses. This is+// the case statusRank could never fix: it only orders issues that already tied+// on relevance, so before this change the cancelled starts-with match (tier 2)+// beat the in_progress contains match (tier 3).+func TestSearchIssues_CancelledLosesToLiveWorkDespiteBetterRelevance(t *testing.T) {+ token := fmt.Sprintf("mulrank%d", time.Now().UnixNano())++ cancelled := seedRankIssue(t, token+" leading match", "cancelled")+ live := seedRankIssue(t, "trailing "+token+" match", "in_progress")++ assertOrder(t, token, searchTitles(t, token), []string{live, cancelled})+}++// Every cancelled issue sinks below every live one, regardless of how the+// relevance tiers fall out among them.+func TestSearchIssues_AllCancelledSortBelowAllLive(t *testing.T) {+ token := fmt.Sprintf("mulrank%d", time.Now().UnixNano())++ cancelledStrong := seedRankIssue(t, token+" alpha", "cancelled")+ cancelledWeak := seedRankIssue(t, "zeta "+token+" alpha", "cancelled")+ liveWeak := seedRankIssue(t, "omega "+token+" beta", "todo")+ liveStrong := seedRankIssue(t, token+" beta", "in_progress")++ // Within each half the existing relevance tiers still apply: starts-with+ // (tier 2) ahead of contains (tier 3).+ assertOrder(t, token, searchTitles(t, token), []string{+ liveStrong, liveWeak, cancelledStrong, cancelledWeak,+ })+}++// Searching a title verbatim is unambiguous targeting — the searcher already+// knows which issue they want, so demoting it would hide the row they asked for.+func TestSearchIssues_CancelledExactTitleStaysOnTop(t *testing.T) {+ token := fmt.Sprintf("mulrank%d", time.Now().UnixNano())++ exactTitle := token + " alpha"+ cancelled := seedRankIssue(t, exactTitle, "cancelled")+ live := seedRankIssue(t, "alpha "+token+" delta", "todo")++ // Both match every word of the query; only the cancelled one matches it+ // exactly, and that direct hit outranks the demotion.+ assertOrder(t, exactTitle, searchTitles(t, exactTitle), []string{cancelled, live})+}++// Looking an issue up by its identifier must return it, cancelled or not.+func TestSearchIssues_CancelledIdentifierLookupStaysOnTop(t *testing.T) {+ token := fmt.Sprintf("mulrank%d", time.Now().UnixNano())++ cancelled := seedRankIssue(t, token+" cancelled target", "cancelled")++ var number int+ var prefix string+ if err := testPool.QueryRow(context.Background(), `+ SELECT i.number, w.issue_prefix+ FROM issue i JOIN workspace w ON w.id = i.workspace_id+ WHERE i.workspace_id = $1 AND i.title = $2+ `, testWorkspaceID, cancelled).Scan(&number, &prefix); err != nil {+ t.Fatalf("load seeded identifier: %v", err)+ }++ // A live decoy that also matches the identifier as free text, so the+ // assertion is about ordering rather than about being the only result.+ identifier := fmt.Sprintf("%s-%d", prefix, number)+ live := seedRankIssue(t, "notes about "+identifier+" "+token, "in_progress")++ assertOrder(t, identifier, searchTitles(t, identifier), []string{cancelled, live})+}++// Scope guard: 'done' is finished work worth referencing, and this change must+// not sweep it up. A done issue keeps ranking on relevance like any live issue.+func TestSearchIssues_DoneStillRanksOnRelevance(t *testing.T) {+ token := fmt.Sprintf("mulrank%d", time.Now().UnixNano())++ done := seedRankIssue(t, token+" leading match", "done")+ live := seedRankIssue(t, "trailing "+token+" match", "in_progress")++ assertOrder(t, token, searchTitles(t, token), []string{done, live})+}diff --git a/server/internal/handler/search_test.go b/server/internal/handler/search_test.goindex f8309a7d5f..a3947d2736 100644--- a/server/internal/handler/search_test.go+++ b/server/internal/handler/search_test.go@@ -294,3 +294,110 @@ func TestBuildSearchQuery_CommentSubqueryWorkspaceScope(t *testing.T) {fromCountMulti, scopedCountMulti)}}++// --- MUL-5824: cancelled work must not outrank live work ---++// orderByClause returns everything after the final ORDER BY, so ranking-order+// assertions cannot be satisfied by an expression that merely appears in the+// SELECT list or the WHERE clause.+func orderByClause(t *testing.T, query string) string {+ t.Helper()+ i := strings.LastIndex(query, "ORDER BY ")+ if i == -1 {+ t.Fatalf("query has no ORDER BY clause:\n%s", query)+ }+ return query[i+len("ORDER BY "):]+}++// The cancelled demotion must sort BEFORE the relevance tiers, not after.+// As a tie-breaker it would be inert: statusRank only orders issues that+// already landed in the same tier, so an exactly-titled cancelled issue+// (tier 1) would still beat an in_progress title-contains match (tier 3).+func TestBuildSearchQuery_CancelledDemotedAheadOfRelevance(t *testing.T) {+ orderBy := orderByClause(t, buildSearchQueryForTest(t, "login bug", []string{"login", "bug"}, 0, false, true))++ cancelledAt := strings.Index(orderBy, "i.status = 'cancelled' AND NOT")+ if cancelledAt == -1 {+ t.Fatalf("ORDER BY has no cancelled demotion:\n%s", orderBy)+ }++ // "ELSE 9 END" terminates the relevance CASE (rankExpr).+ relevanceEndsAt := strings.Index(orderBy, "ELSE 9 END")+ if relevanceEndsAt == -1 {+ t.Fatalf("ORDER BY has no relevance rank CASE:\n%s", orderBy)+ }+ if cancelledAt > relevanceEndsAt {+ t.Errorf("cancelled demotion sorts after the relevance tiers, so a well-matching cancelled issue still outranks live work:\n%s", orderBy)+ }++ // The demotion must not replace the existing status ordering.+ if !strings.Contains(orderBy, "WHEN 'in_progress' THEN 0") {+ t.Errorf("statusRank was dropped from ORDER BY:\n%s", orderBy)+ }+ if !strings.Contains(orderBy, "i.updated_at DESC") {+ t.Errorf("recency tie-breaker was dropped from ORDER BY:\n%s", orderBy)+ }+}++// Searching an exact title or an exact identifier is unambiguous targeting —+// the searcher already knows which issue they want, so demoting it would just+// hide the row they asked for.+func TestBuildSearchQuery_CancelledDirectHitExempt(t *testing.T) {+ // $1 is the exact (non-wildcard) phrase param.+ textOnly := orderByClause(t, buildSearchQueryForTest(t, "ship it", []string{"ship", "it"}, 0, false, true))+ if !strings.Contains(textOnly, "i.status = 'cancelled' AND NOT (LOWER(i.title) = $1)") {+ t.Errorf("exact-title hit is not exempt from the cancelled demotion:\n%s", textOnly)+ }+ if strings.Contains(textOnly, "i.number = ") {+ t.Errorf("non-numeric query should not reference i.number in the demotion:\n%s", textOnly)+ }++ withNumber := orderByClause(t, buildSearchQueryForTest(t, "MUL-42", []string{"MUL-42"}, 42, true, true))+ if !strings.Contains(withNumber, "LOWER(i.title) = $1 OR i.number = ") {+ t.Errorf("identifier lookup is not exempt from the cancelled demotion, so MUL-42 sinks below every fuzzy match:\n%s", withNumber)+ }+}++// 'done' is finished work worth referencing; only 'cancelled' is thrown away.+func TestBuildSearchQuery_DoneNotDemotedAheadOfRelevance(t *testing.T) {+ orderBy := orderByClause(t, buildSearchQueryForTest(t, "login", []string{"login"}, 0, false, true))++ relevanceEndsAt := strings.Index(orderBy, "ELSE 9 END")+ if doneAt := strings.Index(orderBy, "i.status = 'done'"); doneAt != -1 && doneAt < relevanceEndsAt {+ t.Errorf("done issues were demoted ahead of relevance; only cancelled should be:\n%s", orderBy)+ }+}++// Project search has no statusRank at all, and the command palette renders+// projects above issues — an undemoted cancelled project can be the first row+// of the entire result list.+func TestBuildProjectSearchQuery_CancelledDemotedAheadOfRelevance(t *testing.T) {+ query, _ := buildProjectSearchQuery("platform", []string{"platform"}, true)+ orderBy := orderByClause(t, query)++ cancelledAt := strings.Index(orderBy, "p.status = 'cancelled'")+ if cancelledAt == -1 {+ t.Fatalf("project ORDER BY has no cancelled demotion:\n%s", orderBy)+ }+ relevanceEndsAt := strings.Index(orderBy, "ELSE 5 END")+ if relevanceEndsAt == -1 {+ t.Fatalf("project ORDER BY has no relevance rank CASE:\n%s", orderBy)+ }+ if cancelledAt > relevanceEndsAt {+ t.Errorf("cancelled projects sort after the relevance tiers:\n%s", orderBy)+ }+ if !strings.Contains(orderBy, "LOWER(p.title) <> $1") {+ t.Errorf("exact-title hit is not exempt from the cancelled demotion:\n%s", orderBy)+ }+ if !strings.Contains(orderBy, "p.updated_at DESC") {+ t.Errorf("recency tie-breaker was dropped from project ORDER BY:\n%s", orderBy)+ }+}++// buildSearchQuery mutates the terms slice in place (lowercasing); this wrapper+// keeps each test's literals independent.+func buildSearchQueryForTest(t *testing.T, phrase string, terms []string, num int, hasNum bool, includeClosed bool) string {+ t.Helper()+ query, _ := buildSearchQuery(phrase, append([]string(nil), terms...), num, hasNum, includeClosed)+ return query+}