Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8588 feat(inbox): read an issue's notifications when it is opened outside the inbox (#9921)
Bohan Jiange9bb73a22e3f
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 917a8fe595..71efde625e 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -418,6 +418,7 @@ import {IssueUnreadPageSchema,EMPTY_ISSUE_UNREAD_PAGE,SubscribedIssueIdsSchema,+ IssueInboxReadSchema,InboxItemListSchema,ArchivedInboxPageSchema,ArchivedInboxFacetsSchema,@@ -3064,6 +3065,19 @@ export class ApiClient {return this.fetch("/api/inbox/mark-all-read", { method: "POST" });}+ /**+ * Reads every unread notification the caller has on one issue. `count` is+ * how many rows the server read, or `null` when the response did not say:+ * the write itself succeeded, so callers must not read `null` as "nothing+ * changed".+ */+ async markIssueInboxRead(issueId: string): Promise<{ count: number | null }> {+ const raw = await this.fetch<unknown>(`/api/inbox/issues/${issueId}/read`, { method: "POST" });+ return parseWithFallback<{ count: number | null }>(raw, IssueInboxReadSchema, { count: null }, {+ endpoint: "POST /api/inbox/issues/{id}/read",+ });+ }+async archiveAllInbox(): Promise<{ count: number }> {return this.fetch("/api/inbox/archive-all", { method: "POST" });}diff --git a/packages/core/api/issue-inbox-read.test.ts b/packages/core/api/issue-inbox-read.test.tsnew file mode 100644index 0000000000..b8aea18ff5--- /dev/null+++ b/packages/core/api/issue-inbox-read.test.ts@@ -0,0 +1,38 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from "vitest";+import { ApiClient } from "./client";++afterEach(() => vi.unstubAllGlobals());++const read = (body: unknown) => {+ const fetch = vi.fn().mockResolvedValue(Response.json(body));+ vi.stubGlobal("fetch", fetch);+ return { fetch, result: new ApiClient("https://api.example.test").markIssueInboxRead("issue-1") };+};++describe("markIssueInboxRead", () => {+ it("posts to the issue's inbox read route and returns the count", async () => {+ const { fetch, result } = read({ count: 2, extra: true });++ await expect(result).resolves.toEqual({ count: 2, extra: true });+ const [url, init] = fetch.mock.calls[0]!;+ expect(new URL(url).pathname).toBe("/api/inbox/issues/issue-1/read");+ expect(init?.method).toBe("POST");+ });++ it("returns a zero count as zero", async () => {+ await expect(read({ count: 0 }).result).resolves.toEqual({ count: 0 });+ });++ // The write succeeded but the body cannot say whether rows changed. `null`+ // makes the caller refresh rather than read it as "nothing changed".+ it.each([+ ["a missing count", {}],+ ["a string count", { count: "2" }],+ ["a negative count", { count: -1 }],+ ["a fractional count", { count: 1.5 }],+ ["a null body", null],+ ])("reports an unknown count for %s", async (_name, body) => {+ await expect(read(body).result).resolves.toEqual({ count: null });+ });+});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex d0aced8f2e..05ff2bde3e 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2794,6 +2794,16 @@ export const EMPTY_ISSUE_UNREAD_PAGE: { items: IssueUnread[]; next_cursor: strinnext_cursor: null,};+// Reading one issue's notifications (`/api/inbox/issues/{id}/read` POST).+// `count` is how many rows the write read; the client refreshes its inbox+// caches only when it is above zero. A body without a usable count cannot say+// that nothing changed, so the client treats it as unknown and refreshes.+export const IssueInboxReadSchema = z+ .object({+ count: z.number().int().nonnegative(),+ })+ .loose();+// The viewer's subscribed issue ids (`/api/issues/subscribed` GET), behind the// "subscribed" relation filter on client-filtered surfaces. A non-string entry// is dropped; a body without the list has no safe fallback — an empty setdiff --git a/packages/core/inbox/mutations.test.tsx b/packages/core/inbox/mutations.test.tsxindex 493d5fe7d2..43b075673c 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, InboxWorkspaceUnread } from "../types";-import { useMarkInboxRead, useMarkInboxUnread, useUnarchiveInbox } from "./mutations";+import { useMarkInboxRead, useMarkInboxUnread, useMarkIssueInboxRead, useUnarchiveInbox } from "./mutations";import { inboxKeys, useInboxUnreadCount } from "./queries";import { onInboxSummaryInvalidate } from "./ws-updaters";import { createQueryClient } from "../query-client";@@ -140,6 +140,67 @@ describe("useMarkInboxUnread", () => {});});+describe("useMarkIssueInboxRead", () => {+ let queryClient: QueryClient;++ beforeEach(() => {+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ });++ it("refreshes the inbox caches when the server read rows", async () => {+ const markIssueInboxRead = vi.fn(async () => ({ count: 2 }));+ setApiInstance({ markIssueInboxRead } as unknown as ApiClient);+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");++ const { result } = renderHook(() => useMarkIssueInboxRead(WORKSPACE_ID), {+ wrapper: createWrapper(queryClient),+ });+ result.current.mutate("issue-1");++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(markIssueInboxRead).toHaveBeenCalledWith("issue-1");+ await waitFor(() =>+ expect(invalidate).toHaveBeenCalledWith({ queryKey: inboxKeys.unreadSummary() }),+ );+ expect(invalidate).toHaveBeenCalledWith({ queryKey: inboxKeys.all(WORKSPACE_ID) });+ });++ it("refreshes when the response did not say how many rows changed", async () => {+ setApiInstance({+ markIssueInboxRead: vi.fn(async () => ({ count: null })),+ } as unknown as ApiClient);+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");++ const { result } = renderHook(() => useMarkIssueInboxRead(WORKSPACE_ID), {+ wrapper: createWrapper(queryClient),+ });+ result.current.mutate("issue-1");++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ await waitFor(() =>+ expect(invalidate).toHaveBeenCalledWith({ queryKey: inboxKeys.unreadSummary() }),+ );+ });++ it("leaves the caches alone when the issue had nothing unread", async () => {+ setApiInstance({+ markIssueInboxRead: vi.fn(async () => ({ count: 0 })),+ } as unknown as ApiClient);+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");++ const { result } = renderHook(() => useMarkIssueInboxRead(WORKSPACE_ID), {+ wrapper: createWrapper(queryClient),+ });+ result.current.mutate("issue-1");++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ await act(() => new Promise((resolve) => setTimeout(resolve, 20)));+ expect(invalidate).not.toHaveBeenCalled();+ });+});+describe("useUnarchiveInbox", () => {let queryClient: QueryClient;let unarchiveInbox: ReturnType<typeof vi.fn>;diff --git a/packages/core/inbox/mutations.ts b/packages/core/inbox/mutations.tsindex b4becc22f7..e48a94ea8a 100644--- a/packages/core/inbox/mutations.ts+++ b/packages/core/inbox/mutations.ts@@ -47,6 +47,27 @@ export function useMarkInboxRead() {});}+/**+ * Read every unread notification on one issue: what viewing the issue outside+ * the inbox does (MUL-8588). The caller passes the workspace id it already+ * holds.+ *+ * Not optimistic. Outside the inbox the list is usually not loaded, and only+ * the server knows which of the issue's rows are unread. The caches refresh+ * unless the server reports that no row changed, so opening an issue with+ * nothing unread costs no inbox refetch. A response without a count is treated+ * as a change: skipping the refresh then could leave the badge stale.+ */+export function useMarkIssueInboxRead(wsId: string) {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (issueId: string) => api.markIssueInboxRead(issueId),+ onSuccess: (result) => {+ if (result.count !== 0) refreshInboxAfterWrite(qc, wsId);+ },+ });+}+export function useRetrySourceContextQuickCreate() {const qc = useQueryClient();const wsId = useWorkspaceId();diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex bc44fb0974..b05e45cb41 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -249,6 +249,9 @@ export interface IssueUnreadChangedPayload {export interface InboxBatchReadPayload {recipient_id: string;count: number;+ /** Set when the batch is one issue's notifications, read by viewing the+ * issue outside the inbox. Absent for "mark all as read". */+ issue_id?: string;}export interface InboxBatchArchivedPayload {diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsxindex df17732dc1..e1b3c4c754 100644--- a/packages/views/inbox/components/inbox-page.test.tsx+++ b/packages/views/inbox/components/inbox-page.test.tsx@@ -636,6 +636,19 @@ describe("InboxPage", () => {expect(issueDetailProps.at(-1)?.highlightRequestToken).toBe(1);});+ it("keeps its own detail pane from reading the inbox, so a row marked unread stays unread", () => {+ // The detail reads an issue's notifications when it is opened anywhere+ // else (MUL-8588). Here the page reads the row it selected itself, and a+ // row the reader marks unread while it is open must not be read again.+ reset();+ layout.width = DESKTOP;+ listData.active = [item()];++ render(<InboxPage />);+ fireEvent.click(screen.getByTestId("row"));+ expect(issueDetailProps.at(-1)).toMatchObject({ readsInbox: false });+ });+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.diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex 85b0baca6f..425b6334a7 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -838,6 +838,9 @@ export function InboxPage() {layoutId="multica_inbox_issue_detail_layout"highlightCommentId={detailItem.details?.comment_id ?? undefined}highlightRequestToken={highlightRequestToken}+ // The inbox reads the row it selected itself (see the auto-read+ // effect above), and must keep a row marked unread while it is open.+ readsInbox={false}// The split layout already has a nav trigger in the list header.// Explicit false suppresses the detail header's fallback trigger,// which is the way back once the list column is collapsed.diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex dbf2a1f316..45694b76ed 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -166,6 +166,7 @@ import { useIssueTimeline } from "../hooks/use-issue-timeline";import { useIssueReactions } from "../hooks/use-issue-reactions";import { useIssueSubscribers } from "../hooks/use-issue-subscribers";import { useMarkIssueReadWhileViewing } from "../hooks/use-mark-issue-read-while-viewing";+import { useMarkIssueInboxReadWhileViewing } from "../hooks/use-mark-issue-inbox-read-while-viewing";import { ReactionBar } from "@multica/ui/components/common/reaction-bar";import { useLocale, useTimeAgo } from "../../i18n";import {@@ -1187,6 +1188,12 @@ interface IssueDetailProps {variant?: "page" | "peek";/** Peek only: host controls at the end of the header (open full page, close). */trailingActions?: ReactNode;+ /**+ * Read the viewer's inbox notifications on this issue while it is on screen+ * (MUL-8588). The inbox turns this off for the issue it has open: it reads+ * the notification it selected itself, and keeps one marked unread there.+ */+ readsInbox?: boolean;}// Not found@@ -1319,7 +1326,7 @@ export function IssueDetailSkeleton({// IssueDetail-export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = "multica_issue_detail_layout", highlightCommentId, highlightRequestToken, leadingAction, variant = "page", trailingActions }: IssueDetailProps) {+export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = true, layoutId = "multica_issue_detail_layout", highlightCommentId, highlightRequestToken, leadingAction, variant = "page", trailingActions, readsInbox = true }: IssueDetailProps) {const isPeek = variant === "peek";const { t } = useT("issues");const { t: tCommon } = useT("common");@@ -1560,6 +1567,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr},});useMarkIssueReadWhileViewing(wsId, issue?.id ?? "");+ useMarkIssueInboxReadWhileViewing(wsId, issue?.id ?? "", readsInbox);const descriptionSourceId = `description:${id}`;const descriptionAnnotations = useCommentAnnotations({draftKey: `new:${id}`,diff --git a/packages/views/issues/hooks/use-mark-issue-inbox-read-while-viewing.test.tsx b/packages/views/issues/hooks/use-mark-issue-inbox-read-while-viewing.test.tsxnew file mode 100644index 0000000000..1ce15e84d5--- /dev/null+++ b/packages/views/issues/hooks/use-mark-issue-inbox-read-while-viewing.test.tsx@@ -0,0 +1,205 @@+import { act, renderHook } from "@testing-library/react";+import { QueryClientProvider } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createQueryClient } from "@multica/core/query-client";+import { api } from "@multica/core/api";+import { inboxKeys } from "@multica/core/inbox";+import type { InboxItem, InboxWorkspaceUnread } from "@multica/core/types";+import { useMarkIssueInboxReadWhileViewing } from "./use-mark-issue-inbox-read-while-viewing";++vi.mock("@multica/core/api", () => ({+ api: { markIssueInboxRead: vi.fn(), getInboxUnreadSummary: vi.fn() },+}));++const foreground = vi.hoisted(() => ({ value: true }));+vi.mock("../../common/use-app-foreground", () => ({ useAppForeground: () => foreground.value }));++const wsHandlers = vi.hoisted(() => new Map<string, (payload: unknown) => void>());+const reconnectHandlers = vi.hoisted(() => ({ current: null as (() => void) | null }));+vi.mock("@multica/core/realtime", () => ({+ useWSEvent: (event: string, handler: (payload: unknown) => void) => {+ wsHandlers.set(event, handler);+ },+ useWSReconnect: (callback: () => void) => {+ reconnectHandlers.current = callback;+ },+}));++function notification(issueId: string | null): { item: Partial<InboxItem> } {+ return { item: { id: `inbox-${Math.random()}`, issue_id: issueId, read: false } };+}++function deliver(payload: unknown) {+ act(() => wsHandlers.get("inbox:new")?.(payload));+}++function reconnect() {+ act(() => reconnectHandlers.current?.());+}++const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 20)));++let client: ReturnType<typeof createQueryClient>;+const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+);++function setUnreadSummary(count: number) {+ client.setQueryData<InboxWorkspaceUnread[]>(+ inboxKeys.unreadSummary(),+ count > 0 ? [{ workspace_id: "ws-1", count }] : [],+ );+}++beforeEach(() => {+ client = createQueryClient();+ foreground.value = true;+ wsHandlers.clear();+ reconnectHandlers.current = null;+ vi.mocked(api.markIssueInboxRead).mockResolvedValue({ count: 1 });+ vi.mocked(api.getInboxUnreadSummary).mockResolvedValue([]);+});++afterEach(() => {+ client.clear();+ vi.resetAllMocks();+});++describe("useMarkIssueInboxReadWhileViewing", () => {+ it("reads the issue's notifications once when it opens", async () => {+ setUnreadSummary(3);++ const { rerender } = renderHook(() => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ await settle();+ rerender();+ await settle();++ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);+ expect(api.markIssueInboxRead).toHaveBeenCalledWith("issue-1");+ });++ it("sends nothing while the workspace has no unread notifications", async () => {+ setUnreadSummary(0);++ renderHook(() => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ await settle();++ expect(api.markIssueInboxRead).not.toHaveBeenCalled();+ });++ it("reads a notification on the open issue as it arrives, and ignores other issues", async () => {+ setUnreadSummary(1);++ renderHook(() => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ await settle();+ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);+ // The write read the only unread issue; its refresh brings the count to 0.+ act(() => setUnreadSummary(0));++ // Realtime sync refreshes the summary on every inbox:new; mirror that.+ // The count rising for another issue is not a reason to write again.+ deliver(notification("issue-2"));+ deliver(notification(null));+ act(() => setUnreadSummary(2));+ await settle();+ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);++ deliver(notification("issue-1"));+ act(() => setUnreadSummary(3));+ await settle();+ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(2);+ });++ it("holds an arrival until the unread count reflects it", async () => {+ setUnreadSummary(1);++ renderHook(() => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ await settle();+ act(() => setUnreadSummary(0));++ deliver(notification("issue-1"));+ await settle();+ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);++ act(() => setUnreadSummary(1));+ await settle();+ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(2);+ });++ it("waits for the app to come to the foreground", async () => {+ setUnreadSummary(1);+ foreground.value = false;++ const { rerender } = renderHook(() => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ deliver(notification("issue-1"));+ await settle();+ expect(api.markIssueInboxRead).not.toHaveBeenCalled();++ foreground.value = true;+ rerender();+ await settle();+ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);+ });++ it("reads again after a reconnect, once the refreshed count shows unread", async () => {+ // An inbox:new sent while the socket was down is never replayed. Realtime+ // sync refetches the unread summary on reconnect; the write follows it.+ setUnreadSummary(1);++ renderHook(() => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ await settle();+ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);+ act(() => setUnreadSummary(0));++ reconnect();+ await settle();+ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);++ act(() => setUnreadSummary(1));+ await settle();+ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(2);+ });++ it("reads after a reconnect that happened in the background, once the app is in front", async () => {+ setUnreadSummary(1);++ const { rerender } = renderHook(() => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ await settle();+ act(() => setUnreadSummary(0));++ foreground.value = false;+ rerender();+ reconnect();+ act(() => setUnreadSummary(1));+ await settle();+ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);++ foreground.value = true;+ rerender();+ await settle();+ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(2);+ });++ it("does nothing where the host reads the inbox itself", async () => {+ setUnreadSummary(1);++ renderHook(() => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1", false), { wrapper });+ deliver(notification("issue-1"));+ await settle();++ expect(api.markIssueInboxRead).not.toHaveBeenCalled();+ });++ it("does not resubmit after a failed write", async () => {+ setUnreadSummary(1);+ vi.mocked(api.markIssueInboxRead).mockRejectedValue(Object.assign(new Error("not found"), { status: 404 }));++ const { rerender } = renderHook(() => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ await settle();+ rerender();+ await settle();++ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/views/issues/hooks/use-mark-issue-inbox-read-while-viewing.ts b/packages/views/issues/hooks/use-mark-issue-inbox-read-while-viewing.tsnew file mode 100644index 0000000000..6d8ef61e0d--- /dev/null+++ b/packages/views/issues/hooks/use-mark-issue-inbox-read-while-viewing.ts@@ -0,0 +1,54 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { useInboxUnreadCount, useMarkIssueInboxRead } from "@multica/core/inbox";+import { useWSEvent, useWSReconnect } from "@multica/core/realtime";+import type { InboxNewPayload } from "@multica/core/types";+import { useAppForeground } from "../../common/use-app-foreground";++/**+ * Reads the viewer's inbox notifications on an issue while it is on screen+ * outside the inbox: when it is opened, when a notification on it arrives+ * while it stays open, and after the socket reconnects (an `inbox:new` sent+ * while it was down is never replayed). The inbox already clears an issue's+ * Unread mark when it opens the issue, so with this, reading an issue in+ * either place reads it in both (MUL-8588). Nothing is read while the app is+ * in the background.+ *+ * The inbox passes `enabled: false` for the issue it has open. It reads the+ * row it selected itself, and keeps a row the reader marked unread there.+ *+ * Nothing is sent while the workspace has no unread notifications, so opening+ * issues at inbox zero costs no request. Each opening, arrival and reconnect+ * is written at most once: a failed write is not retried here, and the next+ * one of those tries again.+ */+export function useMarkIssueInboxReadWhileViewing(wsId: string, issueId: string, enabled = true) {+ const foreground = useAppForeground();+ const hasUnreadInbox = useInboxUnreadCount(wsId) > 0;+ const { mutate: markRead } = useMarkIssueInboxRead(wsId);+ // Bumped by every reason to read again since the issue opened. The unread+ // summary alone cannot tell which issue a new notification is for.+ const [generation, setGeneration] = useState(0);+ const written = useRef<string | null>(null);++ const onInboxNew = useCallback(+ (payload: unknown) => {+ const item = (payload as Partial<InboxNewPayload> | null)?.item;+ if (issueId && item?.issue_id === issueId && !item.read) setGeneration((n) => n + 1);+ },+ [issueId],+ );+ useWSEvent("inbox:new", onInboxNew);++ // Realtime sync refetches the unread summary on reconnect, so a missed+ // notification raises it and the write below waits for that.+ const onReconnect = useCallback(() => setGeneration((n) => n + 1), []);+ useWSReconnect(onReconnect);++ useEffect(() => {+ if (!enabled || !issueId || !foreground || !hasUnreadInbox) return;+ const key = `${issueId}|${generation}`;+ if (written.current === key) return;+ written.current = key;+ markRead(issueId);+ }, [enabled, issueId, foreground, hasUnreadInbox, generation, markRead]);+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 572bb11877..745df92b88 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2571,6 +2571,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/archive-all", h.ArchiveAllInbox)r.Post("/archive-all-read", h.ArchiveAllReadInbox)r.Post("/archive-completed", h.ArchiveCompletedInbox)+ // Every unread notification on one issue, for reading the issue+ // outside the inbox (MUL-8588).+ r.Post("/issues/{issueId}/read", h.MarkIssueInboxRead)r.Post("/{id}/read", h.MarkInboxRead)r.Post("/{id}/unread", h.MarkInboxUnread)r.Post("/{id}/archive", h.ArchiveInboxItem)diff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.goindex 15b0c756c9..ce0945df1c 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -437,6 +437,49 @@ func (h *Handler) MarkAllInboxRead(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, map[string]any{"count": count})}+// MarkIssueInboxRead marks the caller's unread notifications on one issue+// read. The client calls it while the issue is on screen outside the inbox, so+// reading an issue anywhere also reads it in the inbox (MUL-8588). The update+// is scoped to the caller's own rows, so an issue id from another workspace+// matches nothing.+func (h *Handler) MarkIssueInboxRead(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+ }+ issueUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "issueId"), "issue id")+ if !ok {+ return+ }++ count, err := h.Queries.MarkInboxReadByIssue(r.Context(), db.MarkInboxReadByIssueParams{+ WorkspaceID: wsUUID,+ RecipientID: parseUUID(userID),+ IssueID: issueUUID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to mark issue inbox read")+ return+ }++ // Opening an issue with nothing unread is the common case. It changes no+ // row, so it must not make every open client refetch its inbox.+ if count > 0 {+ h.publish(protocol.EventInboxBatchRead, workspaceID, "member", userID, map[string]any{+ "recipient_id": userID,+ "count": count,+ "issue_id": uuidToString(issueUUID),+ })+ }++ writeJSON(w, http.StatusOK, map[string]any{"count": count})+}+func (h *Handler) ArchiveAllInbox(w http.ResponseWriter, r *http.Request) {userID, ok := requireUserID(w, r)if !ok {diff --git a/server/internal/handler/inbox_issue_read_test.go b/server/internal/handler/inbox_issue_read_test.gonew file mode 100644index 0000000000..104972cfd6--- /dev/null+++ b/server/internal/handler/inbox_issue_read_test.go@@ -0,0 +1,118 @@+package handler++import (+ "net/http"+ "testing"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestMarkIssueInboxReadReadsOnlyTheCallersActiveRowsOnThatIssue(t *testing.T) {+ workspaceID := dbfx.Workspace(t, "Issue inbox read", "issue-inbox-read-"+uuid.NewString())+ dbfx.Member(t, workspaceID, testUserID, "owner")+ viewedIssueID := dbfx.Issue(t, "Viewed issue", testutil.Cols{"workspace_id": workspaceID})+ otherIssueID := dbfx.Issue(t, "Other issue", testutil.Cols{"workspace_id": workspaceID})+ otherRecipientID := uuid.NewString()+ dbfx.Cleanup(t, `DELETE FROM inbox_item WHERE workspace_id = $1`, workspaceID)++ insert := func(issueID, recipientID, title string, archived bool) {+ t.Helper()+ dbfx.Insert(t, "inbox_item", testutil.Cols{+ "workspace_id": workspaceID,+ "recipient_type": "member",+ "recipient_id": recipientID,+ "type": "new_comment",+ "severity": "info",+ "issue_id": issueID,+ "title": title,+ "read": false,+ "archived": archived,+ })+ }+ insert(viewedIssueID, testUserID, "older", false)+ insert(viewedIssueID, testUserID, "newest", false)+ insert(viewedIssueID, testUserID, "archived", true)+ insert(viewedIssueID, otherRecipientID, "someone else's", false)+ insert(otherIssueID, testUserID, "another issue", false)++ // Bus handlers are never unsubscribed in this suite, so keep only this+ // issue's events. Publish is synchronous: the channel is final on return.+ published := make(chan map[string]any, 4)+ testHandler.Bus.Subscribe(protocol.EventInboxBatchRead, func(e events.Event) {+ payload, ok := e.Payload.(map[string]any)+ if !ok || payload["issue_id"] != viewedIssueID {+ return+ }+ select {+ case published <- payload:+ default:+ }+ })++ call := func() int64 {+ t.Helper()+ var resp struct {+ Count int64 `json:"count"`+ }+ testutil.Call(t, inboxWorkspaceHandler(testHandler.MarkIssueInboxRead),+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/issues/"+viewedIssueID+"/read", workspaceID), "issueId", viewedIssueID)).+ Want(http.StatusOK).+ JSON(&resp)+ return resp.Count+ }++ if got := call(); got != 2 {+ t.Fatalf("count = %d, want the caller's two active rows on the issue", got)+ }+ if got := dbfx.Count(t,+ "SELECT count(*) FROM inbox_item WHERE issue_id = $1 AND recipient_id = $2 AND archived = false AND read = false",+ viewedIssueID, testUserID); got != 0 {+ t.Fatalf("caller's unread active rows on the issue = %d, want 0", got)+ }+ if got := dbfx.Count(t,+ "SELECT count(*) FROM inbox_item WHERE issue_id = $1 AND recipient_id = $2 AND archived = true AND read = false",+ viewedIssueID, testUserID); got != 1 {+ t.Fatalf("caller's unread archived rows = %d, want the archived row untouched", got)+ }+ if got := dbfx.Count(t,+ "SELECT count(*) FROM inbox_item WHERE issue_id = $1 AND recipient_id = $2 AND read = false",+ viewedIssueID, otherRecipientID); got != 1 {+ t.Fatalf("another recipient's unread rows = %d, want 1", got)+ }+ if got := dbfx.Count(t,+ "SELECT count(*) FROM inbox_item WHERE issue_id = $1 AND read = false", otherIssueID); got != 1 {+ t.Fatalf("unread rows on another issue = %d, want 1", got)+ }++ select {+ case payload := <-published:+ if payload["recipient_id"] != testUserID || payload["count"] != int64(2) {+ t.Fatalf("inbox:batch-read payload = %+v, want the caller and count 2", payload)+ }+ default:+ t.Fatal("a write that read rows published no inbox:batch-read")+ }++ // Reopening an issue with nothing unread is the common case: no rows and+ // no event, so other clients do not refetch their inbox.+ if got := call(); got != 0 {+ t.Fatalf("second count = %d, want 0", got)+ }+ select {+ case payload := <-published:+ t.Fatalf("a no-op write published inbox:batch-read: %+v", payload)+ default:+ }+}++func TestMarkIssueInboxReadRejectsInvalidIssueID(t *testing.T) {+ workspaceID := dbfx.Workspace(t, "Issue inbox read invalid", "issue-inbox-read-invalid-"+uuid.NewString())+ dbfx.Member(t, workspaceID, testUserID, "owner")++ testutil.Call(t, inboxWorkspaceHandler(testHandler.MarkIssueInboxRead),+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/issues/nope/read", workspaceID), "issueId", "nope")).+ Want(http.StatusBadRequest)+}diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.goindex 9457f6939f..68a4cbacdb 100644--- a/server/pkg/db/generated/inbox.sql.go+++ b/server/pkg/db/generated/inbox.sql.go@@ -654,6 +654,33 @@ func (q *Queries) MarkInboxRead(ctx context.Context, id pgtype.UUID) (InboxItem,return i, err}+const markInboxReadByIssue = `-- name: MarkInboxReadByIssue :execrows+UPDATE inbox_item SET read = true+WHERE workspace_id = $1 AND recipient_type = 'member' AND recipient_id = $2+ AND issue_id = $3 AND archived = false AND read = false+`++type MarkInboxReadByIssueParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ IssueID pgtype.UUID `json:"issue_id"`+}++// Reading an issue outside the inbox (its page, a side peek, the Unread view)+// reads its notifications too, so the inbox does not ask about the same issue+// again (MUL-8588). Every unread row in the issue's group, not just the newest:+// the group the inbox renders is read once its newest row is, and older unread+// siblings would otherwise stay in CountUnreadInbox. Archived rows are left as+// they are, as in MarkAllInboxRead, which also keeps the lookup on the partial+// index idx_inbox_active_by_issue.+func (q *Queries) MarkInboxReadByIssue(ctx context.Context, arg MarkInboxReadByIssueParams) (int64, error) {+ result, err := q.db.Exec(ctx, markInboxReadByIssue, arg.WorkspaceID, arg.RecipientID, arg.IssueID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const markInboxUnread = `-- name: MarkInboxUnread :oneUPDATE inbox_item SET read = falseWHERE id = $1diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sqlindex b5996db636..479c17f38f 100644--- a/server/pkg/db/queries/inbox.sql+++ b/server/pkg/db/queries/inbox.sql@@ -183,6 +183,18 @@ GROUP BY newest.workspace_id;UPDATE inbox_item SET read = trueWHERE workspace_id = $1 AND recipient_type = 'member' AND recipient_id = $2 AND archived = false AND read = false;+-- name: MarkInboxReadByIssue :execrows+-- Reading an issue outside the inbox (its page, a side peek, the Unread view)+-- reads its notifications too, so the inbox does not ask about the same issue+-- again (MUL-8588). Every unread row in the issue's group, not just the newest:+-- the group the inbox renders is read once its newest row is, and older unread+-- siblings would otherwise stay in CountUnreadInbox. Archived rows are left as+-- they are, as in MarkAllInboxRead, which also keeps the lookup on the partial+-- index idx_inbox_active_by_issue.+UPDATE inbox_item SET read = true+WHERE workspace_id = $1 AND recipient_type = 'member' AND recipient_id = $2+ AND issue_id = $3 AND archived = false AND read = false;+-- name: ArchiveAllInbox :execrowsUPDATE inbox_item SET archived = trueWHERE workspace_id = $1 AND recipient_type = 'member' AND recipient_id = $2 AND archived = false;