Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(inbox): archived notifications sub-view (MUL-3736) (#5518)
Naiyuan Qing6b2097ccbb3c
diff --git a/apps/mobile/data/realtime/use-inbox-realtime.ts b/apps/mobile/data/realtime/use-inbox-realtime.tsindex 6fc885053f..9b2753464d 100644--- a/apps/mobile/data/realtime/use-inbox-realtime.ts+++ b/apps/mobile/data/realtime/use-inbox-realtime.ts@@ -43,6 +43,10 @@ export function useInboxRealtime() {ws.on("inbox:new", invalidate),ws.on("inbox:read", invalidate),ws.on("inbox:archived", invalidate),+ // Mobile has no archived view yet (web/desktop only, MUL-3736), but an+ // unarchive there restores the item to THIS list — without refetching,+ // mobile keeps showing the pre-restore list.+ ws.on("inbox:unarchived", invalidate),ws.on("inbox:batch-read", invalidate),ws.on("inbox:batch-archived", invalidate),diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 73ff7bf788..09c85cad62 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -239,6 +239,8 @@ import {EMPTY_CREATE_FEEDBACK_RESPONSE,InboxUnreadSummarySchema,EMPTY_INBOX_UNREAD_SUMMARY,+ InboxItemListSchema,+ EMPTY_INBOX_ITEMS,NotificationPreferenceResponseSchema,EMPTY_NOTIFICATION_PREFERENCE_RESPONSE,LabelSchema,@@ -1596,6 +1598,20 @@ export class ApiClient {return this.fetch(`/api/inbox/${id}/archive`, { method: "POST" });}+ // Archived notifications, backing the inbox's "Archived" sub-view. Capped+ // server-side (no pagination in v1). Schema-guarded so a contract drift+ // renders an empty archive instead of taking the inbox down with it.+ async listArchivedInbox(): Promise<InboxItem[]> {+ const raw = await this.fetch<unknown>("/api/inbox/archived");+ return parseWithFallback(raw, InboxItemListSchema, EMPTY_INBOX_ITEMS, {+ endpoint: "GET /api/inbox/archived",+ });+ }++ async unarchiveInbox(id: string): Promise<InboxItem> {+ return this.fetch(`/api/inbox/${id}/unarchive`, { method: "POST" });+ }+async getUnreadInboxCount(): Promise<{ count: number }> {return this.fetch("/api/inbox/unread-count");}diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 66be38cc00..712e2aaf2e 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -13,9 +13,11 @@ import {DuplicateIssueErrorBodySchema,EMPTY_CHAT_DRAFT_RESTORES,EMPTY_CREATE_FEEDBACK_RESPONSE,+ EMPTY_INBOX_ITEMS,EMPTY_INBOX_UNREAD_SUMMARY,EMPTY_SEARCH_PROJECTS_RESPONSE,EMPTY_USER,+ InboxItemListSchema,InboxUnreadSummarySchema,IssueTriggerPreviewSchema,ListIssuesResponseSchema,@@ -731,6 +733,86 @@ describe("InboxUnreadSummarySchema", () => {});});+describe("InboxItemListSchema", () => {+ const ENDPOINT = { endpoint: "GET /api/inbox/archived" };++ const row = (overrides: Record<string, unknown> = {}) => ({+ id: "inbox-1",+ workspace_id: "ws-1",+ recipient_type: "member",+ recipient_id: "member-1",+ type: "new_comment",+ severity: "info",+ issue_id: "issue-1",+ title: "Issue title",+ body: null,+ read: false,+ archived: true,+ created_at: "2026-06-15T08:00:00Z",+ ...overrides,+ });++ it("parses a well-formed archived list and tolerates extra fields", () => {+ const parsed = parseWithFallback(+ [row({ issue_status: "in_progress", details: { comment_id: "c-1" }, future_field: 1 })],+ InboxItemListSchema,+ EMPTY_INBOX_ITEMS,+ ENDPOINT,+ );+ expect(parsed).toHaveLength(1);+ expect(parsed[0]).toMatchObject({ id: "inbox-1", archived: true });+ });++ it("keeps a notification type this client doesn't know yet", () => {+ // Enums stay lenient on purpose: a backend that ships a new inbox type+ // must not blank the whole archived list on older clients.+ const parsed = parseWithFallback(+ [row({ type: "some_future_type", severity: "future_severity" })],+ InboxItemListSchema,+ EMPTY_INBOX_ITEMS,+ ENDPOINT,+ );+ expect(parsed).toHaveLength(1);+ });++ it("accepts rows that omit the nullable optional fields", () => {+ const { body, issue_id, ...withoutOptionals } = row();+ void body;+ void issue_id;+ expect(+ parseWithFallback([withoutOptionals], InboxItemListSchema, EMPTY_INBOX_ITEMS, ENDPOINT),+ ).toHaveLength(1);+ });++ it("returns the empty fallback for a non-array body", () => {+ expect(+ parseWithFallback({ items: [] }, InboxItemListSchema, EMPTY_INBOX_ITEMS, ENDPOINT),+ ).toBe(EMPTY_INBOX_ITEMS);+ expect(+ parseWithFallback(null, InboxItemListSchema, EMPTY_INBOX_ITEMS, ENDPOINT),+ ).toBe(EMPTY_INBOX_ITEMS);+ });++ it("returns the empty fallback when a row is missing a required field", () => {+ const { id, ...withoutId } = row();+ void id;+ expect(+ parseWithFallback([withoutId], InboxItemListSchema, EMPTY_INBOX_ITEMS, ENDPOINT),+ ).toBe(EMPTY_INBOX_ITEMS);+ });++ it("returns the empty fallback when `archived` is wrong-typed", () => {+ expect(+ parseWithFallback(+ [row({ archived: "yes" })],+ InboxItemListSchema,+ EMPTY_INBOX_ITEMS,+ ENDPOINT,+ ),+ ).toBe(EMPTY_INBOX_ITEMS);+ });+});+describe("SearchProjectsResponseSchema date drift", () => {const ENDPOINT = { endpoint: "GET /api/projects/search" };diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex f1390ba8fc..f190c7c48d 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -18,6 +18,7 @@ import type {CreateBillingCheckoutSessionResponse,CreateBillingPortalSessionResponse,GroupedIssuesResponse,+ InboxItem,InboxWorkspaceUnread,Label,IssueProperty,@@ -1313,6 +1314,38 @@ export const InboxUnreadSummarySchema = z.array(export const EMPTY_INBOX_UNREAD_SUMMARY: InboxWorkspaceUnread[] = [];+// ---------------------------------------------------------------------------+// Archived inbox items (`/api/inbox/archived` GET).+// Lenient per the usual rules: `severity` / `type` / `recipient_type` stay+// `z.string()` so a notification kind this client doesn't know yet still+// parses and renders (the UI's type-label lookup already tolerates unknown+// kinds). Nullable optional fields are declared optional as well, since older+// rows can omit them entirely. On malformed JSON parseWithFallback returns the+// empty list — the archived view then reads as empty rather than white-+// screening the inbox.+// ---------------------------------------------------------------------------++export const InboxItemListSchema = z.array(+ z+ .object({+ id: z.string(),+ workspace_id: z.string(),+ recipient_type: z.string(),+ recipient_id: z.string(),+ type: z.string(),+ severity: z.string(),+ issue_id: z.string().nullish(),+ title: z.string(),+ body: z.string().nullish(),+ read: z.boolean(),+ archived: z.boolean(),+ created_at: z.string(),+ })+ .loose(),+);++export const EMPTY_INBOX_ITEMS: InboxItem[] = [];+// ---------------------------------------------------------------------------// Billing schemas (cloud-billing proxy surface)//diff --git a/packages/core/inbox/mutations.test.tsx b/packages/core/inbox/mutations.test.tsxnew file mode 100644index 0000000000..e1fb3054a3--- /dev/null+++ b/packages/core/inbox/mutations.test.tsx@@ -0,0 +1,133 @@+/**+ * @vitest-environment jsdom+ */+import { beforeEach, describe, expect, it, vi } from "vitest";+import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";++import { setApiInstance } from "../api";+import type { ApiClient } from "../api/client";+import type { InboxItem } from "../types";+import { useUnarchiveInbox } from "./mutations";+import { inboxKeys } from "./queries";++vi.mock("../hooks", () => ({+ useWorkspaceId: () => "workspace-1",+}));++const WORKSPACE_ID = "workspace-1";++function item(overrides: Partial<InboxItem> = {}): InboxItem {+ return {+ id: "inbox-1",+ workspace_id: WORKSPACE_ID,+ recipient_type: "member",+ recipient_id: "member-1",+ actor_type: "agent",+ actor_id: "agent-1",+ type: "new_comment",+ severity: "info",+ issue_id: "issue-1",+ title: "Issue title",+ body: null,+ issue_status: null,+ read: false,+ archived: true,+ created_at: "2026-06-15T08:00:00Z",+ details: null,+ ...overrides,+ };+}++function createWrapper(queryClient: QueryClient) {+ return function Wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ };+}++function archivedCache(qc: QueryClient) {+ return qc.getQueryData<InboxItem[]>(inboxKeys.archived(WORKSPACE_ID)) ?? [];+}++describe("useUnarchiveInbox", () => {+ let queryClient: QueryClient;+ let unarchiveInbox: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ unarchiveInbox = vi.fn(async (id: string) => item({ id, archived: false }));+ setApiInstance({ unarchiveInbox } as unknown as ApiClient);+ });++ it("drops the whole issue group out of the archived list optimistically", async () => {+ // Archiving is issue-level, so restoring has to bring every sibling back —+ // leaving one behind would keep the issue in the archived list.+ queryClient.setQueryData<InboxItem[]>(inboxKeys.archived(WORKSPACE_ID), [+ item({ id: "sibling-a", issue_id: "issue-1" }),+ item({ id: "sibling-b", issue_id: "issue-1" }),+ item({ id: "other-issue", issue_id: "issue-2" }),+ ]);++ const { result } = renderHook(() => useUnarchiveInbox(), {+ wrapper: createWrapper(queryClient),+ });+ result.current.mutate("sibling-a");++ await waitFor(() => {+ const stillArchived = archivedCache(queryClient).filter((i) => i.archived);+ expect(stillArchived.map((i) => i.id)).toEqual(["other-issue"]);+ });+ });++ it("preserves unread state and refreshes the badge sources, so the badge rises again", async () => {+ // Restoring an item that was archived while unread legitimately RAISES the+ // unread badge: the count only ever included non-archived items. Two halves+ // make that work, and this covers the client's half — never touch `read`,+ // and re-pull both the workspace list (the Inbox nav count) and the+ // cross-workspace summary (the switcher dot). The server's half — that+ // UnarchiveInboxItem leaves `read` alone — is pinned by+ // TestUnarchiveInboxPreservesUnread in the Go suite.+ queryClient.setQueryData<InboxItem[]>(inboxKeys.archived(WORKSPACE_ID), [+ item({ id: "inbox-1", read: false }),+ ]);+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");++ const { result } = renderHook(() => useUnarchiveInbox(), {+ wrapper: createWrapper(queryClient),+ });+ result.current.mutate("inbox-1");++ await waitFor(() => expect(result.current.isSuccess).toBe(true));++ // No cache write may flip `read` — an unread item must come back unread.+ expect(archivedCache(queryClient).every((i) => i.read === false)).toBe(true);+ expect(invalidate).toHaveBeenCalledWith({+ queryKey: inboxKeys.all(WORKSPACE_ID),+ });+ expect(invalidate).toHaveBeenCalledWith({+ queryKey: inboxKeys.unreadSummary(),+ });+ });++ it("rolls the archived list back when the request fails", async () => {+ unarchiveInbox.mockRejectedValue(new Error("boom"));+ const original = [item({ id: "inbox-1" })];+ queryClient.setQueryData<InboxItem[]>(+ inboxKeys.archived(WORKSPACE_ID),+ original,+ );++ const { result } = renderHook(() => useUnarchiveInbox(), {+ wrapper: createWrapper(queryClient),+ });+ result.current.mutate("inbox-1");++ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(archivedCache(queryClient)).toEqual(original);+ });+});diff --git a/packages/core/inbox/mutations.ts b/packages/core/inbox/mutations.tsindex 4ed6636865..e6dd44e20e 100644--- a/packages/core/inbox/mutations.ts+++ b/packages/core/inbox/mutations.ts@@ -10,18 +10,24 @@ export function useMarkInboxRead() {return useMutation({mutationFn: (id: string) => api.markInboxRead(id),onMutate: async (id) => {- await qc.cancelQueries({ queryKey: inboxKeys.list(wsId) });+ await qc.cancelQueries({ queryKey: inboxKeys.all(wsId) });const prev = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));- qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), (old) =>- old?.map((item) => (item.id === id ? { ...item, read: true } : item)),- );- return { prev };+ 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);+ 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);},onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });+ qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });},});}@@ -50,7 +56,52 @@ export function useArchiveInbox() {if (ctx?.prev) qc.setQueryData(inboxKeys.list(wsId), ctx.prev);},onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });+ // Both lists: the item just moved from the main inbox into the archive.+ qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });+ },+ });+}++/**+ * Restore an archived notification to the main inbox.+ *+ * Optimistic on the ARCHIVED cache only: flipping `archived` there makes the+ * row leave the archived list at once (the dedup helper filters on it), the+ * user stays put, and rollback is a single snapshot restore. The main list is+ * left to `onSettled` — its contents after a restore are the server's call+ * (which sibling rows come back, their read state, their order), so it is+ * invalidated rather than reconstructed client-side.+ */+export function useUnarchiveInbox() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ 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,+ ),+ );+ return { prev };+ },+ onError: (_err, _id, ctx) => {+ if (ctx?.prev) qc.setQueryData(inboxKeys.archived(wsId), ctx.prev);+ },+ onSettled: () => {+ // Both lists: the item moves from one to the other, and the unread badge+ // rises again when it was archived unread.+ qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });+ qc.invalidateQueries({ queryKey: inboxKeys.unreadSummary() });},});}@@ -79,13 +130,15 @@ export function useMarkAllInboxRead() {});}+// The three batch-archive mutations below all move items into the archive, so+// each invalidates BOTH lists on settle.export function useArchiveAllInbox() {const qc = useQueryClient();const wsId = useWorkspaceId();return useMutation({mutationFn: () => api.archiveAllInbox(),onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });+ qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });},});}@@ -96,7 +149,7 @@ export function useArchiveAllReadInbox() {return useMutation({mutationFn: () => api.archiveAllReadInbox(),onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });+ qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });},});}@@ -107,7 +160,7 @@ export function useArchiveCompletedInbox() {return useMutation({mutationFn: () => api.archiveCompletedInbox(),onSettled: () => {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });+ qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });},});}diff --git a/packages/core/inbox/queries.test.ts b/packages/core/inbox/queries.test.tsindex f14da54d45..7b652edbee 100644--- a/packages/core/inbox/queries.test.ts+++ b/packages/core/inbox/queries.test.ts@@ -1,6 +1,12 @@import { describe, expect, it } from "vitest";import type { InboxItem, InboxWorkspaceUnread } from "../types";-import { deduplicateInboxItems, hasOtherWorkspaceUnread, inboxKeys, unreadWorkspaceIds } from "./queries";+import {+ deduplicateArchivedInboxItems,+ deduplicateInboxItems,+ hasOtherWorkspaceUnread,+ inboxKeys,+ unreadWorkspaceIds,+} from "./queries";function item(overrides: Partial<InboxItem>): InboxItem {return {@@ -71,6 +77,63 @@ describe("deduplicateInboxItems", () => {expect(merged[0]?.id).toBe("newer-comment");expect(merged[0]?.details?.comment_id).toBe("comment-2");});++ it("drops archived rows so an optimistic archive leaves the list at once", () => {+ const merged = deduplicateInboxItems([+ item({ id: "active", issue_id: "issue-1" }),+ item({ id: "filed-away", issue_id: "issue-2", archived: true }),+ ]);++ expect(merged.map((i) => i.id)).toEqual(["active"]);+ });+});++describe("deduplicateArchivedInboxItems", () => {+ it("keeps only archived rows, one per issue, newest first", () => {+ const merged = deduplicateArchivedInboxItems([+ item({+ id: "archived-older",+ issue_id: "issue-1",+ archived: true,+ created_at: "2026-06-15T08:00:00Z",+ }),+ item({+ id: "archived-newer",+ issue_id: "issue-1",+ archived: true,+ created_at: "2026-06-15T09:00:00Z",+ }),+ item({+ id: "archived-other-issue",+ issue_id: "issue-2",+ archived: true,+ created_at: "2026-06-15T07:00:00Z",+ }),+ item({ id: "still-active", issue_id: "issue-3" }),+ ]);++ expect(merged.map((i) => i.id)).toEqual([+ "archived-newer",+ "archived-other-issue",+ ]);+ });++ it("drops a row the moment an optimistic unarchive flips it back", () => {+ // What useUnarchiveInbox's onMutate does: flip `archived` on the archived+ // cache. The row must leave this list without waiting for the refetch.+ const restored = item({ id: "restored", archived: false });++ expect(deduplicateArchivedInboxItems([restored])).toEqual([]);+ });++ it("groups issue-less notifications on their own id rather than merging them", () => {+ const merged = deduplicateArchivedInboxItems([+ item({ id: "standalone-1", issue_id: null, archived: true }),+ item({ id: "standalone-2", issue_id: null, archived: true }),+ ]);++ expect(merged).toHaveLength(2);+ });});describe("hasOtherWorkspaceUnread", () => {diff --git a/packages/core/inbox/queries.ts b/packages/core/inbox/queries.tsindex fc536fe1fa..e93b7bff37 100644--- a/packages/core/inbox/queries.ts+++ b/packages/core/inbox/queries.ts@@ -5,6 +5,7 @@ import type { InboxItem, InboxWorkspaceUnread } from "../types";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,// 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,@@ -17,6 +18,20 @@ 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.+ */+export function archivedInboxListOptions(wsId: string) {+ return queryOptions({+ queryKey: inboxKeys.archived(wsId),+ queryFn: () => api.listArchivedInbox(),+ });+}+/*** Cross-workspace unread inbox summary. One cache entry shared across all* workspaces — the data is account-level, so switching workspaces does not@@ -74,9 +89,22 @@ export function useInboxUnreadCount(wsId: string | null | undefined): number {* (to avoid new array references on every cache update).*/export function deduplicateInboxItems(items: InboxItem[]): InboxItem[] {- const active = items.filter((i) => !i.archived);+ return groupInboxItemsByIssue(items.filter((i) => !i.archived));+}++/**+ * Same grouping for the archived sub-view. The `archived` filter is what makes+ * an optimistic unarchive drop the row out of the archived list immediately —+ * exactly mirroring how `deduplicateInboxItems`' filter drops an optimistically+ * archived row out of the main list.+ */+export function deduplicateArchivedInboxItems(items: InboxItem[]): InboxItem[] {+ return groupInboxItemsByIssue(items.filter((i) => i.archived));+}++function groupInboxItemsByIssue(items: InboxItem[]): InboxItem[] {const groups = new Map<string, InboxItem[]>();- for (const item of active) {+ for (const item of items) {const key = item.issue_id ?? item.id;const group = groups.get(key) ?? [];group.push(item);diff --git a/packages/core/inbox/ws-updaters.test.ts b/packages/core/inbox/ws-updaters.test.tsindex e7c73ded71..b40a8e6444 100644--- a/packages/core/inbox/ws-updaters.test.ts+++ b/packages/core/inbox/ws-updaters.test.ts@@ -1,6 +1,11 @@import { describe, it, expect, vi } from "vitest";import { QueryClient } from "@tanstack/react-query";-import { onInboxIssueDeleted, onInboxIssueStatusChanged, onInboxSummaryInvalidate } from "./ws-updaters";+import {+ onInboxInvalidate,+ onInboxIssueDeleted,+ onInboxIssueStatusChanged,+ onInboxSummaryInvalidate,+} from "./ws-updaters";import { inboxKeys } from "./queries";import type { InboxItem } from "../types";@@ -49,6 +54,22 @@ describe("onInboxIssueDeleted", () => {expect(after?.map((i) => i.id)).toEqual(["i3", "i4"]);});+ it("also strips the issue from the archived list", () => {+ // Deleting an issue removes its rows whether they were archived or not, so+ // leaving them in the archived cache would render a row that 404s on tap.+ const qc = new QueryClient();+ qc.setQueryData<InboxItem[]>(inboxKeys.archived(wsId), [+ makeItem("a1", "issue-a", { archived: true }),+ makeItem("a2", "issue-b", { archived: true }),+ ]);++ onInboxIssueDeleted(qc, wsId, "issue-a");++ expect(+ qc.getQueryData<InboxItem[]>(inboxKeys.archived(wsId))?.map((i) => i.id),+ ).toEqual(["a2"]);+ });+it("is a no-op when the inbox cache is empty", () => {const qc = new QueryClient();expect(() => onInboxIssueDeleted(qc, wsId, "issue-a")).not.toThrow();@@ -56,6 +77,33 @@ describe("onInboxIssueDeleted", () => {});});+describe("onInboxInvalidate", () => {+ it("invalidates the workspace prefix, covering both the main and archived lists", () => {+ // Every inbox event can move an item across the two lists, so they are+ // always refreshed together (MUL-3736).+ const qc = new QueryClient();+ const spy = vi.spyOn(qc, "invalidateQueries");++ onInboxInvalidate(qc, wsId);++ expect(spy).toHaveBeenCalledWith({ queryKey: inboxKeys.all(wsId) });+ });++ it("does not reach the account-level summary key", () => {+ // The summary is keyed ["inbox", "unread-summary"], NOT under the+ // workspace prefix — its own updater owns it.+ const qc = new QueryClient();+ qc.setQueryData(inboxKeys.unreadSummary(), [{ workspace_id: wsId, count: 3 }]);+ const summaryQuery = qc+ .getQueryCache()+ .find({ queryKey: inboxKeys.unreadSummary() });++ onInboxInvalidate(qc, wsId);++ expect(summaryQuery?.state.isInvalidated).toBe(false);+ });+});+describe("onInboxSummaryInvalidate", () => {it("invalidates the account-level summary key regardless of active workspace", () => {const qc = new QueryClient();@@ -93,4 +141,17 @@ describe("onInboxIssueStatusChanged", () => {expect(after?.find((i) => i.id === "i1")?.issue_status).toBe("done");expect(after?.find((i) => i.id === "i2")?.issue_status).toBe("todo");});++ it("patches archived rows too, which render the same status icon", () => {+ const qc = new QueryClient();+ qc.setQueryData<InboxItem[]>(inboxKeys.archived(wsId), [+ makeItem("a1", "issue-a", { archived: true, issue_status: "todo" }),+ ]);++ onInboxIssueStatusChanged(qc, wsId, "issue-a", "done");++ expect(+ qc.getQueryData<InboxItem[]>(inboxKeys.archived(wsId))?.[0]?.issue_status,+ ).toBe("done");+ });});diff --git a/packages/core/inbox/ws-updaters.ts b/packages/core/inbox/ws-updaters.tsindex a308dfad9c..d9b3ca89d5 100644--- a/packages/core/inbox/ws-updaters.ts+++ b/packages/core/inbox/ws-updaters.ts@@ -9,7 +9,12 @@ export function onInboxNew() {// Use invalidateQueries instead of setQueryData — triggers a refetch that// reliably notifies all observers. The inbox list is small so this is cheap.- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });+ //+ // Both lists: a new notification on an ARCHIVED issue puts that issue back in+ // the main inbox, which means it must also leave the archived list. The+ // server owns that split (ListArchivedInboxItems excludes issues with an+ // active row), so refetching both is what keeps them mutually exclusive.+ qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });}export function patchInboxIssueStatus(@@ -18,11 +23,11 @@ export function patchInboxIssueStatus(issueId: string,status: IssueStatus,) {- qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), (old) =>- old?.map((i) =>- i.issue_id === issueId ? { ...i, issue_status: status } : i,- ),- );+ const patch = (old: InboxItem[] | undefined) =>+ old?.map((i) => (i.issue_id === issueId ? { ...i, issue_status: status } : i));+ qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), patch);+ // Archived rows render the same status icon, so they need the same patch.+ qc.setQueryData<InboxItem[]>(inboxKeys.archived(wsId), patch);}export function onInboxIssueStatusChanged(@@ -36,19 +41,25 @@ export function onInboxIssueStatusChanged(// Mirrors the DB-level ON DELETE CASCADE on inbox_item.issue_id: when an issue// is deleted, all inbox items that referenced it are gone server-side, so drop-// them from the cache too.+// them from the cache too — from the archived list as well, which holds rows+// for the same issues.export function onInboxIssueDeleted(qc: QueryClient,wsId: string,issueId: string,) {- qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), (old) =>- old?.filter((i) => i.issue_id !== issueId),- );+ const drop = (old: InboxItem[] | undefined) =>+ old?.filter((i) => i.issue_id !== issueId);+ qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), drop);+ qc.setQueryData<InboxItem[]>(inboxKeys.archived(wsId), drop);}+// Refresh both the main and archived lists. Every inbox event can move an item+// across that boundary (archive, unarchive, or a new notification reviving an+// archived issue), and the split is decided server-side, so the two are always+// invalidated together.export function onInboxInvalidate(qc: QueryClient, wsId: string) {- qc.invalidateQueries({ queryKey: inboxKeys.list(wsId) });+ qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });}// Refresh the cross-workspace unread summary (workspace-switcher dot). Thediff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.tsindex 5ea79ac819..4242ddc2bb 100644--- a/packages/core/realtime/use-realtime-sync.test.ts+++ b/packages/core/realtime/use-realtime-sync.test.ts@@ -692,8 +692,11 @@ describe("handleInboxNew", () => {await handleInboxNew(qc, inboxItem());+ // The workspace prefix, which covers both the main list and the archived+ // one: a new notification on an archived issue revives it into the main+ // inbox, so the archived list has to drop it in the same pass (MUL-3736).expect(invalidate).toHaveBeenCalledWith({- queryKey: inboxKeys.list("ws-a"),+ queryKey: inboxKeys.all("ws-a"),});expect(showNotification).toHaveBeenCalledWith(expect.objectContaining({ slug: "workspace-a" }),diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex ad7c100a02..4bc3d2b5a3 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -588,11 +588,12 @@ export function useRealtimeSync(inbox: () => {const wsId = getCurrentWsId();if (wsId) onInboxInvalidate(qc, wsId);- // inbox:read / inbox:archived / batch events arrive here. They can- // originate from a workspace other than the active one (personal- // events fan out to all the user's connections), so always refresh- // the cross-workspace summary — its dot must clear when another- // workspace's items are read/archived.+ // inbox:read / inbox:archived / inbox:unarchived / batch events arrive+ // here. They can originate from a workspace other than the active one+ // (personal events fan out to all the user's connections), so always+ // refresh the cross-workspace summary — its dot must clear when another+ // workspace's items are read/archived, and light again when an unread+ // item is restored from the archive.onInboxSummaryInvalidate(qc);},agent: () => {diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex 5cf3e5cdf8..059a4ae90b 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -34,6 +34,7 @@ export type WSEventType =| "inbox:new"| "inbox:read"| "inbox:archived"+ | "inbox:unarchived"| "inbox:batch-read"| "inbox:batch-archived"| "workspace:updated"@@ -166,6 +167,12 @@ export interface InboxArchivedPayload {recipient_id: string;}+export interface InboxUnarchivedPayload {+ item_id: string;+ issue_id: string | null;+ recipient_id: string;+}+export interface InboxBatchReadPayload {recipient_id: string;count: number;@@ -487,6 +494,7 @@ export interface WSEventPayloadMap {"inbox:new": InboxNewPayload;"inbox:read": InboxReadPayload;"inbox:archived": InboxArchivedPayload;+ "inbox:unarchived": InboxUnarchivedPayload;"inbox:batch-read": InboxBatchReadPayload;"inbox:batch-archived": InboxBatchArchivedPayload;"workspace:updated": WorkspaceUpdatedPayload;diff --git a/packages/views/inbox/components/inbox-list-item.tsx b/packages/views/inbox/components/inbox-list-item.tsxindex 9d4a6473df..79b1ce444b 100644--- a/packages/views/inbox/components/inbox-list-item.tsx+++ b/packages/views/inbox/components/inbox-list-item.tsx@@ -2,8 +2,9 @@import { StatusIcon } from "../../issues/components";import { ActorAvatar } from "../../common/actor-avatar";-import { Archive } from "lucide-react";+import { Archive, ArchiveRestore } from "lucide-react";import type { InboxItem } from "@multica/core/types";+import type { InboxView } from "./inbox-view";import { InboxDetailLabel } from "./inbox-detail-label";import { getInboxDisplayTitle } from "./inbox-display";import { useT } from "../../i18n";@@ -27,18 +28,27 @@ export function useTimeAgo() {export function InboxListItem({item,+ view,isSelected,onClick,- onArchive,+ onAction,}: {item: InboxItem;+ view: InboxView;isSelected: boolean;onClick: () => void;- onArchive: () => void;+ // Archive in the main list, unarchive in the archived one — the row action is+ // always the reversal of the current view, so the two lists share this row.+ onAction: () => void;}) {const { t } = useT("inbox");const timeAgo = useTimeAgo();const displayTitle = getInboxDisplayTitle(item);+ const isArchivedView = view === "archived";+ const ActionIcon = isArchivedView ? ArchiveRestore : Archive;+ const actionLabel = isArchivedView+ ? t(($) => $.list.unarchive_tooltip)+ : t(($) => $.list.archive_tooltip);return (<button@@ -70,20 +80,21 @@ export function InboxListItem({<spanrole="button"tabIndex={-1}- title={t(($) => $.list.archive_tooltip)}+ title={actionLabel}+ aria-label={actionLabel}onClick={(e) => {e.stopPropagation();- onArchive();+ onAction();}}onKeyDown={(e) => {if (e.key === "Enter" || e.key === " ") {e.stopPropagation();- onArchive();+ onAction();}}}className="hidden rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground group-hover:inline-flex">- <Archive className="h-3.5 w-3.5" />+ <ActionIcon className="h-3.5 w-3.5" /></span>{item.issue_status && (<StatusIcon status={item.issue_status} className="h-3.5 w-3.5 shrink-0" />diff --git a/packages/views/inbox/components/inbox-list.tsx b/packages/views/inbox/components/inbox-list.tsxindex 14b672e5d8..62395400f2 100644--- a/packages/views/inbox/components/inbox-list.tsx+++ b/packages/views/inbox/components/inbox-list.tsx@@ -1,9 +1,10 @@"use client";-import { useState } from "react";+import { useCallback, useMemo, useState } from "react";import { Virtuoso } from "react-virtuoso";-import { Inbox } from "lucide-react";+import { Archive, ChevronRight, Inbox } from "lucide-react";import type { InboxItem } from "@multica/core/types";+import type { InboxView } from "./inbox-view";import { InboxListItem } from "./inbox-list-item";import { VirtuosoSeed, VIRTUOSO_SEED_COUNT } from "../../common/virtuoso-seed";import { useT } from "../../i18n";@@ -31,28 +32,74 @@ import { useT } from "../../i18n";*/export function InboxList({items,+ view,selectedKey,+ archivedCount,onSelect,- onArchive,+ onAction,+ onOpenArchived,}: {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;onSelect: (item: InboxItem) => void;- onArchive: (id: string) => void;+ onAction: (id: string) => void;+ onOpenArchived: () => void;}) {const { t } = useT("inbox");// Virtuoso's `customScrollParent` wants the actual HTMLElement, not a ref.// A callback ref into state hands the element over once it mounts and// triggers the re-render that lets Virtuoso attach to it.const [scrollEl, setScrollEl] = useState<HTMLDivElement | null>(null);+ const isArchivedView = view === "archived";++ // The entry into the archive sits below the last row and scrolls with the+ // list (same placement as chat's). Virtuoso mounts it via `components.Footer`,+ // and swaps the component whenever that prop's identity changes — so both the+ // element and the Footer wrapping it are memoized. Without that the entry+ // remounts on every parent render and drops hover/focus mid-click.+ const archivedEntry = useMemo(+ () =>+ !isArchivedView && archivedCount > 0 ? (+ <button+ type="button"+ onClick={onOpenArchived}+ className="mt-1 flex h-10 w-full items-center gap-2 rounded-md px-2 text-left text-xs text-muted-foreground outline-none transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring"+ >+ <span className="flex size-7 shrink-0 items-center justify-center">+ <Archive className="size-4" />+ </span>+ <span className="min-w-0 flex-1 truncate font-medium">+ {t(($) => $.list.archived_title)}+ </span>+ <span className="shrink-0 tabular-nums text-muted-foreground/70">+ {archivedCount}+ </span>+ <ChevronRight className="size-4 shrink-0 text-muted-foreground/50" />+ </button>+ ) : null,+ [isArchivedView, archivedCount, onOpenArchived, t],+ );++ const Footer = useCallback(() => archivedEntry, [archivedEntry]);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"><Inbox className="mb-3 h-8 w-8 text-muted-foreground/50" />- <p className="text-sm">{t(($) => $.list.empty)}</p>+ <p className="text-sm">+ {isArchivedView+ ? t(($) => $.list.archived_empty)+ : t(($) => $.list.empty)}+ </p></div>+ {/* Still offer the archive when the main list is empty — that is+ exactly when a user goes looking for what they filed away. */}+ {archivedEntry && <div className="px-2">{archivedEntry}</div>}</div>);}@@ -61,9 +108,10 @@ export function InboxList({const itemContent = (_index: number, item: InboxItem) => (<InboxListItemitem={item}+ view={view}isSelected={(item.issue_id ?? item.id) === selectedKey}onClick={() => onSelect(item)}- onArchive={() => onArchive(item.id)}+ onAction={() => onAction(item.id)}/>);@@ -82,13 +130,20 @@ export function InboxList({initialItemCount={Math.min(items.length, VIRTUOSO_SEED_COUNT)}increaseViewportBy={{ top: 400, bottom: 400 }}itemContent={itemContent}+ components={{ Footer }}/>) : (- <VirtuosoSeed- data={items}- itemContent={itemContent}- computeItemKey={computeItemKey}- />+ <>+ <VirtuosoSeed+ data={items}+ itemContent={itemContent}+ computeItemKey={computeItemKey}+ />+ {/* The seed frame renders a bounded slice, so the entry would be+ mid-list rather than after the last row — only show it once the+ seed IS the whole list. */}+ {items.length <= VIRTUOSO_SEED_COUNT && archivedEntry}+ </>)}</div></div>diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsxindex 0f6805dd4a..6b79b50484 100644--- a/packages/views/inbox/components/inbox-page.test.tsx+++ b/packages/views/inbox/components/inbox-page.test.tsx@@ -1,13 +1,26 @@-import { render } from "@testing-library/react";+import { fireEvent, render, screen } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";+import type { InboxItem } from "@multica/core/types";import { InboxPage } from "./inbox-page";vi.mock("react-resizable-panels", () => ({useDefaultLayout: () => ({ defaultLayout: undefined, onLayoutChanged: vi.fn() }),}));+// 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[] } = {+ active: [],+ archived: [],+};+vi.mock("@tanstack/react-query", () => ({- useQuery: () => ({ data: [], isLoading: false }),+ useQuery: (options: { queryKey: readonly unknown[] }) => ({+ data: options.queryKey.includes("archived") ? listData.archived : listData.active,+ isLoading: false,+ isError: false,+ }),}));vi.mock("@multica/core/hooks", () => ({@@ -30,8 +43,10 @@ vi.mock("@multica/core/issues/stores/draft-store", () => ({}));vi.mock("@multica/core/inbox/queries", () => ({- inboxListOptions: () => ({ queryKey: ["inbox"] }),- deduplicateInboxItems: (items: unknown[]) => items,+ inboxListOptions: () => ({ queryKey: ["inbox", "workspace-1", "list"] }),+ archivedInboxListOptions: () => ({ queryKey: ["inbox", "workspace-1", "archived"] }),+ deduplicateInboxItems: (items: InboxItem[]) => items.filter((i) => !i.archived),+ deduplicateArchivedInboxItems: (items: InboxItem[]) => items.filter((i) => i.archived),useInboxUnreadCount: () => 2,}));@@ -40,6 +55,7 @@ vi.mock("@multica/core/inbox/mutations", () => {return {useMarkInboxRead: mutation,useArchiveInbox: mutation,+ useUnarchiveInbox: mutation,useMarkAllInboxRead: mutation,useArchiveAllInbox: mutation,useArchiveAllReadInbox: mutation,@@ -47,20 +63,74 @@ vi.mock("@multica/core/inbox/mutations", () => {};});-vi.mock("../../issues/components", () => ({ IssueDetail: () => null }));+vi.mock("../../issues/components", () => ({+ IssueDetail: () => null,+ StatusIcon: () => null,+}));++const replace = vi.fn();+let searchParams = new URLSearchParams();vi.mock("../../navigation", () => ({- useNavigation: () => ({ searchParams: new URLSearchParams(), replace: vi.fn() }),+ useNavigation: () => ({ searchParams, replace }),}));vi.mock("@multica/ui/hooks/use-mobile", () => ({ useIsMobile: () => true }));-vi.mock("./inbox-list", () => ({ InboxList: () => null }));+vi.mock("./inbox-list", () => ({+ InboxList: ({+ items,+ view,+ onSelect,+ }: {+ items: InboxItem[];+ view: string;+ onSelect: (item: InboxItem) => void;+ }) => (+ <div data-testid="list" data-view={view}>+ {items.map((i) => (+ <button key={i.id} data-testid="row" onClick={() => onSelect(i)}>+ {i.id}+ </button>+ ))}+ </div>+ ),+}));vi.mock("./inbox-list-item", () => ({ useTimeAgo: () => vi.fn() }));vi.mock("./inbox-detail-label", () => ({ useTypeLabels: () => ({}) }));vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "Inbox" }) }));+function item(overrides: Partial<InboxItem> = {}): InboxItem {+ return {+ id: "inbox-1",+ workspace_id: "workspace-1",+ recipient_type: "member",+ recipient_id: "member-1",+ actor_type: "agent",+ actor_id: "agent-1",+ type: "new_comment",+ severity: "info",+ issue_id: "issue-1",+ title: "Issue title",+ body: null,+ issue_status: null,+ read: true,+ archived: false,+ created_at: "2026-06-15T08:00:00Z",+ details: null,+ ...overrides,+ };+}++function reset() {+ listData.active = [];+ listData.archived = [];+ searchParams = new URLSearchParams();+ replace.mockClear();+}+describe("InboxPage", () => {it("keeps the title unread count static", () => {+ reset();const { container } = render(<InboxPage />);const titleCount = container.querySelector("h1")?.parentElement?.querySelector("number-flow-react",@@ -69,4 +139,93 @@ describe("InboxPage", () => {expect(titleCount?.getAttribute("aria-label")).toBe("2");expect(titleCount?.animated).toBe(false);});++ it("shows the active list by default", () => {+ reset();+ listData.active = [item({ id: "active-1" })];+ listData.archived = [item({ id: "archived-1", archived: true })];++ render(<InboxPage />);++ expect(screen.getByTestId("list").dataset.view).toBe("inbox");+ expect(screen.getByTestId("row").textContent).toBe("active-1");+ });++ 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.+ reset();+ searchParams = new URLSearchParams("view=archived");+ listData.active = [item({ id: "active-1" })];+ listData.archived = [item({ id: "archived-1", archived: true })];++ render(<InboxPage />);++ expect(screen.getByTestId("list").dataset.view).toBe("archived");+ expect(screen.getByTestId("row").textContent).toBe("archived-1");+ });++ it("hides the batch-actions menu in the archived view", () => {+ // Every batch action archives from the MAIN inbox; offering them over the+ // archived list would read as "archive all of these" and do the opposite.+ reset();+ listData.archived = [item({ id: "archived-1", archived: true })];+ const { container: mainView } = render(<InboxPage />);+ expect(mainView.querySelector('[aria-haspopup="menu"]')).not.toBeNull();++ searchParams = new URLSearchParams("view=archived");+ const { container: archivedView } = render(<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.+ reset();+ searchParams = new URLSearchParams("view=archived");+ listData.archived = [];++ render(<InboxPage />);++ expect(replace).toHaveBeenCalledWith("/acme/inbox");+ });++ it("keeps the archived view in the URL when selecting an item there", () => {+ // A bare `?issue=` write would silently drop the user back to the main+ // inbox on the next refresh — both pieces of state travel together.+ reset();+ searchParams = new URLSearchParams("view=archived");+ listData.archived = [+ item({ id: "archived-1", issue_id: "issue-9", archived: true }),+ ];++ render(<InboxPage />);+ fireEvent.click(screen.getByTestId("row"));++ expect(replace).toHaveBeenCalledWith("/acme/inbox?view=archived&issue=issue-9");+ });++ it("writes a bare issue param when selecting in the main view", () => {+ reset();+ listData.active = [item({ id: "active-1", issue_id: "issue-3" })];++ render(<InboxPage />);+ fireEvent.click(screen.getByTestId("row"));++ expect(replace).toHaveBeenCalledWith("/acme/inbox?issue=issue-3");+ });++ it("does not swallow a deep link to an issue that is not in the archive", () => {+ // ?view=archived&issue=X with an empty archive: the drain effect and the+ // unresolved-selection fallback both want to navigate. The fallback must+ // win, or the deep link silently lands on an empty inbox instead of X.+ reset();+ searchParams = new URLSearchParams("view=archived&issue=issue-404");+ listData.archived = [];++ render(<InboxPage />);++ expect(replace).toHaveBeenCalledWith("/acme/issues/issue-404");+ expect(replace).not.toHaveBeenCalledWith("/acme/inbox");+ });});diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex 77dba961fd..d39eba6a27 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -9,12 +9,15 @@ import { useModalStore } from "@multica/core/modals";import { useIssueDraftStore } from "@multica/core/issues/stores/draft-store";import {inboxListOptions,+ archivedInboxListOptions,deduplicateInboxItems,+ deduplicateArchivedInboxItems,useInboxUnreadCount,} from "@multica/core/inbox/queries";import {useMarkInboxRead,useArchiveInbox,+ useUnarchiveInbox,useMarkAllInboxRead,useArchiveAllInbox,useArchiveAllReadInbox,@@ -30,7 +33,9 @@ import {Inbox,CheckCheck,Archive,+ ArchiveRestore,BookCheck,+ ChevronLeft,ListChecks,ArrowLeft,} from "lucide-react";@@ -54,6 +59,7 @@ import { useIsMobile } from "@multica/ui/hooks/use-mobile";import { PageHeader } from "../../layout/page-header";import { useTimeAgo } from "./inbox-list-item";import { InboxList } from "./inbox-list";+import { ARCHIVED_VIEW_PARAM, type InboxView } from "./inbox-view";import { useTypeLabels } from "./inbox-detail-label";import { getInboxDisplayTitle } from "./inbox-display";import { useT } from "../../i18n";@@ -62,20 +68,43 @@ export function InboxPage() {const { t } = useT("inbox");const { searchParams, replace } = useNavigation();const urlIssue = searchParams.get("issue") ?? "";+ const urlView: InboxView =+ searchParams.get("view") === ARCHIVED_VIEW_PARAM ? "archived" : "inbox";const wsPaths = useWorkspacePaths();const [selectedKey, setSelectedKeyState] = useState(() => urlIssue);+ const [view, setViewState] = useState<InboxView>(() => urlView);// Sync from URL when searchParams change (e.g. navigation)useEffect(() => {setSelectedKeyState(urlIssue);}, [urlIssue]);+ useEffect(() => {+ setViewState(urlView);+ }, [urlView]);const wsId = useWorkspaceId();const { data: rawItems = [], isLoading: loading } = useQuery(inboxListOptions(wsId));const items = useMemo(() => deduplicateInboxItems(rawItems), [rawItems]);- const selected = items.find((i) => (i.issue_id ?? i.id) === selectedKey) ?? null;+ // 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 visibleItems = isArchivedView ? archivedItems : items;++ const selected =+ visibleItems.find((i) => (i.issue_id ?? i.id) === selectedKey) ?? null;// Track the last key we actually resolved against the inbox list. Lets the// fallback effect distinguish "shared-link to a notification not in our@@ -86,12 +115,43 @@ export function InboxPage() {if (selected) lastResolvedKeyRef.current = selectedKey;}, [selected, selectedKey]);+ // Both the view and the selection live in the URL, so every write has to+ // carry the other one — a bare `?issue=` would silently drop the user out of+ // the archived view on the next selection.+ const buildInboxUrl = useCallback(+ (nextView: InboxView, key: string) => {+ const params = new URLSearchParams();+ if (nextView === "archived") params.set("view", ARCHIVED_VIEW_PARAM);+ if (key) params.set("issue", key);+ const query = params.toString();+ const inboxPath = wsPaths.inbox();+ return query ? `${inboxPath}?${query}` : inboxPath;+ },+ [wsPaths],+ );+const setSelectedKey = useCallback((key: string) => {setSelectedKeyState(key);- const inboxPath = wsPaths.inbox();- const url = key ? `${inboxPath}?issue=${key}` : inboxPath;- replace(url);- }, [replace, wsPaths]);+ replace(buildInboxUrl(view, key));+ }, [replace, buildInboxUrl, view]);++ // Switching views always clears the selection: the two lists are mutually+ // exclusive, so a key carried across would never resolve, and the fallback+ // effect below would bounce the user to the issue page.+ const setView = useCallback((nextView: InboxView) => {+ setViewState(nextView);+ setSelectedKeyState("");+ replace(buildInboxUrl(nextView, ""));+ }, [replace, buildInboxUrl]);++ // Stable identity: InboxList memoizes the archive entry on this callback, so+ // an inline arrow here would rebuild (and remount) the entry every render.+ const openArchived = useCallback(() => setView("archived"), [setView]);++ // 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.+ const viewLoading = isArchivedView ? archivedLoading : loading;// 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@@ -100,7 +160,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 (loading) return;+ if (viewLoading) return;if (!selectedKey) return;if (selected) return;if (lastResolvedKeyRef.current === selectedKey) {@@ -108,7 +168,33 @@ export function InboxPage() {return;}replace(wsPaths.issueDetail(selectedKey));- }, [loading, selectedKey, selected, replace, wsPaths, setSelectedKey]);+ }, [viewLoading, selectedKey, selected, replace, wsPaths, 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",@@ -119,6 +205,7 @@ export function InboxPage() {const markReadMutation = useMarkInboxRead();const archiveMutation = useArchiveInbox();+ const unarchiveMutation = useUnarchiveInbox();const markAllReadMutation = useMarkAllInboxRead();const archiveAllMutation = useArchiveAllInbox();const archiveAllReadMutation = useArchiveAllReadInbox();@@ -151,18 +238,24 @@ export function InboxPage() {setSelectedKey(item.issue_id ?? item.id);};+ // Both archive and unarchive remove the row from the list it was actioned+ // from, so both have to move the selection off it first. `list` is whichever+ // list the row came from — the main one for archive, the archived one for+ // unarchive.+ const advanceSelectionPast = (id: string, list: InboxItem[]) => {+ const idx = list.findIndex((i) => i.id === id);+ const target = idx >= 0 ? list[idx] : null;+ const wasSelected = !!target && (target.issue_id ?? target.id) === selectedKey;+ if (!wasSelected) return;+ // List is sorted newest-first; prefer the next (older) item, fall back+ // to the previous (newer) one when actioning at the bottom, and only+ // clear the selection when nothing else is left.+ const next = list[idx + 1] ?? list[idx - 1] ?? null;+ setSelectedKey(next ? (next.issue_id ?? next.id) : "");+ };+const handleArchive = (id: string) => {- const idx = items.findIndex((i) => i.id === id);- const archived = idx >= 0 ? items[idx] : null;- const wasSelected =- !!archived && (archived.issue_id ?? archived.id) === selectedKey;- if (wasSelected) {- // List is sorted newest-first; prefer the next (older) item, fall back- // to the previous (newer) one when archiving at the bottom, and only- // clear the selection when nothing else is left.- const next = items[idx + 1] ?? items[idx - 1] ?? null;- setSelectedKey(next ? (next.issue_id ?? next.id) : "");- }+ advanceSelectionPast(id, items);archiveMutation.mutate(id, {onError: (err) =>toast.error(@@ -173,6 +266,18 @@ export function InboxPage() {});};+ const handleUnarchive = (id: string) => {+ advanceSelectionPast(id, archivedItems);+ unarchiveMutation.mutate(id, {+ onError: (err) =>+ toast.error(+ err instanceof Error && err.message+ ? err.message+ : t(($) => $.errors.unarchive_failed),+ ),+ });+ };+// Batch operationsconst handleMarkAllRead = () => {markAllReadMutation.mutate(undefined, {@@ -238,6 +343,10 @@ export function InboxPage() {/>)}</div>+ {/* Batch actions are main-view only. Every entry archives from the MAIN+ inbox, so offering them while the archived list is on screen reads as+ "archive all of these" and does the opposite of what it looks like. */}+ {!isArchivedView && (<DropdownMenu><DropdownMenuTriggerrender={@@ -270,18 +379,54 @@ export function InboxPage() {</DropdownMenuItem></DropdownMenuContent></DropdownMenu>+ )}</PageHeader>);- const list = (+ // Back out of the archive. Sits inside the list panel rather than replacing+ // the PageHeader: the user is still in the Inbox, so the page title stays put+ // and this reads as a sub-view — the same shape chat's archived view uses.+ const archivedBackRow = (+ <button+ type="button"+ onClick={() => setView("inbox")}+ className="flex w-full shrink-0 items-center gap-1.5 border-b px-3 py-2 text-left text-xs font-medium text-muted-foreground outline-none transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring"+ >+ <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/70">+ {archivedItems.length}+ </span>+ </button>+ );++ const list = archivedError && isArchivedView ? (+ <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-muted-foreground/50" />+ <p className="text-sm">{t(($) => $.errors.archived_load_failed)}</p>+ </div>+ </div>+ ) : (<InboxList- items={items}+ items={visibleItems}+ view={view}selectedKey={selectedKey}+ archivedCount={archivedItems.length}onSelect={handleSelect}- onArchive={handleArchive}+ onAction={isArchivedView ? handleUnarchive : handleArchive}+ onOpenArchived={openArchived}/>);+ const listPanel = (+ <>+ {listHeader}+ {isArchivedView && archivedBackRow}+ {list}+ </>+ );+const detailContent = selected?.issue_id ? (// Key by issue_id (not inbox-item id): a new comment/reaction generates a// new inbox notification for the same issue, and the dedup helper picks the@@ -348,14 +493,27 @@ export function InboxPage() {{t(($) => $.detail.edit_advanced)}</Button>)}- <Button- variant="outline"- size="sm"- onClick={() => handleArchive(selected.id)}- >- <Archive className="mr-1.5 h-3.5 w-3.5" />- {t(($) => $.detail.archive)}- </Button>+ {/* Mirrors the row action: the button always reverses the view the+ item is being read in. */}+ {isArchivedView ? (+ <Button+ variant="outline"+ size="sm"+ onClick={() => handleUnarchive(selected.id)}+ >+ <ArchiveRestore className="mr-1.5 h-3.5 w-3.5" />+ {t(($) => $.detail.unarchive)}+ </Button>+ ) : (+ <Button+ variant="outline"+ size="sm"+ onClick={() => handleArchive(selected.id)}+ >+ <Archive className="mr-1.5 h-3.5 w-3.5" />+ {t(($) => $.detail.archive)}+ </Button>+ )}</div></div>) : null;@@ -363,7 +521,7 @@ export function InboxPage() {// -- Mobile layout: list / detail toggle -----------------------------------if (isMobile) {- if (loading) {+ if (viewLoading) {return (<div className="flex flex-1 flex-col min-h-0"><div className="flex h-12 shrink-0 items-center border-b px-4">@@ -396,7 +554,11 @@ export function InboxPage() {className="gap-1.5 text-muted-foreground"><ArrowLeft className="h-4 w-4" />- {t(($) => $.page.back)}+ {/* Back goes to the list the user came FROM, so the label has to+ name it — "Inbox" here would be a lie about the destination. */}+ {isArchivedView+ ? t(($) => $.list.archived_title)+ : t(($) => $.page.back)}</Button></div><div className="flex-1 min-h-0 overflow-y-auto">@@ -407,17 +569,12 @@ export function InboxPage() {}// Mobile: full-screen list- return (- <div className="flex flex-1 flex-col min-h-0">- {listHeader}- {list}- </div>- );+ return <div className="flex flex-1 flex-col min-h-0">{listPanel}</div>;}// -- Desktop layout: resizable two-panel ------------------------------------ if (loading) {+ if (viewLoading) {return (<ResizablePanelGroup orientation="horizontal" className="flex-1 min-h-0" defaultLayout={defaultLayout} onLayoutChanged={onLayoutChanged}><ResizablePanel id="list" defaultSize={320} minSize={240} maxSize={480} groupResizeBehavior="preserve-pixel-size">@@ -453,8 +610,7 @@ export function InboxPage() {<ResizablePanelGroup orientation="horizontal" className="flex-1 min-h-0" defaultLayout={defaultLayout} onLayoutChanged={onLayoutChanged}><ResizablePanel id="list" defaultSize={320} minSize={240} maxSize={480} groupResizeBehavior="preserve-pixel-size"><div className="flex flex-col border-r h-full">- {listHeader}- {list}+ {listPanel}</div></ResizablePanel><ResizableHandle />@@ -464,7 +620,7 @@ export function InboxPage() {<div className="flex h-full flex-col items-center justify-center text-muted-foreground"><Inbox className="mb-3 h-10 w-10 text-muted-foreground/30" /><p className="text-sm">- {items.length === 0+ {visibleItems.length === 0? t(($) => $.detail.empty): t(($) => $.detail.select_prompt)}</p>diff --git a/packages/views/inbox/components/inbox-view.ts b/packages/views/inbox/components/inbox-view.tsnew file mode 100644index 0000000000..a8d729c666--- /dev/null+++ b/packages/views/inbox/components/inbox-view.ts@@ -0,0 +1,15 @@+/**+ * Which of the inbox's two lists is showing.+ *+ * "inbox" is the default list of active notifications; "archived" is the+ * sub-view reached from the entry at the bottom of that list. The two are+ * mutually exclusive per issue — the server decides which list an issue+ * belongs to (see ListArchivedInboxItems) — so a view is a complete swap of+ * the list's data source and row action, not a filter layered on one list.+ *+ * Persisted in the URL as `?view=archived` so a refresh, a back/forward step,+ * or a mobile detail-back returns to the list the user was actually in.+ */+export type InboxView = "inbox" | "archived";++export const ARCHIVED_VIEW_PARAM = "archived";diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.jsonindex 5335d4f946..f40c912391 100644--- a/packages/views/locales/en/inbox.json+++ b/packages/views/locales/en/inbox.json@@ -18,14 +18,18 @@"minutes": "{{count}}m","hours": "{{count}}h","days": "{{count}}d"- }+ },+ "archived_title": "Archived",+ "archived_empty": "No archived notifications",+ "unarchive_tooltip": "Unarchive"},"detail": {"select_prompt": "Select a notification to view details","empty": "Your inbox is empty","original_input": "Original input","edit_advanced": "Edit as advanced form",- "archive": "Archive"+ "archive": "Archive",+ "unarchive": "Unarchive"},"types": {"issue_assigned": "Assigned",@@ -67,6 +71,8 @@"mark_all_read_failed": "Failed to mark all as read","archive_all_failed": "Failed to archive all","archive_all_read_failed": "Failed to archive read items",- "archive_completed_failed": "Failed to archive completed"+ "archive_completed_failed": "Failed to archive completed",+ "unarchive_failed": "Failed to unarchive",+ "archived_load_failed": "Failed to load archived notifications"}}diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.jsonindex b952066564..8eb7c00b08 100644--- a/packages/views/locales/ja/inbox.json+++ b/packages/views/locales/ja/inbox.json@@ -18,14 +18,18 @@"minutes": "{{count}}分","hours": "{{count}}時間","days": "{{count}}日"- }+ },+ "archived_title": "アーカイブ済み",+ "archived_empty": "アーカイブされた通知はありません",+ "unarchive_tooltip": "アーカイブ解除"},"detail": {"select_prompt": "詳細を表示する通知を選択してください","empty": "インボックスは空です","original_input": "元の入力","edit_advanced": "詳細フォームで編集",- "archive": "アーカイブ"+ "archive": "アーカイブ",+ "unarchive": "アーカイブ解除"},"types": {"issue_assigned": "割り当て済み",@@ -67,6 +71,8 @@"mark_all_read_failed": "すべて既読にできませんでした","archive_all_failed": "すべてアーカイブできませんでした","archive_all_read_failed": "既読の項目をアーカイブできませんでした",- "archive_completed_failed": "完了した項目をアーカイブできませんでした"+ "archive_completed_failed": "完了した項目をアーカイブできませんでした",+ "unarchive_failed": "アーカイブ解除に失敗しました",+ "archived_load_failed": "アーカイブ済み通知を読み込めませんでした"}}diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.jsonindex 698f4714c7..1ae6b3d4e2 100644--- a/packages/views/locales/ko/inbox.json+++ b/packages/views/locales/ko/inbox.json@@ -18,14 +18,18 @@"minutes": "{{count}}분","hours": "{{count}}시간","days": "{{count}}일"- }+ },+ "archived_title": "보관됨",+ "archived_empty": "보관된 알림이 없습니다",+ "unarchive_tooltip": "보관 해제"},"detail": {"select_prompt": "자세히 볼 알림을 선택하세요","empty": "인박스가 비어 있습니다","original_input": "원본 입력","edit_advanced": "고급 양식으로 수정",- "archive": "보관"+ "archive": "보관",+ "unarchive": "보관 해제"},"types": {"issue_assigned": "할당됨",@@ -67,6 +71,8 @@"mark_all_read_failed": "모두 읽음으로 표시하지 못했습니다","archive_all_failed": "모두 보관하지 못했습니다","archive_all_read_failed": "읽은 항목을 보관하지 못했습니다",- "archive_completed_failed": "완료된 항목을 보관하지 못했습니다"+ "archive_completed_failed": "완료된 항목을 보관하지 못했습니다",+ "unarchive_failed": "보관 해제에 실패했습니다",+ "archived_load_failed": "보관된 알림을 불러오지 못했습니다"}}diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.jsonindex cdd5b2960b..e3060eb8f7 100644--- a/packages/views/locales/zh-Hans/inbox.json+++ b/packages/views/locales/zh-Hans/inbox.json@@ -18,14 +18,18 @@"minutes": "{{count}} 分钟","hours": "{{count}} 小时","days": "{{count}} 天"- }+ },+ "archived_title": "已归档",+ "archived_empty": "暂无已归档通知",+ "unarchive_tooltip": "取消归档"},"detail": {"select_prompt": "选择一条通知查看详情","empty": "收件箱为空","original_input": "原始输入","edit_advanced": "在完整表单中编辑",- "archive": "归档"+ "archive": "归档",+ "unarchive": "取消归档"},"types": {"issue_assigned": "已分配",@@ -67,6 +71,8 @@"mark_all_read_failed": "全部标为已读失败","archive_all_failed": "归档全部失败","archive_all_read_failed": "归档已读失败",- "archive_completed_failed": "归档已完成失败"+ "archive_completed_failed": "归档已完成失败",+ "unarchive_failed": "取消归档失败",+ "archived_load_failed": "无法加载已归档通知"}}diff --git a/server/cmd/server/integration_test.go b/server/cmd/server/integration_test.goindex ad20982558..f4f9d0beb4 100644--- a/server/cmd/server/integration_test.go+++ b/server/cmd/server/integration_test.go@@ -848,6 +848,233 @@ func TestInboxUnreadSummaryThroughRouter(t *testing.T) {}}+// ---- Archived inbox (MUL-3736) ----++type inboxItemJSON struct {+ ID string `json:"id"`+ IssueID *string `json:"issue_id"`+ Title string `json:"title"`+ Read bool `json:"read"`+ Archived bool `json:"archived"`+}++// seedArchivedFixtureIssue creates an issue owned by the test user and returns+// its id, registering the cleanup that cascades to its inbox_item rows.+//+// `number` is taken from the workspace counter the way the real create path+// does it (see IncrementIssueCounter). Letting it default to 0 works only for a+// test that seeds ONE issue — a second one collides on uq_issue_workspace_number.+func seedArchivedFixtureIssue(t *testing.T, title string) string {+ t.Helper()+ ctx := context.Background()+ var issueID string+ if err := testPool.QueryRow(ctx, `+ WITH bumped AS (+ UPDATE workspace SET issue_counter = issue_counter + 1+ WHERE id = $1+ RETURNING issue_counter+ )+ INSERT INTO issue (workspace_id, title, creator_type, creator_id, number)+ SELECT $1, $2, 'member', $3, bumped.issue_counter FROM bumped+ RETURNING id+ `, testWorkspaceID, title, testUserID).Scan(&issueID); err != nil {+ t.Fatalf("failed to seed issue: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)+ })+ return issueID+}++func listArchivedInbox(t *testing.T) []inboxItemJSON {+ t.Helper()+ resp := authRequest(t, "GET", "/api/inbox/archived", nil)+ if resp.StatusCode != 200 {+ t.Fatalf("ListArchivedInbox: expected 200, got %d", resp.StatusCode)+ }+ var items []inboxItemJSON+ readJSON(t, resp, &items)+ if items == nil {+ t.Fatal("expected non-nil archived items array")+ }+ return items+}++func TestArchivedInboxThroughRouter(t *testing.T) {+ issueID := seedArchivedFixtureIssue(t, "Archived fixture")+ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, type, title, issue_id, archived)+ VALUES ($1, 'member', $2, 'new_comment', 'archived one', $3, true)+ `, testWorkspaceID, testUserID, issueID); err != nil {+ t.Fatalf("failed to seed inbox item: %v", err)+ }++ var found bool+ for _, item := range listArchivedInbox(t) {+ if item.Title == "archived one" {+ found = true+ if !item.Archived {+ t.Fatalf("archived list returned a non-archived item: %+v", item)+ }+ }+ }+ if !found {+ t.Fatal("expected the archived item in GET /api/inbox/archived")+ }+}++// The main inbox and the archived list must stay mutually exclusive per issue.+// Archiving is issue-level, so a NEW notification on an already-archived issue+// leaves old archived rows sitting next to a fresh active one — without the+// query's NOT EXISTS guard the issue would render in BOTH lists.+func TestArchivedInboxExcludesIssuesWithActiveItems(t *testing.T) {+ ctx := context.Background()+ revivedIssue := seedArchivedFixtureIssue(t, "Revived fixture")+ quietIssue := seedArchivedFixtureIssue(t, "Quiet fixture")++ if _, err := testPool.Exec(ctx, `+ INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, type, title, issue_id, archived, created_at)+ VALUES+ -- Archived a while ago, then a new notification arrived: back in the+ -- main inbox, so it must NOT appear in the archive.+ ($1, 'member', $2, 'new_comment', 'revived-old', $3, true, now() - interval '2 hours'),+ ($1, 'member', $2, 'status_changed', 'revived-new', $3, false, now()),+ -- Archived with no follow-up: belongs in the archive.+ ($1, 'member', $2, 'new_comment', 'quiet-old', $4, true, now() - interval '2 hours')+ `, testWorkspaceID, testUserID, revivedIssue, quietIssue); err != nil {+ t.Fatalf("failed to seed inbox items: %v", err)+ }++ var sawRevived, sawQuiet bool+ for _, item := range listArchivedInbox(t) {+ if item.IssueID == nil {+ continue+ }+ if *item.IssueID == revivedIssue {+ sawRevived = true+ }+ if *item.IssueID == quietIssue {+ sawQuiet = true+ }+ }+ if sawRevived {+ t.Fatal("an issue with an active inbox item must not appear in the archived list")+ }+ if !sawQuiet {+ t.Fatal("an issue whose items are all archived must appear in the archived list")+ }+}++// Unarchive restores the whole issue group (mirroring issue-level archive) and+// leaves `read` alone. Restoring an item that was archived while unread raises+// the unread badge again — that is correct, not a regression: the unread count+// only ever included non-archived rows.+func TestUnarchiveInboxPreservesUnread(t *testing.T) {+ ctx := context.Background()+ issueID := seedArchivedFixtureIssue(t, "Unarchive fixture")++ var unreadItemID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, type, title, issue_id, read, archived, created_at)+ VALUES ($1, 'member', $2, 'new_comment', 'archived unread', $3, false, true, now())+ RETURNING id+ `, testWorkspaceID, testUserID, issueID).Scan(&unreadItemID); err != nil {+ t.Fatalf("failed to seed inbox item: %v", err)+ }+ // A read sibling on the same issue: the restore is issue-level, so it must+ // come back too — and come back READ, not reset.+ if _, err := testPool.Exec(ctx, `+ INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, type, title, issue_id, read, archived, created_at)+ VALUES ($1, 'member', $2, 'status_changed', 'archived read', $3, true, true, now() - interval '1 hour')+ `, testWorkspaceID, testUserID, issueID); err != nil {+ t.Fatalf("failed to seed sibling inbox item: %v", err)+ }++ resp := authRequest(t, "POST", "/api/inbox/"+unreadItemID+"/unarchive", nil)+ if resp.StatusCode != 200 {+ t.Fatalf("UnarchiveInboxItem: expected 200, got %d", resp.StatusCode)+ }+ var restored inboxItemJSON+ readJSON(t, resp, &restored)+ if restored.Archived {+ t.Fatalf("expected the restored item to be un-archived, got %+v", restored)+ }+ if restored.Read {+ t.Fatalf("unarchive must not mark an unread item read, got %+v", restored)+ }++ // Both siblings are back, each with its original read state.+ rows, err := testPool.Query(ctx, `+ SELECT title, read, archived FROM inbox_item WHERE issue_id = $1 ORDER BY title+ `, issueID)+ if err != nil {+ t.Fatalf("failed to read back inbox items: %v", err)+ }+ defer rows.Close()+ got := map[string][2]bool{}+ for rows.Next() {+ var title string+ var read, archived bool+ if err := rows.Scan(&title, &read, &archived); err != nil {+ t.Fatalf("scan: %v", err)+ }+ got[title] = [2]bool{read, archived}+ }+ if want := ([2]bool{false, false}); got["archived unread"] != want {+ t.Fatalf("unread item: expected read=false archived=false, got read=%v archived=%v",+ got["archived unread"][0], got["archived unread"][1])+ }+ if want := ([2]bool{true, false}); got["archived read"] != want {+ t.Fatalf("read sibling: expected read=true archived=false, got read=%v archived=%v",+ got["archived read"][0], got["archived read"][1])+ }++ // The restored unread item now counts toward the badge again.+ resp = authRequest(t, "GET", "/api/inbox/unread-count", nil)+ if resp.StatusCode != 200 {+ t.Fatalf("CountUnreadInbox: expected 200, got %d", resp.StatusCode)+ }+ var count struct {+ Count int64 `json:"count"`+ }+ readJSON(t, resp, &count)+ if count.Count < 1 {+ t.Fatal("expected the restored unread item to raise the unread count")+ }+}++// An inbox item belonging to someone else must not be unarchivable, even with a+// valid session — the loader resolves the item within the caller's workspace and+// recipient scope.+func TestUnarchiveInboxRejectsForeignItem(t *testing.T) {+ ctx := context.Background()+ var foreignItemID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, type, title, archived)+ VALUES ($1, 'member', gen_random_uuid(), 'issue_assigned', 'someone else', true)+ RETURNING id+ `, testWorkspaceID).Scan(&foreignItemID); err != nil {+ t.Fatalf("failed to seed foreign inbox item: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM inbox_item WHERE id = $1`, foreignItemID)+ })++ resp := authRequest(t, "POST", "/api/inbox/"+foreignItemID+"/unarchive", nil)+ if resp.StatusCode == 200 {+ t.Fatal("expected unarchive of another recipient's item to be rejected")+ }++ var archived bool+ if err := testPool.QueryRow(ctx,+ `SELECT archived FROM inbox_item WHERE id = $1`, foreignItemID).Scan(&archived); err != nil {+ t.Fatalf("failed to read back foreign item: %v", err)+ }+ if !archived {+ t.Fatal("another recipient's item must stay archived")+ }+}+// An issue's inbox notifications are deduplicated per issue: opening the issue// marks only the NEWEST item read, leaving older siblings unread. The summary// must mirror the inbox UI (issue is read when its newest item is read), so adiff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.goindex 2afa136b2c..8e17441625 100644--- a/server/cmd/server/listeners.go+++ b/server/cmd/server/listeners.go@@ -27,6 +27,7 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {protocol.EventInboxNew: true,protocol.EventInboxRead: true,protocol.EventInboxArchived: true,+ protocol.EventInboxUnarchived: true,protocol.EventInboxBatchRead: true,protocol.EventInboxBatchArchived: true,protocol.EventInvitationCreated: true,@@ -60,10 +61,10 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {sendToRecipient(b, e, recipientID)})- // inbox:read, inbox:archived, inbox:batch-read, inbox:batch-archived- // — extract recipient from top-level payload+ // inbox:read, inbox:archived, inbox:unarchived, inbox:batch-read,+ // inbox:batch-archived — extract recipient from top-level payloadfor _, eventType := range []string{- protocol.EventInboxRead, protocol.EventInboxArchived,+ protocol.EventInboxRead, protocol.EventInboxArchived, protocol.EventInboxUnarchived,protocol.EventInboxBatchRead, protocol.EventInboxBatchArchived,} {bus.Subscribe(eventType, func(e events.Event) {diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex eb2d70bb6c..9b1eb3e7d5 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1356,6 +1356,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Inboxr.Route("/api/inbox", func(r chi.Router) {r.Get("/", h.ListInbox)+ // Archived notifications, for the inbox's "Archived" sub-view.+ // Separate from "/" so the main list keeps its contract and+ // never carries the unbounded archive.+ r.Get("/archived", h.ListArchivedInbox)r.Get("/unread-count", h.CountUnreadInbox)// Cross-workspace unread summary: account-level, keyed on the// user. Backs the workspace-switcher dot for OTHER workspaces.@@ -1366,6 +1370,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/archive-completed", h.ArchiveCompletedInbox)r.Post("/{id}/read", h.MarkInboxRead)r.Post("/{id}/archive", h.ArchiveInboxItem)+ r.Post("/{id}/unarchive", h.UnarchiveInboxItem)})// Notification preferencesdiff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.goindex 5c5a934a66..a7b488b58b 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -73,6 +73,14 @@ func inboxRowToResponse(r db.ListInboxItemsRow) InboxItemResponse {}}+// ListArchivedInboxItemsRow carries the same columns as ListInboxItemsRow (both+// queries select `inbox_item.*` plus the joined issue status), so the archived+// row converts to the active one and reuses its mapper. If either query's+// column list drifts, this conversion stops compiling — which is the point.+func archivedInboxRowToResponse(r db.ListArchivedInboxItemsRow) InboxItemResponse {+ return inboxRowToResponse(db.ListInboxItemsRow(r))+}+func (h *Handler) enrichInboxResponse(ctx context.Context, resp InboxItemResponse, issueID pgtype.UUID) InboxItemResponse {if !issueID.Valid {return resp@@ -114,6 +122,43 @@ func (h *Handler) ListInbox(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, resp)}+// ListArchivedInbox returns the recipient's archived notifications, backing the+// inbox's "Archived" sub-view. Kept as its own endpoint rather than a flag on+// ListInbox so installed clients keep their current contract, and so the+// unbounded archive never rides along with the main list.+//+// The query drops any issue that also has an active row, keeping this list and+// the main inbox mutually exclusive per issue group, and caps the response at+// 200 rows — see the query comment for both.+func (h *Handler) ListArchivedInbox(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ workspaceID := ctxWorkspaceID(r.Context())+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")+ if !ok {+ return+ }++ items, err := h.Queries.ListArchivedInboxItems(r.Context(), db.ListArchivedInboxItemsParams{+ WorkspaceID: wsUUID,+ RecipientType: "member",+ RecipientID: parseUUID(userID),+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list archived inbox")+ return+ }++ resp := make([]InboxItemResponse, len(items))+ for i, item := range items {+ resp[i] = archivedInboxRowToResponse(item)+ }++ writeJSON(w, http.StatusOK, resp)+}+func (h *Handler) MarkInboxRead(w http.ResponseWriter, r *http.Request) {id := chi.URLParam(r, "id")prev, ok := h.loadInboxItemForUser(w, r, id)@@ -171,6 +216,48 @@ func (h *Handler) ArchiveInboxItem(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, resp)}+// UnarchiveInboxItem restores an archived notification to the main inbox. It is+// the inverse of ArchiveInboxItem and mirrors its issue-level scope: archiving+// one item archives every sibling for the same issue, so restoring brings the+// whole group back.+//+// `read` is untouched on purpose. An item archived while unread comes back+// unread, which raises the unread badge again — the badge only ever counted+// non-archived items, so restoring one is a real addition, not a bug.+func (h *Handler) UnarchiveInboxItem(w http.ResponseWriter, r *http.Request) {+ id := chi.URLParam(r, "id")+ prev, ok := h.loadInboxItemForUser(w, r, id)+ if !ok {+ return+ }+ item, err := h.Queries.UnarchiveInboxItem(r.Context(), prev.ID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to unarchive")+ return+ }++ // Restore all sibling inbox items for the same issue (issue-level restore).+ if item.IssueID.Valid {+ h.Queries.UnarchiveInboxByIssue(r.Context(), db.UnarchiveInboxByIssueParams{+ WorkspaceID: item.WorkspaceID,+ RecipientType: item.RecipientType,+ RecipientID: item.RecipientID,+ IssueID: item.IssueID,+ })+ }++ userID := requestUserID(r)+ workspaceID := uuidToString(item.WorkspaceID)+ h.publish(protocol.EventInboxUnarchived, workspaceID, "member", userID, map[string]any{+ "item_id": uuidToString(item.ID),+ "issue_id": uuidToPtr(item.IssueID),+ "recipient_id": uuidToString(item.RecipientID),+ })++ resp := h.enrichInboxResponse(r.Context(), inboxToResponse(item), item.IssueID)+ writeJSON(w, http.StatusOK, resp)+}+func (h *Handler) CountUnreadInbox(w http.ResponseWriter, r *http.Request) {userID, ok := requireUserID(w, r)if !ok {diff --git a/server/migrations/200_inbox_archived_listing_index.down.sql b/server/migrations/200_inbox_archived_listing_index.down.sqlnew file mode 100644index 0000000000..7df5a40686--- /dev/null+++ b/server/migrations/200_inbox_archived_listing_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_inbox_recipient_archived_created;diff --git a/server/migrations/200_inbox_archived_listing_index.up.sql b/server/migrations/200_inbox_archived_listing_index.up.sqlnew file mode 100644index 0000000000..fdbaa1ce9b--- /dev/null+++ b/server/migrations/200_inbox_archived_listing_index.up.sql@@ -0,0 +1,8 @@+-- Back the archived-inbox listing (MUL-3736). The only inbox_item index is+-- idx_inbox_recipient (recipient_type, recipient_id, read), which carries+-- neither workspace_id nor archived nor created_at, so the archived list would+-- scan and sort every notification the recipient ever received. Keep this as+-- the migration's only statement: PostgreSQL rejects CREATE INDEX CONCURRENTLY+-- inside a transaction or multi-command string.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_inbox_recipient_archived_created+ ON inbox_item (workspace_id, recipient_type, recipient_id, archived, created_at DESC);diff --git a/server/migrations/201_inbox_active_by_issue_index.down.sql b/server/migrations/201_inbox_active_by_issue_index.down.sqlnew file mode 100644index 0000000000..8f28bcca4e--- /dev/null+++ b/server/migrations/201_inbox_active_by_issue_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_inbox_active_by_issue;diff --git a/server/migrations/201_inbox_active_by_issue_index.up.sql b/server/migrations/201_inbox_active_by_issue_index.up.sqlnew file mode 100644index 0000000000..f486225d96--- /dev/null+++ b/server/migrations/201_inbox_active_by_issue_index.up.sql@@ -0,0 +1,10 @@+-- Partial index over ACTIVE rows keyed by issue (MUL-3736). Serves the+-- NOT EXISTS probe in ListArchivedInboxItems, which asks "does this issue still+-- have a non-archived row?" once per archived row, and the identically-filtered+-- ArchiveInboxByIssue / UnarchiveInboxByIssue writes. Partial on archived=false+-- so it stays small as the archive grows. Keep this as the migration's only+-- statement: PostgreSQL rejects CREATE INDEX CONCURRENTLY inside a transaction+-- or multi-command string.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_inbox_active_by_issue+ ON inbox_item (workspace_id, recipient_type, recipient_id, issue_id)+ WHERE archived = false;diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.goindex bafd32ca64..afa1c130cc 100644--- a/server/pkg/db/generated/inbox.sql.go+++ b/server/pkg/db/generated/inbox.sql.go@@ -345,6 +345,102 @@ func (q *Queries) GetInboxItemInWorkspace(ctx context.Context, arg GetInboxItemIreturn i, err}+const listArchivedInboxItems = `-- name: ListArchivedInboxItems :many+SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details,+ iss.status as issue_status+FROM inbox_item i+LEFT JOIN issue iss ON iss.id = i.issue_id+WHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3 AND i.archived = 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 i.created_at DESC+LIMIT 200+`++type ListArchivedInboxItemsParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientType string `json:"recipient_type"`+ RecipientID pgtype.UUID `json:"recipient_id"`+}++type ListArchivedInboxItemsRow struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientType string `json:"recipient_type"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ Type string `json:"type"`+ Severity string `json:"severity"`+ IssueID pgtype.UUID `json:"issue_id"`+ Title string `json:"title"`+ Body pgtype.Text `json:"body"`+ Read bool `json:"read"`+ Archived bool `json:"archived"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ ActorType pgtype.Text `json:"actor_type"`+ ActorID pgtype.UUID `json:"actor_id"`+ Details []byte `json:"details"`+ IssueStatus pgtype.Text `json:"issue_status"`+}++// Archived counterpart of ListInboxItems, backing the inbox's "Archived"+// sub-view (MUL-3736).+//+// An issue whose group still has an active row is excluded: archiving is+// issue-level, so a NEW notification on an already-archived issue leaves the+// old archived rows in place alongside the fresh active one. The issue belongs+// in the main inbox at that point, and the two lists must stay mutually+// exclusive per issue group — otherwise the same issue renders in both. The+// exclusion lives here rather than in the client so neither list depends on+// the other's cache being loaded. Items without an issue_id group on their own+// id and can never have an active sibling, hence the IS NULL short-circuit.+//+// LIMIT bounds the response while the archive grows without end (v1 ships no+// pagination). Rows are newest-first, so truncation drops the OLDEST rows and+// can never hide a group's newest row — the one the deduplicated UI renders.+func (q *Queries) ListArchivedInboxItems(ctx context.Context, arg ListArchivedInboxItemsParams) ([]ListArchivedInboxItemsRow, error) {+ rows, err := q.db.Query(ctx, listArchivedInboxItems, arg.WorkspaceID, arg.RecipientType, arg.RecipientID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListArchivedInboxItemsRow{}+ for rows.Next() {+ var i ListArchivedInboxItemsRow+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.RecipientType,+ &i.RecipientID,+ &i.Type,+ &i.Severity,+ &i.IssueID,+ &i.Title,+ &i.Body,+ &i.Read,+ &i.Archived,+ &i.CreatedAt,+ &i.ActorType,+ &i.ActorID,+ &i.Details,+ &i.IssueStatus,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listInboxItems = `-- name: ListInboxItems :manySELECT 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,iss.status as issue_status@@ -462,3 +558,63 @@ func (q *Queries) MarkInboxRead(ctx context.Context, id pgtype.UUID) (InboxItem,)return i, err}++const unarchiveInboxByIssue = `-- name: UnarchiveInboxByIssue :execrows+UPDATE inbox_item SET archived = false+WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_id = $4 AND archived = true+`++type UnarchiveInboxByIssueParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientType string `json:"recipient_type"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++// Issue-level restore, mirroring ArchiveInboxByIssue: archiving one item+// archives every sibling for the same issue, so unarchiving must bring the+// whole group back. Leaves `read` untouched for the same reason as above.+func (q *Queries) UnarchiveInboxByIssue(ctx context.Context, arg UnarchiveInboxByIssueParams) (int64, error) {+ result, err := q.db.Exec(ctx, unarchiveInboxByIssue,+ arg.WorkspaceID,+ arg.RecipientType,+ arg.RecipientID,+ arg.IssueID,+ )+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const unarchiveInboxItem = `-- name: UnarchiveInboxItem :one+UPDATE inbox_item SET archived = false+WHERE id = $1+RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details+`++// Deliberately does not touch `read`: unarchiving restores an item to the main+// inbox in the exact read/unread state it was archived in, so restoring an+// unread item legitimately raises the unread badge again (MUL-3736).+func (q *Queries) UnarchiveInboxItem(ctx context.Context, id pgtype.UUID) (InboxItem, error) {+ row := q.db.QueryRow(ctx, unarchiveInboxItem, id)+ var i InboxItem+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.RecipientType,+ &i.RecipientID,+ &i.Type,+ &i.Severity,+ &i.IssueID,+ &i.Title,+ &i.Body,+ &i.Read,+ &i.Archived,+ &i.CreatedAt,+ &i.ActorType,+ &i.ActorID,+ &i.Details,+ )+ return i, err+}diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sqlindex bc7a5161e4..2d4064a5bf 100644--- a/server/pkg/db/queries/inbox.sql+++ b/server/pkg/db/queries/inbox.sql@@ -6,6 +6,39 @@ LEFT JOIN issue iss ON iss.id = i.issue_idWHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3 AND i.archived = falseORDER BY i.created_at DESC;+-- name: ListArchivedInboxItems :many+-- Archived counterpart of ListInboxItems, backing the inbox's "Archived"+-- sub-view (MUL-3736).+--+-- An issue whose group still has an active row is excluded: archiving is+-- issue-level, so a NEW notification on an already-archived issue leaves the+-- old archived rows in place alongside the fresh active one. The issue belongs+-- in the main inbox at that point, and the two lists must stay mutually+-- exclusive per issue group — otherwise the same issue renders in both. The+-- exclusion lives here rather than in the client so neither list depends on+-- the other's cache being loaded. Items without an issue_id group on their own+-- id and can never have an active sibling, hence the IS NULL short-circuit.+--+-- LIMIT bounds the response while the archive grows without end (v1 ships no+-- pagination). Rows are newest-first, so truncation drops the OLDEST rows and+-- can never hide a group's newest row — the one the deduplicated UI renders.+SELECT i.*,+ iss.status as issue_status+FROM inbox_item i+LEFT JOIN issue iss ON iss.id = i.issue_id+WHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3 AND i.archived = 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 i.created_at DESC+LIMIT 200;+-- name: GetInboxItem :oneSELECT * FROM inbox_itemWHERE id = $1;@@ -36,6 +69,21 @@ RETURNING *;UPDATE inbox_item SET archived = trueWHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_id = $4 AND archived = false;+-- name: UnarchiveInboxItem :one+-- Deliberately does not touch `read`: unarchiving restores an item to the main+-- inbox in the exact read/unread state it was archived in, so restoring an+-- unread item legitimately raises the unread badge again (MUL-3736).+UPDATE inbox_item SET archived = false+WHERE id = $1+RETURNING *;++-- name: UnarchiveInboxByIssue :execrows+-- Issue-level restore, mirroring ArchiveInboxByIssue: archiving one item+-- archives every sibling for the same issue, so unarchiving must bring the+-- whole group back. Leaves `read` untouched for the same reason as above.+UPDATE inbox_item SET archived = false+WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_id = $4 AND archived = true;+-- name: ArchiveInboxByIssueAndType :manyUPDATE inbox_item SET archived = trueWHERE workspace_id = $1 AND issue_id = $2 AND type = $3 AND archived = falsediff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex d6e0d8d2fc..831a1109bf 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -44,6 +44,7 @@ const (EventInboxNew = "inbox:new"EventInboxRead = "inbox:read"EventInboxArchived = "inbox:archived"+ EventInboxUnarchived = "inbox:unarchived"EventInboxBatchRead = "inbox:batch-read"EventInboxBatchArchived = "inbox:batch-archived"