Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8618 fix(inbox): opening an issue reads all of its notifications (#9959)
Bohan Jiangb6b2402c01d6
diff --git a/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsx b/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsxindex d44fb0cc94..62696a19d5 100644--- a/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsx+++ b/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsx@@ -56,13 +56,10 @@ export default function Inbox() {const archiveCompleted = useArchiveCompletedInbox();const onPressItem = useCallback((item: InboxItem) => {- if (!item.read) {- // Optimistic read flip lives in useMarkInboxRead.onMutate — fires- // setQueryData synchronously before the cancelQueries await, so the- // row is already styled "read" by the time iOS captures the source- // snapshot for the native stack push transition.- markRead.mutate(item.id);- }+ // Read on every opening: a read row can hide older unread notifications.+ // The mutation patches synchronously before iOS captures the source+ // snapshot for the native stack push transition.+ markRead.mutate(item.id);const target = getInboxNavigationTarget(item, wsSlug, String(Date.now()));if (target) router.push(target);}, [markRead, wsSlug]);diff --git a/apps/mobile/components/inbox/inbox-screen.test.ts b/apps/mobile/components/inbox/inbox-screen.test.tsnew file mode 100644index 0000000000..310dbac7db--- /dev/null+++ b/apps/mobile/components/inbox/inbox-screen.test.ts@@ -0,0 +1,77 @@+// @vitest-environment node+import type { InboxItem } from "@multica/core/types";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { router } from "expo-router";+import Inbox from "@/app/(app)/[workspace]/(tabs)/inbox";++const state = vi.hoisted(() => ({ rows: [] as InboxItem[], markRead: vi.fn() }));+vi.mock("react", async (importOriginal) => ({+ ...await importOriginal<typeof import("react")>(),+ useMemo: (create: () => unknown) => create(),+ useCallback: (callback: unknown) => callback,+}));+vi.mock("react-native", () => ({+ ActionSheetIOS: {}, Alert: {}, FlatList: "FlatList", View: "View",+}));+vi.mock("expo-router", () => ({ router: { push: vi.fn() } }));+vi.mock("@expo/vector-icons", () => ({ Ionicons: "Ionicons" }));+vi.mock("@tanstack/react-query", () => ({+ useQuery: () => ({ data: state.rows }),+}));+vi.mock("@/data/queries/inbox", () => ({ inboxListOptions: vi.fn() }));+vi.mock("@/data/mutations/inbox", () => {+ const mutation = () => ({ mutate: vi.fn() });+ return {+ useMarkInboxRead: () => ({ mutate: state.markRead }),+ useMarkAllInboxRead: mutation,+ useArchiveInbox: mutation,+ useArchiveAllInbox: mutation,+ useArchiveAllReadInbox: mutation,+ useArchiveCompletedInbox: mutation,+ };+});+vi.mock("@/data/workspace-store", () => ({+ useWorkspaceStore: (selector: (value: unknown) => unknown) => selector({+ currentWorkspaceId: "workspace-1", currentWorkspaceSlug: "acme",+ }),+}));+vi.mock("@/lib/use-color-scheme", () => ({ useColorScheme: () => ({ colorScheme: "light" }) }));+vi.mock("@/lib/theme", () => ({ THEME: { light: { mutedForeground: "gray" } } }));+vi.mock("@/lib/i18n", () => ({ useT: () => ({ t: (key: string) => key }) }));+vi.mock("@/components/ui/text", () => ({ Text: "Text" }));+vi.mock("@/components/ui/button", () => ({ Button: "Button" }));+vi.mock("@/components/ui/skeleton", () => ({ Skeleton: "Skeleton" }));+vi.mock("@/components/ui/header", () => ({ Header: "Header" }));+vi.mock("@/components/ui/icon-button", () => ({ IconButton: "IconButton" }));+vi.mock("@/components/ui/app-header-actions", () => ({ HeaderActions: "HeaderActions" }));+vi.mock("@/components/inbox/swipeable-inbox-row", () => ({ SwipeableInboxRow: "SwipeableInboxRow" }));++describe("Inbox navigation wiring", () => {+ beforeEach(() => vi.clearAllMocks());++ it.each([true, false])("reads the whole issue before navigation when the latest row read=%s", (read) => {+ const comment: InboxItem = {+ id: "comment", 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",+ body: null, issue_status: "todo", read, archived: false,+ created_at: "2026-06-15T08:01:00Z", details: null,+ };+ state.rows = [comment, {+ ...comment, id: "assigned", type: "issue_assigned", severity: "action_required",+ read: false, created_at: "2026-06-15T08:00:00Z",+ }];++ // Inspect props and invoke the tap callback without rendering native UI.+ const list = Inbox().props.children[1];+ expect(list.props.data).toEqual([comment]);+ list.props.renderItem({ item: comment }).props.onPress();++ expect(state.markRead).toHaveBeenCalledExactlyOnceWith("comment");+ expect(router.push).toHaveBeenCalledWith(expect.objectContaining({+ pathname: "/[workspace]/issue/[id]",+ params: expect.objectContaining({ workspace: "acme", id: "issue-1" }),+ }));+ expect(state.markRead.mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(router.push).mock.invocationCallOrder[0]!);+ });+});diff --git a/apps/mobile/data/mutations/inbox.test.ts b/apps/mobile/data/mutations/inbox.test.tsnew file mode 100644index 0000000000..e4ab5c365d--- /dev/null+++ b/apps/mobile/data/mutations/inbox.test.ts@@ -0,0 +1,116 @@+// @vitest-environment node+import { QueryClient } from "@tanstack/react-query";+import type { InboxItem } from "@multica/core/types";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { api } from "@/data/api";+import { inboxKeys } from "@/data/queries/inbox";+import { useMarkInboxRead } from "./inbox";++const state = vi.hoisted(() => ({ qc: undefined as unknown as QueryClient }));++vi.mock("@tanstack/react-query", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@tanstack/react-query")>();+ return {+ ...actual,+ useQueryClient: () => state.qc,+ // Keep the real mutation lifecycle, substituting only React hook wiring.+ useMutation: (+ options: ConstructorParameters<typeof actual.MutationObserver>[1],+ ) => {+ const observer = new actual.MutationObserver(state.qc, options);+ return { mutateAsync: (variables: unknown) => observer.mutate(variables) };+ },+ };+});++vi.mock("@/data/api", () => ({+ api: { markInboxRead: vi.fn() },+}));++vi.mock("@/data/realtime/inbox-ws-updaters", () => ({+ refreshInboxList: vi.fn(),+ refreshInboxUnreadSummary: vi.fn(),+}));++vi.mock("@/data/workspace-store", () => ({+ useWorkspaceStore: (+ selector: (s: { currentWorkspaceId: string }) => unknown,+ ) => selector({ currentWorkspaceId: "workspace-1" }),+}));++const wsId = "workspace-1";++function item(overrides: Partial<InboxItem>): InboxItem {+ return {+ id: "inbox-1",+ workspace_id: wsId,+ 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: false,+ created_at: "2026-06-15T08:00:00Z",+ details: null,+ ...overrides,+ };+}++function readState() {+ const items = state.qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId)) ?? [];+ return Object.fromEntries(items.map((i) => [i.id, i.read]));+}++describe("useMarkInboxRead", () => {+ beforeEach(() => {+ state.qc = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ state.qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), [+ item({ id: "comment" }),+ item({ id: "assigned", type: "issue_assigned", severity: "action_required" }),+ item({ id: "archived-sibling", archived: true }),+ item({ id: "other-issue", issue_id: "issue-2" }),+ item({ id: "no-issue", issue_id: null }),+ ]);+ });++ // MUL-8618: the server reads the issue's other unread active rows with the+ // one the row shows; the optimistic patch covers the same rows.+ it("reads the item and every other active item on its issue", async () => {+ vi.mocked(api.markInboxRead).mockResolvedValue(item({ id: "comment", read: true }));+ const { mutateAsync } = useMarkInboxRead();++ await mutateAsync("comment");++ expect(readState()).toEqual({+ comment: true,+ assigned: true,+ "archived-sibling": false,+ "other-issue": false,+ "no-issue": false,+ });+ });++ it("restores the list as it was before the patch when the request fails", async () => {+ vi.mocked(api.markInboxRead).mockRejectedValue(new Error("boom"));+ const { mutateAsync } = useMarkInboxRead();++ await expect(mutateAsync("comment")).rejects.toThrow("boom");++ expect(readState()).toEqual({+ comment: false,+ assigned: false,+ "archived-sibling": false,+ "other-issue": false,+ "no-issue": false,+ });+ });+});diff --git a/apps/mobile/data/mutations/inbox.ts b/apps/mobile/data/mutations/inbox.tsindex ef0f2c4426..69f8b97afe 100644--- a/apps/mobile/data/mutations/inbox.ts+++ b/apps/mobile/data/mutations/inbox.ts@@ -4,7 +4,10 @@* per Sharing Principles (no runtime imports from @multica/core mutations).** Behavioral parity:- * - mark-read: flip `read` to true locally; rollback on error; settle invalidate.+ * - mark-read: flip `read` to true locally on the item AND on every other+ * non-archived row that shares its `issue_id` — the server reads the whole+ * issue (MUL-8618), so an assignment under a later comment is read with+ * it; rollback on error; settle invalidate.* `onMutate` writes setQueryData BEFORE awaiting cancelQueries — this is* load-bearing for iOS Stack push transitions: when the user taps an* inbox row and we router.push to issue/[id], iOS captures a snapshot of@@ -67,12 +70,17 @@ export function useMarkInboxRead() {onMutate: async (id) => {const key = inboxKeys.list(wsId);// Synchronous patch FIRST — see the file-level doc comment for why.+ const prev = qc.getQueryData<InboxItem[]>(key);+ const issueId = prev?.find((item) => item.id === id)?.issue_id ?? null;qc.setQueryData<InboxItem[]>(key, (old) =>- old?.map((item) => (item.id === id ? { ...item, read: true } : item)),+ old?.map((item) =>+ item.id === id || (issueId != null && item.issue_id === issueId && !item.archived)+ ? { ...item, read: true }+ : item,+ ),);- // Then the standard cancel + snapshot dance for rollback.+ // Then the standard cancel for rollback.await qc.cancelQueries({ queryKey: key });- const prev = qc.getQueryData<InboxItem[]>(key);return { prev, key };},onError: (_err, _id, ctx) => {diff --git a/apps/mobile/vitest.config.ts b/apps/mobile/vitest.config.tsindex 40824ed8a6..c0986b63e6 100644--- a/apps/mobile/vitest.config.ts+++ b/apps/mobile/vitest.config.ts@@ -13,8 +13,8 @@ import path from "node:path";//// Co-located test files (foo.ts + foo.test.ts) match how the rest of the// monorepo organises vitest suites.-// The run cancel button has headless callback/prop tests with native modules-// mocked; these do not verify native rendering.+// The run cancel button and inbox have headless callback/prop tests with+// native modules mocked; these do not verify native rendering.// App configuration tests also run here to cover native prebuild options// across environment variants without loading React Native.export default defineConfig({@@ -31,6 +31,7 @@ export default defineConfig({"lib/**/*.test.ts","data/**/*.test.ts","components/issue/run-cancel-button.test.ts",+ "components/inbox/inbox-screen.test.ts",],passWithNoTests: true,},diff --git a/packages/core/inbox/mutations.test.tsx b/packages/core/inbox/mutations.test.tsxindex 43b075673c..d0d49cd894 100644--- a/packages/core/inbox/mutations.test.tsx+++ b/packages/core/inbox/mutations.test.tsx@@ -65,6 +65,84 @@ function summaryCount(qc: QueryClient) {return summary?.find((e) => e.workspace_id === WORKSPACE_ID)?.count;}+describe("useMarkInboxRead", () => {+ let queryClient: QueryClient;++ beforeEach(() => {+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ setApiInstance({+ markInboxRead: vi.fn(async (id: string) => item({ id, read: true, archived: false })),+ } as unknown as ApiClient);+ });++ // MUL-8618: the server reads the issue's other unread active rows with the+ // one the row shows, so an assignment under a later comment does not stay+ // unread out of sight. The optimistic patch covers the same rows.+ it("reads the item and every other active item on its issue", async () => {+ queryClient.setQueryData<InboxItem[]>(inboxKeys.list(WORKSPACE_ID), [+ item({ id: "comment", type: "new_comment", archived: false }),+ item({ id: "assigned", type: "issue_assigned", severity: "action_required", archived: false }),+ item({ id: "archived-sibling", archived: true }),+ item({ id: "other-issue", issue_id: "issue-2", archived: false }),+ item({ id: "no-issue", issue_id: null, archived: false }),+ ]);++ const { result } = renderHook(() => useMarkInboxRead(), {+ wrapper: createWrapper(queryClient),+ });+ result.current.mutate("comment");++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ const read = Object.fromEntries(listCache(queryClient).map((i) => [i.id, i.read]));+ expect(read).toEqual({+ comment: true,+ assigned: true,+ "archived-sibling": false,+ "other-issue": false,+ "no-issue": false,+ });+ });++ it("reads the issue's active items when the row was opened from the archive", async () => {+ queryClient.setQueryData<InboxItem[]>(inboxKeys.list(WORKSPACE_ID), [+ item({ id: "active", type: "issue_assigned", archived: false }),+ ]);+ queryClient.setQueryData<InboxItem[]>(inboxKeys.archived(WORKSPACE_ID), [+ item({ id: "archived-newest" }),+ item({ id: "archived-older" }),+ ]);++ const { result } = renderHook(() => useMarkInboxRead(), {+ wrapper: createWrapper(queryClient),+ });+ result.current.mutate("archived-newest");++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(listCache(queryClient)[0]?.read).toBe(true);+ expect(archivedCache(queryClient).map((i) => [i.id, i.read])).toEqual([+ ["archived-newest", true],+ ["archived-older", false],+ ]);+ });++ it("reads only the item when it has no issue", async () => {+ queryClient.setQueryData<InboxItem[]>(inboxKeys.list(WORKSPACE_ID), [+ item({ id: "first", issue_id: null, archived: false }),+ item({ id: "second", issue_id: null, archived: false }),+ ]);++ const { result } = renderHook(() => useMarkInboxRead(), {+ wrapper: createWrapper(queryClient),+ });+ result.current.mutate("first");++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(listCache(queryClient).map((i) => i.read)).toEqual([true, false]);+ });+});+describe("useMarkInboxUnread", () => {let queryClient: QueryClient;let markInboxUnread: ReturnType<typeof vi.fn>;@@ -78,8 +156,8 @@ describe("useMarkInboxUnread", () => {});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+ // Item-level, unlike 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 }),diff --git a/packages/core/inbox/mutations.ts b/packages/core/inbox/mutations.tsindex e48a94ea8a..6774510512 100644--- a/packages/core/inbox/mutations.ts+++ b/packages/core/inbox/mutations.ts@@ -20,6 +20,25 @@ function refreshInboxAfterWrite(qc: QueryClient, wsId: string) {void onInboxSummaryInvalidate(qc);}+/** The issue an inbox item belongs to, looked up in the active and archived caches. */+function cachedInboxIssueId(qc: QueryClient, wsId: string, id: string): string | null {+ const active = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId))?.find((item) => item.id === id);+ if (active) return active.issue_id;+ for (const [, data] of qc.getQueriesData<ArchivedInboxCache>({ queryKey: inboxKeys.archived(wsId) })) {+ if (!data) continue;+ const items = Array.isArray(data) ? data : "pages" in data ? data.pages.flatMap((page) => page.items) : data.items;+ const archived = items.find((item) => item.id === id);+ if (archived) return archived.issue_id;+ }+ return null;+}++/**+ * Read an inbox item. The server also reads every other unread active item on+ * its issue (MUL-8618): selecting a row opens the whole issue, so an+ * assignment under a later comment is read with it instead of staying unread+ * out of sight. The optimistic patch mirrors that set.+ */export function useMarkInboxRead() {const qc = useQueryClient();const wsId = useWorkspaceId();@@ -28,8 +47,13 @@ export function useMarkInboxRead() {onMutate: async (id) => {await qc.cancelQueries({ queryKey: inboxKeys.all(wsId) });const prev = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));+ const issueId = cachedInboxIssueId(qc, wsId, id);const markRead = (old: InboxItem[] | undefined) =>- old?.map((item) => (item.id === id ? { ...item, read: true } : item));+ old?.map((item) =>+ item.id === id || (issueId != null && item.issue_id === issueId && !item.archived)+ ? { ...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 thediff --git a/packages/views/inbox/components/inbox-page-query.test.tsx b/packages/views/inbox/components/inbox-page-query.test.tsxindex 2f973aad9a..cd0e7aa891 100644--- a/packages/views/inbox/components/inbox-page-query.test.tsx+++ b/packages/views/inbox/components/inbox-page-query.test.tsx@@ -97,6 +97,30 @@ function deferred<T>() {}const page = (items: InboxItem[]): ArchivedInboxPage => ({ items, hasMore: false, nextCursor: null });+it.each([false, true])("clears an older unread assignment when opening a read row via URL=%s", async (viaUrl) => {+ useInboxFilterStore.setState({ filtersByWorkspace: {} });+ if (viaUrl) searchParams.set("issue", "issue-a");+ let rows = [+ item({ id: "comment", read: true, created_at: "2026-06-15T08:01:00Z" }),+ item({ id: "assigned", type: "issue_assigned", severity: "action_required" }),+ ];+ const listInbox = vi.fn(async () => rows);+ const markInboxRead = vi.fn(async () => {+ rows = rows.map((row) => ({ ...row, read: true }));+ return rows[0]!;+ });+ setApiInstance({ listInbox, markInboxRead, getInboxUnreadSummary: async () => [] } as unknown as ApiClient);++ renderPage();+ const row = await screen.findByText("comment");+ if (!viaUrl) fireEvent.click(row);++ expect(await screen.findByTestId("detail")).toHaveTextContent("issue-a");+ await waitFor(() => expect(markInboxRead).toHaveBeenCalledExactlyOnceWith("comment"));+ await waitFor(() => expect(listInbox).toHaveBeenCalledTimes(2));+ expect(qc.getQueryData<InboxItem[]>(inboxKeys.list("workspace-1"))?.every((row) => row.read)).toBe(true);+});+function archivedFixture() {searchParams = new URLSearchParams("view=archived");const readGate = deferred<void>();diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex 425b6334a7..b2305b5372 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -354,16 +354,22 @@ export function InboxPage() {// 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- // in one pass and can't loop. Kept in a `useEffect` rather than inlined- // in handleSelect so URL-driven selection triggers it too.+ // Read once on opening, even if the visible row is already read: older+ // unread notifications can still be hidden under it. Also read new unread+ // arrivals while the row stays open. Track the opening separately from the+ // optimistic cache patch so a read row cannot cause a request loop.+ const openedItemIdRef = useRef<string | null>(null);const markReadMutate = markReadMutation.mutate;const selectedId = selected?.id;const selectedRead = selected?.read;useEffect(() => {- if (!selectedId || selectedRead) return;+ if (!selectedId) {+ openedItemIdRef.current = null;+ return;+ }+ const justOpened = openedItemIdRef.current !== selectedId;+ openedItemIdRef.current = selectedId;+ if (!justOpened && selectedRead) return;if (manualUnreadIdRef.current === selectedId) return;if (filters.unreadOnly) {pinnedUnreadKeyRef.current = selectedKey;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.tsxindex 1ce15e84d5..654c7ffd9c 100644--- 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.tsx@@ -79,13 +79,19 @@ describe("useMarkIssueInboxReadWhileViewing", () => {expect(api.markIssueInboxRead).toHaveBeenCalledWith("issue-1");});- it("sends nothing while the workspace has no unread notifications", async () => {+ it("clears hidden legacy unread notifications even when the badge is zero", async () => {setUnreadSummary(0);+ client.setQueryData(inboxKeys.list("ws-1"), [+ { id: "comment", issue_id: "issue-1", read: true, archived: false },+ { id: "assigned", issue_id: "issue-1", read: false, archived: false },+ ]);- renderHook(() => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ const { rerender } = renderHook(() => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ await settle();+ rerender();await settle();- expect(api.markIssueInboxRead).not.toHaveBeenCalled();+ expect(api.markIssueInboxRead).toHaveBeenCalledExactlyOnceWith("issue-1");});it("reads a notification on the open issue as it arrives, and ignores other issues", async () => {@@ -111,7 +117,7 @@ describe("useMarkIssueInboxReadWhileViewing", () => {expect(api.markIssueInboxRead).toHaveBeenCalledTimes(2);});- it("holds an arrival until the unread count reflects it", async () => {+ it("reads an arrival before the unread count reflects it", async () => {setUnreadSummary(1);renderHook(() => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });@@ -120,7 +126,7 @@ describe("useMarkIssueInboxReadWhileViewing", () => {deliver(notification("issue-1"));await settle();- expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);+ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(2);act(() => setUnreadSummary(1));await settle();@@ -142,9 +148,9 @@ describe("useMarkIssueInboxReadWhileViewing", () => {expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);});- it("reads again after a reconnect, once the refreshed count shows unread", async () => {+ it("reads again after a reconnect even before the unread summary refreshes", 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.+ // sync also refreshes the summary, but the read need not wait for it.setUnreadSummary(1);renderHook(() => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });@@ -154,7 +160,7 @@ describe("useMarkIssueInboxReadWhileViewing", () => {reconnect();await settle();- expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);+ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(2);act(() => setUnreadSummary(1));await settle();@@ -191,6 +197,40 @@ describe("useMarkIssueInboxReadWhileViewing", () => {expect(api.markIssueInboxRead).not.toHaveBeenCalled();});+ it("reads once per opening when navigating back to an issue at inbox zero", async () => {+ setUnreadSummary(0);+ const { rerender } = renderHook(+ ({ issueId }) => useMarkIssueInboxReadWhileViewing("ws-1", issueId),+ { wrapper, initialProps: { issueId: "issue-1" } },+ );+ await settle();+ rerender({ issueId: "issue-2" });+ await settle();+ rerender({ issueId: "issue-1" });+ await settle();+ rerender({ issueId: "issue-1" });+ await settle();++ expect(vi.mocked(api.markIssueInboxRead).mock.calls.map(([id]) => id)).toEqual([+ "issue-1", "issue-2", "issue-1",+ ]);+ });++ it("reads when an issue becomes enabled after its host stopped reading it", async () => {+ setUnreadSummary(0);+ const { rerender } = renderHook(+ ({ enabled }) => useMarkIssueInboxReadWhileViewing("ws-1", "issue-1", enabled),+ { wrapper, initialProps: { enabled: true } },+ );+ await settle();+ rerender({ enabled: false });+ await settle();+ rerender({ enabled: true });+ await settle();++ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(2);+ });+it("does not resubmit after a failed write", async () => {setUnreadSummary(1);vi.mocked(api.markIssueInboxRead).mockRejectedValue(Object.assign(new Error("not found"), { status: 404 }));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.tsindex 6d8ef61e0d..138ea00143 100644--- 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.ts@@ -1,5 +1,5 @@import { useCallback, useEffect, useRef, useState } from "react";-import { useInboxUnreadCount, useMarkIssueInboxRead } from "@multica/core/inbox";+import { 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";@@ -16,14 +16,13 @@ import { useAppForeground } from "../../common/use-app-foreground";* 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.+ * The deduplicated badge can be zero while older notifications are unread,+ * so each opening, arrival and reconnect is written regardless of the badge.+ * Each 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.@@ -39,16 +38,19 @@ export function useMarkIssueInboxReadWhileViewing(wsId: string, issueId: string,);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.+ // An inbox:new sent while the socket was down is never replayed.const onReconnect = useCallback(() => setGeneration((n) => n + 1), []);useWSReconnect(onReconnect);useEffect(() => {- if (!enabled || !issueId || !foreground || !hasUnreadInbox) return;- const key = `${issueId}|${generation}`;+ if (!enabled || !issueId) {+ written.current = null;+ return;+ }+ if (!foreground) return;+ const key = `${wsId}|${issueId}|${generation}`;if (written.current === key) return;written.current = key;markRead(issueId);- }, [enabled, issueId, foreground, hasUnreadInbox, generation, markRead]);+ }, [enabled, wsId, issueId, foreground, generation, markRead]);}diff --git a/server/cmd/server/integration_test.go b/server/cmd/server/integration_test.goindex 70fb7f7590..24fe08b4e0 100644--- a/server/cmd/server/integration_test.go+++ b/server/cmd/server/integration_test.go@@ -1373,8 +1373,9 @@ func TestUnarchiveInboxRejectsForeignItem(t *testing.T) {}}-// An issue's inbox notifications are deduplicated per issue: opening the issue-// marks only the NEWEST item read, leaving older siblings unread. The summary+// An issue's inbox notifications are deduplicated per issue. Opening the issue+// used to mark only the NEWEST item read, leaving older siblings unread, and+// rows from then are still in the database (MUL-8618 reads them lazily). The summary// must mirror the inbox UI (issue is read when its newest item is read), so a// read-newest / unread-older issue must NOT light the switcher dot (MUL-3695).func TestInboxUnreadSummaryDedupesByIssue(t *testing.T) {diff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.goindex 683307dd76..8916dd729d 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -220,6 +220,9 @@ func (h *Handler) ListArchivedInbox(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, resp)}+// MarkInboxRead reads the item and, when it belongs to an issue, every other+// unread active item the caller has on that issue: selecting a row in the inbox+// opens the whole issue (MUL-8618, see the query comment).func (h *Handler) MarkInboxRead(w http.ResponseWriter, r *http.Request) {id := chi.URLParam(r, "id")prev, ok := h.loadInboxItemForUser(w, r, id)@@ -248,7 +251,8 @@ func (h *Handler) MarkInboxRead(w http.ResponseWriter, r *http.Request) {// 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.+// Scope is the single item, the newest one the row shows, unlike 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)@@ -437,10 +441,10 @@ 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 informational notifications on-// one issue read; items that need handling stay unread (see-// MarkInboxReadByIssue). 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+// MarkIssueInboxRead marks every unread active notification the caller has on+// one issue read (see MarkInboxReadByIssue). 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) {diff --git a/server/internal/handler/inbox_issue_read_test.go b/server/internal/handler/inbox_issue_read_test.goindex ae30392f90..958629d63f 100644--- a/server/internal/handler/inbox_issue_read_test.go+++ b/server/internal/handler/inbox_issue_read_test.go@@ -161,7 +161,7 @@ func (f issueInboxFixture) openIssue() int64 {}// openInInbox is selecting the issue's row in the inbox: it renders the-// group's newest row and marks that one read.+// group's newest row and marks that one read, which reads the whole issue.func (f issueInboxFixture) openInInbox() {f.t.Helper()var items []InboxItemResponse@@ -172,12 +172,32 @@ func (f issueInboxFixture) openInInbox() {if len(items) == 0 {f.t.Fatal("the inbox lists nothing for the issue")}- newest := items[0].ID+ f.markRead(items[0].ID)+}++func (f issueInboxFixture) markRead(id string) {+ f.t.Helper()testutil.Call(f.t, inboxWorkspaceHandler(testHandler.MarkInboxRead),- withURLParam(inboxRequest(http.MethodPost, "/api/inbox/"+newest+"/read", f.workspaceID), "id", newest)).+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/"+id+"/read", f.workspaceID), "id", id)).Want(http.StatusOK)}+func (f issueInboxFixture) markUnread(id string) {+ f.t.Helper()+ testutil.Call(f.t, inboxWorkspaceHandler(testHandler.MarkInboxUnread),+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/"+id+"/unread", f.workspaceID), "id", id)).+ Want(http.StatusOK)+}++// rawUnread is every unread active row the caller has in the workspace, the+// count GET /api/inbox/unread-count reports.+func (f issueInboxFixture) rawUnread() int64 {+ f.t.Helper()+ return int64(dbfx.Count(f.t,+ "SELECT count(*) FROM inbox_item WHERE workspace_id = $1 AND recipient_id = $2 AND archived = false AND read = false",+ f.workspaceID, testUserID))+}+// unreadRows is the issue's row in the unread badge: 1 while its newest// active row is unread.func (f issueInboxFixture) unreadRows() int64 {@@ -202,69 +222,125 @@ func (f issueInboxFixture) read(id string) bool {return read}-func TestMarkIssueInboxReadKeepsPendingItemsThatNeedHandling(t *testing.T) {- for _, kept := range []struct{ notifType, severity string }{+// Items that need handling are read with the rest: opening the issue shows+// all of it (MUL-8618).+func TestMarkIssueInboxReadReadsItemsThatNeedHandling(t *testing.T) {+ for _, pending := range []struct{ notifType, severity string }{{"issue_assigned", "action_required"},{"task_failed", "action_required"},{"autopilot_paused", "attention"},{"mentioned", "info"},} {- t.Run(kept.notifType, func(t *testing.T) {- f := newIssueInboxFixture(t, "keeps "+kept.notifType)- keptID := f.notify(kept.notifType, kept.severity, 2)+ t.Run(pending.notifType, func(t *testing.T) {+ f := newIssueInboxFixture(t, "reads "+pending.notifType)+ pendingID := f.notify(pending.notifType, pending.severity, 2)comment := f.notify("new_comment", "info", 1)- // The comment is the row the inbox shows: reading it would turn the- // row read with the kept item still waiting behind it.- if got := f.openIssue(); got != 0 {- t.Fatalf("count = %d, want nothing read while %s is pending", got, kept.notifType)+ if got := f.openIssue(); got != 2 {+ t.Fatalf("count = %d, want both rows read", got)}- if f.read(keptID) || f.read(comment) || f.unreadRows() != 1 {- t.Fatalf("opening the issue read past a pending %s", kept.notifType)+ if !f.read(pendingID) || !f.read(comment) || f.unreadRows() != 0 || f.rawUnread() != 0 {+ t.Fatalf("opening the issue left %s unread", pending.notifType)}})}-- t.Run("kept row is the newest", func(t *testing.T) {- f := newIssueInboxFixture(t, "keeps the newest row")- comment := f.notify("new_comment", "info", 2)- assigned := f.notify("issue_assigned", "action_required", 1)- if got := f.openIssue(); got != 0 || f.read(comment) || f.read(assigned) {- t.Fatalf("count = %d, want the assignment row left unread as it is", got)- }- })}-func TestMarkIssueInboxReadIsNotBlockedByAnAssignmentTheInboxReadPast(t *testing.T) {- f := newIssueInboxFixture(t, "assignment the inbox read past")+// The MUL-8618 report: an assignment under a later comment. Opening the row+// in the inbox reads the comment it shows and the assignment under it, so no+// unread row is left behind where the inbox never shows it again.+func TestMarkInboxReadReadsEveryActiveRowOnTheIssue(t *testing.T) {+ f := newIssueInboxFixture(t, "inbox read reads the issue")assigned := f.notify("issue_assigned", "action_required", 3)- f.notify("new_comment", "info", 2)+ comment := f.notify("new_comment", "info", 2)+ archived := f.notify("new_comment", "info", 4)+ dbfx.Exec(t, `UPDATE inbox_item SET archived = true WHERE id = $1`, archived)+ otherIssueID := dbfx.Issue(t, "Other issue", testutil.Cols{"workspace_id": f.workspaceID})+ other := dbfx.Insert(t, "inbox_item", testutil.Cols{+ "workspace_id": f.workspaceID,+ "recipient_type": "member",+ "recipient_id": testUserID,+ "type": "new_comment",+ "severity": "info",+ "issue_id": otherIssueID,+ "title": "another issue",+ })+ someoneElses := dbfx.Insert(t, "inbox_item", testutil.Cols{+ "workspace_id": f.workspaceID,+ "recipient_type": "member",+ "recipient_id": uuid.NewString(),+ "type": "issue_assigned",+ "severity": "action_required",+ "issue_id": f.issueID,+ "title": "someone else's",+ })- // The inbox shows and reads only the newest comment; the assignment under- // it stays unread for good.- f.openInInbox()- if f.read(assigned) || f.unreadRows() != 0 {- t.Fatal("setup: want the inbox row read with the assignment still unread under it")+ f.markRead(comment)+ if !f.read(comment) || !f.read(assigned) {+ t.Fatal("reading the row the inbox shows left the assignment under it unread")+ }+ if f.read(archived) {+ t.Fatal("reading the row read an archived row on the issue")+ }+ if f.read(other) {+ t.Fatal("reading the row read another issue's row")+ }+ if f.read(someoneElses) {+ t.Fatal("reading the row read another recipient's row")+ }+ if got := f.rawUnread(); got != 1 {+ t.Fatalf("raw unread = %d, want only the other issue's row", got)}- next := f.notify("new_comment", "info", 1)- if f.unreadRows() != 1 {- t.Fatal("setup: a new comment should make the issue's row unread again")+ // Mark as unread flips only the row the inbox shows; reading it again+ // reads it, and a pending row that arrived since is read with it.+ f.markUnread(comment)+ if f.read(comment) || !f.read(assigned) {+ t.Fatal("mark as unread should flip only the shown row")}- if got := f.openIssue(); got != 1 || !f.read(next) {- t.Fatalf("count = %d, want the new comment read", got)+ reassigned := f.notify("issue_assigned", "action_required", 1)+ f.markRead(comment)+ if !f.read(comment) || !f.read(reassigned) {+ t.Fatal("reading the row again left a newer assignment unread")}- if f.unreadRows() != 0 {- t.Fatal("the issue's inbox row is still unread after opening the issue")+}++// Opening an archived row reads that row and the issue's active rows, the same+// set opening the issue anywhere else reads.+func TestMarkInboxReadOnAnArchivedRowReadsTheIssuesActiveRows(t *testing.T) {+ f := newIssueInboxFixture(t, "inbox read on an archived row")+ archivedOlder := f.notify("new_comment", "info", 3)+ archivedNewest := f.notify("new_comment", "info", 2)+ dbfx.Exec(t, `UPDATE inbox_item SET archived = true WHERE id = ANY($1::uuid[])`, []string{archivedOlder, archivedNewest})+ active := f.notify("issue_assigned", "action_required", 1)++ f.markRead(archivedNewest)+ if !f.read(archivedNewest) || !f.read(active) {+ t.Fatal("want the archived row and the issue's active row read")+ }+ if f.read(archivedOlder) {+ t.Fatal("an archived sibling should be left as it is")}- if f.read(assigned) {- t.Fatal("opening the issue read the assignment")+}++func TestMarkInboxReadWithoutAnIssueReadsOnlyTheItem(t *testing.T) {+ f := newIssueInboxFixture(t, "inbox read without an issue")+ insert := func(title string) string {+ t.Helper()+ return dbfx.Insert(t, "inbox_item", testutil.Cols{+ "workspace_id": f.workspaceID,+ "recipient_type": "member",+ "recipient_id": testUserID,+ "type": "autopilot_paused",+ "severity": "attention",+ "title": title,+ })}+ first := insert("first")+ second := insert("second")- // An assignment that arrives after that is pending again.- reassigned := f.notify("issue_assigned", "action_required", 0)- f.notify("new_comment", "info", 0)- if got := f.openIssue(); got != 0 || f.read(reassigned) || f.unreadRows() != 1 {- t.Fatalf("count = %d, want a new assignment to keep the row unread", got)+ f.markRead(first)+ if !f.read(first) || f.read(second) {+ t.Fatal("reading an item without an issue should read only that item")}}diff --git a/server/pkg/agent/zcode.go b/server/pkg/agent/zcode.goindex 5023ad5c28..419151591b 100644--- a/server/pkg/agent/zcode.go+++ b/server/pkg/agent/zcode.go@@ -390,6 +390,19 @@ func (b *zcodeBackend) Execute(ctx context.Context, prompt string, opts ExecOpti}}+ withStartupStderr := func(msg string) string {+ // A failed RPC can beat the independent stderr copier to EOF.+ // Stop the failed process and bound the drain before reading its tail.+ stopProcess()+ timer := time.NewTimer(defaultZcodeInterruptGrace)+ defer timer.Stop()+ select {+ case <-stderrDone:+ case <-timer.C:+ }+ return withAgentStderr(msg, "zcode", stderrBuf.Tail())+ }+// 1. session/create or session/resume.// 2. Early session pin so a cancelled run still preserves the resume// pointer.@@ -437,7 +450,7 @@ func (b *zcodeBackend) Execute(ctx context.Context, prompt string, opts ExecOptistatus, msg := classifyStartupFailure(err, "session/resume")resCh <- Result{Status: status,- Error: withAgentStderr(msg, "zcode", stderrBuf.Tail()),+ Error: withStartupStderr(msg),DurationMs: time.Since(startTime).Milliseconds(),SessionID: opts.ResumeSessionID,}@@ -497,7 +510,7 @@ func (b *zcodeBackend) Execute(ctx context.Context, prompt string, opts ExecOptistatus, msg := classifyStartupFailure(err, "session/create")resCh <- Result{Status: status,- Error: withAgentStderr(msg, "zcode", stderrBuf.Tail()),+ Error: withStartupStderr(msg),DurationMs: time.Since(startTime).Milliseconds(),}return@@ -506,7 +519,7 @@ func (b *zcodeBackend) Execute(ctx context.Context, prompt string, opts ExecOptiif sessionID == "" {resCh <- Result{Status: "failed",- Error: withAgentStderr("zcode session/create returned no sessionId", "zcode", stderrBuf.Tail()),+ Error: withStartupStderr("zcode session/create returned no sessionId"),DurationMs: time.Since(startTime).Milliseconds(),}return@@ -525,7 +538,7 @@ func (b *zcodeBackend) Execute(ctx context.Context, prompt string, opts ExecOptistatus, msg := classifyStartupFailure(err, "session/subscribe")resCh <- Result{Status: status,- Error: withAgentStderr(msg, "zcode", stderrBuf.Tail()),+ Error: withStartupStderr(msg),DurationMs: time.Since(startTime).Milliseconds(),SessionID: sessionID,}@@ -546,7 +559,7 @@ func (b *zcodeBackend) Execute(ctx context.Context, prompt string, opts ExecOptistatus, msg := classifyStartupFailure(err, "session/send")resCh <- Result{Status: status,- Error: withAgentStderr(msg, "zcode", stderrBuf.Tail()),+ Error: withStartupStderr(msg),DurationMs: time.Since(startTime).Milliseconds(),SessionID: sessionID,}diff --git a/server/pkg/agent/zcode_test.go b/server/pkg/agent/zcode_test.goindex a52a63dff1..ee3e7858fe 100644--- a/server/pkg/agent/zcode_test.go+++ b/server/pkg/agent/zcode_test.go@@ -6,6 +6,7 @@ import ("encoding/json""errors""fmt"+ "io""log/slog""os""os/exec"@@ -573,6 +574,77 @@ exit 1}}+type zcodeDelayedStderrHandler struct {+ slog.Handler+ entered chan struct{}+ release chan struct{}+ once sync.Once+}++func (h *zcodeDelayedStderrHandler) Handle(ctx context.Context, record slog.Record) error {+ if strings.HasPrefix(record.Message, "[zcode:stderr] ") {+ h.once.Do(func() { close(h.entered) })+ <-h.release+ }+ return h.Handler.Handle(ctx, record)+}++func TestZcodeStartupFailureWaitsForStderr(t *testing.T) {+ for _, method := range []string{"session/create", "session/resume", "session/subscribe", "session/send"} {+ t.Run(method, func(t *testing.T) {+ t.Parallel()+ failureCase := fmt.Sprintf(` case "$line" in+ *'"method":"%s"'*)+ echo "zcode: authentication failed" >&2+ exit 1+ ;;+`, method)+ script := strings.Replace(fakeZcodeHappyScript(""), ` case "$line" in`, failureCase, 1)+ handler := &zcodeDelayedStderrHandler{+ Handler: slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelDebug}),+ entered: make(chan struct{}),+ release: make(chan struct{}),+ }+ releaseStderr := sync.OnceFunc(func() { close(handler.release) })+ defer releaseStderr()+ backend, err := New("zcode", Config{+ ExecutablePath: writeFakeZcodeScript(t, script),+ Logger: slog.New(handler),+ })+ if err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ opts := ExecOptions{Cwd: t.TempDir()}+ if method == "session/resume" {+ opts.ResumeSessionID = fakeZcodeSessionID+ }+ session, err := backend.Execute(ctx, "prompt", opts)+ if err != nil {+ t.Fatal(err)+ }+ select {+ case <-handler.entered:+ case <-ctx.Done():+ t.Fatal("stderr was never forwarded")+ }+ // Hold the independent stderr copier after the child writes its+ // diagnostic. A transport failure must not publish an empty tail.+ select {+ case result := <-session.Result:+ t.Fatalf("result arrived before stderr was drained: %+v", result)+ case <-time.After(50 * time.Millisecond):+ }+ releaseStderr()+ _, result := collectZcodeSession(t, session)+ if result.Status != "failed" || !strings.Contains(result.Error, "authentication failed") {+ t.Fatalf("expected failure with stderr diagnostic, got %+v", result)+ }+ })+ }+}+// TestZcodeThinkingDeltas covers T19: reasoning deltas map to MessageThinking.func TestZcodeThinkingDeltas(t *testing.T) {t.Parallel()diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.goindex 76348020b4..31736d68c5 100644--- a/server/pkg/db/generated/inbox.sql.go+++ b/server/pkg/db/generated/inbox.sql.go@@ -230,10 +230,11 @@ type CountUnreadInboxByWorkspaceRow struct {// Per-workspace unread inbox counts for a recipient member, matching the// inbox UI's deduplicated view: notifications are grouped per issue// (Linear-style, one row per issue) and an issue counts as unread only when-// its NEWEST non-archived item is unread. Opening an issue marks just that-// newest item read, so counting raw unread rows would keep older siblings-// alive and light the switcher dot for a workspace whose inbox the user sees-// as empty (MUL-3695). Items without an issue group on their own id. The+// its NEWEST non-archived item is unread. Opening an issue reads the whole+// group now (MUL-8618), but rows read before that read only the newest item,+// so counting raw unread rows would keep those older siblings alive and light+// the switcher dot for a workspace whose inbox the user sees as empty+// (MUL-3695). Items without an issue group on their own id. The// member join keeps counts scoped to workspaces the user still belongs to,// so a stale item left behind in a workspace the user has since left cannot// light the dot.@@ -625,11 +626,34 @@ func (q *Queries) MarkAllInboxRead(ctx context.Context, arg MarkAllInboxReadPara}const markInboxRead = `-- name: MarkInboxRead :one-UPDATE inbox_item SET read = true-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, section+WITH target AS (+ SELECT t.workspace_id, t.recipient_type, t.recipient_id, t.issue_id+ FROM inbox_item t+ WHERE t.id = $1 AND t.issue_id IS NOT NULL+), siblings AS (+ UPDATE inbox_item s SET read = true+ FROM target+ WHERE s.workspace_id = target.workspace_id+ AND s.recipient_type = target.recipient_type+ AND s.recipient_id = target.recipient_id+ AND s.issue_id = target.issue_id+ AND s.archived = false AND s.read = false+ AND s.id <> $1+)+UPDATE inbox_item AS item SET read = true+WHERE item.id = $1+RETURNING item.id, item.workspace_id, item.recipient_type, item.recipient_id, item.type, item.severity, item.issue_id, item.title, item.body, item.read, item.archived, item.created_at, item.actor_type, item.actor_id, item.details, item.section`+// Opening a row in the inbox opens its issue, so it reads every active unread+// row on that issue, not just the one shown (MUL-8618). The inbox renders one+// row per issue carrying its newest item; reading only that item left older+// unread siblings (an assignment under a later comment) unread for good, out of+// sight. This is the same rule as MarkInboxReadByIssue, which reads an issue+// opened outside the inbox. The item itself is read whether or not it is+// archived; its siblings only while active, as in MarkInboxReadByIssue, which+// keeps the probe on the partial index idx_inbox_active_by_issue. Items without+// an issue are their own group.func (q *Queries) MarkInboxRead(ctx context.Context, id pgtype.UUID) (InboxItem, error) {row := q.db.QueryRow(ctx, markInboxRead, id)var i InboxItem@@ -655,22 +679,9 @@ func (q *Queries) MarkInboxRead(ctx context.Context, id pgtype.UUID) (InboxItem,}const markInboxReadByIssue = `-- name: MarkInboxReadByIssue :execrows-UPDATE inbox_item i SET read = true-WHERE i.workspace_id = $1 AND i.recipient_type = 'member' AND i.recipient_id = $2- AND i.issue_id = $3 AND i.archived = false AND i.read = false- AND i.severity = 'info' AND i.type <> 'mentioned'- AND NOT EXISTS (- SELECT 1 FROM inbox_item kept- WHERE kept.workspace_id = $1 AND kept.recipient_type = 'member' AND kept.recipient_id = $2- AND kept.issue_id = $3 AND kept.archived = false AND kept.read = false- AND (kept.severity <> 'info' OR kept.type = 'mentioned')- AND NOT EXISTS (- SELECT 1 FROM inbox_item seen- WHERE seen.workspace_id = $1 AND seen.recipient_type = 'member' AND seen.recipient_id = $2- AND seen.issue_id = $3 AND seen.archived = false AND seen.read = true- AND (seen.created_at, seen.id) > (kept.created_at, kept.id)- )- )+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 {@@ -681,19 +692,13 @@ type MarkInboxReadByIssueParams struct {// 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.-//-// Only informational rows are read (MUL-8596). action_required and attention-// rows, and mentions, which are addressed to the reader, stay until handled.-// The inbox renders the group's newest row, so reading info rows around a-// pending kept row could turn the group read and hide it; while one is pending-// nothing is read. A kept row stops being pending once a newer row in the group-// has been read: the inbox already showed the group past it, and it would-// otherwise block every later notification on the issue.+// again (MUL-8588). Every unread row in the issue's group, not just the newest,+// whatever its severity: opening the issue shows all of it, so an assignment,+// review request or mention on it counts as seen (MUL-8618; this replaces the+// MUL-8596 rule that kept those unread). Opening the row in the inbox does the+// same through MarkInboxRead. 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 {@@ -708,12 +713,12 @@ WHERE id = $1RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section`-// 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.+// Item-level, unlike MarkInboxRead: 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, so flipping the newest item is enough to make the row unread.+// 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 InboxItemdiff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sqlindex 38d27bdb38..6a6786dbce 100644--- a/server/pkg/db/queries/inbox.sql+++ b/server/pkg/db/queries/inbox.sql@@ -106,17 +106,40 @@ WHERE ($2::text = 'member' AND EXISTS (RETURNING *;-- name: MarkInboxRead :one-UPDATE inbox_item SET read = true-WHERE id = $1-RETURNING *;+-- Opening a row in the inbox opens its issue, so it reads every active unread+-- row on that issue, not just the one shown (MUL-8618). The inbox renders one+-- row per issue carrying its newest item; reading only that item left older+-- unread siblings (an assignment under a later comment) unread for good, out of+-- sight. This is the same rule as MarkInboxReadByIssue, which reads an issue+-- opened outside the inbox. The item itself is read whether or not it is+-- archived; its siblings only while active, as in MarkInboxReadByIssue, which+-- keeps the probe on the partial index idx_inbox_active_by_issue. Items without+-- an issue are their own group.+WITH target AS (+ SELECT t.workspace_id, t.recipient_type, t.recipient_id, t.issue_id+ FROM inbox_item t+ WHERE t.id = $1 AND t.issue_id IS NOT NULL+), siblings AS (+ UPDATE inbox_item s SET read = true+ FROM target+ WHERE s.workspace_id = target.workspace_id+ AND s.recipient_type = target.recipient_type+ AND s.recipient_id = target.recipient_id+ AND s.issue_id = target.issue_id+ AND s.archived = false AND s.read = false+ AND s.id <> $1+)+UPDATE inbox_item AS item SET read = true+WHERE item.id = $1+RETURNING item.*;-- 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.+-- Item-level, unlike MarkInboxRead: 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, so flipping the newest item is enough to make the row unread.+-- 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 = falseWHERE id = $1RETURNING *;@@ -158,10 +181,11 @@ WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND read =-- Per-workspace unread inbox counts for a recipient member, matching the-- inbox UI's deduplicated view: notifications are grouped per issue-- (Linear-style, one row per issue) and an issue counts as unread only when--- its NEWEST non-archived item is unread. Opening an issue marks just that--- newest item read, so counting raw unread rows would keep older siblings--- alive and light the switcher dot for a workspace whose inbox the user sees--- as empty (MUL-3695). Items without an issue group on their own id. The+-- its NEWEST non-archived item is unread. Opening an issue reads the whole+-- group now (MUL-8618), but rows read before that read only the newest item,+-- so counting raw unread rows would keep those older siblings alive and light+-- the switcher dot for a workspace whose inbox the user sees as empty+-- (MUL-3695). Items without an issue group on their own id. The-- member join keeps counts scoped to workspaces the user still belongs to,-- so a stale item left behind in a workspace the user has since left cannot-- light the dot.@@ -186,35 +210,16 @@ WHERE workspace_id = $1 AND recipient_type = 'member' AND recipient_id = $2 AND-- 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.------ Only informational rows are read (MUL-8596). action_required and attention--- rows, and mentions, which are addressed to the reader, stay until handled.--- The inbox renders the group's newest row, so reading info rows around a--- pending kept row could turn the group read and hide it; while one is pending--- nothing is read. A kept row stops being pending once a newer row in the group--- has been read: the inbox already showed the group past it, and it would--- otherwise block every later notification on the issue.-UPDATE inbox_item i SET read = true-WHERE i.workspace_id = $1 AND i.recipient_type = 'member' AND i.recipient_id = $2- AND i.issue_id = $3 AND i.archived = false AND i.read = false- AND i.severity = 'info' AND i.type <> 'mentioned'- AND NOT EXISTS (- SELECT 1 FROM inbox_item kept- WHERE kept.workspace_id = $1 AND kept.recipient_type = 'member' AND kept.recipient_id = $2- AND kept.issue_id = $3 AND kept.archived = false AND kept.read = false- AND (kept.severity <> 'info' OR kept.type = 'mentioned')- AND NOT EXISTS (- SELECT 1 FROM inbox_item seen- WHERE seen.workspace_id = $1 AND seen.recipient_type = 'member' AND seen.recipient_id = $2- AND seen.issue_id = $3 AND seen.archived = false AND seen.read = true- AND (seen.created_at, seen.id) > (kept.created_at, kept.id)- )- );+-- again (MUL-8588). Every unread row in the issue's group, not just the newest,+-- whatever its severity: opening the issue shows all of it, so an assignment,+-- review request or mention on it counts as seen (MUL-8618; this replaces the+-- MUL-8596 rule that kept those unread). Opening the row in the inbox does the+-- same through MarkInboxRead. 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 = true