Skip to content

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

Go

MUL-8797 feat(inbox): align the inbox filter with the issue filter (#10161)

Jiayuan Zhangcc6d2436eecd
diff --git a/packages/core/api/archived-inbox.test.ts b/packages/core/api/archived-inbox.test.ts
index 913ee2fe5d..23ae833b16 100644
--- a/packages/core/api/archived-inbox.test.ts
+++ b/packages/core/api/archived-inbox.test.ts
@@ -15,17 +15,19 @@ describe("archived inbox API", () => {
it("sends cursor, lookup and every archive filter dimension and maps the page", async () => {
const fetch = respond({ items: [], next_cursor: null, has_more: false });
const api = new ApiClient("https://api.example.test");
- // The archive has no idle dimension; a selection carried in from the
+ // The archive has no agent dimension; a selection carried in from the
// active inbox must not reach the server.
const filters: InboxFilters = {
- statuses: ["in_review"], priorities: ["high"], actors: ["system"], unreadOnly: true, idleOnly: true,
+ ...EMPTY_INBOX_FILTERS,
+ statuses: ["in_review"], priorities: ["high"], actors: ["system"], unreadOnly: true, agent: "idle",
+ labels: ["label-1"], negated: ["label"],
};
await expect(api.listArchivedInboxPage(filters, { cursor: "cursor-value", groupId: "group" })).resolves.toEqual({ items: [], nextCursor: null, hasMore: false });
const url = new URL(fetch.mock.calls[0]![0]);
expect(url.pathname).toBe("/api/inbox/archived/page");
expect(Object.fromEntries(url.searchParams)).toEqual({
statuses: "in_review", priorities: "high", actors: "system", unread_only: "true",
- limit: "50", cursor: "cursor-value", group_id: "group",
+ labels: "label-1", negated: "label", limit: "50", cursor: "cursor-value", group_id: "group",
});
});
@@ -43,8 +45,14 @@ describe("archived inbox API", () => {
it("maps complete facets and rejects incomplete or invalid counts", async () => {
respond({ statuses: { in_review: 2 }, priorities: {}, actors: { system: 0 }, unread_count: 1 });
const api = new ApiClient("https://api.example.test");
+ // An older server sends no type / project / assignee / label counts.
await expect(api.getArchivedInboxFacets(EMPTY_INBOX_FILTERS)).resolves.toEqual({
statuses: { in_review: 2 }, priorities: {}, actors: { system: 0 }, unreadCount: 1,
+ types: {}, projects: {}, assignees: {}, labels: {},
+ });
+ respond({ statuses: {}, priorities: {}, actors: {}, types: { mention: 1 }, projects: { none: 2 }, assignees: {}, labels: { l: 1 }, unread_count: 0 });
+ await expect(api.getArchivedInboxFacets(EMPTY_INBOX_FILTERS)).resolves.toMatchObject({
+ types: { mention: 1 }, projects: { none: 2 }, labels: { l: 1 },
});
for (const body of [{}, { statuses: {}, priorities: {}, actors: {}, unread_count: -1 }]) {
respond(body);
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 653a9b88d6..1964caa76e 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -3,7 +3,7 @@ import { AgentRuntimeSchema, EMPTY_RUNTIME } from "../runtimes/schema";
import type { IssueWakeup, IssueWakeupInput, IssueWakeupSummaryRow, PausedWakeup, SystemWakeup, WakeupRun, WorkspaceSystemWakeup } from "../types/issue-wakeup";
import type { WorkspaceWakeupPage, WorkspaceWakeupFilters } from "../types/issue-wakeup";
import { WorkspaceWakeupPageSchema, IssueWakeupSchema, IssueWakeupSummaryRowSchema, PausedWakeupSchema, SystemWakeupSchema, WakeupRunSchema, WorkspaceSystemWakeupSchema } from "./schemas";
-import type { ArchivedInboxFilters } from "../inbox/filter-store";
+import { archivedInboxQuery, type ArchivedInboxFilters } from "../inbox/filters";
import type { ArchivedInboxPage, ArchivedInboxFacets } from "../types/inbox";
import { parseQoderConnection, parseQoderCatalog, type QoderInput } from "../runtimes/qoder-schema";
import { configStore } from "../config";
@@ -3024,12 +3024,7 @@ export class ApiClient {
}
private archivedInboxParams(filters: ArchivedInboxFilters): URLSearchParams {
- const params = new URLSearchParams();
- if (filters.statuses.length) params.set("statuses", [...filters.statuses].sort().join(","));
- if (filters.priorities.length) params.set("priorities", [...filters.priorities].sort().join(","));
- if (filters.actors.length) params.set("actors", [...filters.actors].sort().join(","));
- if (filters.unreadOnly) params.set("unread_only", "true");
- return params;
+ return new URLSearchParams(archivedInboxQuery(filters));
}
async listArchivedInboxPage(filters: ArchivedInboxFilters, options: {
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 6791fd2393..c3b86ff82b 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -2872,6 +2872,11 @@ export const InboxItemListSchema = z.array(
body: z.string().nullish(),
issue_status: z.string().nullish(),
issue_priority: z.string().nullish(),
+ issue_project_id: z.string().nullish(),
+ issue_assignee_type: z.string().nullish(),
+ issue_assignee_id: z.string().nullish(),
+ issue_due_date: z.string().nullish(),
+ issue_label_ids: z.array(z.string()).nullish(),
read: z.boolean(),
archived: z.boolean(),
created_at: z.string(),
@@ -2887,14 +2892,24 @@ export const ArchivedInboxPageSchema = z.object({
(!page.has_more || page.items.length > 0))
.transform((page) => ({ items: page.items, nextCursor: page.next_cursor, hasMore: page.has_more }));
+const FacetCountsSchema = z.record(z.string(), z.number().int().nonnegative());
+
+// The type / project / assignee / label counts arrived later; an older server
+// omits them, so they default to empty rather than failing the whole menu.
export const ArchivedInboxFacetsSchema = z.object({
- statuses: z.record(z.string(), z.number().int().nonnegative()),
- priorities: z.record(z.string(), z.number().int().nonnegative()),
- actors: z.record(z.string(), z.number().int().nonnegative()),
+ statuses: FacetCountsSchema,
+ priorities: FacetCountsSchema,
+ actors: FacetCountsSchema,
+ types: FacetCountsSchema.optional(),
+ projects: FacetCountsSchema.optional(),
+ assignees: FacetCountsSchema.optional(),
+ labels: FacetCountsSchema.optional(),
unread_count: z.number().int().nonnegative(),
}).transform((facets) => ({
statuses: facets.statuses, priorities: facets.priorities,
- actors: facets.actors, unreadCount: facets.unread_count,
+ actors: facets.actors, types: facets.types ?? {},
+ projects: facets.projects ?? {}, assignees: facets.assignees ?? {},
+ labels: facets.labels ?? {}, unreadCount: facets.unread_count,
}));
export const EMPTY_INBOX_ITEMS: InboxItem[] = [];
diff --git a/packages/core/inbox/filter-store.test.ts b/packages/core/inbox/filter-store.test.ts
index d44b66d4e5..2dec0acc7c 100644
--- a/packages/core/inbox/filter-store.test.ts
+++ b/packages/core/inbox/filter-store.test.ts
@@ -4,12 +4,21 @@ import { beforeEach, describe, expect, it } from "vitest";
import type { InboxItem } from "../types";
import {
EMPTY_INBOX_FILTERS,
+ archivedInboxQuery,
+ effectiveInboxFilters,
filterInboxItems,
inboxActorKey,
+ inboxFacetCounts,
inboxFiltersForPrioritySupport,
inboxFilterCount,
+ inboxIssueFieldsSupport,
inboxPriorityFilterSupport,
+ inboxReceivedAfter,
+ inboxTypeGroup,
+ isEmptyInboxFilters,
+ sanitizeInboxFilters,
useInboxFilterStore,
+ type InboxFilters,
} from "./filter-store";
function item(
@@ -32,6 +41,11 @@ function item(
body: null,
issue_status: issueStatus,
issue_priority: issuePriority,
+ issue_project_id: null,
+ issue_assignee_type: null,
+ issue_assignee_id: null,
+ issue_due_date: null,
+ issue_label_ids: [],
read: false,
archived: false,
created_at: "2026-08-24T00:00:00Z",
@@ -40,6 +54,8 @@ function item(
};
}
+const ids = (items: InboxItem[]) => items.map((candidate) => candidate.id);
+
const ITEMS = [
item("todo-high", "todo", "high"),
item("todo-low", "todo", "low"),
@@ -52,27 +68,28 @@ beforeEach(() => {
});
describe("filterInboxItems", () => {
- it("keeps the original reference when no filter is active", () => {
- expect(filterInboxItems(ITEMS, EMPTY_INBOX_FILTERS)).toBe(ITEMS);
+ it("shows each issue's newest notification when no filter is active", () => {
+ const older = item("older", "todo", "high", { issue_id: "issue-1", created_at: "2026-08-23T00:00:00Z" });
+ const newer = item("newer", "todo", "high", { issue_id: "issue-1" });
+ expect(ids(filterInboxItems([older, newer, ...ITEMS], EMPTY_INBOX_FILTERS))).toEqual([
+ "newer", "todo-high", "todo-low", "done-high", "system",
+ ]);
});
it("uses OR within a dimension and AND between dimensions", () => {
expect(
- filterInboxItems(ITEMS, {
+ ids(filterInboxItems(ITEMS, {
...EMPTY_INBOX_FILTERS,
statuses: ["todo", "done"],
priorities: ["high"],
- }).map((candidate) => candidate.id),
+ })),
).toEqual(["todo-high", "done-high"]);
});
- it("excludes notifications without an issue when an issue filter is active", () => {
- expect(
- filterInboxItems(ITEMS, {
- ...EMPTY_INBOX_FILTERS,
- priorities: ["high"],
- }).map((candidate) => candidate.id),
- ).toEqual(["todo-high", "done-high"]);
+ it("excludes notifications without an issue from issue filters, negated ones too", () => {
+ const filters = { ...EMPTY_INBOX_FILTERS, priorities: ["high"] } as const;
+ expect(ids(filterInboxItems(ITEMS, filters))).toEqual(["todo-high", "done-high"]);
+ expect(ids(filterInboxItems(ITEMS, { ...filters, negated: ["priority"] }))).toEqual(["todo-low"]);
});
it("does not apply a priority condition until the projection is supported", () => {
@@ -99,7 +116,7 @@ describe("filterInboxItems", () => {
});
});
-describe("actor filtering", () => {
+describe("notification dimensions", () => {
const alice = { actor_type: "member" as const, actor_id: "alice" };
const bob = { actor_type: "agent" as const, actor_id: "bob" };
@@ -114,36 +131,81 @@ describe("actor filtering", () => {
expect(inboxActorKey(item("d", "todo", "high"))).toBeNull();
});
- it("matches the rendered row's actor, not one buried in its group", () => {
- // Alice commented, then Bob changed the status. Deduplication keeps Bob's
- // row, and that row shows Bob — so filtering by Alice must not return it,
- // or the list would answer "Alice" with Bob's avatar and Bob's wording.
- const surviving = item("newest", "todo", "high", {
- issue_id: "issue-1",
- ...bob,
+ it("matches any notification of an issue and shows the newest one that matched", () => {
+ // Alice commented, then Bob changed the status. Filtering by Alice finds
+ // the issue and renders Alice's comment, not Bob's later change.
+ const comment = item("comment", "todo", "high", {
+ issue_id: "issue-1", type: "new_comment", created_at: "2026-08-23T00:00:00Z",
+ details: { comment_id: "c-1" }, ...alice,
});
+ const change = item("change", "todo", "high", { issue_id: "issue-1", type: "status_changed", ...bob });
+
+ expect(ids(filterInboxItems([comment, change], { ...EMPTY_INBOX_FILTERS, actors: ["member:alice"] }))).toEqual(["comment"]);
+ expect(ids(filterInboxItems([comment, change], { ...EMPTY_INBOX_FILTERS, types: ["comment"] }))).toEqual(["comment"]);
+ // "Is not" also asks of any notification: Bob's change is not a comment.
+ const notComment = filterInboxItems([comment, change], { ...EMPTY_INBOX_FILTERS, types: ["comment"], negated: ["type"] });
+ expect(ids(notComment)).toEqual(["change"]);
+ // The rendered row keeps the issue's comment anchor.
+ expect(notComment[0]?.details?.comment_id).toBe("c-1");
+ });
- expect(
- filterInboxItems([surviving], {
- ...EMPTY_INBOX_FILTERS,
- actors: ["member:alice"],
- }),
- ).toEqual([]);
- expect(
- filterInboxItems([surviving], {
- ...EMPTY_INBOX_FILTERS,
- actors: ["agent:bob"],
- }).map((candidate) => candidate.id),
- ).toEqual(["newest"]);
+ it("treats a row without attribution as not matching a sender, and as matching its exclusion", () => {
+ const unattributed = [item("unattributed", "todo", "high")];
+ expect(filterInboxItems(unattributed, { ...EMPTY_INBOX_FILTERS, actors: ["member:alice"] })).toEqual([]);
+ expect(ids(filterInboxItems(unattributed, { ...EMPTY_INBOX_FILTERS, actors: ["member:alice"], negated: ["actor"] })))
+ .toEqual(["unattributed"]);
});
- it("excludes a row that carries no attribution", () => {
- expect(
- filterInboxItems([item("unattributed", "todo", "high")], {
- ...EMPTY_INBOX_FILTERS,
- actors: ["member:alice"],
- }),
- ).toEqual([]);
+ it("groups every notification kind, unknown ones as system", () => {
+ expect(inboxTypeGroup("mentioned")).toBe("mention");
+ expect(inboxTypeGroup("reaction_added")).toBe("comment");
+ expect(inboxTypeGroup("issue_subscribed")).toBe("assign");
+ expect(inboxTypeGroup("children_done")).toBe("change");
+ expect(inboxTypeGroup("agent_blocked")).toBe("run");
+ expect(inboxTypeGroup("quick_create_failed")).toBe("system");
+ expect(inboxTypeGroup("something_new")).toBe("system");
+ });
+
+ it("filters by local calendar days received", () => {
+ const now = new Date(2026, 7, 24, 15, 0);
+ expect(inboxReceivedAfter("today", now)).toEqual(new Date(2026, 7, 24));
+ expect(inboxReceivedAfter("last_7_days", now)).toEqual(new Date(2026, 7, 18));
+ const rows = [
+ item("this-morning", "todo", "high", { created_at: new Date(2026, 7, 24, 8).toISOString() }),
+ item("last-night", "todo", "high", { created_at: new Date(2026, 7, 23, 23).toISOString() }),
+ ];
+ expect(ids(filterInboxItems(rows, { ...EMPTY_INBOX_FILTERS, received: "today" }, { now }))).toEqual(["this-morning"]);
+ });
+});
+
+describe("issue dimensions", () => {
+ const rows = [
+ item("tracked", "todo", "high", {
+ issue_project_id: "project-1", issue_assignee_type: "agent", issue_assignee_id: "agent-1",
+ issue_label_ids: ["bug", "ui"], issue_due_date: "2026-08-24",
+ }),
+ item("bare", "todo", "high"),
+ item("no-issue", null, null),
+ ];
+ const run = (filters: Partial<InboxFilters>) =>
+ ids(filterInboxItems(rows, { ...EMPTY_INBOX_FILTERS, ...filters }, { now: new Date(2026, 7, 24, 12) }));
+
+ it("matches project, assignee, label and due date, with none for unset", () => {
+ expect(run({ projects: ["project-1"] })).toEqual(["tracked"]);
+ expect(run({ projects: ["none"] })).toEqual(["bare"]);
+ expect(run({ assignees: ["agent:agent-1"] })).toEqual(["tracked"]);
+ expect(run({ assignees: ["none"] })).toEqual(["bare"]);
+ expect(run({ labels: ["ui"] })).toEqual(["tracked"]);
+ expect(run({ labels: ["bug"], negated: ["label"] })).toEqual(["bare"]);
+ expect(run({ dueDates: ["today"] })).toEqual(["tracked"]);
+ expect(run({ dueDates: ["overdue", "none"] })).toEqual(["bare"]);
+ });
+
+ it("keeps or drops issues by whether an agent is on them", () => {
+ const filters = (agent: InboxFilters["agent"]) => ({ ...EMPTY_INBOX_FILTERS, agent });
+ const activeIssueIds = new Set(["issue-tracked"]);
+ expect(ids(filterInboxItems(rows, filters("running"), { activeIssueIds }))).toEqual(["tracked"]);
+ expect(ids(filterInboxItems(rows, filters("idle"), { activeIssueIds }))).toEqual(["bare"]);
});
});
@@ -155,9 +217,7 @@ describe("unread filtering", () => {
];
const filters = { ...EMPTY_INBOX_FILTERS, unreadOnly: true };
- expect(
- filterInboxItems(rows, filters).map((candidate) => candidate.id),
- ).toEqual(["unread"]);
+ expect(ids(filterInboxItems(rows, filters))).toEqual(["unread"]);
expect(inboxFilterCount(filters)).toBe(1);
});
@@ -177,9 +237,7 @@ describe("unread filtering", () => {
const read = item("read", "todo", "high", { read: true });
expect(
- filterInboxItems([opened, read], filters, { pinnedUnreadKey: "issue-opened" }).map(
- (candidate) => candidate.id,
- ),
+ ids(filterInboxItems([opened, read], filters, { pinnedUnreadKey: "issue-opened" })),
).toEqual(["opened"]);
// Pinning only crosses the unread dimension: an explicit issue filter
@@ -190,37 +248,18 @@ describe("unread filtering", () => {
});
});
-describe("idle filtering", () => {
- it("keeps only issues no agent is active on and counts as one filter", () => {
- const rows = [
- item("busy", "todo", "high", { issue_id: "issue-busy" }),
- item("idle", "todo", "high", { issue_id: "issue-idle" }),
- // Idle is a property of an issue; a row without one has none to report.
- item("no-issue", null, null),
- ];
- const filters = { ...EMPTY_INBOX_FILTERS, idleOnly: true };
-
- expect(
- filterInboxItems(rows, filters, { activeIssueIds: new Set(["issue-busy"]) }).map(
- (candidate) => candidate.id,
- ),
- ).toEqual(["idle"]);
- expect(inboxFilterCount(filters)).toBe(1);
- });
-});
-
-describe("pinned row with idle filtering", () => {
+describe("pinned row with agent filtering", () => {
it("keeps the open notification after an agent starts on its issue", () => {
- const filters = { ...EMPTY_INBOX_FILTERS, idleOnly: true };
+ const filters = { ...EMPTY_INBOX_FILTERS, agent: "idle" as const };
const opened = item("opened", "todo", "high", { issue_id: "issue-opened" });
const other = item("other", "todo", "high", { issue_id: "issue-other" });
const activeIssueIds = new Set(["issue-opened", "issue-other"]);
expect(
- filterInboxItems([opened, other], filters, {
+ ids(filterInboxItems([opened, other], filters, {
activeIssueIds,
- pinnedIdleKey: "issue-opened",
- }).map((candidate) => candidate.id),
+ pinnedAgentKey: "issue-opened",
+ })),
).toEqual(["opened"]);
// Each pin crosses only its own dimension.
@@ -233,8 +272,8 @@ describe("pinned row with idle filtering", () => {
expect(
filterInboxItems(
[{ ...opened, read: true }],
- { ...filters, idleOnly: false, unreadOnly: true },
- { pinnedIdleKey: "issue-opened" },
+ { ...filters, agent: null, unreadOnly: true },
+ { pinnedAgentKey: "issue-opened" },
),
).toEqual([]);
@@ -242,13 +281,36 @@ describe("pinned row with idle filtering", () => {
expect(
filterInboxItems([opened], { ...filters, statuses: ["done"] }, {
activeIssueIds,
- pinnedIdleKey: "issue-opened",
+ pinnedAgentKey: "issue-opened",
}),
).toEqual([]);
});
});
-describe("inboxPriorityFilterSupport", () => {
+describe("inboxFacetCounts", () => {
+ it("counts each value as if it alone were selected", () => {
+ const rows = [
+ item("mention", "todo", "high", { issue_id: "issue-1", created_at: "2026-08-23T00:00:00Z", actor_type: "member", actor_id: "alice" }),
+ item("change", "todo", "high", { issue_id: "issue-1", type: "status_changed", read: true, actor_type: "agent", actor_id: "bob" }),
+ item("other", "done", "low", { type: "new_comment", issue_project_id: "project-1", issue_label_ids: ["bug"] }),
+ item("no-issue", null, null, { type: "quick_create_failed" }),
+ ];
+ const counts = inboxFacetCounts(rows, { ...EMPTY_INBOX_FILTERS, types: ["mention"], statuses: ["todo"] });
+ // Type ignores its own selection; status still applies.
+ expect(Object.fromEntries(counts.types)).toEqual({ mention: 1, change: 1 });
+ // Status ignores its own selection; the mention filter picks the rows.
+ expect(Object.fromEntries(counts.statuses)).toEqual({ todo: 1 });
+ expect(Object.fromEntries(counts.actors)).toEqual({ "member:alice": 1 });
+ expect(counts.unread).toBe(1);
+
+ const unfiltered = inboxFacetCounts(rows, EMPTY_INBOX_FILTERS);
+ expect(Object.fromEntries(unfiltered.projects)).toEqual({ none: 1, "project-1": 1 });
+ expect(Object.fromEntries(unfiltered.labels)).toEqual({ bug: 1 });
+ expect(Object.fromEntries(unfiltered.types)).toEqual({ mention: 1, change: 1, comment: 1, system: 1 });
+ });
+});
+
+describe("backend capability", () => {
it("distinguishes an omitted legacy projection from a supported null", () => {
expect(inboxPriorityFilterSupport([])).toBe("unknown");
expect(inboxPriorityFilterSupport([item("system", null, null)])).toBe(
@@ -257,6 +319,43 @@ describe("inboxPriorityFilterSupport", () => {
expect(inboxPriorityFilterSupport([item("legacy", "todo", undefined)])).toBe(
"unsupported",
);
+ expect(inboxIssueFieldsSupport([item("system", null, null)])).toBe("supported");
+ expect(inboxIssueFieldsSupport([item("legacy", "todo", "high", { issue_label_ids: undefined })])).toBe("unsupported");
+ });
+
+ it("keeps unproven dimensions dormant, and on the archive everything an old server would ignore", () => {
+ const filters: InboxFilters = {
+ ...EMPTY_INBOX_FILTERS,
+ types: ["mention"], statuses: ["done"], projects: ["p"], agent: "idle",
+ negated: ["status"], received: "today",
+ };
+ expect(effectiveInboxFilters(filters, { priority: "supported", issueFields: "unknown" })).toEqual({
+ ...filters, projects: [],
+ });
+ expect(effectiveInboxFilters(filters, { priority: "supported", issueFields: "unsupported", archived: true })).toEqual({
+ ...EMPTY_INBOX_FILTERS,
+ });
+ expect(effectiveInboxFilters(filters, { priority: "supported", issueFields: "supported", archived: true })).toEqual({
+ ...filters, agent: null,
+ });
+ });
+});
+
+describe("archivedInboxQuery", () => {
+ it("serializes every archive dimension in a stable order", () => {
+ const now = new Date(2026, 7, 24, 15, 0);
+ expect(archivedInboxQuery({
+ ...EMPTY_INBOX_FILTERS,
+ types: ["run", "mention"], actors: ["system"], statuses: ["todo"], projects: ["none", "p"],
+ assignees: ["member:m"], labels: ["l"], dueDates: ["overdue"], received: "last_7_days",
+ negated: ["type", "label", "priority"], unreadOnly: true,
+ }, now)).toEqual({
+ types: "mention,run", actors: "system", statuses: "todo", projects: "none,p",
+ assignees: "member:m", labels: "l", due_dates: "overdue",
+ // A dimension with nothing selected has nothing to negate.
+ negated: "label,type",
+ today: "2026-08-24", received_after: new Date(2026, 7, 18).toISOString(), unread_only: "true",
+ });
});
});
@@ -270,9 +369,6 @@ describe("useInboxFilterStore", () => {
"ws-1": { statuses: ["todo"], priorities: [] },
"ws-2": { statuses: [], priorities: ["urgent"] },
});
- expect(
- useInboxFilterStore.getState().filtersByWorkspace["ws-1"]?.unreadOnly,
- ).toBe(false);
expect(
inboxFilterCount(useInboxFilterStore.getState().filtersByWorkspace["ws-1"]!),
).toBe(1);
@@ -282,12 +378,15 @@ describe("useInboxFilterStore", () => {
expect(useInboxFilterStore.getState().filtersByWorkspace["ws-2"]).toBeDefined();
});
- it("clears only the unsupported priority dimension", () => {
+ it("clears only the unsupported dimensions", () => {
const store = useInboxFilterStore.getState();
store.toggleStatusFilter("ws-1", "todo");
store.togglePriorityFilter("ws-1", "high");
+ store.toggleFilterValue("ws-1", "label", "bug");
+ store.setFilterNegated("ws-1", "label", true);
useInboxFilterStore.getState().clearPriorityFilters("ws-1");
+ useInboxFilterStore.getState().clearIssueFieldFilters("ws-1");
expect(useInboxFilterStore.getState().filtersByWorkspace["ws-1"]).toEqual({
...EMPTY_INBOX_FILTERS,
@@ -295,29 +394,51 @@ describe("useInboxFilterStore", () => {
});
});
- it("keeps an actor or unread selection alive when priority is dropped", () => {
+ it("keeps is not when it is chosen before the first value", () => {
const store = useInboxFilterStore.getState();
- store.toggleActorFilter("ws-1", "member:alice");
- store.toggleUnreadOnly("ws-1");
- store.togglePriorityFilter("ws-1", "high");
+ store.setFilterNegated("ws-1", "type", true);
+ useInboxFilterStore.getState().toggleFilterValue("ws-1", "type", "run");
- useInboxFilterStore.getState().clearPriorityFilters("ws-1");
+ const filters = useInboxFilterStore.getState().filtersByWorkspace["ws-1"]!;
+ expect(filters).toMatchObject({ types: ["run"], negated: ["type"] });
+ expect(inboxFilterCount(filters)).toBe(1);
+ });
- expect(useInboxFilterStore.getState().filtersByWorkspace["ws-1"]).toEqual({
- ...EMPTY_INBOX_FILTERS,
- actors: ["member:alice"],
- unreadOnly: true,
+ it("keeps a dimension's operator across its values and drops it when the field is cleared", () => {
+ const store = useInboxFilterStore.getState();
+ store.toggleFilterValue("ws-1", "type", "mention");
+ store.setFilterNegated("ws-1", "type", true);
+ useInboxFilterStore.getState().toggleFilterValue("ws-1", "type", "mention");
+ useInboxFilterStore.getState().toggleFilterValue("ws-1", "type", "run");
+ expect(useInboxFilterStore.getState().filtersByWorkspace["ws-1"]).toMatchObject({
+ types: ["run"], negated: ["type"],
});
+
+ useInboxFilterStore.getState().clearFilter("ws-1", "type");
+ expect(useInboxFilterStore.getState().filtersByWorkspace["ws-1"]).toBeUndefined();
});
- it("drops the workspace entry when clearing priority leaves nothing", () => {
- useInboxFilterStore.getState().togglePriorityFilter("ws-1", "high");
+ it("does not count or send an operator with no value, and forgets it on reload", () => {
+ useInboxFilterStore.getState().setFilterNegated("ws-1", "label", true);
+ const filters = useInboxFilterStore.getState().filtersByWorkspace["ws-1"]!;
- useInboxFilterStore.getState().clearPriorityFilters("ws-1");
+ expect(inboxFilterCount(filters)).toBe(0);
+ expect(archivedInboxQuery(filters).negated).toBeUndefined();
+ expect(isEmptyInboxFilters(sanitizeInboxFilters(filters))).toBe(true);
+ expect(sanitizeInboxFilters(filters).negated).toEqual([]);
+ });
- expect(
- useInboxFilterStore.getState().filtersByWorkspace["ws-1"],
- ).toBeUndefined();
+ it("selects a single received window and agent state, toggling off on reselect", () => {
+ const store = useInboxFilterStore.getState();
+ store.setReceived("ws-1", "today");
+ store.setReceived("ws-1", "last_7_days");
+ store.setAgent("ws-1", "running");
+ expect(useInboxFilterStore.getState().filtersByWorkspace["ws-1"]).toMatchObject({
+ received: "last_7_days", agent: "running",
+ });
+ useInboxFilterStore.getState().setReceived("ws-1", "last_7_days");
+ useInboxFilterStore.getState().clearFilter("ws-1", "agent");
+ expect(useInboxFilterStore.getState().filtersByWorkspace["ws-1"]).toBeUndefined();
});
it("toggles the unread dimension off again", () => {
@@ -327,8 +448,19 @@ describe("useInboxFilterStore", () => {
).toBe(true);
useInboxFilterStore.getState().toggleUnreadOnly("ws-1");
- expect(
- useInboxFilterStore.getState().filtersByWorkspace["ws-1"]?.unreadOnly,
- ).toBe(false);
+ expect(useInboxFilterStore.getState().filtersByWorkspace["ws-1"]).toBeUndefined();
+ });
+});
+
+describe("sanitizeInboxFilters", () => {
+ it("rebuilds a stored entry, dropping unknown values and carrying the old idle toggle over", () => {
+ expect(sanitizeInboxFilters({
+ statuses: ["todo", 3], types: ["mention", "bogus"], idleOnly: true,
+ negated: ["status", "label", "creator"], received: "yesterday",
+ })).toEqual({
+ ...EMPTY_INBOX_FILTERS,
+ statuses: ["todo"], types: ["mention"], agent: "idle", negated: ["status"],
+ });
+ expect(sanitizeInboxFilters(null)).toEqual(EMPTY_INBOX_FILTERS);
});
});
diff --git a/packages/core/inbox/filter-store.ts b/packages/core/inbox/filter-store.ts
index 1444a933ea..9393e924f7 100644
--- a/packages/core/inbox/filter-store.ts
+++ b/packages/core/inbox/filter-store.ts
@@ -1,164 +1,154 @@
import { create } from "zustand";
-import type { InboxItem, IssuePriority, IssueStatus } from "../types";
-
-export interface InboxFilters {
- readonly statuses: readonly IssueStatus[];
- readonly priorities: readonly IssuePriority[];
- /** Actor keys — see `inboxActorKey`. */
- readonly actors: readonly string[];
- readonly unreadOnly: boolean;
- /** Only issues no agent is running or queued on. Active inbox only. */
- readonly idleOnly: boolean;
-}
-
-/**
- * The dimensions the server-filtered archive understands. It has no idle
- * dimension, so `idleOnly` never reaches its endpoints or query keys.
- */
-export type ArchivedInboxFilters = Omit<InboxFilters, "idleOnly">;
-
-/**
- * Stable identity for "who this notification came from", used as the value of
- * the `actors` dimension.
- *
- * Members and agents key on their id. `system` has no id — the backend writes
- * an invalid UUID that serializes to null — so it keys on the type alone and
- * every system notification collapses into one bucket. Returns null when the
- * row carries no usable attribution; such a row can never match an actor
- * selection, exactly as a row without an issue can never match a status one.
- */
-export function inboxActorKey(item: InboxItem): string | null {
- const type = item.actor_type;
- if (!type) return null;
- if (type === "system") return "system";
- return item.actor_id ? `${type}:${item.actor_id}` : null;
-}
-
-/** Inverse of `inboxActorKey`, for resolving a selection back to a directory. */
-export function inboxActorKeyParts(key: string): { type: string; id: string } {
- const separator = key.indexOf(":");
- if (separator === -1) return { type: key, id: "" };
- return { type: key.slice(0, separator), id: key.slice(separator + 1) };
-}
-
-export type InboxPriorityFilterSupport =
- | "unknown"
- | "supported"
- | "unsupported";
-
-export const EMPTY_INBOX_FILTERS: InboxFilters = Object.freeze({
- statuses: Object.freeze([]),
- priorities: Object.freeze([]),
- actors: Object.freeze([]),
- unreadOnly: false,
- idleOnly: false,
-});
-
-/** True when nothing is selected in any dimension. */
-export function isEmptyInboxFilters(filters: InboxFilters): boolean {
- return inboxFilterCount(filters) === 0;
-}
+import { createJSONStorage, persist } from "zustand/middleware";
+import { defaultStorage } from "../platform/storage";
+import {
+ EMPTY_INBOX_FILTERS,
+ INBOX_DIMENSION_FIELD,
+ INBOX_ISSUE_FIELD_DIMENSIONS,
+ inboxFilterValues,
+ isEmptyInboxFilters,
+ sanitizeInboxFilters,
+ toggleInboxFilterValue,
+ withoutInboxFilter,
+ type InboxAgentFilter,
+ type InboxFilterKey,
+ type InboxFilters,
+ type InboxListDimension,
+ type InboxReceivedFilter,
+} from "./filters";
+import type { IssuePriority, IssueStatus } from "../types";
+
+export * from "./filters";
interface InboxFilterState {
filtersByWorkspace: Record<string, InboxFilters>;
+ toggleFilterValue: (wsId: string, dimension: InboxListDimension, value: string) => void;
+ setFilterNegated: (wsId: string, dimension: InboxListDimension, negated: boolean) => void;
toggleStatusFilter: (wsId: string, status: IssueStatus) => void;
togglePriorityFilter: (wsId: string, priority: IssuePriority) => void;
toggleActorFilter: (wsId: string, actor: string) => void;
toggleUnreadOnly: (wsId: string) => void;
- toggleIdleOnly: (wsId: string) => void;
+ /** Selecting the current value again clears the dimension. */
+ setReceived: (wsId: string, received: InboxReceivedFilter) => void;
+ setAgent: (wsId: string, agent: InboxAgentFilter) => void;
+ clearFilter: (wsId: string, key: InboxFilterKey) => void;
clearPriorityFilters: (wsId: string) => void;
+ clearIssueFieldFilters: (wsId: string) => void;
clearFilters: (wsId: string) => void;
}
-function toggleValue<T extends string>(values: readonly T[], value: T): T[] {
- return values.includes(value)
- ? values.filter((candidate) => candidate !== value)
- : [...values, value];
+function update(
+ state: InboxFilterState,
+ wsId: string,
+ change: (current: InboxFilters) => InboxFilters,
+): Partial<InboxFilterState> | InboxFilterState {
+ const current = state.filtersByWorkspace[wsId] ?? EMPTY_INBOX_FILTERS;
+ const next = change(current);
+ if (next === current) return state;
+ // Emptiness is asked of every dimension: an entry is dropped only when
+ // nothing in it narrows the list any more. An "is not" picked before its
+ // first value narrows nothing yet but must survive until that value comes.
+ if (isEmptyInboxFilters(next) && next.negated.length === 0) {
+ if (!state.filtersByWorkspace[wsId]) return state;
+ const { [wsId]: _removed, ...filtersByWorkspace } = state.filtersByWorkspace;
+ return { filtersByWorkspace };
+ }
+ return { filtersByWorkspace: { ...state.filtersByWorkspace, [wsId]: next } };
}
-export const useInboxFilterStore = create<InboxFilterState>()((set) => ({
- filtersByWorkspace: {},
- toggleStatusFilter: (wsId, status) =>
- set((state) => {
- const current = state.filtersByWorkspace[wsId] ?? EMPTY_INBOX_FILTERS;
- return {
- filtersByWorkspace: {
- ...state.filtersByWorkspace,
- [wsId]: {
+function toggleListValue(current: InboxFilters, dimension: InboxListDimension, value: string): InboxFilters {
+ const field = INBOX_DIMENSION_FIELD[dimension];
+ // "Is not" stays when the last value goes, as in the issue filter: the
+ // operator is the submenu's own setting, and clearing the field resets it.
+ return { ...current, [field]: toggleInboxFilterValue(current[field] as readonly string[], value) };
+}
+
+export const useInboxFilterStore = create<InboxFilterState>()(
+ persist(
+ (set) => ({
+ filtersByWorkspace: {},
+ toggleFilterValue: (wsId, dimension, value) =>
+ set((state) => update(state, wsId, (current) => toggleListValue(current, dimension, value))),
+ setFilterNegated: (wsId, dimension, negated) =>
+ set((state) =>
+ update(state, wsId, (current) => {
+ if (current.negated.includes(dimension) === negated) return current;
+ return {
+ ...current,
+ negated: negated
+ ? [...current.negated, dimension]
+ : current.negated.filter((candidate) => candidate !== dimension),
+ };
+ }),
+ ),
+ toggleStatusFilter: (wsId, status) =>
+ set((state) => update(state, wsId, (current) => toggleListValue(current, "status", status))),
+ togglePriorityFilter: (wsId, priority) =>
+ set((state) => update(state, wsId, (current) => toggleListValue(current, "priority", priority))),
+ toggleActorFilter: (wsId, actor) =>
+ set((state) => update(state, wsId, (current) => toggleListValue(current, "actor", actor))),
+ toggleUnreadOnly: (wsId) =>
+ set((state) => update(state, wsId, (current) => ({ ...current, unreadOnly: !current.unreadOnly }))),
+ setReceived: (wsId, received) =>
+ set((state) =>
+ update(state, wsId, (current) => ({
...current,
- statuses: toggleValue(current.statuses, status),
- },
- },
- };
- }),
- togglePriorityFilter: (wsId, priority) =>
- set((state) => {
- const current = state.filtersByWorkspace[wsId] ?? EMPTY_INBOX_FILTERS;
- return {
- filtersByWorkspace: {
- ...state.filtersByWorkspace,
- [wsId]: {
+ received: current.received === received ? null : received,
+ })),
+ ),
+ setAgent: (wsId, agent) =>
+ set((state) =>
+ update(state, wsId, (current) => ({
...current,
- priorities: toggleValue(current.priorities, priority),
- },
- },
- };
- }),
- toggleActorFilter: (wsId, actor) =>
- set((state) => {
- const current = state.filtersByWorkspace[wsId] ?? EMPTY_INBOX_FILTERS;
- return {
- filtersByWorkspace: {
- ...state.filtersByWorkspace,
- [wsId]: { ...current, actors: toggleValue(current.actors, actor) },
- },
- };
- }),
- toggleUnreadOnly: (wsId) =>
- set((state) => {
- const current = state.filtersByWorkspace[wsId] ?? EMPTY_INBOX_FILTERS;
- return {
- filtersByWorkspace: {
- ...state.filtersByWorkspace,
- [wsId]: { ...current, unreadOnly: !current.unreadOnly },
- },
- };
- }),
- toggleIdleOnly: (wsId) =>
- set((state) => {
- const current = state.filtersByWorkspace[wsId] ?? EMPTY_INBOX_FILTERS;
- return {
- filtersByWorkspace: {
- ...state.filtersByWorkspace,
- [wsId]: { ...current, idleOnly: !current.idleOnly },
- },
- };
- }),
- clearPriorityFilters: (wsId) =>
- set((state) => {
- const current = state.filtersByWorkspace[wsId];
- if (!current || current.priorities.length === 0) return state;
- const next = { ...current, priorities: [] };
- // Emptiness is asked of every dimension, not just statuses: dropping the
- // entry while an actor or unread selection survived in it would clear a
- // filter the user set and the backend never had a say in.
- if (isEmptyInboxFilters(next)) {
- const { [wsId]: _removed, ...filtersByWorkspace } =
- state.filtersByWorkspace;
- return { filtersByWorkspace };
- }
- return {
- filtersByWorkspace: { ...state.filtersByWorkspace, [wsId]: next },
- };
+ agent: current.agent === agent ? null : agent,
+ })),
+ ),
+ clearFilter: (wsId, key) =>
+ set((state) => update(state, wsId, (current) => withoutInboxFilter(current, key))),
+ clearPriorityFilters: (wsId) =>
+ set((state) =>
+ update(state, wsId, (current) =>
+ current.priorities.length === 0 ? current : withoutInboxFilter(current, "priority"),
+ ),
+ ),
+ clearIssueFieldFilters: (wsId) =>
+ set((state) =>
+ update(state, wsId, (current) =>
+ INBOX_ISSUE_FIELD_DIMENSIONS.reduce(
+ (next, dimension) =>
+ inboxFilterValues(next, dimension).length === 0 ? next : withoutInboxFilter(next, dimension),
+ current,
+ ),
+ ),
+ ),
+ clearFilters: (wsId) =>
+ set((state) => {
+ if (!state.filtersByWorkspace[wsId]) return state;
+ const { [wsId]: _removed, ...filtersByWorkspace } = state.filtersByWorkspace;
+ return { filtersByWorkspace };
+ }),
}),
- clearFilters: (wsId) =>
- set((state) => {
- if (!state.filtersByWorkspace[wsId]) return state;
- const { [wsId]: _removed, ...filtersByWorkspace } =
- state.filtersByWorkspace;
- return { filtersByWorkspace };
- }),
-}));
+ {
+ // One entry per workspace inside a single key, like the issue view
+ // filters: switching workspaces swaps the selection without a reload.
+ name: "multica_inbox_filters",
+ version: 1,
+ storage: createJSONStorage(() => defaultStorage),
+ partialize: (state) => ({ filtersByWorkspace: state.filtersByWorkspace }),
+ merge: (persisted, current) => {
+ const stored = (persisted as { filtersByWorkspace?: unknown } | undefined)?.filtersByWorkspace;
+ const filtersByWorkspace: Record<string, InboxFilters> = {};
+ if (stored && typeof stored === "object") {
+ for (const [wsId, raw] of Object.entries(stored)) {
+ const filters = sanitizeInboxFilters(raw);
+ if (!isEmptyInboxFilters(filters)) filtersByWorkspace[wsId] = filters;
+ }
+ }
+ return { ...current, filtersByWorkspace };
+ },
+ },
+ ),
+);
/** Workspace-isolated filter state with a stable empty fallback. */
export function useInboxFilters(wsId: string): InboxFilters {
@@ -167,137 +157,3 @@ export function useInboxFilters(wsId: string): InboxFilters {
EMPTY_INBOX_FILTERS
);
}
-
-/**
- * Capability inferred from the parsed response, not from a version string.
- *
- * The new backend always serializes `issue_priority` for every Inbox row
- * (including `null` for notifications without an issue). An older backend
- * omits it. Requiring every returned row to carry a defined value also keeps a
- * priority cache patch from making a mixed rolling-deploy response look fully
- * supported.
- */
-export function inboxPriorityFilterSupport(
- items: readonly InboxItem[],
-): InboxPriorityFilterSupport {
- if (items.length === 0) return "unknown";
- return items.every((item) => item.issue_priority !== undefined)
- ? "supported"
- : "unsupported";
-}
-
-/** Ignore a stale priority selection until the backend capability is proven. */
-export function inboxFiltersForPrioritySupport(
- filters: InboxFilters,
- support: InboxPriorityFilterSupport,
-): InboxFilters {
- if (support === "supported" || filters.priorities.length === 0) {
- return filters;
- }
- return { ...filters, priorities: [] };
-}
-
-const EMPTY_ISSUE_IDS: ReadonlySet<string> = new Set();
-
-/** Page state `filterInboxItems` needs beyond the selected filters. */
-export interface InboxFilterContext {
- /** Issues an agent is running or queued on. Read only by `idleOnly`. */
- readonly activeIssueIds?: ReadonlySet<string>;
- /**
- * Group key (`issue_id ?? id`) of the open notification, pinned against the
- * unread dimension only. Set by the page after opening marks the row read.
- */
- readonly pinnedUnreadKey?: string | null;
- /**
- * Group key of the open notification, pinned against the idle dimension
- * only. Set by the page once the row was opened while idle.
- */
- readonly pinnedIdleKey?: string | null;
-}
-
-/**
- * The archive is filtered server-side and the backend has no idle dimension,
- * so a selection kept from the active inbox stays dormant there instead of
- * narrowing whichever archived pages happen to be loaded.
- */
-export function inboxFiltersForArchive(filters: InboxFilters): InboxFilters {
- return filters.idleOnly ? { ...filters, idleOnly: false } : filters;
-}
-
-/**
- * OR within a dimension, AND between dimensions.
- *
- * Every dimension is read off the row the list actually renders. For status
- * and priority that is free — they are properties of the issue, identical on
- * every notification in the group. For the actor it is a deliberate choice:
- * deduplication keeps only a group's newest notification, and that row shows
- * ITS actor's avatar and name. Matching an actor buried in an older row of
- * the same group would answer a different question ("issues Alice has ever
- * touched") than the one the row then displays, so selecting Alice would fill
- * the list with Bob. What you filter by is what you see.
- *
- * `unreadOnly` likewise reads the rendered row's `read`. The unread badge
- * (`useInboxUnreadCount`) counts the same thing from the server's summary
- * endpoint, which applies that newest-per-issue rule in SQL — so "only unread"
- * and the number next to Inbox still cannot disagree.
- *
- * `idleOnly` asks about the issue, like status and priority, so a row without
- * one never matches. `activeIssueIds` are the issues an agent is running or
- * queued on; the caller derives them from the agent task snapshot.
- *
- * `pinnedUnreadKey` / `pinnedIdleKey` name the notification whose detail is
- * open. Opening an unread
- * notification marks it read, and replying from the detail can start an
- * agent on its issue; either would otherwise remove the row the user is
- * working in from under the detail pane. The pinned row therefore survives
- * the unread and idle dimensions only, and each pin only crosses its own
- * dimension: a row pinned for unread is still removed when the idle filter
- * is turned on over a busy issue, and vice versa. The status, priority, and
- * actor dimensions always apply, because changing one of those is an
- * explicit request to filter the notification itself out.
- */
-export function filterInboxItems(
- items: InboxItem[],
- filters: InboxFilters,
- {
- activeIssueIds = EMPTY_ISSUE_IDS,
- pinnedUnreadKey = null,
- pinnedIdleKey = null,
- }: InboxFilterContext = {},
-): InboxItem[] {
- if (isEmptyInboxFilters(filters)) return items;
-
- const statuses = new Set(filters.statuses);
- const priorities = new Set(filters.priorities);
- const actors = new Set(filters.actors);
- return items.filter((item) => {
- const actor = inboxActorKey(item);
- const matchesOtherDimensions =
- (statuses.size === 0 ||
- (item.issue_status != null && statuses.has(item.issue_status))) &&
- (priorities.size === 0 ||
- (item.issue_priority != null && priorities.has(item.issue_priority))) &&
- (actors.size === 0 || (actor != null && actors.has(actor)));
- if (!matchesOtherDimensions) return false;
- const key = item.issue_id ?? item.id;
- const matchesUnread =
- !filters.unreadOnly ||
- item.read !== true ||
- (pinnedUnreadKey != null && key === pinnedUnreadKey);
- const matchesIdle =
- !filters.idleOnly ||
- (item.issue_id != null && !activeIssueIds.has(item.issue_id)) ||
- (pinnedIdleKey != null && key === pinnedIdleKey);
- return matchesUnread && matchesIdle;
- });
-}
-
-export function inboxFilterCount(filters: InboxFilters): number {
- return (
- filters.statuses.length +
- filters.priorities.length +
- filters.actors.length +
- (filters.unreadOnly ? 1 : 0) +
- (filters.idleOnly ? 1 : 0)
- );
-}
diff --git a/packages/core/inbox/filters.ts b/packages/core/inbox/filters.ts
new file mode 100644
index 0000000000..03ca3ae323
--- /dev/null
+++ b/packages/core/inbox/filters.ts
@@ -0,0 +1,664 @@
+import { toDateOnly } from "../issues/date";
+import {
+ DUE_DATE_FILTERS,
+ FILTER_NONE_VALUE,
+ dueDateMatches,
+ type DueDateFilter,
+} from "../issues/stores/filter-tree";
+import type { InboxItem, InboxItemType, IssuePriority, IssueStatus } from "../types";
+import { groupInboxRows, sortInboxNewestFirst, withCommentAnchor } from "./group";
+
+/**
+ * Notification kinds, grouped the way a reader thinks about them. Mirrored by
+ * the CASE in `server/pkg/db/queries/inbox_archive.sql`; any kind not listed
+ * (quick create, autopilot, kinds added later) is "system".
+ */
+export type InboxTypeGroup =
+ | "mention"
+ | "comment"
+ | "assign"
+ | "review"
+ | "change"
+ | "run"
+ | "system";
+
+export const INBOX_TYPE_GROUPS: readonly InboxTypeGroup[] = [
+ "mention",
+ "comment",
+ "assign",
+ "review",
+ "change",
+ "run",
+ "system",
+];
+
+const TYPE_GROUP: Partial<Record<InboxItemType, InboxTypeGroup>> = {
+ mentioned: "mention",
+ new_comment: "comment",
+ reaction_added: "comment",
+ issue_assigned: "assign",
+ unassigned: "assign",
+ assignee_changed: "assign",
+ issue_subscribed: "assign",
+ review_requested: "review",
+ status_changed: "change",
+ priority_changed: "change",
+ start_date_changed: "change",
+ due_date_changed: "change",
+ children_done: "change",
+ task_completed: "run",
+ task_failed: "run",
+ agent_blocked: "run",
+ agent_completed: "run",
+};
+
+export function inboxTypeGroup(type: string): InboxTypeGroup {
+ return TYPE_GROUP[type as InboxItemType] ?? "system";
+}
+
+/** When the notification arrived, counted in whole local calendar days. */
+export type InboxReceivedFilter = "today" | "last_7_days" | "last_30_days";
+export const INBOX_RECEIVED_FILTERS: readonly InboxReceivedFilter[] = [
+ "today",
+ "last_7_days",
+ "last_30_days",
+];
+const RECEIVED_DAYS: Record<InboxReceivedFilter, number> = {
+ today: 1,
+ last_7_days: 7,
+ last_30_days: 30,
+};
+
+/** Whether an agent is running or queued on the issue. Active inbox only. */
+export type InboxAgentFilter = "running" | "idle";
+export const INBOX_AGENT_FILTERS: readonly InboxAgentFilter[] = ["running", "idle"];
+
+/** Multi-value dimensions; each one can be flipped to "is not". */
+export type InboxListDimension =
+ | "type"
+ | "actor"
+ | "status"
+ | "priority"
+ | "project"
+ | "assignee"
+ | "label"
+ | "dueDate";
+
+export const INBOX_LIST_DIMENSIONS: readonly InboxListDimension[] = [
+ "type",
+ "actor",
+ "status",
+ "priority",
+ "project",
+ "assignee",
+ "label",
+ "dueDate",
+];
+
+/** Dimensions that ask about the issue rather than the notification. */
+export const INBOX_ISSUE_FIELD_DIMENSIONS: readonly InboxListDimension[] = [
+ "project",
+ "assignee",
+ "label",
+ "dueDate",
+];
+
+export interface InboxFilters {
+ // About the notification.
+ readonly types: readonly InboxTypeGroup[];
+ /** Actor keys — see `inboxActorKey`. */
+ readonly actors: readonly string[];
+ readonly received: InboxReceivedFilter | null;
+ readonly unreadOnly: boolean;
+ // About its issue. Values use the issue filter's condition form: project
+ // and label ids, `member:<id>` style assignees, and "none" for unset.
+ readonly statuses: readonly IssueStatus[];
+ readonly priorities: readonly IssuePriority[];
+ readonly projects: readonly string[];
+ readonly assignees: readonly string[];
+ readonly labels: readonly string[];
+ readonly dueDates: readonly DueDateFilter[];
+ readonly agent: InboxAgentFilter | null;
+ /** Dimensions whose values are excluded rather than required. */
+ readonly negated: readonly InboxListDimension[];
+}
+
+type ListField = "types" | "actors" | "statuses" | "priorities" | "projects" | "assignees" | "labels" | "dueDates";
+
+export const INBOX_DIMENSION_FIELD: Record<InboxListDimension, ListField> = {
+ type: "types",
+ actor: "actors",
+ status: "statuses",
+ priority: "priorities",
+ project: "projects",
+ assignee: "assignees",
+ label: "labels",
+ dueDate: "dueDates",
+};
+
+/** One chip / one "active" row: a list dimension or a single-choice one. */
+export type InboxFilterKey = InboxListDimension | "received" | "unread" | "agent";
+
+export function inboxFilterValues(filters: InboxFilters, dimension: InboxListDimension): readonly string[] {
+ return filters[INBOX_DIMENSION_FIELD[dimension]];
+}
+
+/**
+ * The server-filtered archive has no agent dimension, so `agent` never
+ * reaches its endpoints or query keys.
+ */
+export type ArchivedInboxFilters = Omit<InboxFilters, "agent">;
+
+/**
+ * Stable identity for "who this notification came from", used as the value of
+ * the `actors` dimension.
+ *
+ * Members and agents key on their id. `system` has no id — the backend writes
+ * an invalid UUID that serializes to null — so it keys on the type alone and
+ * every system notification collapses into one bucket. Returns null when the
+ * row carries no usable attribution; such a row never matches an actor
+ * selection, and always matches an excluded one.
+ */
+export function inboxActorKey(item: InboxItem): string | null {
+ const type = item.actor_type;
+ if (!type) return null;
+ if (type === "system") return "system";
+ return item.actor_id ? `${type}:${item.actor_id}` : null;
+}
+
+/** Inverse of `inboxActorKey`, for resolving a selection back to a directory. */
+export function inboxActorKeyParts(key: string): { type: string; id: string } {
+ const separator = key.indexOf(":");
+ if (separator === -1) return { type: key, id: "" };
+ return { type: key.slice(0, separator), id: key.slice(separator + 1) };
+}
+
+export type InboxPriorityFilterSupport =
+ | "unknown"
+ | "supported"
+ | "unsupported";
+
+/** Same tri-state, for the project / assignee / label / due-date projection. */
+export type InboxFilterSupport = InboxPriorityFilterSupport;
+
+export const EMPTY_INBOX_FILTERS: InboxFilters = Object.freeze({
+ types: Object.freeze([]),
+ actors: Object.freeze([]),
+ received: null,
+ unreadOnly: false,
+ statuses: Object.freeze([]),
+ priorities: Object.freeze([]),
+ projects: Object.freeze([]),
+ assignees: Object.freeze([]),
+ labels: Object.freeze([]),
+ dueDates: Object.freeze([]),
+ agent: null,
+ negated: Object.freeze([]),
+});
+
+/** The dimensions that currently narrow the list, in menu order. */
+export function activeInboxFilterKeys(filters: InboxFilters): InboxFilterKey[] {
+ const keys: InboxFilterKey[] = [];
+ if (filters.unreadOnly) keys.push("unread");
+ if (filters.types.length > 0) keys.push("type");
+ if (filters.actors.length > 0) keys.push("actor");
+ if (filters.received) keys.push("received");
+ if (filters.statuses.length > 0) keys.push("status");
+ if (filters.priorities.length > 0) keys.push("priority");
+ if (filters.agent) keys.push("agent");
+ if (filters.projects.length > 0) keys.push("project");
+ if (filters.assignees.length > 0) keys.push("assignee");
+ if (filters.labels.length > 0) keys.push("label");
+ if (filters.dueDates.length > 0) keys.push("dueDate");
+ return keys;
+}
+
+/** Number of active dimensions — one per chip. */
+export function inboxFilterCount(filters: InboxFilters): number {
+ return activeInboxFilterKeys(filters).length;
+}
+
+/** True when nothing is selected in any dimension. */
+export function isEmptyInboxFilters(filters: InboxFilters): boolean {
+ return inboxFilterCount(filters) === 0;
+}
+
+export function toggleInboxFilterValue<T extends string>(values: readonly T[], value: T): T[] {
+ return values.includes(value)
+ ? values.filter((candidate) => candidate !== value)
+ : [...values, value];
+}
+
+/** Clear one dimension, dropping its "is not" with its values. */
+export function withoutInboxFilter(filters: InboxFilters, key: InboxFilterKey): InboxFilters {
+ switch (key) {
+ case "unread":
+ return { ...filters, unreadOnly: false };
+ case "received":
+ return { ...filters, received: null };
+ case "agent":
+ return { ...filters, agent: null };
+ default:
+ return {
+ ...filters,
+ [INBOX_DIMENSION_FIELD[key]]: [],
+ negated: filters.negated.filter((dimension) => dimension !== key),
+ };
+ }
+}
+
+const RECEIVED_SET = new Set<string>(INBOX_RECEIVED_FILTERS);
+const AGENT_SET = new Set<string>(INBOX_AGENT_FILTERS);
+const TYPE_SET = new Set<string>(INBOX_TYPE_GROUPS);
+const DUE_SET = new Set<string>(DUE_DATE_FILTERS);
+const DIMENSION_SET = new Set<string>(INBOX_LIST_DIMENSIONS);
+
+function stringList(value: unknown, allowed?: ReadonlySet<string>): string[] {
+ if (!Array.isArray(value)) return [];
+ return [...new Set(value.filter((v): v is string => typeof v === "string" && v !== "" && (!allowed || allowed.has(v))))];
+}
+
+/**
+ * Rebuild a stored entry field by field. Persisted state outlives the code
+ * that wrote it, so an unknown value or a missing field (an entry written
+ * before a dimension existed) falls back to "not filtering" instead of
+ * reaching the filters as `undefined`.
+ */
+export function sanitizeInboxFilters(raw: unknown): InboxFilters {
+ const value = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
+ const filters: InboxFilters = {
+ types: stringList(value.types, TYPE_SET) as InboxTypeGroup[],
+ actors: stringList(value.actors),
+ received: typeof value.received === "string" && RECEIVED_SET.has(value.received)
+ ? (value.received as InboxReceivedFilter)
+ : null,
+ unreadOnly: value.unreadOnly === true,
+ statuses: stringList(value.statuses) as IssueStatus[],
+ priorities: stringList(value.priorities) as IssuePriority[],
+ projects: stringList(value.projects),
+ assignees: stringList(value.assignees),
+ labels: stringList(value.labels),
+ dueDates: stringList(value.dueDates, DUE_SET) as DueDateFilter[],
+ agent: typeof value.agent === "string" && AGENT_SET.has(value.agent)
+ ? (value.agent as InboxAgentFilter)
+ : value.idleOnly === true
+ ? "idle"
+ : null,
+ negated: stringList(value.negated, DIMENSION_SET) as InboxListDimension[],
+ };
+ return {
+ ...filters,
+ negated: filters.negated.filter((dimension) => inboxFilterValues(filters, dimension).length > 0),
+ };
+}
+
+/**
+ * Capability inferred from the parsed response, not from a version string.
+ *
+ * The new backend always serializes `issue_priority` for every Inbox row
+ * (including `null` for notifications without an issue). An older backend
+ * omits it. Requiring every returned row to carry a defined value also keeps a
+ * priority cache patch from making a mixed rolling-deploy response look fully
+ * supported.
+ */
+export function inboxPriorityFilterSupport(
+ items: readonly InboxItem[],
+): InboxPriorityFilterSupport {
+ if (items.length === 0) return "unknown";
+ return items.every((item) => item.issue_priority !== undefined)
+ ? "supported"
+ : "unsupported";
+}
+
+/**
+ * Same rule for the project / assignee / label / due-date projection. Its
+ * label list is always an array on a server that has it, so that field is
+ * the probe.
+ */
+export function inboxIssueFieldsSupport(
+ items: readonly InboxItem[],
+): InboxFilterSupport {
+ if (items.length === 0) return "unknown";
+ return items.every((item) => Array.isArray(item.issue_label_ids))
+ ? "supported"
+ : "unsupported";
+}
+
+/** Ignore a stale priority selection until the backend capability is proven. */
+export function inboxFiltersForPrioritySupport(
+ filters: InboxFilters,
+ support: InboxPriorityFilterSupport,
+): InboxFilters {
+ if (support === "supported" || filters.priorities.length === 0) {
+ return filters;
+ }
+ return withoutInboxFilter(filters, "priority");
+}
+
+/**
+ * The selection a list can honour. Unproven dimensions stay dormant rather
+ * than hiding every row: priority and the issue fields until the server is
+ * known to send them, and on the archive also everything only that newer
+ * server understands — type, received, and "is not" — since an older one
+ * would ignore them and answer a different question. The archive has no
+ * agent dimension at all.
+ */
+export function effectiveInboxFilters(
+ filters: InboxFilters,
+ {
+ priority,
+ issueFields,
+ archived = false,
+ }: { priority: InboxFilterSupport; issueFields: InboxFilterSupport; archived?: boolean },
+): InboxFilters {
+ let next = inboxFiltersForPrioritySupport(filters, priority);
+ if (issueFields !== "supported") {
+ const dormant: InboxFilterKey[] = archived
+ ? [...INBOX_ISSUE_FIELD_DIMENSIONS, "type", "received", ...next.negated]
+ : [...INBOX_ISSUE_FIELD_DIMENSIONS];
+ next = dormant.reduce(withoutInboxFilter, next);
+ }
+ if (archived && next.agent) next = withoutInboxFilter(next, "agent");
+ return next;
+}
+
+/** @deprecated Use `effectiveInboxFilters` with `archived: true`. */
+export function inboxFiltersForArchive(filters: InboxFilters): InboxFilters {
+ return filters.agent ? withoutInboxFilter(filters, "agent") : filters;
+}
+
+/** Start of the received window, at a local midnight so it holds all day. */
+export function inboxReceivedAfter(received: InboxReceivedFilter, now: Date = new Date()): Date {
+ const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
+ start.setDate(start.getDate() - (RECEIVED_DAYS[received] - 1));
+ return start;
+}
+
+/**
+ * The archive's filter parameters, in a stable order. Also the archive's
+ * query key, so the request and its cache entry can never disagree.
+ */
+export function archivedInboxQuery(
+ filters: ArchivedInboxFilters,
+ now: Date = new Date(),
+): Record<string, string> {
+ const params: Record<string, string> = {};
+ const list = (name: string, values: readonly string[]) => {
+ if (values.length > 0) params[name] = [...values].sort().join(",");
+ };
+ list("types", filters.types);
+ list("actors", filters.actors);
+ list("statuses", filters.statuses);
+ list("priorities", filters.priorities);
+ list("projects", filters.projects);
+ list("assignees", filters.assignees);
+ list("labels", filters.labels);
+ list("due_dates", filters.dueDates);
+ list(
+ "negated",
+ filters.negated.filter((dimension) => inboxFilterValues(filters as InboxFilters, dimension).length > 0),
+ );
+ if (filters.dueDates.length > 0) params.today = toDateOnly(now);
+ if (filters.received) params.received_after = inboxReceivedAfter(filters.received, now).toISOString();
+ if (filters.unreadOnly) params.unread_only = "true";
+ return params;
+}
+
+const EMPTY_ISSUE_IDS: ReadonlySet<string> = new Set();
+
+/** Page state `filterInboxItems` needs beyond the selected filters. */
+export interface InboxFilterContext {
+ /** Issues an agent is running or queued on. Read only by `agent`. */
+ readonly activeIssueIds?: ReadonlySet<string>;
+ /**
+ * Group key (`issue_id ?? id`) of the open notification, pinned against the
+ * unread dimension only. Set by the page after opening marks the row read.
+ */
+ readonly pinnedUnreadKey?: string | null;
+ /**
+ * Group key of the open notification, pinned against the agent dimension
+ * only. Set by the page once the row was opened while it matched.
+ */
+ readonly pinnedAgentKey?: string | null;
+ /** Clock for the received and due-date dimensions. */
+ readonly now?: Date;
+}
+
+type RowTest = (item: InboxItem) => boolean;
+
+/** Values a row has in a dimension; null when it has no issue to ask. */
+function dimensionValues(item: InboxItem, dimension: InboxListDimension, today: string): readonly string[] | null {
+ switch (dimension) {
+ case "type":
+ return [inboxTypeGroup(item.type)];
+ case "actor": {
+ const key = inboxActorKey(item);
+ return key ? [key] : [];
+ }
+ default:
+ break;
+ }
+ if (item.issue_id == null) return null;
+ switch (dimension) {
+ case "status":
+ return item.issue_status == null ? null : [item.issue_status];
+ case "priority":
+ return item.issue_priority == null ? null : [item.issue_priority];
+ case "project":
+ return [item.issue_project_id ?? FILTER_NONE_VALUE];
+ case "assignee":
+ return [
+ item.issue_assignee_type && item.issue_assignee_id
+ ? `${item.issue_assignee_type}:${item.issue_assignee_id}`
+ : FILTER_NONE_VALUE,
+ ];
+ case "label":
+ return item.issue_label_ids ?? [];
+ case "dueDate":
+ return DUE_DATE_FILTERS.filter((bucket) => dueDateMatches(item.issue_due_date, bucket, today));
+ }
+}
+
+function dimensionTest(filters: InboxFilters, dimension: InboxListDimension, today: string): RowTest | null {
+ const selected = inboxFilterValues(filters, dimension);
+ if (selected.length === 0) return null;
+ const set = new Set(selected);
+ const negated = filters.negated.includes(dimension);
+ return (item) => {
+ const values = dimensionValues(item, dimension, today);
+ // A notification without an issue answers no issue question, "is not"
+ // included.
+ if (values === null) return false;
+ return values.some((value) => set.has(value)) !== negated;
+ };
+}
+
+const NOTIFICATION_DIMENSIONS: readonly InboxListDimension[] = ["type", "actor"];
+const ISSUE_DIMENSIONS: readonly InboxListDimension[] = [
+ "status",
+ "priority",
+ "project",
+ "assignee",
+ "label",
+ "dueDate",
+];
+
+interface CompiledInboxFilters {
+ /** Per-notification tests, keyed so a facet can leave its own out. */
+ notification: Map<InboxListDimension | "received", RowTest>;
+ issue: Map<InboxListDimension, RowTest>;
+}
+
+function compile(filters: InboxFilters, now: Date): CompiledInboxFilters {
+ const today = toDateOnly(now);
+ const notification = new Map<InboxListDimension | "received", RowTest>();
+ for (const dimension of NOTIFICATION_DIMENSIONS) {
+ const test = dimensionTest(filters, dimension, today);
+ if (test) notification.set(dimension, test);
+ }
+ if (filters.received) {
+ const after = inboxReceivedAfter(filters.received, now).getTime();
+ notification.set("received", (item) => new Date(item.created_at).getTime() >= after);
+ }
+ const issue = new Map<InboxListDimension, RowTest>();
+ for (const dimension of ISSUE_DIMENSIONS) {
+ const test = dimensionTest(filters, dimension, today);
+ if (test) issue.set(dimension, test);
+ }
+ return { notification, issue };
+}
+
+function passes(
+ tests: Map<string, RowTest>,
+ item: InboxItem,
+ skip?: string,
+): boolean {
+ for (const [key, test] of tests) {
+ if (key !== skip && !test(item)) return false;
+ }
+ return true;
+}
+
+function agentMatches(
+ item: InboxItem,
+ agent: InboxAgentFilter | null,
+ activeIssueIds: ReadonlySet<string>,
+): boolean {
+ if (!agent) return true;
+ if (item.issue_id == null) return false;
+ return activeIssueIds.has(item.issue_id) === (agent === "running");
+}
+
+/**
+ * One row per issue: OR within a dimension, AND between dimensions, "is not"
+ * per dimension.
+ *
+ * Takes every notification, not the deduplicated list, because the
+ * notification dimensions — type, sender, received — match ANY notification
+ * of an issue, and the issue then renders as its newest matching one. Filter
+ * by "mentions" and an issue mentioned yesterday and updated since shows the
+ * mention, not the update: what you filter by is what you see. With no
+ * notification filter that is simply the newest row, as deduplication shows.
+ *
+ * The issue dimensions — status, priority, project, assignee, label, due
+ * date, agent — ask about the issue, so a notification without one never
+ * matches them, "is not" included. `unreadOnly` reads the rendered row. The
+ * unread badge (`useInboxUnreadCount`) counts the same newest-per-issue rows
+ * from the server's summary endpoint, so "only unread" and the number next to
+ * Inbox still cannot disagree when no other filter is set.
+ *
+ * `pinnedUnreadKey` / `pinnedAgentKey` name the notification whose detail is
+ * open. Opening an unread notification marks it read, and replying from the
+ * detail can start or finish an agent on its issue; either would otherwise
+ * remove the row the user is working in from under the detail pane. The
+ * pinned row therefore survives the unread and agent dimensions only, and
+ * each pin only crosses its own dimension. Every other dimension always
+ * applies, because changing one is an explicit request to filter the
+ * notification itself out.
+ */
+export function filterInboxItems(
+ items: readonly InboxItem[],
+ filters: InboxFilters,
+ {
+ activeIssueIds = EMPTY_ISSUE_IDS,
+ pinnedUnreadKey = null,
+ pinnedAgentKey = null,
+ now = new Date(),
+ }: InboxFilterContext = {},
+): InboxItem[] {
+ const tests = compile(filters, now);
+ const out: InboxItem[] = [];
+ for (const group of groupInboxRows(items)) {
+ const row = group.find((item) => passes(tests.notification, item));
+ if (!row || !passes(tests.issue, row)) continue;
+ const key = row.issue_id ?? row.id;
+ const matchesUnread =
+ !filters.unreadOnly ||
+ row.read !== true ||
+ (pinnedUnreadKey != null && key === pinnedUnreadKey);
+ const matchesAgent =
+ agentMatches(row, filters.agent, activeIssueIds) ||
+ (pinnedAgentKey != null && key === pinnedAgentKey);
+ if (matchesUnread && matchesAgent) out.push(withCommentAnchor(row, group));
+ }
+ return sortInboxNewestFirst(out);
+}
+
+export interface InboxFacetCounts {
+ types: Map<string, number>;
+ actors: Map<string, number>;
+ statuses: Map<string, number>;
+ priorities: Map<string, number>;
+ projects: Map<string, number>;
+ assignees: Map<string, number>;
+ labels: Map<string, number>;
+ /** Rows "only unread" would leave. */
+ unread: number;
+}
+
+function bump(counts: Map<string, number>, key: string) {
+ counts.set(key, (counts.get(key) ?? 0) + 1);
+}
+
+/**
+ * Faceted counts: each value's count is the number of rows selecting that
+ * value alone would show, every other dimension applied. For type and sender
+ * that is the issue's newest notification of that value, the row selecting it
+ * renders.
+ */
+export function inboxFacetCounts(
+ items: readonly InboxItem[],
+ filters: InboxFilters,
+ {
+ activeIssueIds = EMPTY_ISSUE_IDS,
+ now = new Date(),
+ }: Pick<InboxFilterContext, "activeIssueIds" | "now"> = {},
+): InboxFacetCounts {
+ const tests = compile(filters, now);
+ const today = toDateOnly(now);
+ const counts: InboxFacetCounts = {
+ types: new Map(),
+ actors: new Map(),
+ statuses: new Map(),
+ priorities: new Map(),
+ projects: new Map(),
+ assignees: new Map(),
+ labels: new Map(),
+ unread: 0,
+ };
+ const issueFacets: [InboxListDimension, Map<string, number>][] = [
+ ["status", counts.statuses],
+ ["priority", counts.priorities],
+ ["project", counts.projects],
+ ["assignee", counts.assignees],
+ ["label", counts.labels],
+ ];
+ const readMatches = (item: InboxItem) => !filters.unreadOnly || item.read !== true;
+ for (const group of groupInboxRows(items)) {
+ const head = group[0];
+ if (!head || !agentMatches(head, filters.agent, activeIssueIds)) continue;
+ const issueOk = passes(tests.issue, head);
+
+ const row = group.find((item) => passes(tests.notification, item));
+ if (row) {
+ for (const [dimension, target] of issueFacets) {
+ if (!readMatches(row) || !passes(tests.issue, row, dimension)) continue;
+ for (const value of dimensionValues(row, dimension, today) ?? []) bump(target, value);
+ }
+ if (issueOk && row.read !== true) counts.unread++;
+ }
+ if (!issueOk) continue;
+ for (const [dimension, target] of [["type", counts.types], ["actor", counts.actors]] as const) {
+ const seen = new Set<string>();
+ for (const item of group) {
+ if (!passes(tests.notification, item, dimension)) continue;
+ for (const value of dimensionValues(item, dimension, today) ?? []) {
+ if (seen.has(value)) continue;
+ seen.add(value);
+ if (readMatches(item)) bump(target, value);
+ }
+ }
+ }
+ }
+ return counts;
+}
diff --git a/packages/core/inbox/group.ts b/packages/core/inbox/group.ts
new file mode 100644
index 0000000000..d41efa0b0c
--- /dev/null
+++ b/packages/core/inbox/group.ts
@@ -0,0 +1,41 @@
+import type { InboxItem } from "../types";
+
+function byNewest(a: InboxItem, b: InboxItem): number {
+ return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
+}
+
+/** Notifications grouped by issue (`issue_id ?? id`), each group newest first. */
+export function groupInboxRows(items: readonly InboxItem[]): InboxItem[][] {
+ const groups = new Map<string, InboxItem[]>();
+ for (const item of items) {
+ const key = item.issue_id ?? item.id;
+ const group = groups.get(key);
+ if (group) group.push(item);
+ else groups.set(key, [item]);
+ }
+ const out = [...groups.values()];
+ for (const group of out) group.sort(byNewest);
+ return out;
+}
+
+/**
+ * The row a group renders as. It keeps the group's newest comment anchor when
+ * it has none of its own, so opening it still scrolls to the comment.
+ */
+export function withCommentAnchor(row: InboxItem, group: readonly InboxItem[]): InboxItem {
+ if (row.details?.comment_id) return row;
+ const commentId = group.find((item) => item.details?.comment_id)?.details?.comment_id;
+ if (!commentId) return row;
+ return { ...row, details: { ...(row.details ?? {}), comment_id: commentId } };
+}
+
+/** One row per issue: its newest notification. Newest group first. */
+export function groupInboxItemsByIssue(items: readonly InboxItem[]): InboxItem[] {
+ return groupInboxRows(items)
+ .flatMap((group) => (group[0] ? [withCommentAnchor(group[0], group)] : []))
+ .sort(byNewest);
+}
+
+export function sortInboxNewestFirst(items: InboxItem[]): InboxItem[] {
+ return items.sort(byNewest);
+}
diff --git a/packages/core/inbox/queries.test.ts b/packages/core/inbox/queries.test.ts
index ed91dcbf5b..146a6b5d89 100644
--- a/packages/core/inbox/queries.test.ts
+++ b/packages/core/inbox/queries.test.ts
@@ -141,8 +141,8 @@ describe("deduplicateArchivedInboxItems", () => {
});
describe("archived inbox options", () => {
- it("keeps an idle selection out of archive query keys", () => {
- const idle: InboxFilters = { ...EMPTY_INBOX_FILTERS, idleOnly: true };
+ it("keeps an agent selection out of archive query keys", () => {
+ const idle: InboxFilters = { ...EMPTY_INBOX_FILTERS, agent: "idle" };
expect(archivedInboxPagesOptions("ws", idle).queryKey).toEqual(
archivedInboxPagesOptions("ws", EMPTY_INBOX_FILTERS).queryKey,
diff --git a/packages/core/inbox/queries.ts b/packages/core/inbox/queries.ts
index 40623a41ad..d78138c06b 100644
--- a/packages/core/inbox/queries.ts
+++ b/packages/core/inbox/queries.ts
@@ -1,6 +1,7 @@
import type { InfiniteData, QueryClient } from "@tanstack/react-query";
import type { ArchivedInboxPage } from "../types/inbox";
-import { EMPTY_INBOX_FILTERS, type ArchivedInboxFilters } from "./filter-store";
+import { EMPTY_INBOX_FILTERS, archivedInboxQuery, type ArchivedInboxFilters } from "./filters";
+import { groupInboxItemsByIssue } from "./group";
import { infiniteQueryOptions, keepPreviousData, queryOptions, useQuery } from "@tanstack/react-query";
import { api } from "../api";
import type { InboxItem, InboxWorkspaceUnread } from "../types";
@@ -37,11 +38,11 @@ export function archivedInboxListOptions(wsId: string) {
});
}
-// Lists the archived dimensions explicitly, so an `idleOnly` carried in from
-// the active inbox never changes the key or refetches the archive.
-function normalizedInboxFilters(filters: ArchivedInboxFilters): ArchivedInboxFilters {
- return { statuses: [...filters.statuses].sort(), priorities: [...filters.priorities].sort(),
- actors: [...filters.actors].sort(), unreadOnly: filters.unreadOnly };
+// Keyed by the request parameters themselves: an `agent` selection carried in
+// from the active inbox never changes the key, and the relative windows
+// (received, due date) re-key when the day turns.
+function normalizedInboxFilters(filters: ArchivedInboxFilters): Record<string, string> {
+ return archivedInboxQuery(filters);
}
// A filter change re-keys the archive. Keep the previous result while the new
@@ -65,11 +66,19 @@ export function archivedInboxPagesOptions(wsId: string, filters: ArchivedInboxFi
}
export function archivedInboxLookupOptions(wsId: string, groupId: string, filters: ArchivedInboxFilters = EMPTY_INBOX_FILTERS) {
+ const prefix = inboxKeys.lookup(wsId);
return queryOptions({
- queryKey: [...inboxKeys.lookup(wsId), groupId, normalizedInboxFilters(filters)],
+ queryKey: [...prefix, groupId, normalizedInboxFilters(filters)],
queryFn: ({ signal }) => api.listArchivedInboxPage(filters, { groupId, signal }),
enabled: !!groupId,
retry: false,
+ // A filter change re-asks for the same group. Its last answer stays up
+ // meanwhile, so the open row is judged by the new filters at once instead
+ // of the selection hanging on the request.
+ placeholderData: (previousData, previousQuery) =>
+ isSameWorkspace(previousQuery?.queryKey, wsId) && previousQuery?.queryKey[prefix.length] === groupId
+ ? previousData
+ : undefined,
});
}
@@ -219,40 +228,3 @@ export function deduplicateInboxItems(items: InboxItem[]): InboxItem[] {
export function deduplicateArchivedInboxItems(items: InboxItem[]): InboxItem[] {
return groupInboxItemsByIssue(items.filter((i) => i.archived));
}
-
-function groupInboxItemsByIssue(items: InboxItem[]): InboxItem[] {
- const groups = new Map<string, InboxItem[]>();
- for (const item of items) {
- const key = item.issue_id ?? item.id;
- const group = groups.get(key) ?? [];
- group.push(item);
- groups.set(key, group);
- }
- const merged: InboxItem[] = [];
- for (const group of groups.values()) {
- group.sort(
- (a, b) =>
- new Date(b.created_at).getTime() - new Date(a.created_at).getTime(),
- );
- const newest = group[0];
- if (!newest) continue;
-
- const commentId =
- newest.details?.comment_id ??
- group.find((item) => item.details?.comment_id)?.details?.comment_id;
-
- if (commentId && newest.details?.comment_id !== commentId) {
- merged.push({
- ...newest,
- details: { ...(newest.details ?? {}), comment_id: commentId },
- });
- continue;
- }
-
- merged.push(newest);
- }
- return merged.sort(
- (a, b) =>
- new Date(b.created_at).getTime() - new Date(a.created_at).getTime(),
- );
-}
diff --git a/packages/core/inbox/ws-updaters.ts b/packages/core/inbox/ws-updaters.ts
index 6c6cccd7da..de8de52d07 100644
--- a/packages/core/inbox/ws-updaters.ts
+++ b/packages/core/inbox/ws-updaters.ts
@@ -1,6 +1,6 @@
import type { QueryClient, QueryKey } from "@tanstack/react-query";
import { inboxKeys, mapArchivedInboxCache, type ArchivedInboxCache } from "./queries";
-import type { InboxItem, IssuePriority, IssueStatus } from "../types";
+import type { InboxItem, IssueAssigneeType, IssuePriority, IssueStatus } from "../types";
// Re-read a query because the server changed — in a way that is never answered
// by a request that was already on the wire before the change.
@@ -66,28 +66,55 @@ function patchInboxLists(
}
}
+/** Issue fields inbox rows mirror for display and filtering. */
+export interface InboxIssueProjectionPatch {
+ status?: IssueStatus;
+ priority?: IssuePriority;
+ project_id?: string | null;
+ assignee_type?: IssueAssigneeType | null;
+ assignee_id?: string | null;
+ due_date?: string | null;
+ label_ids?: string[];
+}
+
export function patchInboxIssueProjection(
qc: QueryClient,
wsId: string,
issueId: string,
- patch: { status?: IssueStatus; priority?: IssuePriority },
+ patch: InboxIssueProjectionPatch,
) {
const project = (old: InboxItem[]) => {
let changed = false;
const next = old.map((item) => {
if (item.issue_id !== issueId) return item;
changed = true;
+ // Do not manufacture a projection on data returned by an older
+ // backend. Capability detection relies on `undefined` continuing to
+ // mean "this endpoint version does not provide the field".
+ const hasIssueFields = item.issue_label_ids !== undefined;
return {
...item,
...(patch.status !== undefined
? { issue_status: patch.status }
: {}),
- // Do not manufacture the projection on data returned by an older
- // backend. Capability detection relies on `undefined` continuing to
- // mean "this endpoint version does not provide issue_priority".
...(patch.priority !== undefined && item.issue_priority !== undefined
? { issue_priority: patch.priority }
: {}),
+ ...(hasIssueFields && patch.project_id !== undefined
+ ? { issue_project_id: patch.project_id }
+ : {}),
+ ...(hasIssueFields && patch.assignee_type !== undefined
+ ? { issue_assignee_type: patch.assignee_type }
+ : {}),
+ ...(hasIssueFields && patch.assignee_id !== undefined
+ ? { issue_assignee_id: patch.assignee_id }
+ : {}),
+ ...(hasIssueFields && patch.due_date !== undefined
+ ? { issue_due_date: patch.due_date }
+ : {}),
+ ...(hasIssueFields && patch.label_ids !== undefined
+ ? { issue_label_ids: patch.label_ids }
+ : {}),
};
});
return changed ? next : old;
@@ -142,6 +169,17 @@ export async function onInboxIssueDeleted(
]);
}
+// An issue field the archive filters and counts on changed. Loaded rows are
+// patched in place, but which groups match and the facet counts are decided
+// by the server: an issue that newly matches a filter would never appear, and
+// with `staleTime: Infinity` an empty result would stay empty. Marked
+// synchronously so an archive that is not mounted re-reads on its next visit.
+export async function refreshArchivedInboxMatches(qc: QueryClient, wsId: string) {
+ const keys = [inboxKeys.pages(wsId), inboxKeys.lookup(wsId), inboxKeys.facets(wsId)];
+ for (const queryKey of keys) void qc.invalidateQueries({ queryKey, refetchType: "none" });
+ await Promise.all(keys.map((queryKey) => refreshInboxQuery(qc, queryKey)));
+}
+
// Whether a request for either inbox list is out (paused ones included).
export function isInboxListRequestInFlight(
qc: QueryClient,
diff --git a/packages/core/issues/cache-coordinator.ts b/packages/core/issues/cache-coordinator.ts
index 5a94f9dbbe..8d081beeff 100644
--- a/packages/core/issues/cache-coordinator.ts
+++ b/packages/core/issues/cache-coordinator.ts
@@ -532,19 +532,21 @@ export function applyIssueChange(
if (!prevIssue) prevIssue = prevDetail;
}
- // Inbox rows carry issue status/priority snapshots used by presentation and
- // filtering. The issue is the real state, so both projections follow every
+ // Inbox rows carry snapshots of the issue fields used by presentation and
+ // filtering. The issue is the real state, so the projections follow every
// write immediately.
let prevInboxList: InboxItem[] | undefined;
let prevArchivedInboxCaches: [QueryKey, ArchivedInboxCache | undefined][] | undefined;
- if (patch.status !== undefined || patch.priority !== undefined) {
+ const inboxFields = ["project_id", "assignee_type", "assignee_id", "due_date"] as const;
+ if (patch.status !== undefined || patch.priority !== undefined || inboxFields.some((field) => patch[field] !== undefined)) {
prevInboxList = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));
prevArchivedInboxCaches = qc.getQueriesData<ArchivedInboxCache>({ queryKey: inboxKeys.archived(wsId) });
// Membership and facets are server-owned; callers refresh after commit.
- // Full issue events also carry unchanged status/priority on title edits.
+ // Full issue events also carry unchanged fields on title edits.
const archiveProjectionChanged =
(patch.status !== undefined && (changed.status || !prevIssue || prevIssue.status !== patch.status)) ||
- (patch.priority !== undefined && (!prevIssue || prevIssue.priority !== patch.priority));
+ (patch.priority !== undefined && (!prevIssue || prevIssue.priority !== patch.priority)) ||
+ inboxFields.some((field) => patch[field] !== undefined && (!prevIssue || prevIssue[field] !== patch[field]));
if (archiveProjectionChanged) {
staleKeys.push(...qc.getQueryCache().findAll({ queryKey: inboxKeys.archived(wsId) })
.filter((query) => query.queryKey.length > inboxKeys.archived(wsId).length)
@@ -554,6 +556,10 @@ export function applyIssueChange(
patchInboxIssueProjection(qc, wsId, id, {
status: patch.status,
priority: patch.priority,
+ project_id: patch.project_id,
+ assignee_type: patch.assignee_type,
+ assignee_id: patch.assignee_id,
+ due_date: patch.due_date,
});
}
diff --git a/packages/core/issues/ws-updaters.test.ts b/packages/core/issues/ws-updaters.test.ts
index aba7600a44..5c3bb02f34 100644
--- a/packages/core/issues/ws-updaters.test.ts
+++ b/packages/core/issues/ws-updaters.test.ts
@@ -18,6 +18,8 @@ import {
} from "./ws-updaters";
import { issueKeys } from "./queries";
import { labelKeys } from "../labels/queries";
+import { EMPTY_INBOX_FILTERS } from "../inbox/filters";
+import { archivedInboxFacetsOptions, archivedInboxPagesOptions } from "../inbox/queries";
import { projectKeys } from "../projects/queries";
import type {
AgentActivityBucket,
@@ -205,6 +207,28 @@ describe("onIssueLabelsChanged", () => {
});
});
+ it("re-asks a label-filtered archive and its facets once a label change lands", () => {
+ const filters = { ...EMPTY_INBOX_FILTERS, labels: [labelB.id] };
+ const pages = archivedInboxPagesOptions(WS_ID, filters).queryKey;
+ const facets = archivedInboxFacetsOptions(WS_ID, filters).queryKey;
+ qc.setQueryData(pages, { pages: [{ items: [], nextCursor: null, hasMore: false }], pageParams: [null] });
+ qc.setQueryData(facets, { statuses: {}, priorities: {}, actors: {}, types: {}, projects: {}, assignees: {}, labels: {}, unreadCount: 0 });
+
+ onIssueLabelsChanged(qc, WS_ID, ISSUE_ID, [labelB], 2);
+
+ expectInvalidated(qc, pages);
+ expectInvalidated(qc, facets);
+ });
+
+ it("leaves the archive alone for an optimistic label patch", () => {
+ const pages = archivedInboxPagesOptions(WS_ID, EMPTY_INBOX_FILTERS).queryKey;
+ qc.setQueryData(pages, { pages: [{ items: [], nextCursor: null, hasMore: false }], pageParams: [null] });
+
+ patchIssueLabels(qc, WS_ID, ISSUE_ID, [labelB]);
+
+ expect(qc.getQueryState(pages)?.isInvalidated).toBe(false);
+ });
+
it("leaves the per-issue label cache untouched when the picker has not fetched", () => {
onIssueLabelsChanged(qc, WS_ID, ISSUE_ID, [labelB]);
diff --git a/packages/core/issues/ws-updaters.ts b/packages/core/issues/ws-updaters.ts
index e79331ba4e..4ded6b75b1 100644
--- a/packages/core/issues/ws-updaters.ts
+++ b/packages/core/issues/ws-updaters.ts
@@ -22,6 +22,7 @@ import {
patchIssueInBuckets,
} from "./cache-helpers";
import { cleanupDeletedIssueCaches } from "./delete-cache";
+import { patchInboxIssueProjection, refreshArchivedInboxMatches } from "../inbox/ws-updaters";
import type {
Issue,
IssueLabelsResponse,
@@ -556,6 +557,9 @@ export function onIssueLabelsChanged(
labels: Label[],
revision?: number,
) {
+ // Runs after the change is committed (event or mutation success), so the
+ // archive can be asked again; the optimistic patch below cannot.
+ void refreshArchivedInboxMatches(qc, wsId);
if (refetchForUnversionedIssueEvent(qc, wsId, issueId, revision)) {
qc.invalidateQueries({ queryKey: labelKeys.byIssue(wsId, issueId) });
return;
@@ -585,6 +589,7 @@ export function patchIssueLabels(
return;
}
patchIssueSnapshot(qc, wsId, issueId, { labels }, revision);
+ patchInboxIssueProjection(qc, wsId, issueId, { label_ids: labels.map((label) => label.id) });
qc.setQueryData<IssueLabelsResponse>(labelKeys.byIssue(wsId, issueId), (old) =>
old &&
!(
diff --git a/packages/core/types/inbox.ts b/packages/core/types/inbox.ts
index 473ed003a8..e789f1b98c 100644
--- a/packages/core/types/inbox.ts
+++ b/packages/core/types/inbox.ts
@@ -1,4 +1,4 @@
-import type { IssuePriority, IssueStatus } from "./issue";
+import type { IssueAssigneeType, IssuePriority, IssueStatus } from "./issue";
export type InboxSeverity = "action_required" | "attention" | "info";
@@ -63,6 +63,16 @@ export interface InboxItem {
* projection; null also covers notifications without a linked issue.
*/
issue_priority?: IssuePriority | null;
+ /**
+ * The linked issue's fields the inbox filters match on. Optional for the
+ * same reason as `issue_priority`; a server that has them always sends
+ * `issue_label_ids` as an array.
+ */
+ issue_project_id?: string | null;
+ issue_assignee_type?: IssueAssigneeType | null;
+ issue_assignee_id?: string | null;
+ issue_due_date?: string | null;
+ issue_label_ids?: string[] | null;
read: boolean;
archived: boolean;
created_at: string;
@@ -80,5 +90,9 @@ export interface ArchivedInboxFacets {
statuses: Record<string, number>;
priorities: Record<string, number>;
actors: Record<string, number>;
+ types: Record<string, number>;
+ projects: Record<string, number>;
+ assignees: Record<string, number>;
+ labels: Record<string, number>;
unreadCount: number;
}
diff --git a/packages/views/inbox/components/inbox-filter-menu.test.tsx b/packages/views/inbox/components/inbox-filter-menu.test.tsx
index 4464543372..20ba145096 100644
--- a/packages/views/inbox/components/inbox-filter-menu.test.tsx
+++ b/packages/views/inbox/components/inbox-filter-menu.test.tsx
@@ -15,7 +15,7 @@ import {
BUILT_IN_STATUS_ORDER,
} from "@multica/core/issues/config";
import {
- type InboxPriorityFilterSupport,
+ type InboxFilterSupport,
useInboxFilterStore,
} from "@multica/core/inbox/filter-store";
import type { InboxItem, IssueStatusEntry } from "@multica/core/types";
@@ -26,6 +26,7 @@ import { InboxFilterMenu } from "./inbox-filter-menu";
// this leaf render has none of — stubbed the same way the sibling
// inbox-detail-label suite stubs it.
const ACTOR_NAMES: Record<string, string> = { alice: "Alice", bob: "Bob" };
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
vi.mock("@multica/core/workspace/hooks", () => ({
useActorName: () => ({
getActorName: (type: string, id: string) =>
@@ -88,13 +89,15 @@ const ITEMS = [
function renderMenu({
items = ITEMS,
priorityFilterSupport = "supported",
+ issueFieldsSupport = "supported",
archived = false,
activeIssueIds,
getArchivedInboxFacets = vi.fn(async () => ({ statuses: {}, priorities: {}, actors: {}, unreadCount: 0 })),
statusEntries = BUILT_IN_STATUS_ORDER.map(statusEntry),
}: {
items?: InboxItem[];
- priorityFilterSupport?: InboxPriorityFilterSupport;
+ priorityFilterSupport?: InboxFilterSupport;
+ issueFieldsSupport?: InboxFilterSupport;
archived?: boolean;
activeIssueIds?: ReadonlySet<string>;
getArchivedInboxFacets?: ReturnType<typeof vi.fn>;
@@ -108,6 +111,11 @@ function renderMenu({
categories: [],
total: statusEntries.length,
}),
+ listProjects: async () => ({ projects: PROJECTS, total: PROJECTS.length }),
+ listLabels: async () => ({ labels: [], total: 0 }),
+ listMembers: async () => [],
+ listAgents: async () => [],
+ listSquads: async () => [],
} as unknown as ApiClient);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
@@ -118,6 +126,7 @@ function renderMenu({
wsId="ws-1"
items={items}
priorityFilterSupport={priorityFilterSupport}
+ issueFieldsSupport={issueFieldsSupport}
activeIssueIds={activeIssueIds}
archived={archived}
/>
@@ -125,12 +134,19 @@ function renderMenu({
);
}
-async function openSubmenu(name: "From" | "Status" | "Priority") {
- fireEvent.click(screen.getByRole("button", { name: "Filter inbox" }));
- const trigger = await screen.findByRole("menuitem", {
- name: new RegExp(`^${name}`),
- });
- fireEvent.click(trigger);
+const PROJECTS = [{ id: "project-1", title: "Launch", icon: null, status: "in_progress" }];
+
+function openMenu(name = "Filter inbox") {
+ fireEvent.click(screen.getByRole("button", { name }));
+}
+
+async function openSubmenu(name: string, trigger = "Filter inbox") {
+ openMenu(trigger);
+ fireEvent.click(await screen.findByRole("menuitem", { name: new RegExp(`^${name}`) }));
+}
+
+function storedFilters() {
+ return useInboxFilterStore.getState().filtersByWorkspace["ws-1"];
}
beforeEach(() => {
@@ -143,6 +159,103 @@ afterEach(() => {
});
describe("InboxFilterMenu", () => {
+ it("groups the fields into notification and issue sections", async () => {
+ renderMenu({
+ items: [item("from-alice", "todo", "high", { actor_type: "member", actor_id: "alice" })],
+ });
+ openMenu();
+
+ const notification = await screen.findByText("Notification");
+ const issue = screen.getByText("Issue");
+ for (const name of ["Read state", "Type", "From", "Received", "Status", "Priority", "Agent status", "Project", "Assignee", "Label", "Due date"]) {
+ expect(screen.getByRole("menuitem", { name: new RegExp(`^${name}`) })).toBeTruthy();
+ }
+ expect(notification.compareDocumentPosition(issue) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(screen.queryByText("Active")).toBeNull();
+ });
+
+ it("pins the fields in use on top with their current value", async () => {
+ const store = useInboxFilterStore.getState();
+ store.toggleFilterValue("ws-1", "type", "mention");
+ store.setFilterNegated("ws-1", "type", true);
+ renderMenu();
+ openMenu("1 active filter");
+
+ expect(await screen.findByText("Active")).toBeTruthy();
+ const type = screen.getByRole("menuitem", { name: /^Type/ });
+ expect(type).toHaveTextContent(/is not/);
+ expect(type).toHaveTextContent(/Mentions/);
+ // Pinned once: the notification section no longer repeats it.
+ expect(screen.getAllByRole("menuitem", { name: /^Type/ })).toHaveLength(1);
+ });
+
+ it("selects a notification type and switches it to is not", async () => {
+ renderMenu({
+ items: [
+ item("mention", "todo", "high"),
+ item("comment", "todo", "high", { type: "new_comment" }),
+ ],
+ });
+ await openSubmenu("Type");
+ fireEvent.click(await screen.findByRole("menuitemcheckbox", { name: /Comments & reactions.*1 notification/ }));
+ expect(storedFilters()?.types).toEqual(["comment"]);
+
+ fireEvent.click(screen.getByRole("menuitemradio", { name: "is not" }));
+ expect(storedFilters()?.negated).toEqual(["type"]);
+ });
+
+ it("keeps is not when it is chosen before the first type", async () => {
+ renderMenu({ items: [item("mention", "todo", "high")] });
+ await openSubmenu("Type");
+ fireEvent.click(await screen.findByRole("menuitemradio", { name: "is not" }));
+ fireEvent.click(screen.getByRole("menuitemcheckbox", { name: /^Agent runs/ }));
+
+ expect(storedFilters()).toMatchObject({ types: ["run"], negated: ["type"] });
+ expect(screen.getByRole("menuitemradio", { name: "is not" })).toHaveAttribute("aria-checked", "true");
+ });
+
+ it("finds a value by search and adds it in one click", async () => {
+ renderMenu();
+ openMenu();
+ fireEvent.change(await screen.findByRole("textbox", { name: "Filter by field or value…" }), {
+ target: { value: "last 7" },
+ });
+
+ fireEvent.click(await screen.findByRole("menuitemcheckbox", { name: /Received.*Last 7 days/ }));
+ expect(storedFilters()?.received).toBe("last_7_days");
+ });
+
+ it("offers a project from the directory and stores its id", async () => {
+ renderMenu({ items: [item("in-project", "todo", "high", { issue_project_id: "project-1", issue_label_ids: [] })] });
+ await openSubmenu("Project");
+
+ fireEvent.click(await screen.findByRole("menuitemcheckbox", { name: /Launch/ }));
+ expect(storedFilters()?.projects).toEqual(["project-1"]);
+ });
+
+ it("hides the issue-field dimensions for a server without them and clears a carried-over selection", async () => {
+ useInboxFilterStore.getState().toggleFilterValue("ws-1", "project", "project-1");
+ renderMenu({ issueFieldsSupport: "unsupported" });
+ openMenu();
+
+ await screen.findByRole("menuitem", { name: /^Status/ });
+ for (const name of ["Project", "Assignee", "Label", "Due date"]) {
+ expect(screen.queryByRole("menuitem", { name: new RegExp(`^${name}`) })).toBeNull();
+ }
+ await waitFor(() => expect(storedFilters()).toBeUndefined());
+ });
+
+ it("hides type, received and is not on an older archive server", async () => {
+ useInboxFilterStore.getState().toggleStatusFilter("ws-1", "done");
+ renderMenu({ archived: true, issueFieldsSupport: "unsupported" });
+ await openSubmenu("Status", "1 active filter");
+
+ await screen.findByRole("menuitemcheckbox", { name: /Done/ });
+ expect(screen.queryByRole("menuitemradio", { name: "is not" })).toBeNull();
+ expect(screen.queryByRole("menuitem", { name: /^Type/ })).toBeNull();
+ expect(screen.queryByRole("menuitem", { name: /^Received/ })).toBeNull();
+ });
+
it("keeps a selected retired status removable when absent from archive facets and pages", async () => {
useInboxFilterStore.getState().toggleStatusFilter("ws-1", "custom-retired");
renderMenu({
@@ -152,23 +265,21 @@ describe("InboxFilterMenu", () => {
name: "Retired status", is_system: false, archived_at: "2026-09-01T00:00:00Z",
}],
});
- fireEvent.click(screen.getByRole("button", { name: "1 active filter" }));
- fireEvent.click(await screen.findByRole("menuitem", { name: /^Status/ }));
+ await openSubmenu("Status", "1 active filter");
const selected = await screen.findByRole("menuitemcheckbox", { name: "Retired status" });
expect(selected).toHaveAttribute("aria-checked", "true");
fireEvent.click(selected);
- expect(useInboxFilterStore.getState().filtersByWorkspace["ws-1"]?.statuses).toEqual([]);
+ expect(storedFilters()).toBeUndefined();
});
it("keeps a selected priority removable when absent from archive facets and pages", async () => {
useInboxFilterStore.getState().togglePriorityFilter("ws-1", "high");
renderMenu({ items: [], archived: true });
- fireEvent.click(screen.getByRole("button", { name: "1 active filter" }));
- fireEvent.click(await screen.findByRole("menuitem", { name: /^Priority/ }));
+ await openSubmenu("Priority", "1 active filter");
const selected = await screen.findByRole("menuitemcheckbox", { name: "High" });
expect(selected).toHaveAttribute("aria-checked", "true");
fireEvent.click(selected);
- expect(useInboxFilterStore.getState().filtersByWorkspace["ws-1"]?.priorities).toEqual([]);
+ expect(storedFilters()).toBeUndefined();
});
it("loads full-archive facets only when opened, including an actor absent from loaded rows", async () => {
@@ -183,88 +294,59 @@ describe("InboxFilterMenu", () => {
it("selects a status and exposes the active count on the trigger", async () => {
renderMenu();
await openSubmenu("Status");
- const todo = await screen.findByRole("menuitemcheckbox", {
- name: /Todo.*1 notification/,
- });
-
- fireEvent.click(todo);
+ fireEvent.click(await screen.findByRole("menuitemcheckbox", { name: /Todo.*1 notification/ }));
- expect(
- useInboxFilterStore.getState().filtersByWorkspace["ws-1"]?.statuses,
- ).toEqual(["todo"]);
+ expect(storedFilters()?.statuses).toEqual(["todo"]);
await waitFor(() =>
- expect(
- screen.getByRole("button", { name: "1 active filter" }),
- ).toHaveTextContent("1"),
+ expect(screen.getByRole("button", { name: "1 active filter" })).toHaveTextContent("1"),
);
});
it("selects a priority", async () => {
renderMenu();
await openSubmenu("Priority");
- const high = await screen.findByRole("menuitemcheckbox", {
- name: /High.*1 notification/,
- });
+ fireEvent.click(await screen.findByRole("menuitemcheckbox", { name: /High.*1 notification/ }));
- fireEvent.click(high);
-
- expect(
- useInboxFilterStore.getState().filtersByWorkspace["ws-1"]?.priorities,
- ).toEqual(["high"]);
+ expect(storedFilters()?.priorities).toEqual(["high"]);
});
- it("clears every active filter from the root menu", async () => {
+ it("resets every active filter from the root menu", async () => {
const store = useInboxFilterStore.getState();
store.toggleStatusFilter("ws-1", "todo");
store.togglePriorityFilter("ws-1", "high");
renderMenu();
- fireEvent.click(screen.getByRole("button", { name: "2 active filters" }));
- fireEvent.click(await screen.findByRole("menuitem", { name: "Clear filters" }));
+ openMenu("2 active filters");
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Reset all filters" }));
- expect(
- useInboxFilterStore.getState().filtersByWorkspace["ws-1"],
- ).toBeUndefined();
+ expect(storedFilters()).toBeUndefined();
});
- it("offers only the actors the visible rows carry", async () => {
+ it("offers only the actors the view's notifications carry", async () => {
renderMenu({
items: [
- item("from-alice", "todo", "high", {
- actor_type: "member",
- actor_id: "alice",
- }),
- item("from-bob", "done", "low", {
- actor_type: "agent",
- actor_id: "bob",
- }),
+ item("from-alice", "todo", "high", { actor_type: "member", actor_id: "alice" }),
+ item("from-bob", "done", "low", { actor_type: "agent", actor_id: "bob" }),
],
});
await openSubmenu("From");
- const alice = await screen.findByRole("menuitemcheckbox", {
- name: /Alice.*1 notification/,
- });
- expect(
- screen.getByRole("menuitemcheckbox", { name: /Bob.*1 notification/ }),
- ).toBeTruthy();
+ const alice = await screen.findByRole("menuitemcheckbox", { name: /Alice.*1 notification/ });
+ expect(screen.getByRole("menuitemcheckbox", { name: /Bob.*1 notification/ })).toBeTruthy();
fireEvent.click(alice);
-
- expect(
- useInboxFilterStore.getState().filtersByWorkspace["ws-1"]?.actors,
- ).toEqual(["member:alice"]);
+ expect(storedFilters()?.actors).toEqual(["member:alice"]);
});
- it("hides the From submenu when no row carries an actor", async () => {
+ it("hides From when no notification carries an actor", async () => {
renderMenu();
+ openMenu();
- fireEvent.click(screen.getByRole("button", { name: "Filter inbox" }));
-
+ await screen.findByRole("menuitem", { name: /^Status/ });
expect(screen.queryByRole("menuitem", { name: /^From/ })).toBeNull();
});
- it("toggles unread only and counts the unread rows behind it", async () => {
+ it("filters to unread and counts the unread issues behind it", async () => {
renderMenu({
items: [
item("unread", "todo", "high"),
@@ -272,46 +354,32 @@ describe("InboxFilterMenu", () => {
],
});
- fireEvent.click(screen.getByRole("button", { name: "Filter inbox" }));
- const unread = await screen.findByRole("menuitemcheckbox", {
- name: /Unread only.*1 notification/,
- });
-
- fireEvent.click(unread);
+ await openSubmenu("Read state");
+ fireEvent.click(await screen.findByRole("menuitemcheckbox", { name: /Unread.*1 notification/ }));
- expect(
- useInboxFilterStore.getState().filtersByWorkspace["ws-1"]?.unreadOnly,
- ).toBe(true);
+ expect(storedFilters()?.unreadOnly).toBe(true);
await waitFor(() =>
- expect(
- screen.getByRole("button", { name: "1 active filter" }),
- ).toHaveTextContent("1"),
+ expect(screen.getByRole("button", { name: "1 active filter" })).toHaveTextContent("1"),
);
});
- it("toggles no agents working without a count beside it", async () => {
+ it("filters by agent status without a count beside it", async () => {
renderMenu({ activeIssueIds: new Set(["issue-todo-high"]) });
- fireEvent.click(screen.getByRole("button", { name: "Filter inbox" }));
- fireEvent.click(
- await screen.findByRole("menuitemcheckbox", {
- name: /^No agents working$/,
- }),
- );
+ await openSubmenu("Agent status");
+ fireEvent.click(await screen.findByRole("menuitemcheckbox", { name: /^Idle$/ }));
- expect(
- useInboxFilterStore.getState().filtersByWorkspace["ws-1"]?.idleOnly,
- ).toBe(true);
+ expect(storedFilters()?.agent).toBe("idle");
});
- it("hides no agents working in the archive and ignores a carried-over selection", async () => {
- useInboxFilterStore.getState().toggleIdleOnly("ws-1");
+ it("hides agent status in the archive and ignores a carried-over selection", async () => {
+ useInboxFilterStore.getState().setAgent("ws-1", "idle");
renderMenu({ archived: true });
// Not counted on the trigger, and not offered in the menu.
- fireEvent.click(screen.getByRole("button", { name: "Filter inbox" }));
- await screen.findByRole("menuitemcheckbox", { name: /Unread only/ });
- expect(screen.queryByRole("menuitemcheckbox", { name: /No agents working/ })).toBeNull();
+ openMenu();
+ await screen.findByRole("menuitem", { name: /^Status/ });
+ expect(screen.queryByRole("menuitem", { name: /^Agent status/ })).toBeNull();
});
it("hides priority and clears its filter for a legacy response", async () => {
@@ -321,14 +389,9 @@ describe("InboxFilterMenu", () => {
priorityFilterSupport: "unsupported",
});
- fireEvent.click(screen.getByRole("button", { name: "Filter inbox" }));
- expect(
- screen.queryByRole("menuitem", { name: /^Priority/ }),
- ).toBeNull();
- await waitFor(() =>
- expect(
- useInboxFilterStore.getState().filtersByWorkspace["ws-1"],
- ).toBeUndefined(),
- );
+ openMenu();
+ await screen.findByRole("menuitem", { name: /^Status/ });
+ expect(screen.queryByRole("menuitem", { name: /^Priority/ })).toBeNull();
+ await waitFor(() => expect(storedFilters()).toBeUndefined());
});
});
diff --git a/packages/views/inbox/components/inbox-filter-menu.tsx b/packages/views/inbox/components/inbox-filter-menu.tsx
index d7e7a3a40b..b9fb1b0dab 100644
--- a/packages/views/inbox/components/inbox-filter-menu.tsx
+++ b/packages/views/inbox/components/inbox-filter-menu.tsx
@@ -1,16 +1,23 @@
"use client";
-import { useEffect, useMemo, useState } from "react";
-import { BotOff, CircleDot, Filter, Mail, RotateCcw, SignalHigh, UserRound } from "@multica/ui/icons";
+import { useEffect, useMemo, useState, type ReactNode } from "react";
+import { Filter, RotateCcw, Search } from "@multica/ui/icons";
import { PRIORITY_DISPLAY_ORDER } from "@multica/core/issues/config";
+import { DUE_DATE_FILTERS, FILTER_NONE_VALUE } from "@multica/core/issues/stores/filter-tree";
import {
- filterInboxItems,
+ INBOX_AGENT_FILTERS,
+ INBOX_RECEIVED_FILTERS,
+ INBOX_TYPE_GROUPS,
+ activeInboxFilterKeys,
+ effectiveInboxFilters,
inboxActorKey,
inboxActorKeyParts,
- inboxFiltersForArchive,
- inboxFiltersForPrioritySupport,
+ inboxFacetCounts,
inboxFilterCount,
- type InboxPriorityFilterSupport,
+ inboxFilterValues,
+ type InboxFilterKey,
+ type InboxFilterSupport,
+ type InboxListDimension,
useInboxFilters,
useInboxFilterStore,
} from "@multica/core/inbox/filter-store";
@@ -25,7 +32,9 @@ import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
+ DropdownMenuGroup,
DropdownMenuItem,
+ DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
@@ -33,163 +42,193 @@ import {
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
import { cn } from "@multica/ui/lib/utils";
+import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
import { PriorityIcon } from "../../issues/components/priority-icon";
import { StatusIcon } from "../../issues/components/status-icon";
+import { FilterOperator } from "../../issues/components/filter-chips-bar";
+import { matchesFilterQuery, useFilterValueCatalog } from "../../issues/components/filter-field-options";
+import { stopMenuSearchKeys } from "../../issues/components/advanced-filter-panel";
+import {
+ ActorSubContent,
+ FilterOperatorToggle,
+ LabelSubContent,
+ ProjectSubContent,
+} from "../../issues/components/issues-header";
import { useStatusOptions } from "../../issues/utils/status-options";
import { useT } from "../../i18n";
+import {
+ INBOX_AGENT_ICONS,
+ INBOX_FILTER_ICONS,
+ INBOX_TYPE_ICONS,
+ useInboxFilterChips,
+ useInboxFilterLabels,
+} from "./inbox-filter-options";
-function statusCounts(items: InboxItem[]): Map<string, number> {
- const counts = new Map<string, number>();
- for (const item of items) {
- if (item.issue_status == null) continue;
- counts.set(item.issue_status, (counts.get(item.issue_status) ?? 0) + 1);
- }
- return counts;
-}
+const EMPTY_ISSUE_IDS: ReadonlySet<string> = new Set();
+const NO_COUNTS = new Map<string, number>();
-function priorityCounts(items: InboxItem[]): Map<string, number> {
- const counts = new Map<string, number>();
- for (const item of items) {
- if (item.issue_priority == null) continue;
- counts.set(
- item.issue_priority,
- (counts.get(item.issue_priority) ?? 0) + 1,
- );
- }
- return counts;
-}
+const NOTIFICATION_KEYS: readonly InboxFilterKey[] = ["unread", "type", "actor", "received"];
+const ISSUE_KEYS: readonly InboxFilterKey[] = [
+ "status",
+ "priority",
+ "agent",
+ "project",
+ "assignee",
+ "label",
+ "dueDate",
+];
-function actorCounts(items: InboxItem[]): Map<string, number> {
- const counts = new Map<string, number>();
- for (const item of items) {
- const key = inboxActorKey(item);
- if (key == null) continue;
- counts.set(key, (counts.get(key) ?? 0) + 1);
- }
- return counts;
+function toMap(record: Record<string, number> | undefined): Map<string, number> {
+ return new Map(Object.entries(record ?? {}));
}
-const EMPTY_ISSUE_IDS: ReadonlySet<string> = new Set();
+/** A value row: hover checkbox, icon, label, and its faceted count. */
+function ValueItem({
+ checked,
+ onToggle,
+ icon,
+ label,
+ count,
+}: {
+ checked: boolean;
+ onToggle: () => void;
+ icon: ReactNode;
+ label: string;
+ count?: number;
+}) {
+ const { t } = useT("inbox");
+ return (
+ <DropdownMenuCheckboxItem checked={checked} onCheckedChange={onToggle} className={FILTER_ITEM_CLASS}>
+ <HoverCheck checked={checked} />
+ {icon}
+ <span className="truncate">{label}</span>
+ {count != null && count > 0 && (
+ <span className="ml-auto pl-3 text-caption text-muted-foreground">
+ {t(($) => $.filters.notification_count, { count })}
+ </span>
+ )}
+ </DropdownMenuCheckboxItem>
+ );
+}
-/** Faceted filters for the deduplicated list currently on screen. */
+/**
+ * The inbox filter, shaped like the issue filter: search, the dimensions in
+ * use pinned on top, then notification and issue fields, "is" / "is not" per
+ * field, and each field's current value on its row.
+ *
+ * `items` are the view's notifications, every one rather than one per issue:
+ * the notification fields match any notification of an issue.
+ */
export function InboxFilterMenu({
wsId,
items,
priorityFilterSupport,
+ issueFieldsSupport = "supported",
activeIssueIds = EMPTY_ISSUE_IDS,
archived = false,
}: {
wsId: string;
items: InboxItem[];
- priorityFilterSupport: InboxPriorityFilterSupport;
+ priorityFilterSupport: InboxFilterSupport;
+ issueFieldsSupport?: InboxFilterSupport;
/** Issues an agent is running or queued on. */
activeIssueIds?: ReadonlySet<string>;
archived?: boolean;
}) {
const { t } = useT("inbox");
const { t: tIssues } = useT("issues");
+ const labels = useInboxFilterLabels();
const filters = useInboxFilters(wsId);
+ // Actions are stable; handlers read them without subscribing to the store.
+ const store = useInboxFilterStore.getState();
+ const clearPriorityFilters = useInboxFilterStore((state) => state.clearPriorityFilters);
+ const clearIssueFieldFilters = useInboxFilterStore((state) => state.clearIssueFieldFilters);
const [open, setOpen] = useState(false);
- const facetsQuery = useQuery({ ...archivedInboxFacetsOptions(wsId, filters), enabled: archived && open });
- const facets = archived ? facetsQuery.data : undefined;
- const toggleStatus = useInboxFilterStore((state) => state.toggleStatusFilter);
- const togglePriority = useInboxFilterStore(
- (state) => state.togglePriorityFilter,
- );
- const toggleActor = useInboxFilterStore((state) => state.toggleActorFilter);
- const toggleUnreadOnly = useInboxFilterStore(
- (state) => state.toggleUnreadOnly,
- );
- const toggleIdleOnly = useInboxFilterStore((state) => state.toggleIdleOnly);
+ const [search, setSearch] = useState("");
+ const [activeAtOpen, setActiveAtOpen] = useState<ReadonlySet<InboxFilterKey> | null>(null);
+ const query = search.trim().toLowerCase();
const { getActorName, getActorInitials, getActorAvatarUrl } = useActorName();
- const clearFilters = useInboxFilterStore((state) => state.clearFilters);
- const clearPriorityFilters = useInboxFilterStore(
- (state) => state.clearPriorityFilters,
+
+ const effectiveFilters = useMemo(
+ () => effectiveInboxFilters(filters, { priority: priorityFilterSupport, issueFields: issueFieldsSupport, archived }),
+ [filters, priorityFilterSupport, issueFieldsSupport, archived],
);
+ const facetsQuery = useQuery({ ...archivedInboxFacetsOptions(wsId, effectiveFilters), enabled: archived && open });
+ const facets = archived ? facetsQuery.data : undefined;
+ const activeCount = inboxFilterCount(effectiveFilters);
+ const chips = useInboxFilterChips(wsId, effectiveFilters);
+ const chipByKey = new Map(chips.map((chip) => [chip.key, chip]));
+
+ const issueFieldsSupported = issueFieldsSupport === "supported";
+ // An older archive server ignores type, received and "is not"; offering
+ // them there would answer a different question than the one asked.
+ const serverOnlySupported = !archived || issueFieldsSupported;
+ const available = (key: InboxFilterKey) => {
+ switch (key) {
+ case "priority":
+ return priorityFilterSupport === "supported";
+ case "agent":
+ return !archived;
+ case "actor":
+ return actorOptions.length > 0;
+ case "project":
+ case "assignee":
+ case "label":
+ case "dueDate":
+ return issueFieldsSupported;
+ case "type":
+ case "received":
+ return serverOnlySupported;
+ default:
+ return true;
+ }
+ };
+
+ // A workspace keeps its filters while its backend changes (Desktop server
+ // switch, self-hosted downgrade, rolling deployment). Drop a selection only
+ // once incompatibility is confirmed; "unknown" keeps it dormant.
+ const hasPriorities = filters.priorities.length > 0;
+ const hasIssueFields = filters.projects.length + filters.assignees.length + filters.labels.length + filters.dueDates.length > 0;
+ useEffect(() => {
+ if (priorityFilterSupport === "unsupported" && hasPriorities) clearPriorityFilters(wsId);
+ }, [clearPriorityFilters, hasPriorities, priorityFilterSupport, wsId]);
+ useEffect(() => {
+ if (issueFieldsSupport === "unsupported" && hasIssueFields) clearIssueFieldFilters(wsId);
+ }, [clearIssueFieldFilters, hasIssueFields, issueFieldsSupport, wsId]);
+
+ // Counts are faceted: each respects every other active dimension while
+ // ignoring its own, so it says how many rows selecting that value shows.
+ const localCounts = useMemo(
+ () => (archived || !open ? null : inboxFacetCounts(items, effectiveFilters, { activeIssueIds })),
+ [archived, open, items, effectiveFilters, activeIssueIds],
+ );
+ const counts = {
+ types: archived ? toMap(facets?.types) : localCounts?.types ?? NO_COUNTS,
+ actors: archived ? toMap(facets?.actors) : localCounts?.actors ?? NO_COUNTS,
+ statuses: archived ? toMap(facets?.statuses) : localCounts?.statuses ?? NO_COUNTS,
+ priorities: archived ? toMap(facets?.priorities) : localCounts?.priorities ?? NO_COUNTS,
+ projects: archived ? toMap(facets?.projects) : localCounts?.projects ?? NO_COUNTS,
+ assignees: archived ? toMap(facets?.assignees) : localCounts?.assignees ?? NO_COUNTS,
+ labels: archived ? toMap(facets?.labels) : localCounts?.labels ?? NO_COUNTS,
+ unread: archived ? facets?.unreadCount ?? 0 : localCounts?.unread ?? 0,
+ };
+
const inboxStatusKeys = useMemo(
() => [
...new Set([
...filters.statuses,
...Object.keys(facets?.statuses ?? {}),
- ...items.flatMap((item) =>
- item.issue_status == null ? [] : [item.issue_status],
- ),
+ ...items.flatMap((item) => (item.issue_status == null ? [] : [item.issue_status])),
]),
],
[items, facets, filters.statuses],
);
const statusOptions = useStatusOptions(wsId, inboxStatusKeys);
- const effectiveFilters = useMemo(() => {
- const supported = inboxFiltersForPrioritySupport(filters, priorityFilterSupport);
- return archived ? inboxFiltersForArchive(supported) : supported;
- }, [filters, priorityFilterSupport, archived]);
- const activeCount = inboxFilterCount(effectiveFilters);
- const priorityFilteringSupported = priorityFilterSupport === "supported";
-
- // A workspace can retain filters while its backend changes (Desktop server
- // switch, self-hosted downgrade, or rolling deployment). Remove a priority
- // selection only once incompatibility is confirmed; "unknown" simply keeps
- // it dormant while an empty list gives us no capability evidence.
- useEffect(() => {
- if (
- priorityFilterSupport === "unsupported" &&
- filters.priorities.length > 0
- ) {
- clearPriorityFilters(wsId);
- }
- }, [
- clearPriorityFilters,
- filters.priorities.length,
- priorityFilterSupport,
- wsId,
- ]);
-
- // Counts are faceted: every count respects the other active dimensions while
- // ignoring its own, so each number says how many rows selecting that value
- // can actually reveal.
- const statusFacetItems = useMemo(
- () => filterInboxItems(items, { ...effectiveFilters, statuses: [] }, { activeIssueIds }),
- [items, effectiveFilters, activeIssueIds],
- );
- const priorityFacetItems = useMemo(
- () => filterInboxItems(items, { ...effectiveFilters, priorities: [] }, { activeIssueIds }),
- [items, effectiveFilters, activeIssueIds],
- );
- const actorFacetItems = useMemo(
- () => filterInboxItems(items, { ...effectiveFilters, actors: [] }, { activeIssueIds }),
- [items, effectiveFilters, activeIssueIds],
- );
- const localUnreadCount = useMemo(
- () =>
- filterInboxItems(
- items,
- { ...effectiveFilters, unreadOnly: false },
- { activeIssueIds },
- ).filter((item) => item.read !== true).length,
- [items, effectiveFilters, activeIssueIds],
- );
- const localStatuses = useMemo(
- () => statusCounts(statusFacetItems),
- [statusFacetItems],
- );
- const localPriorities = useMemo(
- () => priorityCounts(priorityFacetItems),
- [priorityFacetItems],
- );
- const localActors = useMemo(
- () => actorCounts(actorFacetItems),
- [actorFacetItems],
- );
- const unreadCount = archived ? facets?.unreadCount ?? 0 : localUnreadCount;
- const statuses = archived ? new Map(Object.entries(facets?.statuses ?? {})) : localStatuses;
- const priorities = archived ? new Map(Object.entries(facets?.priorities ?? {})) : localPriorities;
- const actors = archived ? new Map(Object.entries(facets?.actors ?? {})) : localActors;
- // The universe of actors comes from every row in the view rather than the
- // faceted subset: picking one actor must not remove the others from the menu
- // that offers them. Sorted by name so the list does not reshuffle as counts
- // change under other selections.
+ // The sender list comes from every notification in the view rather than
+ // the faceted subset: picking one sender must not remove the others from
+ // the menu that offers them. Sorted by name so it does not reshuffle.
const actorOptions = useMemo(() => {
- const keys = new Set<string>(archived ? [...Object.keys(facets?.actors ?? {}), ...filters.actors] : []);
+ const keys = new Set<string>([...filters.actors, ...Object.keys(facets?.actors ?? {})]);
for (const item of archived ? [] : items) {
const key = inboxActorKey(item);
if (key != null) keys.add(key);
@@ -201,13 +240,367 @@ export function InboxFilterMenu({
})
.sort((a, b) => a.name.localeCompare(b.name));
}, [items, getActorName, archived, facets, filters.actors]);
+ const valueCatalog = useFilterValueCatalog(query.length > 0);
+
+ const isSelected = (dimension: InboxListDimension, value: string) =>
+ inboxFilterValues(effectiveFilters, dimension).includes(value);
+ const toggle = (dimension: InboxListDimension, value: string) =>
+ store.toggleFilterValue(wsId, dimension, value);
+ const operator = (dimension: InboxListDimension) =>
+ serverOnlySupported ? (
+ <FilterOperatorToggle
+ negated={effectiveFilters.negated.includes(dimension)}
+ onNegatedChange={(negated) => store.setFilterNegated(wsId, dimension, negated)}
+ />
+ ) : null;
+ const actorAvatar = (option: { type: string; id: string; name: string }) => (
+ <ActorAvatar
+ size="xs"
+ name={option.name}
+ initials={getActorInitials(option.type, option.id)}
+ avatarUrl={getActorAvatarUrl(option.type, option.id)}
+ isAgent={option.type === "agent"}
+ isSquad={option.type === "squad"}
+ isSystem={option.type === "system"}
+ />
+ );
+ const statusIcon = (key: string) => {
+ const option = statusOptions.find((candidate) => candidate.key === key);
+ return option ? (
+ <StatusIcon status={option.key} category={option.category} color={option.color} icon={option.icon} className="size-3.5" />
+ ) : null;
+ };
+
+ const submenuBody = (key: InboxFilterKey): ReactNode => {
+ switch (key) {
+ case "unread":
+ return (
+ <ValueItem
+ checked={effectiveFilters.unreadOnly}
+ onToggle={() => store.toggleUnreadOnly(wsId)}
+ icon={<span className="flex size-3.5 items-center justify-center"><span className="size-1.5 rounded-full bg-brand" /></span>}
+ label={labels.unread}
+ count={counts.unread}
+ />
+ );
+ case "type":
+ return (
+ <>
+ {operator("type")}
+ {INBOX_TYPE_GROUPS.map((type) => {
+ const Icon = INBOX_TYPE_ICONS[type];
+ return (
+ <ValueItem
+ key={type}
+ checked={isSelected("type", type)}
+ onToggle={() => toggle("type", type)}
+ icon={<Icon className="size-3.5 text-muted-foreground" />}
+ label={labels.type[type]}
+ count={counts.types.get(type)}
+ />
+ );
+ })}
+ </>
+ );
+ case "actor":
+ return (
+ <>
+ {operator("actor")}
+ <div className="max-h-72 overflow-y-auto">
+ {actorOptions.map((option) => (
+ <ValueItem
+ key={option.key}
+ checked={isSelected("actor", option.key)}
+ onToggle={() => toggle("actor", option.key)}
+ icon={actorAvatar(option)}
+ label={option.name}
+ count={counts.actors.get(option.key)}
+ />
+ ))}
+ </div>
+ </>
+ );
+ case "received":
+ return INBOX_RECEIVED_FILTERS.map((received) => (
+ <ValueItem
+ key={received}
+ checked={effectiveFilters.received === received}
+ onToggle={() => store.setReceived(wsId, received)}
+ icon={<INBOX_FILTER_ICONS.received className="size-3.5 text-muted-foreground" />}
+ label={labels.received[received]}
+ />
+ ));
+ case "status":
+ return (
+ <>
+ {operator("status")}
+ {statusOptions.map((option) => (
+ <ValueItem
+ key={option.key}
+ checked={isSelected("status", option.key)}
+ onToggle={() => toggle("status", option.key)}
+ icon={statusIcon(option.key)}
+ label={option.label}
+ count={counts.statuses.get(option.key)}
+ />
+ ))}
+ </>
+ );
+ case "priority":
+ return (
+ <>
+ {operator("priority")}
+ {PRIORITY_DISPLAY_ORDER.map((priority) => (
+ <ValueItem
+ key={priority}
+ checked={isSelected("priority", priority)}
+ onToggle={() => toggle("priority", priority)}
+ icon={<PriorityIcon priority={priority} />}
+ label={tIssues(($) => $.priority[priority])}
+ count={counts.priorities.get(priority)}
+ />
+ ))}
+ </>
+ );
+ case "agent":
+ return INBOX_AGENT_FILTERS.map((agent) => {
+ const Icon = INBOX_AGENT_ICONS[agent];
+ return (
+ <ValueItem
+ key={agent}
+ checked={effectiveFilters.agent === agent}
+ onToggle={() => store.setAgent(wsId, agent)}
+ icon={<Icon className="size-3.5 text-muted-foreground" />}
+ label={labels.agent[agent]}
+ />
+ );
+ });
+ case "project":
+ return (
+ <>
+ {operator("project")}
+ <ProjectSubContent
+ counts={counts.projects}
+ selected={effectiveFilters.projects.filter((id) => id !== FILTER_NONE_VALUE)}
+ onToggle={(id) => toggle("project", id)}
+ includeNoProject={isSelected("project", FILTER_NONE_VALUE)}
+ onToggleNoProject={() => toggle("project", FILTER_NONE_VALUE)}
+ noProjectCount={counts.projects.get(FILTER_NONE_VALUE) ?? 0}
+ />
+ </>
+ );
+ case "assignee":
+ return (
+ <>
+ {operator("assignee")}
+ <ActorSubContent
+ counts={counts.assignees}
+ selected={effectiveFilters.assignees.flatMap((key) => {
+ const { type, id } = inboxActorKeyParts(key);
+ return type === "member" || type === "agent" || type === "squad" ? [{ type, id }] : [];
+ })}
+ onToggle={(actor) => toggle("assignee", `${actor.type}:${actor.id}`)}
+ showNoAssignee
+ includeNoAssignee={isSelected("assignee", FILTER_NONE_VALUE)}
+ onToggleNoAssignee={() => toggle("assignee", FILTER_NONE_VALUE)}
+ noAssigneeCount={counts.assignees.get(FILTER_NONE_VALUE) ?? 0}
+ />
+ </>
+ );
+ case "label":
+ return (
+ <>
+ {operator("label")}
+ <LabelSubContent
+ counts={counts.labels}
+ selected={[...effectiveFilters.labels]}
+ onToggle={(id) => toggle("label", id)}
+ />
+ </>
+ );
+ case "dueDate":
+ return (
+ <>
+ {operator("dueDate")}
+ {DUE_DATE_FILTERS.map((bucket) => (
+ <ValueItem
+ key={bucket}
+ checked={isSelected("dueDate", bucket)}
+ onToggle={() => toggle("dueDate", bucket)}
+ icon={<INBOX_FILTER_ICONS.dueDate className="size-3.5 text-muted-foreground" />}
+ label={labels.dueDate(bucket)}
+ />
+ ))}
+ </>
+ );
+ }
+ };
+
+ // Directory-backed submenus bring their own search and padding.
+ const flushContent = (key: InboxFilterKey) => key === "project" || key === "assignee" || key === "label";
+ const section = (key: InboxFilterKey) => {
+ const Icon = INBOX_FILTER_ICONS[key];
+ const chip = chipByKey.get(key);
+ return (
+ <DropdownMenuSub key={key}>
+ <DropdownMenuSubTrigger>
+ <Icon className="size-3.5" />
+ <span className="flex-1">{labels.dimension[key]}</span>
+ {chip && (
+ <span className="ml-3 flex min-w-0 items-center gap-1 text-caption">
+ <FilterOperator negated={chip.negated} />
+ <span className="max-w-40 truncate font-medium text-primary">{chip.value}</span>
+ </span>
+ )}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className={cn("w-auto min-w-52", flushContent(key) && "p-0")}>
+ {submenuBody(key)}
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+ };
+
+ // The dimensions in use when the menu opened go first; membership is
+ // taken at open, so a row never jumps out from under the pointer.
+ const activeKeys = activeAtOpen ?? new Set(activeInboxFilterKeys(effectiveFilters));
+ const group = (title: string, keys: readonly InboxFilterKey[]) => {
+ const shown = keys.filter((key) => available(key) && !activeKeys.has(key));
+ if (shown.length === 0) return null;
+ return (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{title}</DropdownMenuLabel>
+ {shown.map(section)}
+ </DropdownMenuGroup>
+ );
+ };
+
+ // Search: matching fields keep their submenus; matching values become
+ // one-click rows that read as the condition they add.
+ const allKeys = [...NOTIFICATION_KEYS, ...ISSUE_KEYS].filter(available);
+ const fieldHits = query ? allKeys.filter((key) => matchesFilterQuery(labels.dimension[key], query)) : [];
+ type ValueHit = { key: InboxFilterKey; value: string; label: string; icon: ReactNode; checked: boolean; onToggle: () => void };
+ const valueHits: ValueHit[] = [];
+ if (query) {
+ const listHit = (key: InboxListDimension, value: string, label: string, icon: ReactNode) => ({
+ key, value, label, icon, checked: isSelected(key, value), onToggle: () => toggle(key, value),
+ });
+ if (available("unread")) {
+ valueHits.push({
+ key: "unread", value: "unread", label: labels.unread, icon: null,
+ checked: effectiveFilters.unreadOnly, onToggle: () => store.toggleUnreadOnly(wsId),
+ });
+ }
+ if (available("type")) {
+ for (const type of INBOX_TYPE_GROUPS) {
+ const Icon = INBOX_TYPE_ICONS[type];
+ valueHits.push(listHit("type", type, labels.type[type], <Icon className="size-3.5 text-muted-foreground" />));
+ }
+ }
+ for (const option of actorOptions) valueHits.push(listHit("actor", option.key, option.name, actorAvatar(option)));
+ if (available("received")) {
+ for (const received of INBOX_RECEIVED_FILTERS) {
+ valueHits.push({
+ key: "received", value: received, label: labels.received[received], icon: null,
+ checked: effectiveFilters.received === received, onToggle: () => store.setReceived(wsId, received),
+ });
+ }
+ }
+ for (const option of statusOptions) valueHits.push(listHit("status", option.key, option.label, statusIcon(option.key)));
+ if (available("priority")) {
+ for (const option of valueCatalog("priority")) valueHits.push(listHit("priority", option.value, option.label, option.icon));
+ }
+ if (available("agent")) {
+ for (const agent of INBOX_AGENT_FILTERS) {
+ valueHits.push({
+ key: "agent", value: agent, label: labels.agent[agent], icon: null,
+ checked: effectiveFilters.agent === agent, onToggle: () => store.setAgent(wsId, agent),
+ });
+ }
+ }
+ for (const dimension of ["project", "assignee", "label", "dueDate"] as const) {
+ if (!available(dimension)) continue;
+ for (const option of valueCatalog(dimension)) valueHits.push(listHit(dimension, option.value, option.label, option.icon));
+ }
+ }
+ const matchedValues = valueHits.filter((hit) => matchesFilterQuery(hit.label, query)).slice(0, 50);
+
+ const menuBody = query ? (
+ <>
+ {fieldHits.length > 0 && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{tIssues(($) => $.filters.search_fields)}</DropdownMenuLabel>
+ {fieldHits.map(section)}
+ </DropdownMenuGroup>
+ )}
+ {fieldHits.length > 0 && matchedValues.length > 0 && <DropdownMenuSeparator />}
+ {matchedValues.length > 0 && (
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{tIssues(($) => $.filters.search_values)}</DropdownMenuLabel>
+ {matchedValues.map((hit) => {
+ const FieldIcon = INBOX_FILTER_ICONS[hit.key];
+ return (
+ <DropdownMenuCheckboxItem
+ key={`${hit.key}:${hit.value}`}
+ checked={hit.checked}
+ onCheckedChange={hit.onToggle}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={hit.checked} />
+ <FieldIcon className="size-3.5 text-muted-foreground" />
+ <span className="shrink-0 text-muted-foreground">{labels.dimension[hit.key]}</span>
+ <FilterOperator negated={effectiveFilters.negated.includes(hit.key as InboxListDimension)} />
+ {hit.icon}
+ <span className="truncate">{hit.label}</span>
+ </DropdownMenuCheckboxItem>
+ );
+ })}
+ </DropdownMenuGroup>
+ )}
+ {fieldHits.length === 0 && matchedValues.length === 0 && (
+ <div className="px-2 py-3 text-center text-body text-muted-foreground">
+ {tIssues(($) => $.filters.no_results)}
+ </div>
+ )}
+ </>
+ ) : (
+ <>
+ {activeKeys.size > 0 && (
+ <>
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>{tIssues(($) => $.filters.active_section)}</DropdownMenuLabel>
+ {[...NOTIFICATION_KEYS, ...ISSUE_KEYS].filter((key) => available(key) && activeKeys.has(key)).map(section)}
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ </>
+ )}
+ {group(t(($) => $.filters.section_notification), NOTIFICATION_KEYS)}
+ {group(t(($) => $.filters.section_issue), ISSUE_KEYS)}
+ {activeCount > 0 && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => store.clearFilters(wsId)}>
+ <RotateCcw className="size-3.5" />
+ {tIssues(($) => $.filters.reset)}
+ </DropdownMenuItem>
+ </>
+ )}
+ </>
+ );
+
const triggerLabel =
activeCount > 0
? t(($) => $.filters.active_count, { count: activeCount })
: t(($) => $.filters.tooltip);
return (
- <DropdownMenu open={open} onOpenChange={setOpen}>
+ <DropdownMenu
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next);
+ setActiveAtOpen(next ? new Set(activeInboxFilterKeys(effectiveFilters)) : null);
+ if (!next) setSearch("");
+ }}
+ >
<DropdownMenuTrigger
render={
<IconButton
@@ -228,164 +621,32 @@ export function InboxFilterMenu({
<span className="text-caption tabular-nums">{activeCount}</span>
)}
</DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-auto min-w-44">
- {archived && facetsQuery.isLoading && <p role="status" className="px-2 py-1 text-caption text-muted-foreground">{t(($) => $.list.loading_more)}</p>}
- {archived && facetsQuery.isError && <div className="px-2 py-1">
- <p role="alert" className="text-caption text-destructive">{t(($) => $.errors.filters_load_failed)}</p>
- <Button variant="ghost" size="sm" onClick={() => { void facetsQuery.refetch(); }}>{t(($) => $.list.retry)}</Button>
- </div>}
- <DropdownMenuCheckboxItem
- checked={effectiveFilters.unreadOnly}
- onCheckedChange={() => toggleUnreadOnly(wsId)}
- >
- <Mail className="size-3.5" />
- <span className="flex-1">{t(($) => $.filters.unread_only)}</span>
- {unreadCount > 0 && (
- <span className="text-caption text-muted-foreground">
- {t(($) => $.filters.notification_count, { count: unreadCount })}
- </span>
+ <DropdownMenuContent align="end" className="w-auto min-w-64 p-0">
+ <div data-filter-search className="flex items-center gap-1.5 border-b border-foreground/5 px-2.5 py-2">
+ <Search className="size-3.5 shrink-0 text-muted-foreground" />
+ <input
+ type="text"
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ onKeyDown={stopMenuSearchKeys}
+ placeholder={tIssues(($) => $.filters.search_placeholder)}
+ aria-label={tIssues(($) => $.filters.search_placeholder)}
+ className="w-full bg-transparent text-body outline-none placeholder:text-muted-foreground"
+ autoFocus
+ />
+ </div>
+ <div className="max-h-[min(70vh,36rem)] overflow-x-hidden overflow-y-auto p-1">
+ {archived && facetsQuery.isLoading && (
+ <p role="status" className="px-2 py-1 text-caption text-muted-foreground">{t(($) => $.list.loading_more)}</p>
)}
- </DropdownMenuCheckboxItem>
- {/* The archive is filtered server-side, which has no idle dimension. */}
- {!archived && (
- <DropdownMenuCheckboxItem
- checked={effectiveFilters.idleOnly}
- onCheckedChange={() => toggleIdleOnly(wsId)}
- >
- <BotOff className="size-3.5" />
- <span className="flex-1">{t(($) => $.filters.no_agents_working)}</span>
- </DropdownMenuCheckboxItem>
- )}
- <DropdownMenuSeparator />
-
- {actorOptions.length > 0 && (
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <UserRound className="size-3.5" />
- <span className="flex-1">{t(($) => $.filters.from)}</span>
- {effectiveFilters.actors.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {effectiveFilters.actors.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-auto min-w-48">
- {actorOptions.map((option) => {
- const checked = effectiveFilters.actors.includes(option.key);
- const count = actors.get(option.key) ?? 0;
- return (
- <DropdownMenuCheckboxItem
- key={option.key}
- checked={checked}
- onCheckedChange={() => toggleActor(wsId, option.key)}
- >
- <ActorAvatar
- size="xs"
- name={option.name}
- initials={getActorInitials(option.type, option.id)}
- avatarUrl={getActorAvatarUrl(option.type, option.id)}
- isAgent={option.type === "agent"}
- isSquad={option.type === "squad"}
- isSystem={option.type === "system"}
- />
- <span className="flex-1">{option.name}</span>
- {count > 0 && (
- <span className="text-caption text-muted-foreground">
- {t(($) => $.filters.notification_count, { count })}
- </span>
- )}
- </DropdownMenuCheckboxItem>
- );
- })}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- )}
-
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <CircleDot className="size-3.5" />
- <span className="flex-1">{t(($) => $.filters.status)}</span>
- {effectiveFilters.statuses.length > 0 && (
- <span className="text-caption font-medium text-primary">
- {effectiveFilters.statuses.length}
- </span>
- )}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-auto min-w-48">
- {statusOptions.map((option) => {
- const checked = effectiveFilters.statuses.includes(option.key);
- const count = statuses.get(option.key) ?? 0;
- return (
- <DropdownMenuCheckboxItem
- key={option.key}
- checked={checked}
- onCheckedChange={() => toggleStatus(wsId, option.key)}
- >
- <StatusIcon
- status={option.key}
- category={option.category}
- color={option.color}
- icon={option.icon}
- className="size-3.5"
- />
- <span className="flex-1">{option.label}</span>
- {count > 0 && (
- <span className="text-caption text-muted-foreground">
- {t(($) => $.filters.notification_count, { count })}
- </span>
- )}
- </DropdownMenuCheckboxItem>
- );
- })}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
-
- {priorityFilteringSupported ? (
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <SignalHigh className="size-3.5" />
- <span className="flex-1">{t(($) => $.filters.priority)}</span>
- {effectiveFilters.priorities.length > 0 ? (
- <span className="text-caption font-medium text-primary">
- {effectiveFilters.priorities.length}
- </span>
- ) : null}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent className="w-auto min-w-44">
- {PRIORITY_DISPLAY_ORDER.map((priority) => {
- const checked = effectiveFilters.priorities.includes(priority);
- const count = priorities.get(priority) ?? 0;
- return (
- <DropdownMenuCheckboxItem
- key={priority}
- checked={checked}
- onCheckedChange={() => togglePriority(wsId, priority)}
- >
- <PriorityIcon priority={priority} />
- <span className="flex-1">
- {tIssues(($) => $.priority[priority])}
- </span>
- {count > 0 ? (
- <span className="text-caption text-muted-foreground">
- {t(($) => $.filters.notification_count, { count })}
- </span>
- ) : null}
- </DropdownMenuCheckboxItem>
- );
- })}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- ) : null}
-
- {activeCount > 0 && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem onClick={() => clearFilters(wsId)}>
- <RotateCcw className="size-3.5" />
- {t(($) => $.filters.clear)}
- </DropdownMenuItem>
- </>
- )}
+ {archived && facetsQuery.isError && (
+ <div className="px-2 py-1">
+ <p role="alert" className="text-caption text-destructive">{t(($) => $.errors.filters_load_failed)}</p>
+ <Button variant="ghost" size="sm" onClick={() => { void facetsQuery.refetch(); }}>{t(($) => $.list.retry)}</Button>
+ </div>
+ )}
+ {menuBody}
+ </div>
</DropdownMenuContent>
</DropdownMenu>
);
diff --git a/packages/views/inbox/components/inbox-filter-options.tsx b/packages/views/inbox/components/inbox-filter-options.tsx
new file mode 100644
index 0000000000..77637a9e31
--- /dev/null
+++ b/packages/views/inbox/components/inbox-filter-options.tsx
@@ -0,0 +1,213 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import {
+ Activity,
+ AtSign,
+ Bell,
+ Bot,
+ BotOff,
+ CalendarClock,
+ CircleDot,
+ Clock,
+ Eye,
+ FolderKanban,
+ MessageSquare,
+ PencilLine,
+ Settings,
+ SignalHigh,
+ Tag,
+ User,
+ UserPlus,
+ UserRound,
+ X,
+ type IconComponent,
+} from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import { FILTER_NONE_VALUE } from "@multica/core/issues/stores/filter-tree";
+import {
+ activeInboxFilterKeys,
+ inboxActorKeyParts,
+ useInboxFilterStore,
+ type InboxAgentFilter,
+ type InboxFilterKey,
+ type InboxFilters,
+ type InboxReceivedFilter,
+ type InboxTypeGroup,
+} from "@multica/core/inbox/filter-store";
+import { useActorName } from "@multica/core/workspace/hooks";
+import { projectListOptions } from "@multica/core/projects/queries";
+import { labelListOptions } from "@multica/core/labels/queries";
+import { ChipSpan, summarize, type FilterChip } from "../../issues/components/filter-chips-bar";
+import { DUE_DATE_LABEL_KEY } from "../../issues/components/filter-field-options";
+import { useStatusOptions } from "../../issues/utils/status-options";
+import { useT } from "../../i18n";
+
+export const INBOX_FILTER_ICONS: Record<InboxFilterKey, IconComponent> = {
+ unread: Eye,
+ type: Bell,
+ actor: UserRound,
+ received: Clock,
+ status: CircleDot,
+ priority: SignalHigh,
+ agent: Bot,
+ project: FolderKanban,
+ assignee: User,
+ label: Tag,
+ dueDate: CalendarClock,
+};
+
+export const INBOX_TYPE_ICONS: Record<InboxTypeGroup, IconComponent> = {
+ mention: AtSign,
+ comment: MessageSquare,
+ assign: UserPlus,
+ review: Eye,
+ change: PencilLine,
+ run: Bot,
+ system: Settings,
+};
+
+export const INBOX_AGENT_ICONS: Record<InboxAgentFilter, IconComponent> = {
+ running: Activity,
+ idle: BotOff,
+};
+
+/** Display names for every dimension and the values that have no directory. */
+export function useInboxFilterLabels() {
+ const { t } = useT("inbox");
+ const { t: tIssues } = useT("issues");
+ const dimension: Record<InboxFilterKey, string> = {
+ unread: tIssues(($) => $.filters.section_read_state),
+ type: t(($) => $.filters.type),
+ actor: t(($) => $.filters.from),
+ received: t(($) => $.filters.received),
+ status: tIssues(($) => $.filters.section_status),
+ priority: tIssues(($) => $.filters.section_priority),
+ agent: tIssues(($) => $.filters.section_agent_status),
+ project: tIssues(($) => $.filters.section_project),
+ assignee: tIssues(($) => $.filters.section_assignee),
+ label: tIssues(($) => $.filters.section_label),
+ dueDate: tIssues(($) => $.filters.section_due_date),
+ };
+ const type: Record<InboxTypeGroup, string> = {
+ mention: t(($) => $.filters.type_mention),
+ comment: t(($) => $.filters.type_comment),
+ assign: t(($) => $.filters.type_assign),
+ review: t(($) => $.filters.type_review),
+ change: t(($) => $.filters.type_change),
+ run: t(($) => $.filters.type_run),
+ system: t(($) => $.filters.type_system),
+ };
+ const received: Record<InboxReceivedFilter, string> = {
+ today: t(($) => $.filters.received_today),
+ last_7_days: t(($) => $.filters.received_last_7_days),
+ last_30_days: t(($) => $.filters.received_last_30_days),
+ };
+ const agent: Record<InboxAgentFilter, string> = {
+ running: tIssues(($) => $.filters.agent_status_running),
+ idle: t(($) => $.filters.agent_idle),
+ };
+ return {
+ dimension,
+ type,
+ received,
+ agent,
+ unread: tIssues(($) => $.filters.read_state_unread),
+ noProject: tIssues(($) => $.filters.no_project),
+ noAssignee: tIssues(($) => $.filters.no_assignee),
+ dueDate: (bucket: keyof typeof DUE_DATE_LABEL_KEY) => tIssues(($) => $.filters[DUE_DATE_LABEL_KEY[bucket]]),
+ };
+}
+
+const CHIP_ICON_CLASS = "size-3 shrink-0 text-muted-foreground";
+
+/** One chip per active dimension, in menu order; each clears its dimension. */
+export function useInboxFilterChips(wsId: string, filters: InboxFilters): FilterChip[] {
+ const labels = useInboxFilterLabels();
+ const clearFilter = useInboxFilterStore((state) => state.clearFilter);
+ const { getActorName } = useActorName();
+ const statusOptions = useStatusOptions(wsId, filters.statuses);
+ const { t: tIssues } = useT("issues");
+ const keys = activeInboxFilterKeys(filters);
+ const { data: projects = [] } = useQuery({ ...projectListOptions(wsId), enabled: keys.includes("project") });
+ const { data: workspaceLabels = [] } = useQuery({ ...labelListOptions(wsId), enabled: keys.includes("label") });
+
+ const actorName = (key: string) => {
+ if (key === FILTER_NONE_VALUE) return labels.noAssignee;
+ const { type, id } = inboxActorKeyParts(key);
+ return getActorName(type, id);
+ };
+ const values = (key: InboxFilterKey): string[] => {
+ switch (key) {
+ case "unread":
+ return [labels.unread];
+ case "type":
+ return filters.types.map((type) => labels.type[type]);
+ case "actor":
+ return filters.actors.map(actorName);
+ case "received":
+ return filters.received ? [labels.received[filters.received]] : [];
+ case "status":
+ return filters.statuses.map(
+ (status) => statusOptions.find((option) => option.key === status)?.label ?? status,
+ );
+ case "priority":
+ return filters.priorities.map((priority) => tIssues(($) => $.priority[priority]));
+ case "agent":
+ return filters.agent ? [labels.agent[filters.agent]] : [];
+ case "project":
+ return filters.projects.map((id) =>
+ id === FILTER_NONE_VALUE ? labels.noProject : projects.find((p) => p.id === id)?.title ?? "",
+ );
+ case "assignee":
+ return filters.assignees.map(actorName);
+ case "label":
+ return filters.labels.map((id) => workspaceLabels.find((l) => l.id === id)?.name ?? "");
+ case "dueDate":
+ return filters.dueDates.map(labels.dueDate);
+ }
+ };
+
+ return keys.map((key) => {
+ const Icon = INBOX_FILTER_ICONS[key];
+ return {
+ key,
+ icon: <Icon className={CHIP_ICON_CLASS} />,
+ label: labels.dimension[key],
+ value: summarize(values(key)),
+ negated: filters.negated.includes(key as never),
+ onRemove: () => clearFilter(wsId, key),
+ };
+ });
+}
+
+/**
+ * The active filters under the list header, compact enough for the list
+ * column: icon and value only, the field name on hover.
+ */
+export function InboxFilterChipsBar({ wsId, filters }: { wsId: string; filters: InboxFilters }) {
+ const { t } = useT("inbox");
+ const chips = useInboxFilterChips(wsId, filters);
+ const clearFilters = useInboxFilterStore((state) => state.clearFilters);
+ if (chips.length === 0) return null;
+ return (
+ <div
+ data-testid="inbox-filter-chips"
+ className="mx-3 mb-2 flex shrink-0 flex-wrap items-center gap-1.5 rounded-lg bg-muted/50 px-1.5 py-1.5"
+ >
+ {chips.map((chip) => (
+ <ChipSpan key={chip.key} chip={chip} compact />
+ ))}
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label={t(($) => $.filters.clear)}
+ title={t(($) => $.filters.clear)}
+ className="ml-auto text-muted-foreground"
+ onClick={() => clearFilters(wsId)}
+ >
+ <X className="size-3" />
+ </Button>
+ </div>
+ );
+}
diff --git a/packages/views/inbox/components/inbox-page-query.test.tsx b/packages/views/inbox/components/inbox-page-query.test.tsx
index a0fd4e288e..3e6db23784 100644
--- a/packages/views/inbox/components/inbox-page-query.test.tsx
+++ b/packages/views/inbox/components/inbox-page-query.test.tsx
@@ -4,7 +4,7 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { setApiInstance } from "@multica/core/api";
import type { ApiClient } from "@multica/core/api/client";
-import { useInboxFilterStore, type InboxFilters } from "@multica/core/inbox/filter-store";
+import { EMPTY_INBOX_FILTERS, filterInboxItems, useInboxFilterStore, type InboxFilters } from "@multica/core/inbox/filter-store";
import { archivedInboxLookupOptions, inboxKeys } from "@multica/core/inbox/queries";
import { onInboxIssueDeleted, patchInboxIssueProjection } from "@multica/core/inbox/ws-updaters";
import type { ArchivedInboxPage } from "@multica/core/types/inbox";
@@ -204,6 +204,51 @@ it.each(["click", "url"])("keeps the archived row and detail mounted through ref
expect(screen.queryByText("inbox-a")).not.toBeInTheDocument();
});
+it("keeps an older archived notification open through auto-read when the lookup carries its type filter", async () => {
+ searchParams = new URLSearchParams("view=archived");
+ useInboxFilterStore.getState().toggleFilterValue("workspace-1", "type", "mention");
+ const gate = deferred<void>();
+ let rows = [
+ item({ id: "newer-change", type: "status_changed", archived: true, read: false, issue_label_ids: [] }),
+ item({ id: "older-mention", type: "mentioned", archived: true, issue_label_ids: [], created_at: "2026-06-15T07:00:00Z" }),
+ ];
+ const listArchivedInboxPage = vi.fn(async (filters: InboxFilters) =>
+ page(filterInboxItems(rows, { ...EMPTY_INBOX_FILTERS, ...filters })));
+ const markInboxRead = vi.fn(async (id: string) => {
+ rows = rows.map((row) => row.id === id ? { ...row, read: true } : row);
+ await gate.promise;
+ return rows.find((row) => row.id === id)!;
+ });
+ setApiInstance({ listArchivedInboxPage, markInboxRead, getInboxUnreadSummary: async () => [] } as unknown as ApiClient);
+ renderPage();
+ fireEvent.click(await screen.findByText("older-mention"));
+ expect(await screen.findByTestId("detail")).toHaveTextContent("issue-a");
+ await waitFor(() => expect(markInboxRead).toHaveBeenCalledWith("older-mention"));
+ await act(async () => gate.resolve());
+ await waitFor(() => expect(listArchivedInboxPage.mock.calls.length).toBeGreaterThanOrEqual(3));
+ await waitFor(() => expect(qc.isFetching()).toBe(0));
+ expect(replace).not.toHaveBeenCalledWith("/acme/inbox?view=archived");
+ expect(screen.getByTestId("detail")).toHaveTextContent("issue-a");
+});
+
+it("asks the lookup with the view's filters except unread, and clears a filtered-out deep link instead of redirecting", async () => {
+ searchParams = new URLSearchParams("view=archived&issue=issue-a");
+ useInboxFilterStore.getState().toggleFilterValue("workspace-1", "type", "mention");
+ const rows = [item({ id: "comment-only", archived: true, issue_label_ids: [] })];
+ const listArchivedInboxPage = vi.fn(async (filters: InboxFilters, options: { groupId?: string }) => {
+ const matches = filterInboxItems(rows, { ...EMPTY_INBOX_FILTERS, ...filters });
+ return page(options.groupId ? matches.filter((row) => row.issue_id === options.groupId) : matches);
+ });
+ setApiInstance({ listArchivedInboxPage, getInboxUnreadSummary: async () => [] } as unknown as ApiClient);
+ renderPage();
+
+ await waitFor(() => expect(replace).toHaveBeenLastCalledWith("/acme/inbox?view=archived"));
+ const lookups = listArchivedInboxPage.mock.calls.filter(([, options]) => options.groupId === "issue-a");
+ expect(lookups[0]![0]).toMatchObject({ types: ["mention"], unreadOnly: false });
+ expect(lookups.at(-1)![0]).toMatchObject({ types: [], unreadOnly: false });
+ expect(replace).not.toHaveBeenCalledWith(expect.stringContaining("/issues/"));
+});
+
it("keeps reading through lookup failure and clears a confirmed missing notification", async () => {
const fixture = archivedFixture();
const detail = await openArchived(fixture);
diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsx
index e1b3c4c754..a2349f114c 100644
--- a/packages/views/inbox/components/inbox-page.test.tsx
+++ b/packages/views/inbox/components/inbox-page.test.tsx
@@ -183,6 +183,11 @@ vi.mock("./inbox-filter-menu", () => ({
InboxFilterMenu: () => <button type="button">Filter inbox</button>,
}));
vi.mock("./inbox-list-item", () => ({ useTimeAgo: () => vi.fn() }));
+vi.mock("./inbox-filter-options", () => ({
+ InboxFilterChipsBar: ({ filters }: { filters: { types: string[]; agent: string | null } }) => (
+ <div data-testid="filter-chips" data-types={filters.types.join(",")} data-agent={filters.agent ?? ""} />
+ ),
+}));
// Capture the row actions the page hands the context menu, so the read/unread
// handlers can be driven without standing up Base UI's menu.
@@ -287,7 +292,7 @@ describe("InboxPage", () => {
rerender(<InboxPage />);
expect(screen.getByTestId("row")).toHaveTextContent("busy-row");
- act(() => useInboxFilterStore.getState().toggleIdleOnly("workspace-1"));
+ act(() => useInboxFilterStore.getState().setAgent("workspace-1", "idle"));
expect(screen.queryByTestId("row")).toBeNull();
});
@@ -296,7 +301,7 @@ describe("InboxPage", () => {
reset();
layout.width = DESKTOP;
listData.active = [item({ id: "read-row", issue_id: "idle-issue", read: true })];
- useInboxFilterStore.getState().toggleIdleOnly("workspace-1");
+ useInboxFilterStore.getState().setAgent("workspace-1", "idle");
render(<InboxPage />);
fireEvent.click(screen.getByTestId("row"));
@@ -309,15 +314,15 @@ describe("InboxPage", () => {
reset();
layout.width = DESKTOP;
listData.active = [item({ id: "was-idle", issue_id: "issue-a", read: true })];
- useInboxFilterStore.getState().toggleIdleOnly("workspace-1");
+ useInboxFilterStore.getState().setAgent("workspace-1", "idle");
const { rerender } = render(<InboxPage />);
fireEvent.click(screen.getByTestId("row"));
- act(() => useInboxFilterStore.getState().toggleIdleOnly("workspace-1"));
+ act(() => useInboxFilterStore.getState().setAgent("workspace-1", "idle"));
listData.tasks = [{ id: "task-a", agent_id: "agent-1", issue_id: "issue-a", status: "running" }] as AgentTask[];
rerender(<InboxPage />);
expect(screen.getByTestId("row")).toHaveTextContent("was-idle");
- act(() => useInboxFilterStore.getState().toggleIdleOnly("workspace-1"));
+ act(() => useInboxFilterStore.getState().setAgent("workspace-1", "idle"));
expect(screen.queryByTestId("row")).toBeNull();
});
@@ -412,6 +417,38 @@ describe("InboxPage", () => {
expect(screen.getByTestId("row")).toHaveTextContent("from-alice");
});
+ it("matches a type on any notification of an issue and shows the newest match", () => {
+ reset();
+ listData.active = [
+ item({ id: "newest-comment", issue_id: "issue-1", type: "new_comment", created_at: "2026-06-15T09:00:00Z" }),
+ item({ id: "older-mention", issue_id: "issue-1", type: "mentioned", created_at: "2026-06-15T08:00:00Z" }),
+ item({ id: "other-comment", issue_id: "issue-2", type: "new_comment" }),
+ ];
+ useInboxFilterStore.getState().toggleFilterValue("workspace-1", "type", "mention");
+
+ render(<InboxPage />);
+
+ expect(screen.getAllByTestId("row")).toHaveLength(1);
+ expect(screen.getByTestId("row")).toHaveTextContent("older-mention");
+ expect(screen.getByTestId("filter-chips").dataset.types).toBe("mention");
+ });
+
+ it("keeps a type filtered out with is not", () => {
+ reset();
+ listData.active = [
+ item({ id: "mention", issue_id: "issue-1", type: "mentioned" }),
+ item({ id: "comment", issue_id: "issue-2", type: "new_comment" }),
+ ];
+ const filters = useInboxFilterStore.getState();
+ filters.toggleFilterValue("workspace-1", "type", "mention");
+ filters.setFilterNegated("workspace-1", "type", true);
+
+ render(<InboxPage />);
+
+ expect(screen.getAllByTestId("row")).toHaveLength(1);
+ expect(screen.getByTestId("row")).toHaveTextContent("comment");
+ });
+
it("hides issues an agent is running or queued on while the idle filter is on", () => {
reset();
listData.active = [
@@ -425,7 +462,7 @@ describe("InboxPage", () => {
{ id: "task-2", agent_id: "agent-1", issue_id: "issue-2", status: "queued" },
{ id: "task-3", agent_id: "agent-1", issue_id: "issue-3", status: "completed" },
] as AgentTask[];
- useInboxFilterStore.getState().toggleIdleOnly("workspace-1");
+ useInboxFilterStore.getState().setAgent("workspace-1", "idle");
render(<InboxPage />);
@@ -603,11 +640,12 @@ describe("InboxPage", () => {
listData.tasks = [
{ id: "task-1", agent_id: "agent-1", issue_id: "issue-1", status: "running" },
] as AgentTask[];
- useInboxFilterStore.getState().toggleIdleOnly("workspace-1");
+ useInboxFilterStore.getState().setAgent("workspace-1", "idle");
render(<InboxPage />);
expect(screen.getByTestId("row")).toHaveTextContent("archived-busy");
+ expect(screen.getByTestId("filter-chips").dataset.agent).toBe("");
});
it("keeps the archive open when it is empty", () => {
@@ -821,7 +859,7 @@ describe("InboxPage", () => {
item({ id: "inbox-a", issue_id: "issue-a", read: true }),
item({ id: "inbox-b", issue_id: "issue-b", read: true }),
];
- useInboxFilterStore.getState().toggleIdleOnly("workspace-1");
+ useInboxFilterStore.getState().setAgent("workspace-1", "idle");
const { rerender } = render(<InboxPage />);
fireEvent.click(screen.getAllByTestId("row")[0]!);
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index 183dc3cb42..115a59f5c3 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -42,13 +42,15 @@ import {
useRetrySourceContextQuickCreate,
} from "@multica/core/inbox/mutations";
import {
+ effectiveInboxFilters,
filterInboxItems,
- inboxFiltersForArchive,
- inboxFiltersForPrioritySupport,
inboxFilterCount,
+ inboxIssueFieldsSupport,
inboxPriorityFilterSupport,
useInboxFilters,
useInboxFilterStore,
+ type InboxAgentFilter,
+ type InboxFilterSupport,
} from "@multica/core/inbox/filter-store";
import { IssueDetail, issueHighlightMementoKey } from "../../issues/components/issue-detail";
@@ -99,6 +101,7 @@ import { ListColumn } from "../../layout/list-column";
import { useTimeAgo } from "./inbox-list-item";
import { InboxList } from "./inbox-list";
import { InboxFilterMenu } from "./inbox-filter-menu";
+import { InboxFilterChipsBar } from "./inbox-filter-options";
import { InboxContextMenuProvider } from "./inbox-context-menu";
import { ARCHIVED_VIEW_PARAM, type InboxView } from "./inbox-view";
import { useTypeLabels } from "./inbox-detail-label";
@@ -133,11 +136,12 @@ export function InboxPage() {
// so the filter would otherwise drop the row before the detail finishes
// mounting. Scoped to the selection: moving away releases it.
const pinnedUnreadKeyRef = useRef<string | null>(null);
- // The row the user opened under the idle filter. Replying from the detail
- // can start an agent on its issue, which would otherwise drop the row the
- // user is working in. Set once the open row has passed the idle filter, so
- // turning the filter on over a busy row still filters it out.
- const pinnedIdleKeyRef = useRef<string | null>(null);
+ // The row the user opened under the agent filter. Replying from the detail
+ // can start or finish an agent on its issue, which would otherwise drop the
+ // row the user is working in. Set once the open row has passed the agent
+ // filter, so turning the filter on over a non-matching row still filters
+ // it out; it only holds for the agent state it was pinned under.
+ const pinnedAgentRef = useRef<{ key: string; agent: InboxAgentFilter } | null>(null);
// Sync from URL when searchParams change (e.g. navigation)
useEffect(() => {
@@ -155,8 +159,19 @@ export function InboxPage() {
...inboxListOptions(wsId), enabled: !isArchivedView,
});
const items = useMemo(() => deduplicateInboxItems(rawItems), [rawItems]);
+ // The filters read every notification of an issue, not just its newest.
+ const activeRows = useMemo(() => rawItems.filter((item) => !item.archived), [rawItems]);
+ // The archive is filtered by the server, so its capability can only be
+ // proven by the rows those filters return. An empty answer proves nothing
+ // and must not flip what is sent, so only a confirmed older server — rows
+ // without the projection — makes its extra dimensions dormant.
+ const [archiveIssueFields, setArchiveIssueFields] = useState<InboxFilterSupport>("supported");
+ const archiveFilters = useMemo(
+ () => effectiveInboxFilters(filters, { priority: "supported", issueFields: archiveIssueFields, archived: true }),
+ [filters, archiveIssueFields],
+ );
const archiveQuery = useInfiniteQuery({
- ...archivedInboxPagesOptions(wsId, filters), enabled: isArchivedView,
+ ...archivedInboxPagesOptions(wsId, archiveFilters), enabled: isArchivedView,
});
const fetchNextArchivedPage = archiveQuery.fetchNextPage;
const loadNextArchivedPage = useCallback(() => { void fetchNextArchivedPage(); }, [fetchNextArchivedPage]);
@@ -165,48 +180,72 @@ export function InboxPage() {
const archivedItems = useMemo(() => deduplicateArchivedInboxItems(
archiveQuery.data?.pages.flatMap((page) => page.items) ?? [],
), [archiveQuery.data]);
+ if (archiveIssueFields !== "unsupported" && inboxIssueFieldsSupport(archivedItems) === "unsupported") {
+ setArchiveIssueFields("unsupported");
+ }
const viewItems = isArchivedView ? archivedItems : items;
- // The paginated endpoint guarantees the projection, including on empty pages.
+ // The paginated endpoint guarantees the priority projection, including on
+ // empty pages.
const priorityFilterSupport = isArchivedView ? "supported" : inboxPriorityFilterSupport(rawItems);
- const effectiveFilters = useMemo(() => {
- const supported = inboxFiltersForPrioritySupport(filters, priorityFilterSupport);
- return isArchivedView ? inboxFiltersForArchive(supported) : supported;
- }, [filters, priorityFilterSupport, isArchivedView]);
+ const issueFieldsSupport = isArchivedView ? archiveIssueFields : inboxIssueFieldsSupport(rawItems);
+ const activeFilters = useMemo(
+ () => effectiveInboxFilters(filters, { priority: priorityFilterSupport, issueFields: issueFieldsSupport }),
+ [filters, priorityFilterSupport, issueFieldsSupport],
+ );
+ const effectiveFilters = isArchivedView ? archiveFilters : activeFilters;
// "Active" is the same running-or-queued rule the row's activity badge uses.
const { activityByIssueId } = useIssueSurfaceActivity();
const activeIssueIds = useMemo(() => new Set(activityByIssueId.keys()), [activityByIssueId]);
- // Only an idle selection reads the snapshot, so task churn leaves the list
- // alone while it is off.
- const idleFilterIssueIds = effectiveFilters.idleOnly ? activeIssueIds : undefined;
- // The open row survives the unread and idle dimensions while it stays
+ // Only an agent selection reads the snapshot, so task churn leaves the
+ // list alone while it is off.
+ const agentFilterIssueIds = effectiveFilters.agent ? activeIssueIds : undefined;
+ // The open row survives the unread and agent dimensions while it stays
// selected; see the pin refs above. Each pin is passed separately so it
// only crosses its own dimension.
const pinnedUnreadKey =
effectiveFilters.unreadOnly && pinnedUnreadKeyRef.current === selectedKey
? selectedKey
: null;
- const pinnedIdleKey =
- effectiveFilters.idleOnly && pinnedIdleKeyRef.current === selectedKey
+ const pinnedAgentKey =
+ effectiveFilters.agent &&
+ pinnedAgentRef.current?.key === selectedKey &&
+ pinnedAgentRef.current.agent === effectiveFilters.agent
? selectedKey
: null;
- const pinnedKey = pinnedUnreadKey ?? pinnedIdleKey;
+ const pinnedKey = pinnedUnreadKey ?? pinnedAgentKey;
const filterContext = useMemo(
- () => ({ activeIssueIds: idleFilterIssueIds, pinnedUnreadKey, pinnedIdleKey }),
- [idleFilterIssueIds, pinnedUnreadKey, pinnedIdleKey],
+ () => ({ activeIssueIds: agentFilterIssueIds, pinnedUnreadKey, pinnedAgentKey }),
+ [agentFilterIssueIds, pinnedUnreadKey, pinnedAgentKey],
);
+ const filterRows = isArchivedView ? archivedItems : activeRows;
const filteredItems = useMemo(
- () => filterInboxItems(viewItems, effectiveFilters, filterContext),
- [viewItems, effectiveFilters, filterContext],
+ () => filterInboxItems(filterRows, effectiveFilters, filterContext),
+ [filterRows, effectiveFilters, filterContext],
);
const hasActiveFilters = inboxFilterCount(effectiveFilters) > 0;
const selectedOnPage = viewItems.find((i) => (i.issue_id ?? i.id) === selectedKey);
// A deep link can point beyond every loaded page. Resolve its group directly
// without adding it to the cursor chain or mistaking a page miss for a 404.
+ // It asks with the view's filters, so the server answers with the group's
+ // newest MATCHING notification — the row the list showed — rather than its
+ // newest one. Unread is left out: the open row is exempt from it (MUL-8073).
+ const lookupFilters = useMemo(() => ({ ...archiveFilters, unreadOnly: false }), [archiveFilters]);
+ const lookupFiltered = inboxFilterCount(lookupFilters) > 0;
+ const lookupEnabled = isArchivedView && !!selectedKey && !selectedOnPage && !archivedLoading && !archivedError;
const lookup = useQuery({
+ ...archivedInboxLookupOptions(wsId, selectedKey, lookupFilters),
+ enabled: lookupEnabled,
+ });
+ // A filtered lookup that comes back empty cannot tell a filtered-out group
+ // from a missing one. Ask without filters only then, so a filtered-out deep
+ // link clears the selection instead of redirecting to the issue page.
+ const lookupMissed = lookupFiltered && lookup.isSuccess && !lookup.isPlaceholderData && lookup.data.items.length === 0;
+ const presence = useQuery({
...archivedInboxLookupOptions(wsId, selectedKey),
- enabled: isArchivedView && !!selectedKey && !selectedOnPage && !archivedLoading && !archivedError,
+ enabled: lookupEnabled && lookupMissed,
});
const lookupItems = useMemo(() => deduplicateArchivedInboxItems(lookup.data?.items ?? []), [lookup.data]);
+ const presenceItems = lookupMissed ? presence.data?.items ?? [] : [];
const selectionItems = useMemo(() => {
if (!isArchivedView || selectedOnPage) return filteredItems;
return deduplicateArchivedInboxItems([
@@ -227,7 +266,9 @@ export function InboxPage() {
setInboxZeroRises(prevInboxZeroCount > 0 && inboxZeroCount === 0);
}
const selected = selectionItems.find((i) => (i.issue_id ?? i.id) === selectedKey) ?? null;
- const selectedInView = selectedOnPage ?? (isArchivedView ? lookupItems.find((i) => (i.issue_id ?? i.id) === selectedKey) : null);
+ const selectedInView = selectedOnPage ?? (isArchivedView
+ ? [...lookupItems, ...presenceItems].find((i) => (i.issue_id ?? i.id) === selectedKey)
+ : null);
const selectionFilteredOut = !!selectedKey && !!selectedInView && !selected;
// What the DETAIL pane shows, one React transition behind the click.
@@ -297,8 +338,8 @@ export function InboxPage() {
// pending/error states only block resolution of the off-page selection.
const viewLoading = isArchivedView ? archivedLoading : loading;
const needsLookup = isArchivedView && !!selectedKey && !selectedOnPage;
- const lookupLoading = needsLookup && lookup.isLoading;
- const lookupError = needsLookup && lookup.isError && !selected;
+ const lookupLoading = needsLookup && (lookup.isLoading || presence.isLoading);
+ const lookupError = needsLookup && (lookup.isError || presence.isError) && !selected;
// Shared inbox links (?issue=<id>) may point to notifications not in this
// user's inbox (archived, or never received). Fall back to the issue page
@@ -376,7 +417,7 @@ export function InboxPage() {
if (isArchivedView && selected) {
// The unread page drops this group on refetch. Seed its lookup before
// the mutation so cache patches, rollback and deletion apply to it too.
- queryClient.setQueryData(archivedInboxLookupOptions(wsId, selectedKey).queryKey, {
+ queryClient.setQueryData(archivedInboxLookupOptions(wsId, selectedKey, lookupFilters).queryKey, {
items: [selected], hasMore: false, nextCursor: null,
});
}
@@ -389,7 +430,7 @@ export function InboxPage() {
: t(($) => $.errors.mark_read_failed),
),
});
- }, [selectedId, selectedRead, selectedKey, selected, filters.unreadOnly, isArchivedView, queryClient, wsId, markReadMutate, t]);
+ }, [selectedId, selectedRead, selectedKey, selected, filters.unreadOnly, isArchivedView, queryClient, wsId, lookupFilters, markReadMutate, t]);
// Release the guards as soon as the selection moves off their row.
useEffect(() => {
@@ -399,27 +440,27 @@ export function InboxPage() {
if (pinnedUnreadKeyRef.current && pinnedUnreadKeyRef.current !== selectedKey) {
pinnedUnreadKeyRef.current = null;
}
- if (pinnedIdleKeyRef.current && pinnedIdleKeyRef.current !== selectedKey) {
- pinnedIdleKeyRef.current = null;
+ if (pinnedAgentRef.current && pinnedAgentRef.current.key !== selectedKey) {
+ pinnedAgentRef.current = null;
}
}, [selectedId, selectedKey]);
// `selected` only exists once the open row passed every filter, so under
- // the idle filter this pins a row that was idle when the user opened it.
- const idleOnlyActive = effectiveFilters.idleOnly;
+ // the agent filter this pins a row that matched when the user opened it.
+ const agentFilter = effectiveFilters.agent;
const unreadOnlyActive = effectiveFilters.unreadOnly;
const hasSelected = selected != null;
useEffect(() => {
- if (idleOnlyActive && hasSelected && selectedKey) {
- pinnedIdleKeyRef.current = selectedKey;
+ if (agentFilter && hasSelected && selectedKey) {
+ pinnedAgentRef.current = { key: selectedKey, agent: agentFilter };
}
- }, [idleOnlyActive, hasSelected, selectedKey]);
+ }, [agentFilter, hasSelected, selectedKey]);
// Turning a filter off releases its pin, so turning it back on judges the
// open row by its current state instead of an exemption from earlier.
useEffect(() => {
- if (!idleOnlyActive) pinnedIdleKeyRef.current = null;
- }, [idleOnlyActive]);
+ if (!agentFilter) pinnedAgentRef.current = null;
+ }, [agentFilter]);
useEffect(() => {
if (!unreadOnlyActive) pinnedUnreadKeyRef.current = null;
}, [unreadOnlyActive]);
@@ -674,8 +715,9 @@ export function InboxPage() {
>
<InboxFilterMenu
wsId={wsId}
- items={viewItems}
+ items={filterRows}
priorityFilterSupport={priorityFilterSupport}
+ issueFieldsSupport={issueFieldsSupport}
activeIssueIds={activeIssueIds}
archived={isArchivedView}
/>
@@ -770,6 +812,7 @@ export function InboxPage() {
const listPanel = (
<>
{listHeader}
+ <InboxFilterChipsBar wsId={wsId} filters={effectiveFilters} />
{lookupLoading && (
<p role="status" className="shrink-0 border-b px-3 py-2 text-caption text-muted-foreground">
{t(($) => $.list.loading_selection)}
@@ -780,7 +823,7 @@ export function InboxPage() {
<p className="flex-1 text-caption text-muted-foreground">
{t(($) => $.errors.archived_lookup_failed)}
</p>
- <Button variant="outline" size="sm" disabled={lookup.isFetching} onClick={() => void lookup.refetch()}>
+ <Button variant="outline" size="sm" disabled={lookup.isFetching || presence.isFetching} onClick={() => void (lookup.isError ? lookup.refetch() : presence.refetch())}>
{t(($) => $.list.retry)}
</Button>
</div>
diff --git a/packages/views/issues/components/filter-chips-bar.tsx b/packages/views/issues/components/filter-chips-bar.tsx
index ba6256addb..981fc19113 100644
--- a/packages/views/issues/components/filter-chips-bar.tsx
+++ b/packages/views/issues/components/filter-chips-bar.tsx
@@ -683,18 +683,32 @@ export function useFilterChips(
return { chips, hasAny: chips.length > 0, clearAll };
}
-export function ChipSpan({ chip, className }: { chip: FilterChip; className?: string }) {
+export function ChipSpan({
+ chip,
+ className,
+ compact = false,
+}: {
+ chip: FilterChip;
+ className?: string;
+ /** Icon and value only, for narrow columns; the field name moves to the
+ * hover title. */
+ compact?: boolean;
+}) {
const { t } = useT("issues");
const removeLabel = t(($) => $.filters.chip_remove, { name: chip.label });
+ const operator = chip.negated ? t(($) => $.filters.operator_is_not) : t(($) => $.filters.operator_is);
return (
// Keyed per dimension: the chip animates in once when its dimension
// first gains a value; value changes inside it re-render without
// re-animating. No exit animation — unmount presence isn't worth the
// machinery for a 150ms nicety.
- <span className={cn("flex h-6 max-w-72 shrink-0 items-center gap-1.5 rounded-md bg-background pl-2 pr-1 text-caption shadow-xs animate-in fade-in-0 zoom-in-95 duration-150", className)}>
+ <span
+ title={compact ? `${chip.label} ${operator} ${chip.value}` : undefined}
+ className={cn("flex h-6 max-w-72 shrink-0 items-center gap-1.5 rounded-md bg-background pl-2 pr-1 text-caption shadow-xs animate-in fade-in-0 zoom-in-95 duration-150", compact && "min-w-0 max-w-full shrink", className)}
+ >
<span className="flex shrink-0 items-center gap-1 text-muted-foreground">
{chip.icon}
- <span>{chip.label}</span>
+ {!compact && <span>{chip.label}</span>}
</span>
<span className="flex min-w-0 items-center gap-1">
{chip.negated && <FilterOperator negated />}
diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsx
index 01d1d6bcef..6340679d5a 100644
--- a/packages/views/issues/components/issues-header.tsx
+++ b/packages/views/issues/components/issues-header.tsx
@@ -343,7 +343,7 @@ function useIssueCounts(
// Actor sub-menu content (shared between Assignee and Creator)
-function ActorSubContent({
+export function ActorSubContent({
counts,
selected,
onToggle,
@@ -528,7 +528,7 @@ function ActorSubContent({
// Project sub-menu content
-function ProjectSubContent({
+export function ProjectSubContent({
counts,
selected,
onToggle,
@@ -667,7 +667,7 @@ function ProjectStatusSubContent({
// Label sub-menu content
-function LabelSubContent({
+export function LabelSubContent({
counts,
selected,
onToggle,
@@ -911,16 +911,20 @@ const OPERATOR_SEGMENT_CLASS =
/** "Is" / "is not" for one dimension, heading its submenu. Radio items keep
* it in the menu's keyboard order; the selection below is left as it is. */
-function FilterOperatorSwitch({ dimension }: { dimension: NegatableFilterDimension }) {
+export function FilterOperatorToggle({
+ negated,
+ onNegatedChange,
+}: {
+ negated: boolean;
+ onNegatedChange: (negated: boolean) => void;
+}) {
const { t } = useT("issues");
- const negated = useViewStore((s) => s.negatedFilters.includes(dimension));
- const setFilterNegated = useViewStore((s) => s.setFilterNegated);
return (
<>
<DropdownMenuRadioGroup
aria-label={t(($) => $.filters.operator_label)}
value={negated ? "is_not" : "is"}
- onValueChange={(value) => setFilterNegated(dimension, value === "is_not")}
+ onValueChange={(value) => onNegatedChange(value === "is_not")}
className="m-1 flex gap-0.5 rounded-lg bg-muted p-0.5"
>
<DropdownMenuRadioItem value="is" closeOnClick={false} className={OPERATOR_SEGMENT_CLASS}>
@@ -935,6 +939,17 @@ function FilterOperatorSwitch({ dimension }: { dimension: NegatableFilterDimensi
);
}
+function FilterOperatorSwitch({ dimension }: { dimension: NegatableFilterDimension }) {
+ const negated = useViewStore((s) => s.negatedFilters.includes(dimension));
+ const setFilterNegated = useViewStore((s) => s.setFilterNegated);
+ return (
+ <FilterOperatorToggle
+ negated={negated}
+ onNegatedChange={(next) => setFilterNegated(dimension, next)}
+ />
+ );
+}
+
const RELATION_ICONS: Record<IssueRelationFilter, typeof User> = {
assigned: CircleUser,
created: UserPen,
diff --git a/packages/views/layout/panels/list-space-peeks.tsx b/packages/views/layout/panels/list-space-peeks.tsx
index 6bf6512f98..65834a37d1 100644
--- a/packages/views/layout/panels/list-space-peeks.tsx
+++ b/packages/views/layout/panels/list-space-peeks.tsx
@@ -7,14 +7,14 @@ import { useSetChatSessionArchived } from "@multica/core/chat/mutations";
import { chatSessionsOptions } from "@multica/core/chat/queries";
import { useWorkspaceId } from "@multica/core/hooks";
import {
+ effectiveInboxFilters,
filterInboxItems,
- inboxFiltersForPrioritySupport,
+ inboxIssueFieldsSupport,
inboxPriorityFilterSupport,
useInboxFilters,
} from "@multica/core/inbox/filter-store";
import { useArchiveInbox } from "@multica/core/inbox/mutations";
import {
- deduplicateInboxItems,
inboxListOptions,
useInboxUnreadCount,
} from "@multica/core/inbox/queries";
@@ -48,9 +48,12 @@ export function InboxPeek() {
const archive = useArchiveInbox();
const items = useMemo(() => {
- const effective = inboxFiltersForPrioritySupport(filters, inboxPriorityFilterSupport(rawItems));
- return filterInboxItems(deduplicateInboxItems(rawItems), effective, {
- activeIssueIds: effective.idleOnly ? new Set(activityByIssueId.keys()) : undefined,
+ const effective = effectiveInboxFilters(filters, {
+ priority: inboxPriorityFilterSupport(rawItems),
+ issueFields: inboxIssueFieldsSupport(rawItems),
+ });
+ return filterInboxItems(rawItems.filter((item) => !item.archived), effective, {
+ activeIssueIds: effective.agent ? new Set(activityByIssueId.keys()) : undefined,
});
}, [rawItems, filters, activityByIssueId]);
diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.json
index ceb7c6ac9d..7c8fa9058a 100644
--- a/packages/views/locales/en/inbox.json
+++ b/packages/views/locales/en/inbox.json
@@ -16,12 +16,25 @@
"status": "Status",
"priority": "Priority",
"from": "From",
- "unread_only": "Unread only",
- "no_agents_working": "No agents working",
"notification_count_one": "{{count}} notification",
"notification_count_other": "{{count}} notifications",
"clear": "Clear filters",
- "empty": "No notifications match your filters"
+ "empty": "No notifications match your filters",
+ "section_notification": "Notification",
+ "section_issue": "Issue",
+ "type": "Type",
+ "received": "Received",
+ "type_mention": "Mentions",
+ "type_comment": "Comments & reactions",
+ "type_assign": "Assignments & subscriptions",
+ "type_review": "Review requests",
+ "type_change": "Issue changes",
+ "type_run": "Agent runs",
+ "type_system": "System",
+ "received_today": "Today",
+ "received_last_7_days": "Last 7 days",
+ "received_last_30_days": "Last 30 days",
+ "agent_idle": "Idle"
},
"context_menu": {
"mark_read": "Mark as read",
diff --git a/packages/views/locales/es/inbox.json b/packages/views/locales/es/inbox.json
index 157873decc..6e5fb86903 100644
--- a/packages/views/locales/es/inbox.json
+++ b/packages/views/locales/es/inbox.json
@@ -16,12 +16,25 @@
"status": "Estado",
"priority": "Prioridad",
"from": "De",
- "unread_only": "Solo no leídos",
"notification_count_one": "{{count}} notificación",
"notification_count_other": "{{count}} notificaciones",
"clear": "Limpiar filtros",
"empty": "Ninguna notificación coincide con tus filtros",
- "no_agents_working": "No hay agentes trabajando"
+ "section_notification": "Notificación",
+ "section_issue": "Tarea",
+ "type": "Tipo",
+ "received": "Recibido",
+ "type_mention": "Menciones",
+ "type_comment": "Comentarios y reacciones",
+ "type_assign": "Asignaciones y suscripciones",
+ "type_review": "Solicitudes de revisión",
+ "type_change": "Cambios en la tarea",
+ "type_run": "Ejecuciones de agentes",
+ "type_system": "Sistema",
+ "received_today": "Hoy",
+ "received_last_7_days": "Últimos 7 días",
+ "received_last_30_days": "Últimos 30 días",
+ "agent_idle": "Inactivo"
},
"context_menu": {
"mark_read": "Marcar como leído",
diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.json
index 5d48ee2d52..5ea8b34bcd 100644
--- a/packages/views/locales/fr/inbox.json
+++ b/packages/views/locales/fr/inbox.json
@@ -16,12 +16,25 @@
"status": "Statut",
"priority": "Priorité",
"from": "De",
- "unread_only": "Non lues uniquement",
- "no_agents_working": "Aucun agent au travail",
"notification_count_one": "{{count}} notification",
"notification_count_other": "{{count}} notifications",
"clear": "Effacer les filtres",
- "empty": "Aucune notification ne correspond à vos filtres"
+ "empty": "Aucune notification ne correspond à vos filtres",
+ "section_notification": "Notification",
+ "section_issue": "Tâche",
+ "type": "Type",
+ "received": "Reçue",
+ "type_mention": "Mentions",
+ "type_comment": "Commentaires et réactions",
+ "type_assign": "Assignations et abonnements",
+ "type_review": "Demandes de relecture",
+ "type_change": "Modifications de la tâche",
+ "type_run": "Exécutions d'agents",
+ "type_system": "Système",
+ "received_today": "Aujourd'hui",
+ "received_last_7_days": "7 derniers jours",
+ "received_last_30_days": "30 derniers jours",
+ "agent_idle": "Inactif"
},
"context_menu": {
"mark_read": "Marquer comme lu",
diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.json
index 5b154dd71e..130e728156 100644
--- a/packages/views/locales/ja/inbox.json
+++ b/packages/views/locales/ja/inbox.json
@@ -15,11 +15,24 @@
"status": "ステータス",
"priority": "優先度",
"from": "送信者",
- "unread_only": "未読のみ",
- "no_agents_working": "作業中のエージェントなし",
"notification_count_other": "{{count}} 件の通知",
"clear": "フィルターをクリア",
- "empty": "フィルターに一致する通知はありません"
+ "empty": "フィルターに一致する通知はありません",
+ "section_notification": "通知",
+ "section_issue": "タスク",
+ "type": "通知の種類",
+ "received": "受信日時",
+ "type_mention": "メンション",
+ "type_comment": "コメントとリアクション",
+ "type_assign": "割り当てと購読",
+ "type_review": "レビュー依頼",
+ "type_change": "タスクの変更",
+ "type_run": "エージェントの実行",
+ "type_system": "システム",
+ "received_today": "今日",
+ "received_last_7_days": "過去 7 日間",
+ "received_last_30_days": "過去 30 日間",
+ "agent_idle": "待機中"
},
"context_menu": {
"mark_read": "既読にする",
diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.json
index dc66eb8d09..216087905c 100644
--- a/packages/views/locales/ko/inbox.json
+++ b/packages/views/locales/ko/inbox.json
@@ -15,11 +15,24 @@
"status": "상태",
"priority": "우선순위",
"from": "보낸 사람",
- "unread_only": "읽지 않음만",
- "no_agents_working": "작업 중인 에이전트 없음",
"notification_count_other": "알림 {{count}}개",
"clear": "필터 지우기",
- "empty": "필터와 일치하는 알림이 없습니다"
+ "empty": "필터와 일치하는 알림이 없습니다",
+ "section_notification": "알림",
+ "section_issue": "태스크",
+ "type": "알림 유형",
+ "received": "받은 시간",
+ "type_mention": "멘션",
+ "type_comment": "댓글 및 반응",
+ "type_assign": "할당 및 구독",
+ "type_review": "리뷰 요청",
+ "type_change": "태스크 변경",
+ "type_run": "에이전트 실행",
+ "type_system": "시스템",
+ "received_today": "오늘",
+ "received_last_7_days": "최근 7일",
+ "received_last_30_days": "최근 30일",
+ "agent_idle": "유휴"
},
"context_menu": {
"mark_read": "읽음으로 표시",
diff --git a/packages/views/locales/ru/inbox.json b/packages/views/locales/ru/inbox.json
index 8f5e15d72f..7474715f32 100644
--- a/packages/views/locales/ru/inbox.json
+++ b/packages/views/locales/ru/inbox.json
@@ -16,8 +16,6 @@
"status": "Статус",
"priority": "Приоритет",
"from": "От",
- "unread_only": "Только непрочитанные",
- "no_agents_working": "Нет работающих агентов",
"notification_count_one": "{{count}} уведомление",
"notification_count_other": "{{count}} уведомления",
"clear": "Очистить фильтры",
@@ -25,7 +23,22 @@
"active_count_few": "{{count}} активных фильтра",
"active_count_many": "{{count}} активных фильтров",
"notification_count_few": "{{count}} уведомления",
- "notification_count_many": "{{count}} уведомлений"
+ "notification_count_many": "{{count}} уведомлений",
+ "section_notification": "Уведомление",
+ "section_issue": "Задача",
+ "type": "Тип",
+ "received": "Получено",
+ "type_mention": "Упоминания",
+ "type_comment": "Комментарии и реакции",
+ "type_assign": "Назначения и подписки",
+ "type_review": "Запросы на ревью",
+ "type_change": "Изменения задачи",
+ "type_run": "Запуски агентов",
+ "type_system": "Система",
+ "received_today": "Сегодня",
+ "received_last_7_days": "Последние 7 дней",
+ "received_last_30_days": "Последние 30 дней",
+ "agent_idle": "Простаивает"
},
"context_menu": {
"mark_read": "Отметить как прочитанное",
diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.json
index e2568ccfc0..df953bb023 100644
--- a/packages/views/locales/zh-Hans/inbox.json
+++ b/packages/views/locales/zh-Hans/inbox.json
@@ -15,11 +15,24 @@
"status": "状态",
"priority": "优先级",
"from": "来自",
- "unread_only": "只看未读",
- "no_agents_working": "没有智能体在工作",
"notification_count_other": "{{count}} 条通知",
"clear": "清除筛选",
- "empty": "没有符合筛选条件的通知"
+ "empty": "没有符合筛选条件的通知",
+ "section_notification": "通知",
+ "section_issue": "任务",
+ "type": "通知类型",
+ "received": "收到时间",
+ "type_mention": "提及我",
+ "type_comment": "评论与回应",
+ "type_assign": "分配与订阅",
+ "type_review": "审查请求",
+ "type_change": "任务变更",
+ "type_run": "智能体运行",
+ "type_system": "系统",
+ "received_today": "今天",
+ "received_last_7_days": "最近 7 天",
+ "received_last_30_days": "最近 30 天",
+ "agent_idle": "空闲"
},
"context_menu": {
"mark_read": "标为已读",
diff --git a/packages/views/locales/zh-Hant/inbox.json b/packages/views/locales/zh-Hant/inbox.json
index 4b80c5d00a..8bd66ebab1 100644
--- a/packages/views/locales/zh-Hant/inbox.json
+++ b/packages/views/locales/zh-Hant/inbox.json
@@ -15,11 +15,24 @@
"status": "狀態",
"priority": "優先順序",
"from": "來自",
- "unread_only": "只看未讀",
- "no_agents_working": "沒有 AI 代理在工作",
"notification_count_other": "{{count}} 條通知",
"clear": "清除篩選",
- "empty": "沒有符合篩選條件的通知"
+ "empty": "沒有符合篩選條件的通知",
+ "section_notification": "通知",
+ "section_issue": "任務",
+ "type": "通知類型",
+ "received": "收到時間",
+ "type_mention": "提及我",
+ "type_comment": "評論與回應",
+ "type_assign": "分配與訂閱",
+ "type_review": "審查請求",
+ "type_change": "任務變更",
+ "type_run": "AI 代理執行",
+ "type_system": "系統",
+ "received_today": "今天",
+ "received_last_7_days": "最近 7 天",
+ "received_last_30_days": "最近 30 天",
+ "agent_idle": "閒置"
},
"context_menu": {
"mark_read": "標為已讀",
diff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.go
index 8916dd729d..8afc44feb4 100644
--- a/server/internal/handler/inbox.go
+++ b/server/internal/handler/inbox.go
@@ -14,23 +14,31 @@ import (
)
type InboxItemResponse struct {
- ID string `json:"id"`
- WorkspaceID string `json:"workspace_id"`
- RecipientType string `json:"recipient_type"`
- RecipientID string `json:"recipient_id"`
- Type string `json:"type"`
- Severity string `json:"severity"`
- IssueID *string `json:"issue_id"`
- Title string `json:"title"`
- Body *string `json:"body"`
- Read bool `json:"read"`
- Archived bool `json:"archived"`
- CreatedAt string `json:"created_at"`
- IssueStatus *string `json:"issue_status"`
- IssuePriority *string `json:"issue_priority"`
- ActorType *string `json:"actor_type"`
- ActorID *string `json:"actor_id"`
- Details json.RawMessage `json:"details"`
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ RecipientType string `json:"recipient_type"`
+ RecipientID string `json:"recipient_id"`
+ Type string `json:"type"`
+ Severity string `json:"severity"`
+ IssueID *string `json:"issue_id"`
+ Title string `json:"title"`
+ Body *string `json:"body"`
+ Read bool `json:"read"`
+ Archived bool `json:"archived"`
+ CreatedAt string `json:"created_at"`
+ IssueStatus *string `json:"issue_status"`
+ IssuePriority *string `json:"issue_priority"`
+ // Issue fields the inbox filters match on. List rows always carry them
+ // (an empty label list included), which is how a client tells a server
+ // that supports those filters from an older one.
+ IssueProjectID *string `json:"issue_project_id"`
+ IssueAssigneeType *string `json:"issue_assignee_type"`
+ IssueAssigneeID *string `json:"issue_assignee_id"`
+ IssueDueDate *string `json:"issue_due_date"`
+ IssueLabelIDs []string `json:"issue_label_ids"`
+ ActorType *string `json:"actor_type"`
+ ActorID *string `json:"actor_id"`
+ Details json.RawMessage `json:"details"`
}
func inboxToResponse(i db.InboxItem) InboxItemResponse {
@@ -111,26 +119,38 @@ func inboxListBody(notifType string, issueID pgtype.UUID, body pgtype.Text) *str
// through inboxToResponse and keep the full body.
func inboxRowToResponse(r db.ListInboxItemsRow) InboxItemResponse {
return InboxItemResponse{
- ID: uuidToString(r.ID),
- WorkspaceID: uuidToString(r.WorkspaceID),
- RecipientType: r.RecipientType,
- RecipientID: uuidToString(r.RecipientID),
- Type: r.Type,
- Severity: r.Severity,
- IssueID: uuidToPtr(r.IssueID),
- Title: r.Title,
- Body: inboxListBody(r.Type, r.IssueID, r.Body),
- Read: r.Read,
- Archived: r.Archived,
- CreatedAt: timestampToString(r.CreatedAt),
- IssueStatus: textToPtr(r.IssueStatus),
- IssuePriority: textToPtr(r.IssuePriority),
- ActorType: textToPtr(r.ActorType),
- ActorID: uuidToPtr(r.ActorID),
- Details: json.RawMessage(r.Details),
+ ID: uuidToString(r.ID),
+ WorkspaceID: uuidToString(r.WorkspaceID),
+ RecipientType: r.RecipientType,
+ RecipientID: uuidToString(r.RecipientID),
+ Type: r.Type,
+ Severity: r.Severity,
+ IssueID: uuidToPtr(r.IssueID),
+ Title: r.Title,
+ Body: inboxListBody(r.Type, r.IssueID, r.Body),
+ Read: r.Read,
+ Archived: r.Archived,
+ CreatedAt: timestampToString(r.CreatedAt),
+ IssueStatus: textToPtr(r.IssueStatus),
+ IssuePriority: textToPtr(r.IssuePriority),
+ IssueProjectID: uuidToPtr(r.IssueProjectID),
+ IssueAssigneeType: textToPtr(r.IssueAssigneeType),
+ IssueAssigneeID: uuidToPtr(r.IssueAssigneeID),
+ IssueDueDate: dateToPtr(r.IssueDueDate),
+ IssueLabelIDs: inboxLabelIDs(r.IssueLabelIds),
+ ActorType: textToPtr(r.ActorType),
+ ActorID: uuidToPtr(r.ActorID),
+ Details: json.RawMessage(r.Details),
}
}
+func inboxLabelIDs(ids []string) []string {
+ if ids == nil {
+ return []string{}
+ }
+ return ids
+}
+
// ListArchivedInboxItemsRow carries the same columns as ListInboxItemsRow (both
// queries select `inbox_item.*` plus the joined issue projections), so the archived
// row converts to the active one and reuses its mapper. If either query's
@@ -149,6 +169,17 @@ func (h *Handler) enrichInboxResponse(ctx context.Context, resp InboxItemRespons
resp.IssueStatus = &s
p := issue.Priority
resp.IssuePriority = &p
+ resp.IssueProjectID = uuidToPtr(issue.ProjectID)
+ resp.IssueAssigneeType = textToPtr(issue.AssigneeType)
+ resp.IssueAssigneeID = uuidToPtr(issue.AssigneeID)
+ resp.IssueDueDate = dateToPtr(issue.DueDate)
+ labels, err := h.Queries.ListLabelsByIssue(ctx, db.ListLabelsByIssueParams{IssueID: issue.ID, WorkspaceID: issue.WorkspaceID})
+ if err == nil {
+ resp.IssueLabelIDs = make([]string, len(labels))
+ for i, label := range labels {
+ resp.IssueLabelIDs[i] = uuidToString(label.ID)
+ }
+ }
}
return resp
}
diff --git a/server/internal/handler/inbox_archive.go b/server/internal/handler/inbox_archive.go
index bdf33694bb..3800cfc750 100644
--- a/server/internal/handler/inbox_archive.go
+++ b/server/internal/handler/inbox_archive.go
@@ -31,9 +31,21 @@ type archivedInboxFacetsResponse struct {
Statuses map[string]int64 `json:"statuses"`
Priorities map[string]int64 `json:"priorities"`
Actors map[string]int64 `json:"actors"`
+ Types map[string]int64 `json:"types"`
+ Projects map[string]int64 `json:"projects"`
+ Assignees map[string]int64 `json:"assignees"`
+ Labels map[string]int64 `json:"labels"`
UnreadCount int64 `json:"unread_count"`
}
+// Values the closed-set filters accept; the type groups mirror the CASE in
+// inbox_archive.sql and INBOX_TYPE_GROUPS in packages/core/inbox.
+var (
+ archivedInboxTypeGroups = []string{"mention", "comment", "assign", "review", "change", "run", "system"}
+ archivedInboxDueDates = []string{"overdue", "today", "this_week", "next_7_days", "none"}
+ archivedInboxNegatable = []string{"type", "actor", "status", "priority", "project", "assignee", "label", "dueDate"}
+)
+
func parseArchivedInboxFilters(w http.ResponseWriter, r *http.Request) (db.ArchivedInboxFacetsParams, bool) {
var p db.ArchivedInboxFacetsParams
userID, ok := requireUserID(w, r)
@@ -46,7 +58,12 @@ func parseArchivedInboxFilters(w http.ResponseWriter, r *http.Request) (db.Archi
}
p.RecipientID = parseUUID(userID)
q := r.URL.Query()
- for name, target := range map[string]*[]string{"statuses": &p.Statuses, "priorities": &p.Priorities, "actors": &p.Actors} {
+ lists := map[string]*[]string{
+ "statuses": &p.Statuses, "priorities": &p.Priorities, "actors": &p.Actors,
+ "types": &p.Types, "projects": &p.Projects, "assignees": &p.Assignees,
+ "labels": &p.Labels, "due_dates": &p.DueDates, "negated": &p.Negated,
+ }
+ for name, target := range lists {
*target = []string{}
if raw := q.Get(name); raw != "" {
if len(raw) > 8192 {
@@ -68,6 +85,14 @@ func parseArchivedInboxFilters(w http.ResponseWriter, r *http.Request) (db.Archi
*target = slices.Compact(*target)
}
}
+ for name, allowed := range map[string][]string{"types": archivedInboxTypeGroups, "due_dates": archivedInboxDueDates, "negated": archivedInboxNegatable} {
+ for _, value := range *lists[name] {
+ if !slices.Contains(allowed, value) {
+ writeError(w, http.StatusBadRequest, "invalid "+name+" filter")
+ return p, false
+ }
+ }
+ }
if raw := q.Get("unread_only"); raw != "" {
if raw != "true" && raw != "false" {
writeError(w, http.StatusBadRequest, "invalid unread_only")
@@ -75,6 +100,27 @@ func parseArchivedInboxFilters(w http.ResponseWriter, r *http.Request) (db.Archi
}
p.UnreadOnly = raw == "true"
}
+ if raw := q.Get("received_after"); raw != "" {
+ after, err := time.Parse(time.RFC3339Nano, raw)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid received_after")
+ return p, false
+ }
+ p.ReceivedAfter = pgtype.Timestamptz{Time: after.UTC(), Valid: true}
+ }
+ // Due-date buckets are relative to the viewer's calendar day, which only
+ // the client knows.
+ if raw := q.Get("today"); raw != "" {
+ today, err := time.Parse(time.DateOnly, raw)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid today")
+ return p, false
+ }
+ p.Today = pgtype.Date{Time: today, Valid: true}
+ } else if len(p.DueDates) > 0 {
+ writeError(w, http.StatusBadRequest, "due_dates requires today")
+ return p, false
+ }
return p, true
}
@@ -95,7 +141,10 @@ func (h *Handler) ListArchivedInboxPage(w http.ResponseWriter, r *http.Request)
}
p := db.ListArchivedInboxPageParams{
WorkspaceID: filters.WorkspaceID, RecipientID: filters.RecipientID,
- Statuses: filters.Statuses, Priorities: filters.Priorities, Actors: filters.Actors, UnreadOnly: filters.UnreadOnly,
+ Types: filters.Types, Negated: filters.Negated, Actors: filters.Actors, ReceivedAfter: filters.ReceivedAfter,
+ Statuses: filters.Statuses, Priorities: filters.Priorities, Projects: filters.Projects,
+ Assignees: filters.Assignees, Labels: filters.Labels, DueDates: filters.DueDates, Today: filters.Today,
+ UnreadOnly: filters.UnreadOnly,
}
limit := 50
if raw := r.URL.Query().Get("limit"); raw != "" {
@@ -149,6 +198,9 @@ func (h *Handler) ListArchivedInboxPage(w http.ResponseWriter, r *http.Request)
item := inboxToResponse(row.InboxItem)
item.Body = inboxListBody(row.InboxItem.Type, row.InboxItem.IssueID, row.InboxItem.Body)
item.IssueStatus, item.IssuePriority = textToPtr(row.IssueStatus), textToPtr(row.IssuePriority)
+ item.IssueProjectID, item.IssueDueDate = uuidToPtr(row.IssueProjectID), dateToPtr(row.IssueDueDate)
+ item.IssueAssigneeType, item.IssueAssigneeID = textToPtr(row.IssueAssigneeType), uuidToPtr(row.IssueAssigneeID)
+ item.IssueLabelIDs = inboxLabelIDs(row.IssueLabelIds)
if row.CommentID != "" {
var details map[string]json.RawMessage
if len(item.Details) == 0 || string(item.Details) == "null" {
@@ -181,15 +233,20 @@ func (h *Handler) GetArchivedInboxFacets(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusInternalServerError, "failed to load archived inbox filters")
return
}
- resp := archivedInboxFacetsResponse{Statuses: map[string]int64{}, Priorities: map[string]int64{}, Actors: map[string]int64{}}
+ resp := archivedInboxFacetsResponse{
+ Statuses: map[string]int64{}, Priorities: map[string]int64{}, Actors: map[string]int64{},
+ Types: map[string]int64{}, Projects: map[string]int64{}, Assignees: map[string]int64{}, Labels: map[string]int64{},
+ }
+ dimensions := map[string]map[string]int64{
+ "statuses": resp.Statuses, "priorities": resp.Priorities, "actors": resp.Actors,
+ "types": resp.Types, "projects": resp.Projects, "assignees": resp.Assignees, "labels": resp.Labels,
+ }
for _, row := range rows {
+ if counts, ok := dimensions[row.Dimension]; ok {
+ counts[row.Key] = row.Count
+ continue
+ }
switch row.Dimension {
- case "statuses":
- resp.Statuses[row.Key] = row.Count
- case "priorities":
- resp.Priorities[row.Key] = row.Count
- case "actors":
- resp.Actors[row.Key] = row.Count
case "unread":
resp.UnreadCount = row.Count
}
diff --git a/server/internal/handler/inbox_archive_test.go b/server/internal/handler/inbox_archive_test.go
index 534d0758ac..88ee4115bb 100644
--- a/server/internal/handler/inbox_archive_test.go
+++ b/server/internal/handler/inbox_archive_test.go
@@ -3,6 +3,7 @@ package handler
import (
"net/http"
"net/url"
+ "slices"
"testing"
"time"
@@ -67,6 +68,37 @@ func TestArchivedInboxPageBeyond200(t *testing.T) {
}
}
+func TestArchivedInboxMatchedNotificationKeepsItsCommentAnchor(t *testing.T) {
+ ws := dbfx.Workspace(t, "Archive anchors", "archive-anchor-"+uuid.NewString())
+ dbfx.Member(t, ws, testUserID, "owner")
+ issue := dbfx.Issue(t, "Anchored", testutil.Cols{"workspace_id": ws})
+ c1, c2 := uuid.NewString(), uuid.NewString()
+ old := time.Now().UTC().Add(-time.Hour)
+ insert := func(kind string, created time.Time, comment string) string {
+ return dbfx.Insert(t, "inbox_item", testutil.Cols{
+ "workspace_id": ws, "recipient_type": "member", "recipient_id": testUserID,
+ "type": kind, "severity": "info", "title": "Anchored", "issue_id": issue,
+ "archived": true, "created_at": created, "details": `{"comment_id":"` + comment + `"}`,
+ })
+ }
+ mention := insert("mentioned", old, c1)
+ newest := insert("new_comment", old.Add(time.Minute), c2)
+ get := func(query string) archivedInboxPageResponse {
+ var page archivedInboxPageResponse
+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListArchivedInboxPage), inboxRequest(http.MethodGet, "/api/inbox/archived/page?"+query, ws)).Want(http.StatusOK).JSON(&page)
+ return page
+ }
+ for _, query := range []string{"types=mention", "group_id=" + issue + "&types=mention"} {
+ page := get(query)
+ if len(page.Items) != 1 || page.Items[0].ID != mention || string(page.Items[0].Details) != `{"comment_id":"`+c1+`"}` {
+ t.Fatalf("%s: mention lost its own comment: %+v", query, page.Items)
+ }
+ }
+ if page := get(""); len(page.Items) != 1 || page.Items[0].ID != newest || string(page.Items[0].Details) != `{"comment_id":"`+c2+`"}` {
+ t.Fatalf("unfiltered group did not show the newest comment: %+v", page.Items)
+ }
+}
+
func TestArchivedInboxFiltersAndLookupUseLatestGroup(t *testing.T) {
ws := dbfx.Workspace(t, "Archive filters", "archive-filter-"+uuid.NewString())
dbfx.Member(t, ws, testUserID, "owner")
@@ -103,15 +135,20 @@ func TestArchivedInboxFiltersAndLookupUseLatestGroup(t *testing.T) {
if len(get("group_id="+issue+"&unread_only=true").Items) != 0 {
t.Fatal("older unread notification matched")
}
- if len(get("group_id="+issue+"&actors=agent:"+actor).Items) != 0 {
- t.Fatal("older actor matched")
+ // A sender filter matches any notification in the group and renders the
+ // newest one it matched.
+ if byActor := get("group_id=" + issue + "&actors=agent:" + actor); len(byActor.Items) != 1 || byActor.Items[0].ID == newest {
+ t.Fatalf("older actor did not select its own notification: %+v", byActor)
+ }
+ if len(get("group_id="+issue+"&actors=agent:"+actor+"&unread_only=true").Items) != 1 {
+ t.Fatal("unread did not test the notification the sender filter selected")
}
if len(get("group_id="+issue).Items) != 1 {
t.Fatal("deep link outside first page did not resolve")
}
var facets archivedInboxFacetsResponse
testutil.Call(t, inboxWorkspaceHandler(testHandler.GetArchivedInboxFacets), inboxRequest(http.MethodGet, "/api/inbox/archived/facets?actors=system", ws)).Want(http.StatusOK).JSON(&facets)
- if facets.Statuses["in_review"] != 1 || facets.Priorities["high"] != 1 || facets.Actors["agent:"+actor] != 55 || facets.Actors["system"] != 1 || facets.UnreadCount != 0 {
+ if facets.Statuses["in_review"] != 1 || facets.Priorities["high"] != 1 || facets.Actors["agent:"+actor] != 56 || facets.Actors["system"] != 1 || facets.UnreadCount != 0 {
t.Fatalf("incorrect facets: %+v", facets)
}
insert(&issue, false, "system", nil, time.Now(), `{}`, false)
@@ -144,3 +181,94 @@ func TestArchivedInboxFiltersAndLookupUseLatestGroup(t *testing.T) {
testutil.Call(t, inboxWorkspaceHandler(handler), req).Want(http.StatusNotFound)
}
}
+
+func TestArchivedInboxNotificationAndIssueFilters(t *testing.T) {
+ ws := dbfx.Workspace(t, "Archive extended filters", "archive-extended-"+uuid.NewString())
+ dbfx.Member(t, ws, testUserID, "owner")
+ today := time.Date(2026, 3, 11, 0, 0, 0, 0, time.UTC) // a Wednesday
+ project := dbfx.Project(t, "Filtered project", testutil.Cols{"workspace_id": ws})
+ label := dbfx.Insert(t, "issue_label", testutil.Cols{"workspace_id": ws, "name": "bug", "color": "#f00", "resource_type": "issue"})
+ tracked := dbfx.Issue(t, "Tracked", testutil.Cols{
+ "workspace_id": ws, "project_id": project, "assignee_type": "member", "assignee_id": testUserID,
+ "due_date": today.Format(time.DateOnly),
+ })
+ dbfx.Exec(t, `INSERT INTO issue_to_label (issue_id, label_id) VALUES ($1, $2)`, tracked, label)
+ bare := dbfx.Issue(t, "Bare", testutil.Cols{"workspace_id": ws})
+ base := time.Now().UTC().Add(-time.Hour)
+ insert := func(issueID *string, notifType string, created time.Time) string {
+ return dbfx.Insert(t, "inbox_item", testutil.Cols{
+ "workspace_id": ws, "recipient_type": "member", "recipient_id": testUserID,
+ "type": notifType, "severity": "info", "title": notifType, "issue_id": issueID,
+ "read": true, "actor_type": "system", "archived": true, "created_at": created,
+ })
+ }
+ mention := insert(&tracked, "mentioned", base)
+ change := insert(&tracked, "status_changed", base.Add(time.Minute))
+ comment := insert(&bare, "new_comment", base)
+ issueless := insert(nil, "quick_create_failed", base)
+
+ ids := func(query string) []string {
+ var page archivedInboxPageResponse
+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListArchivedInboxPage), inboxRequest(http.MethodGet, "/api/inbox/archived/page?"+query, ws)).Want(http.StatusOK).JSON(&page)
+ out := make([]string, len(page.Items))
+ for i, item := range page.Items {
+ out[i] = item.ID
+ }
+ slices.Sort(out)
+ return out
+ }
+ sorted := func(values ...string) []string {
+ slices.Sort(values)
+ return values
+ }
+ day := "today=" + today.Format(time.DateOnly)
+ for _, tc := range []struct {
+ query string
+ want []string
+ }{
+ // The type filter picks the matching notification, not the newest one.
+ {"types=mention", []string{mention}},
+ {"types=comment,mention", sorted(mention, comment)},
+ {"types=change&negated=type", sorted(mention, comment, issueless)},
+ {"projects=" + project, []string{change}},
+ {"projects=none", []string{comment}},
+ // Issue filters, negated ones too, never match an issue-less notification.
+ {"projects=" + project + "&negated=project", []string{comment}},
+ {"assignees=member:" + testUserID, []string{change}},
+ {"assignees=none", []string{comment}},
+ {"labels=" + label, []string{change}},
+ {"labels=" + label + "&negated=label", []string{comment}},
+ {"due_dates=today&" + day, []string{change}},
+ {"due_dates=this_week,overdue&" + day, []string{change}},
+ {"due_dates=none&" + day, []string{comment}},
+ {"due_dates=today&negated=dueDate&" + day, []string{comment}},
+ {"received_after=" + url.QueryEscape(time.Now().UTC().Add(time.Hour).Format(time.RFC3339Nano)), []string{}},
+ {"types=mention&received_after=" + url.QueryEscape(base.Add(30*time.Second).Format(time.RFC3339Nano)), []string{}},
+ } {
+ if got := ids(tc.query); !slices.Equal(got, tc.want) {
+ t.Errorf("%s: got %v, want %v", tc.query, got, tc.want)
+ }
+ }
+
+ facets := func(query string) archivedInboxFacetsResponse {
+ var out archivedInboxFacetsResponse
+ testutil.Call(t, inboxWorkspaceHandler(testHandler.GetArchivedInboxFacets), inboxRequest(http.MethodGet, "/api/inbox/archived/facets?"+query, ws)).Want(http.StatusOK).JSON(&out)
+ return out
+ }
+ // Each count ignores its own dimension, and an issue filter drops the
+ // issue-less notification from every other count.
+ if got := facets("types=mention&projects=none"); got.Types["mention"] != 0 || got.Types["comment"] != 1 || got.Types["system"] != 0 ||
+ got.Projects[project] != 1 || got.Projects["none"] != 0 {
+ t.Fatalf("facets with type and project filters: %+v", got)
+ }
+ if got := facets("types=mention"); got.Labels[label] != 1 || got.Assignees["member:"+testUserID] != 1 || got.Projects["none"] != 0 {
+ t.Fatalf("facets with a type filter: %+v", got)
+ }
+ if got := facets(""); got.Types["mention"] != 1 || got.Types["change"] != 1 || got.Types["system"] != 1 || got.Projects["none"] != 1 || got.Assignees["none"] != 1 {
+ t.Fatalf("unfiltered facets: %+v", got)
+ }
+
+ for _, query := range []string{"types=bogus", "negated=creator", "due_dates=later&" + day, "due_dates=today", "today=03/11/2026", "received_after=yesterday"} {
+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListArchivedInboxPage), inboxRequest(http.MethodGet, "/api/inbox/archived/page?"+query, ws)).Want(http.StatusBadRequest)
+ }
+}
diff --git a/server/internal/handler/inbox_test.go b/server/internal/handler/inbox_test.go
index 898c649f00..5cca80f186 100644
--- a/server/internal/handler/inbox_test.go
+++ b/server/internal/handler/inbox_test.go
@@ -28,10 +28,25 @@ func inboxWorkspaceHandler(handler http.HandlerFunc) http.HandlerFunc {
func TestListInboxProjectsCurrentIssueStatusAndPriority(t *testing.T) {
workspaceID := dbfx.Workspace(t, "Inbox filter projections", "inbox-filter-"+uuid.NewString())
dbfx.Member(t, workspaceID, testUserID, "owner")
+ projectID := dbfx.Project(t, "Projected project", testutil.Cols{"workspace_id": workspaceID})
+ labelID := dbfx.Insert(t, "issue_label", testutil.Cols{"workspace_id": workspaceID, "name": "bug", "color": "#f00", "resource_type": "issue"})
issueID := dbfx.Issue(t, "Filtered issue", testutil.Cols{
- "workspace_id": workspaceID,
- "status": "in_review",
- "priority": "high",
+ "workspace_id": workspaceID,
+ "status": "in_review",
+ "priority": "high",
+ "project_id": projectID,
+ "assignee_type": "member",
+ "assignee_id": testUserID,
+ "due_date": "2026-03-11",
+ })
+ dbfx.Exec(t, `INSERT INTO issue_to_label (issue_id, label_id) VALUES ($1, $2)`, issueID, labelID)
+ dbfx.Insert(t, "inbox_item", testutil.Cols{
+ "workspace_id": workspaceID,
+ "recipient_type": "member",
+ "recipient_id": testUserID,
+ "type": "system",
+ "severity": "info",
+ "title": "Issue-less",
})
dbfx.Insert(t, "inbox_item", testutil.Cols{
"workspace_id": workspaceID,
@@ -49,8 +64,21 @@ func TestListInboxProjectsCurrentIssueStatusAndPriority(t *testing.T) {
Want(http.StatusOK).
JSON(&items)
- if len(items) != 1 {
- t.Fatalf("inbox items = %d, want 1: %+v", len(items), items)
+ if len(items) != 2 {
+ t.Fatalf("inbox items = %d, want 2: %+v", len(items), items)
+ }
+ if items[1].IssueID != nil {
+ items[0], items[1] = items[1], items[0]
+ }
+ if items[1].IssueLabelIDs == nil || len(items[1].IssueLabelIDs) != 0 {
+ t.Errorf("issue-less issue_label_ids = %v, want an empty list", items[1].IssueLabelIDs)
+ }
+ if got := items[0]; got.IssueProjectID == nil || *got.IssueProjectID != projectID ||
+ got.IssueAssigneeType == nil || *got.IssueAssigneeType != "member" ||
+ got.IssueAssigneeID == nil || *got.IssueAssigneeID != testUserID ||
+ got.IssueDueDate == nil || *got.IssueDueDate != "2026-03-11" ||
+ len(got.IssueLabelIDs) != 1 || got.IssueLabelIDs[0] != labelID {
+ t.Errorf("issue projection = %+v", got)
}
if items[0].IssueStatus == nil || *items[0].IssueStatus != "in_review" {
t.Errorf("issue_status = %v, want in_review", items[0].IssueStatus)
diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.go
index 31736d68c5..7c6afedfdf 100644
--- a/server/pkg/db/generated/inbox.sql.go
+++ b/server/pkg/db/generated/inbox.sql.go
@@ -437,7 +437,14 @@ WITH eligible_archived AS MATERIALIZED (
)
SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section,
iss.status AS issue_status,
- iss.priority AS issue_priority
+ iss.priority AS issue_priority,
+ iss.project_id AS issue_project_id,
+ iss.assignee_type AS issue_assignee_type,
+ iss.assignee_id AS issue_assignee_id,
+ iss.due_date AS issue_due_date,
+ ARRAY(SELECT il.label_id::text FROM issue_to_label il
+ WHERE iss.id IS NOT NULL AND il.issue_id = iss.id
+ ORDER BY il.label_id)::text[] AS issue_label_ids
FROM inbox_item i
JOIN selected_ids selected ON selected.id = i.id
LEFT JOIN issue iss ON iss.id = i.issue_id
@@ -451,24 +458,29 @@ type ListArchivedInboxItemsParams struct {
}
type ListArchivedInboxItemsRow struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- RecipientType string `json:"recipient_type"`
- RecipientID pgtype.UUID `json:"recipient_id"`
- Type string `json:"type"`
- Severity string `json:"severity"`
- IssueID pgtype.UUID `json:"issue_id"`
- Title string `json:"title"`
- Body pgtype.Text `json:"body"`
- Read bool `json:"read"`
- Archived bool `json:"archived"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- ActorType pgtype.Text `json:"actor_type"`
- ActorID pgtype.UUID `json:"actor_id"`
- Details []byte `json:"details"`
- Section pgtype.Text `json:"section"`
- IssueStatus pgtype.Text `json:"issue_status"`
- IssuePriority pgtype.Text `json:"issue_priority"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RecipientType string `json:"recipient_type"`
+ RecipientID pgtype.UUID `json:"recipient_id"`
+ Type string `json:"type"`
+ Severity string `json:"severity"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Title string `json:"title"`
+ Body pgtype.Text `json:"body"`
+ Read bool `json:"read"`
+ Archived bool `json:"archived"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ ActorType pgtype.Text `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ Details []byte `json:"details"`
+ Section pgtype.Text `json:"section"`
+ IssueStatus pgtype.Text `json:"issue_status"`
+ IssuePriority pgtype.Text `json:"issue_priority"`
+ IssueProjectID pgtype.UUID `json:"issue_project_id"`
+ IssueAssigneeType pgtype.Text `json:"issue_assignee_type"`
+ IssueAssigneeID pgtype.UUID `json:"issue_assignee_id"`
+ IssueDueDate pgtype.Date `json:"issue_due_date"`
+ IssueLabelIds []string `json:"issue_label_ids"`
}
// Archived counterpart of ListInboxItems, backing the inbox's "Archived"
@@ -520,6 +532,11 @@ func (q *Queries) ListArchivedInboxItems(ctx context.Context, arg ListArchivedIn
&i.Section,
&i.IssueStatus,
&i.IssuePriority,
+ &i.IssueProjectID,
+ &i.IssueAssigneeType,
+ &i.IssueAssigneeID,
+ &i.IssueDueDate,
+ &i.IssueLabelIds,
); err != nil {
return nil, err
}
@@ -534,7 +551,14 @@ func (q *Queries) ListArchivedInboxItems(ctx context.Context, arg ListArchivedIn
const listInboxItems = `-- name: ListInboxItems :many
SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section,
iss.status AS issue_status,
- iss.priority AS issue_priority
+ iss.priority AS issue_priority,
+ iss.project_id AS issue_project_id,
+ iss.assignee_type AS issue_assignee_type,
+ iss.assignee_id AS issue_assignee_id,
+ iss.due_date AS issue_due_date,
+ ARRAY(SELECT il.label_id::text FROM issue_to_label il
+ WHERE iss.id IS NOT NULL AND il.issue_id = iss.id
+ ORDER BY il.label_id)::text[] AS issue_label_ids
FROM inbox_item i
LEFT JOIN issue iss ON iss.id = i.issue_id
WHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3 AND i.archived = false
@@ -548,26 +572,34 @@ type ListInboxItemsParams struct {
}
type ListInboxItemsRow struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- RecipientType string `json:"recipient_type"`
- RecipientID pgtype.UUID `json:"recipient_id"`
- Type string `json:"type"`
- Severity string `json:"severity"`
- IssueID pgtype.UUID `json:"issue_id"`
- Title string `json:"title"`
- Body pgtype.Text `json:"body"`
- Read bool `json:"read"`
- Archived bool `json:"archived"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- ActorType pgtype.Text `json:"actor_type"`
- ActorID pgtype.UUID `json:"actor_id"`
- Details []byte `json:"details"`
- Section pgtype.Text `json:"section"`
- IssueStatus pgtype.Text `json:"issue_status"`
- IssuePriority pgtype.Text `json:"issue_priority"`
-}
-
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RecipientType string `json:"recipient_type"`
+ RecipientID pgtype.UUID `json:"recipient_id"`
+ Type string `json:"type"`
+ Severity string `json:"severity"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Title string `json:"title"`
+ Body pgtype.Text `json:"body"`
+ Read bool `json:"read"`
+ Archived bool `json:"archived"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ ActorType pgtype.Text `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ Details []byte `json:"details"`
+ Section pgtype.Text `json:"section"`
+ IssueStatus pgtype.Text `json:"issue_status"`
+ IssuePriority pgtype.Text `json:"issue_priority"`
+ IssueProjectID pgtype.UUID `json:"issue_project_id"`
+ IssueAssigneeType pgtype.Text `json:"issue_assignee_type"`
+ IssueAssigneeID pgtype.UUID `json:"issue_assignee_id"`
+ IssueDueDate pgtype.Date `json:"issue_due_date"`
+ IssueLabelIds []string `json:"issue_label_ids"`
+}
+
+// The issue projections feed the inbox filters. Keep this column list
+// identical to ListArchivedInboxItems: the handler converts one row type into
+// the other.
func (q *Queries) ListInboxItems(ctx context.Context, arg ListInboxItemsParams) ([]ListInboxItemsRow, error) {
rows, err := q.db.Query(ctx, listInboxItems, arg.WorkspaceID, arg.RecipientType, arg.RecipientID)
if err != nil {
@@ -596,6 +628,11 @@ func (q *Queries) ListInboxItems(ctx context.Context, arg ListInboxItemsParams)
&i.Section,
&i.IssueStatus,
&i.IssuePriority,
+ &i.IssueProjectID,
+ &i.IssueAssigneeType,
+ &i.IssueAssigneeID,
+ &i.IssueDueDate,
+ &i.IssueLabelIds,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/inbox_archive.sql.go b/server/pkg/db/generated/inbox_archive.sql.go
index d02cf19da6..d695168fd4 100644
--- a/server/pkg/db/generated/inbox_archive.sql.go
+++ b/server/pkg/db/generated/inbox_archive.sql.go
@@ -12,9 +12,17 @@ import (
)
const archivedInboxFacets = `-- name: ArchivedInboxFacets :many
-WITH newest AS MATERIALIZED (
- SELECT DISTINCT ON (COALESCE(i.issue_id, i.id))
- i.id, i.issue_id, i.created_at, i.read,
+WITH base AS MATERIALIZED (
+ SELECT i.id, i.issue_id, COALESCE(i.issue_id, i.id) AS group_id, i.created_at, i.read,
+ CASE
+ WHEN i.type = 'mentioned' THEN 'mention'
+ WHEN i.type IN ('new_comment', 'reaction_added') THEN 'comment'
+ WHEN i.type IN ('issue_assigned', 'unassigned', 'assignee_changed', 'issue_subscribed') THEN 'assign'
+ WHEN i.type = 'review_requested' THEN 'review'
+ WHEN i.type IN ('status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'
+ WHEN i.type IN ('task_completed', 'task_failed', 'agent_blocked', 'agent_completed') THEN 'run'
+ ELSE 'system'
+ END AS type_group,
CASE WHEN i.actor_type = 'system' THEN 'system'
ELSE i.actor_type || ':' || i.actor_id::text END AS actor
FROM inbox_item i
@@ -29,44 +37,120 @@ WITH newest AS MATERIALIZED (
AND active.recipient_id = i.recipient_id
AND active.issue_id = i.issue_id AND active.archived = false
))
- ORDER BY COALESCE(i.issue_id, i.id), i.created_at DESC, i.id DESC
+), notification_match AS MATERIALIZED (
+ SELECT base.id, base.issue_id, base.group_id, base.created_at, base.read, base.type_group, base.actor,
+ (cardinality($3::text[]) = 0
+ OR (type_group = ANY($3::text[])) <> ('type' = ANY($4::text[]))) AS type_match,
+ (cardinality($5::text[]) = 0
+ OR COALESCE(actor = ANY($5::text[]), false) <> ('actor' = ANY($4::text[]))) AS actor_match,
+ ($6::timestamptz IS NULL OR created_at >= $6::timestamptz) AS received_match
+ FROM base
+), groups AS (
+ SELECT DISTINCT group_id, issue_id FROM base
), projected AS (
- SELECT newest.id, newest.issue_id, newest.created_at, newest.read, newest.actor, iss.status AS issue_status, iss.priority AS issue_priority
- FROM newest
- LEFT JOIN issue iss ON iss.id = newest.issue_id
+ SELECT groups.group_id,
+ iss.id AS issue_ref, iss.status AS issue_status, iss.priority AS issue_priority,
+ COALESCE(iss.project_id::text, 'none') AS project_key,
+ CASE WHEN iss.assignee_id IS NULL THEN 'none'
+ ELSE iss.assignee_type || ':' || iss.assignee_id::text END AS assignee_key,
+ iss.due_date,
+ ARRAY(SELECT il.label_id::text FROM issue_to_label il
+ WHERE iss.id IS NOT NULL AND il.issue_id = iss.id)::text[] AS label_ids
+ FROM groups
+ LEFT JOIN issue iss ON iss.id = groups.issue_id
AND iss.workspace_id = $1::uuid
-), matched AS (
- SELECT projected.id, projected.issue_id, projected.created_at, projected.read, projected.actor, projected.issue_status, projected.issue_priority,
- (cardinality($3::text[]) = 0 OR issue_status = ANY($3::text[])) AS status_match,
- (cardinality($4::text[]) = 0 OR issue_priority = ANY($4::text[])) AS priority_match,
- (cardinality($5::text[]) = 0 OR actor = ANY($5::text[])) AS actor_match,
- (NOT $6::boolean OR NOT read) AS read_match
+), issue_match AS MATERIALIZED (
+ SELECT projected.group_id, projected.issue_ref, projected.issue_status, projected.issue_priority, projected.project_key, projected.assignee_key, projected.due_date, projected.label_ids,
+ (cardinality($7::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (issue_status = ANY($7::text[])) <> ('status' = ANY($4::text[])))) AS status_match,
+ (cardinality($8::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (issue_priority = ANY($8::text[])) <> ('priority' = ANY($4::text[])))) AS priority_match,
+ (cardinality($9::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (project_key = ANY($9::text[])) <> ('project' = ANY($4::text[])))) AS project_match,
+ (cardinality($10::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (assignee_key = ANY($10::text[])) <> ('assignee' = ANY($4::text[])))) AS assignee_match,
+ (cardinality($11::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (label_ids && $11::text[]) <> ('label' = ANY($4::text[])))) AS label_match,
+ (cardinality($12::text[]) = 0 OR (issue_ref IS NOT NULL AND COALESCE(
+ ('overdue' = ANY($12::text[]) AND due_date < $13::date)
+ OR ('today' = ANY($12::text[]) AND due_date = $13::date)
+ OR ('this_week' = ANY($12::text[])
+ AND due_date >= $13::date - (EXTRACT(ISODOW FROM $13::date)::int - 1)
+ AND due_date < $13::date - (EXTRACT(ISODOW FROM $13::date)::int - 1) + 7)
+ OR ('next_7_days' = ANY($12::text[])
+ AND due_date >= $13::date AND due_date < $13::date + 7)
+ OR ('none' = ANY($12::text[]) AND due_date IS NULL), false)
+ <> ('dueDate' = ANY($4::text[])))) AS due_match
FROM projected
+), reps AS (
+ SELECT DISTINCT ON (group_id) group_id, read
+ FROM notification_match
+ WHERE type_match AND actor_match AND received_match
+ ORDER BY group_id, created_at DESC, id DESC
+), matched AS (
+ SELECT issue_match.group_id, issue_match.issue_ref, issue_match.issue_status, issue_match.issue_priority, issue_match.project_key, issue_match.assignee_key, issue_match.due_date, issue_match.label_ids, issue_match.status_match, issue_match.priority_match, issue_match.project_match, issue_match.assignee_match, issue_match.label_match, issue_match.due_match, (NOT $14::boolean OR NOT reps.read) AS read_match, reps.read
+ FROM reps JOIN issue_match USING (group_id)
+), type_reps AS (
+ SELECT DISTINCT ON (group_id, type_group) group_id, type_group, read
+ FROM notification_match
+ WHERE actor_match AND received_match
+ ORDER BY group_id, type_group, created_at DESC, id DESC
+), actor_reps AS (
+ SELECT DISTINCT ON (group_id, actor) group_id, actor, read
+ FROM notification_match
+ WHERE type_match AND received_match AND actor IS NOT NULL
+ ORDER BY group_id, actor, created_at DESC, id DESC
)
SELECT 'statuses'::text AS dimension, issue_status::text AS key,
- count(*) FILTER (WHERE priority_match AND actor_match AND read_match)::bigint AS count
+ count(*) FILTER (WHERE priority_match AND project_match AND assignee_match AND label_match AND due_match AND read_match)::bigint AS count
FROM matched WHERE issue_status IS NOT NULL GROUP BY issue_status
UNION ALL
SELECT 'priorities'::text, issue_priority::text,
- count(*) FILTER (WHERE status_match AND actor_match AND read_match)::bigint
+ count(*) FILTER (WHERE status_match AND project_match AND assignee_match AND label_match AND due_match AND read_match)::bigint
FROM matched WHERE issue_priority IS NOT NULL GROUP BY issue_priority
UNION ALL
-SELECT 'actors'::text, actor::text,
- count(*) FILTER (WHERE status_match AND priority_match AND read_match)::bigint
-FROM matched WHERE actor IS NOT NULL GROUP BY actor
+SELECT 'projects'::text, project_key::text,
+ count(*) FILTER (WHERE status_match AND priority_match AND assignee_match AND label_match AND due_match AND read_match)::bigint
+FROM matched WHERE issue_ref IS NOT NULL GROUP BY project_key
+UNION ALL
+SELECT 'assignees'::text, assignee_key::text,
+ count(*) FILTER (WHERE status_match AND priority_match AND project_match AND label_match AND due_match AND read_match)::bigint
+FROM matched WHERE issue_ref IS NOT NULL GROUP BY assignee_key
+UNION ALL
+SELECT 'labels'::text, label::text,
+ count(*) FILTER (WHERE status_match AND priority_match AND project_match AND assignee_match AND due_match AND read_match)::bigint
+FROM matched, unnest(label_ids) AS label GROUP BY label
+UNION ALL
+SELECT 'types'::text, type_reps.type_group::text,
+ count(*) FILTER (WHERE status_match AND priority_match AND project_match AND assignee_match AND label_match AND due_match
+ AND (NOT $14::boolean OR NOT type_reps.read))::bigint
+FROM type_reps JOIN issue_match USING (group_id) GROUP BY type_reps.type_group
+UNION ALL
+SELECT 'actors'::text, actor_reps.actor::text,
+ count(*) FILTER (WHERE status_match AND priority_match AND project_match AND assignee_match AND label_match AND due_match
+ AND (NOT $14::boolean OR NOT actor_reps.read))::bigint
+FROM actor_reps JOIN issue_match USING (group_id) GROUP BY actor_reps.actor
UNION ALL
SELECT 'unread'::text, 'unread'::text,
- count(*) FILTER (WHERE status_match AND priority_match AND actor_match AND NOT read)::bigint
+ count(*) FILTER (WHERE status_match AND priority_match AND project_match AND assignee_match AND label_match AND due_match AND NOT read)::bigint
FROM matched
`
type ArchivedInboxFacetsParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- RecipientID pgtype.UUID `json:"recipient_id"`
- Statuses []string `json:"statuses"`
- Priorities []string `json:"priorities"`
- Actors []string `json:"actors"`
- UnreadOnly bool `json:"unread_only"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RecipientID pgtype.UUID `json:"recipient_id"`
+ Types []string `json:"types"`
+ Negated []string `json:"negated"`
+ Actors []string `json:"actors"`
+ ReceivedAfter pgtype.Timestamptz `json:"received_after"`
+ Statuses []string `json:"statuses"`
+ Priorities []string `json:"priorities"`
+ Projects []string `json:"projects"`
+ Assignees []string `json:"assignees"`
+ Labels []string `json:"labels"`
+ DueDates []string `json:"due_dates"`
+ Today pgtype.Date `json:"today"`
+ UnreadOnly bool `json:"unread_only"`
}
type ArchivedInboxFacetsRow struct {
@@ -75,14 +159,24 @@ type ArchivedInboxFacetsRow struct {
Count int64 `json:"count"`
}
-// Select narrow group representatives before loading bodies or comment anchors.
+// Every count ignores its own dimension, so it says how many rows selecting
+// that value alone would show. Type and sender counts pick the newest
+// notification of that value in each group, the row selecting it renders.
func (q *Queries) ArchivedInboxFacets(ctx context.Context, arg ArchivedInboxFacetsParams) ([]ArchivedInboxFacetsRow, error) {
rows, err := q.db.Query(ctx, archivedInboxFacets,
arg.WorkspaceID,
arg.RecipientID,
+ arg.Types,
+ arg.Negated,
+ arg.Actors,
+ arg.ReceivedAfter,
arg.Statuses,
arg.Priorities,
- arg.Actors,
+ arg.Projects,
+ arg.Assignees,
+ arg.Labels,
+ arg.DueDates,
+ arg.Today,
arg.UnreadOnly,
)
if err != nil {
@@ -104,9 +198,18 @@ func (q *Queries) ArchivedInboxFacets(ctx context.Context, arg ArchivedInboxFace
}
const listArchivedInboxPage = `-- name: ListArchivedInboxPage :many
-WITH newest AS MATERIALIZED (
- SELECT DISTINCT ON (COALESCE(i.issue_id, i.id))
- i.id, i.issue_id, i.created_at, i.read,
+
+WITH base AS MATERIALIZED (
+ SELECT i.id, i.issue_id, COALESCE(i.issue_id, i.id) AS group_id, i.created_at, i.read,
+ CASE
+ WHEN i.type = 'mentioned' THEN 'mention'
+ WHEN i.type IN ('new_comment', 'reaction_added') THEN 'comment'
+ WHEN i.type IN ('issue_assigned', 'unassigned', 'assignee_changed', 'issue_subscribed') THEN 'assign'
+ WHEN i.type = 'review_requested' THEN 'review'
+ WHEN i.type IN ('status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'
+ WHEN i.type IN ('task_completed', 'task_failed', 'agent_blocked', 'agent_completed') THEN 'run'
+ ELSE 'system'
+ END AS type_group,
CASE WHEN i.actor_type = 'system' THEN 'system'
ELSE i.actor_type || ':' || i.actor_id::text END AS actor
FROM inbox_item i
@@ -123,32 +226,71 @@ WITH newest AS MATERIALIZED (
AND active.recipient_id = i.recipient_id
AND active.issue_id = i.issue_id AND active.archived = false
))
- ORDER BY COALESCE(i.issue_id, i.id), i.created_at DESC, i.id DESC
+), newest AS (
+ SELECT DISTINCT ON (group_id) base.id, base.issue_id, base.group_id, base.created_at, base.read, base.type_group, base.actor
+ FROM base
+ WHERE (cardinality($4::text[]) = 0
+ OR (type_group = ANY($4::text[])) <> ('type' = ANY($5::text[])))
+ AND (cardinality($6::text[]) = 0
+ OR COALESCE(actor = ANY($6::text[]), false) <> ('actor' = ANY($5::text[])))
+ AND ($7::timestamptz IS NULL OR created_at >= $7::timestamptz)
+ ORDER BY group_id, created_at DESC, id DESC
), projected AS (
- SELECT newest.id, newest.issue_id, newest.created_at, newest.read, newest.actor, iss.status AS issue_status, iss.priority AS issue_priority
+ SELECT newest.id, newest.created_at, newest.read,
+ iss.id AS issue_ref, iss.status AS issue_status, iss.priority AS issue_priority,
+ COALESCE(iss.project_id::text, 'none') AS project_key,
+ CASE WHEN iss.assignee_id IS NULL THEN 'none'
+ ELSE iss.assignee_type || ':' || iss.assignee_id::text END AS assignee_key,
+ iss.due_date,
+ ARRAY(SELECT il.label_id::text FROM issue_to_label il
+ WHERE iss.id IS NOT NULL AND il.issue_id = iss.id)::text[] AS label_ids
FROM newest
LEFT JOIN issue iss ON iss.id = newest.issue_id
AND iss.workspace_id = $1::uuid
-), matched AS (
- SELECT projected.id, projected.issue_id, projected.created_at, projected.read, projected.actor, projected.issue_status, projected.issue_priority,
- (cardinality($4::text[]) = 0 OR issue_status = ANY($4::text[])) AS status_match,
- (cardinality($5::text[]) = 0 OR issue_priority = ANY($5::text[])) AS priority_match,
- (cardinality($6::text[]) = 0 OR actor = ANY($6::text[])) AS actor_match,
- (NOT $7::boolean OR NOT read) AS read_match
+), selected AS (
+ SELECT projected.id, projected.created_at, projected.issue_status, projected.issue_priority
FROM projected
-)
-, selected AS (
- SELECT id, issue_id, created_at, read, actor, issue_status, issue_priority, status_match, priority_match, actor_match, read_match FROM matched
- WHERE status_match AND priority_match AND actor_match AND read_match
- AND ($8::timestamptz IS NULL OR
- (created_at, id) < ($8::timestamptz, $9::uuid))
+ WHERE (cardinality($8::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (issue_status = ANY($8::text[])) <> ('status' = ANY($5::text[]))))
+ AND (cardinality($9::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (issue_priority = ANY($9::text[])) <> ('priority' = ANY($5::text[]))))
+ AND (cardinality($10::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (project_key = ANY($10::text[])) <> ('project' = ANY($5::text[]))))
+ AND (cardinality($11::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (assignee_key = ANY($11::text[])) <> ('assignee' = ANY($5::text[]))))
+ AND (cardinality($12::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (label_ids && $12::text[]) <> ('label' = ANY($5::text[]))))
+ AND (cardinality($13::text[]) = 0 OR (issue_ref IS NOT NULL AND COALESCE(
+ ('overdue' = ANY($13::text[]) AND due_date < $14::date)
+ OR ('today' = ANY($13::text[]) AND due_date = $14::date)
+ OR ('this_week' = ANY($13::text[])
+ AND due_date >= $14::date - (EXTRACT(ISODOW FROM $14::date)::int - 1)
+ AND due_date < $14::date - (EXTRACT(ISODOW FROM $14::date)::int - 1) + 7)
+ OR ('next_7_days' = ANY($13::text[])
+ AND due_date >= $14::date AND due_date < $14::date + 7)
+ OR ('none' = ANY($13::text[]) AND due_date IS NULL), false)
+ <> ('dueDate' = ANY($5::text[]))))
+ AND (NOT $15::boolean OR NOT read)
+ AND ($16::timestamptz IS NULL OR
+ (created_at, id) < ($16::timestamptz, $17::uuid))
ORDER BY created_at DESC, id DESC
- LIMIT $10::int
+ LIMIT $18::int
)
SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section, selected.issue_status, selected.issue_priority,
- COALESCE(anchor.comment_id, '')::text AS comment_id
+ iss.project_id AS issue_project_id,
+ iss.assignee_type AS issue_assignee_type,
+ iss.assignee_id AS issue_assignee_id,
+ iss.due_date AS issue_due_date,
+ ARRAY(SELECT il.label_id::text FROM issue_to_label il
+ WHERE iss.id IS NOT NULL AND il.issue_id = iss.id
+ ORDER BY il.label_id)::text[] AS issue_label_ids,
+ -- The notification's own comment wins: a filter can pick an older row
+ -- (a mention of C1) under a newer comment (C2). The group's newest
+ -- anchor only fills rows that point at no comment.
+ COALESCE(NULLIF(i.details->>'comment_id', ''), anchor.comment_id, '')::text AS comment_id
FROM selected
JOIN inbox_item i ON i.id = selected.id
+LEFT JOIN issue iss ON iss.id = i.issue_id AND iss.workspace_id = i.workspace_id
LEFT JOIN LATERAL (
SELECT a.details->>'comment_id' AS comment_id
FROM inbox_item a
@@ -162,34 +304,60 @@ ORDER BY i.created_at DESC, i.id DESC
`
type ListArchivedInboxPageParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- RecipientID pgtype.UUID `json:"recipient_id"`
- GroupID pgtype.UUID `json:"group_id"`
- Statuses []string `json:"statuses"`
- Priorities []string `json:"priorities"`
- Actors []string `json:"actors"`
- UnreadOnly bool `json:"unread_only"`
- BeforeTime pgtype.Timestamptz `json:"before_time"`
- BeforeID pgtype.UUID `json:"before_id"`
- PageLimit int32 `json:"page_limit"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RecipientID pgtype.UUID `json:"recipient_id"`
+ GroupID pgtype.UUID `json:"group_id"`
+ Types []string `json:"types"`
+ Negated []string `json:"negated"`
+ Actors []string `json:"actors"`
+ ReceivedAfter pgtype.Timestamptz `json:"received_after"`
+ Statuses []string `json:"statuses"`
+ Priorities []string `json:"priorities"`
+ Projects []string `json:"projects"`
+ Assignees []string `json:"assignees"`
+ Labels []string `json:"labels"`
+ DueDates []string `json:"due_dates"`
+ Today pgtype.Date `json:"today"`
+ UnreadOnly bool `json:"unread_only"`
+ BeforeTime pgtype.Timestamptz `json:"before_time"`
+ BeforeID pgtype.UUID `json:"before_id"`
+ PageLimit int32 `json:"page_limit"`
}
type ListArchivedInboxPageRow struct {
- InboxItem InboxItem `json:"inbox_item"`
- IssueStatus pgtype.Text `json:"issue_status"`
- IssuePriority pgtype.Text `json:"issue_priority"`
- CommentID string `json:"comment_id"`
+ InboxItem InboxItem `json:"inbox_item"`
+ IssueStatus pgtype.Text `json:"issue_status"`
+ IssuePriority pgtype.Text `json:"issue_priority"`
+ IssueProjectID pgtype.UUID `json:"issue_project_id"`
+ IssueAssigneeType pgtype.Text `json:"issue_assignee_type"`
+ IssueAssigneeID pgtype.UUID `json:"issue_assignee_id"`
+ IssueDueDate pgtype.Date `json:"issue_due_date"`
+ IssueLabelIds []string `json:"issue_label_ids"`
+ CommentID string `json:"comment_id"`
}
+// Archived inbox filtering mirrors filterInboxItems (packages/core/inbox):
+// notification filters (type, sender, received) pick each group's newest
+// MATCHING notification, which is the row the list renders; issue filters and
+// "unread" then test that group. Issue filters never match a notification
+// without an issue, "is not" included. Type groups mirror INBOX_TYPE_GROUPS.
// Select narrow group representatives before loading bodies or comment anchors.
func (q *Queries) ListArchivedInboxPage(ctx context.Context, arg ListArchivedInboxPageParams) ([]ListArchivedInboxPageRow, error) {
rows, err := q.db.Query(ctx, listArchivedInboxPage,
arg.WorkspaceID,
arg.RecipientID,
arg.GroupID,
+ arg.Types,
+ arg.Negated,
+ arg.Actors,
+ arg.ReceivedAfter,
arg.Statuses,
arg.Priorities,
- arg.Actors,
+ arg.Projects,
+ arg.Assignees,
+ arg.Labels,
+ arg.DueDates,
+ arg.Today,
arg.UnreadOnly,
arg.BeforeTime,
arg.BeforeID,
@@ -221,6 +389,11 @@ func (q *Queries) ListArchivedInboxPage(ctx context.Context, arg ListArchivedInb
&i.InboxItem.Section,
&i.IssueStatus,
&i.IssuePriority,
+ &i.IssueProjectID,
+ &i.IssueAssigneeType,
+ &i.IssueAssigneeID,
+ &i.IssueDueDate,
+ &i.IssueLabelIds,
&i.CommentID,
); err != nil {
return nil, err
diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sql
index 6a6786dbce..860417e320 100644
--- a/server/pkg/db/queries/inbox.sql
+++ b/server/pkg/db/queries/inbox.sql
@@ -1,7 +1,17 @@
-- name: ListInboxItems :many
+-- The issue projections feed the inbox filters. Keep this column list
+-- identical to ListArchivedInboxItems: the handler converts one row type into
+-- the other.
SELECT i.*,
iss.status AS issue_status,
- iss.priority AS issue_priority
+ iss.priority AS issue_priority,
+ iss.project_id AS issue_project_id,
+ iss.assignee_type AS issue_assignee_type,
+ iss.assignee_id AS issue_assignee_id,
+ iss.due_date AS issue_due_date,
+ ARRAY(SELECT il.label_id::text FROM issue_to_label il
+ WHERE iss.id IS NOT NULL AND il.issue_id = iss.id
+ ORDER BY il.label_id)::text[] AS issue_label_ids
FROM inbox_item i
LEFT JOIN issue iss ON iss.id = i.issue_id
WHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3 AND i.archived = false
@@ -75,7 +85,14 @@ WITH eligible_archived AS MATERIALIZED (
)
SELECT i.*,
iss.status AS issue_status,
- iss.priority AS issue_priority
+ iss.priority AS issue_priority,
+ iss.project_id AS issue_project_id,
+ iss.assignee_type AS issue_assignee_type,
+ iss.assignee_id AS issue_assignee_id,
+ iss.due_date AS issue_due_date,
+ ARRAY(SELECT il.label_id::text FROM issue_to_label il
+ WHERE iss.id IS NOT NULL AND il.issue_id = iss.id
+ ORDER BY il.label_id)::text[] AS issue_label_ids
FROM inbox_item i
JOIN selected_ids selected ON selected.id = i.id
LEFT JOIN issue iss ON iss.id = i.issue_id
diff --git a/server/pkg/db/queries/inbox_archive.sql b/server/pkg/db/queries/inbox_archive.sql
index ac56469558..7f6f7b1b5d 100644
--- a/server/pkg/db/queries/inbox_archive.sql
+++ b/server/pkg/db/queries/inbox_archive.sql
@@ -1,8 +1,22 @@
+-- Archived inbox filtering mirrors filterInboxItems (packages/core/inbox):
+-- notification filters (type, sender, received) pick each group's newest
+-- MATCHING notification, which is the row the list renders; issue filters and
+-- "unread" then test that group. Issue filters never match a notification
+-- without an issue, "is not" included. Type groups mirror INBOX_TYPE_GROUPS.
+
-- name: ListArchivedInboxPage :many
-- Select narrow group representatives before loading bodies or comment anchors.
-WITH newest AS MATERIALIZED (
- SELECT DISTINCT ON (COALESCE(i.issue_id, i.id))
- i.id, i.issue_id, i.created_at, i.read,
+WITH base AS MATERIALIZED (
+ SELECT i.id, i.issue_id, COALESCE(i.issue_id, i.id) AS group_id, i.created_at, i.read,
+ CASE
+ WHEN i.type = 'mentioned' THEN 'mention'
+ WHEN i.type IN ('new_comment', 'reaction_added') THEN 'comment'
+ WHEN i.type IN ('issue_assigned', 'unassigned', 'assignee_changed', 'issue_subscribed') THEN 'assign'
+ WHEN i.type = 'review_requested' THEN 'review'
+ WHEN i.type IN ('status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'
+ WHEN i.type IN ('task_completed', 'task_failed', 'agent_blocked', 'agent_completed') THEN 'run'
+ ELSE 'system'
+ END AS type_group,
CASE WHEN i.actor_type = 'system' THEN 'system'
ELSE i.actor_type || ':' || i.actor_id::text END AS actor
FROM inbox_item i
@@ -19,32 +33,71 @@ WITH newest AS MATERIALIZED (
AND active.recipient_id = i.recipient_id
AND active.issue_id = i.issue_id AND active.archived = false
))
- ORDER BY COALESCE(i.issue_id, i.id), i.created_at DESC, i.id DESC
+), newest AS (
+ SELECT DISTINCT ON (group_id) base.*
+ FROM base
+ WHERE (cardinality(sqlc.arg(types)::text[]) = 0
+ OR (type_group = ANY(sqlc.arg(types)::text[])) <> ('type' = ANY(sqlc.arg(negated)::text[])))
+ AND (cardinality(sqlc.arg(actors)::text[]) = 0
+ OR COALESCE(actor = ANY(sqlc.arg(actors)::text[]), false) <> ('actor' = ANY(sqlc.arg(negated)::text[])))
+ AND (sqlc.narg(received_after)::timestamptz IS NULL OR created_at >= sqlc.narg(received_after)::timestamptz)
+ ORDER BY group_id, created_at DESC, id DESC
), projected AS (
- SELECT newest.*, iss.status AS issue_status, iss.priority AS issue_priority
+ SELECT newest.id, newest.created_at, newest.read,
+ iss.id AS issue_ref, iss.status AS issue_status, iss.priority AS issue_priority,
+ COALESCE(iss.project_id::text, 'none') AS project_key,
+ CASE WHEN iss.assignee_id IS NULL THEN 'none'
+ ELSE iss.assignee_type || ':' || iss.assignee_id::text END AS assignee_key,
+ iss.due_date,
+ ARRAY(SELECT il.label_id::text FROM issue_to_label il
+ WHERE iss.id IS NOT NULL AND il.issue_id = iss.id)::text[] AS label_ids
FROM newest
LEFT JOIN issue iss ON iss.id = newest.issue_id
AND iss.workspace_id = sqlc.arg(workspace_id)::uuid
-), matched AS (
- SELECT projected.*,
- (cardinality(sqlc.arg(statuses)::text[]) = 0 OR issue_status = ANY(sqlc.arg(statuses)::text[])) AS status_match,
- (cardinality(sqlc.arg(priorities)::text[]) = 0 OR issue_priority = ANY(sqlc.arg(priorities)::text[])) AS priority_match,
- (cardinality(sqlc.arg(actors)::text[]) = 0 OR actor = ANY(sqlc.arg(actors)::text[])) AS actor_match,
- (NOT sqlc.arg(unread_only)::boolean OR NOT read) AS read_match
+), selected AS (
+ SELECT projected.id, projected.created_at, projected.issue_status, projected.issue_priority
FROM projected
-)
-, selected AS (
- SELECT * FROM matched
- WHERE status_match AND priority_match AND actor_match AND read_match
+ WHERE (cardinality(sqlc.arg(statuses)::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (issue_status = ANY(sqlc.arg(statuses)::text[])) <> ('status' = ANY(sqlc.arg(negated)::text[]))))
+ AND (cardinality(sqlc.arg(priorities)::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (issue_priority = ANY(sqlc.arg(priorities)::text[])) <> ('priority' = ANY(sqlc.arg(negated)::text[]))))
+ AND (cardinality(sqlc.arg(projects)::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (project_key = ANY(sqlc.arg(projects)::text[])) <> ('project' = ANY(sqlc.arg(negated)::text[]))))
+ AND (cardinality(sqlc.arg(assignees)::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (assignee_key = ANY(sqlc.arg(assignees)::text[])) <> ('assignee' = ANY(sqlc.arg(negated)::text[]))))
+ AND (cardinality(sqlc.arg(labels)::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (label_ids && sqlc.arg(labels)::text[]) <> ('label' = ANY(sqlc.arg(negated)::text[]))))
+ AND (cardinality(sqlc.arg(due_dates)::text[]) = 0 OR (issue_ref IS NOT NULL AND COALESCE(
+ ('overdue' = ANY(sqlc.arg(due_dates)::text[]) AND due_date < sqlc.narg(today)::date)
+ OR ('today' = ANY(sqlc.arg(due_dates)::text[]) AND due_date = sqlc.narg(today)::date)
+ OR ('this_week' = ANY(sqlc.arg(due_dates)::text[])
+ AND due_date >= sqlc.narg(today)::date - (EXTRACT(ISODOW FROM sqlc.narg(today)::date)::int - 1)
+ AND due_date < sqlc.narg(today)::date - (EXTRACT(ISODOW FROM sqlc.narg(today)::date)::int - 1) + 7)
+ OR ('next_7_days' = ANY(sqlc.arg(due_dates)::text[])
+ AND due_date >= sqlc.narg(today)::date AND due_date < sqlc.narg(today)::date + 7)
+ OR ('none' = ANY(sqlc.arg(due_dates)::text[]) AND due_date IS NULL), false)
+ <> ('dueDate' = ANY(sqlc.arg(negated)::text[]))))
+ AND (NOT sqlc.arg(unread_only)::boolean OR NOT read)
AND (sqlc.narg(before_time)::timestamptz IS NULL OR
(created_at, id) < (sqlc.narg(before_time)::timestamptz, sqlc.narg(before_id)::uuid))
ORDER BY created_at DESC, id DESC
LIMIT sqlc.arg(page_limit)::int
)
SELECT sqlc.embed(i), selected.issue_status, selected.issue_priority,
- COALESCE(anchor.comment_id, '')::text AS comment_id
+ iss.project_id AS issue_project_id,
+ iss.assignee_type AS issue_assignee_type,
+ iss.assignee_id AS issue_assignee_id,
+ iss.due_date AS issue_due_date,
+ ARRAY(SELECT il.label_id::text FROM issue_to_label il
+ WHERE iss.id IS NOT NULL AND il.issue_id = iss.id
+ ORDER BY il.label_id)::text[] AS issue_label_ids,
+ -- The notification's own comment wins: a filter can pick an older row
+ -- (a mention of C1) under a newer comment (C2). The group's newest
+ -- anchor only fills rows that point at no comment.
+ COALESCE(NULLIF(i.details->>'comment_id', ''), anchor.comment_id, '')::text AS comment_id
FROM selected
JOIN inbox_item i ON i.id = selected.id
+LEFT JOIN issue iss ON iss.id = i.issue_id AND iss.workspace_id = i.workspace_id
LEFT JOIN LATERAL (
SELECT a.details->>'comment_id' AS comment_id
FROM inbox_item a
@@ -57,10 +110,20 @@ LEFT JOIN LATERAL (
ORDER BY i.created_at DESC, i.id DESC;
-- name: ArchivedInboxFacets :many
--- Select narrow group representatives before loading bodies or comment anchors.
-WITH newest AS MATERIALIZED (
- SELECT DISTINCT ON (COALESCE(i.issue_id, i.id))
- i.id, i.issue_id, i.created_at, i.read,
+-- Every count ignores its own dimension, so it says how many rows selecting
+-- that value alone would show. Type and sender counts pick the newest
+-- notification of that value in each group, the row selecting it renders.
+WITH base AS MATERIALIZED (
+ SELECT i.id, i.issue_id, COALESCE(i.issue_id, i.id) AS group_id, i.created_at, i.read,
+ CASE
+ WHEN i.type = 'mentioned' THEN 'mention'
+ WHEN i.type IN ('new_comment', 'reaction_added') THEN 'comment'
+ WHEN i.type IN ('issue_assigned', 'unassigned', 'assignee_changed', 'issue_subscribed') THEN 'assign'
+ WHEN i.type = 'review_requested' THEN 'review'
+ WHEN i.type IN ('status_changed', 'priority_changed', 'start_date_changed', 'due_date_changed', 'children_done') THEN 'change'
+ WHEN i.type IN ('task_completed', 'task_failed', 'agent_blocked', 'agent_completed') THEN 'run'
+ ELSE 'system'
+ END AS type_group,
CASE WHEN i.actor_type = 'system' THEN 'system'
ELSE i.actor_type || ':' || i.actor_id::text END AS actor
FROM inbox_item i
@@ -75,32 +138,100 @@ WITH newest AS MATERIALIZED (
AND active.recipient_id = i.recipient_id
AND active.issue_id = i.issue_id AND active.archived = false
))
- ORDER BY COALESCE(i.issue_id, i.id), i.created_at DESC, i.id DESC
+), notification_match AS MATERIALIZED (
+ SELECT base.*,
+ (cardinality(sqlc.arg(types)::text[]) = 0
+ OR (type_group = ANY(sqlc.arg(types)::text[])) <> ('type' = ANY(sqlc.arg(negated)::text[]))) AS type_match,
+ (cardinality(sqlc.arg(actors)::text[]) = 0
+ OR COALESCE(actor = ANY(sqlc.arg(actors)::text[]), false) <> ('actor' = ANY(sqlc.arg(negated)::text[]))) AS actor_match,
+ (sqlc.narg(received_after)::timestamptz IS NULL OR created_at >= sqlc.narg(received_after)::timestamptz) AS received_match
+ FROM base
+), groups AS (
+ SELECT DISTINCT group_id, issue_id FROM base
), projected AS (
- SELECT newest.*, iss.status AS issue_status, iss.priority AS issue_priority
- FROM newest
- LEFT JOIN issue iss ON iss.id = newest.issue_id
+ SELECT groups.group_id,
+ iss.id AS issue_ref, iss.status AS issue_status, iss.priority AS issue_priority,
+ COALESCE(iss.project_id::text, 'none') AS project_key,
+ CASE WHEN iss.assignee_id IS NULL THEN 'none'
+ ELSE iss.assignee_type || ':' || iss.assignee_id::text END AS assignee_key,
+ iss.due_date,
+ ARRAY(SELECT il.label_id::text FROM issue_to_label il
+ WHERE iss.id IS NOT NULL AND il.issue_id = iss.id)::text[] AS label_ids
+ FROM groups
+ LEFT JOIN issue iss ON iss.id = groups.issue_id
AND iss.workspace_id = sqlc.arg(workspace_id)::uuid
-), matched AS (
+), issue_match AS MATERIALIZED (
SELECT projected.*,
- (cardinality(sqlc.arg(statuses)::text[]) = 0 OR issue_status = ANY(sqlc.arg(statuses)::text[])) AS status_match,
- (cardinality(sqlc.arg(priorities)::text[]) = 0 OR issue_priority = ANY(sqlc.arg(priorities)::text[])) AS priority_match,
- (cardinality(sqlc.arg(actors)::text[]) = 0 OR actor = ANY(sqlc.arg(actors)::text[])) AS actor_match,
- (NOT sqlc.arg(unread_only)::boolean OR NOT read) AS read_match
+ (cardinality(sqlc.arg(statuses)::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (issue_status = ANY(sqlc.arg(statuses)::text[])) <> ('status' = ANY(sqlc.arg(negated)::text[])))) AS status_match,
+ (cardinality(sqlc.arg(priorities)::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (issue_priority = ANY(sqlc.arg(priorities)::text[])) <> ('priority' = ANY(sqlc.arg(negated)::text[])))) AS priority_match,
+ (cardinality(sqlc.arg(projects)::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (project_key = ANY(sqlc.arg(projects)::text[])) <> ('project' = ANY(sqlc.arg(negated)::text[])))) AS project_match,
+ (cardinality(sqlc.arg(assignees)::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (assignee_key = ANY(sqlc.arg(assignees)::text[])) <> ('assignee' = ANY(sqlc.arg(negated)::text[])))) AS assignee_match,
+ (cardinality(sqlc.arg(labels)::text[]) = 0 OR (issue_ref IS NOT NULL
+ AND (label_ids && sqlc.arg(labels)::text[]) <> ('label' = ANY(sqlc.arg(negated)::text[])))) AS label_match,
+ (cardinality(sqlc.arg(due_dates)::text[]) = 0 OR (issue_ref IS NOT NULL AND COALESCE(
+ ('overdue' = ANY(sqlc.arg(due_dates)::text[]) AND due_date < sqlc.narg(today)::date)
+ OR ('today' = ANY(sqlc.arg(due_dates)::text[]) AND due_date = sqlc.narg(today)::date)
+ OR ('this_week' = ANY(sqlc.arg(due_dates)::text[])
+ AND due_date >= sqlc.narg(today)::date - (EXTRACT(ISODOW FROM sqlc.narg(today)::date)::int - 1)
+ AND due_date < sqlc.narg(today)::date - (EXTRACT(ISODOW FROM sqlc.narg(today)::date)::int - 1) + 7)
+ OR ('next_7_days' = ANY(sqlc.arg(due_dates)::text[])
+ AND due_date >= sqlc.narg(today)::date AND due_date < sqlc.narg(today)::date + 7)
+ OR ('none' = ANY(sqlc.arg(due_dates)::text[]) AND due_date IS NULL), false)
+ <> ('dueDate' = ANY(sqlc.arg(negated)::text[])))) AS due_match
FROM projected
+), reps AS (
+ SELECT DISTINCT ON (group_id) group_id, read
+ FROM notification_match
+ WHERE type_match AND actor_match AND received_match
+ ORDER BY group_id, created_at DESC, id DESC
+), matched AS (
+ SELECT issue_match.*, (NOT sqlc.arg(unread_only)::boolean OR NOT reps.read) AS read_match, reps.read
+ FROM reps JOIN issue_match USING (group_id)
+), type_reps AS (
+ SELECT DISTINCT ON (group_id, type_group) group_id, type_group, read
+ FROM notification_match
+ WHERE actor_match AND received_match
+ ORDER BY group_id, type_group, created_at DESC, id DESC
+), actor_reps AS (
+ SELECT DISTINCT ON (group_id, actor) group_id, actor, read
+ FROM notification_match
+ WHERE type_match AND received_match AND actor IS NOT NULL
+ ORDER BY group_id, actor, created_at DESC, id DESC
)
SELECT 'statuses'::text AS dimension, issue_status::text AS key,
- count(*) FILTER (WHERE priority_match AND actor_match AND read_match)::bigint AS count
+ count(*) FILTER (WHERE priority_match AND project_match AND assignee_match AND label_match AND due_match AND read_match)::bigint AS count
FROM matched WHERE issue_status IS NOT NULL GROUP BY issue_status
UNION ALL
SELECT 'priorities'::text, issue_priority::text,
- count(*) FILTER (WHERE status_match AND actor_match AND read_match)::bigint
+ count(*) FILTER (WHERE status_match AND project_match AND assignee_match AND label_match AND due_match AND read_match)::bigint
FROM matched WHERE issue_priority IS NOT NULL GROUP BY issue_priority
UNION ALL
-SELECT 'actors'::text, actor::text,
- count(*) FILTER (WHERE status_match AND priority_match AND read_match)::bigint
-FROM matched WHERE actor IS NOT NULL GROUP BY actor
+SELECT 'projects'::text, project_key::text,
+ count(*) FILTER (WHERE status_match AND priority_match AND assignee_match AND label_match AND due_match AND read_match)::bigint
+FROM matched WHERE issue_ref IS NOT NULL GROUP BY project_key
+UNION ALL
+SELECT 'assignees'::text, assignee_key::text,
+ count(*) FILTER (WHERE status_match AND priority_match AND project_match AND label_match AND due_match AND read_match)::bigint
+FROM matched WHERE issue_ref IS NOT NULL GROUP BY assignee_key
+UNION ALL
+SELECT 'labels'::text, label::text,
+ count(*) FILTER (WHERE status_match AND priority_match AND project_match AND assignee_match AND due_match AND read_match)::bigint
+FROM matched, unnest(label_ids) AS label GROUP BY label
+UNION ALL
+SELECT 'types'::text, type_reps.type_group::text,
+ count(*) FILTER (WHERE status_match AND priority_match AND project_match AND assignee_match AND label_match AND due_match
+ AND (NOT sqlc.arg(unread_only)::boolean OR NOT type_reps.read))::bigint
+FROM type_reps JOIN issue_match USING (group_id) GROUP BY type_reps.type_group
+UNION ALL
+SELECT 'actors'::text, actor_reps.actor::text,
+ count(*) FILTER (WHERE status_match AND priority_match AND project_match AND assignee_match AND label_match AND due_match
+ AND (NOT sqlc.arg(unread_only)::boolean OR NOT actor_reps.read))::bigint
+FROM actor_reps JOIN issue_match USING (group_id) GROUP BY actor_reps.actor
UNION ALL
SELECT 'unread'::text, 'unread'::text,
- count(*) FILTER (WHERE status_match AND priority_match AND actor_match AND NOT read)::bigint
+ count(*) FILTER (WHERE status_match AND priority_match AND project_match AND assignee_match AND label_match AND due_match AND NOT read)::bigint
FROM matched;