Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7422: paginate archived inbox and load it on demand (#8471)
Jiayuan Zhang3fe16b8fcb5f
diff --git a/apps/docs/content/docs/inbox.ja.mdx b/apps/docs/content/docs/inbox.ja.mdxindex 86c454f1fe..3c5954ffaa 100644--- a/apps/docs/content/docs/inbox.ja.mdx+++ b/apps/docs/content/docs/inbox.ja.mdx@@ -56,6 +56,8 @@ import { Callout } from "fumadocs-ui/components/callout";- `done` または `cancelled` のタスクの通知をアーカイブする- 「アーカイブ済み」を開いて通知を復元する+インボックス下部の**アーカイブ済み**を開くと、スクロールに合わせて過去の通知が読み込まれます。フィルターは、まだ読み込まれていない通知も含め、アーカイブ全体に適用されます。+## 通知タイプの調整**設定 → 通知**では、次のグループを個別にオン・オフできます。diff --git a/apps/docs/content/docs/inbox.ko.mdx b/apps/docs/content/docs/inbox.ko.mdxindex 1f584873e9..7a5180ace5 100644--- a/apps/docs/content/docs/inbox.ko.mdx+++ b/apps/docs/content/docs/inbox.ko.mdx@@ -56,6 +56,8 @@ import { Callout } from "fumadocs-ui/components/callout";- 상태가 `done` 또는 `cancelled`인 태스크 알림 보관- "보관됨"을 열고 특정 알림 복원+인박스 하단의 **보관됨**을 열고 아래로 스크롤하면 이전 알림이 계속 불러와집니다. 필터는 아직 불러오지 않은 알림을 포함한 전체 보관 기록에 적용됩니다.+## 알림 유형 조정**설정 → 알림**을 열면 다음 유형을 각각 켜거나 끌 수 있습니다.diff --git a/apps/docs/content/docs/inbox.mdx b/apps/docs/content/docs/inbox.mdxindex 9dc50e9454..4558be36ca 100644--- a/apps/docs/content/docs/inbox.mdx+++ b/apps/docs/content/docs/inbox.mdx@@ -56,6 +56,8 @@ From the inbox menu you can also:- archive notifications for issues in `done` or `cancelled`;- open Archived and restore a notification.+Open **Archived** at the bottom of the inbox to browse older notifications. More records load as you scroll. Filters apply to the entire archive, including records that have not loaded yet.+## Tune notification typesOpen **Settings → Notifications** to toggle each group separately:diff --git a/apps/docs/content/docs/inbox.zh.mdx b/apps/docs/content/docs/inbox.zh.mdxindex f29f40e545..6bfe2027c9 100644--- a/apps/docs/content/docs/inbox.zh.mdx+++ b/apps/docs/content/docs/inbox.zh.mdx@@ -56,6 +56,8 @@ import { Callout } from "fumadocs-ui/components/callout";- 归档状态为 `done` 或 `cancelled` 的任务通知;- 打开"已归档"并恢复某条通知。+从收件箱底部打开**已归档**,向下滚动可继续加载更早的通知。筛选覆盖全部归档记录,包括尚未加载的记录。+## 调整通知类型打开**设置 → 通知**,可以分别开关:diff --git a/packages/core/api/archived-inbox.test.ts b/packages/core/api/archived-inbox.test.tsnew file mode 100644index 0000000000..29ad14f51d--- /dev/null+++ b/packages/core/api/archived-inbox.test.ts@@ -0,0 +1,51 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from "vitest";+import { ApiClient } from "./client";+import { EMPTY_INBOX_FILTERS } from "../inbox/filter-store";++afterEach(() => vi.unstubAllGlobals());++function respond(body: unknown) {+ const fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify(body), { status: 200 }));+ vi.stubGlobal("fetch", fetch);+ return fetch;+}++describe("archived inbox API", () => {+ it("sends cursor, lookup and every 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");+ await expect(api.listArchivedInboxPage({+ statuses: ["in_review"], priorities: ["high"], actors: ["system"], unreadOnly: true,+ }, { 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",+ });+ });++ it.each([+ {}, [], { items: [] }, { items: "wrong", next_cursor: null, has_more: false },+ { items: [], next_cursor: null, has_more: true },+ { items: [], next_cursor: "next", has_more: true },+ { items: [{ id: "broken" }], next_cursor: null, has_more: false },+ ])("rejects malformed pages instead of presenting an empty archive: %j", async (body) => {+ respond(body);+ await expect(new ApiClient("https://api.example.test").listArchivedInboxPage(EMPTY_INBOX_FILTERS))+ .rejects.toThrow("Invalid archived inbox page response");+ });++ 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");+ await expect(api.getArchivedInboxFacets(EMPTY_INBOX_FILTERS)).resolves.toEqual({+ statuses: { in_review: 2 }, priorities: {}, actors: { system: 0 }, unreadCount: 1,+ });+ for (const body of [{}, { statuses: {}, priorities: {}, actors: {}, unread_count: -1 }]) {+ respond(body);+ await expect(api.getArchivedInboxFacets(EMPTY_INBOX_FILTERS)).rejects.toThrow("Invalid archived inbox facets response");+ }+ });+});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex fbc13b094e..f257ad9827 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1,3 +1,5 @@+import type { InboxFilters } from "../inbox/filter-store";+import type { ArchivedInboxPage, ArchivedInboxFacets } from "../types/inbox";import { configStore } from "../config";import type {Issue,@@ -378,6 +380,8 @@ import {InboxUnreadSummarySchema,EMPTY_INBOX_UNREAD_SUMMARY,InboxItemListSchema,+ ArchivedInboxPageSchema,+ ArchivedInboxFacetsSchema,EMPTY_INBOX_ITEMS,NotificationPreferenceResponseSchema,EMPTY_NOTIFICATION_PREFERENCE_RESPONSE,@@ -2488,6 +2492,39 @@ export class ApiClient {});}+ private archivedInboxParams(filters: InboxFilters): 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;+ }++ async listArchivedInboxPage(filters: InboxFilters, options: {+ cursor?: string | null; groupId?: string; signal?: AbortSignal;+ } = {}): Promise<ArchivedInboxPage> {+ const params = this.archivedInboxParams(filters);+ params.set("limit", "50");+ if (options.cursor) params.set("cursor", options.cursor);+ if (options.groupId) params.set("group_id", options.groupId);+ const raw = await this.fetch<unknown>(`/api/inbox/archived/page?${params}`, { signal: options.signal });+ const page = parseWithFallback<ArchivedInboxPage | null>(raw, ArchivedInboxPageSchema, null, {+ endpoint: "GET /api/inbox/archived/page",+ });+ if (!page) throw new Error("Invalid archived inbox page response");+ return page;+ }++ async getArchivedInboxFacets(filters: InboxFilters, signal?: AbortSignal): Promise<ArchivedInboxFacets> {+ const raw = await this.fetch<unknown>(`/api/inbox/archived/facets?${this.archivedInboxParams(filters)}`, { signal });+ const facets = parseWithFallback<ArchivedInboxFacets | null>(raw, ArchivedInboxFacetsSchema, null, {+ endpoint: "GET /api/inbox/archived/facets",+ });+ if (!facets) throw new Error("Invalid archived inbox facets response");+ return facets;+ }+async unarchiveInbox(id: string): Promise<InboxItem> {return this.fetch(`/api/inbox/${id}/unarchive`, { method: "POST" });}diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex a05ffdfc39..ea01fbd2db 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2488,6 +2488,24 @@ export const InboxItemListSchema = z.array(.loose(),);+export const ArchivedInboxPageSchema = z.object({+ items: InboxItemListSchema,+ next_cursor: z.string().min(1).nullable(),+ has_more: z.boolean(),+}).refine((page) => page.has_more === (page.next_cursor !== null) &&+ (!page.has_more || page.items.length > 0))+ .transform((page) => ({ items: page.items, nextCursor: page.next_cursor, hasMore: page.has_more }));++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()),+ unread_count: z.number().int().nonnegative(),+}).transform((facets) => ({+ statuses: facets.statuses, priorities: facets.priorities,+ actors: facets.actors, unreadCount: facets.unread_count,+}));+export const EMPTY_INBOX_ITEMS: InboxItem[] = [];// ---------------------------------------------------------------------------diff --git a/packages/core/inbox/mutations.ts b/packages/core/inbox/mutations.tsindex 0ba3e85ac4..0c6b2880e4 100644--- a/packages/core/inbox/mutations.ts+++ b/packages/core/inbox/mutations.ts@@ -1,7 +1,7 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import type { QueryClient } from "@tanstack/react-query";import { api } from "../api";-import { inboxKeys } from "./queries";+import { inboxKeys, mapArchivedInboxCache, patchArchivedInboxCaches, type ArchivedInboxCache } from "./queries";import { onInboxInvalidate, onInboxSummaryInvalidate } from "./ws-updaters";import { useWorkspaceId } from "../hooks";import type { InboxItem } from "../types";@@ -50,19 +50,18 @@ export function useMarkInboxRead() {onMutate: async (id) => {await qc.cancelQueries({ queryKey: inboxKeys.all(wsId) });const prev = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));- const prevArchived = qc.getQueryData<InboxItem[]>(inboxKeys.archived(wsId));const markRead = (old: InboxItem[] | undefined) =>old?.map((item) => (item.id === id ? { ...item, read: true } : item));qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), markRead);// Opening a notification from the archived sub-view marks it read too —// patch that cache as well, or its unread dot would sit there until the// next refetch.- qc.setQueryData<InboxItem[]>(inboxKeys.archived(wsId), markRead);+ const prevArchived = patchArchivedInboxCaches(qc, wsId, (items) => markRead(items) ?? items);return { prev, prevArchived };},onError: (_err, _id, ctx) => {if (ctx?.prev) qc.setQueryData(inboxKeys.list(wsId), ctx.prev);- if (ctx?.prevArchived) qc.setQueryData(inboxKeys.archived(wsId), ctx.prevArchived);+ for (const [key, data] of ctx?.prevArchived ?? []) qc.setQueryData(key, data);},onSettled: () => {refreshInboxAfterWrite(qc, wsId);@@ -100,16 +99,15 @@ export function useMarkInboxUnread() {onMutate: async (id) => {await qc.cancelQueries({ queryKey: inboxKeys.all(wsId) });const prev = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));- const prevArchived = qc.getQueryData<InboxItem[]>(inboxKeys.archived(wsId));const markUnread = (old: InboxItem[] | undefined) =>old?.map((item) => (item.id === id ? { ...item, read: false } : item));qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), markUnread);- qc.setQueryData<InboxItem[]>(inboxKeys.archived(wsId), markUnread);+ const prevArchived = patchArchivedInboxCaches(qc, wsId, (items) => markUnread(items) ?? items);return { prev, prevArchived };},onError: (_err, _id, ctx) => {if (ctx?.prev) qc.setQueryData(inboxKeys.list(wsId), ctx.prev);- if (ctx?.prevArchived) qc.setQueryData(inboxKeys.archived(wsId), ctx.prevArchived);+ for (const [key, data] of ctx?.prevArchived ?? []) qc.setQueryData(key, data);},onSettled: () => {// The switcher dot must light again when the workspace goes back to@@ -166,23 +164,20 @@ export function useUnarchiveInbox() {mutationFn: (id: string) => api.unarchiveInbox(id),onMutate: async (id) => {await qc.cancelQueries({ queryKey: inboxKeys.archived(wsId) });- const prev = qc.getQueryData<InboxItem[]>(inboxKeys.archived(wsId));- // Restore every sibling for the same issue — the server unarchives the- // whole issue group, so the optimistic patch must too or the rest of the- // group would linger in the archived list until the refetch lands.- const target = prev?.find((i) => i.id === id);- const issueId = target?.issue_id;- qc.setQueryData<InboxItem[]>(inboxKeys.archived(wsId), (old) =>- old?.map((item) =>- item.id === id || (issueId && item.issue_id === issueId)- ? { ...item, archived: false }- : item,- ),- );+ // Resolve the group once across every page and deep-link cache.+ let issueId: string | null | undefined;+ for (const [, data] of qc.getQueriesData<ArchivedInboxCache>({ queryKey: inboxKeys.archived(wsId) })) {+ if (data) mapArchivedInboxCache(data, (items) => {+ issueId ??= items.find((item) => item.id === id)?.issue_id;+ return items;+ });+ }+ const prev = patchArchivedInboxCaches(qc, wsId, (items) => items.map((item) =>+ item.id === id || (issueId && item.issue_id === issueId) ? { ...item, archived: false } : item));return { prev };},onError: (_err, _id, ctx) => {- if (ctx?.prev) qc.setQueryData(inboxKeys.archived(wsId), ctx.prev);+ for (const [key, data] of ctx?.prev ?? []) qc.setQueryData(key, data);},onSettled: () => {// Both lists: the item moves from one to the other, and the unread badgediff --git a/packages/core/inbox/pagination.test.tsx b/packages/core/inbox/pagination.test.tsxnew file mode 100644index 0000000000..978d8e74e2--- /dev/null+++ b/packages/core/inbox/pagination.test.tsx@@ -0,0 +1,133 @@+// @vitest-environment jsdom+import { act, renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider, useInfiniteQuery, type InfiniteData } from "@tanstack/react-query";+import { describe, expect, it, vi } from "vitest";+import type { ReactNode } from "react";+import { setApiInstance } from "../api";+import type { ApiClient } from "../api/client";+import type { ArchivedInboxPage, InboxItem } from "../types";+import { issueChangedDims } from "../issues/surface/membership";+import { applyIssueChange, rollbackIssueChange, invalidateStaleListKeys } from "../issues/cache-coordinator";+import { EMPTY_INBOX_FILTERS } from "./filter-store";+import { archivedInboxPagesOptions, inboxKeys } from "./queries";+import { useUnarchiveInbox, useMarkInboxRead } from "./mutations";+import { onInboxNew, onInboxIssueDeleted, onInboxIssueStatusChanged } from "./ws-updaters";++vi.mock("../hooks", () => ({ useWorkspaceId: () => "ws" }));++function item(id: string): InboxItem {+ return { id, workspace_id: "ws", recipient_type: "member", recipient_id: "user", actor_type: "system", actor_id: null,+ type: "mentioned", severity: "info", issue_id: id, title: id, body: null, issue_status: "done", issue_priority: "high",+ read: false, archived: true, created_at: "2026-09-01T00:00:00Z", details: null };+}+const page = (items: InboxItem[], nextCursor: string | null = null): ArchivedInboxPage => ({ items, nextCursor, hasMore: !!nextCursor });+function setup() {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity }, mutations: { retry: false } } });+ const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={qc}>{children}</QueryClientProvider>;+ return { qc, wrapper };+}++describe("archived inbox pagination", () => {+ it("loads subsequent pages, preserves rows on failure, and retries the same cursor", async () => {+ const { qc, wrapper } = setup();+ const listArchivedInboxPage = vi.fn().mockResolvedValueOnce(page([item("first")], "next"))+ .mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce(page([item("second")]));+ setApiInstance({ listArchivedInboxPage } as unknown as ApiClient);+ const { result, unmount } = renderHook(() => useInfiniteQuery(archivedInboxPagesOptions("ws", EMPTY_INBOX_FILTERS)), { wrapper });+ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ await act(() => result.current.fetchNextPage());+ expect(result.current.data?.pages[0]?.items[0]?.id).toBe("first");+ await waitFor(() => expect(result.current.isFetchNextPageError).toBe(true));+ await act(() => result.current.fetchNextPage());+ await waitFor(() => expect(result.current.data?.pages).toHaveLength(2));+ expect(listArchivedInboxPage.mock.calls.slice(1).map((call) => call[1].cursor)).toEqual(["next", "next"]);+ expect(result.current.hasNextPage).toBe(false);+ unmount(); qc.clear();+ });++ it("marks unopened archives stale without fetching until the archive is opened", async () => {+ const { qc, wrapper } = setup();+ const listArchivedInboxPage = vi.fn(async () => page([item("archived")]));+ setApiInstance({ listArchivedInboxPage } as unknown as ApiClient);+ const { result, rerender, unmount } = renderHook(({ open }) => useInfiniteQuery({+ ...archivedInboxPagesOptions("ws", EMPTY_INBOX_FILTERS), enabled: open,+ }), { wrapper, initialProps: { open: false } });+ await act(() => onInboxNew(qc, "ws", item("new")));+ expect(listArchivedInboxPage).not.toHaveBeenCalled();+ rerender({ open: true });+ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(listArchivedInboxPage).toHaveBeenCalledOnce();+ unmount(); qc.clear();+ });++ it("patches and rolls back restore across pages, filters and deep links", async () => {+ const { qc, wrapper } = setup();+ const keys = [archivedInboxPagesOptions("ws", EMPTY_INBOX_FILTERS).queryKey,+ archivedInboxPagesOptions("ws", { ...EMPTY_INBOX_FILTERS, priorities: ["high"] }).queryKey];+ const initial: InfiniteData<ArchivedInboxPage> = { pages: [page([item("first")], "next"), page([item("target")])], pageParams: [null, "next"] };+ for (const key of keys) qc.setQueryData(key, initial);+ const lookupKey = [...inboxKeys.lookup("ws"), "target"];+ qc.setQueryData(lookupKey, page([item("target")]));+ let reject!: (reason: Error) => void;+ setApiInstance({ unarchiveInbox: () => new Promise((_resolve, fail) => { reject = fail; }) } as unknown as ApiClient);+ const { result, unmount } = renderHook(() => useUnarchiveInbox(), { wrapper });+ act(() => result.current.mutate("target"));+ await waitFor(() => expect(qc.getQueryData<ArchivedInboxPage>(lookupKey)?.items[0]?.archived).toBe(false));+ for (const key of keys) expect(qc.getQueryData<InfiniteData<ArchivedInboxPage>>(key)?.pages[1]?.items[0]?.archived).toBe(false);+ act(() => reject(new Error("restore failed")));+ await waitFor(() => expect(result.current.isError).toBe(true));+ for (const key of keys) expect(qc.getQueryData(key)).toEqual(initial);+ expect(qc.getQueryData<ArchivedInboxPage>(lookupKey)?.items[0]?.archived).toBe(true);+ unmount(); qc.clear();+ });++ it("rolls back issue projections across archive caches without fetching uncommitted state", () => {+ const { qc } = setup();+ const key = archivedInboxPagesOptions("ws", EMPTY_INBOX_FILTERS).queryKey;+ const initial = { pages: [page([item("target")])], pageParams: [null] };+ qc.setQueryData(key, initial);+ const result = applyIssueChange(qc, "ws", "target", { priority: "low" }, { changed: issueChangedDims({ priority: "low" }) });+ expect(qc.getQueryData<InfiniteData<ArchivedInboxPage>>(key)?.pages[0]?.items[0]?.issue_priority).toBe("low");+ expect(qc.getQueryState(key)?.isInvalidated).toBe(false);+ expect(result.staleKeys).toContainEqual(key);+ rollbackIssueChange(qc, "ws", "target", result);+ expect(qc.getQueryData(key)).toEqual(initial);+ qc.clear();+ });++ it("replaces a first page request that predates an issue projection change", async () => {+ const { qc, wrapper } = setup();+ let resolveOld!: (value: ArchivedInboxPage) => void;+ const listArchivedInboxPage = vi.fn()+ .mockImplementationOnce(() => new Promise<ArchivedInboxPage>((resolve) => { resolveOld = resolve; }))+ .mockResolvedValue(page([{ ...item("target"), issue_priority: "low" }]));+ setApiInstance({ listArchivedInboxPage } as unknown as ApiClient);+ const { result, unmount } = renderHook(() => useInfiniteQuery(archivedInboxPagesOptions("ws", EMPTY_INBOX_FILTERS)), { wrapper });+ await waitFor(() => expect(listArchivedInboxPage).toHaveBeenCalledOnce());+ act(() => {+ const change = applyIssueChange(qc, "ws", "target", { priority: "low" }, { changed: issueChangedDims({ priority: "low" }) });+ invalidateStaleListKeys(qc, change.staleKeys);+ });+ await waitFor(() => expect(listArchivedInboxPage).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(result.current.data?.pages[0]?.items[0]?.issue_priority).toBe("low"));+ await act(async () => resolveOld(page([item("target")])));+ expect(result.current.data?.pages[0]?.items[0]?.issue_priority).toBe("low");+ unmount(); qc.clear();+ });++ it("updates read state on later pages and invalidates server-owned filter membership on issue events", async () => {+ const { qc, wrapper } = setup();+ const key = archivedInboxPagesOptions("ws", EMPTY_INBOX_FILTERS).queryKey;+ qc.setQueryData<InfiniteData<ArchivedInboxPage>>(key, { pages: [page([item("first")], "next"), page([item("target")])], pageParams: [null, "next"] });+ setApiInstance({ markInboxRead: async () => ({ ...item("target"), read: true }) } as unknown as ApiClient);+ const { result, unmount } = renderHook(() => useMarkInboxRead(), { wrapper });+ await act(() => result.current.mutateAsync("target"));+ expect(qc.getQueryData<InfiniteData<ArchivedInboxPage>>(key)?.pages[1]?.items[0]?.read).toBe(true);+ onInboxIssueStatusChanged(qc, "ws", "target", "todo");+ expect(qc.getQueryData<InfiniteData<ArchivedInboxPage>>(key)?.pages[1]?.items[0]?.issue_status).toBe("todo");+ expect(qc.getQueryState(key)?.isInvalidated).toBe(true);+ await onInboxIssueDeleted(qc, "ws", "target");+ expect(qc.getQueryData<InfiniteData<ArchivedInboxPage>>(key)?.pages[1]?.items).toEqual([]);+ unmount(); qc.clear();+ });+});diff --git a/packages/core/inbox/queries.ts b/packages/core/inbox/queries.tsindex c4d0fdb080..e62ee33780 100644--- a/packages/core/inbox/queries.ts+++ b/packages/core/inbox/queries.ts@@ -1,4 +1,7 @@-import { queryOptions, useQuery } from "@tanstack/react-query";+import type { InfiniteData, QueryClient } from "@tanstack/react-query";+import type { ArchivedInboxPage } from "../types/inbox";+import { EMPTY_INBOX_FILTERS, type InboxFilters } from "./filter-store";+import { infiniteQueryOptions, queryOptions, useQuery } from "@tanstack/react-query";import { api } from "../api";import type { InboxItem, InboxWorkspaceUnread } from "../types";@@ -6,6 +9,9 @@ export const inboxKeys = {all: (wsId: string) => ["inbox", wsId] as const,list: (wsId: string) => [...inboxKeys.all(wsId), "list"] as const,archived: (wsId: string) => [...inboxKeys.all(wsId), "archived"] as const,+ pages: (wsId: string) => [...inboxKeys.archived(wsId), "pages"] as const,+ lookup: (wsId: string) => [...inboxKeys.archived(wsId), "lookup"] as const,+ facets: (wsId: string) => [...inboxKeys.all(wsId), "archived-facets"] as const,// Account-level (not workspace-scoped): a single shared cache entry that// holds unread counts for every workspace the user belongs to.unreadSummary: () => ["inbox", "unread-summary"] as const,@@ -19,11 +25,9 @@ export function inboxListOptions(wsId: string) {}/**- * Archived notifications, backing the inbox's "Archived" sub-view. A separate- * cache entry from the main list rather than one flat cache split locally- * (which is what chat does): the archive grows without end, so it is fetched- * from its own capped endpoint, and the server — not the client — decides- * which issues belong in which list.+ * @deprecated Legacy array endpoint, capped at 200 groups. New archive+ * consumers must use archivedInboxPagesOptions for the complete archive.+ * Retained for compatibility with legacy cache consumers.*/export function archivedInboxListOptions(wsId: string) {return queryOptions({@@ -32,6 +36,54 @@ export function archivedInboxListOptions(wsId: string) {});}+function normalizedInboxFilters(filters: InboxFilters): InboxFilters {+ return { statuses: [...filters.statuses].sort(), priorities: [...filters.priorities].sort(),+ actors: [...filters.actors].sort(), unreadOnly: filters.unreadOnly };+}++export function archivedInboxPagesOptions(wsId: string, filters: InboxFilters) {+ return infiniteQueryOptions({+ queryKey: [...inboxKeys.pages(wsId), normalizedInboxFilters(filters)],+ initialPageParam: null as string | null,+ queryFn: ({ pageParam, signal }) => api.listArchivedInboxPage(filters, { cursor: pageParam, signal }),+ getNextPageParam: (page) => page.nextCursor ?? undefined,+ retry: false,+ });+}++export function archivedInboxLookupOptions(wsId: string, groupId: string, filters: InboxFilters = EMPTY_INBOX_FILTERS) {+ return queryOptions({+ queryKey: [...inboxKeys.lookup(wsId), groupId, normalizedInboxFilters(filters)],+ queryFn: ({ signal }) => api.listArchivedInboxPage(filters, { groupId, signal }),+ enabled: !!groupId,+ retry: false,+ });+}++export function archivedInboxFacetsOptions(wsId: string, filters: InboxFilters) {+ return queryOptions({+ queryKey: [...inboxKeys.facets(wsId), normalizedInboxFilters(filters)],+ queryFn: ({ signal }) => api.getArchivedInboxFacets(filters, signal),+ retry: false,+ });+}++export type ArchivedInboxCache = InboxItem[] | ArchivedInboxPage | InfiniteData<ArchivedInboxPage>;++export function mapArchivedInboxCache(data: ArchivedInboxCache, patch: (items: InboxItem[]) => InboxItem[]): ArchivedInboxCache {+ if (Array.isArray(data)) return patch(data);+ if ("pages" in data) return { ...data, pages: data.pages.map((page) => ({ ...page, items: patch(page.items) })) };+ return { ...data, items: patch(data.items) };+}++export function patchArchivedInboxCaches(qc: QueryClient, wsId: string, patch: (items: InboxItem[]) => InboxItem[]) {+ const snapshot = qc.getQueriesData<ArchivedInboxCache>({ queryKey: inboxKeys.archived(wsId) });+ for (const [key, data] of snapshot) {+ if (data) qc.setQueryData(key, mapArchivedInboxCache(data, patch));+ }+ return snapshot;+}+/*** Cross-workspace unread inbox summary. One cache entry shared across all* workspaces — the data is account-level, so switching workspaces does notdiff --git a/packages/core/inbox/ws-updaters.ts b/packages/core/inbox/ws-updaters.tsindex 7d46ee455f..4236e775e5 100644--- a/packages/core/inbox/ws-updaters.ts+++ b/packages/core/inbox/ws-updaters.ts@@ -1,5 +1,5 @@import type { QueryClient, QueryKey } from "@tanstack/react-query";-import { inboxKeys } from "./queries";+import { inboxKeys, mapArchivedInboxCache, type ArchivedInboxCache } from "./queries";import type { InboxItem, IssuePriority, IssueStatus } from "../types";// Re-read a query because the server changed — in a way that is never answered@@ -53,11 +53,11 @@ function patchInboxLists(wsId: string,patch: (items: InboxItem[]) => InboxItem[],) {- for (const queryKey of [inboxKeys.list(wsId), inboxKeys.archived(wsId)]) {+ for (const queryKey of [inboxKeys.list(wsId), ...qc.getQueryCache().findAll({ queryKey: inboxKeys.archived(wsId) }).map((query) => query.queryKey)]) {const invalidated = qc.getQueryState(queryKey)?.isInvalidated === true;- qc.setQueryData<InboxItem[]>(queryKey, (old) => {+ qc.setQueryData<ArchivedInboxCache>(queryKey, (old) => {if (!old) return undefined;- const next = patch(old);+ const next = mapArchivedInboxCache(old, patch);return next === old ? undefined : next;});if (invalidated) {@@ -111,6 +111,7 @@ export function onInboxIssueStatusChanged(issueId: string,status: IssueStatus,) {+ // The issue cache coordinator owns membership invalidation after commit.patchInboxIssueStatus(qc, wsId, issueId, status);}@@ -133,7 +134,12 @@ export async function onInboxIssueDeleted(patchInboxLists(qc, wsId, (items) =>items.filter((i) => i.issue_id !== issueId),);- await onInboxSummaryInvalidate(qc);+ await Promise.all([+ onInboxSummaryInvalidate(qc),+ refreshInboxQuery(qc, inboxKeys.pages(wsId)),+ refreshInboxQuery(qc, inboxKeys.lookup(wsId)),+ refreshInboxQuery(qc, inboxKeys.facets(wsId)),+ ]);}// Whether a request for either inbox list is out (paused ones included).diff --git a/packages/core/issues/cache-coordinator.ts b/packages/core/issues/cache-coordinator.tsindex b10778cf7c..439fae5866 100644--- a/packages/core/issues/cache-coordinator.ts+++ b/packages/core/issues/cache-coordinator.ts@@ -11,7 +11,7 @@ import {type IssueSortParam,type MyIssuesFilter,} from "./queries";-import { inboxKeys } from "../inbox/queries";+import { inboxKeys, type ArchivedInboxCache } from "../inbox/queries";import { patchInboxIssueProjection } from "../inbox/ws-updaters";import { projectKeys } from "../projects/queries";import {@@ -89,7 +89,7 @@ export interface IssueCacheChangeResult {prevTableRows: [QueryKey, IssueTableRowCache][];prevDetail: Issue | undefined;prevInboxList: InboxItem[] | undefined;- prevArchivedInboxList: InboxItem[] | undefined;+ prevArchivedInboxCaches: [QueryKey, ArchivedInboxCache | undefined][] | undefined;/** Loaded list keys whose server result may have drifted (membership* unknown, possible enter/leave beyond the loaded window, bucket-count* drift). Invalidate on settle (mutation) or immediately (WS). */@@ -534,12 +534,21 @@ export function applyIssueChange(// filtering. The issue is the real state, so both projections follow every// write immediately.let prevInboxList: InboxItem[] | undefined;- let prevArchivedInboxList: InboxItem[] | undefined;+ let prevArchivedInboxCaches: [QueryKey, ArchivedInboxCache | undefined][] | undefined;if (patch.status !== undefined || patch.priority !== undefined) {prevInboxList = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));- prevArchivedInboxList = qc.getQueryData<InboxItem[]>(- inboxKeys.archived(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.+ const archiveProjectionChanged =+ (patch.status !== undefined && (changed.status || !prevIssue || prevIssue.status !== patch.status)) ||+ (patch.priority !== undefined && (!prevIssue || prevIssue.priority !== patch.priority));+ if (archiveProjectionChanged) {+ staleKeys.push(...qc.getQueryCache().findAll({ queryKey: inboxKeys.archived(wsId) })+ .filter((query) => query.queryKey.length > inboxKeys.archived(wsId).length)+ .map((query) => query.queryKey));+ staleKeys.push(...qc.getQueryCache().findAll({ queryKey: inboxKeys.facets(wsId) }).map((query) => query.queryKey));+ }patchInboxIssueProjection(qc, wsId, id, {status: patch.status,priority: patch.priority,@@ -552,7 +561,7 @@ export function applyIssueChange(prevTableRows,prevDetail,prevInboxList,- prevArchivedInboxList,+ prevArchivedInboxCaches,staleKeys,prevIssue,};@@ -571,7 +580,7 @@ export function rollbackIssueChange(| "prevTableRows"| "prevDetail"| "prevInboxList"- | "prevArchivedInboxList"+ | "prevArchivedInboxCaches">,) {for (const [key, snapshot] of result.prevLists) {@@ -589,11 +598,8 @@ export function rollbackIssueChange(if (result.prevInboxList !== undefined) {qc.setQueryData(inboxKeys.list(wsId), result.prevInboxList);}- if (result.prevArchivedInboxList !== undefined) {- qc.setQueryData(- inboxKeys.archived(wsId),- result.prevArchivedInboxList,- );+ for (const [key, snapshot] of result.prevArchivedInboxCaches ?? []) {+ qc.setQueryData(key, snapshot);}}@@ -678,6 +684,13 @@ export function invalidateStaleListKeys(qc: QueryClient, staleKeys: QueryKey[])const hash = hashKey(key);if (seen.has(hash)) continue;seen.add(hash);- qc.invalidateQueries({ queryKey: key, exact: true });+ if (key[0] === "inbox") {+ // A first archive page/facet request may predate this committed issue+ // change. Cancel before invalidation even when it has no cached data.+ void qc.cancelQueries({ queryKey: key, exact: true }).then(() =>+ qc.invalidateQueries({ queryKey: key, exact: true }));+ } else {+ qc.invalidateQueries({ queryKey: key, exact: true });+ }}}diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.tsindex 0f74716199..fe145509ba 100644--- a/packages/core/issues/mutations.ts+++ b/packages/core/issues/mutations.ts@@ -9,7 +9,7 @@ import {import { api } from "../api";import { issueKeys } from "./queries";import { projectKeys } from "../projects/queries";-import { inboxKeys } from "../inbox/queries";+import { inboxKeys, type ArchivedInboxCache } from "../inbox/queries";import {cancelInboxLists,isInboxListRequestInFlight,@@ -539,7 +539,7 @@ export function useBatchUpdateIssues() {>();const prevDetailById = new Map<string, Issue>();let prevInboxList: InboxItem[] | undefined;- let prevArchivedInboxList: InboxItem[] | undefined;+ let prevArchivedInboxCaches: [QueryKey, ArchivedInboxCache | undefined][] | undefined;const staleKeys: QueryKey[] = [];for (const id of ids) {const base = qc.getQueryData<Issue>(issueKeys.detail(wsId, id));@@ -568,10 +568,10 @@ export function useBatchUpdateIssues() {prevInboxList = change.prevInboxList;}if (- prevArchivedInboxList === undefined &&- change.prevArchivedInboxList !== undefined+ prevArchivedInboxCaches === undefined &&+ change.prevArchivedInboxCaches !== undefined) {- prevArchivedInboxList = change.prevArchivedInboxList;+ prevArchivedInboxCaches = change.prevArchivedInboxCaches;}staleKeys.push(...change.staleKeys);}@@ -601,7 +601,7 @@ export function useBatchUpdateIssues() {prevTableRows: [...prevTableRowByHash.values()],prevDetailById,prevInboxList,- prevArchivedInboxList,+ prevArchivedInboxCaches,inboxWrite,staleKeys,prevChildren,@@ -632,11 +632,8 @@ export function useBatchUpdateIssues() {if (ctx?.prevInboxList !== undefined) {qc.setQueryData(inboxKeys.list(wsId), ctx.prevInboxList);}- if (ctx?.prevArchivedInboxList !== undefined) {- qc.setQueryData(- inboxKeys.archived(wsId),- ctx.prevArchivedInboxList,- );+ for (const [key, snapshot] of ctx?.prevArchivedInboxCaches ?? []) {+ qc.setQueryData(key, snapshot);}if (ctx?.prevChildren) {for (const [parentId, snapshot] of ctx.prevChildren) {diff --git a/packages/core/types/inbox.ts b/packages/core/types/inbox.tsindex 1605f18050..4d83c18cab 100644--- a/packages/core/types/inbox.ts+++ b/packages/core/types/inbox.ts@@ -65,3 +65,17 @@ export interface InboxItem {created_at: string;details: Record<string, string> | null;}+++export interface ArchivedInboxPage {+ items: InboxItem[];+ nextCursor: string | null;+ hasMore: boolean;+}++export interface ArchivedInboxFacets {+ statuses: Record<string, number>;+ priorities: Record<string, number>;+ actors: Record<string, number>;+ unreadCount: number;+}diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 73fa8cb52c..f070e2284f 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -113,7 +113,7 @@ export type {PluginMCPTool,PluginTokenIssue,} from "./plugin";-export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread } from "./inbox";+export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread, ArchivedInboxPage, ArchivedInboxFacets } from "./inbox";export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";export type { Comment, CommentType, CommentAuthorType, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, CommentTriggerOutcome, CommentTriggerStatus, Reaction } from "./comment";export type { Label, LabelResourceType, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse, ResourceLabelsResponse } from "./label";diff --git a/packages/views/inbox/components/inbox-filter-menu.test.tsx b/packages/views/inbox/components/inbox-filter-menu.test.tsxindex 88026852c9..aadaf79bb3 100644--- a/packages/views/inbox/components/inbox-filter-menu.test.tsx+++ b/packages/views/inbox/components/inbox-filter-menu.test.tsx@@ -88,15 +88,22 @@ const ITEMS = [function renderMenu({items = ITEMS,priorityFilterSupport = "supported",+ archived = false,+ getArchivedInboxFacets = vi.fn(async () => ({ statuses: {}, priorities: {}, actors: {}, unreadCount: 0 })),+ statusEntries = BUILT_IN_STATUS_ORDER.map(statusEntry),}: {items?: InboxItem[];priorityFilterSupport?: InboxPriorityFilterSupport;+ archived?: boolean;+ getArchivedInboxFacets?: ReturnType<typeof vi.fn>;+ statusEntries?: IssueStatusEntry[];} = {}) {setApiInstance({+ getArchivedInboxFacets,listIssueStatuses: async () => ({- statuses: BUILT_IN_STATUS_ORDER.map(statusEntry),+ statuses: statusEntries,categories: [],- total: BUILT_IN_STATUS_ORDER.length,+ total: statusEntries.length,}),} as unknown as ApiClient);const queryClient = new QueryClient({@@ -108,6 +115,7 @@ function renderMenu({wsId="ws-1"items={items}priorityFilterSupport={priorityFilterSupport}+ archived={archived}/></QueryClientProvider>,);@@ -131,6 +139,43 @@ afterEach(() => {});describe("InboxFilterMenu", () => {+ it("keeps a selected retired status removable when absent from archive facets and pages", async () => {+ useInboxFilterStore.getState().toggleStatusFilter("ws-1", "custom-retired");+ renderMenu({+ items: [], archived: true,+ statusEntries: [...BUILT_IN_STATUS_ORDER.map(statusEntry), {+ ...statusEntry("todo"), id: "retired", key: "custom-retired",+ 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/ }));+ 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([]);+ });++ 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/ }));+ 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([]);+ });++ it("loads full-archive facets only when opened, including an actor absent from loaded rows", async () => {+ const getArchivedInboxFacets = vi.fn(async () => ({ statuses: { done: 251 }, priorities: { high: 251 }, actors: { "member:alice": 251 }, unreadCount: 0 }));+ renderMenu({ items: [], archived: true, getArchivedInboxFacets });+ expect(getArchivedInboxFacets).not.toHaveBeenCalled();+ await openSubmenu("From");+ expect(await screen.findByRole("menuitemcheckbox", { name: /Alice.*251/ })).toBeTruthy();+ expect(getArchivedInboxFacets).toHaveBeenCalledTimes(1);+ });+it("selects a status and exposes the active count on the trigger", async () => {renderMenu();await openSubmenu("Status");diff --git a/packages/views/inbox/components/inbox-filter-menu.tsx b/packages/views/inbox/components/inbox-filter-menu.tsxindex 7cb36448b9..f63c4c10b8 100644--- a/packages/views/inbox/components/inbox-filter-menu.tsx+++ b/packages/views/inbox/components/inbox-filter-menu.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useMemo } from "react";+import { useEffect, useMemo, useState } from "react";import { CircleDot, Filter, Mail, RotateCcw, SignalHigh, UserRound } from "lucide-react";import { PRIORITY_DISPLAY_ORDER } from "@multica/core/issues/config";import {@@ -13,6 +13,8 @@ import {useInboxFilters,useInboxFilterStore,} from "@multica/core/inbox/filter-store";+import { useQuery } from "@tanstack/react-query";+import { archivedInboxFacetsOptions } from "@multica/core/inbox/queries";import { useActorName } from "@multica/core/workspace/hooks";import type { InboxItem } from "@multica/core/types";import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";@@ -70,14 +72,19 @@ export function InboxFilterMenu({wsId,items,priorityFilterSupport,+ archived = false,}: {wsId: string;items: InboxItem[];priorityFilterSupport: InboxPriorityFilterSupport;+ archived?: boolean;}) {const { t } = useT("inbox");const { t: tIssues } = useT("issues");const filters = useInboxFilters(wsId);+ 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,@@ -93,13 +100,15 @@ export function InboxFilterMenu({);const inboxStatusKeys = useMemo(() => [- ...new Set(- items.flatMap((item) =>+ ...new Set([+ ...filters.statuses,+ ...Object.keys(facets?.statuses ?? {}),+ ...items.flatMap((item) =>item.issue_status == null ? [] : [item.issue_status],),- ),+ ]),],- [items],+ [items, facets, filters.statuses],);const statusOptions = useStatusOptions(wsId, inboxStatusKeys);const effectiveFilters = useMemo(@@ -142,32 +151,36 @@ export function InboxFilterMenu({() => filterInboxItems(items, { ...effectiveFilters, actors: [] }),[items, effectiveFilters],);- const unreadCount = useMemo(+ const localUnreadCount = useMemo(() =>filterInboxItems(items, { ...effectiveFilters, unreadOnly: false }).filter((item) => item.read !== true,).length,[items, effectiveFilters],);- const statuses = useMemo(+ const localStatuses = useMemo(() => statusCounts(statusFacetItems),[statusFacetItems],);- const priorities = useMemo(+ const localPriorities = useMemo(() => priorityCounts(priorityFacetItems),[priorityFacetItems],);- const actors = useMemo(+ 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.const actorOptions = useMemo(() => {- const keys = new Set<string>();- for (const item of items) {+ const keys = new Set<string>(archived ? [...Object.keys(facets?.actors ?? {}), ...filters.actors] : []);+ for (const item of archived ? [] : items) {const key = inboxActorKey(item);if (key != null) keys.add(key);}@@ -177,14 +190,14 @@ export function InboxFilterMenu({return { key, type, id, name: getActorName(type, id) };}).sort((a, b) => a.name.localeCompare(b.name));- }, [items, getActorName]);+ }, [items, getActorName, archived, facets, filters.actors]);const triggerLabel =activeCount > 0? t(($) => $.filters.active_count, { count: activeCount }): t(($) => $.filters.tooltip);return (- <DropdownMenu>+ <DropdownMenu open={open} onOpenChange={setOpen}><DropdownMenuTriggerrender={<Button@@ -206,6 +219,11 @@ export function InboxFilterMenu({)}</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>}<DropdownMenuCheckboxItemchecked={effectiveFilters.unreadOnly}onCheckedChange={() => toggleUnreadOnly(wsId)}diff --git a/packages/views/inbox/components/inbox-list.test.tsx b/packages/views/inbox/components/inbox-list.test.tsxindex 1dad39386f..ce01df9fab 100644--- a/packages/views/inbox/components/inbox-list.test.tsx+++ b/packages/views/inbox/components/inbox-list.test.tsx@@ -14,7 +14,11 @@ vi.mock("react-virtuoso", () => ({{data,itemContent,+ components,+ endReached,}: {+ components: { Footer: React.ComponentType };+ endReached: () => void;data: InboxItem[];itemContent: (index: number, item: InboxItem) => React.ReactNode;},@@ -23,9 +27,11 @@ vi.mock("react-virtuoso", () => ({useImperativeHandle(ref, () => ({ scrollIntoView }));return (<div>+ <button onClick={endReached}>Reach list end</button>{data.map((item, index) => (<div key={item.id}>{itemContent(index, item)}</div>))}+ <components.Footer /></div>);}),@@ -49,7 +55,10 @@ vi.mock("./inbox-list-item", () => ({),}));-vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "Inbox" }) }));+vi.mock("../../i18n", async () => {+ const strings = (await import("../../locales/en/inbox.json")).default;+ return { useT: () => ({ t: (select: (value: typeof strings) => string) => select(strings) }) };+});function item(id: string, overrides: Partial<InboxItem> = {}): InboxItem {return {@@ -81,7 +90,6 @@ function renderList(selectedKey: string, onSelect = vi.fn()) {items={items}view="inbox"selectedKey={selectedKey}- archivedCount={0}onSelect={onSelect}onAction={vi.fn()}onOpenArchived={vi.fn()}@@ -192,3 +200,35 @@ describe("InboxList keyboard navigation", () => {expect(document.activeElement).toBe(scroller);});});+++describe("InboxList archive pagination", () => {+ it("keeps a count-free archive entry available with an empty inbox", () => {+ const onOpenArchived = vi.fn();+ render(<InboxList items={[]} view="inbox" selectedKey="" onSelect={vi.fn()} onAction={vi.fn()} onOpenArchived={onOpenArchived} />);+ fireEvent.click(screen.getByRole("button", { name: "Archived" }));+ expect(onOpenArchived).toHaveBeenCalledOnce();+ });++ it("loads at the end, suppresses automatic retries, and provides a retry button", () => {+ const onLoadMore = vi.fn();+ const props = { items, view: "archived" as const, selectedKey: "", onSelect: vi.fn(), onAction: vi.fn(), onOpenArchived: vi.fn(), onLoadMore };+ const { rerender } = render(<InboxList {...props} />);+ fireEvent.click(screen.getByRole("button", { name: "Reach list end" }));+ expect(onLoadMore).toHaveBeenCalledOnce();+ onLoadMore.mockClear();+ rerender(<InboxList {...props} loadMoreError />);+ fireEvent.click(screen.getByRole("button", { name: "Reach list end" }));+ expect(onLoadMore).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));+ expect(onLoadMore).toHaveBeenCalledOnce();+ expect(screen.getByText("a")).toBeTruthy();+ });++ it("loads the next page when restored rows drain the loaded window", () => {+ const onLoadMore = vi.fn();+ render(<InboxList items={[]} view="archived" selectedKey="" onSelect={vi.fn()} onAction={vi.fn()} onOpenArchived={vi.fn()} onLoadMore={onLoadMore} />);+ expect(onLoadMore).toHaveBeenCalledOnce();+ expect(screen.queryByText("No archived notifications")).toBeNull();+ });+});diff --git a/packages/views/inbox/components/inbox-list.tsx b/packages/views/inbox/components/inbox-list.tsxindex 5c05b902c8..252186777c 100644--- a/packages/views/inbox/components/inbox-list.tsx+++ b/packages/views/inbox/components/inbox-list.tsx@@ -2,6 +2,7 @@import {useCallback,+ useEffect,useMemo,useRef,useState,@@ -50,7 +51,9 @@ export function InboxList({items,view,selectedKey,- archivedCount,+ onLoadMore,+ loadingMore = false,+ loadMoreError = false,onSelect,onAction,onOpenArchived,@@ -60,9 +63,9 @@ export function InboxList({items: InboxItem[];view: InboxView;selectedKey: string;- // Deduplicated archived-issue count. Only read in the main view, to label the- // entry into the archive; the entry hides at zero.- archivedCount: number;+ onLoadMore?: () => void;+ loadingMore?: boolean;+ loadMoreError?: boolean;onSelect: (item: InboxItem) => void;onAction: (id: string) => void;onOpenArchived: () => void;@@ -158,7 +161,7 @@ export function InboxList({// remounts on every parent render and drops hover/focus mid-click.const archivedEntry = useMemo(() =>- !isArchivedView && archivedCount > 0 ? (+ !isArchivedView ? (<buttontype="button"onClick={onOpenArchived}@@ -170,21 +173,35 @@ export function InboxList({<span className="min-w-0 flex-1 truncate font-medium">{t(($) => $.list.archived_title)}</span>- <span className="shrink-0 tabular-nums text-muted-foreground">- {archivedCount}- </span><ChevronRight className="size-4 shrink-0 text-faint-foreground" /></button>) : null,- [isArchivedView, archivedCount, onOpenArchived, t],+ [isArchivedView, onOpenArchived, t],);- const Footer = useCallback(() => archivedEntry, [archivedEntry]);+ const loadMore = useCallback(() => {+ if (!loadingMore && !loadMoreError) onLoadMore?.();+ }, [loadingMore, loadMoreError, onLoadMore]);+ useEffect(() => {+ if (items.length === 0) loadMore();+ }, [items.length, loadMore]);+ const Footer = useCallback(() => <>+ {archivedEntry}+ {isArchivedView && onLoadMore && (+ <div className="flex flex-col items-center gap-2 py-3">+ {loadMoreError && <p role="alert" className="text-caption text-destructive">{t(($) => $.errors.archived_load_failed)}</p>}+ <button type="button" disabled={loadingMore} onClick={onLoadMore}+ className="rounded-md px-3 py-2 text-caption text-muted-foreground hover:bg-accent/50 focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50">+ {loadingMore ? t(($) => $.list.loading_more) : loadMoreError ? t(($) => $.list.retry) : t(($) => $.list.load_more)}+ </button>+ </div>+ )}+ </>, [archivedEntry, isArchivedView, onLoadMore, loadingMore, loadMoreError, t]);if (items.length === 0) {return (<div className="flex-1 min-h-0 overflow-y-auto">- <div className="flex flex-col items-center justify-center py-16 text-muted-foreground">+ {!onLoadMore && <div className="flex flex-col items-center justify-center py-16 text-muted-foreground"><Inbox className="mb-3 h-8 w-8 text-faint-foreground" /><p className="text-body">{emptyLabel ??@@ -193,10 +210,10 @@ export function InboxList({: t(($) => $.list.empty))}</p>{emptyAction && <div className="mt-3">{emptyAction}</div>}- </div>+ </div>}{/* Still offer the archive when the main list is empty — that isexactly when a user goes looking for what they filed away. */}- {archivedEntry && <div className="px-2">{archivedEntry}</div>}+ <div className="px-2"><Footer /></div></div>);}@@ -232,6 +249,7 @@ export function InboxList({ref={virtuosoRef}customScrollParent={scrollEl}data={items}+ endReached={loadMore}computeItemKey={computeItemKey}initialScrollTop={restoredScrollTop}initialItemCount={Math.min(items.length, VIRTUOSO_SEED_COUNT)}diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsxindex 5b6d57f72d..b175df5932 100644--- a/packages/views/inbox/components/inbox-page.test.tsx+++ b/packages/views/inbox/components/inbox-page.test.tsx@@ -17,17 +17,31 @@ vi.mock("react-resizable-panels", () => ({// The page runs two queries — the active list and the archived one. They are// told apart by the queryKey their options carry, so each test can stock the// two lists independently.-const listData: { active: InboxItem[]; archived: InboxItem[] } = {+const listData: { active: InboxItem[]; archived: InboxItem[]; lookup?: InboxItem[] } = {active: [],archived: [],};+const queryCalls: Array<{ queryKey: readonly unknown[]; enabled?: boolean }> = [];+const lookupState = { isLoading: false, isError: false, refetch: vi.fn() };vi.mock("@tanstack/react-query", () => ({- useQuery: (options: { queryKey: readonly unknown[] }) => ({- data: options.queryKey.includes("archived") ? listData.archived : listData.active,+ useQuery: (options: { queryKey: readonly unknown[]; enabled?: boolean }) => {+ queryCalls.push(options);+ return ({+ data: options.queryKey.includes("archived") ? { items: listData.lookup ?? listData.archived, hasMore: false, nextCursor: null } : listData.active,isLoading: false,isError: false,- }),+ refetch: vi.fn(),+ ...(options.queryKey.includes("lookup") ? lookupState : {}),+ }); },+ useInfiniteQuery: (options: { queryKey: readonly unknown[]; enabled?: boolean }) => {+ queryCalls.push(options);+ return ({+ data: { pages: [{ items: listData.archived, hasMore: false, nextCursor: null }] },+ isLoading: false, isError: false, hasNextPage: false,+ isFetchingNextPage: false, isFetchNextPageError: false,+ fetchNextPage: vi.fn(), refetch: vi.fn(),+ }); },}));vi.mock("@multica/core/hooks", () => ({@@ -55,7 +69,8 @@ vi.mock("@multica/core/issues/stores/draft-store", () => ({vi.mock("@multica/core/inbox/queries", () => ({inboxListOptions: () => ({ queryKey: ["inbox", "workspace-1", "list"] }),- archivedInboxListOptions: () => ({ queryKey: ["inbox", "workspace-1", "archived"] }),+ archivedInboxPagesOptions: () => ({ queryKey: ["inbox", "workspace-1", "archived", "pages"] }),+ archivedInboxLookupOptions: () => ({ queryKey: ["inbox", "workspace-1", "archived", "lookup"] }),deduplicateInboxItems: (items: InboxItem[]) => items.filter((i) => !i.archived),deduplicateArchivedInboxItems: (items: InboxItem[]) => items.filter((i) => i.archived),useInboxUnreadCount: () => 2,@@ -256,6 +271,11 @@ function item(overrides: Partial<InboxItem> = {}): InboxItem {function reset() {listData.active = [];listData.archived = [];+ listData.lookup = undefined;+ lookupState.isLoading = false;+ lookupState.isError = false;+ lookupState.refetch.mockClear();+ queryCalls.length = 0;searchParams = new URLSearchParams();replace.mockClear();markReadMutate.mockClear();@@ -402,6 +422,79 @@ describe("InboxPage", () => {expect(screen.getByTestId("row")).toHaveTextContent("legacy-todo");});+ it("only enables the current inbox view's list", () => {+ reset();+ const main = render(<InboxPage />);+ expect(queryCalls.find((q) => q.queryKey.includes("list"))?.enabled).toBe(true);+ expect(queryCalls.find((q) => q.queryKey.includes("pages"))?.enabled).toBe(false);+ main.unmount();+ reset();+ searchParams = new URLSearchParams("view=archived");+ render(<InboxPage />);+ expect(queryCalls.find((q) => q.queryKey.includes("list"))?.enabled).toBe(false);+ expect(queryCalls.find((q) => q.queryKey.includes("pages"))?.enabled).toBe(true);+ });++ it("opens a deep-linked archive group outside the loaded pages with its comment anchor", () => {+ reset();+ searchParams = new URLSearchParams("view=archived&issue=old-issue");+ listData.archived = [item({ id: "recent", archived: true })];+ listData.lookup = [item({ id: "older", issue_id: "old-issue", archived: true, details: { comment_id: "old-comment" } })];+ render(<InboxPage />);+ expect(replace).not.toHaveBeenCalled();+ expect(issueDetailProps.at(-1)).toMatchObject({ issueId: "old-issue", highlightCommentId: "old-comment" });+ expect(queryCalls.find((q) => q.queryKey.includes("lookup"))?.enabled).toBe(true);+ });++ describe.each([PHONE, DESKTOP])("archive deep links at width %s", (width) => {+ function setupLookup() {+ reset();+ layout.width = width;+ searchParams = new URLSearchParams("view=archived&issue=old-issue");+ listData.archived = [item({ id: "recent", issue_id: "recent-issue", archived: true })];+ listData.lookup = [];+ }++ it("keeps loaded rows visible while resolving the selection, then opens its detail", () => {+ setupLookup();+ lookupState.isLoading = true;+ const { rerender } = render(<InboxPage />);+ expect(screen.getByTestId("row")).toHaveTextContent("recent");+ expect(replace).not.toHaveBeenCalled();+ expect(issueDetailProps).toHaveLength(0);++ lookupState.isLoading = false;+ listData.lookup = [item({ id: "older", issue_id: "old-issue", archived: true })];+ rerender(<InboxPage />);+ expect(issueDetailProps.at(-1)).toMatchObject({ issueId: "old-issue" });+ expect(replace).not.toHaveBeenCalled();+ });++ it("keeps the list usable on lookup failure and retries only the lookup", () => {+ setupLookup();+ lookupState.isError = true;+ render(<InboxPage />);+ expect(screen.getByTestId("row")).toHaveTextContent("recent");+ expect(replace).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("alert").querySelector("button")!);+ expect(lookupState.refetch).toHaveBeenCalledTimes(1);++ fireEvent.click(screen.getByTestId("row"));+ expect(issueDetailProps.at(-1)).toMatchObject({ issueId: "recent-issue" });+ expect(screen.queryByRole("alert")).toBeNull();+ });++ it("only falls back to the issue after the lookup confirms the group is absent", () => {+ setupLookup();+ lookupState.isLoading = true;+ const { rerender } = render(<InboxPage />);+ expect(replace).not.toHaveBeenCalled();+ lookupState.isLoading = false;+ rerender(<InboxPage />);+ expect(replace).toHaveBeenCalledWith("/acme/issues/old-issue");+ });+ });+it("renders the archived list when the URL asks for it", () => {// ?view=archived is what makes a refresh, a back/forward step, or a mobile// detail-back land in the archive instead of the main inbox.@@ -429,16 +522,13 @@ describe("InboxPage", () => {expect(archivedView.querySelector('[aria-haspopup="menu"]')).toBeNull();});- it("falls back to the main inbox when the archive drains", () => {- // Restoring the last archived item must not strand the user on an empty- // archive — same fallback chat's archived view has.+ it("keeps the archive open when it is empty", () => {reset();searchParams = new URLSearchParams("view=archived");listData.archived = [];-render(<InboxPage />);-- expect(replace).toHaveBeenCalledWith("/acme/inbox");+ expect(replace).not.toHaveBeenCalled();+ expect(screen.getByTestId("list").dataset.view).toBe("archived");});it("replays the comment highlight when the already-open row is clicked again", () => {diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex 559552264c..a0160edb8f 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -9,7 +9,7 @@ import {useRef,} from "react";import { useDefaultLayout } from "react-resizable-panels";-import { useQuery } from "@tanstack/react-query";+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";import { useWorkspaceId } from "@multica/core/hooks";import { ApiError, errorCode } from "@multica/core/api";import { useWorkspacePaths } from "@multica/core/paths";@@ -24,7 +24,8 @@ import { isImeComposing } from "@multica/core/utils";import { useIssueDraftStore } from "@multica/core/issues/stores/draft-store";import {inboxListOptions,- archivedInboxListOptions,+ archivedInboxPagesOptions,+ archivedInboxLookupOptions,deduplicateInboxItems,deduplicateArchivedInboxItems,useInboxUnreadCount,@@ -128,50 +129,44 @@ export function InboxPage() {}, [urlView]);const wsId = useWorkspaceId();- const { data: rawItems = [], isLoading: loading } = useQuery(inboxListOptions(wsId));- const items = useMemo(() => deduplicateInboxItems(rawItems), [rawItems]);-- // Fetched in both views, not just the archived one: the main list's entry- // into the archive is labelled with this count, so it has to be known before- // the user goes there.- const {- data: rawArchivedItems = [],- isLoading: archivedLoading,- isError: archivedError,- } = useQuery(archivedInboxListOptions(wsId));- const archivedItems = useMemo(- () => deduplicateArchivedInboxItems(rawArchivedItems),- [rawArchivedItems],- );-const isArchivedView = view === "archived";- const viewItems = isArchivedView ? archivedItems : items;const filters = useInboxFilters(wsId);const clearFilters = useInboxFilterStore((state) => state.clearFilters);- // Active and archived endpoints return the same row contract and are both- // already loaded on this page. Requiring the combined response to expose the- // projection prevents one pod in a rolling deploy from advertising a- // capability the other pod does not have yet.- const priorityFilterSupport = useMemo(- () => inboxPriorityFilterSupport([...rawItems, ...rawArchivedItems]),- [rawItems, rawArchivedItems],- );- const effectiveFilters = useMemo(- () => inboxFiltersForPrioritySupport(filters, priorityFilterSupport),- [filters, priorityFilterSupport],- );- const visibleItems = useMemo(- () => filterInboxItems(viewItems, effectiveFilters),- [viewItems, effectiveFilters],- );+ const { data: rawItems = [], isLoading: loading } = useQuery({+ ...inboxListOptions(wsId), enabled: !isArchivedView,+ });+ const items = useMemo(() => deduplicateInboxItems(rawItems), [rawItems]);+ const archiveQuery = useInfiniteQuery({+ ...archivedInboxPagesOptions(wsId, filters), enabled: isArchivedView,+ });+ const fetchNextArchivedPage = archiveQuery.fetchNextPage;+ const loadNextArchivedPage = useCallback(() => { void fetchNextArchivedPage(); }, [fetchNextArchivedPage]);+ const archivedLoading = archiveQuery.isLoading;+ const archivedError = archiveQuery.isError && !archiveQuery.data;+ const archivedItems = useMemo(() => deduplicateArchivedInboxItems(+ archiveQuery.data?.pages.flatMap((page) => page.items) ?? [],+ ), [archiveQuery.data]);+ const viewItems = isArchivedView ? archivedItems : items;+ // The paginated endpoint guarantees the projection, including on empty pages.+ const priorityFilterSupport = isArchivedView ? "supported" : inboxPriorityFilterSupport(rawItems);+ const effectiveFilters = useMemo(() => inboxFiltersForPrioritySupport(filters, priorityFilterSupport), [filters, priorityFilterSupport]);+ const visibleItems = useMemo(() => filterInboxItems(viewItems, effectiveFilters), [viewItems, effectiveFilters]);const hasActiveFilters = inboxFilterCount(effectiveFilters) > 0;-- const selected =- visibleItems.find((i) => (i.issue_id ?? i.id) === selectedKey) ?? null;- const selectedInView =- viewItems.find((i) => (i.issue_id ?? i.id) === selectedKey) ?? null;- const selectionFilteredOut =- selectedKey.length > 0 && selectedInView !== null && selected === null;+ 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.+ const lookup = useQuery({+ ...archivedInboxLookupOptions(wsId, selectedKey),+ enabled: isArchivedView && !!selectedKey && !selectedOnPage && !archivedLoading && !archivedError,+ });+ const lookupItems = useMemo(() => deduplicateArchivedInboxItems(lookup.data?.items ?? []), [lookup.data]);+ const selectionItems = useMemo(() => {+ if (!isArchivedView || selectedOnPage) return visibleItems;+ return [...visibleItems, ...filterInboxItems(lookupItems, effectiveFilters)];+ }, [isArchivedView, selectedOnPage, visibleItems, lookupItems, effectiveFilters]);+ 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 selectionFilteredOut = !!selectedKey && !!selectedInView && !selected;// What the DETAIL pane shows, one React transition behind the click.//@@ -184,7 +179,7 @@ export function InboxPage() {// painting — and the previous issue stays on screen until it is ready.const detailKey = useDeferredValue(selectedKey);const detailSwapping = detailKey !== selectedKey;- const detailItem = resolveDetailItem(visibleItems, selectedKey, detailKey);+ const detailItem = resolveDetailItem(selectionItems, selectedKey, detailKey);// The gap above is invisible to the navigation adapter — the inbox stays on// the same route and only rewrites `?issue=` — so report it explicitly and@@ -240,10 +235,12 @@ export function InboxPage() {if (selectionFilteredOut) setSelectedKey("");}, [selectionFilteredOut, setSelectedKey]);- // Whether the list currently on screen has finished its first load. The- // fallback and drain effects below both key on this, and getting it wrong in- // the archived view means acting on an empty list that simply hasn't arrived.+ // A targeted lookup must not hide pages that have already loaded. Its+ // 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;// 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@@ -252,7 +249,7 @@ export function InboxPage() {// and `onInboxIssueDeleted` pruned the cache), the issue detail would 404// too — clear the selection and stay on /inbox instead.useEffect(() => {- if (viewLoading) return;+ if (viewLoading || lookupLoading || lookupError || (isArchivedView && archivedError)) return;if (!selectedKey) return;if (selected) return;if (selectionFilteredOut) return;@@ -263,6 +260,10 @@ export function InboxPage() {replace(wsPaths.issueDetail(selectedKey));}, [viewLoading,+ isArchivedView,+ archivedError,+ lookupLoading,+ lookupError,selectedKey,selected,selectionFilteredOut,@@ -271,32 +272,6 @@ export function InboxPage() {setSelectedKey,]);- // Never strand the user on an empty archive: when the last archived issue is- // restored (or a new notification revives it into the main inbox), fall back- // to the main list. Same fallback chat's archived view has. Gated on the load- // so a cold `?view=archived` open doesn't bounce before the data lands.- useEffect(() => {- if (!isArchivedView) return;- if (archivedLoading) return;- // A failed fetch is also "no items" — bouncing here would swap the error- // message for the main list and leave the user with no idea it failed.- if (archivedError) return;- // Let the fallback effect above settle an unresolved selection first. On a- // deep link like `?view=archived&issue=X` into an empty archive both would- // otherwise fire in the same commit, and this one's replace() would land- // last and swallow the redirect to X.- if (selectedKey) return;- if (archivedItems.length > 0) return;- setView("inbox");- }, [- isArchivedView,- archivedLoading,- archivedError,- archivedItems.length,- selectedKey,- setView,- ]);-const { defaultLayout, onLayoutChanged } = useDefaultLayout({id: "multica_inbox_layout",});@@ -421,7 +396,7 @@ export function InboxPage() {// Toasts live in these shared handlers so every archive surface confirms alike.const handleArchive = (id: string) => {- advanceSelectionPast(id, visibleItems);+ advanceSelectionPast(id, selectionItems);archiveMutation.mutate(id, {onSuccess: () => toast.success(t(($) => $.toasts.archived)),onError: (err) =>@@ -434,7 +409,7 @@ export function InboxPage() {};const handleUnarchive = (id: string) => {- advanceSelectionPast(id, visibleItems);+ advanceSelectionPast(id, selectionItems);unarchiveMutation.mutate(id, {onSuccess: () => toast.success(t(($) => $.toasts.unarchived)),onError: (err) =>@@ -539,6 +514,7 @@ export function InboxPage() {wsId={wsId}items={viewItems}priorityFilterSupport={priorityFilterSupport}+ archived={isArchivedView}/>{/* Batch actions are main-view only. Every entry archives from the MAINinbox, so offering them while the archived list is on screen reads as@@ -591,17 +567,17 @@ export function InboxPage() {><ChevronLeft className="size-4 shrink-0" /><span className="truncate">{t(($) => $.list.archived_title)}</span>- <span className="ml-auto shrink-0 tabular-nums text-muted-foreground">- {archivedItems.length}- </span></button>);- const list = archivedError && isArchivedView ? (+ const list = isArchivedView && archivedError ? (<div className="flex-1 min-h-0 overflow-y-auto"><div className="flex flex-col items-center justify-center py-16 text-muted-foreground"><Archive className="mb-3 h-8 w-8 text-faint-foreground" /><p className="text-body">{t(($) => $.errors.archived_load_failed)}</p>+ <Button variant="outline" size="sm" className="mt-3" onClick={() => void archiveQuery.refetch()}>+ {t(($) => $.list.retry)}+ </Button></div></div>) : (@@ -617,17 +593,19 @@ export function InboxPage() {items={visibleItems}view={view}selectedKey={selectedKey}- archivedCount={archivedItems.length}+ onLoadMore={isArchivedView && archiveQuery.hasNextPage ? loadNextArchivedPage : undefined}+ loadingMore={archiveQuery.isFetchingNextPage}+ loadMoreError={archiveQuery.isFetchNextPageError}onSelect={handleSelect}onAction={isArchivedView ? handleUnarchive : handleArchive}onOpenArchived={openArchived}emptyLabel={- hasActiveFilters && viewItems.length > 0 && visibleItems.length === 0+ hasActiveFilters && visibleItems.length === 0? t(($) => $.filters.empty): undefined}emptyAction={- hasActiveFilters && viewItems.length > 0 && visibleItems.length === 0 ? (+ hasActiveFilters && visibleItems.length === 0 ? (<Buttonvariant="outline"size="sm"@@ -645,6 +623,21 @@ export function InboxPage() {<>{listHeader}{isArchivedView && archivedBackRow}+ {lookupLoading && (+ <p role="status" className="shrink-0 border-b px-3 py-2 text-caption text-muted-foreground">+ {t(($) => $.list.loading_selection)}+ </p>+ )}+ {lookupError && (+ <div role="alert" className="flex shrink-0 items-center gap-2 border-b px-3 py-2">+ <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()}>+ {t(($) => $.list.retry)}+ </Button>+ </div>+ )}{list}</>);diff --git a/packages/views/layout/tab-presentation.test.tsx b/packages/views/layout/tab-presentation.test.tsxindex b7e25aff15..3c0dd2467f 100644--- a/packages/views/layout/tab-presentation.test.tsx+++ b/packages/views/layout/tab-presentation.test.tsx@@ -8,8 +8,10 @@ import { projectDetailOptions } from "@multica/core/projects/queries";import { chatSessionsOptions } from "@multica/core/chat/queries";import {inboxListOptions,- archivedInboxListOptions,+ archivedInboxPagesOptions,+ archivedInboxLookupOptions,} from "@multica/core/inbox/queries";+import { EMPTY_INBOX_FILTERS } from "@multica/core/inbox/filter-store";import { agentListOptions } from "@multica/core/workspace/queries";import { runtimeListOptions } from "@multica/core/runtimes/queries";@@ -73,11 +75,22 @@ function seed(qc: QueryClient) {{ id: "n1", issue_id: "i9", title: "Assigned to you", type: "issue_assigned" },{ id: "n2", issue_id: null, title: "Quick create failed", type: "quick_create_failed" },] as never);+ const archiveRow = {+ workspace_id: "ws1", recipient_type: "member" as const, recipient_id: "user",+ actor_type: null, actor_id: null, severity: "info" as const, body: null,+ issue_status: null, read: true, archived: true, created_at: "2026-09-01T00:00:00Z", details: null,+ };// Archived list is a distinct cache; these items are NOT in the main list.- qc.setQueryData(archivedInboxListOptions("ws1").queryKey, [- { id: "a1", issue_id: "i1", title: "Old assignment", type: "issue_assigned" },- { id: "a2", issue_id: null, title: "Archived note", type: "quick_create_failed" },- ] as never);+ qc.setQueryData(archivedInboxPagesOptions("ws1", EMPTY_INBOX_FILTERS).queryKey, {+ pages: [{ items: [+ { ...archiveRow, id: "a1", issue_id: "i1", title: "Old assignment", type: "issue_assigned" },+ { ...archiveRow, id: "a2", issue_id: null, title: "Archived note", type: "quick_create_failed" },+ ], hasMore: false, nextCursor: null }], pageParams: [null],+ });+ qc.setQueryData(archivedInboxLookupOptions("ws1", "a3").queryKey, {+ items: [{ ...archiveRow, id: "a3", issue_id: null, title: "Deep archived note", type: "quick_create_failed" }],+ hasMore: false, nextCursor: null,+ });qc.setQueryData(agentListOptions("ws1").queryKey, [{ id: "ag1", name: "Robby", avatar_url: null },] as never);@@ -219,7 +232,7 @@ describe("useTabPresentation — live from cache", () => {const qc = makeClient();seed(qc);qc.removeQueries({ queryKey: inboxListOptions("ws1").queryKey });- qc.removeQueries({ queryKey: archivedInboxListOptions("ws1").queryKey });+ qc.removeQueries({ queryKey: archivedInboxPagesOptions("ws1", EMPTY_INBOX_FILTERS).queryKey });const wrapper = ({ children }: { children: ReactNode }) => (<QueryClientProvider client={qc}>{children}</QueryClientProvider>);@@ -263,6 +276,12 @@ describe("useTabPresentation — live from cache", () => {});});+ it("archived inbox: a deep-link lookup supplies the title outside loaded pages", () => {+ expect(presentationOf("/acme/inbox?view=archived&issue=a3")).toEqual({+ visual: { kind: "icon", icon: "Inbox" }, title: "Deep archived note",+ });+ });+it("attachment: filename from ?name= drives the title and file icon", () => {expect(presentationOf("/acme/attachments/att1/preview?name=diagram.png")).toEqual({visual: { kind: "icon", icon: "FileImage" },diff --git a/packages/views/layout/tab-presentation.tsx b/packages/views/layout/tab-presentation.tsxindex e0e260b7b9..889824125c 100644--- a/packages/views/layout/tab-presentation.tsx+++ b/packages/views/layout/tab-presentation.tsx@@ -1,7 +1,7 @@"use client";import { useMemo } from "react";-import { useQuery } from "@tanstack/react-query";+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";import { issueStatusListOptions, buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";import {parseTabSubject,@@ -27,8 +27,10 @@ import { runtimeDisplayName } from "@multica/core/runtimes";import { chatSessionsOptions } from "@multica/core/chat/queries";import {inboxListOptions,- archivedInboxListOptions,+ archivedInboxPagesOptions,+ archivedInboxLookupOptions,} from "@multica/core/inbox/queries";+import { useInboxFilters } from "@multica/core/inbox/filter-store";import { cn } from "@multica/ui/lib/utils";import { StatusIcon } from "../issues/components";import { ProjectIcon } from "../projects/components/project-icon";@@ -81,10 +83,16 @@ function useTabEntityData(subject: TabSubject, wsId: string): TabEntityData {// an archived selection has to resolve against the archived cache — the same// list the InboxPage populates when `?view=archived` is active.const inboxList = useQuery({ ...inboxListOptions(wsId), enabled: false }).data;- const archivedInboxList = useQuery({- ...archivedInboxListOptions(wsId),+ const inboxFilters = useInboxFilters(wsId);+ const archivedPages = useInfiniteQuery({ ...archivedInboxPagesOptions(wsId, inboxFilters), enabled: false }).data;+ const archivedLookup = useQuery({+ ...archivedInboxLookupOptions(wsId, subject.kind === "inbox" ? subject.selectedKey ?? "" : ""),enabled: false,}).data;+ const archivedInboxList = useMemo(() => [+ ...(archivedPages?.pages.flatMap((page) => page.items) ?? []),+ ...(archivedLookup?.items ?? []),+ ], [archivedPages, archivedLookup]);const activeInboxList =subject.kind === "inbox" && subject.archived ? archivedInboxList : inboxList;const inboxItem =diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.jsonindex 2dc722a884..736f050468 100644--- a/packages/views/locales/en/inbox.json+++ b/packages/views/locales/en/inbox.json@@ -30,6 +30,7 @@"open_in_new_tab": "Open in new tab"},"list": {+ "loading_selection": "Loading notification…","empty": "No notifications","mark_done_tooltip": "Mark as done","archive_tooltip": "Archive",@@ -42,7 +43,10 @@"archived_title": "Archived","archived_empty": "No archived notifications","unarchive_tooltip": "Unarchive",- "actions_aria": "Notification actions"+ "actions_aria": "Notification actions",+ "load_more": "Load more",+ "loading_more": "Loading…",+ "retry": "Retry"},"detail": {"select_prompt": "Select a notification to view details",@@ -98,6 +102,7 @@"unarchived": "Notification restored"},"errors": {+ "archived_lookup_failed": "Failed to load the linked notification","source_context_retry_failed": "Could not retry with the original context","source_context_retry_unavailable": "This context can no longer be retried. Start again from the branch point.","mark_read_failed": "Failed to mark as read",@@ -109,6 +114,7 @@"archive_all_read_failed": "Failed to archive read items","archive_completed_failed": "Failed to archive completed","unarchive_failed": "Failed to unarchive",- "archived_load_failed": "Failed to load archived notifications"+ "archived_load_failed": "Failed to load archived notifications",+ "filters_load_failed": "Could not load filters"}}diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.jsonindex 2e10dbdf6c..4411ac5262 100644--- a/packages/views/locales/fr/inbox.json+++ b/packages/views/locales/fr/inbox.json@@ -30,6 +30,7 @@"open_in_new_tab": "Ouvrir dans un nouvel onglet"},"list": {+ "loading_selection": "Chargement de la notification…","empty": "Aucune notification","mark_done_tooltip": "Marquer comme traité","archive_tooltip": "Archiver",@@ -42,7 +43,10 @@"archived_title": "Archivées","archived_empty": "Aucune notification archivée","unarchive_tooltip": "Désarchiver",- "actions_aria": "Actions de notification"+ "actions_aria": "Actions de notification",+ "load_more": "Charger plus",+ "loading_more": "Chargement…",+ "retry": "Réessayer"},"detail": {"select_prompt": "Sélectionnez une notification pour afficher les détails",@@ -98,6 +102,7 @@"unarchived": "Notification restaurée"},"errors": {+ "archived_lookup_failed": "Échec du chargement de la notification liée","source_context_retry_failed": "Impossible de réessayer avec le contexte d'origine","source_context_retry_unavailable": "Ce contexte ne peut plus être réutilisé pour une nouvelle tentative. Recommencez depuis le point de branchement.","mark_read_failed": "Échec du marquage comme lu",@@ -109,6 +114,7 @@"archive_all_read_failed": "Échec de l'archivage des éléments lus","archive_completed_failed": "Échec de l'archivage des éléments terminés","unarchive_failed": "Échec du désarchivage",- "archived_load_failed": "Échec du chargement des notifications archivées"+ "archived_load_failed": "Échec du chargement des notifications archivées",+ "filters_load_failed": "Impossible de charger les filtres"}}diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.jsonindex 5bfb9b6b18..16c404e698 100644--- a/packages/views/locales/ja/inbox.json+++ b/packages/views/locales/ja/inbox.json@@ -28,6 +28,7 @@"open_in_new_tab": "新しいタブで開く"},"list": {+ "loading_selection": "通知を読み込み中…","empty": "通知はありません","mark_done_tooltip": "完了にする","archive_tooltip": "アーカイブ",@@ -40,7 +41,10 @@"archived_title": "アーカイブ済み","archived_empty": "アーカイブされた通知はありません","unarchive_tooltip": "アーカイブ解除",- "actions_aria": "通知の操作"+ "actions_aria": "通知の操作",+ "load_more": "さらに読み込む",+ "loading_more": "読み込み中…",+ "retry": "再試行"},"detail": {"select_prompt": "詳細を表示する通知を選択してください",@@ -96,6 +100,7 @@"unarchived": "通知を元に戻しました"},"errors": {+ "archived_lookup_failed": "リンク先の通知を読み込めませんでした","source_context_retry_failed": "元のコンテキストで再試行できませんでした","source_context_retry_unavailable": "このコンテキストは再試行できません。分岐点からやり直してください。","mark_read_failed": "既読にできませんでした",@@ -107,6 +112,7 @@"archive_all_read_failed": "既読の項目をアーカイブできませんでした","archive_completed_failed": "完了した項目をアーカイブできませんでした","unarchive_failed": "アーカイブ解除に失敗しました",- "archived_load_failed": "アーカイブ済み通知を読み込めませんでした"+ "archived_load_failed": "アーカイブ済み通知を読み込めませんでした",+ "filters_load_failed": "フィルターを読み込めませんでした"}}diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.jsonindex 7c0b68a8f4..1a706a846c 100644--- a/packages/views/locales/ko/inbox.json+++ b/packages/views/locales/ko/inbox.json@@ -28,6 +28,7 @@"open_in_new_tab": "새 탭에서 열기"},"list": {+ "loading_selection": "알림을 불러오는 중…","empty": "알림이 없습니다","mark_done_tooltip": "완료로 표시","archive_tooltip": "보관",@@ -40,7 +41,10 @@"archived_title": "보관됨","archived_empty": "보관된 알림이 없습니다","unarchive_tooltip": "보관 해제",- "actions_aria": "알림 작업"+ "actions_aria": "알림 작업",+ "load_more": "더 불러오기",+ "loading_more": "불러오는 중…",+ "retry": "다시 시도"},"detail": {"select_prompt": "자세히 볼 알림을 선택하세요",@@ -96,6 +100,7 @@"unarchived": "알림을 복원했습니다"},"errors": {+ "archived_lookup_failed": "링크된 알림을 불러오지 못했습니다","source_context_retry_failed": "원본 컨텍스트로 재시도하지 못했습니다","source_context_retry_unavailable": "이 컨텍스트는 더 이상 재시도할 수 없습니다. 분기 지점에서 다시 시작하세요.","mark_read_failed": "읽음 표시를 하지 못했습니다",@@ -107,6 +112,7 @@"archive_all_read_failed": "읽은 항목을 보관하지 못했습니다","archive_completed_failed": "완료된 항목을 보관하지 못했습니다","unarchive_failed": "보관 해제에 실패했습니다",- "archived_load_failed": "보관된 알림을 불러오지 못했습니다"+ "archived_load_failed": "보관된 알림을 불러오지 못했습니다",+ "filters_load_failed": "필터를 불러올 수 없습니다"}}diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.jsonindex b9ce5648c1..6aff9140b6 100644--- a/packages/views/locales/zh-Hans/inbox.json+++ b/packages/views/locales/zh-Hans/inbox.json@@ -28,6 +28,7 @@"open_in_new_tab": "在新标签页打开"},"list": {+ "loading_selection": "正在加载通知…","empty": "暂无通知","mark_done_tooltip": "标为已完成","archive_tooltip": "归档",@@ -40,7 +41,10 @@"archived_title": "已归档","archived_empty": "暂无已归档通知","unarchive_tooltip": "取消归档",- "actions_aria": "通知操作"+ "actions_aria": "通知操作",+ "load_more": "加载更多",+ "loading_more": "加载中...",+ "retry": "重试"},"detail": {"select_prompt": "选择一条通知查看详情",@@ -96,6 +100,7 @@"unarchived": "已恢复通知"},"errors": {+ "archived_lookup_failed": "无法加载链接指向的通知","source_context_retry_failed": "无法使用原始上下文重试","source_context_retry_unavailable": "该上下文已无法重试,请从派生起点重新发起。","mark_read_failed": "标为已读失败",@@ -107,6 +112,7 @@"archive_all_read_failed": "归档已读失败","archive_completed_failed": "归档已完成失败","unarchive_failed": "取消归档失败",- "archived_load_failed": "无法加载已归档通知"+ "archived_load_failed": "无法加载已归档通知",+ "filters_load_failed": "无法加载筛选项"}}diff --git a/server/cmd/server/inbox_archive_test.go b/server/cmd/server/inbox_archive_test.gonew file mode 100644index 0000000000..8c3395f1ca--- /dev/null+++ b/server/cmd/server/inbox_archive_test.go@@ -0,0 +1,39 @@+package main++import (+ "testing"++ "github.com/google/uuid"+)++// Exercise routing and the JSON contract; group/filter semantics live in the+// handler suite, where fixtures isolate every archive from other test data.+func TestArchivedInboxPageAndFacetsThroughRouter(t *testing.T) {+ resp := authRequest(t, "GET", "/api/inbox/archived/page?group_id="+uuid.NewString(), nil)+ if resp.StatusCode != 200 {+ t.Fatalf("archive page status = %d", resp.StatusCode)+ }+ var page struct {+ Items []inboxItemJSON `json:"items"`+ NextCursor *string `json:"next_cursor"`+ HasMore bool `json:"has_more"`+ }+ readJSON(t, resp, &page)+ if page.Items == nil || len(page.Items) != 0 || page.NextCursor != nil || page.HasMore {+ t.Fatalf("empty lookup contract: %+v", page)+ }+ resp = authRequest(t, "GET", "/api/inbox/archived/facets", nil)+ if resp.StatusCode != 200 {+ t.Fatalf("archive facets status = %d", resp.StatusCode)+ }+ var facets struct {+ Statuses map[string]int64 `json:"statuses"`+ Priorities map[string]int64 `json:"priorities"`+ Actors map[string]int64 `json:"actors"`+ UnreadCount int64 `json:"unread_count"`+ }+ readJSON(t, resp, &facets)+ if facets.Statuses == nil || facets.Priorities == nil || facets.Actors == nil || facets.UnreadCount < 0 {+ t.Fatalf("facets contract: %+v", facets)+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex cc0a9ec101..309776bca5 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2299,6 +2299,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Separate from "/" so the main list keeps its contract and// never carries the unbounded archive.r.Get("/archived", h.ListArchivedInbox)+ r.Get("/archived/page", h.ListArchivedInboxPage)+ r.Get("/archived/facets", h.GetArchivedInboxFacets)r.Get("/unread-count", h.CountUnreadInbox)// Cross-workspace unread summary: account-level, keyed on the// user. Backs the workspace-switcher dot for OTHER workspaces.diff --git a/server/internal/handler/inbox_archive.go b/server/internal/handler/inbox_archive.gonew file mode 100644index 0000000000..bdf33694bb--- /dev/null+++ b/server/internal/handler/inbox_archive.go@@ -0,0 +1,198 @@+package handler++import (+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "net/http"+ "slices"+ "strconv"+ "strings"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type archivedInboxCursor struct {+ Time string `json:"time"`+ ID string `json:"id"`+ Scope string `json:"scope"`+}++type archivedInboxPageResponse struct {+ Items []InboxItemResponse `json:"items"`+ NextCursor *string `json:"next_cursor"`+ HasMore bool `json:"has_more"`+}++type archivedInboxFacetsResponse struct {+ Statuses map[string]int64 `json:"statuses"`+ Priorities map[string]int64 `json:"priorities"`+ Actors map[string]int64 `json:"actors"`+ UnreadCount int64 `json:"unread_count"`+}++func parseArchivedInboxFilters(w http.ResponseWriter, r *http.Request) (db.ArchivedInboxFacetsParams, bool) {+ var p db.ArchivedInboxFacetsParams+ userID, ok := requireUserID(w, r)+ if !ok {+ return p, false+ }+ p.WorkspaceID, ok = parseUUIDOrBadRequest(w, ctxWorkspaceID(r.Context()), "workspace id")+ if !ok {+ return p, false+ }+ p.RecipientID = parseUUID(userID)+ q := r.URL.Query()+ for name, target := range map[string]*[]string{"statuses": &p.Statuses, "priorities": &p.Priorities, "actors": &p.Actors} {+ *target = []string{}+ if raw := q.Get(name); raw != "" {+ if len(raw) > 8192 {+ writeError(w, http.StatusBadRequest, "filter is too long")+ return p, false+ }+ *target = strings.Split(raw, ",")+ if len(*target) > 100 {+ writeError(w, http.StatusBadRequest, "too many filter values")+ return p, false+ }+ for _, value := range *target {+ if value == "" {+ writeError(w, http.StatusBadRequest, "empty filter value")+ return p, false+ }+ }+ slices.Sort(*target)+ *target = slices.Compact(*target)+ }+ }+ if raw := q.Get("unread_only"); raw != "" {+ if raw != "true" && raw != "false" {+ writeError(w, http.StatusBadRequest, "invalid unread_only")+ return p, false+ }+ p.UnreadOnly = raw == "true"+ }+ return p, true+}++// A cursor is tied to the recipient and filters, so it cannot accidentally+// continue a different archive or a changed filter selection.+func archivedInboxScope(p db.ArchivedInboxFacetsParams, groupID pgtype.UUID) string {+ encoded, _ := json.Marshal(struct {+ Filters db.ArchivedInboxFacetsParams+ Group pgtype.UUID+ }{p, groupID})+ return fmt.Sprintf("%x", sha256.Sum256(encoded))+}++func (h *Handler) ListArchivedInboxPage(w http.ResponseWriter, r *http.Request) {+ filters, ok := parseArchivedInboxFilters(w, r)+ if !ok {+ return+ }+ p := db.ListArchivedInboxPageParams{+ WorkspaceID: filters.WorkspaceID, RecipientID: filters.RecipientID,+ Statuses: filters.Statuses, Priorities: filters.Priorities, Actors: filters.Actors, UnreadOnly: filters.UnreadOnly,+ }+ limit := 50+ if raw := r.URL.Query().Get("limit"); raw != "" {+ var err error+ limit, err = strconv.Atoi(raw)+ if err != nil || limit < 1 || limit > 100 {+ writeError(w, http.StatusBadRequest, "limit must be between 1 and 100")+ return+ }+ }+ if raw := r.URL.Query().Get("group_id"); raw != "" {+ p.GroupID, ok = parseUUIDOrBadRequest(w, raw, "group_id")+ if !ok {+ return+ }+ }+ scope := archivedInboxScope(filters, p.GroupID)+ if raw := r.URL.Query().Get("cursor"); raw != "" {+ if len(raw) > 2048 {+ writeError(w, http.StatusBadRequest, "invalid archive cursor")+ return+ }+ var cursor archivedInboxCursor+ decoded, err := base64.RawURLEncoding.DecodeString(raw)+ if err != nil || json.Unmarshal(decoded, &cursor) != nil || cursor.Scope != scope {+ writeError(w, http.StatusBadRequest, "invalid archive cursor")+ return+ }+ before, err := time.Parse(time.RFC3339Nano, cursor.Time)+ if err != nil {+ writeError(w, http.StatusBadRequest, "invalid archive cursor time")+ return+ }+ p.BeforeID, ok = parseUUIDOrBadRequest(w, cursor.ID, "cursor id")+ if !ok {+ return+ }+ p.BeforeTime = pgtype.Timestamptz{Time: before, Valid: true}+ }+ p.PageLimit = int32(limit + 1)+ rows, err := h.Queries.ListArchivedInboxPage(r.Context(), p)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load archived inbox page")+ return+ }+ resp := archivedInboxPageResponse{Items: make([]InboxItemResponse, 0, limit), HasMore: len(rows) > limit}+ if resp.HasMore {+ rows = rows[:limit]+ }+ for _, row := range rows {+ 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)+ if row.CommentID != "" {+ var details map[string]json.RawMessage+ if len(item.Details) == 0 || string(item.Details) == "null" {+ details = map[string]json.RawMessage{}+ } else if err := json.Unmarshal(item.Details, &details); err != nil {+ writeError(w, http.StatusInternalServerError, "invalid archived notification details")+ return+ }+ details["comment_id"], _ = json.Marshal(row.CommentID)+ item.Details, _ = json.Marshal(details)+ }+ resp.Items = append(resp.Items, item)+ }+ if resp.HasMore {+ last := rows[len(rows)-1].InboxItem+ encoded, _ := json.Marshal(archivedInboxCursor{Time: last.CreatedAt.Time.Format(time.RFC3339Nano), ID: uuidToString(last.ID), Scope: scope})+ cursor := base64.RawURLEncoding.EncodeToString(encoded)+ resp.NextCursor = &cursor+ }+ writeJSON(w, http.StatusOK, resp)+}++func (h *Handler) GetArchivedInboxFacets(w http.ResponseWriter, r *http.Request) {+ p, ok := parseArchivedInboxFilters(w, r)+ if !ok {+ return+ }+ rows, err := h.Queries.ArchivedInboxFacets(r.Context(), p)+ if err != nil {+ 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{}}+ for _, row := range rows {+ 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+ }+ }+ writeJSON(w, http.StatusOK, resp)+}diff --git a/server/internal/handler/inbox_archive_test.go b/server/internal/handler/inbox_archive_test.gonew file mode 100644index 0000000000..534d0758ac--- /dev/null+++ b/server/internal/handler/inbox_archive_test.go@@ -0,0 +1,146 @@+package handler++import (+ "net/http"+ "net/url"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestArchivedInboxPageBeyond200(t *testing.T) {+ ws := dbfx.Workspace(t, "Paged archive", "archive-page-"+uuid.NewString())+ dbfx.Member(t, ws, testUserID, "owner")+ // Equal timestamps exercise the ID tie-breaker at every page boundary.+ created := time.Now().UTC().Truncate(time.Microsecond)+ for range 205 {+ issue := dbfx.Issue(t, "Archived", testutil.Cols{"workspace_id": ws})+ dbfx.Insert(t, "inbox_item", testutil.Cols{+ "workspace_id": ws, "recipient_type": "member", "recipient_id": testUserID,+ "type": "mentioned", "severity": "info", "title": "Archived", "issue_id": issue,+ "archived": true, "created_at": created,+ })+ }+ seen := map[string]bool{}+ cursor := ""+ var firstCursor string+ for pageNumber := 0; ; pageNumber++ {+ if pageNumber > 5 {+ t.Fatal("pagination did not terminate")+ }+ var page archivedInboxPageResponse+ path := "/api/inbox/archived/page?limit=50&cursor=" + url.QueryEscape(cursor)+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListArchivedInboxPage), inboxRequest(http.MethodGet, path, ws)).Want(http.StatusOK).JSON(&page)+ for _, item := range page.Items {+ if item.IssueID == nil || seen[*item.IssueID] {+ t.Fatalf("missing or duplicate group: %+v", item)+ }+ seen[*item.IssueID] = true+ }+ if !page.HasMore {+ if page.NextCursor != nil {+ t.Fatal("last page has a cursor")+ }+ break+ }+ if len(page.Items) != 50 || page.NextCursor == nil {+ t.Fatalf("invalid page: %+v", page)+ }+ cursor = *page.NextCursor+ if firstCursor == "" {+ firstCursor = cursor+ }+ }+ if len(seen) != 205 {+ t.Fatalf("got %d groups, want 205", len(seen))+ }+ // Old installed clients retain their capped array response.+ var legacy []InboxItemResponse+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListArchivedInbox), inboxRequest(http.MethodGet, "/api/inbox/archived", ws)).Want(http.StatusOK).JSON(&legacy)+ if len(legacy) != 200 {+ t.Fatalf("legacy archive = %d, want 200", len(legacy))+ }+ for _, query := range []string{"limit=0", "limit=101", "cursor=broken", "group_id=bad", "unread_only=bad", "statuses=a,,b", "unread_only=true&cursor=" + firstCursor} {+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListArchivedInboxPage), inboxRequest(http.MethodGet, "/api/inbox/archived/page?"+query, ws)).Want(http.StatusBadRequest)+ }+}++func TestArchivedInboxFiltersAndLookupUseLatestGroup(t *testing.T) {+ ws := dbfx.Workspace(t, "Archive filters", "archive-filter-"+uuid.NewString())+ dbfx.Member(t, ws, testUserID, "owner")+ issue := dbfx.Issue(t, "Older matching group", testutil.Cols{"workspace_id": ws, "status": "in_review", "priority": "high"})+ actor := uuid.NewString()+ comment := uuid.NewString()+ old := time.Now().UTC().Add(-time.Hour)+ insert := func(issueID *string, read bool, actorType string, actorID *string, created time.Time, details string, archived bool) string {+ return dbfx.Insert(t, "inbox_item", testutil.Cols{+ "workspace_id": ws, "recipient_type": "member", "recipient_id": testUserID,+ "type": "mentioned", "severity": "info", "title": "Archive filter", "issue_id": issueID,+ "read": read, "actor_type": actorType, "actor_id": actorID, "archived": archived,+ "created_at": created, "details": details,+ })+ }+ insert(&issue, false, "agent", &actor, old.Add(-time.Minute), `{"comment_id":"`+comment+`"}`, true)+ newest := insert(&issue, true, "system", nil, old, `{}`, true)+ // Fill the newest page with nonmatching groups, so a local filter would miss the match.+ for range 55 {+ insert(nil, false, "agent", &actor, old.Add(time.Minute), `{}`, true)+ }+ 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+ }+ page := get("statuses=in_review&priorities=high&actors=system")+ if len(page.Items) != 1 || page.Items[0].ID != newest {+ t.Fatalf("filter lost older match: %+v", page)+ }+ if string(page.Items[0].Details) != `{"comment_id":"`+comment+`"}` {+ t.Fatalf("comment anchor lost: %s", page.Items[0].Details)+ }+ 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")+ }+ 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 {+ t.Fatalf("incorrect facets: %+v", facets)+ }+ insert(&issue, false, "system", nil, time.Now(), `{}`, false)+ if len(get("group_id="+issue).Items) != 0 {+ t.Fatal("active issue also appeared in archive")+ }+ // Another recipient and another workspace cannot read this archive, including lookup.+ otherWS := dbfx.Workspace(t, "Other archive", "other-archive-"+uuid.NewString())+ dbfx.Member(t, otherWS, testUserID, "owner")+ var other archivedInboxPageResponse+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListArchivedInboxPage), inboxRequest(http.MethodGet, "/api/inbox/archived/page?group_id="+issue, otherWS)).Want(http.StatusOK).JSON(&other)+ if len(other.Items) != 0 {+ t.Fatal("cross-workspace archive leak")+ }+ otherUser := dbfx.User(t, "Other recipient", uuid.NewString()+"@example.test")+ dbfx.Member(t, ws, otherUser, "member")+ req := inboxRequest(http.MethodGet, "/api/inbox/archived/page?group_id="+issue, ws)+ req.Header.Set("X-User-ID", otherUser)+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListArchivedInboxPage), req).Want(http.StatusOK).JSON(&other)+ if len(other.Items) != 0 {+ t.Fatal("cross-recipient archive leak")+ }+ insert(&issue, false, "system", nil, time.Now(), `{}`, false)+ if len(get("group_id="+issue).Items) != 0 {+ t.Fatal("active issue also appeared in archive")+ }+ for _, handler := range []http.HandlerFunc{testHandler.ListArchivedInboxPage, testHandler.GetArchivedInboxFacets} {+ req := inboxRequest(http.MethodGet, "/api/inbox/archived/page", ws)+ req.Header.Set("X-User-ID", uuid.NewString())+ testutil.Call(t, inboxWorkspaceHandler(handler), req).Want(http.StatusNotFound)+ }+}diff --git a/server/pkg/db/generated/inbox_archive.sql.go b/server/pkg/db/generated/inbox_archive.sql.gonew file mode 100644index 0000000000..c4e6438ccf--- /dev/null+++ b/server/pkg/db/generated/inbox_archive.sql.go@@ -0,0 +1,233 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: inbox_archive.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++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,+ CASE WHEN i.actor_type = 'system' THEN 'system'+ ELSE i.actor_type || ':' || i.actor_id::text END AS actor+ FROM inbox_item i+ WHERE i.workspace_id = $1::uuid+ AND i.recipient_type = 'member'+ AND i.recipient_id = $2::uuid+ AND i.archived = true+ AND (i.issue_id IS NULL OR NOT EXISTS (+ SELECT 1 FROM inbox_item active+ WHERE active.workspace_id = i.workspace_id+ AND active.recipient_type = i.recipient_type+ 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+), 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+ 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+ FROM projected+)+SELECT 'statuses'::text AS dimension, issue_status::text AS key,+ count(*) FILTER (WHERE priority_match AND actor_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+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+UNION ALL+SELECT 'unread'::text, 'unread'::text,+ count(*) FILTER (WHERE status_match AND priority_match AND actor_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"`+}++type ArchivedInboxFacetsRow struct {+ Dimension string `json:"dimension"`+ Key string `json:"key"`+ Count int64 `json:"count"`+}++// Select narrow group representatives before loading bodies or comment anchors.+func (q *Queries) ArchivedInboxFacets(ctx context.Context, arg ArchivedInboxFacetsParams) ([]ArchivedInboxFacetsRow, error) {+ rows, err := q.db.Query(ctx, archivedInboxFacets,+ arg.WorkspaceID,+ arg.RecipientID,+ arg.Statuses,+ arg.Priorities,+ arg.Actors,+ arg.UnreadOnly,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ArchivedInboxFacetsRow{}+ for rows.Next() {+ var i ArchivedInboxFacetsRow+ if err := rows.Scan(&i.Dimension, &i.Key, &i.Count); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++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,+ CASE WHEN i.actor_type = 'system' THEN 'system'+ ELSE i.actor_type || ':' || i.actor_id::text END AS actor+ FROM inbox_item i+ WHERE i.workspace_id = $1::uuid+ AND i.recipient_type = 'member'+ AND i.recipient_id = $2::uuid+ AND i.archived = true+ AND ($3::uuid IS NULL OR i.issue_id = $3::uuid+ OR (i.issue_id IS NULL AND i.id = $3::uuid))+ AND (i.issue_id IS NULL OR NOT EXISTS (+ SELECT 1 FROM inbox_item active+ WHERE active.workspace_id = i.workspace_id+ AND active.recipient_type = i.recipient_type+ 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+), 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+ 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+ 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))+ ORDER BY created_at DESC, id DESC+ LIMIT $10::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, selected.issue_status, selected.issue_priority,+ COALESCE(anchor.comment_id, '')::text AS comment_id+FROM selected+JOIN inbox_item i ON i.id = selected.id+LEFT JOIN LATERAL (+ SELECT a.details->>'comment_id' AS comment_id+ FROM inbox_item a+ WHERE i.issue_id IS NOT NULL AND a.issue_id = i.issue_id+ AND a.workspace_id = i.workspace_id AND a.recipient_type = i.recipient_type+ AND a.recipient_id = i.recipient_id AND a.archived = true+ AND NULLIF(a.details->>'comment_id', '') IS NOT NULL+ ORDER BY a.created_at DESC, a.id DESC LIMIT 1+) anchor ON true+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"`+}++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"`+}++// 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.Statuses,+ arg.Priorities,+ arg.Actors,+ arg.UnreadOnly,+ arg.BeforeTime,+ arg.BeforeID,+ arg.PageLimit,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListArchivedInboxPageRow{}+ for rows.Next() {+ var i ListArchivedInboxPageRow+ if err := rows.Scan(+ &i.InboxItem.ID,+ &i.InboxItem.WorkspaceID,+ &i.InboxItem.RecipientType,+ &i.InboxItem.RecipientID,+ &i.InboxItem.Type,+ &i.InboxItem.Severity,+ &i.InboxItem.IssueID,+ &i.InboxItem.Title,+ &i.InboxItem.Body,+ &i.InboxItem.Read,+ &i.InboxItem.Archived,+ &i.InboxItem.CreatedAt,+ &i.InboxItem.ActorType,+ &i.InboxItem.ActorID,+ &i.InboxItem.Details,+ &i.IssueStatus,+ &i.IssuePriority,+ &i.CommentID,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}diff --git a/server/pkg/db/queries/inbox_archive.sql b/server/pkg/db/queries/inbox_archive.sqlnew file mode 100644index 0000000000..ac56469558--- /dev/null+++ b/server/pkg/db/queries/inbox_archive.sql@@ -0,0 +1,106 @@+-- 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,+ CASE WHEN i.actor_type = 'system' THEN 'system'+ ELSE i.actor_type || ':' || i.actor_id::text END AS actor+ FROM inbox_item i+ WHERE i.workspace_id = sqlc.arg(workspace_id)::uuid+ AND i.recipient_type = 'member'+ AND i.recipient_id = sqlc.arg(recipient_id)::uuid+ AND i.archived = true+ AND (sqlc.narg(group_id)::uuid IS NULL OR i.issue_id = sqlc.narg(group_id)::uuid+ OR (i.issue_id IS NULL AND i.id = sqlc.narg(group_id)::uuid))+ AND (i.issue_id IS NULL OR NOT EXISTS (+ SELECT 1 FROM inbox_item active+ WHERE active.workspace_id = i.workspace_id+ AND active.recipient_type = i.recipient_type+ 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+), 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+ 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+ FROM projected+)+, selected AS (+ SELECT * FROM matched+ WHERE status_match AND priority_match AND actor_match AND read_match+ 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+FROM selected+JOIN inbox_item i ON i.id = selected.id+LEFT JOIN LATERAL (+ SELECT a.details->>'comment_id' AS comment_id+ FROM inbox_item a+ WHERE i.issue_id IS NOT NULL AND a.issue_id = i.issue_id+ AND a.workspace_id = i.workspace_id AND a.recipient_type = i.recipient_type+ AND a.recipient_id = i.recipient_id AND a.archived = true+ AND NULLIF(a.details->>'comment_id', '') IS NOT NULL+ ORDER BY a.created_at DESC, a.id DESC LIMIT 1+) anchor ON true+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,+ CASE WHEN i.actor_type = 'system' THEN 'system'+ ELSE i.actor_type || ':' || i.actor_id::text END AS actor+ FROM inbox_item i+ WHERE i.workspace_id = sqlc.arg(workspace_id)::uuid+ AND i.recipient_type = 'member'+ AND i.recipient_id = sqlc.arg(recipient_id)::uuid+ AND i.archived = true+ AND (i.issue_id IS NULL OR NOT EXISTS (+ SELECT 1 FROM inbox_item active+ WHERE active.workspace_id = i.workspace_id+ AND active.recipient_type = i.recipient_type+ 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+), 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+ 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+ FROM projected+)+SELECT 'statuses'::text AS dimension, issue_status::text AS key,+ count(*) FILTER (WHERE priority_match AND actor_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+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+UNION ALL+SELECT 'unread'::text, 'unread'::text,+ count(*) FILTER (WHERE status_match AND priority_match AND actor_match AND NOT read)::bigint+FROM matched;