Skip to content

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

Go

feat(inbox): mark a notification unread from the row context menu (MUL-5496) (#6137)

Jiayuan Zhangf0110da555b2
diff --git a/apps/docs/content/docs/inbox.ja.mdx b/apps/docs/content/docs/inbox.ja.mdx
index 4e87b467e8..e9f29089e0 100644
--- a/apps/docs/content/docs/inbox.ja.mdx
+++ b/apps/docs/content/docs/inbox.ja.mdx
@@ -47,6 +47,8 @@ import { Callout } from "fumadocs-ui/components/callout";
通知を選択すると既読になります。対応が済んだらアーカイブできます。アーカイブしても対応するイシューは変更・削除されません。イシューが `in_review`、`done`、`cancelled` になると、その「実行失敗」の通知は自動的にアーカイブされます。
+通知を右クリックすると、**既読にする** / **未読にする**と**アーカイブ**(「アーカイブ済み」ビューでは**アーカイブ解除**)を使えます。未読にするは「目は通したが、まだ終わっていない」ための操作です。通知は未読に戻り、未読数も戻ります。開いたままでも未読のままで、あとでもう一度開けば通常どおり既読になります。アーカイブ済みの通知は既読状態を保持するため、復元すると元のまま戻ります。
+
インボックスのメニューからは次の操作もできます。
- すべて既読にする
diff --git a/apps/docs/content/docs/inbox.ko.mdx b/apps/docs/content/docs/inbox.ko.mdx
index b1624d2b7a..2212d48fd8 100644
--- a/apps/docs/content/docs/inbox.ko.mdx
+++ b/apps/docs/content/docs/inbox.ko.mdx
@@ -47,6 +47,8 @@ import { Callout } from "fumadocs-ui/components/callout";
알림을 선택하면 읽음으로 표시됩니다. 처리한 뒤 보관할 수 있으며, 보관해도 해당 이슈가 변경되거나 삭제되지 않습니다. 이슈가 `in_review`, `done`, `cancelled` 상태가 되면 그 이슈의 "실행 실패" 알림은 자동으로 보관됩니다.
+알림을 오른쪽 클릭하면 **읽음으로 표시** / **읽지 않음으로 표시**와 **보관**("보관됨" 뷰에서는 **보관 해제**)을 쓸 수 있습니다. 읽지 않음으로 표시는 "보긴 했지만 아직 끝내지 않았다"는 뜻입니다. 알림이 다시 읽지 않음이 되고 읽지 않은 개수도 다시 올라가며, 열어둔 상태에서도 읽지 않음으로 유지됩니다. 나중에 다시 열면 평소대로 읽음으로 바뀝니다. 보관된 알림은 읽음 상태를 유지하므로 복원하면 그대로 돌아옵니다.
+
인박스 메뉴에서는 다음 작업도 할 수 있습니다.
- 모두 읽음으로 표시
diff --git a/apps/docs/content/docs/inbox.mdx b/apps/docs/content/docs/inbox.mdx
index fdb170f414..1a0564fa8c 100644
--- a/apps/docs/content/docs/inbox.mdx
+++ b/apps/docs/content/docs/inbox.mdx
@@ -47,6 +47,8 @@ The inbox is only for workspace members. Even when an agent is the assignee or a
Selecting a notification marks it as read. Archive it when you're done; archiving doesn't modify or delete the corresponding issue. Once an issue reaches `in_review`, `done`, or `cancelled`, its run-failure notifications archive automatically.
+Right-click a notification for **Mark as read** / **Mark as unread** and **Archive** (**Unarchive** in the Archived view). Mark as unread is the "I looked, but I'm not done with this" action: the notification goes back to unread and raises the unread count again, and it stays unread even while you keep it open — opening it again later marks it read as usual. Archived notifications keep their read state, so restoring one brings it back exactly as you left it.
+
From the inbox menu you can also:
- mark all as read;
diff --git a/apps/docs/content/docs/inbox.zh.mdx b/apps/docs/content/docs/inbox.zh.mdx
index 1df514ac8d..9424dca77b 100644
--- a/apps/docs/content/docs/inbox.zh.mdx
+++ b/apps/docs/content/docs/inbox.zh.mdx
@@ -47,6 +47,8 @@ import { Callout } from "fumadocs-ui/components/callout";
选择一条通知会把它标为已读。处理完后可以归档;归档不会修改或删除对应的 issue。issue 进入 `in_review`、`done` 或 `cancelled` 后,它的"执行失败"通知会自动归档。
+右键点击一条通知,可以使用**标为已读** / **标为未读**和**归档**(在"已归档"视图中是**取消归档**)。标为未读表达的是"我看过了,但还没处理完":该通知重新变为未读,未读数也会回升;即使它还开着也会保持未读——之后再打开一次才会照常标为已读。已归档的通知会保留已读状态,因此恢复时会原样回来。
+
收件箱菜单还可以:
- 全部标为已读;
diff --git a/apps/mobile/data/realtime/use-inbox-realtime.ts b/apps/mobile/data/realtime/use-inbox-realtime.ts
index 9b2753464d..e3970c1396 100644
--- a/apps/mobile/data/realtime/use-inbox-realtime.ts
+++ b/apps/mobile/data/realtime/use-inbox-realtime.ts
@@ -42,6 +42,11 @@ export function useInboxRealtime() {
// Inbox-domain events: refetch the small inbox list.
ws.on("inbox:new", invalidate),
ws.on("inbox:read", invalidate),
+ // Mobile has no mark-unread affordance yet (web/desktop right-click
+ // only), but a mark-unread there must un-read the row here too —
+ // otherwise the phone keeps showing it read and the unread dots
+ // disagree across clients.
+ ws.on("inbox:unread", 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,
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index c71ba77023..c0d285a5bd 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -1842,6 +1842,10 @@ export class ApiClient {
return this.fetch(`/api/inbox/${id}/read`, { method: "POST" });
}
+ async markInboxUnread(id: string): Promise<InboxItem> {
+ return this.fetch(`/api/inbox/${id}/unread`, { method: "POST" });
+ }
+
async archiveInbox(id: string): Promise<InboxItem> {
return this.fetch(`/api/inbox/${id}/archive`, { method: "POST" });
}
diff --git a/packages/core/inbox/mutations.test.tsx b/packages/core/inbox/mutations.test.tsx
index e1fb3054a3..d44e2867dc 100644
--- a/packages/core/inbox/mutations.test.tsx
+++ b/packages/core/inbox/mutations.test.tsx
@@ -9,7 +9,7 @@ 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 { useMarkInboxUnread, useUnarchiveInbox } from "./mutations";
import { inboxKeys } from "./queries";
vi.mock("../hooks", () => ({
@@ -52,6 +52,85 @@ function archivedCache(qc: QueryClient) {
return qc.getQueryData<InboxItem[]>(inboxKeys.archived(WORKSPACE_ID)) ?? [];
}
+function listCache(qc: QueryClient) {
+ return qc.getQueryData<InboxItem[]>(inboxKeys.list(WORKSPACE_ID)) ?? [];
+}
+
+describe("useMarkInboxUnread", () => {
+ let queryClient: QueryClient;
+ let markInboxUnread: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ markInboxUnread = vi.fn(async (id: string) => item({ id, read: false }));
+ setApiInstance({ markInboxUnread } as unknown as ApiClient);
+ });
+
+ it("flips only the targeted item unread, in both lists", async () => {
+ // Item-level, mirroring mark-read: the list shows one row per issue
+ // carrying that group's newest item, so flipping siblings would resurrect
+ // notifications the user already dealt with without changing the row.
+ queryClient.setQueryData<InboxItem[]>(inboxKeys.list(WORKSPACE_ID), [
+ item({ id: "inbox-1", read: true, archived: false }),
+ item({ id: "sibling", issue_id: "issue-1", read: true, archived: false }),
+ ]);
+ queryClient.setQueryData<InboxItem[]>(inboxKeys.archived(WORKSPACE_ID), [
+ item({ id: "inbox-1", read: true }),
+ ]);
+
+ const { result } = renderHook(() => useMarkInboxUnread(), {
+ wrapper: createWrapper(queryClient),
+ });
+ result.current.mutate("inbox-1");
+
+ await waitFor(() => {
+ expect(
+ listCache(queryClient).find((i) => i.id === "inbox-1")?.read,
+ ).toBe(false);
+ });
+ expect(listCache(queryClient).find((i) => i.id === "sibling")?.read).toBe(true);
+ // Actioned from either list, patched in both — otherwise a view switch
+ // shows two different read states for one notification.
+ expect(archivedCache(queryClient)[0]?.read).toBe(false);
+ });
+
+ it("refreshes the cross-workspace summary so the switcher dot lights again", async () => {
+ queryClient.setQueryData<InboxItem[]>(inboxKeys.list(WORKSPACE_ID), [
+ item({ id: "inbox-1", read: true, archived: false }),
+ ]);
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");
+
+ const { result } = renderHook(() => useMarkInboxUnread(), {
+ wrapper: createWrapper(queryClient),
+ });
+ result.current.mutate("inbox-1");
+
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: inboxKeys.unreadSummary(),
+ });
+ });
+
+ it("rolls both lists back when the request fails", async () => {
+ markInboxUnread.mockRejectedValue(new Error("boom"));
+ const active = [item({ id: "inbox-1", read: true, archived: false })];
+ const archived = [item({ id: "inbox-1", read: true })];
+ queryClient.setQueryData<InboxItem[]>(inboxKeys.list(WORKSPACE_ID), active);
+ queryClient.setQueryData<InboxItem[]>(inboxKeys.archived(WORKSPACE_ID), archived);
+
+ const { result } = renderHook(() => useMarkInboxUnread(), {
+ wrapper: createWrapper(queryClient),
+ });
+ result.current.mutate("inbox-1");
+
+ await waitFor(() => expect(result.current.isError).toBe(true));
+ expect(listCache(queryClient)).toEqual(active);
+ expect(archivedCache(queryClient)).toEqual(archived);
+ });
+});
+
describe("useUnarchiveInbox", () => {
let queryClient: QueryClient;
let unarchiveInbox: ReturnType<typeof vi.fn>;
diff --git a/packages/core/inbox/mutations.ts b/packages/core/inbox/mutations.ts
index e6dd44e20e..f9cb7642a8 100644
--- a/packages/core/inbox/mutations.ts
+++ b/packages/core/inbox/mutations.ts
@@ -32,6 +32,47 @@ export function useMarkInboxRead() {
});
}
+/**
+ * Flip a notification back to unread — the inverse of {@link useMarkInboxRead}.
+ *
+ * Same optimistic shape as marking read (predictable outcome, no navigation,
+ * trivial rollback), and it patches BOTH caches for the same reason: an item
+ * can be actioned from either list, and leaving the other one stale would show
+ * two different read states for one notification after a view switch.
+ *
+ * The unread badge is derived from the main list's cache (`useInboxUnreadCount`
+ * dedupes it client-side), so the optimistic patch raises the badge without
+ * waiting for the round-trip; `onSettled` re-pulls the cross-workspace summary,
+ * which is server-computed and cannot be patched here.
+ */
+export function useMarkInboxUnread() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (id: string) => api.markInboxUnread(id),
+ 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);
+ 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.all(wsId) });
+ // The switcher dot must light again when the workspace goes back to
+ // having unread items — that count lives on the server.
+ qc.invalidateQueries({ queryKey: inboxKeys.unreadSummary() });
+ },
+ });
+}
+
export function useArchiveInbox() {
const qc = useQueryClient();
const wsId = useWorkspaceId();
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index 059a4ae90b..d0fe0d9bd6 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -33,6 +33,7 @@ export type WSEventType =
| "task:cancelled"
| "inbox:new"
| "inbox:read"
+ | "inbox:unread"
| "inbox:archived"
| "inbox:unarchived"
| "inbox:batch-read"
@@ -162,6 +163,12 @@ export interface InboxReadPayload {
recipient_id: string;
}
+/** Emitted when a recipient flips a notification back to unread. */
+export interface InboxUnreadPayload {
+ item_id: string;
+ recipient_id: string;
+}
+
export interface InboxArchivedPayload {
item_id: string;
recipient_id: string;
@@ -493,6 +500,7 @@ export interface WSEventPayloadMap {
"task:progress": unknown;
"inbox:new": InboxNewPayload;
"inbox:read": InboxReadPayload;
+ "inbox:unread": InboxUnreadPayload;
"inbox:archived": InboxArchivedPayload;
"inbox:unarchived": InboxUnarchivedPayload;
"inbox:batch-read": InboxBatchReadPayload;
diff --git a/packages/views/inbox/components/inbox-context-menu.test.tsx b/packages/views/inbox/components/inbox-context-menu.test.tsx
new file mode 100644
index 0000000000..892e8d9883
--- /dev/null
+++ b/packages/views/inbox/components/inbox-context-menu.test.tsx
@@ -0,0 +1,142 @@
+import { describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import type { ReactNode } from "react";
+import type { InboxItem } from "@multica/core/types";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enInbox from "../../locales/en/inbox.json";
+
+vi.mock("../../issues/components", () => ({ StatusIcon: () => null }));
+vi.mock("../../issues/components/issue-agent-activity-indicator", () => ({
+ IssueAgentActivityIndicator: () => null,
+}));
+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
+vi.mock("./inbox-detail-label", () => ({ InboxDetailLabel: () => null }));
+
+// Import after mocks.
+import { InboxContextMenuProvider, type InboxRowActions } from "./inbox-context-menu";
+import { InboxListItem } from "./inbox-list-item";
+
+const TEST_RESOURCES = { en: { inbox: enInbox } };
+
+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 wrap(ui: ReactNode) {
+ return (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ {ui}
+ </I18nProvider>
+ );
+}
+
+function renderRow({
+ entry = item(),
+ view = "inbox" as const,
+ actions = {},
+}: {
+ entry?: InboxItem;
+ view?: "inbox" | "archived";
+ actions?: Partial<InboxRowActions>;
+} = {}) {
+ const rowActions: InboxRowActions = {
+ onMarkRead: vi.fn(),
+ onMarkUnread: vi.fn(),
+ onAction: vi.fn(),
+ ...actions,
+ };
+ render(
+ wrap(
+ <InboxContextMenuProvider view={view} actions={rowActions}>
+ <InboxListItem
+ item={entry}
+ view={view}
+ isSelected={false}
+ onClick={vi.fn()}
+ onAction={vi.fn()}
+ />
+ </InboxContextMenuProvider>,
+ ),
+ );
+ const row = screen.getByText(entry.title).closest("button");
+ if (!row) throw new Error("inbox row button not found");
+ return { rowActions, row };
+}
+
+describe("inbox row context menu", () => {
+ it("offers mark-as-unread on a read row and reports the item id", async () => {
+ const onMarkUnread = vi.fn();
+ const { row } = renderRow({
+ entry: item({ id: "inbox-7", read: true }),
+ actions: { onMarkUnread },
+ });
+
+ fireEvent.contextMenu(row);
+ fireEvent.click(await screen.findByText("Mark as unread"));
+
+ expect(onMarkUnread).toHaveBeenCalledWith("inbox-7");
+ });
+
+ it("offers mark-as-read on an unread row instead", async () => {
+ // One toggle, not two entries: the row is either read or unread, and
+ // offering the no-op direction is noise the user has to read past.
+ const { row } = renderRow({ entry: item({ read: false }) });
+
+ fireEvent.contextMenu(row);
+
+ expect(await screen.findByText("Mark as read")).toBeInTheDocument();
+ expect(screen.queryByText("Mark as unread")).toBeNull();
+ });
+
+ it("archives from the menu in the main view", async () => {
+ const onAction = vi.fn();
+ const { row } = renderRow({ entry: item({ id: "inbox-3" }), actions: { onAction } });
+
+ fireEvent.contextMenu(row);
+ fireEvent.click(await screen.findByText("Archive"));
+
+ expect(onAction).toHaveBeenCalledWith("inbox-3");
+ });
+
+ it("drops the read toggle in the archived view and offers unarchive", async () => {
+ // Archived rows deliberately render as read and the unread count excludes
+ // them, so a read toggle there would report success and change nothing.
+ const { row } = renderRow({
+ entry: item({ read: true, archived: true }),
+ view: "archived",
+ });
+
+ fireEvent.contextMenu(row);
+
+ expect(await screen.findByText("Unarchive")).toBeInTheDocument();
+ expect(screen.queryByText("Mark as unread")).toBeNull();
+ expect(screen.queryByText("Mark as read")).toBeNull();
+ });
+
+ it("suppresses the browser's native menu so ours is the only one", async () => {
+ const { row } = renderRow();
+
+ const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
+ row.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(true);
+ });
+});
diff --git a/packages/views/inbox/components/inbox-context-menu.tsx b/packages/views/inbox/components/inbox-context-menu.tsx
new file mode 100644
index 0000000000..1c9d73f7b0
--- /dev/null
+++ b/packages/views/inbox/components/inbox-context-menu.tsx
@@ -0,0 +1,184 @@
+"use client";
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useMemo,
+ useRef,
+ useState,
+ type MouseEvent,
+ type ReactNode,
+} from "react";
+import { Archive, ArchiveRestore, Check, CircleDot } from "lucide-react";
+import type { InboxItem } from "@multica/core/types";
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuSeparator,
+} from "@multica/ui/components/ui/context-menu";
+import type { InboxView } from "./inbox-view";
+import { useT } from "../../i18n";
+
+/**
+ * Right-click actions for inbox rows.
+ *
+ * One shared menu for the whole list rather than a Base UI ContextMenu root
+ * per row — the same shape `IssueContextMenuProvider` uses, for the same two
+ * reasons. Only one menu is ever open, so N roots is N times the machinery for
+ * nothing; and the list is virtualized, so a per-row root would unmount (taking
+ * its open menu with it) the moment the row scrolls out of the viewport.
+ *
+ * Rows delegate: the row only reports (item, cursor position) up to this
+ * singleton, which anchors the menu at the cursor via a virtual anchor element.
+ */
+
+/** Row-level actions the menu invokes, all keyed by inbox item id. */
+export interface InboxRowActions {
+ onMarkRead: (id: string) => void;
+ onMarkUnread: (id: string) => void;
+ /**
+ * Archive in the main list, unarchive in the archived one — the same
+ * reversal-of-the-current-view the row's hover button performs.
+ */
+ onAction: (id: string) => void;
+}
+
+interface ActiveMenu {
+ item: InboxItem;
+ position: { x: number; y: number };
+}
+
+type OpenInboxContextMenu = (item: InboxItem, event: MouseEvent) => void;
+
+const InboxContextMenuContext = createContext<OpenInboxContextMenu | null>(null);
+
+export function InboxContextMenuProvider({
+ view,
+ actions,
+ children,
+}: {
+ view: InboxView;
+ actions: InboxRowActions;
+ children: ReactNode;
+}) {
+ const [active, setActive] = useState<ActiveMenu | null>(null);
+ const [open, setOpen] = useState(false);
+ // The row the user right-clicked. Rows style their "menu is open for me"
+ // state off `data-popup-open`; setting it imperatively keeps that affordance
+ // without re-rendering every row on open/close.
+ const triggerElRef = useRef<HTMLElement | null>(null);
+
+ const openMenu = useCallback<OpenInboxContextMenu>((item, event) => {
+ event.preventDefault();
+ triggerElRef.current?.removeAttribute("data-popup-open");
+ const el = event.currentTarget as HTMLElement;
+ el.setAttribute("data-popup-open", "");
+ triggerElRef.current = el;
+ setActive({ item, position: { x: event.clientX, y: event.clientY } });
+ setOpen(true);
+ }, []);
+
+ const handleOpenChange = useCallback((v: boolean) => {
+ if (!v) {
+ triggerElRef.current?.removeAttribute("data-popup-open");
+ triggerElRef.current = null;
+ }
+ setOpen(v);
+ }, []);
+
+ return (
+ <InboxContextMenuContext.Provider value={openMenu}>
+ {children}
+ {/* Mounted on first use, kept mounted after — the popup itself unmounts
+ while closed. */}
+ {active && (
+ <InboxContextMenuSingleton
+ item={active.item}
+ position={active.position}
+ view={view}
+ actions={actions}
+ open={open}
+ onOpenChange={handleOpenChange}
+ />
+ )}
+ </InboxContextMenuContext.Provider>
+ );
+}
+
+/**
+ * Opens the list's shared context menu for a row. Returns `null` when no
+ * provider is above — the row then simply has no right-click menu instead of
+ * crashing, which keeps `InboxListItem` renderable on its own.
+ */
+export function useInboxContextMenu(): OpenInboxContextMenu | null {
+ return useContext(InboxContextMenuContext);
+}
+
+function InboxContextMenuSingleton({
+ item,
+ position,
+ view,
+ actions,
+ open,
+ onOpenChange,
+}: ActiveMenu & {
+ view: InboxView;
+ actions: InboxRowActions;
+ open: boolean;
+ onOpenChange: (v: boolean) => void;
+}) {
+ const { t } = useT("inbox");
+ const isArchivedView = view === "archived";
+
+ // Point-sized virtual anchor at the right-click position, so the menu opens
+ // at the cursor rather than at the row's top-left corner.
+ const anchor = useMemo(
+ () => ({
+ getBoundingClientRect: () =>
+ DOMRect.fromRect({ x: position.x, y: position.y, width: 0, height: 0 }),
+ }),
+ [position.x, position.y],
+ );
+
+ return (
+ <ContextMenu open={open} onOpenChange={onOpenChange}>
+ <ContextMenuContent anchor={anchor}>
+ {/* The read toggle is main-view only. Archived rows deliberately render
+ as read (archiving preserves `read` so a restore can bring the real
+ state back) and the unread count excludes archived items — so a
+ toggle here would report success and change nothing on screen. */}
+ {!isArchivedView && (
+ <>
+ {item.read === true ? (
+ <ContextMenuItem onClick={() => actions.onMarkUnread(item.id)}>
+ <CircleDot className="h-4 w-4" />
+ {t(($) => $.context_menu.mark_unread)}
+ </ContextMenuItem>
+ ) : (
+ <ContextMenuItem onClick={() => actions.onMarkRead(item.id)}>
+ <Check className="h-4 w-4" />
+ {t(($) => $.context_menu.mark_read)}
+ </ContextMenuItem>
+ )}
+ <ContextMenuSeparator />
+ </>
+ )}
+ <ContextMenuItem onClick={() => actions.onAction(item.id)}>
+ {isArchivedView ? (
+ <>
+ <ArchiveRestore className="h-4 w-4" />
+ {t(($) => $.context_menu.unarchive)}
+ </>
+ ) : (
+ <>
+ <Archive className="h-4 w-4" />
+ {t(($) => $.context_menu.archive)}
+ </>
+ )}
+ </ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenu>
+ );
+}
diff --git a/packages/views/inbox/components/inbox-list-item.tsx b/packages/views/inbox/components/inbox-list-item.tsx
index 97bc0e0541..9e0becb07b 100644
--- a/packages/views/inbox/components/inbox-list-item.tsx
+++ b/packages/views/inbox/components/inbox-list-item.tsx
@@ -10,6 +10,7 @@ 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 { useInboxContextMenu } from "./inbox-context-menu";
import { useT } from "../../i18n";
// Hook returning a localized relative-time formatter — the i18n equivalent
@@ -46,6 +47,7 @@ export function InboxListItem({
}) {
const { t } = useT("inbox");
const timeAgo = useTimeAgo();
+ const openContextMenu = useInboxContextMenu();
const displayTitle = getInboxDisplayTitle(item);
const isArchivedView = view === "archived";
// Archiving deliberately leaves `read` untouched so unarchiving restores the
@@ -62,8 +64,16 @@ export function InboxListItem({
<button
type="button"
onClick={onClick}
- className={`group flex w-full items-center gap-3 rounded-md px-2 py-2.5 text-left transition-colors ${
- isSelected ? "bg-accent" : "hover:bg-accent/50"
+ // Right-click opens the list's shared menu (mark read/unread, archive).
+ // `select-none` mirrors what Base UI's own trigger used to merge in, so
+ // right-clicking a row never starts a text selection.
+ onContextMenu={
+ openContextMenu ? (e) => openContextMenu(item, e) : undefined
+ }
+ className={`group flex w-full select-none items-center gap-3 rounded-md px-2 py-2.5 text-left transition-colors ${
+ isSelected
+ ? "bg-accent"
+ : "hover:bg-accent/50 data-[popup-open]:bg-accent/50"
}`}
>
<ActorAvatar
diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsx
index 6b79b50484..75410715c4 100644
--- a/packages/views/inbox/components/inbox-page.test.tsx
+++ b/packages/views/inbox/components/inbox-page.test.tsx
@@ -1,4 +1,4 @@
-import { fireEvent, render, screen } from "@testing-library/react";
+import { act, 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";
@@ -50,10 +50,16 @@ vi.mock("@multica/core/inbox/queries", () => ({
useInboxUnreadCount: () => 2,
}));
+// Stable spies: the auto-mark-read effect keys on the mutate identity, so a
+// fresh `vi.fn()` per render would make the effect's deps churn.
+const markReadMutate = vi.fn();
+const markUnreadMutate = vi.fn();
+
vi.mock("@multica/core/inbox/mutations", () => {
const mutation = () => ({ mutate: vi.fn() });
return {
- useMarkInboxRead: mutation,
+ useMarkInboxRead: () => ({ mutate: markReadMutate }),
+ useMarkInboxUnread: () => ({ mutate: markUnreadMutate }),
useArchiveInbox: mutation,
useUnarchiveInbox: mutation,
useMarkAllInboxRead: mutation,
@@ -75,7 +81,23 @@ vi.mock("../../navigation", () => ({
useNavigation: () => ({ searchParams, replace }),
}));
-vi.mock("@multica/ui/hooks/use-mobile", () => ({ useIsMobile: () => true }));
+// Mobile by default — it renders the list and the detail as one column, which
+// keeps most assertions simple. Tests about actioning a row WHILE it is open
+// need the two-panel desktop layout, since mobile swaps the list out for the
+// detail on selection.
+const layout = { isMobile: true };
+vi.mock("@multica/ui/hooks/use-mobile", () => ({
+ useIsMobile: () => layout.isMobile,
+}));
+vi.mock("@multica/ui/components/ui/resizable", () => ({
+ ResizablePanelGroup: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ ResizablePanel: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ ResizableHandle: () => null,
+}));
vi.mock("./inbox-list", () => ({
InboxList: ({
items,
@@ -96,6 +118,26 @@ vi.mock("./inbox-list", () => ({
),
}));
vi.mock("./inbox-list-item", () => ({ useTimeAgo: () => vi.fn() }));
+
+// Capture the row actions the page hands the context menu, so the read/unread
+// handlers can be driven without standing up Base UI's menu.
+let rowActions: {
+ onMarkRead: (id: string) => void;
+ onMarkUnread: (id: string) => void;
+ onAction: (id: string) => void;
+} | null = null;
+vi.mock("./inbox-context-menu", () => ({
+ InboxContextMenuProvider: ({
+ actions,
+ children,
+ }: {
+ actions: NonNullable<typeof rowActions>;
+ children: React.ReactNode;
+ }) => {
+ rowActions = actions;
+ return children;
+ },
+}));
vi.mock("./inbox-detail-label", () => ({ useTypeLabels: () => ({}) }));
vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "Inbox" }) }));
@@ -126,6 +168,10 @@ function reset() {
listData.archived = [];
searchParams = new URLSearchParams();
replace.mockClear();
+ markReadMutate.mockClear();
+ markUnreadMutate.mockClear();
+ rowActions = null;
+ layout.isMobile = true;
}
describe("InboxPage", () => {
@@ -215,6 +261,61 @@ describe("InboxPage", () => {
expect(replace).toHaveBeenCalledWith("/acme/inbox?issue=issue-3");
});
+ it("marks the opened notification read", () => {
+ reset();
+ listData.active = [
+ item({ id: "inbox-a", issue_id: "issue-a", read: false }),
+ ];
+
+ render(<InboxPage />);
+ fireEvent.click(screen.getByTestId("row"));
+
+ expect(markReadMutate).toHaveBeenCalledWith("inbox-a", expect.anything());
+ });
+
+ it("keeps an explicitly unread row unread while it stays open", () => {
+ // Without the guard the auto-read effect fires on the very next commit and
+ // silently undoes the user's "mark as unread" — the action looks like a
+ // no-op.
+ reset();
+ layout.isMobile = false;
+ listData.active = [
+ item({ id: "inbox-a", issue_id: "issue-a", read: false }),
+ ];
+
+ const { rerender } = render(<InboxPage />);
+ fireEvent.click(screen.getByTestId("row"));
+ markReadMutate.mockClear();
+
+ act(() => rowActions?.onMarkUnread("inbox-a"));
+ rerender(<InboxPage />);
+
+ expect(markUnreadMutate).toHaveBeenCalledWith("inbox-a", expect.anything());
+ expect(markReadMutate).not.toHaveBeenCalled();
+ });
+
+ it("marks a parked row read again once it is re-opened", () => {
+ // The guard is scoped to the row while it stays selected. Coming back to it
+ // later is a fresh open and must behave like any other.
+ reset();
+ layout.isMobile = false;
+ listData.active = [
+ item({ id: "inbox-a", issue_id: "issue-a", read: false }),
+ item({ id: "inbox-b", issue_id: "issue-b", read: false }),
+ ];
+
+ render(<InboxPage />);
+ const [rowA, rowB] = screen.getAllByTestId("row");
+ fireEvent.click(rowA!);
+ act(() => rowActions?.onMarkUnread("inbox-a"));
+
+ fireEvent.click(rowB!);
+ markReadMutate.mockClear();
+ fireEvent.click(rowA!);
+
+ expect(markReadMutate).toHaveBeenCalledWith("inbox-a", expect.anything());
+ });
+
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
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index 061a1a1a9f..1f0d047cde 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -16,6 +16,7 @@ import {
} from "@multica/core/inbox/queries";
import {
useMarkInboxRead,
+ useMarkInboxUnread,
useArchiveInbox,
useUnarchiveInbox,
useMarkAllInboxRead,
@@ -59,6 +60,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 { InboxContextMenuProvider } from "./inbox-context-menu";
import { ARCHIVED_VIEW_PARAM, type InboxView } from "./inbox-view";
import { useTypeLabels } from "./inbox-detail-label";
import { getInboxDisplayTitle, isQuickCreateOutcome } from "./inbox-display";
@@ -204,6 +206,7 @@ export function InboxPage() {
const unreadCount = useInboxUnreadCount(wsId);
const markReadMutation = useMarkInboxRead();
+ const markUnreadMutation = useMarkInboxUnread();
const archiveMutation = useArchiveInbox();
const unarchiveMutation = useUnarchiveInbox();
const markAllReadMutation = useMarkAllInboxRead();
@@ -214,6 +217,13 @@ export function InboxPage() {
const typeLabels = useTypeLabels();
+ // An explicit "mark as unread" on the row that is currently open has to
+ // survive the auto-read effect below, which would otherwise fire on the very
+ // next commit and silently undo it. Holds that one item's id, and only while
+ // it stays selected: moving the selection elsewhere releases the guard, so
+ // re-opening the row later marks it read again like any other open.
+ const manualUnreadIdRef = useRef<string | null>(null);
+
// Auto-mark-read whenever a selected item is unread — covers both click-
// to-select and URL-param-select (e.g. OS notification click on desktop).
// The mutation flips `read: true` optimistically, so this effect settles
@@ -224,6 +234,7 @@ export function InboxPage() {
const selectedRead = selected?.read;
useEffect(() => {
if (!selectedId || selectedRead) return;
+ if (manualUnreadIdRef.current === selectedId) return;
markReadMutate(selectedId, {
onError: (err) =>
toast.error(
@@ -234,10 +245,45 @@ export function InboxPage() {
});
}, [selectedId, selectedRead, markReadMutate, t]);
+ // Release the guard as soon as the selection moves off the parked row.
+ useEffect(() => {
+ if (manualUnreadIdRef.current && manualUnreadIdRef.current !== selectedId) {
+ manualUnreadIdRef.current = null;
+ }
+ }, [selectedId]);
+
const handleSelect = (item: InboxItem) => {
setSelectedKey(item.issue_id ?? item.id);
};
+ const handleMarkRead = (id: string) => {
+ // Reading it back explicitly cancels an earlier park on the same row.
+ if (manualUnreadIdRef.current === id) manualUnreadIdRef.current = null;
+ markReadMutation.mutate(id, {
+ onError: (err) =>
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.errors.mark_read_failed),
+ ),
+ });
+ };
+
+ const handleMarkUnread = (id: string) => {
+ // Only the open row needs the guard — the auto-read effect never touches
+ // the others, and arming it for a background row would suppress the very
+ // first open of that row later.
+ if (selected?.id === id) manualUnreadIdRef.current = id;
+ markUnreadMutation.mutate(id, {
+ onError: (err) =>
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.errors.mark_unread_failed),
+ ),
+ });
+ };
+
// 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
@@ -408,15 +454,24 @@ export function InboxPage() {
</div>
</div>
) : (
- <InboxList
- items={visibleItems}
+ <InboxContextMenuProvider
view={view}
- selectedKey={selectedKey}
- archivedCount={archivedItems.length}
- onSelect={handleSelect}
- onAction={isArchivedView ? handleUnarchive : handleArchive}
- onOpenArchived={openArchived}
- />
+ actions={{
+ onMarkRead: handleMarkRead,
+ onMarkUnread: handleMarkUnread,
+ onAction: isArchivedView ? handleUnarchive : handleArchive,
+ }}
+ >
+ <InboxList
+ items={visibleItems}
+ view={view}
+ selectedKey={selectedKey}
+ archivedCount={archivedItems.length}
+ onSelect={handleSelect}
+ onAction={isArchivedView ? handleUnarchive : handleArchive}
+ onOpenArchived={openArchived}
+ />
+ </InboxContextMenuProvider>
);
const listPanel = (
diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.json
index d5349b8498..0ebe6b3575 100644
--- a/packages/views/locales/en/inbox.json
+++ b/packages/views/locales/en/inbox.json
@@ -9,6 +9,12 @@
"archive_all_read": "Archive all read",
"archive_completed": "Archive completed"
},
+ "context_menu": {
+ "mark_read": "Mark as read",
+ "mark_unread": "Mark as unread",
+ "archive": "Archive",
+ "unarchive": "Unarchive"
+ },
"list": {
"empty": "No notifications",
"mark_done_tooltip": "Mark as done",
@@ -67,6 +73,7 @@
},
"errors": {
"mark_read_failed": "Failed to mark as read",
+ "mark_unread_failed": "Failed to mark as unread",
"archive_failed": "Failed to archive",
"mark_done_failed": "Failed to mark as done",
"mark_all_read_failed": "Failed to mark all as read",
diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.json
index 6a4d3c342f..9f92f58a70 100644
--- a/packages/views/locales/ja/inbox.json
+++ b/packages/views/locales/ja/inbox.json
@@ -9,6 +9,12 @@
"archive_all_read": "既読の項目をすべてアーカイブ",
"archive_completed": "完了した項目をアーカイブ"
},
+ "context_menu": {
+ "mark_read": "既読にする",
+ "mark_unread": "未読にする",
+ "archive": "アーカイブ",
+ "unarchive": "アーカイブ解除"
+ },
"list": {
"empty": "通知はありません",
"mark_done_tooltip": "完了にする",
@@ -67,6 +73,7 @@
},
"errors": {
"mark_read_failed": "既読にできませんでした",
+ "mark_unread_failed": "未読にできませんでした",
"archive_failed": "アーカイブできませんでした",
"mark_done_failed": "完了にできませんでした",
"mark_all_read_failed": "すべて既読にできませんでした",
diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.json
index a1eb3d1568..d240219ff7 100644
--- a/packages/views/locales/ko/inbox.json
+++ b/packages/views/locales/ko/inbox.json
@@ -9,6 +9,12 @@
"archive_all_read": "읽은 항목 모두 보관",
"archive_completed": "완료된 항목 보관"
},
+ "context_menu": {
+ "mark_read": "읽음으로 표시",
+ "mark_unread": "읽지 않음으로 표시",
+ "archive": "보관",
+ "unarchive": "보관 해제"
+ },
"list": {
"empty": "알림이 없습니다",
"mark_done_tooltip": "완료로 표시",
@@ -67,6 +73,7 @@
},
"errors": {
"mark_read_failed": "읽음 표시를 하지 못했습니다",
+ "mark_unread_failed": "읽지 않음 표시를 하지 못했습니다",
"archive_failed": "보관하지 못했습니다",
"mark_done_failed": "완료 표시를 하지 못했습니다",
"mark_all_read_failed": "모두 읽음으로 표시하지 못했습니다",
diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.json
index 29907d0cf5..e25b7a5168 100644
--- a/packages/views/locales/zh-Hans/inbox.json
+++ b/packages/views/locales/zh-Hans/inbox.json
@@ -9,6 +9,12 @@
"archive_all_read": "归档全部已读",
"archive_completed": "归档已完成"
},
+ "context_menu": {
+ "mark_read": "标为已读",
+ "mark_unread": "标为未读",
+ "archive": "归档",
+ "unarchive": "取消归档"
+ },
"list": {
"empty": "暂无通知",
"mark_done_tooltip": "标为已完成",
@@ -67,6 +73,7 @@
},
"errors": {
"mark_read_failed": "标为已读失败",
+ "mark_unread_failed": "标为未读失败",
"archive_failed": "归档失败",
"mark_done_failed": "标为已完成失败",
"mark_all_read_failed": "全部标为已读失败",
diff --git a/server/cmd/server/integration_test.go b/server/cmd/server/integration_test.go
index f4f9d0beb4..60c0901b76 100644
--- a/server/cmd/server/integration_test.go
+++ b/server/cmd/server/integration_test.go
@@ -1046,6 +1046,98 @@ func TestUnarchiveInboxPreservesUnread(t *testing.T) {
// 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.
+// Mark-unread is the inverse of mark-read and, like it, scoped to the single
+// item: the inbox renders one row per issue carrying that group's NEWEST item,
+// so flipping the whole group would resurrect siblings the user already dealt
+// with. The restored item counts toward the unread badge again.
+func TestMarkInboxUnreadIsItemScoped(t *testing.T) {
+ ctx := context.Background()
+ issueID := seedArchivedFixtureIssue(t, "Mark unread fixture")
+
+ var newestID 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', 'newest', $3, true, false, now())
+ RETURNING id
+ `, testWorkspaceID, testUserID, issueID).Scan(&newestID); err != nil {
+ t.Fatalf("failed to seed inbox item: %v", err)
+ }
+ // An older sibling on the same issue, already read. It must stay read.
+ 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', 'older sibling', $3, true, false, 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/"+newestID+"/unread", nil)
+ if resp.StatusCode != 200 {
+ t.Fatalf("MarkInboxUnread: expected 200, got %d", resp.StatusCode)
+ }
+ var updated inboxItemJSON
+ readJSON(t, resp, &updated)
+ if updated.Read {
+ t.Fatalf("expected the item to come back unread, got %+v", updated)
+ }
+ if updated.Archived {
+ t.Fatalf("mark unread must not archive the item, got %+v", updated)
+ }
+
+ rows, err := testPool.Query(ctx, `
+ SELECT title, read 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]bool{}
+ for rows.Next() {
+ var title string
+ var read bool
+ if err := rows.Scan(&title, &read); err != nil {
+ t.Fatalf("scan: %v", err)
+ }
+ got[title] = read
+ }
+ if got["newest"] {
+ t.Fatal("the targeted item must be unread")
+ }
+ if !got["older sibling"] {
+ t.Fatal("mark unread must not touch older siblings on the same issue")
+ }
+}
+
+// The read/unread endpoints resolve the item within the caller's workspace and
+// recipient scope, so someone else's notification is not addressable.
+func TestMarkInboxUnreadRejectsForeignItem(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, read)
+ 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+"/unread", nil)
+ if resp.StatusCode == 200 {
+ t.Fatal("expected mark-unread of another recipient's item to be rejected")
+ }
+
+ var read bool
+ if err := testPool.QueryRow(ctx,
+ `SELECT read FROM inbox_item WHERE id = $1`, foreignItemID).Scan(&read); err != nil {
+ t.Fatalf("failed to read back foreign item: %v", err)
+ }
+ if !read {
+ t.Fatal("another recipient's item must stay read")
+ }
+}
+
func TestUnarchiveInboxRejectsForeignItem(t *testing.T) {
ctx := context.Background()
var foreignItemID string
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 773a3d241f..8408b22a83 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1461,6 +1461,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/archive-all-read", h.ArchiveAllReadInbox)
r.Post("/archive-completed", h.ArchiveCompletedInbox)
r.Post("/{id}/read", h.MarkInboxRead)
+ r.Post("/{id}/unread", h.MarkInboxUnread)
r.Post("/{id}/archive", h.ArchiveInboxItem)
r.Post("/{id}/unarchive", h.UnarchiveInboxItem)
})
diff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.go
index a7b488b58b..ad1147d303 100644
--- a/server/internal/handler/inbox.go
+++ b/server/internal/handler/inbox.go
@@ -182,6 +182,35 @@ func (h *Handler) MarkInboxRead(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
+// MarkInboxUnread flips a notification back to unread, the inverse of
+// MarkInboxRead. It exists so a user can park something they opened but did not
+// act on: the inbox auto-marks an item read the moment it is selected, which
+// otherwise makes "opened" and "handled" the same signal.
+//
+// Scope is the single item, matching MarkInboxRead — see the query comment.
+func (h *Handler) MarkInboxUnread(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.MarkInboxUnread(r.Context(), prev.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to mark unread")
+ return
+ }
+
+ userID := requestUserID(r)
+ workspaceID := uuidToString(item.WorkspaceID)
+ h.publish(protocol.EventInboxUnread, workspaceID, "member", userID, map[string]any{
+ "item_id": uuidToString(item.ID),
+ "recipient_id": uuidToString(item.RecipientID),
+ })
+
+ resp := h.enrichInboxResponse(r.Context(), inboxToResponse(item), item.IssueID)
+ writeJSON(w, http.StatusOK, resp)
+}
+
func (h *Handler) ArchiveInboxItem(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
prev, ok := h.loadInboxItemForUser(w, r, id)
diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.go
index afa1c130cc..453bc180be 100644
--- a/server/pkg/db/generated/inbox.sql.go
+++ b/server/pkg/db/generated/inbox.sql.go
@@ -559,6 +559,41 @@ func (q *Queries) MarkInboxRead(ctx context.Context, id pgtype.UUID) (InboxItem,
return i, err
}
+const markInboxUnread = `-- name: MarkInboxUnread :one
+UPDATE inbox_item SET read = 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
+`
+
+// Exact inverse of MarkInboxRead, and item-level for the same reason it is:
+// the inbox renders one row per issue carrying that group's NEWEST item, and
+// the group's read state is that item's read state. Flipping the whole group
+// unread would resurrect older siblings the user already dealt with and
+// inflate CountUnreadInbox (which counts raw rows), while changing nothing the
+// UI shows.
+func (q *Queries) MarkInboxUnread(ctx context.Context, id pgtype.UUID) (InboxItem, error) {
+ row := q.db.QueryRow(ctx, markInboxUnread, 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
+}
+
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
diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sql
index 2d4064a5bf..79063b5d49 100644
--- a/server/pkg/db/queries/inbox.sql
+++ b/server/pkg/db/queries/inbox.sql
@@ -60,6 +60,17 @@ UPDATE inbox_item SET read = true
WHERE id = $1
RETURNING *;
+-- name: MarkInboxUnread :one
+-- Exact inverse of MarkInboxRead, and item-level for the same reason it is:
+-- the inbox renders one row per issue carrying that group's NEWEST item, and
+-- the group's read state is that item's read state. Flipping the whole group
+-- unread would resurrect older siblings the user already dealt with and
+-- inflate CountUnreadInbox (which counts raw rows), while changing nothing the
+-- UI shows.
+UPDATE inbox_item SET read = false
+WHERE id = $1
+RETURNING *;
+
-- name: ArchiveInboxItem :one
UPDATE inbox_item SET archived = true
WHERE id = $1
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index ef7e598aa0..2d1ca386c9 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -43,6 +43,7 @@ const (
// Inbox events
EventInboxNew = "inbox:new"
EventInboxRead = "inbox:read"
+ EventInboxUnread = "inbox:unread"
EventInboxArchived = "inbox:archived"
EventInboxUnarchived = "inbox:unarchived"
EventInboxBatchRead = "inbox:batch-read"