Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8483: feat(inbox): Needs action / Activity sections, shared read state, per-kind routing in Inbox settings (#9815)
Jiayuan Zhang92911409c8cc
diff --git a/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsx b/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsxindex d44fb0cc94..294b62f9af 100644--- a/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsx+++ b/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsx@@ -1,4 +1,4 @@-import { useCallback, useMemo } from "react";+import { useCallback, useMemo, useState } from "react";import {ActionSheetIOS,Alert,@@ -8,11 +8,13 @@ import {import { useQuery } from "@tanstack/react-query";import { router } from "expo-router";import { Ionicons } from "@expo/vector-icons";-import type { InboxItem } from "@multica/core/types";+import type { InboxItem, InboxSection } from "@multica/core/types";+import { isInboxItemUnread } from "@multica/core/inbox/section";import { Text } from "@/components/ui/text";import { Button } from "@/components/ui/button";import { Skeleton } from "@/components/ui/skeleton";import { Header } from "@/components/ui/header";+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";import { IconButton } from "@/components/ui/icon-button";import { HeaderActions } from "@/components/ui/app-header-actions";import { SwipeableInboxRow } from "@/components/inbox/swipeable-inbox-row";@@ -29,9 +31,10 @@ import { useWorkspaceStore } from "@/data/workspace-store";import { useColorScheme } from "@/lib/use-color-scheme";import { THEME } from "@/lib/theme";import { useT } from "@/lib/i18n";+import { useInboxUnreadCount } from "@/lib/unread-counts";import {- deduplicateInboxItems,getInboxNavigationTarget,+ groupInboxItemsBySection,} from "@/lib/inbox-display";export default function Inbox() {@@ -42,12 +45,15 @@ export default function Inbox() {const { data: rawItems, isLoading, error, refetch, isRefetching } = useQuery(inboxListOptions(wsId),);- // Dedup + drop archived to match web/desktop. See CLAUDE.md- // "Behavioral parity" → inbox dedup incident.- const data = useMemo(- () => deduplicateInboxItems(rawItems ?? []),+ // Dedup + drop archived to match web/desktop, split into the same two+ // sections. See CLAUDE.md "Behavioral parity" → inbox dedup incident.+ const [section, setSection] = useState<InboxSection>("action");+ const sections = useMemo(+ () => groupInboxItemsBySection(rawItems ?? []),[rawItems],);+ const data = sections[section];+ const unreadCount = useInboxUnreadCount(wsId);const markRead = useMarkInboxRead();const markAllRead = useMarkAllInboxRead();const archive = useArchiveInbox();@@ -56,7 +62,7 @@ export default function Inbox() {const archiveCompleted = useArchiveCompletedInbox();const onPressItem = useCallback((item: InboxItem) => {- if (!item.read) {+ if (isInboxItemUnread(item)) {// 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@@ -123,6 +129,24 @@ export default function Inbox() {</>}/>+ <View className="px-4 pb-2">+ <Tabs+ value={section}+ onValueChange={(value) => setSection(value as InboxSection)}+ >+ <TabsList className="w-full">+ <TabsTrigger value="action" className="flex-1">+ <Text>{t("sections.action")}</Text>+ {unreadCount > 0 ? (+ <Text className="text-xs text-brand">{unreadCount}</Text>+ ) : null}+ </TabsTrigger>+ <TabsTrigger value="activity" className="flex-1">+ <Text>{t("sections.activity")}</Text>+ </TabsTrigger>+ </TabsList>+ </Tabs>+ </View>{isLoading ? (<InboxLoading />) : error ? (@@ -137,7 +161,10 @@ export default function Inbox() {</Button></View>) : !data || data.length === 0 ? (- <InboxEmpty iconColor={THEME[colorScheme].mutedForeground} />+ <InboxEmpty+ section={section}+ iconColor={THEME[colorScheme].mutedForeground}+ />) : (<FlatListdata={data}@@ -180,17 +207,27 @@ function InboxLoading() {);}-function InboxEmpty({ iconColor }: { iconColor: string }) {+function InboxEmpty({+ section,+ iconColor,+}: {+ section: InboxSection;+ iconColor: string;+}) {const { t } = useT("inbox");return (<View className="flex-1 items-center justify-center px-8 gap-3"><Ionicons name="mail-open-outline" size={42} color={iconColor} /><Text className="text-base font-medium text-foreground text-center">- {t("empty.title")}+ {section === "activity"+ ? t("sections.activity_empty")+ : t("empty.title")}</Text><Text className="text-sm text-muted-foreground text-center">- {t("empty.body")}+ {section === "activity"+ ? t("sections.activity_empty_body")+ : t("empty.body")}</Text></View>);diff --git a/apps/mobile/app/(app)/[workspace]/issue/[id].tsx b/apps/mobile/app/(app)/[workspace]/issue/[id].tsxindex 91f2b8e4dc..753af24add 100644--- a/apps/mobile/app/(app)/[workspace]/issue/[id].tsx+++ b/apps/mobile/app/(app)/[workspace]/issue/[id].tsx@@ -40,6 +40,7 @@ import { useAuthStore } from "@/data/auth-store";import { useIssueRealtime } from "@/data/realtime/use-issue-realtime";import { useWorkspaceStore } from "@/data/workspace-store";import { useViewedIssuesStore } from "@/data/viewed-issues-store";+import { useMarkInboxReadOnOpen } from "@/lib/use-mark-inbox-read-on-open";import { useCommentSelectStore } from "@/data/comment-select-store";import { useReplyTargetStore } from "@/data/stores/reply-target-store";import { useT } from "@/lib/i18n";@@ -78,6 +79,8 @@ export default function IssueDetail() {}}, [wsId, id]);+ useMarkInboxReadOnOpen(wsId, id);+// Screen-scoped composer state — clear on unmount so re-entering the// issue starts from a clean slate (no stale text-selection comment id,// no stale "Replying to X" target). Both stores are singletons used bydiff --git a/apps/mobile/app/(app)/[workspace]/more/settings.tsx b/apps/mobile/app/(app)/[workspace]/more/settings.tsxindex 1acf056f8c..df0c3a30b9 100644--- a/apps/mobile/app/(app)/[workspace]/more/settings.tsx+++ b/apps/mobile/app/(app)/[workspace]/more/settings.tsx@@ -8,7 +8,7 @@** Subscreens push under more/settings/:* - more/settings/profile — edit name + avatar- * - more/settings/notifications — per-group inbox + system toggles+ * - more/settings/notifications — Inbox routing per kind + system toggle** Theme picker stays inline (3 fixed options, fits in one section).*/diff --git a/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx b/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsxindex 0bef74efa7..149457641f 100644--- a/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx+++ b/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx@@ -1,82 +1,72 @@/**- * Notification preferences subscreen. 6 inbox groups + system_notifications- * toggle, each backed by an optimistic PATCH /api/notification-preferences.+ * Inbox settings subscreen: where each kind of notification goes (Needs+ * action / Activity / Off) plus the system_notifications toggle, each backed+ * by an optimistic PATCH /api/notification-preferences.*- * Copy mirrors packages/views/settings/components/notifications-tab.tsx.- * Group labels describe the same server-side semantics as web; divergent- * labels would violate behavioral parity (apps/mobile/CLAUDE.md).+ * Copy and routing rules mirror packages/views/settings/components/+ * notifications-tab.tsx; both resolve routes through+ * @multica/core/notification-preferences/routes so the two never disagree.*/-import { ActivityIndicator, ScrollView, View } from "react-native";+import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";import { useQuery } from "@tanstack/react-query";+import { Ionicons } from "@expo/vector-icons";import type {- NotificationGroupKey,NotificationPreferences,+ NotificationRoute,} from "@multica/core/types";+import {+ NOTIFICATION_ROUTE_KINDS,+ notificationRoutesAreDefault,+ resolveNotificationRoute,+ withDefaultNotificationRoutes,+ withNotificationRoute,+} from "@multica/core/notification-preferences/routes";import { Text } from "@/components/ui/text";import { Switch } from "@/components/ui/switch";import { Separator } from "@/components/ui/separator";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";import { useWorkspaceStore } from "@/data/workspace-store";import { notificationPreferenceOptions } from "@/data/queries/notification-preferences";import { useUpdateNotificationPreferences } from "@/data/mutations/notification-preferences";import { useT } from "@/lib/i18n";+import { useColorScheme } from "@/lib/use-color-scheme";+import { THEME } from "@/lib/theme";-const INBOX_GROUPS: {- key: Exclude<NotificationGroupKey, "system_notifications">;- labelKey: string;- descriptionKey?: string;-}[] = [- {- key: "assignments",- labelKey: "groups.assignments",- descriptionKey: "groups.assignments_description",- },- {- key: "status_changes",- labelKey: "groups.status_changes",- },- {- key: "comments",- labelKey: "groups.comments",- descriptionKey: "groups.comments_description",- },- {- key: "mentions",- labelKey: "groups.mentions",- descriptionKey: "groups.mentions_description",- },- {- key: "updates",- labelKey: "groups.updates",- descriptionKey: "groups.updates_description",- },- {- key: "agent_activity",- labelKey: "groups.agent_activity",- descriptionKey: "groups.agent_activity_description",- },-];+const ROUTES: readonly NotificationRoute[] = ["action", "activity", "muted"];++function RouteMark({ route, color }: { route: NotificationRoute; color: string }) {+ if (route === "action") {+ return (+ <View className="size-4 items-center justify-center">+ <View className="size-1.5 rounded-full bg-brand" />+ </View>+ );+ }+ return (+ <Ionicons+ name={route === "activity" ? "eye-outline" : "notifications-off-outline"}+ size={16}+ color={color}+ />+ );+}export default function NotificationsSettingsScreen() {const wsId = useWorkspaceStore((s) => s.currentWorkspaceId);const { t } = useT("settings");+ const { colorScheme } = useColorScheme();+ const theme = THEME[colorScheme];const { data, isLoading, error } = useQuery(notificationPreferenceOptions(wsId),);const mutation = useUpdateNotificationPreferences();const preferences: NotificationPreferences = data?.preferences ?? {};-- const onToggle = (key: NotificationGroupKey, enabled: boolean) => {- const next: NotificationPreferences = { ...preferences };- if (enabled) {- // Default is "all" — omitting the key keeps the object clean.- delete next[key];- } else {- next[key] = "muted";- }- mutation.mutate(next);- };-const systemEnabled = preferences.system_notifications !== "muted";if (isLoading) {@@ -97,34 +87,109 @@ export default function NotificationsSettingsScreen() {);}+ const routesAreDefault = notificationRoutesAreDefault(preferences);+return (<ScrollViewclassName="flex-1 bg-background"contentContainerClassName="px-4 py-4 gap-6"><Section- title={t("groups.inbox_notifications")}+ title={t("routing.title")}+ description={t("routing.description")}+ action={+ <Pressable+ accessibilityRole="button"+ disabled={routesAreDefault}+ onPress={() =>+ mutation.mutate(withDefaultNotificationRoutes(preferences))+ }+ className="flex-row items-center gap-1 active:opacity-60"+ style={{ opacity: routesAreDefault ? 0.4 : 1 }}+ >+ <Ionicons name="refresh" size={14} color={theme.mutedForeground} />+ <Text className="text-xs text-muted-foreground">+ {t("routing.reset")}+ </Text>+ </Pressable>+ }>- {INBOX_GROUPS.map((group, idx) => {- const enabled = preferences[group.key] !== "muted";- const isLast = idx === INBOX_GROUPS.length - 1;+ {NOTIFICATION_ROUTE_KINDS.map((kind, idx) => {+ const route = resolveNotificationRoute(preferences, kind);+ const isLast = idx === NOTIFICATION_ROUTE_KINDS.length - 1;return (- <View key={group.key}>+ <View key={kind.key}><View className="flex-row items-center px-4 py-3 gap-3"><View className="flex-1"><Text className="text-base font-medium text-foreground">- {t(group.labelKey)}+ {t(`routing.kinds.${kind.key}.label`)}+ </Text>+ <Text className="text-xs text-muted-foreground mt-0.5">+ {t(`routing.kinds.${kind.key}.description`)}</Text>- {group.descriptionKey ? (- <Text className="text-xs text-muted-foreground mt-0.5">- {t(group.descriptionKey)}- </Text>- ) : null}</View>- <Switch- checked={enabled}- onCheckedChange={(checked) => onToggle(group.key, checked)}- />+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={t(`routing.kinds.${kind.key}.label`)}+ className="flex-row items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 active:bg-accent"+ >+ <RouteMark route={route} color={theme.mutedForeground} />+ <Text+ className={+ route === "muted"+ ? "text-sm text-muted-foreground"+ : "text-sm text-foreground"+ }+ >+ {t(`routing.routes.${route}.label`)}+ </Text>+ <Ionicons+ name="chevron-down"+ size={14}+ color={theme.mutedForeground}+ />+ </Pressable>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-64 p-1">+ {ROUTES.map((value) => (+ <DropdownMenuItem+ key={value}+ className="items-start"+ onPress={() => {+ if (value !== route) {+ mutation.mutate(+ withNotificationRoute(preferences, kind, value),+ );+ }+ }}+ >+ <View className="mt-0.5">+ <RouteMark+ route={value}+ color={theme.mutedForeground}+ />+ </View>+ <View className="flex-1">+ <Text className="text-sm">+ {t(`routing.routes.${value}.label`)}+ </Text>+ <Text className="text-xs text-muted-foreground">+ {t(`routing.routes.${value}.description`)}+ </Text>+ </View>+ {value === route ? (+ <Ionicons+ name="checkmark"+ size={16}+ color={theme.foreground}+ />+ ) : null}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu></View>{!isLast ? <Separator /> : null}</View>@@ -132,9 +197,7 @@ export default function NotificationsSettingsScreen() {})}</Section>- <Section- title={t("groups.system")}- >+ <Section title={t("groups.system")}><View className="flex-row items-center px-4 py-3 gap-3"><View className="flex-1"><Text className="text-base font-medium text-foreground">@@ -146,9 +209,12 @@ export default function NotificationsSettingsScreen() {</View><Switchchecked={systemEnabled}- onCheckedChange={(checked) =>- onToggle("system_notifications", checked)- }+ onCheckedChange={(checked) => {+ const next: NotificationPreferences = { ...preferences };+ if (checked) delete next.system_notifications;+ else next.system_notifications = "muted";+ mutation.mutate(next);+ }}/></View></Section>@@ -159,18 +225,23 @@ export default function NotificationsSettingsScreen() {function Section({title,description,+ action,children,}: {title: string;description?: string;+ action?: React.ReactNode;children: React.ReactNode;}) {return (<View className="gap-2"><View className="px-1">- <Text className="text-xs uppercase tracking-wider text-muted-foreground">- {title}- </Text>+ <View className="flex-row items-center justify-between gap-3">+ <Text className="text-xs uppercase tracking-wider text-muted-foreground">+ {title}+ </Text>+ {action}+ </View>{description ? (<Text className="text-xs text-muted-foreground mt-1">{description}diff --git a/apps/mobile/components/inbox/inbox-row.tsx b/apps/mobile/components/inbox/inbox-row.tsxindex ff59f40a6d..599fb5374c 100644--- a/apps/mobile/components/inbox/inbox-row.tsx+++ b/apps/mobile/components/inbox/inbox-row.tsx@@ -12,6 +12,7 @@*/import { Pressable, View } from "react-native";import type { InboxItem } from "@multica/core/types";+import { isInboxItemUnread } from "@multica/core/inbox/section";import { Text } from "@/components/ui/text";import { ActorAvatar } from "@/components/ui/actor-avatar";import { StatusIcon } from "@/components/ui/status-icon";@@ -27,7 +28,7 @@ interface Props {}export function InboxRow({ item, onPress }: Props) {- const isUnread = !item.read;+ const isUnread = isInboxItemUnread(item);const { categoryOf, colorOf, iconOf } = useIssueStatuses();const displayTitle = getInboxDisplayTitle(item);const actorType = item.actor_type ?? item.recipient_type;diff --git a/apps/mobile/data/api.ts b/apps/mobile/data/api.tsindex 9d89a10d19..9004f800ab 100644--- a/apps/mobile/data/api.ts+++ b/apps/mobile/data/api.ts@@ -27,6 +27,7 @@ import type {CreateProjectResourceRequest,InboxItem,InboxWorkspaceUnread,+ MarkIssueInboxReadResult,Issue,IssueLabelsResponse,Label,@@ -99,6 +100,7 @@ import {EMPTY_COMMENT,EMPTY_INBOX_LIST,EMPTY_INBOX_UNREAD_SUMMARY,+ UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT,EMPTY_ISSUE_FALLBACK,EMPTY_LIST_LABELS_RESPONSE,EMPTY_LIST_PROJECT_RESOURCES_RESPONSE,@@ -115,6 +117,7 @@ import {EMPTY_WORKSPACE_LIST,InboxListSchema,InboxUnreadSummarySchema,+ MarkIssueInboxReadResultSchema,NotificationPreferenceResponseSchema,ListLabelsResponseSchema,ListProjectResourcesResponseSchema,@@ -537,6 +540,20 @@ class ApiClient {// markInboxRead above and the project write endpoints): a malformed// archive response should surface naturally so the optimistic patch// rolls back.+ // Marks every active notification on the issue read; called when an issue+ // is opened so reading it anywhere settles the inbox too.+ async markIssueInboxRead(issueId: string): Promise<MarkIssueInboxReadResult> {+ const raw = await this.fetch<unknown>(`/api/inbox/issues/${issueId}/read`, {+ method: "POST",+ });+ return parseWithFallback(+ raw,+ MarkIssueInboxReadResultSchema,+ UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT,+ { endpoint: "POST /api/inbox/issues/:id/read" },+ );+ }+async archiveInbox(id: string): Promise<InboxItem> {return this.fetch<InboxItem>(`/api/inbox/${id}/archive`, { method: "POST" });}diff --git a/apps/mobile/data/inbox-schema.test.ts b/apps/mobile/data/inbox-schema.test.tsindex bf3086abd6..1d34d00c71 100644--- a/apps/mobile/data/inbox-schema.test.ts+++ b/apps/mobile/data/inbox-schema.test.ts@@ -1,5 +1,11 @@import { describe, expect, it } from "vitest";-import { InboxListSchema, InboxUnreadSummarySchema } from "./schemas";+import { parseWithFallback } from "@/lib/parse-response";+import {+ InboxListSchema,+ InboxUnreadSummarySchema,+ MarkIssueInboxReadResultSchema,+ UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT,+} from "./schemas";/*** Tests for mobile's CLIENT-SIDE parsing of GET /api/inbox.@@ -48,6 +54,29 @@ describe("inbox list schema", () => {expect(parsed.success && parsed.data[0]?.details?.to).toBe("in_review");});+ it("keeps the inbox section and tolerates a missing or unknown one", () => {+ const row = (section?: unknown) => ({+ id: "inbox-s",+ recipient_type: "member",+ type: "status_changed",+ ...(section === undefined ? {} : { section }),+ });++ const parsed = InboxListSchema.safeParse([+ row("activity"),+ row("action"),+ row(),+ row("someday"),+ ]);+ expect(parsed.success).toBe(true);+ expect(parsed.success && parsed.data.map((i) => i.section)).toEqual([+ "activity",+ "action",+ undefined,+ undefined,+ ]);+ });+it("rejects a numeric details value", () => {const badRow = {id: "inbox-2",@@ -143,3 +172,23 @@ describe("inbox unread summary schema", () => {).toBe(false);});});++describe("mark issue inbox read result schema", () => {+ const parse = (raw: unknown) =>+ parseWithFallback(+ raw,+ MarkIssueInboxReadResultSchema,+ UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT,+ { endpoint: "POST /api/inbox/issues/:id/read" },+ );++ it("keeps the server's count", () => {+ expect(parse({ count: 2 })).toEqual({ count: 2 });+ });++ it("reports an unknown count for a malformed reply, so the caller refreshes", () => {+ for (const raw of [null, "<html>", { count: "2" }, {}]) {+ expect(parse(raw)).toEqual({ count: null });+ }+ });+});diff --git a/apps/mobile/data/mutations/inbox.ts b/apps/mobile/data/mutations/inbox.tsindex ef0f2c4426..696e28214f 100644--- a/apps/mobile/data/mutations/inbox.ts+++ b/apps/mobile/data/mutations/inbox.ts@@ -18,6 +18,9 @@* packages/core/inbox/mutations.ts:37-46). Visually the row disappears* because `deduplicateInboxItems` (apps/mobile/lib/inbox-display.ts)* filters archived items out before render.+ * - mark-issue-read: flip `read` on every row of the opened issue; refresh+ * unless the server confirms nothing changed (an unreadable reply counts+ * as a change).* - mark-all-read: flip `read` to true on every non-archived row (matches* web; the server-side query does the same predicate).* - archive batch (all / all-read / completed): no optimistic patch — the@@ -28,6 +31,7 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import type { QueryClient } from "@tanstack/react-query";import type { InboxItem } from "@multica/core/types";+import { inboxItemSection } from "@multica/core/inbox/section";import { api } from "@/data/api";import { inboxKeys } from "@/data/queries/inbox";import {@@ -94,16 +98,20 @@ export function useArchiveInbox() {const key = inboxKeys.list(wsId);await qc.cancelQueries({ queryKey: key });const prev = qc.getQueryData<InboxItem[]>(key);- // Match web: archive every row that shares the same issue_id — the- // single archive endpoint archives all sibling rows server-side too- // (`server/internal/queries/inbox.sql` UPDATE … WHERE issue_id = ?).+ // Match web: archive the rows that share the same issue_id, as the+ // single archive endpoint does server-side — every sibling for an+ // action row, only the issue's other activity for an activity row.// Patching only the tapped row would let dedup'd siblings briefly// resurface between the request and the WS invalidate.const target = prev?.find((i) => i.id === id);const issueId = target?.issue_id ?? null;+ const activityOnly = target ? inboxItemSection(target) === "activity" : false;qc.setQueryData<InboxItem[]>(key, (old) =>old?.map((item) =>- item.id === id || (issueId && item.issue_id === issueId)+ item.id === id ||+ (issueId &&+ item.issue_id === issueId &&+ (!activityOnly || inboxItemSection(item) === "activity"))? { ...item, archived: true }: item,),@@ -119,6 +127,40 @@ export function useArchiveInbox() {});}+/**+ * Mark every notification on an issue read when the issue is opened, so+ * reading it from anywhere settles the inbox (web: useMarkIssueInboxRead in+ * packages/core/inbox/mutations.ts). Nothing is refreshed when nothing+ * changed.+ */+export function useMarkIssueInboxRead() {+ const qc = useQueryClient();+ const wsId = useWorkspaceStore((s) => s.currentWorkspaceId);++ return useMutation({+ mutationFn: (issueId: string) => api.markIssueInboxRead(issueId),+ onMutate: async (issueId) => {+ const key = inboxKeys.list(wsId);+ await qc.cancelQueries({ queryKey: key });+ const prev = qc.getQueryData<InboxItem[]>(key);+ qc.setQueryData<InboxItem[]>(key, (old) =>+ old?.map((item) =>+ item.issue_id === issueId && !item.archived && !item.read+ ? { ...item, read: true }+ : item,+ ),+ );+ return { prev, key };+ },+ onError: (_err, _issueId, ctx) => {+ if (ctx?.prev) qc.setQueryData(ctx.key, ctx.prev);+ },+ onSuccess: (result) => {+ if (result.count !== 0) refreshInboxAfterWrite(qc, wsId);+ },+ });+}+export function useMarkAllInboxRead() {const qc = useQueryClient();const wsId = useWorkspaceStore((s) => s.currentWorkspaceId);diff --git a/apps/mobile/data/realtime/use-inbox-realtime.ts b/apps/mobile/data/realtime/use-inbox-realtime.tsindex aa18618173..2240c51df2 100644--- a/apps/mobile/data/realtime/use-inbox-realtime.ts+++ b/apps/mobile/data/realtime/use-inbox-realtime.ts@@ -25,6 +25,7 @@* no replay buffer in v1).*/import { useQueryClient } from "@tanstack/react-query";+import { inboxItemSection } from "@multica/core/inbox/section";import { useWSSubscriptions } from "@/lib/use-ws-subscriptions";import {dropInboxItemsByIssue,@@ -48,7 +49,13 @@ export function useInboxRealtime() {return [// Inbox-domain events: refetch the inbox list and the badge count.- ws.on("inbox:new", invalidate),+ // Activity never counts as unread, so it cannot move the badge.+ ws.on("inbox:new", (payload) => {+ void refreshInboxList(qc, wsId);+ if (inboxItemSection(payload.item) !== "activity") {+ void refreshInboxUnreadSummary(qc);+ }+ }),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 —diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.tsindex 8f914d86e4..16050d4055 100644--- a/apps/mobile/data/schemas.ts+++ b/apps/mobile/data/schemas.ts@@ -21,6 +21,7 @@ import type {Comment,InboxItem,InboxWorkspaceUnread,+ MarkIssueInboxReadResult,IssueLabelsResponse,Label,ListLabelsResponse,@@ -582,6 +583,10 @@ const InboxItemSchema: z.ZodType<InboxItem> = z.object({issue_status: z.string().nullable().default(null) as unknown as z.ZodType<InboxItem["issue_status"]>,+ // Inbox section (packages/core/types/inbox.ts InboxSection). A missing or+ // unknown value reads as "action" through inboxItemSection, the behavior+ // before sections existed.+ section: z.enum(["action", "activity"]).optional().catch(undefined),read: z.boolean().default(false),archived: z.boolean().default(false),created_at: z.string().default(""),@@ -609,6 +614,16 @@ export const InboxUnreadSummarySchema = z.default([]);export const EMPTY_INBOX_UNREAD_SUMMARY: InboxWorkspaceUnread[] = [];+// `POST /api/inbox/issues/{id}/read`. Mirrors MarkIssueInboxReadResultSchema+// in packages/core/api/schemas.ts: a malformed body yields an unknown (null)+// count, which the mutation treats as a change and refreshes.+export const MarkIssueInboxReadResultSchema = z+ .object({ count: z.number() })+ .loose();+export const UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT: MarkIssueInboxReadResult = {+ count: null,+};+export const MemberWithUserSchema: z.ZodType<MemberWithUser> = z.object({id: z.string(),workspace_id: z.string().default(""),diff --git a/apps/mobile/lib/inbox-display.test.ts b/apps/mobile/lib/inbox-display.test.tsindex 25b5376e8d..0a78cff01d 100644--- a/apps/mobile/lib/inbox-display.test.ts+++ b/apps/mobile/lib/inbox-display.test.ts@@ -5,6 +5,7 @@ import {getAutopilotQuotaBody,getInboxDisplayTitle,getInboxNavigationTarget,+ groupInboxItemsBySection,} from "./inbox-display";function item(overrides: Partial<InboxItem>): InboxItem {@@ -58,6 +59,21 @@ describe("deduplicateInboxItems", () => {});});+describe("groupInboxItemsBySection", () => {+ it("splits sections per issue like web, so activity does not move the action row", () => {+ const { action, activity } = groupInboxItemsBySection([+ item({ id: "mention", type: "mentioned", section: "action", created_at: "2026-06-15T08:00:00Z" }),+ item({ id: "legacy", issue_id: "issue-2", type: "issue_assigned", created_at: "2026-06-15T08:01:00Z" }),+ item({ id: "status", type: "status_changed", section: "activity", created_at: "2026-06-15T08:02:00Z" }),+ item({ id: "reply", section: "activity", created_at: "2026-06-15T08:03:00Z" }),+ item({ id: "gone", issue_id: "issue-3", section: "activity", archived: true }),+ ]);++ expect(action.map((i) => i.id)).toEqual(["legacy", "mention"]);+ expect(activity.map((i) => i.id)).toEqual(["reply"]);+ });+});+describe("getInboxDisplayTitle", () => {it("uses the same stable quota title as web instead of backend fallback copy", () => {expect(diff --git a/apps/mobile/lib/inbox-display.ts b/apps/mobile/lib/inbox-display.tsindex 5cff69fa12..c125edcec0 100644--- a/apps/mobile/lib/inbox-display.ts+++ b/apps/mobile/lib/inbox-display.ts@@ -6,7 +6,8 @@* the title a user sees in the mobile inbox MUST match what they see on* web for the same item. When the web version changes, sync this file.*/-import type { InboxItem } from "@multica/core/types";+import type { InboxItem, InboxSection } from "@multica/core/types";+import { inboxItemSection } from "@multica/core/inbox/section";import { i18n } from "@/lib/i18n/singleton";function formatResetAt(value: string | undefined): string {@@ -135,7 +136,30 @@ export function getInboxNavigationTarget(* 5. Sort the result newest-first.*/export function deduplicateInboxItems(items: InboxItem[]): InboxItem[] {+ return groupInboxItemsByIssue(items.filter((i) => !i.archived));+}++/**+ * Active items split into the two Inbox sections, each grouped one entry per+ * issue. Mirrors packages/core/inbox/queries.ts groupInboxItemsBySection: an+ * issue with both kinds appears in both sections, and activity never moves+ * its action entry.+ */+export function groupInboxItemsBySection(+ items: InboxItem[],+): Record<InboxSection, InboxItem[]> {const active = items.filter((i) => !i.archived);+ return {+ action: groupInboxItemsByIssue(+ active.filter((i) => inboxItemSection(i) === "action"),+ ),+ activity: groupInboxItemsByIssue(+ active.filter((i) => inboxItemSection(i) === "activity"),+ ),+ };+}++function groupInboxItemsByIssue(active: InboxItem[]): InboxItem[] {const groups = new Map<string, InboxItem[]>();for (const item of active) {const key = item.issue_id ?? item.id;diff --git a/apps/mobile/lib/use-mark-inbox-read-on-open.test.ts b/apps/mobile/lib/use-mark-inbox-read-on-open.test.tsnew file mode 100644index 0000000000..bae160a2b9--- /dev/null+++ b/apps/mobile/lib/use-mark-inbox-read-on-open.test.ts@@ -0,0 +1,116 @@+// @vitest-environment node+import { QueryClient } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { InboxItem } from "@multica/core/types";+import { inboxKeys } from "@/data/queries/inbox";+import { useMarkInboxReadOnOpen } from "./use-mark-inbox-read-on-open";++const hook = vi.hoisted(() => ({+ client: undefined as unknown,+ summary: { data: 0 as number | undefined, isSuccess: true, isFetching: false },+ effect: undefined as (() => void) | undefined,+ ref: { current: null as string | null },+ markRead: vi.fn(),+}));++// Run the hook's decision headlessly: the effect is captured and invoked by+// the test, the summary query's state is set per case, and the list cache is+// a real QueryClient so staleness and invalidation behave as in the app.+vi.mock("react", () => ({+ useEffect: (effect: () => void) => { hook.effect = effect; },+ useRef: () => hook.ref,+}));+vi.mock("@tanstack/react-query", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),+ useQuery: () => hook.summary,+ useQueryClient: () => hook.client,+}));+vi.mock("@/data/mutations/inbox", () => ({+ useMarkIssueInboxRead: () => ({ mutate: hook.markRead }),+}));+vi.mock("@/data/api", () => ({ api: {} }));++function item(overrides: Partial<InboxItem> = {}): InboxItem {+ return {+ id: "inbox-1",+ workspace_id: "ws-1",+ recipient_type: "member",+ recipient_id: "member-1",+ actor_type: "member",+ actor_id: "member-2",+ type: "mentioned",+ severity: "info",+ issue_id: "issue-1",+ title: "Issue",+ body: null,+ issue_status: null,+ section: "action",+ read: false,+ archived: false,+ created_at: "2026-11-02T08:00:00Z",+ details: null,+ ...overrides,+ };+}++let client: QueryClient;++const runEffect = () => hook.effect?.();++describe("useMarkInboxReadOnOpen", () => {+ beforeEach(() => {+ client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } });+ hook.client = client;+ hook.summary = { data: 1, isSuccess: true, isFetching: false };+ hook.ref.current = null;+ });+ afterEach(() => {+ client.clear();+ hook.markRead.mockReset();+ });++ it("marks the opened issue read when its unread row is cached", () => {+ client.setQueryData(inboxKeys.list("ws-1"), [item()]);+ useMarkInboxReadOnOpen("ws-1", "issue-1");+ runEffect();+ expect(hook.markRead).toHaveBeenCalledWith("issue-1");+ });++ it("skips when a fresh list holds only activity or read rows for the issue", () => {+ client.setQueryData(inboxKeys.list("ws-1"), [+ item({ id: "status", type: "status_changed", section: "activity" }),+ item({ id: "read", read: true }),+ ]);+ useMarkInboxReadOnOpen("ws-1", "issue-1");+ runEffect();+ expect(hook.markRead).not.toHaveBeenCalled();+ });++ it("ignores an invalidated list that only holds the issue's old read row", async () => {+ client.setQueryData(inboxKeys.list("ws-1"), [item({ read: true })]);+ await client.invalidateQueries({ queryKey: inboxKeys.list("ws-1"), refetchType: "none" });+ useMarkInboxReadOnOpen("ws-1", "issue-1");+ runEffect();+ expect(hook.markRead).toHaveBeenCalledWith("issue-1");+ });++ it("waits for a refetching zero summary instead of consuming the opening", () => {+ hook.summary = { data: 0, isSuccess: true, isFetching: true };+ useMarkInboxReadOnOpen("ws-1", "issue-1");+ runEffect();+ expect(hook.markRead).not.toHaveBeenCalled();+ expect(hook.ref.current).toBeNull();++ hook.summary = { data: 1, isSuccess: true, isFetching: false };+ useMarkInboxReadOnOpen("ws-1", "issue-1");+ runEffect();+ expect(hook.markRead).toHaveBeenCalledWith("issue-1");+ });++ it("skips once the settled summary reports nothing unread", () => {+ hook.summary = { data: 0, isSuccess: true, isFetching: false };+ useMarkInboxReadOnOpen("ws-1", "issue-1");+ runEffect();+ expect(hook.markRead).not.toHaveBeenCalled();+ });+});diff --git a/apps/mobile/lib/use-mark-inbox-read-on-open.ts b/apps/mobile/lib/use-mark-inbox-read-on-open.tsnew file mode 100644index 0000000000..c8a59ef542--- /dev/null+++ b/apps/mobile/lib/use-mark-inbox-read-on-open.ts@@ -0,0 +1,54 @@+/**+ * Settles an issue's inbox notifications when its screen opens, so opening it+ * from a link, search, or the issue list clears the inbox too — the same+ * event is never cleared twice. Mirrors web's useMarkInboxReadWhileViewing+ * (packages/views/issues/hooks/use-mark-inbox-read-while-viewing.ts).+ *+ * Runs once per opened issue. Skips the request only on fresh evidence that+ * nothing can be unread: a settled workspace unread count of zero, or an+ * up-to-date inbox list with no unread row for this issue. A refetching+ * summary is waited for and a stale list is ignored.+ */+import { useEffect, useRef } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import type { InboxItem } from "@multica/core/types";+import { isInboxItemUnread } from "@multica/core/inbox/section";+import { useMarkIssueInboxRead } from "@/data/mutations/inbox";+import { inboxKeys, inboxUnreadSummaryOptions } from "@/data/queries/inbox";++export function useMarkInboxReadOnOpen(+ wsId: string | null,+ issueId: string | undefined,+) {+ const qc = useQueryClient();+ const { data: workspaceUnread, isSuccess, isFetching } = useQuery({+ ...inboxUnreadSummaryOptions(wsId),+ select: (summary) =>+ summary.find((s) => s.workspace_id === wsId)?.count ?? 0,+ });+ const { mutate: markRead } = useMarkIssueInboxRead();+ const openedIssueId = useRef<string | null>(null);++ useEffect(() => {+ if (!wsId || !issueId || !isSuccess || isFetching) return;+ if (openedIssueId.current === issueId) return;+ openedIssueId.current = issueId;+ if (workspaceUnread === 0) return;+ const listQuery = qc.getQueryCache().find<InboxItem[]>({+ queryKey: inboxKeys.list(wsId),+ exact: true,+ });+ const list =+ listQuery && !listQuery.isStale() ? listQuery.state.data : undefined;+ if (+ list &&+ !list.some(+ (item) =>+ item.issue_id === issueId && !item.archived && isInboxItemUnread(item),+ )+ ) {+ return;+ }+ markRead(issueId);+ }, [wsId, issueId, isSuccess, isFetching, workspaceUnread, qc, markRead]);+}diff --git a/apps/mobile/locales/en/inbox.json b/apps/mobile/locales/en/inbox.jsonindex 62520d96d6..bf5f91c8fc 100644--- a/apps/mobile/locales/en/inbox.json+++ b/apps/mobile/locales/en/inbox.json@@ -4,6 +4,12 @@"title": "You're all caught up","body": "Notifications and agent updates appear here."},+ "sections": {+ "action": "Needs action",+ "activity": "Activity",+ "activity_empty": "No recent activity",+ "activity_empty_body": "Status changes and agent replies on your issues appear here."+ },"actions": {"mark_read": "Mark read","mark_unread": "Mark unread",diff --git a/apps/mobile/locales/en/navigation.json b/apps/mobile/locales/en/navigation.jsonindex 4c582d3acd..6dcbf67ce6 100644--- a/apps/mobile/locales/en/navigation.json+++ b/apps/mobile/locales/en/navigation.json@@ -17,7 +17,7 @@"projects": "Projects","settings": "Settings","profile": "Profile",- "notifications": "Notifications",+ "notifications": "Inbox","search": "Search","issue": "Issue","project": "Project",diff --git a/apps/mobile/locales/en/settings.json b/apps/mobile/locales/en/settings.jsonindex 83e97f3aae..80129ac15f 100644--- a/apps/mobile/locales/en/settings.json+++ b/apps/mobile/locales/en/settings.json@@ -6,7 +6,7 @@"sign_out_message": "You'll need to sign in again to use Multica on this device.","workspace": "Workspace","workspaces": "Workspaces",- "notifications_subtitle": "Inbox and system alerts",+ "notifications_subtitle": "Where notifications go, system notifications","load_failed": "Failed to load workspaces"},"profile": {@@ -31,7 +31,7 @@"chinese_traditional": "Traditional Chinese"},"notifications": {- "title": "Notifications",+ "title": "Inbox","issues": "Issues","inbox": "Inbox","chat": "Chat",@@ -66,20 +66,61 @@},"email_fixed": "Email is set at sign-up and can't be changed here.","groups": {- "assignments": "Assignments",- "assignments_description": "Assigned or unassigned.",- "status_changes": "Status changes",- "comments": "Comments",- "comments_description": "New comments on issues you're subscribed to.",- "mentions": "Mentions",- "mentions_description": "When someone @mentions you, including @all and @squad.",- "updates": "Issue updates",- "updates_description": "Edits to title, description, labels, priority, or due date.",- "agent_activity": "Agent activity",- "agent_activity_description": "When an agent run fails.",- "inbox_notifications": "Inbox notifications","system": "System","system_notifications": "System notifications","system_description": "Account changes, security alerts, product updates."+ },+ "routing": {+ "title": "Routing",+ "description": "Changes apply to new notifications.",+ "reset": "Restore defaults",+ "routes": {+ "action": {+ "label": "Needs action",+ "description": "Counts as unread"+ },+ "activity": {+ "label": "Activity",+ "description": "Recorded quietly, never unread"+ },+ "muted": {+ "label": "Off",+ "description": "Not in the Inbox; still visible on the issue"+ }+ },+ "kinds": {+ "assigned": {+ "label": "Assigned to me",+ "description": "When an issue is assigned to you"+ },+ "mentions": {+ "label": "Mentions",+ "description": "When someone @mentions you, including @all and @squad"+ },+ "member_comments": {+ "label": "Member comments",+ "description": "When a member comments on an issue you follow"+ },+ "agent_failures": {+ "label": "Agent errors",+ "description": "When an agent run fails or is blocked and needs you"+ },+ "status_changes": {+ "label": "Status changes",+ "description": "When an issue you follow changes status"+ },+ "assignee_changes": {+ "label": "Assignee changes",+ "description": "When an issue changes assignee, or you are unassigned"+ },+ "updates": {+ "label": "Priority and dates",+ "description": "When priority, start date, or due date changes"+ },+ "agent_comments": {+ "label": "Agent comments",+ "description": "When an agent replies on an issue you follow"+ }+ }}}diff --git a/apps/mobile/locales/zh-Hans/inbox.json b/apps/mobile/locales/zh-Hans/inbox.jsonindex 4c95d9d92a..5d18761ce7 100644--- a/apps/mobile/locales/zh-Hans/inbox.json+++ b/apps/mobile/locales/zh-Hans/inbox.json@@ -4,6 +4,12 @@"title": "已处理全部通知","body": "通知和智能体更新会显示在这里。"},+ "sections": {+ "action": "需要处理",+ "activity": "动态",+ "activity_empty": "暂无动态",+ "activity_empty_body": "你的任务上的状态变更和智能体回复会显示在这里。"+ },"actions": {"mark_read": "标记已读","mark_unread": "标记未读",diff --git a/apps/mobile/locales/zh-Hans/navigation.json b/apps/mobile/locales/zh-Hans/navigation.jsonindex 0259dc8f7f..f5d4a2db57 100644--- a/apps/mobile/locales/zh-Hans/navigation.json+++ b/apps/mobile/locales/zh-Hans/navigation.json@@ -17,7 +17,7 @@"projects": "项目","settings": "设置","profile": "个人资料",- "notifications": "通知",+ "notifications": "收件箱","search": "搜索","issue": "任务","project": "项目",diff --git a/apps/mobile/locales/zh-Hans/settings.json b/apps/mobile/locales/zh-Hans/settings.jsonindex b347ca1ddc..9a7facd6c2 100644--- a/apps/mobile/locales/zh-Hans/settings.json+++ b/apps/mobile/locales/zh-Hans/settings.json@@ -6,7 +6,7 @@"sign_out_message": "你需要重新登录才能在此设备上使用 Multica。","workspace": "工作区","workspaces": "工作区",- "notifications_subtitle": "收件箱和系统提醒",+ "notifications_subtitle": "通知去向和系统通知","load_failed": "工作区加载失败"},"profile": {@@ -31,7 +31,7 @@"chinese_traditional": "繁体中文"},"notifications": {- "title": "通知",+ "title": "收件箱","issues": "任务","inbox": "收件箱","chat": "聊天",@@ -66,22 +66,61 @@},"email_fixed": "邮箱在注册时设置,无法在这里修改。","groups": {- "assignments": "分配给我的",- "assignments_description": "任务分配给我或取消分配给我时。",- "status_changes": "状态变更",- "comments": "评论",- "comments_description": "你订阅的任务有新评论时。",- "mentions": "提及",- "mentions_description": "有人用 @ 提到你时,包括 @all 和 @squad。",- "updates": "任务更新",- "updates_description": "标题、描述、标签、优先级或截止日期变更时。",- "agent_activity": "智能体动态",- "agent_activity_description": "智能体运行失败时。",- "inbox_notifications": "收件箱通知","system": "系统","system_notifications": "系统通知","system_description": "账号变更、安全提醒和产品更新。"},- "groups.assignments_description": "任务分配给我或取消分配给我时。",- "groups.mentions_description": "有人用 @ 提到你时,包括 @all 和 @squad。"+ "routing": {+ "title": "通知去向",+ "description": "更改只影响之后的新通知。",+ "reset": "恢复默认",+ "routes": {+ "action": {+ "label": "需要处理",+ "description": "计入未读"+ },+ "activity": {+ "label": "动态",+ "description": "安静记录,不计未读"+ },+ "muted": {+ "label": "关闭",+ "description": "不进收件箱,在任务里仍能看到"+ }+ },+ "kinds": {+ "assigned": {+ "label": "分配给我",+ "description": "任务分配给你时"+ },+ "mentions": {+ "label": "提及",+ "description": "有人 @ 你时,包括 @all 和 @squad"+ },+ "member_comments": {+ "label": "成员评论",+ "description": "成员在你订阅的任务里发表评论时"+ },+ "agent_failures": {+ "label": "智能体出错",+ "description": "智能体运行失败或被阻塞、需要你介入时"+ },+ "status_changes": {+ "label": "状态变更",+ "description": "你订阅的任务状态变化时"+ },+ "assignee_changes": {+ "label": "负责人变更",+ "description": "任务换了负责人,或你被取消分配时"+ },+ "updates": {+ "label": "优先级与日期",+ "description": "优先级、开始日期或截止日期变化时"+ },+ "agent_comments": {+ "label": "智能体评论",+ "description": "智能体在你订阅的任务里回复时"+ }+ }+ }}diff --git a/apps/mobile/locales/zh-Hant/inbox.json b/apps/mobile/locales/zh-Hant/inbox.jsonindex 657378c89c..7574a25381 100644--- a/apps/mobile/locales/zh-Hant/inbox.json+++ b/apps/mobile/locales/zh-Hant/inbox.json@@ -4,6 +4,12 @@"title": "已處理全部通知","body": "通知和 AI 代理更新會顯示在這裡。"},+ "sections": {+ "action": "需要處理",+ "activity": "動態",+ "activity_empty": "暫無動態",+ "activity_empty_body": "你的任務上的狀態變更和智能體回覆會顯示在這裡。"+ },"actions": {"mark_read": "標記已讀","mark_unread": "標記未讀",diff --git a/apps/mobile/locales/zh-Hant/navigation.json b/apps/mobile/locales/zh-Hant/navigation.jsonindex 1db2a6e2ba..33a1b4d713 100644--- a/apps/mobile/locales/zh-Hant/navigation.json+++ b/apps/mobile/locales/zh-Hant/navigation.json@@ -17,7 +17,7 @@"projects": "專案","settings": "設定","profile": "個人資料",- "notifications": "通知",+ "notifications": "收件箱","search": "搜尋","issue": "任務","project": "專案",diff --git a/apps/mobile/locales/zh-Hant/settings.json b/apps/mobile/locales/zh-Hant/settings.jsonindex 3b36d7b700..3387b52adb 100644--- a/apps/mobile/locales/zh-Hant/settings.json+++ b/apps/mobile/locales/zh-Hant/settings.json@@ -6,7 +6,7 @@"sign_out_message": "你需要重新登入才能在此裝置上使用 Multica。","workspace": "工作區","workspaces": "工作區",- "notifications_subtitle": "收件箱和系統提醒",+ "notifications_subtitle": "通知去向和系統通知","load_failed": "工作區載入失敗"},"profile": {@@ -31,7 +31,7 @@"chinese_traditional": "繁體中文"},"notifications": {- "title": "通知",+ "title": "收件箱","issues": "任務","inbox": "收件箱","chat": "聊天",@@ -66,22 +66,61 @@},"email_fixed": "信箱在註冊時設定,無法在這裡修改。","groups": {- "assignments": "分配給我的",- "assignments_description": "任務分配給我或取消分配給我時。",- "status_changes": "狀態變更",- "comments": "評論",- "comments_description": "你訂閱的任務有新評論時。",- "mentions": "提及",- "mentions_description": "有人用 @ 提到你時,包括 @all 和 @squad。",- "updates": "任務更新",- "updates_description": "標題、描述、標籤、優先順序或截止日期變更時。",- "agent_activity": "AI 代理動態",- "agent_activity_description": "AI 代理執行失敗時。",- "inbox_notifications": "收件箱通知","system": "系統","system_notifications": "系統通知","system_description": "帳號變更、安全提醒和產品更新。"},- "groups.assignments_description": "任務分配給我或取消分配給我時。",- "groups.mentions_description": "有人用 @ 提到你時,包括 @all 和 @squad。"+ "routing": {+ "title": "通知去向",+ "description": "變更只影響之後的新通知。",+ "reset": "恢復預設",+ "routes": {+ "action": {+ "label": "需要處理",+ "description": "計入未讀"+ },+ "activity": {+ "label": "動態",+ "description": "安靜記錄,不計未讀"+ },+ "muted": {+ "label": "關閉",+ "description": "不進收件箱,在任務裡仍能看到"+ }+ },+ "kinds": {+ "assigned": {+ "label": "分配給我",+ "description": "任務分配給你時"+ },+ "mentions": {+ "label": "提及",+ "description": "有人 @ 你時,包括 @all 和 @squad"+ },+ "member_comments": {+ "label": "成員評論",+ "description": "成員在你訂閱的任務裡發表評論時"+ },+ "agent_failures": {+ "label": "AI 代理出錯",+ "description": "AI 代理執行失敗或被阻塞、需要你介入時"+ },+ "status_changes": {+ "label": "狀態變更",+ "description": "你訂閱的任務狀態變化時"+ },+ "assignee_changes": {+ "label": "負責人變更",+ "description": "任務換了負責人,或你被取消分配時"+ },+ "updates": {+ "label": "優先順序與日期",+ "description": "優先順序、開始日期或截止日期變化時"+ },+ "agent_comments": {+ "label": "AI 代理評論",+ "description": "AI 代理在你訂閱的任務裡回覆時"+ }+ }+ }}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex d50098e8c2..c1b116e255 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -54,6 +54,7 @@ import type {UpdateRuntimeProfileRequest,InboxItem,InboxWorkspaceUnread,+ MarkIssueInboxReadResult,IssueSubscriber,IssueUnread,Comment,@@ -415,6 +416,8 @@ import {EMPTY_CREATE_FEEDBACK_RESPONSE,InboxUnreadSummarySchema,EMPTY_INBOX_UNREAD_SUMMARY,+ MarkIssueInboxReadResultSchema,+ UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT,IssueUnreadPageSchema,EMPTY_ISSUE_UNREAD_PAGE,InboxItemListSchema,@@ -2964,6 +2967,14 @@ export class ApiClient {return this.fetch(`/api/inbox/${id}/read`, { method: "POST" });}+ /** Marks every active notification on the issue read for the caller. */+ async markIssueInboxRead(issueId: string): Promise<MarkIssueInboxReadResult> {+ const raw = await this.fetch<unknown>(`/api/inbox/issues/${issueId}/read`, { method: "POST" });+ return parseWithFallback(raw, MarkIssueInboxReadResultSchema, UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT, {+ endpoint: "POST /api/inbox/issues/:id/read",+ });+ }+async markInboxUnread(id: string): Promise<InboxItem> {return this.fetch(`/api/inbox/${id}/unread`, { method: "POST" });}diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 1a91144c94..b4aec002ad 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -45,6 +45,8 @@ import {InboxItemListSchema,InboxUnreadSummarySchema,IssueTriggerPreviewSchema,+ MarkIssueInboxReadResultSchema,+ UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT,ListIssuesResponseSchema,ListPropertiesResponseSchema,MALFORMED_RUNTIME_MODEL_LIST_REQUEST,@@ -78,6 +80,24 @@ import {import { IssueUnreadPageSchema, EMPTY_ISSUE_UNREAD_PAGE } from "./schemas";import { parseWithFallback } from "./schema";+describe("MarkIssueInboxReadResultSchema", () => {+ const endpoint = { endpoint: "POST /api/inbox/issues/:id/read" };++ it("keeps the server's count", () => {+ expect(+ parseWithFallback({ count: 3 }, MarkIssueInboxReadResultSchema, UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT, endpoint),+ ).toEqual({ count: 3 });+ });++ it("reports an unknown count for a malformed reply", () => {+ for (const raw of [null, "<html>", { count: "3" }, {}]) {+ expect(+ parseWithFallback(raw, MarkIssueInboxReadResultSchema, UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT, endpoint),+ ).toEqual({ count: null });+ }+ });+});+describe("IssueUnreadPageSchema", () => {const endpoint = "GET /api/issues/unread";diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 99b99c973f..23a7a04448 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -57,6 +57,7 @@ import type {IssuePullRequestsResponse,InboxItem,InboxWorkspaceUnread,+ MarkIssueInboxReadResult,IssueUnread,Label,MemberWithUser,@@ -2763,6 +2764,13 @@ export const InboxUnreadSummarySchema = z.array(export const EMPTY_INBOX_UNREAD_SUMMARY: InboxWorkspaceUnread[] = [];+// Rows marked read by `POST /api/inbox/issues/{id}/read`. On a malformed body+// the count is unknown (null), and callers refresh rather than trust it.++export const MarkIssueInboxReadResultSchema = z.object({ count: z.number() }).loose();++export const UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT: MarkIssueInboxReadResult = { count: null };+// The viewer's unread issues (`/api/issues/unread` GET), behind the sidebar's// unread dot. `outcome` stays a string so a future kind still lights the dot;// on malformed JSON parseWithFallback returns the empty list, which hides it.@@ -2812,6 +2820,9 @@ export const InboxItemListSchema = z.array(body: z.string().nullish(),issue_status: z.string().nullish(),issue_priority: z.string().nullish(),+ // An unknown section from a newer server drops to undefined, which+ // inboxItemSection reads as "action" so nothing is hidden from unread.+ section: z.enum(["action", "activity"]).optional().catch(undefined),read: z.boolean(),archived: z.boolean(),created_at: z.string(),diff --git a/packages/core/inbox/filter-store.test.ts b/packages/core/inbox/filter-store.test.tsindex d44b66d4e5..0be35241bd 100644--- a/packages/core/inbox/filter-store.test.ts+++ b/packages/core/inbox/filter-store.test.ts@@ -161,6 +161,19 @@ describe("unread filtering", () => {expect(inboxFilterCount(filters)).toBe(1);});+ it("drops activity, which is never unread", () => {+ const rows = [+ item("action", "todo", "high", { section: "action" }),+ item("activity", "todo", "high", { section: "activity" }),+ ];++ expect(+ filterInboxItems(rows, { ...EMPTY_INBOX_FILTERS, unreadOnly: true }).map(+ (candidate) => candidate.id,+ ),+ ).toEqual(["action"]);+ });+it("keeps notifications without an issue, unlike the issue dimensions", () => {// The issue-less rows are the quick-create failures — the ones that most// need to stay reachable while screening for what is unhandled.diff --git a/packages/core/inbox/filter-store.ts b/packages/core/inbox/filter-store.tsindex 1444a933ea..b341b208d5 100644--- a/packages/core/inbox/filter-store.ts+++ b/packages/core/inbox/filter-store.ts@@ -1,5 +1,6 @@import { create } from "zustand";import type { InboxItem, IssuePriority, IssueStatus } from "../types";+import { isInboxItemUnread } from "./section";export interface InboxFilters {readonly statuses: readonly IssueStatus[];@@ -236,7 +237,8 @@ export function inboxFiltersForArchive(filters: InboxFilters): InboxFilters {* touched") than the one the row then displays, so selecting Alice would fill* the list with Bob. What you filter by is what you see.*- * `unreadOnly` likewise reads the rendered row's `read`. The unread badge+ * `unreadOnly` likewise reads whether the rendered row is unread, which an+ * activity row never is. The unread badge* (`useInboxUnreadCount`) counts the same thing from the server's summary* endpoint, which applies that newest-per-issue rule in SQL — so "only unread"* and the number next to Inbox still cannot disagree.@@ -282,7 +284,7 @@ export function filterInboxItems(const key = item.issue_id ?? item.id;const matchesUnread =!filters.unreadOnly ||- item.read !== true ||+ isInboxItemUnread(item) ||(pinnedUnreadKey != null && key === pinnedUnreadKey);const matchesIdle =!filters.idleOnly ||diff --git a/packages/core/inbox/mutations.test.tsx b/packages/core/inbox/mutations.test.tsxindex 493d5fe7d2..ce802adf07 100644--- a/packages/core/inbox/mutations.test.tsx+++ b/packages/core/inbox/mutations.test.tsx@@ -9,7 +9,13 @@ 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 {+ useArchiveInbox,+ useMarkInboxRead,+ useMarkInboxUnread,+ useMarkIssueInboxRead,+ useUnarchiveInbox,+} from "./mutations";import { inboxKeys, useInboxUnreadCount } from "./queries";import { onInboxSummaryInvalidate } from "./ws-updaters";import { createQueryClient } from "../query-client";@@ -65,6 +71,103 @@ function summaryCount(qc: QueryClient) {return summary?.find((e) => e.workspace_id === WORKSPACE_ID)?.count;}+describe("useArchiveInbox sections", () => {+ let queryClient: QueryClient;++ beforeEach(() => {+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ setApiInstance({+ archiveInbox: vi.fn(async (id: string) => item({ id, archived: true })),+ listInbox: vi.fn(async () => listCache(queryClient)),+ listArchivedInbox: vi.fn(async () => []),+ getInboxUnreadSummary: vi.fn(async () => []),+ } as unknown as ApiClient);+ queryClient.setQueryData<InboxItem[]>(inboxKeys.list(WORKSPACE_ID), [+ item({ id: "mention", type: "mentioned", section: "action", archived: false }),+ item({ id: "status", type: "status_changed", section: "activity", archived: false }),+ item({ id: "reply", section: "activity", archived: false }),+ ]);+ });++ const archivedIds = () => listCache(queryClient).filter((i) => i.archived).map((i) => i.id);++ it("archiving activity keeps the issue's action rows", async () => {+ const { result } = renderHook(() => useArchiveInbox(), { wrapper: createWrapper(queryClient) });+ act(() => result.current.mutate("status"));+ await waitFor(() => expect(archivedIds()).toEqual(["status", "reply"]));+ });++ it("archiving an action row takes the whole issue", async () => {+ const { result } = renderHook(() => useArchiveInbox(), { wrapper: createWrapper(queryClient) });+ act(() => result.current.mutate("mention"));+ await waitFor(() => expect(archivedIds()).toEqual(["mention", "status", "reply"]));+ });+});++describe("useMarkIssueInboxRead", () => {+ let queryClient: QueryClient;+ let markIssueInboxRead: ReturnType<typeof vi.fn>;+ let getInboxUnreadSummary: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ markIssueInboxRead = vi.fn(async () => ({ count: 2 }));+ getInboxUnreadSummary = vi.fn(async () => []);+ setApiInstance({+ markIssueInboxRead,+ getInboxUnreadSummary,+ listInbox: vi.fn(async () => listCache(queryClient)),+ listArchivedInbox: vi.fn(async () => []),+ } as unknown as ApiClient);+ queryClient.setQueryData<InboxItem[]>(inboxKeys.list(WORKSPACE_ID), [+ item({ id: "a", archived: false }),+ item({ id: "b", archived: false, type: "mentioned" }),+ item({ id: "other", issue_id: "issue-2", archived: false }),+ ]);+ });++ it("marks every row on the issue read and leaves other issues alone", async () => {+ const { result } = renderHook(() => useMarkIssueInboxRead(WORKSPACE_ID), {+ wrapper: createWrapper(queryClient),+ });+ act(() => result.current.mutate("issue-1"));++ await waitFor(() => expect(markIssueInboxRead).toHaveBeenCalledWith("issue-1"));+ const byId = Object.fromEntries(listCache(queryClient).map((i) => [i.id, i.read]));+ expect(byId).toEqual({ a: true, b: true, other: false });+ });++ it("does not refresh the badge when nothing changed", async () => {+ markIssueInboxRead.mockResolvedValueOnce({ count: 0 });+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");+ const { result } = renderHook(() => useMarkIssueInboxRead(WORKSPACE_ID), {+ wrapper: createWrapper(queryClient),+ });+ await act(() => result.current.mutateAsync("issue-1"));++ expect(invalidate).not.toHaveBeenCalled();+ });++ it("refreshes the badge when the reply could not be read", async () => {+ markIssueInboxRead.mockResolvedValueOnce({ count: null });+ const invalidate = vi.spyOn(queryClient, "invalidateQueries");+ const { result } = renderHook(() => useMarkIssueInboxRead(WORKSPACE_ID), {+ wrapper: createWrapper(queryClient),+ });+ await act(() => result.current.mutateAsync("issue-1"));++ await waitFor(() =>+ expect(invalidate).toHaveBeenCalledWith(+ expect.objectContaining({ queryKey: inboxKeys.unreadSummary() }),+ ),+ );+ });+});+describe("useMarkInboxUnread", () => {let queryClient: QueryClient;let markInboxUnread: ReturnType<typeof vi.fn>;diff --git a/packages/core/inbox/mutations.ts b/packages/core/inbox/mutations.tsindex b4becc22f7..79f8462d7f 100644--- a/packages/core/inbox/mutations.ts+++ b/packages/core/inbox/mutations.ts@@ -1,7 +1,13 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import type { QueryClient } from "@tanstack/react-query";import { api } from "../api";-import { inboxKeys, mapArchivedInboxCache, patchArchivedInboxCaches, type ArchivedInboxCache } from "./queries";+import {+ inboxItemSection,+ inboxKeys,+ mapArchivedInboxCache,+ patchArchivedInboxCaches,+ type ArchivedInboxCache,+} from "./queries";import { onInboxInvalidate, onInboxSummaryInvalidate } from "./ws-updaters";import { useWorkspaceId } from "../hooks";import type { InboxItem } from "../types";@@ -103,12 +109,15 @@ export function useArchiveInbox() {onMutate: async (id) => {await qc.cancelQueries({ queryKey: inboxKeys.list(wsId) });const prev = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));- // Archive all items for the same issue (same behavior as store)+ // Archive the issue's siblings like the server does: an action row takes+ // the whole issue, an activity row only the issue's other activity.const target = prev?.find((i) => i.id === id);const issueId = target?.issue_id;+ const activityOnly = target ? inboxItemSection(target) === "activity" : false;qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), (old) =>old?.map((item) =>- item.id === id || (issueId && item.issue_id === issueId)+ item.id === id ||+ (issueId && item.issue_id === issueId && (!activityOnly || inboxItemSection(item) === "activity"))? { ...item, archived: true }: item,),@@ -165,6 +174,35 @@ export function useUnarchiveInbox() {});}+/**+ * Mark every notification on an issue read — called when the issue is opened+ * from anywhere, so reading it through the Work sidebar settles the Inbox too.+ * Takes `wsId` because the caller (issue detail) may render outside the+ * workspace route context. Nothing is refetched when nothing changed.+ */+export function useMarkIssueInboxRead(wsId: string) {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: (issueId: string) => api.markIssueInboxRead(issueId),+ onMutate: async (issueId) => {+ await qc.cancelQueries({ queryKey: inboxKeys.list(wsId) });+ const prev = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));+ qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), (old) =>+ old?.map((item) =>+ item.issue_id === issueId && !item.archived && !item.read ? { ...item, read: true } : item,+ ),+ );+ return { prev };+ },+ onError: (_err, _issueId, ctx) => {+ if (ctx?.prev) qc.setQueryData(inboxKeys.list(wsId), ctx.prev);+ },+ onSuccess: (result) => {+ if (result.count !== 0) refreshInboxAfterWrite(qc, wsId);+ },+ });+}+export function useMarkAllInboxRead() {const qc = useQueryClient();const wsId = useWorkspaceId();diff --git a/packages/core/inbox/queries.test.ts b/packages/core/inbox/queries.test.tsindex 4ce1406666..4b6d0eac6e 100644--- a/packages/core/inbox/queries.test.ts+++ b/packages/core/inbox/queries.test.ts@@ -6,7 +6,10 @@ import {archivedInboxPagesOptions,deduplicateArchivedInboxItems,deduplicateInboxItems,+ groupInboxItemsBySection,hasOtherWorkspaceUnread,+ inboxItemSection,+ isInboxItemUnread,inboxKeys,unreadCountForWorkspace,unreadWorkspaceIds,@@ -34,6 +37,32 @@ function item(overrides: Partial<InboxItem>): InboxItem {};}+describe("inbox sections", () => {+ it("reads a missing or unknown section as action", () => {+ expect(inboxItemSection(item({}))).toBe("action");+ expect(inboxItemSection(item({ section: "activity" }))).toBe("activity");+ });++ it("never treats activity as unread", () => {+ expect(isInboxItemUnread(item({ read: false, section: "activity" }))).toBe(false);+ expect(isInboxItemUnread(item({ read: false, section: "action" }))).toBe(true);+ expect(isInboxItemUnread(item({ read: true, section: "action" }))).toBe(false);+ });++ it("groups each section per issue, so activity does not move the action row", () => {+ const { action, activity } = groupInboxItemsBySection([+ item({ id: "mention", type: "mentioned", section: "action", created_at: "2026-06-15T08:00:00Z" }),+ item({ id: "other-assign", issue_id: "issue-2", type: "issue_assigned", section: "action", created_at: "2026-06-15T08:01:00Z" }),+ item({ id: "status", type: "status_changed", section: "activity", created_at: "2026-06-15T08:02:00Z" }),+ item({ id: "reply", type: "new_comment", section: "activity", created_at: "2026-06-15T08:03:00Z" }),+ item({ id: "archived", issue_id: "issue-3", section: "activity", archived: true }),+ ]);++ expect(action.map((i) => i.id)).toEqual(["other-assign", "mention"]);+ expect(activity.map((i) => i.id)).toEqual(["reply"]);+ });+});+describe("deduplicateInboxItems", () => {it("keeps the newest issue row while preserving an older comment anchor", () => {const merged = deduplicateInboxItems([diff --git a/packages/core/inbox/queries.ts b/packages/core/inbox/queries.tsindex 290389b6c8..4599c806d1 100644--- a/packages/core/inbox/queries.ts+++ b/packages/core/inbox/queries.ts@@ -3,8 +3,11 @@ import type { ArchivedInboxPage } from "../types/inbox";import { EMPTY_INBOX_FILTERS, type ArchivedInboxFilters } from "./filter-store";import { infiniteQueryOptions, queryOptions, useQuery } from "@tanstack/react-query";import { api } from "../api";-import type { InboxItem, InboxWorkspaceUnread } from "../types";+import type { InboxItem, InboxSection, InboxWorkspaceUnread } from "../types";import { focusManager } from "@tanstack/react-query";+import { inboxItemSection } from "./section";++export { inboxItemSection, isInboxItemUnread } from "./section";export const inboxKeys = {all: (wsId: string) => ["inbox", wsId] as const,@@ -189,6 +192,20 @@ export function useInboxUnreadCount(return data ?? 0;}+/**+ * Active inbox items split into the two sections, each grouped one entry per+ * issue like {@link deduplicateInboxItems}. An issue with both kinds appears+ * in both sections, and routine activity never moves its action entry: each+ * section orders by its own newest row.+ */+export function groupInboxItemsBySection(items: InboxItem[]): Record<InboxSection, InboxItem[]> {+ const active = items.filter((i) => !i.archived);+ return {+ action: groupInboxItemsByIssue(active.filter((i) => inboxItemSection(i) === "action")),+ activity: groupInboxItemsByIssue(active.filter((i) => inboxItemSection(i) === "activity")),+ };+}+/*** Deduplicate inbox items by issue_id (one entry per issue, Linear-style).* Exported for consumers to use in useMemo — not in queryOptions selectdiff --git a/packages/core/inbox/section.ts b/packages/core/inbox/section.tsnew file mode 100644index 0000000000..309d1829b1--- /dev/null+++ b/packages/core/inbox/section.ts@@ -0,0 +1,14 @@+import type { InboxItem, InboxSection } from "../types";++/** The item's Inbox section; a backend that predates sections means "action". */+export function inboxItemSection(item: Pick<InboxItem, "section">): InboxSection {+ return item.section === "activity" ? "activity" : "action";+}++/**+ * Whether the item shows as unread. Activity is never unread, whatever its+ * stored `read` flag: the server leaves it out of every unread count.+ */+export function isInboxItemUnread(item: Pick<InboxItem, "read" | "section">): boolean {+ return !item.read && inboxItemSection(item) === "action";+}diff --git a/packages/core/notification-preferences/index.ts b/packages/core/notification-preferences/index.tsindex 4b3efba544..9865f0237f 100644--- a/packages/core/notification-preferences/index.ts+++ b/packages/core/notification-preferences/index.ts@@ -1,3 +1,4 @@export * from "./queries";export * from "./mutations";export * from "./patch";+export * from "./routes";diff --git a/packages/core/notification-preferences/patch.ts b/packages/core/notification-preferences/patch.tsindex c0c0a331de..ef92874fe4 100644--- a/packages/core/notification-preferences/patch.ts+++ b/packages/core/notification-preferences/patch.ts@@ -5,11 +5,16 @@ import type {} from "../types";const NOTIFICATION_GROUP_KEYS: readonly NotificationGroupKey[] = [- "assignments",- "status_changes",- "comments",+ "assigned","mentions",+ "member_comments",+ "agent_failures",+ "status_changes",+ "assignee_changes","updates",+ "agent_comments",+ "assignments",+ "comments","agent_activity","system_notifications",];@@ -51,10 +56,10 @@ export function applyNotificationPreferencePatch(for (const key of NOTIFICATION_GROUP_KEYS) {const value = patch[key];- if (value === "muted") {- next[key] = value;- } else if (value === "all") {+ if (value === "all") {delete next[key];+ } else if (value !== undefined) {+ next[key] = value;}}@@ -63,7 +68,7 @@ export function applyNotificationPreferencePatch(/*** Roll back only values that still match this mutation's optimistic patch.- * A later toggle that touched the same key wins.+ * A later change that touched the same key wins.*/export function rollbackNotificationPreferencePatch(current: NotificationPreferences,diff --git a/packages/core/notification-preferences/routes.test.ts b/packages/core/notification-preferences/routes.test.tsnew file mode 100644index 0000000000..500906abf1--- /dev/null+++ b/packages/core/notification-preferences/routes.test.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from "vitest";+import type { NotificationPreferences, NotificationRouteKey } from "../types";+import {+ NOTIFICATION_ROUTE_KINDS,+ notificationRoutesAreDefault,+ resolveNotificationRoute,+ withDefaultNotificationRoutes,+ withNotificationRoute,+} from "./routes";++const kind = (key: NotificationRouteKey) => {+ const found = NOTIFICATION_ROUTE_KINDS.find((k) => k.key === key);+ if (!found) throw new Error(key);+ return found;+};++const resolved = (preferences: NotificationPreferences) =>+ Object.fromEntries(+ NOTIFICATION_ROUTE_KINDS.map((k) => [k.key, resolveNotificationRoute(preferences, k)]),+ );++describe("resolveNotificationRoute", () => {+ it("uses each kind's default when nothing is set", () => {+ expect(resolved({})).toEqual({+ assigned: "action",+ mentions: "action",+ member_comments: "action",+ agent_failures: "action",+ status_changes: "activity",+ assignee_changes: "activity",+ updates: "activity",+ agent_comments: "activity",+ });+ expect(notificationRoutesAreDefault({ status_changes: "all" })).toBe(true);+ });++ it("follows the recipient's choice", () => {+ const prefs: NotificationPreferences = {+ status_changes: "action",+ mentions: "activity",+ updates: "muted",+ };+ expect(resolveNotificationRoute(prefs, kind("status_changes"))).toBe("action");+ expect(resolveNotificationRoute(prefs, kind("mentions"))).toBe("activity");+ expect(resolveNotificationRoute(prefs, kind("updates"))).toBe("muted");+ expect(notificationRoutesAreDefault(prefs)).toBe(false);+ });++ it("keeps a muted legacy group muting both halves until the new key is set", () => {+ const prefs: NotificationPreferences = { comments: "muted", agent_comments: "activity" };+ expect(resolveNotificationRoute(prefs, kind("member_comments"))).toBe("muted");+ expect(resolveNotificationRoute(prefs, kind("agent_comments"))).toBe("activity");+ expect(resolveNotificationRoute(prefs, kind("mentions"))).toBe("action");+ expect(resolveNotificationRoute({ assignments: "muted" }, kind("assignee_changes"))).toBe("muted");+ });+});++describe("withNotificationRoute", () => {+ it("stores a non-default choice and clears a default one", () => {+ const routed = withNotificationRoute({}, kind("status_changes"), "action");+ expect(routed).toEqual({ status_changes: "action" });+ expect(withNotificationRoute(routed, kind("status_changes"), "activity")).toEqual({});+ });++ it("retires a muted legacy group without unmuting the other kind it covered", () => {+ const next = withNotificationRoute(+ { comments: "muted", system_notifications: "muted" },+ kind("member_comments"),+ "action",+ );+ expect(next).toEqual({ agent_comments: "muted", system_notifications: "muted" });+ expect(resolveNotificationRoute(next, kind("member_comments"))).toBe("action");+ expect(resolveNotificationRoute(next, kind("agent_comments"))).toBe("muted");+ });++ it("keeps a sibling's explicit choice when retiring the legacy group", () => {+ const next = withNotificationRoute(+ { assignments: "muted", assignee_changes: "action" },+ kind("assigned"),+ "activity",+ );+ expect(next).toEqual({ assigned: "activity", assignee_changes: "action" });+ });+});++describe("withDefaultNotificationRoutes", () => {+ it("resets every kind and legacy group, keeping system notifications", () => {+ const next = withDefaultNotificationRoutes({+ comments: "muted",+ status_changes: "action",+ mentions: "muted",+ system_notifications: "muted",+ });+ expect(next).toEqual({ system_notifications: "muted" });+ expect(notificationRoutesAreDefault(next)).toBe(true);+ });+});diff --git a/packages/core/notification-preferences/routes.ts b/packages/core/notification-preferences/routes.tsnew file mode 100644index 0000000000..ee9fbc3dbd--- /dev/null+++ b/packages/core/notification-preferences/routes.ts@@ -0,0 +1,88 @@+import type {+ NotificationLegacyGroupKey,+ NotificationPreferences,+ NotificationRoute,+ NotificationRouteKey,+} from "../types";++export interface NotificationRouteKind {+ key: NotificationRouteKey;+ default: Exclude<NotificationRoute, "muted">;+ /** Pre-routing group whose "muted" still applies while `key` is unset. */+ legacy?: NotificationLegacyGroupKey;+}++/**+ * Routable kinds in settings order. Mirrors `RouteKinds` in+ * server/internal/inbox/routing.go, which applies them when notifications are+ * created; keep the two in step.+ */+export const NOTIFICATION_ROUTE_KINDS: readonly NotificationRouteKind[] = [+ { key: "assigned", default: "action", legacy: "assignments" },+ { key: "mentions", default: "action" },+ { key: "member_comments", default: "action", legacy: "comments" },+ { key: "agent_failures", default: "action", legacy: "agent_activity" },+ { key: "status_changes", default: "activity" },+ { key: "assignee_changes", default: "activity", legacy: "assignments" },+ { key: "updates", default: "activity" },+ { key: "agent_comments", default: "activity", legacy: "comments" },+];++function isRoute(value: unknown): value is NotificationRoute {+ return value === "action" || value === "activity" || value === "muted";+}++/** Where `kind` currently lands for these preferences. */+export function resolveNotificationRoute(+ preferences: NotificationPreferences,+ kind: NotificationRouteKind,+): NotificationRoute {+ const value = preferences[kind.key];+ if (isRoute(value)) return value;+ if (kind.legacy && preferences[kind.legacy] === "muted") return "muted";+ return kind.default;+}++/** True when every kind lands in its default section. */+export function notificationRoutesAreDefault(preferences: NotificationPreferences): boolean {+ return NOTIFICATION_ROUTE_KINDS.every(+ (kind) => resolveNotificationRoute(preferences, kind) === kind.default,+ );+}++/**+ * Preferences after routing `kind` to `route`. A default choice is stored as+ * "all" so it follows future default changes. If the kind's legacy group was+ * muted, the group is retired and every other kind it covered keeps its muted+ * route explicitly, so changing one kind never unmutes another.+ */+export function withNotificationRoute(+ preferences: NotificationPreferences,+ kind: NotificationRouteKind,+ route: NotificationRoute,+): NotificationPreferences {+ const next: NotificationPreferences = { ...preferences };+ if (kind.legacy && preferences[kind.legacy] === "muted") {+ for (const sibling of NOTIFICATION_ROUTE_KINDS) {+ if (sibling.legacy !== kind.legacy || sibling.key === kind.key) continue;+ next[sibling.key] = resolveNotificationRoute(preferences, sibling);+ if (next[sibling.key] === sibling.default) delete next[sibling.key];+ }+ delete next[kind.legacy];+ }+ if (route === kind.default) delete next[kind.key];+ else next[kind.key] = route;+ return next;+}++/** Preferences with every kind back on its default; other settings are kept. */+export function withDefaultNotificationRoutes(+ preferences: NotificationPreferences,+): NotificationPreferences {+ const next: NotificationPreferences = { ...preferences };+ for (const kind of NOTIFICATION_ROUTE_KINDS) {+ delete next[kind.key];+ if (kind.legacy) delete next[kind.legacy];+ }+ return next;+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 19331012ad..1b8e4d3d9f 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -62,6 +62,7 @@"./issues/stores/*": "./issues/stores/*.ts","./inbox": "./inbox/index.ts","./inbox/queries": "./inbox/queries.ts",+ "./inbox/section": "./inbox/section.ts","./inbox/mutations": "./inbox/mutations.ts","./inbox/filter-store": "./inbox/filter-store.ts","./inbox/ws-updaters": "./inbox/ws-updaters.ts",@@ -69,6 +70,7 @@"./notification-preferences/queries": "./notification-preferences/queries.ts","./notification-preferences/mutations": "./notification-preferences/mutations.ts","./notification-preferences/patch": "./notification-preferences/patch.ts",+ "./notification-preferences/routes": "./notification-preferences/routes.ts","./chat": "./chat/index.ts","./chat/queries": "./chat/queries.ts","./chat/mutations": "./chat/mutations.ts",diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.tsindex 965021a85d..8109e36d8e 100644--- a/packages/core/realtime/use-realtime-sync.test.ts+++ b/packages/core/realtime/use-realtime-sync.test.ts@@ -816,6 +816,24 @@ describe("handleInboxNew", () => {});});+ it("keeps activity quiet: no banner and no unread summary refresh", async () => {+ const qc = createQueryClient();+ qc.setQueryData<Workspace[]>(workspaceKeys.list(), [workspace()]);+ qc.setQueryData(notificationPreferenceKeys.all("ws-a"), {+ preferences: { system_notifications: "all" },+ });+ qc.setQueryData(inboxKeys.unreadSummary(), []);+ const showNotification = stubDesktopAPI();++ await handleInboxNew(+ qc,+ inboxItem({ type: "status_changed", actor_type: "agent", section: "activity" }),+ );++ expect(showNotification).not.toHaveBeenCalled();+ expect(qc.getQueryState(inboxKeys.unreadSummary())?.isInvalidated).toBe(false);+ });+it("invalidates the ITEM's workspace inbox cache and resolves its slug, not the active workspace's", async () => {const qc = createQueryClient();qc.setQueryData<Workspace[]>(workspaceKeys.list(), [diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 660359c837..93fee1b412 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -52,6 +52,7 @@ import {invalidateUpdatedAtSortedIssueLists,} from "../issues/cache-coordinator";import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged, onInboxIssueDeleted, onInboxSummaryInvalidate } from "../inbox/ws-updaters";+import { inboxItemSection } from "../inbox/queries";import {notificationPreferenceOptions,notificationPreferenceKeys,@@ -573,6 +574,9 @@ export async function handleInboxNew(): Promise<void> {const sourceWsId = item.workspace_id;if (sourceWsId) void onInboxNew(qc, sourceWsId, item);+ // Activity is never unread and never interrupts: it cannot move the unread+ // summary, and routine progress does not earn an OS banner.+ if (inboxItemSection(item) === "activity") return;// A new item in ANY workspace can light the workspace-switcher dot, so// refresh the cross-workspace summary regardless of the active workspace.void onInboxSummaryInvalidate(qc);diff --git a/packages/core/types/inbox.ts b/packages/core/types/inbox.tsindex 473ed003a8..5af9595197 100644--- a/packages/core/types/inbox.ts+++ b/packages/core/types/inbox.ts@@ -44,6 +44,19 @@ export interface InboxWorkspaceUnread {count: number;}+/** Rows `POST /api/inbox/issues/{id}/read` marked read; null when the reply was unreadable. */+export interface MarkIssueInboxReadResult {+ count: number | null;+}++/**+ * Inbox section, derived by the server from the notification type and who+ * caused it. "action" waits on the recipient and is the only section that+ * counts as unread; "activity" is routine progress (status moves, agent+ * replies, property edits) that the Work sidebar already tracks.+ */+export type InboxSection = "action" | "activity";+export interface InboxItem {id: string;workspace_id: string;@@ -63,6 +76,12 @@ export interface InboxItem {* projection; null also covers notifications without a linked issue.*/issue_priority?: IssuePriority | null;+ /**+ * Optional so a client remains compatible with a backend that predates the+ * split; read it through `inboxItemSection`, which treats a missing value+ * as "action" — the behavior before sections existed.+ */+ section?: InboxSection;read: boolean;archived: boolean;created_at: string;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex cc2d90d352..1642b6a592 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -135,8 +135,8 @@ export type {PluginMCPTool,PluginTokenIssue,} from "./plugin";-export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread, ArchivedInboxPage, ArchivedInboxFacets } from "./inbox";-export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";+export type { InboxItem, InboxSection, InboxSeverity, InboxItemType, InboxWorkspaceUnread, MarkIssueInboxReadResult, ArchivedInboxPage, ArchivedInboxFacets } from "./inbox";+export type { NotificationGroupKey, NotificationGroupValue, NotificationLegacyGroupKey, NotificationPreferences, NotificationPreferenceResponse, NotificationRoute, NotificationRouteKey } from "./notification-preference";export type { Comment, CommentType, CommentAuthorType, CommentSupplementReceipt, CommentSupplementStatus, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, CommentTriggerOutcome, CommentTriggerStatus, Reaction } from "./comment";export type { Label, LabelResourceType, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse, ResourceLabelsResponse } from "./label";export type { IssueProperty, IssuePropertyType, ScalarIssuePropertyType, ListIssuePropertyType, IssuePropertyOption, IssuePropertyConfig, IssuePropertyValue, IssuePropertyValues, CreatePropertyRequest, UpdatePropertyRequest, ListPropertiesResponse, IssuePropertiesResponse, IssuePropertyActorKind, IssuePropertyActorRef, PropertyFilterOp, PropertyOperatorFilter, PropertyFilterValue } from "./property";diff --git a/packages/core/types/notification-preference.ts b/packages/core/types/notification-preference.tsindex 204dbaa8ec..4a692fab48 100644--- a/packages/core/types/notification-preference.ts+++ b/packages/core/types/notification-preference.ts@@ -1,13 +1,27 @@-export type NotificationGroupKey =- | "assignments"- | "status_changes"- | "comments"+/** A kind of notification whose Inbox section the recipient chooses. */+export type NotificationRouteKey =+ | "assigned"| "mentions"+ | "member_comments"+ | "agent_failures"+ | "status_changes"+ | "assignee_changes"| "updates"- | "agent_activity"+ | "agent_comments";++/** Where a routable kind lands: an Inbox section, or nowhere. */+export type NotificationRoute = "action" | "activity" | "muted";++/** Groups from before per-kind routing; only their "muted" still applies. */+export type NotificationLegacyGroupKey = "assignments" | "comments" | "agent_activity";++export type NotificationGroupKey =+ | NotificationRouteKey+ | NotificationLegacyGroupKey| "system_notifications";-export type NotificationGroupValue = "all" | "muted";+/** "all" (or an absent key) means the kind's default. */+export type NotificationGroupValue = "all" | NotificationRoute;export type NotificationPreferences = Partial<Record<NotificationGroupKey, NotificationGroupValue>>;diff --git a/packages/views/inbox/components/inbox-context-menu.test.tsx b/packages/views/inbox/components/inbox-context-menu.test.tsxindex 2e0f44e4df..69f9dad895 100644--- a/packages/views/inbox/components/inbox-context-menu.test.tsx+++ b/packages/views/inbox/components/inbox-context-menu.test.tsx@@ -140,6 +140,16 @@ describe("inbox row context menu", () => {expect(screen.queryByText("Mark as unread")).toBeNull();});+ it("drops the read toggle on activity, which is never unread", async () => {+ const { row } = renderRow({ entry: item({ read: false, section: "activity" }) });++ fireEvent.contextMenu(row);++ expect(await screen.findByText("Archive")).toBeInTheDocument();+ expect(screen.queryByText("Mark as read")).toBeNull();+ 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 } });diff --git a/packages/views/inbox/components/inbox-item-actions.tsx b/packages/views/inbox/components/inbox-item-actions.tsxindex f7bcf6f58f..a69bb6a524 100644--- a/packages/views/inbox/components/inbox-item-actions.tsx+++ b/packages/views/inbox/components/inbox-item-actions.tsx@@ -1,6 +1,7 @@"use client";import { Archive, ArchiveRestore, Check, CircleDot, ExternalLink } from "@multica/ui/icons";+import { inboxItemSection } from "@multica/core/inbox/queries";import { paths, useWorkspaceSlug } from "@multica/core/paths";import type { InboxItem } from "@multica/core/types";import type { RowActionItem } from "../../common/row-actions-menu";@@ -66,8 +67,9 @@ export function useInboxItemActions(// 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.- if (!isArchivedView) {+ // would report success and change nothing on screen. Activity is never+ // unread at all, so it has no toggle either.+ if (!isArchivedView && inboxItemSection(item) === "action") {groups.push([item.read === true? {diff --git a/packages/views/inbox/components/inbox-list-item.tsx b/packages/views/inbox/components/inbox-list-item.tsxindex 07344c6fe6..e73447eb49 100644--- a/packages/views/inbox/components/inbox-list-item.tsx+++ b/packages/views/inbox/components/inbox-list-item.tsx@@ -1,6 +1,7 @@"use client";import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";+import { isInboxItemUnread } from "@multica/core/inbox/queries";import { StatusIcon } from "../../issues/components";import {IssueAgentActivityIndicator,@@ -80,7 +81,7 @@ export function InboxListItem({// Archiving deliberately leaves `read` untouched so unarchiving restores the// real unread state, so archived rows would otherwise keep an unread marker// the user cannot clear from this view. Suppress the affordance here only.- const showUnread = item.read !== true && !isArchivedView;+ const showUnread = isInboxItemUnread(item) && !isArchivedView;const ActionIcon = isArchivedView ? ArchiveRestore : Archive;const actionLabel = isArchivedView? t(($) => $.list.unarchive_tooltip)diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsxindex 514c60055f..16f142b6a2 100644--- a/packages/views/inbox/components/inbox-page.test.tsx+++ b/packages/views/inbox/components/inbox-page.test.tsx@@ -74,8 +74,16 @@ vi.mock("@multica/core/inbox/queries", () => ({inboxListOptions: () => ({ queryKey: ["inbox", "workspace-1", "list"] }),archivedInboxPagesOptions: () => ({ queryKey: ["inbox", "workspace-1", "archived", "pages"] }),archivedInboxLookupOptions: () => ({ queryKey: ["inbox", "workspace-1", "archived", "lookup"] }),- deduplicateInboxItems: (items: InboxItem[]) => items.filter((i) => !i.archived),+ groupInboxItemsBySection: (items: InboxItem[]) => {+ const active = items.filter((i) => !i.archived);+ return {+ action: active.filter((i) => i.section !== "activity"),+ activity: active.filter((i) => i.section === "activity"),+ };+ },deduplicateArchivedInboxItems: (items: InboxItem[]) => items.filter((i) => i.archived),+ inboxItemSection: (item: InboxItem) => (item.section === "activity" ? "activity" : "action"),+ isInboxItemUnread: (item: InboxItem) => !item.read && item.section !== "activity",useInboxUnreadCount: () => 2,}));@@ -1114,3 +1122,47 @@ describe("InboxPage", () => {expect(replace).not.toHaveBeenCalledWith("/acme/inbox");});});++describe("InboxPage sections", () => {+ const mention = () =>+ item({ id: "mention", issue_id: "issue-a", type: "mentioned", actor_type: "member", section: "action", read: false });+ const status = () =>+ item({ id: "status", issue_id: "issue-b", type: "status_changed", section: "activity", read: false });+ const rows = () => screen.queryAllByTestId("row").map((row) => row.textContent);++ it("opens on the action section and switches to activity", () => {+ reset();+ listData.active = [mention(), status()];+ render(<InboxPage />);++ expect(rows()).toEqual(["mention"]);+ // Activity is never unread, so its tab carries no count.+ expect(screen.getAllByRole("tab")[1]!.textContent).not.toMatch(/\d/);+ fireEvent.click(screen.getAllByRole("tab")[1]!);++ expect(replace).toHaveBeenLastCalledWith("/acme/inbox?section=activity");+ expect(rows()).toEqual(["status"]);+ });++ it("does not auto-mark an opened activity row read", () => {+ reset();+ layout.width = DESKTOP;+ listData.active = [mention(), status()];+ searchParams = new URLSearchParams("section=activity&issue=issue-b");+ render(<InboxPage />);++ expect(rows()).toEqual(["status"]);+ expect(issueDetailProps.at(-1)?.issueId).toBe("issue-b");+ expect(markReadMutate).not.toHaveBeenCalled();+ });++ it("moves a link to the section that holds its issue instead of leaving the inbox", () => {+ reset();+ listData.active = [mention(), status()];+ searchParams = new URLSearchParams("issue=issue-b");+ render(<InboxPage />);++ expect(replace).toHaveBeenCalledWith("/acme/inbox?section=activity&issue=issue-b");+ expect(replace).not.toHaveBeenCalledWith("/acme/issues/issue-b");+ });+});diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex 2ad643bbc1..cf1f3770cc 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -25,8 +25,9 @@ import {inboxListOptions,archivedInboxPagesOptions,archivedInboxLookupOptions,- deduplicateInboxItems,+ groupInboxItemsBySection,deduplicateArchivedInboxItems,+ isInboxItemUnread,useInboxUnreadCount,} from "@multica/core/inbox/queries";import {@@ -70,7 +71,8 @@ import {ListChecks,ArrowLeft,} from "@multica/ui/icons";-import type { InboxItem } from "@multica/core/types";+import type { InboxItem, InboxSection } from "@multica/core/types";+import { Tabs, TabsList, TabsTrigger } from "@multica/ui/components/ui/tabs";import { Button } from "@multica/ui/components/ui/button";import { IconButton } from "@multica/ui/components/common/icon-button";import {@@ -99,7 +101,7 @@ import { useTimeAgo } from "./inbox-list-item";import { InboxList } from "./inbox-list";import { InboxFilterMenu } from "./inbox-filter-menu";import { InboxContextMenuProvider } from "./inbox-context-menu";-import { ARCHIVED_VIEW_PARAM, type InboxView } from "./inbox-view";+import { ACTIVITY_SECTION_PARAM, ARCHIVED_VIEW_PARAM, type InboxView } from "./inbox-view";import { useTypeLabels } from "./inbox-detail-label";import {getInboxDisplayTitle,@@ -124,10 +126,13 @@ export function InboxPage() {const urlIssue = searchParams.get("issue") ?? "";const urlView: InboxView =searchParams.get("view") === ARCHIVED_VIEW_PARAM ? "archived" : "inbox";+ const urlSection: InboxSection =+ searchParams.get("section") === ACTIVITY_SECTION_PARAM ? "activity" : "action";const wsPaths = useWorkspacePaths();const [selectedKey, setSelectedKeyState] = useState(() => urlIssue);const [view, setViewState] = useState<InboxView>(() => urlView);+ const [section, setSectionState] = useState<InboxSection>(() => urlSection);// The row the user opened under the unread filter. Opening it marks it read,// so the filter would otherwise drop the row before the detail finishes// mounting. Scoped to the selection: moving away releases it.@@ -145,6 +150,9 @@ export function InboxPage() {useEffect(() => {setViewState(urlView);}, [urlView]);+ useEffect(() => {+ setSectionState(urlSection);+ }, [urlSection]);const wsId = useWorkspaceId();const isArchivedView = view === "archived";@@ -153,7 +161,8 @@ export function InboxPage() {const { data: rawItems = [], isLoading: loading } = useQuery({...inboxListOptions(wsId), enabled: !isArchivedView,});- const items = useMemo(() => deduplicateInboxItems(rawItems), [rawItems]);+ const sections = useMemo(() => groupInboxItemsBySection(rawItems), [rawItems]);+ const items = sections[section];const archiveQuery = useInfiniteQuery({...archivedInboxPagesOptions(wsId, filters), enabled: isArchivedView,});@@ -249,9 +258,10 @@ export function InboxPage() {// carry the other one — a bare `?issue=` would silently drop the user out of// the archived view on the next selection.const buildInboxUrl = useCallback(- (nextView: InboxView, key: string) => {+ (nextView: InboxView, key: string, nextSection: InboxSection) => {const params = new URLSearchParams();if (nextView === "archived") params.set("view", ARCHIVED_VIEW_PARAM);+ else if (nextSection === "activity") params.set("section", ACTIVITY_SECTION_PARAM);if (key) params.set("issue", key);const query = params.toString();const inboxPath = wsPaths.inbox();@@ -262,8 +272,8 @@ export function InboxPage() {const setSelectedKey = useCallback((key: string) => {setSelectedKeyState(key);- replace(buildInboxUrl(view, key));- }, [replace, buildInboxUrl, view]);+ replace(buildInboxUrl(view, key, section));+ }, [replace, buildInboxUrl, view, section]);// Switching views always clears the selection: the two lists are mutually// exclusive, so a key carried across would never resolve, and the fallback@@ -271,7 +281,16 @@ export function InboxPage() {const setView = useCallback((nextView: InboxView) => {setViewState(nextView);setSelectedKeyState("");- replace(buildInboxUrl(nextView, ""));+ replace(buildInboxUrl(nextView, "", section));+ }, [replace, buildInboxUrl, section]);++ // Switching sections clears the selection unless a key is carried on+ // purpose: the deep-link fallback below moves a link to the section that+ // holds its issue.+ const setSection = useCallback((nextSection: InboxSection, key = "") => {+ setSectionState(nextSection);+ setSelectedKeyState(key);+ replace(buildInboxUrl("inbox", key, nextSection));}, [replace, buildInboxUrl]);// Applying a filter can remove the open row from the list. Clear that local@@ -303,10 +322,22 @@ export function InboxPage() {setSelectedKey("");return;}+ // A link that never resolved may name an issue the other section holds+ // (an issue with only activity, say): open it there.+ if (!isArchivedView) {+ const otherSection: InboxSection = section === "action" ? "activity" : "action";+ if (sections[otherSection].some((i) => (i.issue_id ?? i.id) === selectedKey)) {+ setSection(otherSection, selectedKey);+ return;+ }+ }replace(wsPaths.issueDetail(selectedKey));}, [viewLoading,isArchivedView,+ section,+ sections,+ setSection,archivedError,lookupLoading,lookupError,@@ -349,7 +380,7 @@ export function InboxPage() {// in handleSelect so URL-driven selection triggers it too.const markReadMutate = markReadMutation.mutate;const selectedId = selected?.id;- const selectedRead = selected?.read;+ const selectedRead = selected ? !isInboxItemUnread(selected) : undefined;useEffect(() => {if (!selectedId || selectedRead) return;if (manualUnreadIdRef.current === selectedId) return;@@ -549,7 +580,7 @@ export function InboxPage() {};const handleArchiveAllRead = () => {- const readKeys = items.filter((i) => i.read).map((i) => i.issue_id ?? i.id);+ const readKeys = items.filter((i) => !isInboxItemUnread(i)).map((i) => i.issue_id ?? i.id);if (readKeys.includes(selectedKey)) setSelectedKey("");archiveAllReadMutation.mutate(undefined, {onError: (err) =>@@ -732,7 +763,11 @@ export function InboxPage() {emptyLabel={hasActiveFilters && visibleItems.length === 0? t(($) => $.filters.empty)- : undefined+ : isArchivedView+ ? undefined+ : section === "activity"+ ? t(($) => $.sections.activity_empty)+ : t(($) => $.sections.action_empty)}emptyAction={hasActiveFilters && visibleItems.length === 0 ? (@@ -749,9 +784,28 @@ export function InboxPage() {</InboxContextMenuProvider>);+ const sectionTabs = isArchivedView ? null : (+ <Tabs+ value={section}+ onValueChange={(value) => setSection(value as InboxSection)}+ className="shrink-0 px-3 pb-2"+ >+ <TabsList className="w-full">+ <TabsTrigger value="action">+ {t(($) => $.sections.action)}+ {unreadCount > 0 && (+ <span className="text-caption tabular-nums text-brand">{unreadCount}</span>+ )}+ </TabsTrigger>+ <TabsTrigger value="activity">{t(($) => $.sections.activity)}</TabsTrigger>+ </TabsList>+ </Tabs>+ );+const listPanel = (<>{listHeader}+ {sectionTabs}{lookupLoading && (<p role="status" className="shrink-0 border-b px-3 py-2 text-caption text-muted-foreground">{t(($) => $.list.loading_selection)}@@ -1062,7 +1116,11 @@ export function InboxPage() {? t(($) => $.detail.select_prompt): isArchivedView? t(($) => $.list.archived_empty)- : t(($) => $.detail.empty)}+ : rawItems.some((i) => !i.archived)+ ? section === "activity"+ ? t(($) => $.sections.activity_empty)+ : t(($) => $.sections.action_empty)+ : t(($) => $.detail.empty)}</p></div></>diff --git a/packages/views/inbox/components/inbox-view.ts b/packages/views/inbox/components/inbox-view.tsindex a8d729c666..bcb744e0ef 100644--- a/packages/views/inbox/components/inbox-view.ts+++ b/packages/views/inbox/components/inbox-view.ts@@ -13,3 +13,10 @@export type InboxView = "inbox" | "archived";export const ARCHIVED_VIEW_PARAM = "archived";++/**+ * The main list's section, persisted as `?section=activity`; no parameter+ * means "action". A link that names an issue without a section (an OS banner,+ * a shared URL) still resolves: the page switches to the section that holds it.+ */+export const ACTIVITY_SECTION_PARAM = "activity";diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex fb029b2164..59683eaac3 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 { useMarkInboxReadWhileViewing } from "../hooks/use-mark-inbox-read-while-viewing";import { ReactionBar } from "@multica/ui/components/common/reaction-bar";import { useLocale, useTimeAgo } from "../../i18n";import {@@ -1555,6 +1556,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr},});useMarkIssueReadWhileViewing(wsId, issue?.id ?? "");+ useMarkInboxReadWhileViewing(wsId, issue?.id ?? "");const descriptionSourceId = `description:${id}`;const descriptionAnnotations = useCommentAnnotations({draftKey: `new:${id}`,diff --git a/packages/views/issues/hooks/use-mark-inbox-read-while-viewing.test.tsx b/packages/views/issues/hooks/use-mark-inbox-read-while-viewing.test.tsxnew file mode 100644index 0000000000..0a7128f0f3--- /dev/null+++ b/packages/views/issues/hooks/use-mark-inbox-read-while-viewing.test.tsx@@ -0,0 +1,151 @@+import { act, renderHook, waitFor } 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/queries";+import { onInboxNew } from "@multica/core/inbox/ws-updaters";+import type { InboxItem } from "@multica/core/types";+import { useMarkInboxReadWhileViewing } from "./use-mark-inbox-read-while-viewing";++vi.mock("@multica/core/api", () => ({+ api: {+ markIssueInboxRead: vi.fn(),+ getInboxUnreadSummary: vi.fn(),+ listInbox: vi.fn(),+ listArchivedInbox: vi.fn(),+ },+}));+vi.mock("../../common/use-app-foreground", () => ({ useAppForeground: () => true }));++function item(overrides: Partial<InboxItem> = {}): InboxItem {+ return {+ id: "inbox-1",+ workspace_id: "ws-1",+ recipient_type: "member",+ recipient_id: "member-1",+ actor_type: "member",+ actor_id: "member-2",+ type: "mentioned",+ severity: "info",+ issue_id: "issue-1",+ title: "Issue",+ body: null,+ issue_status: null,+ section: "action",+ read: false,+ archived: false,+ created_at: "2026-11-02T08:00:00Z",+ details: null,+ ...overrides,+ };+}++let client: ReturnType<typeof createQueryClient>;+const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+);++beforeEach(() => {+ client = createQueryClient();+ vi.mocked(api.markIssueInboxRead).mockResolvedValue({ count: 1 });+ vi.mocked(api.getInboxUnreadSummary).mockResolvedValue([]);+ vi.mocked(api.listInbox).mockResolvedValue([]);+});++afterEach(() => {+ client.clear();+ vi.resetAllMocks();+});++const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 50)));++describe("useMarkInboxReadWhileViewing", () => {+ it("marks the issue's inbox read once when it is opened", async () => {+ client.setQueryData(inboxKeys.unreadSummary(), [{ workspace_id: "ws-1", count: 1 }]);+ client.setQueryData(inboxKeys.list("ws-1"), [item()]);++ const { rerender } = renderHook(() => useMarkInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ await waitFor(() => expect(api.markIssueInboxRead).toHaveBeenCalledWith("issue-1"));+ rerender();+ await settle();++ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);+ });++ it("skips the request when the workspace has nothing unread", async () => {+ client.setQueryData(inboxKeys.unreadSummary(), []);++ renderHook(() => useMarkInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ await settle();++ expect(api.markIssueInboxRead).not.toHaveBeenCalled();+ });++ it("skips the request when the issue only has activity or read rows", async () => {+ client.setQueryData(inboxKeys.unreadSummary(), [{ workspace_id: "ws-1", count: 3 }]);+ client.setQueryData(inboxKeys.list("ws-1"), [+ item({ id: "status", type: "status_changed", section: "activity" }),+ item({ id: "read-mention", read: true }),+ item({ id: "elsewhere", issue_id: "issue-2" }),+ ]);++ renderHook(() => useMarkInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ await settle();++ expect(api.markIssueInboxRead).not.toHaveBeenCalled();+ });++ it("does not undo a manual mark-unread while the issue stays open", async () => {+ client.setQueryData(inboxKeys.unreadSummary(), [{ workspace_id: "ws-1", count: 1 }]);+ client.setQueryData(inboxKeys.list("ws-1"), [item()]);++ renderHook(() => useMarkInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });+ await waitFor(() => expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1));+ act(() => {+ client.setQueryData(inboxKeys.list("ws-1"), [item({ read: false })]);+ client.setQueryData(inboxKeys.unreadSummary(), [{ workspace_id: "ws-1", count: 2 }]);+ });+ await settle();++ expect(api.markIssueInboxRead).toHaveBeenCalledTimes(1);+ });++ it("marks again when another issue is opened", async () => {+ client.setQueryData(inboxKeys.unreadSummary(), [{ workspace_id: "ws-1", count: 2 }]);+ vi.mocked(api.getInboxUnreadSummary).mockResolvedValue([{ workspace_id: "ws-1", count: 1 }]);++ const { rerender } = renderHook(+ ({ issueId }) => useMarkInboxReadWhileViewing("ws-1", issueId),+ { wrapper, initialProps: { issueId: "issue-1" } },+ );+ await waitFor(() => expect(api.markIssueInboxRead).toHaveBeenCalledWith("issue-1"));+ rerender({ issueId: "issue-2" });+ await waitFor(() => expect(api.markIssueInboxRead).toHaveBeenCalledWith("issue-2"));+ });++ it("ignores an invalidated list that only holds the issue's old read row", async () => {+ vi.mocked(api.getInboxUnreadSummary).mockResolvedValue([{ workspace_id: "ws-1", count: 1 }]);+ vi.mocked(api.listInbox).mockResolvedValue([item({ id: "new-mention" })]);+ client.setQueryData(inboxKeys.list("ws-1"), [item({ id: "previous-mention", read: true })]);+ await onInboxNew(client, "ws-1", item({ id: "new-mention" }));+ expect(client.getQueryState(inboxKeys.list("ws-1"))?.isInvalidated).toBe(true);+ client.setQueryData(inboxKeys.unreadSummary(), [{ workspace_id: "ws-1", count: 1 }]);++ renderHook(() => useMarkInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });++ await waitFor(() => expect(api.markIssueInboxRead).toHaveBeenCalledWith("issue-1"));+ });++ it("waits for an invalidated zero summary to refresh before deciding", async () => {+ vi.mocked(api.getInboxUnreadSummary).mockResolvedValue([{ workspace_id: "ws-1", count: 1 }]);+ client.setQueryData(inboxKeys.unreadSummary(), []);+ await client.invalidateQueries({ queryKey: inboxKeys.unreadSummary() });++ renderHook(() => useMarkInboxReadWhileViewing("ws-1", "issue-1"), { wrapper });++ await waitFor(() => expect(api.getInboxUnreadSummary).toHaveBeenCalled());+ await waitFor(() => expect(api.markIssueInboxRead).toHaveBeenCalledWith("issue-1"));+ });+});diff --git a/packages/views/issues/hooks/use-mark-inbox-read-while-viewing.ts b/packages/views/issues/hooks/use-mark-inbox-read-while-viewing.tsnew file mode 100644index 0000000000..14c8d0b56b--- /dev/null+++ b/packages/views/issues/hooks/use-mark-inbox-read-while-viewing.ts@@ -0,0 +1,52 @@+import { useEffect, useRef } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useMarkIssueInboxRead } from "@multica/core/inbox/mutations";+import {+ inboxKeys,+ inboxUnreadSummaryEnabled,+ inboxUnreadSummaryOptions,+ isInboxItemUnread,+ unreadCountForWorkspace,+} from "@multica/core/inbox/queries";+import type { InboxItem, InboxWorkspaceUnread } from "@multica/core/types";+import { useAppForeground } from "../../common/use-app-foreground";++/**+ * Settles the issue's Inbox notifications when it is opened, from any surface+ * — the Work sidebar, search, a link — so the same event is never cleared+ * twice. Runs once per opening, in the foreground: a "Mark as unread" made+ * while the issue stays open is kept.+ *+ * Skips the request only on fresh evidence that nothing can be unread: a+ * settled workspace unread count of zero, or an up-to-date Inbox list with no+ * unread row for this issue. A summary that is refetching is waited for, and+ * an invalidated or stale list is ignored, so a mention that just arrived is+ * never skipped on old data.+ */+export function useMarkInboxReadWhileViewing(wsId: string, issueId: string) {+ const qc = useQueryClient();+ const foreground = useAppForeground();+ const { data: workspaceUnread, isSuccess, isFetching } = useQuery({+ ...inboxUnreadSummaryOptions(),+ enabled: inboxUnreadSummaryEnabled(wsId),+ select: (summary: InboxWorkspaceUnread[]) => unreadCountForWorkspace(summary, wsId),+ });+ const { mutate: markRead } = useMarkIssueInboxRead(wsId);+ const viewedIssueId = useRef<string | null>(null);++ useEffect(() => {+ if (!issueId || !foreground || !isSuccess || isFetching) return;+ if (viewedIssueId.current === issueId) return;+ viewedIssueId.current = issueId;+ if (workspaceUnread === 0) return;+ const listQuery = qc.getQueryCache().find<InboxItem[]>({+ queryKey: inboxKeys.list(wsId),+ exact: true,+ });+ const list = listQuery && !listQuery.isStale() ? listQuery.state.data : undefined;+ if (list && !list.some((item) => item.issue_id === issueId && !item.archived && isInboxItemUnread(item))) {+ return;+ }+ markRead(issueId);+ }, [issueId, foreground, isSuccess, isFetching, workspaceUnread, qc, wsId, markRead]);+}diff --git a/packages/views/layout/panels/list-space-peeks.tsx b/packages/views/layout/panels/list-space-peeks.tsxindex 6bf6512f98..c48fb69416 100644--- a/packages/views/layout/panels/list-space-peeks.tsx+++ b/packages/views/layout/panels/list-space-peeks.tsx@@ -14,7 +14,7 @@ import {} from "@multica/core/inbox/filter-store";import { useArchiveInbox } from "@multica/core/inbox/mutations";import {- deduplicateInboxItems,+ groupInboxItemsBySection,inboxListOptions,useInboxUnreadCount,} from "@multica/core/inbox/queries";@@ -33,8 +33,9 @@ const EMPTY_SESSIONS: ChatSession[] = [];const EMPTY_AGENTS: Agent[] = [];/**- * Inbox previewed from another space: the list the Inbox page shows, under- * the same saved filters. Opening a row lands on it in the Inbox.+ * Inbox previewed from another space: the list the Inbox page opens on (its+ * "needs action" section), under the same saved filters. Opening a row lands+ * on it in the Inbox.*/export function InboxPeek() {const { t } = useT("inbox");@@ -49,7 +50,7 @@ export function InboxPeek() {const items = useMemo(() => {const effective = inboxFiltersForPrioritySupport(filters, inboxPriorityFilterSupport(rawItems));- return filterInboxItems(deduplicateInboxItems(rawItems), effective, {+ return filterInboxItems(groupInboxItemsBySection(rawItems).action, effective, {activeIssueIds: effective.idleOnly ? new Set(activityByIssueId.keys()) : undefined,});}, [rawItems, filters, activityByIssueId]);diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.jsonindex ceb7c6ac9d..7fa5560abe 100644--- a/packages/views/locales/en/inbox.json+++ b/packages/views/locales/en/inbox.json@@ -3,6 +3,12 @@"title": "Inbox","back": "Inbox"},+ "sections": {+ "action": "Needs action",+ "activity": "Activity",+ "action_empty": "Nothing needs your attention",+ "activity_empty": "No recent activity"+ },"menu": {"mark_all_read": "Mark all as read","archive_all": "Archive all",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 9f2073396f..58db72b1c1 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -396,7 +396,7 @@"preferences": "Preferences","shortcuts": "Shortcuts","issue": "Issue",- "notifications": "Notifications",+ "notifications": "Inbox","tokens": "API Tokens","general": "General","github": "GitHub",@@ -652,38 +652,61 @@"toast_profile_failed": "Failed to update profile"},"notifications": {- "title": "Inbox Notifications",- "description": "Muted events remain visible on the issue.",+ "title": "Routing",+ "description": "Changes apply to new notifications.",+ "reset": "Restore defaults","toast_failed": "Failed to update notification settings",- "groups": {- "assignments": {- "label": "Assignments",- "description": "When you are assigned or unassigned from an issue"+ "routes": {+ "action": {+ "label": "Needs action",+ "description": "Counts as unread, can send a system notification"},- "status_changes": {- "label": "Status changes",- "description": "When an issue you follow changes status (e.g. todo, in progress, done)"+ "activity": {+ "label": "Activity",+ "description": "Recorded quietly, never unread"},- "comments": {- "label": "Comments",- "description": "New comments on issues you follow"+ "muted": {+ "label": "Off",+ "description": "Not in the Inbox; still visible on the issue"+ }+ },+ "kinds": {+ "assigned": {+ "label": "Assigned to me",+ "description": "When an issue is assigned to you"},"mentions": {"label": "Mentions","description": "When someone @mentions you, including @all and @squad"},+ "member_comments": {+ "label": "Member comments",+ "description": "When a member comments on an issue you follow"+ },+ "agent_failures": {+ "label": "Agent errors",+ "description": "When an agent run fails or is blocked and needs you"+ },+ "status_changes": {+ "label": "Status changes",+ "description": "When an issue you follow changes status"+ },+ "assignee_changes": {+ "label": "Assignee changes",+ "description": "When an issue changes assignee, or you are unassigned"+ },"updates": {- "label": "Priority & Due date",- "description": "When priority or due date changes on issues you follow"+ "label": "Priority and dates",+ "description": "When priority, start date, or due date changes"},- "agent_activity": {- "label": "Agent activity",- "description": "When an agent run fails"+ "agent_comments": {+ "label": "Agent comments",+ "description": "When an agent replies on an issue you follow"}},"system": {"title": "System Notifications",- "label": "Show system notifications when Multica is in the background"+ "label": "Send a system notification for Needs action items while Multica is in the background"},"browser": {"label": "Browser notifications",diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.jsonindex 5d48ee2d52..6a9d653add 100644--- a/packages/views/locales/fr/inbox.json+++ b/packages/views/locales/fr/inbox.json@@ -3,6 +3,12 @@"title": "Boîte de réception","back": "Boîte de réception"},+ "sections": {+ "action": "À traiter",+ "activity": "Activité",+ "action_empty": "Rien ne requiert votre attention",+ "activity_empty": "Aucune activité récente"+ },"menu": {"mark_all_read": "Tout marquer comme lu","archive_all": "Tout archiver",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex 415edae931..32394dbc0d 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -396,7 +396,7 @@"preferences": "Préférences","shortcuts": "Raccourcis","issue": "Tâche",- "notifications": "Notifications",+ "notifications": "Boîte de réception","tokens": "Jetons d'API","general": "Général","github": "GitHub",@@ -652,38 +652,61 @@"toast_profile_failed": "Échec de la mise à jour du profil"},"notifications": {- "title": "Notifications de la boîte de réception",- "description": "Les événements désactivés restent visibles dans la tâche.",+ "title": "Tri des notifications",+ "description": "Les changements s'appliquent aux nouvelles notifications.",+ "reset": "Rétablir les valeurs par défaut","toast_failed": "Échec de la mise à jour des réglages de notification",- "groups": {- "assignments": {- "label": "Assignations",- "description": "Quand une tâche vous est assignée ou retirée"+ "routes": {+ "action": {+ "label": "À traiter",+ "description": "Compte comme non lu, peut envoyer une notification système"},- "status_changes": {- "label": "Changements de statut",- "description": "Quand une tâche que vous suivez change de statut (à faire, en cours, terminé…)"+ "activity": {+ "label": "Activité",+ "description": "Consigné discrètement, jamais non lu"},- "comments": {- "label": "Commentaires",- "description": "Nouveaux commentaires sur les tâches que vous suivez"+ "muted": {+ "label": "Désactivé",+ "description": "Hors de la boîte de réception ; toujours visible sur la tâche"+ }+ },+ "kinds": {+ "assigned": {+ "label": "Assigné à moi",+ "description": "Quand une tâche vous est assignée"},"mentions": {"label": "Mentions",- "description": "Quand quelqu'un vous @mentionne, y compris via @all et @squad"+ "description": "Quand quelqu'un vous @mentionne, y compris @all et @squad"+ },+ "member_comments": {+ "label": "Commentaires des membres",+ "description": "Quand un membre commente une tâche que vous suivez"+ },+ "agent_failures": {+ "label": "Erreurs d'agent",+ "description": "Quand l'exécution d'un agent échoue ou est bloquée et requiert votre intervention"+ },+ "status_changes": {+ "label": "Changements de statut",+ "description": "Quand une tâche que vous suivez change de statut"+ },+ "assignee_changes": {+ "label": "Changements d'assigné",+ "description": "Quand une tâche change d'assigné, ou que vous n'êtes plus assigné"},"updates": {- "label": "Priorité et date d'échéance",- "description": "Quand la priorité ou la date d'échéance change sur les tâches que vous suivez"+ "label": "Priorité et dates",+ "description": "Quand la priorité, la date de début ou l'échéance change"},- "agent_activity": {- "label": "Activité des agents",- "description": "Lorsqu'une exécution d'agent échoue"+ "agent_comments": {+ "label": "Commentaires d'agent",+ "description": "Quand un agent répond sur une tâche que vous suivez"}},"system": {"title": "Notifications système",- "label": "Afficher les notifications système lorsque Multica est en arrière-plan"+ "label": "Envoyer une notification système pour les éléments « À traiter » quand Multica est en arrière-plan"},"browser": {"label": "Notifications du navigateur",diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.jsonindex 5b154dd71e..75b0206051 100644--- a/packages/views/locales/ja/inbox.json+++ b/packages/views/locales/ja/inbox.json@@ -3,6 +3,12 @@"title": "インボックス","back": "インボックス"},+ "sections": {+ "action": "要対応",+ "activity": "アクティビティ",+ "action_empty": "対応が必要なものはありません",+ "activity_empty": "最近のアクティビティはありません"+ },"menu": {"mark_all_read": "すべて既読にする","archive_all": "すべてアーカイブ",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 449db9c309..339a518a66 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -394,7 +394,7 @@"preferences": "環境設定","shortcuts": "ショートカット","issue": "タスク",- "notifications": "通知",+ "notifications": "インボックス","tokens": "API トークン","general": "一般","github": "GitHub",@@ -647,38 +647,61 @@"toast_profile_failed": "プロフィールを更新できませんでした"},"notifications": {- "title": "インボックス通知",- "description": "通知をオフにしても、タスク上で履歴を確認できます。",+ "title": "通知の振り分け",+ "description": "変更はこれからの通知に適用されます。",+ "reset": "デフォルトに戻す","toast_failed": "通知設定を更新できませんでした",- "groups": {- "assignments": {- "label": "担当の割り当て",- "description": "タスクの担当者に割り当てられたとき、または解除されたとき"+ "routes": {+ "action": {+ "label": "要対応",+ "description": "未読に数え、システム通知を送れる"},- "status_changes": {- "label": "ステータス変更",- "description": "フォロー中のタスクのステータスが変わったとき(例: todo、in progress、done)"+ "activity": {+ "label": "アクティビティ",+ "description": "静かに記録し、未読に数えない"},- "comments": {- "label": "コメント",- "description": "フォロー中のタスクに新しいコメントが付いたとき"+ "muted": {+ "label": "オフ",+ "description": "インボックスに入らない。課題では引き続き表示"+ }+ },+ "kinds": {+ "assigned": {+ "label": "自分への割り当て",+ "description": "課題が自分に割り当てられたとき"},"mentions": {"label": "メンション",- "description": "誰かがあなたを @メンションしたとき(@all と @squad を含む)"+ "description": "誰かがあなたを @ したとき(@all と @squad を含む)"+ },+ "member_comments": {+ "label": "メンバーのコメント",+ "description": "フォロー中の課題にメンバーがコメントしたとき"+ },+ "agent_failures": {+ "label": "エージェントのエラー",+ "description": "エージェントの実行が失敗またはブロックされ、対応が必要なとき"+ },+ "status_changes": {+ "label": "ステータス変更",+ "description": "フォロー中の課題のステータスが変わったとき"+ },+ "assignee_changes": {+ "label": "担当者の変更",+ "description": "課題の担当者が変わったとき、または割り当てが外れたとき"},"updates": {- "label": "優先度と期限",- "description": "フォロー中のタスクの優先度や期限が変わったとき"+ "label": "優先度と日付",+ "description": "優先度、開始日、期日が変わったとき"},- "agent_activity": {- "label": "エージェントのアクティビティ",- "description": "エージェントの実行が失敗したとき"+ "agent_comments": {+ "label": "エージェントのコメント",+ "description": "フォロー中の課題でエージェントが返信したとき"}},"system": {"title": "システム通知",- "label": "Multica がバックグラウンドにあるときにシステム通知を表示"+ "label": "Multica がバックグラウンドのとき、「要対応」の通知をシステム通知で知らせる"},"browser": {"label": "ブラウザ通知",diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.jsonindex dc66eb8d09..b6b31764d6 100644--- a/packages/views/locales/ko/inbox.json+++ b/packages/views/locales/ko/inbox.json@@ -3,6 +3,12 @@"title": "인박스","back": "인박스"},+ "sections": {+ "action": "처리 필요",+ "activity": "활동",+ "action_empty": "처리할 항목이 없습니다",+ "activity_empty": "최근 활동이 없습니다"+ },"menu": {"mark_all_read": "모두 읽음으로 표시","archive_all": "모두 보관",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex c9b3196cdd..02c1a58296 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -394,7 +394,7 @@"preferences": "환경설정","shortcuts": "단축키","issue": "태스크",- "notifications": "알림",+ "notifications": "인박스","tokens": "API 토큰","general": "일반","github": "GitHub",@@ -647,38 +647,61 @@"toast_profile_failed": "프로필을 업데이트하지 못했습니다"},"notifications": {- "title": "인박스 알림",- "description": "알림을 꺼도 태스크에서 관련 활동을 볼 수 있습니다.",+ "title": "알림 분류",+ "description": "변경 사항은 이후 새 알림에 적용됩니다.",+ "reset": "기본값 복원","toast_failed": "알림 설정을 업데이트하지 못했습니다",- "groups": {- "assignments": {- "label": "할당",- "description": "태스크에 할당되거나 할당 해제될 때"+ "routes": {+ "action": {+ "label": "처리 필요",+ "description": "읽지 않음으로 집계, 시스템 알림 가능"},- "status_changes": {- "label": "상태 변경",- "description": "팔로우 중인 태스크의 상태가 바뀔 때(예: 할 일, 진행 중, 완료)"+ "activity": {+ "label": "활동",+ "description": "조용히 기록, 읽지 않음 아님"},- "comments": {- "label": "댓글",- "description": "팔로우 중인 태스크에 새 댓글이 달릴 때"+ "muted": {+ "label": "끄기",+ "description": "인박스에 들어오지 않음. 이슈에서는 계속 표시"+ }+ },+ "kinds": {+ "assigned": {+ "label": "나에게 할당",+ "description": "이슈가 나에게 할당될 때"},"mentions": {"label": "멘션",- "description": "누군가 나를 @멘션할 때(@all, @squad 포함)"+ "description": "누군가 나를 @ 멘션할 때(@all, @squad 포함)"+ },+ "member_comments": {+ "label": "멤버 댓글",+ "description": "팔로우 중인 이슈에 멤버가 댓글을 달 때"+ },+ "agent_failures": {+ "label": "에이전트 오류",+ "description": "에이전트 실행이 실패하거나 막혀 내 개입이 필요할 때"+ },+ "status_changes": {+ "label": "상태 변경",+ "description": "팔로우 중인 이슈의 상태가 바뀔 때"+ },+ "assignee_changes": {+ "label": "담당자 변경",+ "description": "이슈 담당자가 바뀌거나 내 할당이 해제될 때"},"updates": {- "label": "우선순위 및 마감일",- "description": "팔로우 중인 태스크의 우선순위나 마감일이 바뀔 때"+ "label": "우선순위와 날짜",+ "description": "우선순위, 시작일, 마감일이 바뀔 때"},- "agent_activity": {- "label": "에이전트 활동",- "description": "에이전트 실행이 실패할 때"+ "agent_comments": {+ "label": "에이전트 댓글",+ "description": "팔로우 중인 이슈에 에이전트가 답할 때"}},"system": {"title": "시스템 알림",- "label": "Multica가 백그라운드에 있을 때 시스템 알림 표시"+ "label": "Multica가 백그라운드에 있을 때 '처리 필요' 알림을 시스템 알림으로 보내기"},"browser": {"label": "브라우저 알림",diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.jsonindex e2568ccfc0..3ae93b0175 100644--- a/packages/views/locales/zh-Hans/inbox.json+++ b/packages/views/locales/zh-Hans/inbox.json@@ -3,6 +3,12 @@"title": "收件箱","back": "收件箱"},+ "sections": {+ "action": "需要处理",+ "activity": "动态",+ "action_empty": "没有需要你处理的事",+ "activity_empty": "暂无动态"+ },"menu": {"mark_all_read": "全部标为已读","archive_all": "归档全部",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 090b7b8c58..315599b163 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -394,7 +394,7 @@"preferences": "偏好设置","shortcuts": "快捷键","issue": "任务",- "notifications": "通知",+ "notifications": "收件箱","tokens": "API Token","general": "常规","github": "GitHub",@@ -647,38 +647,61 @@"toast_profile_failed": "更新资料失败"},"notifications": {- "title": "收件箱通知",- "description": "关闭通知后,仍可在任务中查看相关动态。",+ "title": "通知去向",+ "description": "更改只影响之后的新通知。",+ "reset": "恢复默认","toast_failed": "更新通知设置失败",- "groups": {- "assignments": {- "label": "分配",- "description": "你被分配或取消分配某个任务时"+ "routes": {+ "action": {+ "label": "需要处理",+ "description": "计入未读,可弹出系统通知"},- "status_changes": {- "label": "状态变更",- "description": "你订阅的任务状态变化时(例如 todo、in_progress、done)"+ "activity": {+ "label": "动态",+ "description": "安静记录,不计未读"},- "comments": {- "label": "评论",- "description": "你订阅的任务有新评论时"+ "muted": {+ "label": "关闭",+ "description": "不进收件箱,在任务里仍能看到"+ }+ },+ "kinds": {+ "assigned": {+ "label": "分配给我",+ "description": "任务分配给你时"},"mentions": {"label": "提及","description": "有人 @ 你时,包括 @all 和 @squad"},+ "member_comments": {+ "label": "成员评论",+ "description": "成员在你订阅的任务里发表评论时"+ },+ "agent_failures": {+ "label": "智能体出错",+ "description": "智能体运行失败或被阻塞、需要你介入时"+ },+ "status_changes": {+ "label": "状态变更",+ "description": "你订阅的任务状态变化时"+ },+ "assignee_changes": {+ "label": "负责人变更",+ "description": "任务换了负责人,或你被取消分配时"+ },"updates": {- "label": "优先级与截止日期",- "description": "你订阅的任务优先级或截止日期变更时"+ "label": "优先级与日期",+ "description": "优先级、开始日期或截止日期变化时"},- "agent_activity": {- "label": "智能体活动",- "description": "智能体运行失败时"+ "agent_comments": {+ "label": "智能体评论",+ "description": "智能体在你订阅的任务里回复时"}},"system": {"title": "系统通知",- "label": "Multica 在后台时显示系统通知"+ "label": "Multica 在后台时,为「需要处理」的通知弹出系统通知"},"browser": {"label": "浏览器通知",diff --git a/packages/views/locales/zh-Hant/inbox.json b/packages/views/locales/zh-Hant/inbox.jsonindex 4b80c5d00a..b4af095169 100644--- a/packages/views/locales/zh-Hant/inbox.json+++ b/packages/views/locales/zh-Hant/inbox.json@@ -3,6 +3,12 @@"title": "收件箱","back": "收件箱"},+ "sections": {+ "action": "需要處理",+ "activity": "動態",+ "action_empty": "沒有需要你處理的事",+ "activity_empty": "暫無動態"+ },"menu": {"mark_all_read": "全部標為已讀","archive_all": "歸檔全部",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex ae04bef93d..e360dfa65b 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -394,7 +394,7 @@"preferences": "偏好設定","shortcuts": "快捷鍵","issue": "任務",- "notifications": "通知",+ "notifications": "收件箱","tokens": "API Token","general": "常規","github": "GitHub",@@ -647,38 +647,61 @@"toast_profile_failed": "更新資料失敗"},"notifications": {- "title": "收件箱通知",- "description": "關閉通知後,仍可在任務中檢視相關動態。",+ "title": "通知去向",+ "description": "變更只影響之後的新通知。",+ "reset": "恢復預設","toast_failed": "更新通知設定失敗",- "groups": {- "assignments": {- "label": "分配",- "description": "你被分配或取消分配某個任務時"+ "routes": {+ "action": {+ "label": "需要處理",+ "description": "計入未讀,可彈出系統通知"},- "status_changes": {- "label": "狀態變更",- "description": "你訂閱的任務狀態變化時(例如 todo、in_progress、done)"+ "activity": {+ "label": "動態",+ "description": "安靜記錄,不計未讀"},- "comments": {- "label": "評論",- "description": "你訂閱的任務有新評論時"+ "muted": {+ "label": "關閉",+ "description": "不進收件箱,在任務裡仍能看到"+ }+ },+ "kinds": {+ "assigned": {+ "label": "分配給我",+ "description": "任務分配給你時"},"mentions": {"label": "提及","description": "有人 @ 你時,包括 @all 和 @squad"},+ "member_comments": {+ "label": "成員評論",+ "description": "成員在你訂閱的任務裡發表評論時"+ },+ "agent_failures": {+ "label": "AI 代理出錯",+ "description": "AI 代理執行失敗或被阻塞、需要你介入時"+ },+ "status_changes": {+ "label": "狀態變更",+ "description": "你訂閱的任務狀態變化時"+ },+ "assignee_changes": {+ "label": "負責人變更",+ "description": "任務換了負責人,或你被取消分配時"+ },"updates": {- "label": "優先順序與截止日期",- "description": "你訂閱的任務優先順序或截止日期變更時"+ "label": "優先順序與日期",+ "description": "優先順序、開始日期或截止日期變化時"},- "agent_activity": {- "label": "AI 代理活動",- "description": "AI 代理執行失敗時"+ "agent_comments": {+ "label": "AI 代理評論",+ "description": "AI 代理在你訂閱的任務裡回覆時"}},"system": {"title": "系統通知",- "label": "Multica 在背景時顯示系統通知"+ "label": "Multica 在背景時,為「需要處理」的通知彈出系統通知"},"browser": {"label": "瀏覽器通知",@@ -1146,11 +1169,11 @@"scan_error_generate_failed": "未能從企業微信取得 QR 碼,請稍後再試。","scan_error_integration_unconfigured": "此伺服器未啟用掃碼安裝。","scan_error_installation_conflict": "這個機器人已在別處連線。請先在那裡斷開,再重新掃碼。",- "scan_error_bind_failed": "機器人已在企業微信裡建立,但沒能連到這個智慧體。請在企業微信裡刪掉它,再重新掃碼。",+ "scan_error_bind_failed": "機器人已在企業微信裡建立,但沒能連到這個AI 代理。請在企業微信裡刪掉它,再重新掃碼。","scan_error_wecom_protocol_error": "企業微信回傳了異常回應。","scan_error_internal_error": "發生問題,請再試一次。","scan_error_session_lost": "此安裝工作階段已失效,請重新取得 QR 碼。",- "scan_error_already_connected": "這個智慧體已經連線了企業微信機器人,請先斷開。",+ "scan_error_already_connected": "這個AI 代理已經連線了企業微信機器人,請先斷開。","scan_error_rate_limited": "嘗試次數過多,請幾分鐘後再試。","byo_failed_toast": "無法連線企業微信機器人"},diff --git a/packages/views/settings/components/notifications-tab.test.tsx b/packages/views/settings/components/notifications-tab.test.tsxnew file mode 100644index 0000000000..8c813af277--- /dev/null+++ b/packages/views/settings/components/notifications-tab.test.tsx@@ -0,0 +1,115 @@+import type { ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { I18nProvider } from "@multica/core/i18n/react";+import type { NotificationPreferences } from "@multica/core/types";+import enCommon from "../../locales/en/common.json";+import enSettings from "../../locales/en/settings.json";++const prefs = vi.hoisted(() => ({ current: {} as NotificationPreferences }));+const mutate = vi.hoisted(() => vi.fn());++vi.mock("@tanstack/react-query", () => ({+ useQuery: () => ({ data: { workspace_id: "workspace-1", preferences: prefs.current } }),+ queryOptions: <T,>(opts: T) => opts,+}));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));+vi.mock("@multica/core/notification-preferences/queries", () => ({+ notificationPreferenceOptions: () => ({}),+}));+vi.mock("@multica/core/notification-preferences/mutations", () => ({+ useUpdateNotificationPreferences: () => ({ mutate }),+}));+vi.mock("./browser-notification-setting", () => ({ BrowserNotificationSetting: () => null }));+vi.mock("sonner", () => ({ toast: { error: vi.fn() } }));++import { NotificationsTab } from "./notifications-tab";++const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };++function Wrapper({ children }: { children: ReactNode }) {+ return (+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ {children}+ </I18nProvider>+ );+}++const kinds = enSettings.notifications.kinds;+const routes = enSettings.notifications.routes;+const select = (label: string) => screen.getByRole("combobox", { name: label });++beforeEach(() => {+ vi.clearAllMocks();+ prefs.current = {};+});++describe("NotificationsTab", () => {+ it("shows every kind on its default section", () => {+ render(<NotificationsTab />, { wrapper: Wrapper });++ expect(select(kinds.assigned.label)).toHaveTextContent(routes.action.label);+ expect(select(kinds.mentions.label)).toHaveTextContent(routes.action.label);+ expect(select(kinds.status_changes.label)).toHaveTextContent(routes.activity.label);+ expect(select(kinds.agent_comments.label)).toHaveTextContent(routes.activity.label);+ expect(screen.getByRole("button", { name: enSettings.notifications.reset })).toBeDisabled();+ });++ it("shows a muted legacy group as off on both kinds it covered", () => {+ prefs.current = { comments: "muted" };+ render(<NotificationsTab />, { wrapper: Wrapper });++ expect(select(kinds.member_comments.label)).toHaveTextContent(routes.muted.label);+ expect(select(kinds.agent_comments.label)).toHaveTextContent(routes.muted.label);+ expect(select(kinds.mentions.label)).toHaveTextContent(routes.action.label);+ });++ it("routes a kind to the chosen section", async () => {+ const user = userEvent.setup();+ render(<NotificationsTab />, { wrapper: Wrapper });++ await user.click(select(kinds.status_changes.label));+ await user.click(await screen.findByRole("option", { name: new RegExp(`^${routes.action.label}`) }));++ await waitFor(() =>+ expect(mutate).toHaveBeenCalledWith({ status_changes: "action" }, expect.anything()),+ );+ });++ it("keeps the other half of a muted legacy group muted when one half changes", async () => {+ const user = userEvent.setup();+ prefs.current = { comments: "muted" };+ render(<NotificationsTab />, { wrapper: Wrapper });++ await user.click(select(kinds.member_comments.label));+ await user.click(await screen.findByRole("option", { name: new RegExp(`^${routes.action.label}`) }));++ await waitFor(() =>+ expect(mutate).toHaveBeenCalledWith({ agent_comments: "muted" }, expect.anything()),+ );+ });++ it("restores every kind to its default and keeps system notifications", async () => {+ const user = userEvent.setup();+ prefs.current = { status_changes: "action", comments: "muted", system_notifications: "muted" };+ render(<NotificationsTab />, { wrapper: Wrapper });++ await user.click(screen.getByRole("button", { name: enSettings.notifications.reset }));++ expect(mutate).toHaveBeenCalledWith({ system_notifications: "muted" }, expect.anything());+ });++ it("toggles system notifications without touching routes", async () => {+ const user = userEvent.setup();+ prefs.current = { status_changes: "action" };+ render(<NotificationsTab />, { wrapper: Wrapper });++ await user.click(screen.getByRole("switch", { name: enSettings.notifications.system.label }));++ expect(mutate).toHaveBeenCalledWith(+ { status_changes: "action", system_notifications: "muted" },+ expect.anything(),+ );+ });+});diff --git a/packages/views/settings/components/notifications-tab.tsx b/packages/views/settings/components/notifications-tab.tsxindex bab94ad457..f7911fe2b4 100644--- a/packages/views/settings/components/notifications-tab.tsx+++ b/packages/views/settings/components/notifications-tab.tsx@@ -4,7 +4,24 @@ import { useQuery } from "@tanstack/react-query";import { useWorkspaceId } from "@multica/core/hooks";import { notificationPreferenceOptions } from "@multica/core/notification-preferences/queries";import { useUpdateNotificationPreferences } from "@multica/core/notification-preferences/mutations";-import type { NotificationGroupKey, NotificationPreferences } from "@multica/core/types";+import {+ NOTIFICATION_ROUTE_KINDS,+ notificationRoutesAreDefault,+ resolveNotificationRoute,+ withDefaultNotificationRoutes,+ withNotificationRoute,+ type NotificationRouteKind,+} from "@multica/core/notification-preferences/routes";+import type { NotificationPreferences, NotificationRoute } from "@multica/core/types";+import { BellOff, Eye, RotateCcw } from "@multica/ui/icons";+import { Button } from "@multica/ui/components/ui/button";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@multica/ui/components/ui/select";import { Switch } from "@multica/ui/components/ui/switch";import { toast } from "sonner";import { useT } from "../../i18n";@@ -16,17 +33,19 @@ import {SettingsTab,} from "./settings-layout";-// Inbox event groups rendered in the per-event toggle list. `system_notifications`-// is a sibling preference key but lives in its own section below.-const INBOX_GROUP_KEYS = [- "assignments",- "status_changes",- "comments",- "mentions",- "updates",- "agent_activity",-] as const;-type InboxGroupKey = (typeof INBOX_GROUP_KEYS)[number];+const ROUTES: readonly NotificationRoute[] = ["action", "activity", "muted"];++function RouteMark({ route }: { route: NotificationRoute }) {+ if (route === "action") {+ return (+ <span className="flex size-4 items-center justify-center" aria-hidden>+ <span className="size-1.5 rounded-full bg-brand" />+ </span>+ );+ }+ const Icon = route === "activity" ? Eye : BellOff;+ return <Icon aria-hidden className="text-muted-foreground" />;+}export function NotificationsTab() {const { t } = useT("settings");@@ -36,16 +55,8 @@ export function NotificationsTab() {const preferences = data?.preferences ?? {};- const handleToggle = (key: NotificationGroupKey, enabled: boolean) => {- const updated: NotificationPreferences = {- ...preferences,- [key]: enabled ? "all" : "muted",- };- // Remove keys set to "all" (default) to keep the object clean- if (enabled) {- delete updated[key];- }- mutation.mutate(updated, {+ const save = (next: NotificationPreferences) => {+ mutation.mutate(next, {onError: (err) =>toast.error(err instanceof Error && err.message@@ -55,6 +66,58 @@ export function NotificationsTab() {});};+ const routeLabel = (route: NotificationRoute) => t(($) => $.notifications.routes[route].label);++ const routeSelect = (kind: NotificationRouteKind) => {+ const route = resolveNotificationRoute(preferences, kind);+ const label = t(($) => $.notifications.kinds[kind.key].label);+ return (+ <SettingsRow+ key={kind.key}+ anchor={kind.key}+ label={label}+ description={t(($) => $.notifications.kinds[kind.key].description)}+ size="select"+ >+ <Select+ items={ROUTES.map((value) => ({ value, label: routeLabel(value) }))}+ value={route}+ onValueChange={(value) => {+ if (value && value !== route) {+ save(withNotificationRoute(preferences, kind, value as NotificationRoute));+ }+ }}+ >+ <SelectTrigger size="sm" className="w-full" aria-label={label}>+ <SelectValue>+ <span className="flex items-center gap-2">+ <RouteMark route={route} />+ <span className={route === "muted" ? "text-muted-foreground" : undefined}>+ {routeLabel(route)}+ </span>+ </span>+ </SelectValue>+ </SelectTrigger>+ <SelectContent align="end" className="min-w-64">+ {ROUTES.map((value) => (+ <SelectItem key={value} value={value} className="items-start">+ <span className="mt-0.5 flex">+ <RouteMark route={value} />+ </span>+ <span className="flex flex-col">+ <span>{routeLabel(value)}</span>+ <span className="text-caption text-muted-foreground">+ {t(($) => $.notifications.routes[value].description)}+ </span>+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </SettingsRow>+ );+ };+const systemEnabled = preferences.system_notifications !== "muted";return (@@ -63,26 +126,19 @@ export function NotificationsTab() {title={t(($) => $.notifications.title)}description={t(($) => $.notifications.description)}anchor="inbox"+ action={+ <Button+ variant="ghost"+ size="sm"+ disabled={notificationRoutesAreDefault(preferences)}+ onClick={() => save(withDefaultNotificationRoutes(preferences))}+ >+ <RotateCcw />+ {t(($) => $.notifications.reset)}+ </Button>+ }>- <SettingsCard>- {INBOX_GROUP_KEYS.map((key: InboxGroupKey) => {- const enabled = preferences[key] !== "muted";- return (- <SettingsRow- key={key}- anchor={key}- label={t(($) => $.notifications.groups[key].label)}- description={t(($) => $.notifications.groups[key].description)}- >- <Switch- checked={enabled}- aria-label={t(($) => $.notifications.groups[key].label)}- onCheckedChange={(checked) => handleToggle(key, checked)}- />- </SettingsRow>- );- })}- </SettingsCard>+ <SettingsCard>{NOTIFICATION_ROUTE_KINDS.map(routeSelect)}</SettingsCard></SettingsSection><SettingsSection@@ -96,7 +152,12 @@ export function NotificationsTab() {<Switchchecked={systemEnabled}aria-label={t(($) => $.notifications.system.label)}- onCheckedChange={(checked) => handleToggle("system_notifications", checked)}+ onCheckedChange={(checked) => {+ const next: NotificationPreferences = { ...preferences };+ if (checked) delete next.system_notifications;+ else next.system_notifications = "muted";+ save(next);+ }}/></SettingsRow></SettingsCard>diff --git a/packages/views/settings/components/settings-page.test.tsx b/packages/views/settings/components/settings-page.test.tsxindex 7f7875637b..754d231fc4 100644--- a/packages/views/settings/components/settings-page.test.tsx+++ b/packages/views/settings/components/settings-page.test.tsx@@ -189,6 +189,7 @@ describe("SettingsPage header", () => {{ search: "", label: "Profile" },{ search: "tab=preferences", label: "Preferences" },{ search: "tab=shortcuts", label: "Shortcuts" },+ { search: "tab=notifications", label: "Inbox" },{ search: "tab=members", label: "Members" },{ search: "tab=channels", label: "Messaging" },{ search: "tab=mcp", label: "MCP servers" },diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsxindex e80bf23145..d81bfd5c07 100644--- a/packages/views/settings/components/settings-page.tsx+++ b/packages/views/settings/components/settings-page.tsx@@ -3,10 +3,10 @@import React, { useEffect, useMemo, useRef, useState } from "react";import {AlarmClock,- Bell,Blocks,CreditCard,FolderGit2,+ Inbox,Keyboard,KeyRound,ListPlus,@@ -142,7 +142,7 @@ export function SettingsPage({ extraDeviceTabs = [] }: SettingsPageProps = {}) {entry("notifications",t(($) => $.page.tabs.notifications),- Bell,+ Inbox,<NotificationsTab />,),entry(diff --git a/packages/views/settings/components/use-settings-search-index.ts b/packages/views/settings/components/use-settings-search-index.tsindex 97474cbbb3..ec0720db64 100644--- a/packages/views/settings/components/use-settings-search-index.ts+++ b/packages/views/settings/components/use-settings-search-index.ts@@ -1,19 +1,11 @@"use client";import { useMemo } from "react";+import { NOTIFICATION_ROUTE_KINDS } from "@multica/core/notification-preferences/routes";import { useT } from "../../i18n";import type { SettingsSearchEntry } from "./settings-search";import { CHANNEL_INTEGRATIONS } from "./settings-navigation";-const NOTIFICATION_GROUPS = [- "assignments",- "status_changes",- "comments",- "mentions",- "updates",- "agent_activity",-] as const;-export interface SettingsSearchPage {value: string;label: string;@@ -89,11 +81,17 @@ export function useSettingsSearchIndex(title: t(($) => $.preferences.issue_fields_title),description: t(($) => $.issue.description),},- ...NOTIFICATION_GROUPS.map((group) => ({+ {+ tab: "notifications",+ anchor: "inbox",+ title: t(($) => $.notifications.title),+ description: t(($) => $.notifications.description),+ },+ ...NOTIFICATION_ROUTE_KINDS.map(({ key }) => ({tab: "notifications",- anchor: group,- title: t(($) => $.notifications.groups[group].label),- description: t(($) => $.notifications.groups[group].description),+ anchor: key,+ title: t(($) => $.notifications.kinds[key].label),+ description: t(($) => $.notifications.kinds[key].description),})),{tab: "notifications",diff --git a/server/cmd/server/integration_test.go b/server/cmd/server/integration_test.goindex 70fb7f7590..13eceef1e9 100644--- a/server/cmd/server/integration_test.go+++ b/server/cmd/server/integration_test.go@@ -1394,12 +1394,13 @@ func TestInboxUnreadSummaryDedupesByIssue(t *testing.T) {})// Older sibling stays unread; newer sibling is read (the one "opening the- // issue" would have marked read).+ // issue" would have marked read). Both are action rows: activity never+ // takes part in the unread count.if _, err := testPool.Exec(ctx, `INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, type, title, issue_id, read, created_at)VALUES- ($1, 'member', $2, 'new_comment', 'older', $3, false, now() - interval '1 hour'),- ($1, 'member', $2, 'status_changed', 'newer', $3, true, now())+ ($1, 'member', $2, 'new_comment', 'older', $3, false, now() - interval '1 hour'),+ ($1, 'member', $2, 'mentioned', 'newer', $3, true, now())`, testWorkspaceID, testUserID, issueID); err != nil {t.Fatalf("failed to seed inbox items: %v", err)}diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.goindex e5fcccee68..052008d7b7 100644--- a/server/cmd/server/notification_listeners.go+++ b/server/cmd/server/notification_listeners.go@@ -170,34 +170,6 @@ func deliverToSubscriber(reason, notifType string, statusIsHandoff bool) bool {return statusIsHandoff}-// notifTypeToGroup maps each InboxItemType to a user-configurable preference-// group. Types not in this map are always delivered (not configurable).-var notifTypeToGroup = map[string]string{- "issue_assigned": "assignments",- "unassigned": "assignments",- "assignee_changed": "assignments",- "status_changed": "status_changes",- "new_comment": "comments",- "mentioned": "mentions",- "priority_changed": "updates",- "start_date_changed": "updates",- "due_date_changed": "updates",- "task_completed": "agent_activity",- "task_failed": "agent_activity",- "agent_blocked": "agent_activity",- "agent_completed": "agent_activity",-}--// isNotifMuted returns true if the given notification type is muted for a user-// based on their parsed preferences map.-func isNotifMuted(prefs map[string]string, notifType string) bool {- group, ok := notifTypeToGroup[notifType]- if !ok {- return false // unconfigurable types are always delivered- }- return prefs[group] == "muted"-}-// loadUserPrefs loads notification preferences for a set of user IDs in a// workspace. Returns a map from user_id string to parsed preferences.func loadUserPrefs(@@ -436,8 +408,9 @@ func notifyIssueSubscribers(continue}- // Skip if this notification type is muted by the user- if prefs, ok := userPrefs[subID]; ok && isNotifMuted(prefs, notifType) {+ // The recipient decides which Inbox section this lands in, or mutes it.+ section, routed := inbox.Route(userPrefs[subID], notifType, util.StrToText(e.ActorType))+ if !routed {continue}@@ -461,6 +434,7 @@ func notifyIssueSubscribers(ActorType: util.StrToText(e.ActorType),ActorID: optionalUUID(e.ActorID),Details: details,+ Section: inbox.SectionText(section),})if err != nil {slog.Error("subscriber notification creation failed",@@ -509,10 +483,13 @@ func notifyDirect(return}- // Check notification preferences for member recipients.+ // Member recipients route the notification through their preferences.+ section := inbox.DefaultSection(notifType, util.StrToText(e.ActorType))if recipientType == "member" {prefs := loadUserPrefs(ctx, queries, workspaceID, []string{recipientID})- if p, ok := prefs[recipientID]; ok && isNotifMuted(p, notifType) {+ var routed bool+ section, routed = inbox.Route(prefs[recipientID], notifType, util.StrToText(e.ActorType))+ if !routed {return}}@@ -530,6 +507,7 @@ func notifyDirect(ActorType: util.StrToText(e.ActorType),ActorID: optionalUUID(e.ActorID),Details: details,+ Section: inbox.SectionText(section),})if err != nil {slog.Error("direct notification creation failed",@@ -632,10 +610,10 @@ func notifyMentionedMembers(if id == e.ActorID || skip[id] {continue}- // Skip if mentions are muted by this user. This is deliberately a- // different group from `comments`: muting comment volume must not- // silence someone asking for you by name.- if p, ok := mentionPrefs[id]; ok && isNotifMuted(p, "mentioned") {+ // Mentions route on their own key, deliberately apart from comments:+ // muting comment volume must not silence someone asking for you by name.+ section, routed := inbox.Route(mentionPrefs[id], "mentioned", util.StrToText(e.ActorType))+ if !routed {continue}item, inserted, err := inbox.CreateIfEligible(context.Background(), queries, db.CreateInboxItemParams{@@ -650,6 +628,7 @@ func notifyMentionedMembers(ActorType: util.StrToText(e.ActorType),ActorID: optionalUUID(e.ActorID),Details: details,+ Section: inbox.SectionText(section),})if err != nil {slog.Error("mention inbox creation failed", "mentioned_id", id, "error", err)@@ -1090,6 +1069,7 @@ func inboxItemToResponse(item db.InboxItem) map[string]any {"recipient_id": util.UUIDToString(item.RecipientID),"type": item.Type,"severity": item.Severity,+ "section": inbox.ItemSection(item.Section, item.Type, item.ActorType),"issue_id": util.UUIDToPtr(item.IssueID),"title": item.Title,"body": util.TextToPtr(item.Body),diff --git a/server/cmd/server/notification_listeners_test.go b/server/cmd/server/notification_listeners_test.goindex 465048c12b..f6fe04ae3e 100644--- a/server/cmd/server/notification_listeners_test.go+++ b/server/cmd/server/notification_listeners_test.go@@ -325,6 +325,88 @@ func TestNotification_StatusChanged(t *testing.T) {}}+// TestNotification_StatusChanged_Routed verifies that each recipient's routing+// choice is stored on the row it creates, independent of other subscribers.+func TestNotification_StatusChanged_Routed(t *testing.T) {+ queries := db.New(testPool)+ bus := newNotificationBus(t, queries)+ var published []events.Event+ bus.Subscribe(protocol.EventInboxNew, func(e events.Event) { published = append(published, e) })++ recipients := map[string]string{}+ for _, name := range []string{"action", "legacy", "default"} {+ email := "notif-routed-status-" + name + "@multica.ai"+ recipients[name] = createNotificationMember(t, email)+ t.Cleanup(func() { cleanupTestUser(t, email) })+ }++ issueID := createTestIssue(t, testWorkspaceID, testUserID)+ t.Cleanup(func() {+ cleanupInboxForIssue(t, issueID)+ cleanupTestIssue(t, issueID)+ })++ for name, prefs := range map[string]string{+ "action": `{"status_changes":"action"}`,+ // A muted legacy group must not reach kinds it never covered.+ "legacy": `{"assignments":"muted"}`,+ } {+ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO notification_preference (workspace_id, user_id, preferences)+ VALUES ($1, $2, $3::jsonb)+ `, testWorkspaceID, recipients[name], prefs); err != nil {+ t.Fatalf("seed %s notification preference: %v", name, err)+ }+ }+ for _, id := range recipients {+ addTestSubscriber(t, issueID, "member", id, "commenter")+ }++ bus.Publish(events.Event{+ Type: protocol.EventIssueUpdated,+ WorkspaceID: testWorkspaceID,+ ActorType: "agent",+ ActorID: testUserID,+ Payload: map[string]any{+ "issue": handler.IssueResponse{+ ID: issueID,+ WorkspaceID: testWorkspaceID,+ Title: "routed status test issue",+ Status: "in_review",+ Priority: "medium",+ CreatorType: "member",+ CreatorID: testUserID,+ },+ "assignee_changed": false,+ "status_changed": true,+ "prev_status": "in_progress",+ },+ })++ want := map[string]string{"action": "action", "legacy": "activity", "default": "activity"}+ for name, section := range want {+ items := inboxItemsForRecipient(t, queries, recipients[name])+ if len(items) != 1 {+ t.Fatalf("%s: expected 1 item, got %d", name, len(items))+ }+ if !items[0].Section.Valid || items[0].Section.String != section {+ t.Errorf("%s: stored section = %+v, want %q", name, items[0].Section, section)+ }+ }+ if len(published) != len(want) {+ t.Fatalf("published %d inbox:new events, want %d", len(published), len(want))+ }+ for _, e := range published {+ payload, _ := e.Payload.(map[string]any)+ item, _ := payload["item"].(map[string]any)+ for name, id := range recipients {+ if item["recipient_id"] == id && item["section"] != want[name] {+ t.Errorf("%s: inbox:new section = %v, want %q", name, item["section"], want[name])+ }+ }+ }+}+// TestNotification_StatusChanged_Muted verifies that status_changes="muted"// prevents a new Inbox row without affecting other subscribers.func TestNotification_StatusChanged_Muted(t *testing.T) {diff --git a/server/cmd/server/notification_mute_group_test.go b/server/cmd/server/notification_mute_group_test.godeleted file mode 100644index d50a6673fb..0000000000--- a/server/cmd/server/notification_mute_group_test.go+++ /dev/null@@ -1,47 +0,0 @@-package main--import "testing"--// TestIsNotifMutedGroupSplit pins the contract the `mentions` group exists for:-// muting comment VOLUME must never silence someone asking for you BY NAME.-// `new_comment` and `mentioned` shared the `comments` group until #6468, so a-// user who muted comment churn also lost every mention — and a muted item is-// never created, so it was unrecoverable rather than merely delayed.-func TestIsNotifMutedGroupSplit(t *testing.T) {- cases := []struct {- name string- prefs map[string]string- notifType string- want bool- }{- // The regression this split fixes.- {"muted comments still delivers mentions", map[string]string{"comments": "muted"}, "mentioned", false},- {"muted comments drops new_comment", map[string]string{"comments": "muted"}, "new_comment", true},- {"muted mentions drops mentioned", map[string]string{"mentions": "muted"}, "mentioned", true},- {"muted mentions still delivers new_comment", map[string]string{"mentions": "muted"}, "new_comment", false},- {"both muted drops both", map[string]string{"comments": "muted", "mentions": "muted"}, "mentioned", true},-- // Absent key means the default "all" — preferences are stored sparse,- // which is why existing `{"comments":"muted"}` rows need no migration.- {"empty prefs delivers mentions", map[string]string{}, "mentioned", false},- {"empty prefs delivers comments", map[string]string{}, "new_comment", false},- {"explicit all delivers", map[string]string{"comments": "all"}, "new_comment", false},-- // Other groups are unaffected by the split.- {"assignments group intact", map[string]string{"assignments": "muted"}, "issue_assigned", true},- {"status group intact", map[string]string{"status_changes": "muted"}, "status_changed", true},- {"muting comments leaves assignments alone", map[string]string{"comments": "muted"}, "issue_assigned", false},-- // Types outside the map are always delivered.- {"unconfigurable type always delivered", map[string]string{"comments": "muted"}, "reaction_added", false},- }-- for _, tc := range cases {- t.Run(tc.name, func(t *testing.T) {- if got := isNotifMuted(tc.prefs, tc.notifType); got != tc.want {- t.Fatalf("isNotifMuted(%v, %q) = %v, want %v",- tc.prefs, tc.notifType, got, tc.want)- }- })- }-}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex f50159461f..228b06b8f5 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2564,6 +2564,7 @@ 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)+ 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..c201429b43 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -8,6 +8,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/inbox""github.com/multica-ai/multica/server/internal/logger"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -20,6 +21,7 @@ type InboxItemResponse struct {RecipientID string `json:"recipient_id"`Type string `json:"type"`Severity string `json:"severity"`+ Section string `json:"section"`IssueID *string `json:"issue_id"`Title string `json:"title"`Body *string `json:"body"`@@ -41,6 +43,7 @@ func inboxToResponse(i db.InboxItem) InboxItemResponse {RecipientID: uuidToString(i.RecipientID),Type: i.Type,Severity: i.Severity,+ Section: inbox.ItemSection(i.Section, i.Type, i.ActorType),IssueID: uuidToPtr(i.IssueID),Title: i.Title,Body: textToPtr(i.Body),@@ -117,6 +120,7 @@ func inboxRowToResponse(r db.ListInboxItemsRow) InboxItemResponse {RecipientID: uuidToString(r.RecipientID),Type: r.Type,Severity: r.Severity,+ Section: inbox.ItemSection(r.Section, r.Type, r.ActorType),IssueID: uuidToPtr(r.IssueID),Title: r.Title,Body: inboxListBody(r.Type, r.IssueID, r.Body),@@ -239,6 +243,27 @@ func (h *Handler) MarkInboxRead(w http.ResponseWriter, r *http.Request) {"recipient_id": uuidToString(item.RecipientID),})+ // Reading one row settles the whole issue, as opening the issue does.+ // Clients from before the Inbox sections group an issue under its newest+ // row, which may be activity, and mark only that row; an older unread+ // action row would otherwise keep the badge lit with nothing left to open.+ if item.IssueID.Valid && item.RecipientType == "member" {+ count, err := h.Queries.MarkInboxReadByIssue(r.Context(), db.MarkInboxReadByIssueParams{+ WorkspaceID: item.WorkspaceID,+ RecipientID: item.RecipientID,+ IssueID: item.IssueID,+ })+ if err != nil {+ slog.Warn("mark issue inbox read after item read failed", append(logger.RequestAttrs(r), "error", err)...)+ } else if count > 0 {+ h.publish(protocol.EventInboxBatchRead, workspaceID, "member", userID, map[string]any{+ "recipient_id": uuidToString(item.RecipientID),+ "issue_id": uuidToString(item.IssueID),+ "count": count,+ })+ }+ }+resp := h.enrichInboxResponse(r.Context(), inboxToResponse(item), item.IssueID)writeJSON(w, http.StatusOK, resp)}@@ -255,7 +280,14 @@ func (h *Handler) MarkInboxUnread(w http.ResponseWriter, r *http.Request) {if !ok {return}- item, err := h.Queries.MarkInboxUnread(r.Context(), prev.ID)+ // Activity is never unread, so an explicit "mark unread" on it (only+ // clients from before the Inbox sections offer one) files it under Needs+ // action: it counts again and archive-all-read leaves it in place.+ params := db.MarkInboxUnreadParams{ID: prev.ID}+ if inbox.ItemSection(prev.Section, prev.Type, prev.ActorType) == inbox.SectionActivity {+ params.Section = inbox.SectionText(inbox.SectionAction)+ }+ item, err := h.Queries.MarkInboxUnread(r.Context(), params)if err != nil {writeError(w, http.StatusInternalServerError, "failed to mark unread")return@@ -284,14 +316,28 @@ func (h *Handler) ArchiveInboxItem(w http.ResponseWriter, r *http.Request) {return}- // Archive all sibling inbox items for the same issue (issue-level archive)+ // Archive the sibling inbox items for the same issue. An action row takes+ // the whole issue with it; an activity row only clears the issue's other+ // activity, so an unread mention or failure on it stays in the inbox.+ section := inbox.ItemSection(item.Section, item.Type, item.ActorType)if item.IssueID.Valid {- h.Queries.ArchiveInboxByIssue(r.Context(), db.ArchiveInboxByIssueParams{- WorkspaceID: item.WorkspaceID,- RecipientType: item.RecipientType,- RecipientID: item.RecipientID,- IssueID: item.IssueID,- })+ if section == inbox.SectionActivity {+ h.Queries.ArchiveInboxActivityByIssue(r.Context(), db.ArchiveInboxActivityByIssueParams{+ WorkspaceID: item.WorkspaceID,+ RecipientType: item.RecipientType,+ RecipientID: item.RecipientID,+ IssueID: item.IssueID,+ ActivityTypes: inbox.ActivityTypes,+ AgentActivityTypes: inbox.AgentActivityTypes,+ })+ } else {+ h.Queries.ArchiveInboxByIssue(r.Context(), db.ArchiveInboxByIssueParams{+ WorkspaceID: item.WorkspaceID,+ RecipientType: item.RecipientType,+ RecipientID: item.RecipientID,+ IssueID: item.IssueID,+ })+ }}userID := requestUserID(r)@@ -299,6 +345,7 @@ func (h *Handler) ArchiveInboxItem(w http.ResponseWriter, r *http.Request) {h.publish(protocol.EventInboxArchived, workspaceID, "member", userID, map[string]any{"item_id": uuidToString(item.ID),"issue_id": uuidToPtr(item.IssueID),+ "section": section,"recipient_id": uuidToString(item.RecipientID),})@@ -360,9 +407,11 @@ func (h *Handler) CountUnreadInbox(w http.ResponseWriter, r *http.Request) {}count, err := h.Queries.CountUnreadInbox(r.Context(), db.CountUnreadInboxParams{- WorkspaceID: wsUUID,- RecipientType: "member",- RecipientID: parseUUID(userID),+ WorkspaceID: wsUUID,+ RecipientType: "member",+ RecipientID: parseUUID(userID),+ ActivityTypes: inbox.ActivityTypes,+ AgentActivityTypes: inbox.AgentActivityTypes,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to count unread inbox")@@ -391,7 +440,11 @@ func (h *Handler) UnreadInboxSummary(w http.ResponseWriter, r *http.Request) {return}- rows, err := h.Queries.CountUnreadInboxByWorkspace(r.Context(), parseUUID(userID))+ rows, err := h.Queries.CountUnreadInboxByWorkspace(r.Context(), db.CountUnreadInboxByWorkspaceParams{+ RecipientID: parseUUID(userID),+ ActivityTypes: inbox.ActivityTypes,+ AgentActivityTypes: inbox.AgentActivityTypes,+ })if err != nil {writeError(w, http.StatusInternalServerError, "failed to summarize unread inbox")return@@ -437,6 +490,39 @@ func (h *Handler) MarkAllInboxRead(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, map[string]any{"count": count})}+// MarkIssueInboxRead marks every active notification on one issue read for+// the caller. Clients call it whenever an issue is opened, from any surface,+// so reading an issue through the Work sidebar also settles its inbox rows.+func (h *Handler) MarkIssueInboxRead(w http.ResponseWriter, r *http.Request) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ issue, ok := h.loadIssueForUser(w, r, chi.URLParam(r, "issueId"))+ if !ok {+ return+ }++ count, err := h.Queries.MarkInboxReadByIssue(r.Context(), db.MarkInboxReadByIssueParams{+ WorkspaceID: issue.WorkspaceID,+ RecipientID: parseUUID(userID),+ IssueID: issue.ID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to mark issue inbox read")+ return+ }++ if count > 0 {+ h.publish(protocol.EventInboxBatchRead, uuidToString(issue.WorkspaceID), "member", userID, map[string]any{+ "recipient_id": userID,+ "issue_id": uuidToString(issue.ID),+ "count": count,+ })+ }+ 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 {@@ -478,8 +564,10 @@ func (h *Handler) ArchiveAllReadInbox(w http.ResponseWriter, r *http.Request) {}count, err := h.Queries.ArchiveAllReadInbox(r.Context(), db.ArchiveAllReadInboxParams{- WorkspaceID: wsUUID,- RecipientID: parseUUID(userID),+ WorkspaceID: wsUUID,+ RecipientID: parseUUID(userID),+ ActivityTypes: inbox.ActivityTypes,+ AgentActivityTypes: inbox.AgentActivityTypes,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to archive all read inbox")diff --git a/server/internal/handler/inbox_archive.go b/server/internal/handler/inbox_archive.goindex bdf33694bb..913b4a20bd 100644--- a/server/internal/handler/inbox_archive.go+++ b/server/internal/handler/inbox_archive.go@@ -12,6 +12,7 @@ import ("time""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/inbox"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -96,6 +97,7 @@ func (h *Handler) ListArchivedInboxPage(w http.ResponseWriter, r *http.Request)p := db.ListArchivedInboxPageParams{WorkspaceID: filters.WorkspaceID, RecipientID: filters.RecipientID,Statuses: filters.Statuses, Priorities: filters.Priorities, Actors: filters.Actors, UnreadOnly: filters.UnreadOnly,+ ActivityTypes: inbox.ActivityTypes, AgentActivityTypes: inbox.AgentActivityTypes,}limit := 50if raw := r.URL.Query().Get("limit"); raw != "" {@@ -176,6 +178,9 @@ func (h *Handler) GetArchivedInboxFacets(w http.ResponseWriter, r *http.Request)if !ok {return}+ // Set after parsing, not inside it: the parsed filters also key the page+ // cursor scope, which must not change when the section rule does.+ p.ActivityTypes, p.AgentActivityTypes = inbox.ActivityTypes, inbox.AgentActivityTypesrows, err := h.Queries.ArchivedInboxFacets(r.Context(), p)if err != nil {writeError(w, http.StatusInternalServerError, "failed to load archived inbox filters")diff --git a/server/internal/handler/inbox_section_test.go b/server/internal/handler/inbox_section_test.gonew file mode 100644index 0000000000..b3eb6b5bb7--- /dev/null+++ b/server/internal/handler/inbox_section_test.go@@ -0,0 +1,392 @@+package handler++import (+ "net/http"+ "testing"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/testutil"+)++type sectionFixture struct {+ t *testing.T+ workspaceID string+}++func newSectionFixture(t *testing.T, name string) sectionFixture {+ t.Helper()+ workspaceID := dbfx.Workspace(t, name, "inbox-section-"+uuid.NewString())+ dbfx.Member(t, workspaceID, testUserID, "owner")+ dbfx.Cleanup(t, `DELETE FROM inbox_item WHERE workspace_id = $1`, workspaceID)+ return sectionFixture{t: t, workspaceID: workspaceID}+}++func (f sectionFixture) issue(title string) string {+ f.t.Helper()+ return dbfx.Issue(f.t, title, testutil.Cols{"workspace_id": f.workspaceID})+}++// item inserts one active notification for the test user. actorType "" leaves+// actor_type NULL, as system-authored rows have it.+func (f sectionFixture) item(issueID, notifType, actorType, title string, read bool, createdAt testutil.Raw) string {+ f.t.Helper()+ cols := testutil.Cols{+ "workspace_id": f.workspaceID,+ "recipient_type": "member",+ "recipient_id": testUserID,+ "type": notifType,+ "severity": "info",+ "issue_id": issueID,+ "title": title,+ "read": read,+ "created_at": createdAt,+ }+ if actorType != "" {+ cols["actor_type"] = actorType+ }+ return dbfx.Insert(f.t, "inbox_item", cols)+}++// routed inserts an unread notification whose section was chosen by the+// recipient's routing preferences when it was created.+func (f sectionFixture) routed(issueID, notifType, actorType, title, section string, createdAt testutil.Raw) string {+ f.t.Helper()+ id := f.item(issueID, notifType, actorType, title, false, createdAt)+ dbfx.Exec(f.t, `UPDATE inbox_item SET section = $2 WHERE id = $1`, id, section)+ return id+}++func (f sectionFixture) unreadSummary() int64 {+ f.t.Helper()+ var summary []InboxWorkspaceUnreadResponse+ testutil.Call(f.t, testHandler.UnreadInboxSummary,+ inboxRequest(http.MethodGet, "/api/inbox/unread-summary", f.workspaceID)).+ Want(http.StatusOK).+ JSON(&summary)+ for _, row := range summary {+ if row.WorkspaceID == f.workspaceID {+ return row.Count+ }+ }+ return 0+}++func (f sectionFixture) archived(title string) bool {+ f.t.Helper()+ return dbfx.Count(f.t,+ "SELECT count(*) FROM inbox_item WHERE workspace_id = $1 AND title = $2 AND archived = true",+ f.workspaceID, title) == 1+}++func (f sectionFixture) read(title string) bool {+ f.t.Helper()+ return dbfx.Count(f.t,+ "SELECT count(*) FROM inbox_item WHERE workspace_id = $1 AND title = $2 AND read = true",+ f.workspaceID, title) == 1+}++func TestListInboxReturnsSection(t *testing.T) {+ f := newSectionFixture(t, "Inbox section field")+ issueID := f.issue("Section field")+ f.item(issueID, "mentioned", "member", "mention", false, "now() - interval '4 minutes'")+ f.item(issueID, "status_changed", "agent", "agent status", false, "now() - interval '3 minutes'")+ f.item(issueID, "new_comment", "agent", "agent comment", false, "now() - interval '2 minutes'")+ f.item(issueID, "new_comment", "member", "member comment", false, "now() - interval '1 minute'")++ var items []InboxItemResponse+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListInbox),+ inboxRequest(http.MethodGet, "/api/inbox", f.workspaceID)).+ Want(http.StatusOK).+ JSON(&items)++ want := map[string]string{+ "mention": "action",+ "agent status": "activity",+ "agent comment": "activity",+ "member comment": "action",+ }+ if len(items) != len(want) {+ t.Fatalf("items = %d, want %d: %+v", len(items), len(want), items)+ }+ for _, item := range items {+ if item.Section != want[item.Title] {+ t.Errorf("%s: section = %q, want %q", item.Title, item.Section, want[item.Title])+ }+ }+}++func TestUnreadCountsIgnoreActivity(t *testing.T) {+ f := newSectionFixture(t, "Inbox unread sections")+ // Only routine activity, all stored unread: nothing to count.+ quietIssue := f.issue("Agent finished")+ f.item(quietIssue, "status_changed", "agent", "quiet status", false, "now() - interval '3 minutes'")+ f.item(quietIssue, "new_comment", "agent", "quiet comment", false, "now() - interval '2 minutes'")+ // An unread mention followed by newer activity: the activity must neither+ // count nor decide the group's state.+ mentionIssue := f.issue("Mentioned")+ f.item(mentionIssue, "mentioned", "member", "mention", false, "now() - interval '3 minutes'")+ f.item(mentionIssue, "status_changed", "agent", "later status", true, "now() - interval '1 minute'")+ // A person commenting without a mention still wants the recipient.+ commentIssue := f.issue("Member comment")+ f.item(commentIssue, "new_comment", "member", "member comment", false, "now() - interval '1 minute'")+ // Read action rows never count.+ readIssue := f.issue("Already handled")+ f.item(readIssue, "issue_assigned", "member", "handled", true, "now() - interval '1 minute'")++ var summary []InboxWorkspaceUnreadResponse+ testutil.Call(t, testHandler.UnreadInboxSummary,+ inboxRequest(http.MethodGet, "/api/inbox/unread-summary", f.workspaceID)).+ Want(http.StatusOK).+ JSON(&summary)+ var grouped int64+ for _, row := range summary {+ if row.WorkspaceID == f.workspaceID {+ grouped = row.Count+ }+ }+ if grouped != 2 {+ t.Fatalf("unread summary = %d, want 2 (mention + member comment): %+v", grouped, summary)+ }++ var raw struct {+ Count int64 `json:"count"`+ }+ testutil.Call(t, inboxWorkspaceHandler(testHandler.CountUnreadInbox),+ inboxRequest(http.MethodGet, "/api/inbox/unread-count", f.workspaceID)).+ Want(http.StatusOK).+ JSON(&raw)+ if raw.Count != 2 {+ t.Fatalf("unread count = %d, want 2", raw.Count)+ }+}++func TestArchiveAllReadInboxGroupsBySection(t *testing.T) {+ f := newSectionFixture(t, "Archive read by section")+ issueID := f.issue("Mixed sections")+ f.item(issueID, "mentioned", "member", "unread mention", false, "now() - interval '3 minutes'")+ f.item(issueID, "status_changed", "agent", "newer activity", false, "now() - interval '1 minute'")+ readIssue := f.issue("Read action")+ f.item(readIssue, "issue_assigned", "member", "read assignment", true, "now() - interval '1 minute'")++ testutil.Call(t, inboxWorkspaceHandler(testHandler.ArchiveAllReadInbox),+ inboxRequest(http.MethodPost, "/api/inbox/archive-all-read", f.workspaceID)).+ Want(http.StatusOK)++ if !f.archived("newer activity") {+ t.Error("activity counts as read and should be archived")+ }+ if f.archived("unread mention") {+ t.Error("an unread action row was archived alongside the issue's activity")+ }+ if !f.archived("read assignment") {+ t.Error("a read action group should be archived")+ }+}++func TestArchiveInboxItemScopesActivityToSection(t *testing.T) {+ f := newSectionFixture(t, "Archive item by section")+ issueID := f.issue("Archive scope")+ mentionID := f.item(issueID, "mentioned", "member", "mention", false, "now() - interval '3 minutes'")+ activityID := f.item(issueID, "status_changed", "agent", "status", false, "now() - interval '2 minutes'")+ f.item(issueID, "new_comment", "agent", "agent comment", false, "now() - interval '1 minute'")++ testutil.Call(t, inboxWorkspaceHandler(testHandler.ArchiveInboxItem),+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/"+activityID+"/archive", f.workspaceID), "id", activityID)).+ Want(http.StatusOK)++ if !f.archived("status") || !f.archived("agent comment") {+ t.Fatal("archiving an activity row should clear the issue's activity")+ }+ if f.archived("mention") {+ t.Fatal("archiving an activity row archived the issue's mention")+ }++ testutil.Call(t, inboxWorkspaceHandler(testHandler.ArchiveInboxItem),+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/"+mentionID+"/archive", f.workspaceID), "id", mentionID)).+ Want(http.StatusOK)+ if !f.archived("mention") {+ t.Fatal("archiving an action row should archive it")+ }+}++func TestMarkIssueInboxRead(t *testing.T) {+ f := newSectionFixture(t, "Mark issue inbox read")+ issueID := f.issue("Opened from Work")+ otherIssueID := f.issue("Not opened")+ f.item(issueID, "mentioned", "member", "mention", false, "now() - interval '3 minutes'")+ f.item(issueID, "status_changed", "agent", "status", false, "now() - interval '2 minutes'")+ f.item(otherIssueID, "issue_assigned", "member", "other", false, "now() - interval '1 minute'")++ call := func(id string) *testutil.Response {+ return testutil.Call(t, inboxWorkspaceHandler(testHandler.MarkIssueInboxRead),+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/issues/"+id+"/read", f.workspaceID), "issueId", id))+ }++ var resp struct {+ Count int64 `json:"count"`+ }+ call(issueID).Want(http.StatusOK).JSON(&resp)+ if resp.Count != 2 {+ t.Fatalf("count = %d, want 2", resp.Count)+ }+ if !f.read("mention") || !f.read("status") {+ t.Fatal("every row on the opened issue should be read")+ }+ if f.read("other") {+ t.Fatal("another issue's notification was marked read")+ }++ call(issueID).Want(http.StatusOK).JSON(&resp)+ if resp.Count != 0 {+ t.Fatalf("second call count = %d, want 0", resp.Count)+ }++ foreignWorkspaceID := dbfx.Workspace(t, "Foreign inbox issue", "inbox-section-foreign-"+uuid.NewString())+ foreignIssueID := dbfx.Issue(t, "Foreign", testutil.Cols{"workspace_id": foreignWorkspaceID})+ call(foreignIssueID).Want(http.StatusNotFound)+}++func TestStoredSectionOverridesDefault(t *testing.T) {+ f := newSectionFixture(t, "Routed sections")+ statusIssue := f.issue("Status routed to action")+ f.routed(statusIssue, "status_changed", "agent", "routed status", "action", "now() - interval '2 minutes'")+ mentionIssue := f.issue("Mention routed to activity")+ f.routed(mentionIssue, "mentioned", "member", "routed mention", "activity", "now() - interval '1 minute'")++ var items []InboxItemResponse+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListInbox),+ inboxRequest(http.MethodGet, "/api/inbox", f.workspaceID)).+ Want(http.StatusOK).+ JSON(&items)+ want := map[string]string{"routed status": "action", "routed mention": "activity"}+ for _, item := range items {+ if item.Section != want[item.Title] {+ t.Errorf("%s: section = %q, want %q", item.Title, item.Section, want[item.Title])+ }+ }++ if got := f.unreadSummary(); got != 1 {+ t.Fatalf("unread summary = %d, want 1 (the status routed to action)", got)+ }++ testutil.Call(t, inboxWorkspaceHandler(testHandler.ArchiveAllReadInbox),+ inboxRequest(http.MethodPost, "/api/inbox/archive-all-read", f.workspaceID)).+ Want(http.StatusOK)+ if !f.archived("routed mention") {+ t.Error("a mention routed to activity counts as read and should be archived")+ }+ if f.archived("routed status") {+ t.Error("an unread status routed to action was archived")+ }+}++// Clients from before the Inbox sections group rows once per issue across+// sections and mark only the newest row read through the item endpoint. That+// must still settle the issue, or an older unread mention keeps the badge lit+// with nothing left in their list to open.+func TestMarkInboxReadSettlesIssueForLegacyClients(t *testing.T) {+ f := newSectionFixture(t, "Legacy inbox read")+ issueID := f.issue("Mention then status")+ otherIssueID := f.issue("Untouched")+ f.item(issueID, "mentioned", "member", "older unread mention", false, "now() - interval '3 minutes'")+ activityID := f.item(issueID, "status_changed", "agent", "newer status", false, "now() - interval '2 minutes'")+ f.item(otherIssueID, "issue_assigned", "member", "other issue", false, "now() - interval '1 minute'")++ testutil.Call(t, inboxWorkspaceHandler(testHandler.MarkInboxRead),+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/"+activityID+"/read", f.workspaceID), "id", activityID)).+ Want(http.StatusOK)++ if !f.read("older unread mention") || !f.read("newer status") {+ t.Fatal("reading one row should settle every row of its issue")+ }+ if f.read("other issue") {+ t.Fatal("reading one row marked another issue's notification read")+ }+ if got := f.unreadSummary(); got != 1 {+ t.Fatalf("unread summary = %d, want 1 (the other issue)", got)+ }+}++func TestArchivedInboxTreatsActivityAsRead(t *testing.T) {+ f := newSectionFixture(t, "Archived activity is read")+ activityIssue := f.issue("Archived activity")+ actionIssue := f.issue("Archived mention")+ for _, cols := range []testutil.Cols{+ {"issue_id": activityIssue, "type": "status_changed", "actor_type": "agent", "title": "activity"},+ {"issue_id": actionIssue, "type": "mentioned", "actor_type": "member", "title": "mention"},+ } {+ cols["workspace_id"] = f.workspaceID+ cols["recipient_type"] = "member"+ cols["recipient_id"] = testUserID+ cols["severity"] = "info"+ cols["read"] = false+ cols["archived"] = true+ dbfx.Insert(t, "inbox_item", cols)+ }++ var facets archivedInboxFacetsResponse+ testutil.Call(t, inboxWorkspaceHandler(testHandler.GetArchivedInboxFacets),+ inboxRequest(http.MethodGet, "/api/inbox/archived/facets", f.workspaceID)).+ Want(http.StatusOK).+ JSON(&facets)+ if facets.UnreadCount != 1 {+ t.Fatalf("archived unread count = %d, want 1", facets.UnreadCount)+ }++ var page archivedInboxPageResponse+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListArchivedInboxPage),+ inboxRequest(http.MethodGet, "/api/inbox/archived/page?unread_only=true", f.workspaceID)).+ Want(http.StatusOK).+ JSON(&page)+ if len(page.Items) != 1 || page.Items[0].Title != "mention" {+ t.Fatalf("unread archived page = %+v, want only the mention", page.Items)+ }+}++// Clients from before the Inbox sections can mark an issue's newest row unread+// even when it is activity. That parks the issue: it must count as unread and+// survive archive-all-read, so the row is re-filed under Needs action.+func TestMarkInboxUnreadParksActivityForLegacyClients(t *testing.T) {+ f := newSectionFixture(t, "Legacy mark unread")+ issueID := f.issue("Park for later")+ f.routed(issueID, "mentioned", "member", "older mention", "action", "now() - interval '2 minutes'")+ activityID := f.routed(issueID, "status_changed", "agent", "latest status", "activity", "now() - interval '1 minute'")++ testutil.Call(t, inboxWorkspaceHandler(testHandler.MarkInboxRead),+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/"+activityID+"/read", f.workspaceID), "id", activityID)).Want(http.StatusOK)+ var item InboxItemResponse+ testutil.Call(t, inboxWorkspaceHandler(testHandler.MarkInboxUnread),+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/"+activityID+"/unread", f.workspaceID), "id", activityID)).+ Want(http.StatusOK).+ JSON(&item)+ if item.Section != "action" || item.Read {+ t.Fatalf("unread activity row = section %q read %v, want an unread action row", item.Section, item.Read)+ }+ if got := f.unreadSummary(); got != 1 {+ t.Fatalf("unread summary = %d, want 1 for the parked issue", got)+ }++ testutil.Call(t, inboxWorkspaceHandler(testHandler.ArchiveAllReadInbox),+ inboxRequest(http.MethodPost, "/api/inbox/archive-all-read", f.workspaceID)).Want(http.StatusOK)+ if f.archived("latest status") {+ t.Error("archive-all-read removed the row the client explicitly marked unread")+ }+}++func TestMarkInboxUnreadKeepsActionSection(t *testing.T) {+ f := newSectionFixture(t, "Unread keeps section")+ issueID := f.issue("Mention")+ mentionID := f.item(issueID, "mentioned", "member", "mention", true, "now() - interval '1 minute'")++ var item InboxItemResponse+ testutil.Call(t, inboxWorkspaceHandler(testHandler.MarkInboxUnread),+ withURLParam(inboxRequest(http.MethodPost, "/api/inbox/"+mentionID+"/unread", f.workspaceID), "id", mentionID)).+ Want(http.StatusOK).+ JSON(&item)+ if item.Section != "action" || item.Read {+ t.Fatalf("unread mention = section %q read %v", item.Section, item.Read)+ }+ if n := dbfx.Count(t, "SELECT count(*) FROM inbox_item WHERE id = $1 AND section IS NULL", mentionID); n != 1 {+ t.Fatal("marking an action row unread should not write a section")+ }+}diff --git a/server/internal/handler/inbox_test.go b/server/internal/handler/inbox_test.goindex 898c649f00..bab505712d 100644--- a/server/internal/handler/inbox_test.go+++ b/server/internal/handler/inbox_test.go@@ -129,7 +129,7 @@ func TestArchiveAllReadInboxUsesNewestIssueRow(t *testing.T) {"workspace_id": workspaceID,"recipient_type": "member","recipient_id": testUserID,- "type": "status_changed",+ "type": "issue_assigned","severity": "info","issue_id": issueID,"title": title,diff --git a/server/internal/handler/notification_preference.go b/server/internal/handler/notification_preference.goindex afaed3d08a..5c37625fd0 100644--- a/server/internal/handler/notification_preference.go+++ b/server/internal/handler/notification_preference.go@@ -7,6 +7,7 @@ import ("net/http""github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/inbox""github.com/multica-ai/multica/server/internal/logger"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -33,6 +34,27 @@ var validNotifValues = map[string]bool{"muted": true,}+// validRouteValues is the set of allowed values for a routable kind's key (see+// inbox.RouteKinds): which Inbox section it lands in, muted, or "all" for the+// default. mentions, status_changes and updates are both routable kinds and+// pre-routing groups, so older clients writing "all"/"muted" there stay valid.+var validRouteValues = map[string]bool{+ inbox.RouteDefault: true,+ inbox.RouteMuted: true,+ inbox.RouteAction: true,+ inbox.RouteActivity: true,+}++func validNotifPreference(key, value string) (validKey, validValue bool) {+ if inbox.IsRouteKey(key) {+ return true, validRouteValues[value]+ }+ if validNotifGroups[key] {+ return true, validNotifValues[value]+ }+ return false, false+}+func (h *Handler) GetNotificationPreferences(w http.ResponseWriter, r *http.Request) {userID, ok := requireUserID(w, r)if !ok {@@ -85,11 +107,12 @@ func decodeNotificationPreferenceRequest(w http.ResponseWriter, r *http.Request)}for k, v := range req.Preferences {- if !validNotifGroups[k] {+ validKey, validValue := validNotifPreference(k, v)+ if !validKey {writeError(w, http.StatusBadRequest, "invalid preference group: "+k)return nil, false}- if !validNotifValues[v] {+ if !validValue {writeError(w, http.StatusBadRequest, "invalid preference value: "+v)return nil, false}diff --git a/server/internal/handler/notification_preference_test.go b/server/internal/handler/notification_preference_test.goindex 656ddd670e..a71adf1d65 100644--- a/server/internal/handler/notification_preference_test.go+++ b/server/internal/handler/notification_preference_test.go@@ -176,3 +176,67 @@ func TestPatchNotificationPreferencesRejectsUnknownGroups(t *testing.T) {t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())}}++// TestPatchNotificationPreferencesRoutes covers the per-kind Inbox routing+// keys: they take a section or "muted", while older groups keep all/muted.+func TestPatchNotificationPreferencesRoutes(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ reset := func() {+ _, _ = testPool.Exec(ctx, `+ DELETE FROM notification_preference+ WHERE workspace_id = $1 AND user_id = $2+ `, testWorkspaceID, testUserID)+ }+ reset()+ t.Cleanup(reset)++ recorder := httptest.NewRecorder()+ testHandler.PatchNotificationPreferences(+ recorder,+ notificationPreferenceRequest(t, http.MethodPatch, map[string]string{+ "status_changes": "action",+ "mentions": "activity",+ "agent_comments": "muted",+ "assigned": "all",+ "comments": "muted",+ }),+ )+ if recorder.Code != http.StatusOK {+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())+ }++ var response struct {+ Preferences map[string]string `json:"preferences"`+ }+ if err := json.NewDecoder(recorder.Body).Decode(&response); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ want := map[string]string{+ "status_changes": "action",+ "mentions": "activity",+ "agent_comments": "muted",+ "comments": "muted",+ }+ for key, value := range want {+ if response.Preferences[key] != value {+ t.Errorf("%s = %q, want %q (all: %#v)", key, response.Preferences[key], value, response.Preferences)+ }+ }++ for _, invalid := range []map[string]string{+ {"status_changes": "loud"},+ {"comments": "action"},+ {"system_notifications": "activity"},+ } {+ recorder := httptest.NewRecorder()+ testHandler.PatchNotificationPreferences(recorder,+ notificationPreferenceRequest(t, http.MethodPatch, invalid))+ if recorder.Code != http.StatusBadRequest {+ t.Errorf("%v: status=%d, want 400", invalid, recorder.Code)+ }+ }+}diff --git a/server/internal/inbox/routing.go b/server/internal/inbox/routing.gonew file mode 100644index 0000000000..01fce1d011--- /dev/null+++ b/server/internal/inbox/routing.go@@ -0,0 +1,102 @@+package inbox++import "github.com/jackc/pgx/v5/pgtype"++// Recipients choose, per kind of notification, whether it lands in "action",+// in "activity", or nowhere ("muted"). The choice lives in the recipient's+// notification preferences under the kind's key.+//+// Three earlier preference groups each covered two kinds that now default to+// different sections (assignments, comments, agent_activity). Their kinds got+// new keys, and a muted legacy group still mutes both halves until the+// recipient sets the new key, so nobody starts receiving what they had+// silenced.+const (+ RouteAction = SectionAction+ RouteActivity = SectionActivity+ RouteMuted = "muted"+ // RouteDefault is what older clients write to unmute a group.+ RouteDefault = "all"+)++type routeKind struct {+ Key string+ Default string+ // Legacy is the pre-routing group whose "muted" still applies while Key+ // is unset. Empty when the key itself predates routing.+ Legacy string+}++// RouteKinds lists the routable kinds in the order settings render them.+var RouteKinds = []routeKind{+ {Key: "assigned", Default: SectionAction, Legacy: "assignments"},+ {Key: "mentions", Default: SectionAction},+ {Key: "member_comments", Default: SectionAction, Legacy: "comments"},+ {Key: "agent_failures", Default: SectionAction, Legacy: "agent_activity"},+ {Key: "status_changes", Default: SectionActivity},+ {Key: "assignee_changes", Default: SectionActivity, Legacy: "assignments"},+ {Key: "updates", Default: SectionActivity},+ {Key: "agent_comments", Default: SectionActivity, Legacy: "comments"},+}++var routeKindByKey = func() map[string]routeKind {+ m := make(map[string]routeKind, len(RouteKinds))+ for _, k := range RouteKinds {+ m[k.Key] = k+ }+ return m+}()++// RouteKindKey names the routable kind of a notification, or "" when the type+// is not routable (review requests, quick-create and autopilot results,+// reactions...) and always lands in its default section.+func RouteKindKey(notifType string, actorType pgtype.Text) string {+ agent := actorType.Valid && actorType.String == "agent"+ switch notifType {+ case "issue_assigned":+ return "assigned"+ case "mentioned":+ return "mentions"+ case "new_comment":+ if agent {+ return "agent_comments"+ }+ return "member_comments"+ case "task_failed", "agent_blocked":+ return "agent_failures"+ case "status_changed":+ return "status_changes"+ case "unassigned", "assignee_changed":+ return "assignee_changes"+ case "priority_changed", "start_date_changed", "due_date_changed":+ return "updates"+ }+ return ""+}++// Route resolves where a notification goes for a recipient with these+// preferences. ok is false when the recipient muted it.+func Route(prefs map[string]string, notifType string, actorType pgtype.Text) (section string, ok bool) {+ kind, routable := routeKindByKey[RouteKindKey(notifType, actorType)]+ if !routable {+ return DefaultSection(notifType, actorType), true+ }+ switch prefs[kind.Key] {+ case RouteAction:+ return SectionAction, true+ case RouteActivity:+ return SectionActivity, true+ case RouteMuted:+ return "", false+ }+ if kind.Legacy != "" && prefs[kind.Legacy] == RouteMuted {+ return "", false+ }+ return kind.Default, true+}++// IsRouteKey reports whether key is a routable kind's preference key.+func IsRouteKey(key string) bool {+ _, ok := routeKindByKey[key]+ return ok+}diff --git a/server/internal/inbox/routing_test.go b/server/internal/inbox/routing_test.gonew file mode 100644index 0000000000..6e2119ee7f--- /dev/null+++ b/server/internal/inbox/routing_test.go@@ -0,0 +1,85 @@+package inbox++import (+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+)++func TestRoute(t *testing.T) {+ agent := pgtype.Text{String: "agent", Valid: true}+ member := pgtype.Text{String: "member", Valid: true}+ muted := ""++ cases := []struct {+ name string+ prefs map[string]string+ notifType string+ actor pgtype.Text+ want string // muted means not delivered+ }{+ // Defaults match DefaultSection, so an untouched account sees no change.+ {"default assigned", nil, "issue_assigned", member, SectionAction},+ {"default mention", nil, "mentioned", agent, SectionAction},+ {"default member comment", nil, "new_comment", member, SectionAction},+ {"default agent comment", nil, "new_comment", agent, SectionActivity},+ {"default agent failure", nil, "task_failed", agent, SectionAction},+ {"default status", nil, "status_changed", member, SectionActivity},+ {"default assignee change", nil, "unassigned", member, SectionActivity},+ {"default update", nil, "due_date_changed", member, SectionActivity},+ {"explicit all is the default", map[string]string{"status_changes": "all"}, "status_changed", agent, SectionActivity},++ // The recipient's choice wins.+ {"status routed to action", map[string]string{"status_changes": "action"}, "status_changed", agent, SectionAction},+ {"agent comments routed to action", map[string]string{"agent_comments": "action"}, "new_comment", agent, SectionAction},+ {"mentions routed to activity", map[string]string{"mentions": "activity"}, "mentioned", member, SectionActivity},+ {"updates muted", map[string]string{"updates": "muted"}, "priority_changed", member, muted},+ {"agent comment choice leaves member comments alone", map[string]string{"agent_comments": "muted"}, "new_comment", member, SectionAction},++ // Muting comment volume never silences someone asking for you by name.+ {"muted comments still delivers mentions", map[string]string{"comments": "muted"}, "mentioned", member, SectionAction},+ {"muted mentions drops mentioned", map[string]string{"mentions": "muted"}, "mentioned", member, muted},+ {"muted mentions still delivers new_comment", map[string]string{"mentions": "muted"}, "new_comment", member, SectionAction},++ // A muted pre-routing group mutes both halves until the new key is set.+ {"legacy comments muted drops member comment", map[string]string{"comments": "muted"}, "new_comment", member, muted},+ {"legacy comments muted drops agent comment", map[string]string{"comments": "muted"}, "new_comment", agent, muted},+ {"legacy assignments muted drops assigned", map[string]string{"assignments": "muted"}, "issue_assigned", member, muted},+ {"legacy assignments muted drops unassigned", map[string]string{"assignments": "muted"}, "unassigned", member, muted},+ {"legacy agent_activity muted drops failure", map[string]string{"agent_activity": "muted"}, "task_failed", agent, muted},+ {"new key overrides muted legacy group", map[string]string{"comments": "muted", "agent_comments": "activity"}, "new_comment", agent, SectionActivity},+ {"muting comments leaves assignments alone", map[string]string{"comments": "muted"}, "issue_assigned", member, SectionAction},++ // Types outside the routable kinds always land in their default section.+ {"unroutable reaction", map[string]string{"comments": "muted"}, "reaction_added", member, SectionActivity},+ {"unroutable review request", map[string]string{"assigned": "muted"}, "review_requested", member, SectionAction},+ {"unknown value falls back to default", map[string]string{"status_changes": "loud"}, "status_changed", member, SectionActivity},+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ got, ok := Route(c.prefs, c.notifType, c.actor)+ if c.want == muted {+ if ok {+ t.Fatalf("Route = (%q, delivered), want muted", got)+ }+ return+ }+ if !ok || got != c.want {+ t.Fatalf("Route = (%q, %v), want (%q, delivered)", got, ok, c.want)+ }+ })+ }+}++func TestItemSection(t *testing.T) {+ agent := pgtype.Text{String: "agent", Valid: true}+ if got := ItemSection(SectionText(SectionAction), "status_changed", agent); got != SectionAction {+ t.Errorf("stored action = %q", got)+ }+ if got := ItemSection(pgtype.Text{}, "status_changed", agent); got != SectionActivity {+ t.Errorf("unset falls back to default, got %q", got)+ }+ if got := ItemSection(SectionText("bogus"), "mentioned", agent); got != SectionAction {+ t.Errorf("unknown stored value falls back to default, got %q", got)+ }+}diff --git a/server/internal/inbox/section.go b/server/internal/inbox/section.gonew file mode 100644index 0000000000..21bbe55e98--- /dev/null+++ b/server/internal/inbox/section.go@@ -0,0 +1,83 @@+package inbox++import "github.com/jackc/pgx/v5/pgtype"++// Every notification belongs to one of two Inbox sections. "action" is what+// waits on the recipient — an assignment, a mention, a failed run, a person+// talking on their issue — and is the only section that counts as unread.+// "activity" is routine progress the Work sidebar already tracks live (status+// moves, agent replies, property edits); it stays listable but never raises+// the unread badge.+//+// A row written since recipients could route notifications (see Route)+// stores its section. Older rows store none and classify by DefaultSection,+// so the two kinds of row read the same way without a backfill.+const (+ SectionAction = "action"+ SectionActivity = "activity"+)++// ActivityTypes are activity by default, whoever caused them. task_completed,+// agent_completed and issue_subscribed are no longer written but may exist in+// older rows.+var ActivityTypes = []string{+ "status_changed",+ "priority_changed",+ "start_date_changed",+ "due_date_changed",+ "assignee_changed",+ "unassigned",+ "reaction_added",+ "quick_create_done",+ "task_completed",+ "agent_completed",+ "issue_subscribed",+}++// AgentActivityTypes are activity by default when an agent caused them and+// action when a person did: an agent's reply is the run's result, which the+// sidebar already shows; a person commenting on your issue usually wants you.+var AgentActivityTypes = []string{+ "new_comment",+}++var (+ activityTypeSet = toSet(ActivityTypes)+ agentActivityTypeSet = toSet(AgentActivityTypes)+)++func toSet(values []string) map[string]bool {+ set := make(map[string]bool, len(values))+ for _, v := range values {+ set[v] = true+ }+ return set+}++// DefaultSection classifies a notification nobody routed. Unknown types are+// action, so a new kind is never hidden from the unread count by default. The+// SQL predicates apply the same rule to rows without a stored section through+// ActivityTypes and AgentActivityTypes; keep the two in step.+func DefaultSection(notifType string, actorType pgtype.Text) string {+ if activityTypeSet[notifType] {+ return SectionActivity+ }+ if agentActivityTypeSet[notifType] && actorType.Valid && actorType.String == "agent" {+ return SectionActivity+ }+ return SectionAction+}++// ItemSection is the section of a stored row: the one it was routed to, or the+// default for rows written before routing existed.+func ItemSection(stored pgtype.Text, notifType string, actorType pgtype.Text) string {+ if stored.Valid && (stored.String == SectionAction || stored.String == SectionActivity) {+ return stored.String+ }+ return DefaultSection(notifType, actorType)+}++// SectionText is the value written to inbox_item.section.+func SectionText(section string) pgtype.Text {+ return pgtype.Text{String: section, Valid: true}+}diff --git a/server/internal/inbox/section_test.go b/server/internal/inbox/section_test.gonew file mode 100644index 0000000000..f6924c3943--- /dev/null+++ b/server/internal/inbox/section_test.go@@ -0,0 +1,42 @@+package inbox++import (+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+)++func TestDefaultSection(t *testing.T) {+ agent := pgtype.Text{String: "agent", Valid: true}+ member := pgtype.Text{String: "member", Valid: true}+ none := pgtype.Text{}++ cases := []struct {+ notifType string+ actor pgtype.Text+ want string+ }{+ {"issue_assigned", member, SectionAction},+ {"mentioned", agent, SectionAction},+ {"task_failed", none, SectionAction},+ {"children_done", none, SectionAction},+ {"quick_create_failed", agent, SectionAction},+ {"autopilot_paused", none, SectionAction},+ {"new_comment", member, SectionAction},+ {"new_comment", none, SectionAction},+ {"new_comment", agent, SectionActivity},+ {"status_changed", agent, SectionActivity},+ {"status_changed", member, SectionActivity},+ {"priority_changed", member, SectionActivity},+ {"assignee_changed", agent, SectionActivity},+ {"reaction_added", member, SectionActivity},+ {"quick_create_done", agent, SectionActivity},+ {"task_completed", agent, SectionActivity},+ {"some_future_type", agent, SectionAction},+ }+ for _, c := range cases {+ if got := DefaultSection(c.notifType, c.actor); got != c.want {+ t.Errorf("DefaultSection(%q, %q) = %q, want %q", c.notifType, c.actor.String, got, c.want)+ }+ }+}diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 5b7de029d3..3a648929fd 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -944,6 +944,7 @@ func (s *AutopilotService) notifyAutopilotSubscribersOnCreate("recipient_id": util.UUIDToString(item.RecipientID),"type": item.Type,"severity": item.Severity,+ "section": inbox.ItemSection(item.Section, item.Type, item.ActorType),"issue_id": util.UUIDToPtr(item.IssueID),"issue_status": issue.Status,"title": item.Title,diff --git a/server/internal/service/autopilot_quota_notifications.go b/server/internal/service/autopilot_quota_notifications.goindex ea69f8d254..6c30a69e08 100644--- a/server/internal/service/autopilot_quota_notifications.go+++ b/server/internal/service/autopilot_quota_notifications.go@@ -189,7 +189,7 @@ func (s *AutopilotService) publishAutopilotQuotaInboxItems(items []db.InboxItem)Payload: map[string]any{"item": map[string]any{"id": util.UUIDToString(item.ID), "workspace_id": util.UUIDToString(item.WorkspaceID),"recipient_type": item.RecipientType, "recipient_id": util.UUIDToString(item.RecipientID),- "type": item.Type, "severity": item.Severity, "issue_id": nil,+ "type": item.Type, "severity": item.Severity, "section": inbox.ItemSection(item.Section, item.Type, item.ActorType), "issue_id": nil,"issue_status": nil, "issue_priority": nil,"title": item.Title, "body": util.TextToPtr(item.Body), "read": item.Read,"archived": item.Archived, "created_at": util.TimestampToString(item.CreatedAt),diff --git a/server/internal/service/delegated_failure_recovery_routing_test.go b/server/internal/service/delegated_failure_recovery_routing_test.gonew file mode 100644index 0000000000..a5c423b786--- /dev/null+++ b/server/internal/service/delegated_failure_recovery_routing_test.go@@ -0,0 +1,80 @@+package service++import (+ "context"+ "fmt"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/inbox"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// TestRecoveryExhaustionHonorsAgentFailureRoute: the failure notification+// written when delegated recovery gives up follows the recipient's+// agent_failures route like any other task_failed.+func TestRecoveryExhaustionHonorsAgentFailureRoute(t *testing.T) {+ for _, route := range []string{"activity", "muted"} {+ t.Run(route, func(t *testing.T) {+ f, svc := seedDelegatedFailureFixture(t)+ ctx := context.Background()+ fx := testutil.New(f.pool, f.workspaceID, f.userID)+ fx.Insert(t, "notification_preference", testutil.Cols{+ "workspace_id": f.workspaceID, "user_id": f.userID,+ "preferences": fmt.Sprintf(`{"agent_failures":%q}`, route),+ })+ failedID := f.insertWorkerTask(t, "failed", "comment", 1, 2)+ fx.Exec(t, `UPDATE agent_task_queue SET failure_reason = 'agent_error.process_failure',+ error = 'worker exited', completed_at = now() WHERE id = $1`, failedID)+ failed, err := svc.Queries.GetAgentTask(ctx, failedID)+ if err != nil {+ t.Fatal(err)+ }+ if handled, err := svc.recoverDelegatedTaskFailure(ctx, failed); err != nil || !handled {+ t.Fatalf("initial recovery: handled=%v err=%v", handled, err)+ }+ for attempt := 1; attempt <= delegatedFailureRecoveryMaxTaskAttempts; attempt++ {+ var currentTaskID pgtype.UUID+ if err := f.pool.QueryRow(ctx, `SELECT id FROM agent_task_queue+ WHERE trigger_evidence_kind = 'delegated_failure' AND trigger_evidence_ref_id = $1+ AND status = 'queued' ORDER BY created_at DESC, id DESC LIMIT 1`, failedID).Scan(¤tTaskID); err != nil {+ t.Fatal(err)+ }+ fx.Exec(t, `UPDATE agent_task_queue SET status = 'failed', completed_at = now(),+ failure_reason = 'queued_expired', error = 'task expired in queue',+ delivered_comment_ids = '{}' WHERE id = $1`, currentTaskID)+ result, err := svc.RecoverPendingDelegatedFailures(ctx, 100)+ if err != nil {+ t.Fatal(err)+ }+ if attempt == delegatedFailureRecoveryMaxTaskAttempts && result.Exhausted != 1 {+ t.Fatalf("final recovery result = %+v, want exhausted", result)+ }+ }+ items, err := svc.Queries.ListInboxItems(ctx, db.ListInboxItemsParams{+ WorkspaceID: util.MustParseUUID(f.workspaceID), RecipientType: "member", RecipientID: util.MustParseUUID(f.userID),+ })+ if err != nil {+ t.Fatal(err)+ }+ failures := 0+ for _, item := range items {+ if item.Type != "task_failed" {+ continue+ }+ failures+++ if route == "muted" {+ t.Errorf("agent_failures=muted still creates task_failed notification")+ }+ if route == "activity" && inbox.ItemSection(item.Section, item.Type, item.ActorType) != "activity" {+ t.Errorf("agent_failures=activity produced section %q", inbox.ItemSection(item.Section, item.Type, item.ActorType))+ }+ }+ if route == "activity" && failures != 1 {+ t.Fatalf("failure notifications = %d, want 1", failures)+ }+ })+ }+}diff --git a/server/internal/service/issue_wakeup_system.go b/server/internal/service/issue_wakeup_system.goindex ccab4a4a4a..1a6f3927a8 100644--- a/server/internal/service/issue_wakeup_system.go+++ b/server/internal/service/issue_wakeup_system.go@@ -700,7 +700,7 @@ func (s *IssueWakeupService) publishSystemInbox(item db.InboxItem, issueStatus sPayload: map[string]any{"item": map[string]any{"id": util.UUIDToString(item.ID), "workspace_id": util.UUIDToString(item.WorkspaceID),"recipient_type": item.RecipientType, "recipient_id": util.UUIDToString(item.RecipientID),- "type": item.Type, "severity": item.Severity, "issue_id": util.UUIDToPtr(item.IssueID),+ "type": item.Type, "severity": item.Severity, "section": inboxwriter.ItemSection(item.Section, item.Type, item.ActorType), "issue_id": util.UUIDToPtr(item.IssueID),"title": item.Title, "body": util.TextToPtr(item.Body), "read": item.Read, "archived": item.Archived,"created_at": util.TimestampToString(item.CreatedAt), "actor_type": util.TextToPtr(item.ActorType),"actor_id": util.UUIDToPtr(item.ActorID), "details": json.RawMessage(item.Details), "issue_status": issueStatus,diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 016ce3fc20..602019d2e7 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -6740,7 +6740,9 @@ func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, targe// Exhaustion deliberately does not @mention the coordinator agent: doing// so would enqueue a fourth recovery run and defeat the attempt bound.// Instead, create one durable action-required inbox item for the human- // who originated (or is accountable for) the delegated work.+ // who originated (or is accountable for) the delegated work, routed by+ // their agent-failure preference like every other task_failed. The+ // system comment above explains the outcome either way._, recipient := delegatedFailureRecoveryAttribution(target)if recipient.Valid {_, err = qtx.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{@@ -6754,6 +6756,22 @@ func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, targereturn fmt.Errorf("validate delegated failure exhaustion recipient: %w", err)}+ var prefs map[string]string+ pref, err := qtx.GetNotificationPreference(ctx, db.GetNotificationPreferenceParams{+ WorkspaceID: target.issue.WorkspaceID,+ UserID: recipient,+ })+ if err == nil {+ _ = json.Unmarshal(pref.Preferences, &prefs)+ } else if !errors.Is(err, pgx.ErrNoRows) {+ return fmt.Errorf("load delegated failure exhaustion recipient preferences: %w", err)+ }+ actorType := pgtype.Text{String: "system", Valid: true}+ section, routed := inbox.Route(prefs, "task_failed", actorType)+ if !routed {+ return nil+ }+details, err := json.Marshal(map[string]any{"failed_task_id": util.UUIDToString(target.failed.ID),"source_task_id": util.UUIDToString(target.source.ID),@@ -6773,9 +6791,10 @@ func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, targeIssueID: target.issue.ID,Title: target.issue.Title,Body: pgtype.Text{String: exhaustedComment.Content, Valid: true},- ActorType: pgtype.Text{String: "system", Valid: true},+ ActorType: actorType,ActorID: pgtype.UUID{},Details: details,+ Section: inbox.SectionText(section),})if err != nil {return fmt.Errorf("create delegated failure exhaustion inbox item: %w", err)@@ -6812,6 +6831,7 @@ func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, targe"recipient_id": util.UUIDToString(exhaustedInbox.RecipientID),"type": exhaustedInbox.Type,"severity": exhaustedInbox.Severity,+ "section": inbox.ItemSection(exhaustedInbox.Section, exhaustedInbox.Type, exhaustedInbox.ActorType),"issue_id": util.UUIDToPtr(exhaustedInbox.IssueID),"title": exhaustedInbox.Title,"body": util.TextToPtr(exhaustedInbox.Body),@@ -8358,6 +8378,7 @@ func (s *TaskService) publishQuickCreateInbox(item db.InboxItem, workspaceID, ag"recipient_id": util.UUIDToString(item.RecipientID),"type": item.Type,"severity": item.Severity,+ "section": inbox.ItemSection(item.Section, item.Type, item.ActorType),"issue_id": util.UUIDToPtr(item.IssueID),"title": item.Title,"body": util.TextToPtr(item.Body),diff --git a/server/migrations/607_inbox_item_section.down.sql b/server/migrations/607_inbox_item_section.down.sqlnew file mode 100644index 0000000000..8f8aabbc4c--- /dev/null+++ b/server/migrations/607_inbox_item_section.down.sql@@ -0,0 +1 @@+ALTER TABLE inbox_item DROP COLUMN IF EXISTS section;diff --git a/server/migrations/607_inbox_item_section.up.sql b/server/migrations/607_inbox_item_section.up.sqlnew file mode 100644index 0000000000..6813171f59--- /dev/null+++ b/server/migrations/607_inbox_item_section.up.sql@@ -0,0 +1,9 @@+-- MUL-8483: the Inbox section ("action" or "activity") a notification was+-- routed to by its recipient's preferences at write time.+--+-- NULL means "classify by type", the rule every row followed before routing+-- existed, so existing rows need no backfill and older servers keep writing+-- valid rows. Values are validated in code (inbox.ItemSection ignores anything+-- else); there is no CHECK constraint so the ALTER stays a catalog-only change+-- with no table scan.+ALTER TABLE inbox_item ADD COLUMN IF NOT EXISTS section TEXT;diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.goindex 9634931fea..2c601bf0ab 100644--- a/server/pkg/db/generated/inbox.sql.go+++ b/server/pkg/db/generated/inbox.sql.go@@ -30,42 +30,57 @@ func (q *Queries) ArchiveAllInbox(ctx context.Context, arg ArchiveAllInboxParams}const archiveAllReadInbox = `-- name: ArchiveAllReadInbox :execrows-WITH newest_groups AS (- SELECT DISTINCT ON (COALESCE(i.issue_id, i.id))+WITH active AS (+ SELECT i.id,COALESCE(i.issue_id, i.id) AS group_id,- i.read+ i.created_at,+ i.read,+ COALESCE(i.section = 'activity', i.type = ANY($1::text[])+ OR (COALESCE(i.actor_type, '') = 'agent' AND i.type = ANY($2::text[]))) AS is_activityFROM inbox_item i- WHERE i.workspace_id = $1+ WHERE i.workspace_id = $3AND i.recipient_type = 'member'- AND i.recipient_id = $2+ AND i.recipient_id = $4AND i.archived = false- ORDER BY COALESCE(i.issue_id, i.id), i.created_at DESC, i.id DESC+), newest_groups AS (+ SELECT DISTINCT ON (group_id, is_activity)+ group_id,+ is_activity,+ read+ FROM active+ ORDER BY group_id, is_activity, created_at DESC, id DESC), read_groups AS (- SELECT group_id+ SELECT group_id, is_activityFROM newest_groups- WHERE read = true+ WHERE read = true OR is_activity)UPDATE inbox_item i SET archived = true-FROM read_groups selected-WHERE i.workspace_id = $1- AND i.recipient_type = 'member'- AND i.recipient_id = $2- AND i.archived = false- AND COALESCE(i.issue_id, i.id) = selected.group_id+FROM active a+JOIN read_groups selected USING (group_id, is_activity)+WHERE i.id = a.id`type ArchiveAllReadInboxParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- RecipientID pgtype.UUID `json:"recipient_id"`+ ActivityTypes []string `json:"activity_types"`+ AgentActivityTypes []string `json:"agent_activity_types"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientID pgtype.UUID `json:"recipient_id"`}-// "Read" is the state of the one issue row the inbox renders: the newest-// active notification in that issue group. Archive every row in groups whose-// newest row is read, and leave an unread group wholly untouched. Updating raw-// read rows instead makes an older unread sibling reappear after the newest-// row is archived (and can archive an older read sibling under an unread row).+// "Read" is the state of the one row the inbox renders per issue and section:+// the newest active notification in that group. Action and activity group+// separately (MUL-8483), and an activity group always counts as read. Archive+// every row in qualifying groups and leave an unread action group wholly+// untouched. Updating raw read rows instead makes an older unread sibling+// reappear after the newest row is archived (and can archive an older read+// sibling under an unread row).func (q *Queries) ArchiveAllReadInbox(ctx context.Context, arg ArchiveAllReadInboxParams) (int64, error) {- result, err := q.db.Exec(ctx, archiveAllReadInbox, arg.WorkspaceID, arg.RecipientID)+ result, err := q.db.Exec(ctx, archiveAllReadInbox,+ arg.ActivityTypes,+ arg.AgentActivityTypes,+ arg.WorkspaceID,+ arg.RecipientID,+ )if err != nil {return 0, err}@@ -96,6 +111,46 @@ func (q *Queries) ArchiveCompletedInbox(ctx context.Context, arg ArchiveCompletereturn result.RowsAffected(), nil}+const archiveInboxActivityByIssue = `-- name: ArchiveInboxActivityByIssue :execrows+UPDATE inbox_item i SET archived = true+WHERE i.workspace_id = $1+ AND i.recipient_type = $2+ AND i.recipient_id = $3+ AND i.issue_id = $4+ AND i.archived = false+ AND COALESCE(i.section = 'activity', i.type = ANY($5::text[])+ OR (COALESCE(i.actor_type, '') = 'agent' AND i.type = ANY($6::text[])))+`++type ArchiveInboxActivityByIssueParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientType string `json:"recipient_type"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ ActivityTypes []string `json:"activity_types"`+ AgentActivityTypes []string `json:"agent_activity_types"`+}++// Section-scoped counterpart of ArchiveInboxByIssue, used when the archived row+// is activity: clearing routine progress must not take an unread action item+// on the same issue (a mention, a failed run) with it. The activity predicate+// mirrors inbox.ItemSection: a stored section wins, otherwise the type rule+// the caller passes as inbox.ActivityTypes and inbox.AgentActivityTypes.+func (q *Queries) ArchiveInboxActivityByIssue(ctx context.Context, arg ArchiveInboxActivityByIssueParams) (int64, error) {+ result, err := q.db.Exec(ctx, archiveInboxActivityByIssue,+ arg.WorkspaceID,+ arg.RecipientType,+ arg.RecipientID,+ arg.IssueID,+ arg.ActivityTypes,+ arg.AgentActivityTypes,+ )+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const archiveInboxByIssue = `-- name: ArchiveInboxByIssue :execrowsUPDATE inbox_item SET archived = trueWHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_id = $4 AND archived = false@@ -161,7 +216,7 @@ func (q *Queries) ArchiveInboxByIssueAndType(ctx context.Context, arg ArchiveInbconst archiveInboxItem = `-- name: ArchiveInboxItem :oneUPDATE inbox_item SET archived = trueWHERE 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+RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section`func (q *Queries) ArchiveInboxItem(ctx context.Context, id pgtype.UUID) (InboxItem, error) {@@ -183,23 +238,40 @@ func (q *Queries) ArchiveInboxItem(ctx context.Context, id pgtype.UUID) (InboxIt&i.ActorType,&i.ActorID,&i.Details,+ &i.Section,)return i, err}const countUnreadInbox = `-- name: CountUnreadInbox :one-SELECT count(*) FROM inbox_item-WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND read = false AND archived = false+SELECT count(*) FROM inbox_item i+WHERE i.workspace_id = $1+ AND i.recipient_type = $2+ AND i.recipient_id = $3+ AND i.read = false+ AND i.archived = false+ AND NOT COALESCE(i.section = 'activity', i.type = ANY($4::text[])+ OR (COALESCE(i.actor_type, '') = 'agent' AND i.type = ANY($5::text[])))`type CountUnreadInboxParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- RecipientType string `json:"recipient_type"`- RecipientID pgtype.UUID `json:"recipient_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientType string `json:"recipient_type"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ ActivityTypes []string `json:"activity_types"`+ AgentActivityTypes []string `json:"agent_activity_types"`}+// Activity rows never count as unread, whatever their stored `read` flag; see+// inbox.ItemSection for the rule the predicate mirrors.func (q *Queries) CountUnreadInbox(ctx context.Context, arg CountUnreadInboxParams) (int64, error) {- row := q.db.QueryRow(ctx, countUnreadInbox, arg.WorkspaceID, arg.RecipientType, arg.RecipientID)+ row := q.db.QueryRow(ctx, countUnreadInbox,+ arg.WorkspaceID,+ arg.RecipientType,+ arg.RecipientID,+ arg.ActivityTypes,+ arg.AgentActivityTypes,+ )var count int64err := row.Scan(&count)return count, err@@ -215,12 +287,20 @@ FROM (WHERE i.recipient_type = 'member'AND i.recipient_id = $1AND i.archived = false+ AND NOT COALESCE(i.section = 'activity', i.type = ANY($2::text[])+ OR (COALESCE(i.actor_type, '') = 'agent' AND i.type = ANY($3::text[])))ORDER BY i.workspace_id, COALESCE(i.issue_id, i.id), i.created_at DESC) newestWHERE newest.read = falseGROUP BY newest.workspace_id`+type CountUnreadInboxByWorkspaceParams struct {+ RecipientID pgtype.UUID `json:"recipient_id"`+ ActivityTypes []string `json:"activity_types"`+ AgentActivityTypes []string `json:"agent_activity_types"`+}+type CountUnreadInboxByWorkspaceRow struct {WorkspaceID pgtype.UUID `json:"workspace_id"`Count int64 `json:"count"`@@ -236,8 +316,12 @@ type CountUnreadInboxByWorkspaceRow struct {// 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.-func (q *Queries) CountUnreadInboxByWorkspace(ctx context.Context, recipientID pgtype.UUID) ([]CountUnreadInboxByWorkspaceRow, error) {- rows, err := q.db.Query(ctx, countUnreadInboxByWorkspace, recipientID)+//+// Only action rows take part (MUL-8483): activity is never unread, and it does+// not decide a group's state either, so a routine status change landing after+// an unread mention leaves the mention counted.+func (q *Queries) CountUnreadInboxByWorkspace(ctx context.Context, arg CountUnreadInboxByWorkspaceParams) ([]CountUnreadInboxByWorkspaceRow, error) {+ rows, err := q.db.Query(ctx, countUnreadInboxByWorkspace, arg.RecipientID, arg.ActivityTypes, arg.AgentActivityTypes)if err != nil {return nil, err}@@ -260,15 +344,15 @@ const createInboxItem = `-- name: CreateInboxItem :oneINSERT INTO inbox_item (workspace_id, recipient_type, recipient_id,type, severity, issue_id, title, body,- actor_type, actor_id, details, id+ actor_type, actor_id, details, id, section)-SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE($12::uuid, gen_random_uuid())+SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE($12::uuid, gen_random_uuid()), $13::textWHERE ($2::text = 'member' AND EXISTS (SELECT 1 FROM member WHERE workspace_id = $1 AND user_id = $3)) OR ($2::text = 'agent' AND EXISTS (SELECT 1 FROM agent WHERE workspace_id = $1 AND id = $3))-RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details+RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section`type CreateInboxItemParams struct {@@ -284,6 +368,7 @@ type CreateInboxItemParams struct {ActorID pgtype.UUID `json:"actor_id"`Details []byte `json:"details"`ID pgtype.UUID `json:"id"`+ Section pgtype.Text `json:"section"`}// A missing recipient is a quiet skip (pgx.ErrNoRows), not a delivery failure.@@ -302,6 +387,7 @@ func (q *Queries) CreateInboxItem(ctx context.Context, arg CreateInboxItemParamsarg.ActorID,arg.Details,arg.ID,+ arg.Section,)var i InboxItemerr := row.Scan(@@ -320,12 +406,13 @@ func (q *Queries) CreateInboxItem(ctx context.Context, arg CreateInboxItemParams&i.ActorType,&i.ActorID,&i.Details,+ &i.Section,)return i, err}const getInboxItem = `-- name: GetInboxItem :one-SELECT id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details FROM inbox_item+SELECT id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section FROM inbox_itemWHERE id = $1`@@ -348,12 +435,13 @@ func (q *Queries) GetInboxItem(ctx context.Context, id pgtype.UUID) (InboxItem,&i.ActorType,&i.ActorID,&i.Details,+ &i.Section,)return i, err}const getInboxItemInWorkspace = `-- name: GetInboxItemInWorkspace :one-SELECT id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details FROM inbox_item+SELECT id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section FROM inbox_itemWHERE id = $1 AND workspace_id = $2`@@ -381,6 +469,7 @@ func (q *Queries) GetInboxItemInWorkspace(ctx context.Context, arg GetInboxItemI&i.ActorType,&i.ActorID,&i.Details,+ &i.Section,)return i, err}@@ -430,7 +519,7 @@ WITH eligible_archived AS MATERIALIZED (UNIONSELECT id FROM comment_anchors)-SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details,+SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section,iss.status AS issue_status,iss.priority AS issue_priorityFROM inbox_item i@@ -461,6 +550,7 @@ type ListArchivedInboxItemsRow struct {ActorType pgtype.Text `json:"actor_type"`ActorID pgtype.UUID `json:"actor_id"`Details []byte `json:"details"`+ Section pgtype.Text `json:"section"`IssueStatus pgtype.Text `json:"issue_status"`IssuePriority pgtype.Text `json:"issue_priority"`}@@ -511,6 +601,7 @@ func (q *Queries) ListArchivedInboxItems(ctx context.Context, arg ListArchivedIn&i.ActorType,&i.ActorID,&i.Details,+ &i.Section,&i.IssueStatus,&i.IssuePriority,); err != nil {@@ -525,7 +616,7 @@ func (q *Queries) ListArchivedInboxItems(ctx context.Context, arg ListArchivedIn}const listInboxItems = `-- name: ListInboxItems :many-SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details,+SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section,iss.status AS issue_status,iss.priority AS issue_priorityFROM inbox_item i@@ -556,6 +647,7 @@ type ListInboxItemsRow struct {ActorType pgtype.Text `json:"actor_type"`ActorID pgtype.UUID `json:"actor_id"`Details []byte `json:"details"`+ Section pgtype.Text `json:"section"`IssueStatus pgtype.Text `json:"issue_status"`IssuePriority pgtype.Text `json:"issue_priority"`}@@ -585,6 +677,7 @@ func (q *Queries) ListInboxItems(ctx context.Context, arg ListInboxItemsParams)&i.ActorType,&i.ActorID,&i.Details,+ &i.Section,&i.IssueStatus,&i.IssuePriority,); err != nil {@@ -619,7 +712,7 @@ func (q *Queries) MarkAllInboxRead(ctx context.Context, arg MarkAllInboxReadParaconst markInboxRead = `-- name: MarkInboxRead :oneUPDATE inbox_item SET read = trueWHERE 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+RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section`func (q *Queries) MarkInboxRead(ctx context.Context, id pgtype.UUID) (InboxItem, error) {@@ -641,24 +734,54 @@ func (q *Queries) MarkInboxRead(ctx context.Context, id pgtype.UUID) (InboxItem,&i.ActorType,&i.ActorID,&i.Details,+ &i.Section,)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"`+}++// Opening an issue anywhere (Work sidebar, search, a link) settles its inbox+// notifications, so the same event is never cleared twice. Every active row is+// marked, not just the newest, so no older sibling resurfaces as unread.+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 :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+UPDATE inbox_item SET read = false, section = COALESCE($1::text, section)+WHERE id = $2+RETURNING 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.-func (q *Queries) MarkInboxUnread(ctx context.Context, id pgtype.UUID) (InboxItem, error) {- row := q.db.QueryRow(ctx, markInboxUnread, id)+type MarkInboxUnreadParams struct {+ Section pgtype.Text `json:"section"`+ ID pgtype.UUID `json:"id"`+}++// Item-level: the inbox renders one row per issue and section 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. (Marking read, by contrast, also+// settles the item's siblings; see the MarkInboxRead handler.)+// A non-null section re-files the item; see the MarkInboxUnread handler.+func (q *Queries) MarkInboxUnread(ctx context.Context, arg MarkInboxUnreadParams) (InboxItem, error) {+ row := q.db.QueryRow(ctx, markInboxUnread, arg.Section, arg.ID)var i InboxItemerr := row.Scan(&i.ID,@@ -676,6 +799,7 @@ func (q *Queries) MarkInboxUnread(ctx context.Context, id pgtype.UUID) (InboxIte&i.ActorType,&i.ActorID,&i.Details,+ &i.Section,)return i, err}@@ -711,7 +835,7 @@ func (q *Queries) UnarchiveInboxByIssue(ctx context.Context, arg UnarchiveInboxBconst unarchiveInboxItem = `-- name: UnarchiveInboxItem :oneUPDATE inbox_item SET archived = falseWHERE 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+RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section`// Deliberately does not touch `read`: unarchiving restores an item to the main@@ -736,6 +860,7 @@ func (q *Queries) UnarchiveInboxItem(ctx context.Context, id pgtype.UUID) (Inbox&i.ActorType,&i.ActorID,&i.Details,+ &i.Section,)return i, err}diff --git a/server/pkg/db/generated/inbox_archive.sql.go b/server/pkg/db/generated/inbox_archive.sql.goindex c4e6438ccf..4850a8b784 100644--- a/server/pkg/db/generated/inbox_archive.sql.go+++ b/server/pkg/db/generated/inbox_archive.sql.go@@ -14,13 +14,17 @@ import (const archivedInboxFacets = `-- name: ArchivedInboxFacets :manyWITH newest AS MATERIALIZED (SELECT DISTINCT ON (COALESCE(i.issue_id, i.id))- i.id, i.issue_id, i.created_at, i.read,+ i.id, i.issue_id, i.created_at,+ -- Activity is never unread (inbox.Section); the caller passes+ -- inbox.ActivityTypes and inbox.AgentActivityTypes.+ (i.read OR COALESCE(i.section = 'activity', i.type = ANY($1::text[])+ OR (COALESCE(i.actor_type, '') = 'agent' AND i.type = ANY($2::text[])))) AS read,CASE WHEN i.actor_type = 'system' THEN 'system'ELSE i.actor_type || ':' || i.actor_id::text END AS actorFROM inbox_item i- WHERE i.workspace_id = $1::uuid+ WHERE i.workspace_id = $3::uuidAND i.recipient_type = 'member'- AND i.recipient_id = $2::uuid+ AND i.recipient_id = $4::uuidAND i.archived = trueAND (i.issue_id IS NULL OR NOT EXISTS (SELECT 1 FROM inbox_item active@@ -34,13 +38,13 @@ WITH newest AS MATERIALIZED (SELECT newest.id, newest.issue_id, newest.created_at, newest.read, newest.actor, iss.status AS issue_status, iss.priority AS issue_priorityFROM newestLEFT JOIN issue iss ON iss.id = newest.issue_id- AND iss.workspace_id = $1::uuid+ AND iss.workspace_id = $3::uuid), matched AS (SELECT projected.id, projected.issue_id, projected.created_at, projected.read, projected.actor, projected.issue_status, projected.issue_priority,- (cardinality($3::text[]) = 0 OR issue_status = ANY($3::text[])) AS status_match,- (cardinality($4::text[]) = 0 OR issue_priority = ANY($4::text[])) AS priority_match,- (cardinality($5::text[]) = 0 OR actor = ANY($5::text[])) AS actor_match,- (NOT $6::boolean OR NOT read) AS read_match+ (cardinality($5::text[]) = 0 OR issue_status = ANY($5::text[])) AS status_match,+ (cardinality($6::text[]) = 0 OR issue_priority = ANY($6::text[])) AS priority_match,+ (cardinality($7::text[]) = 0 OR actor = ANY($7::text[])) AS actor_match,+ (NOT $8::boolean OR NOT read) AS read_matchFROM projected)SELECT 'statuses'::text AS dimension, issue_status::text AS key,@@ -61,12 +65,14 @@ FROM matched`type ArchivedInboxFacetsParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- RecipientID pgtype.UUID `json:"recipient_id"`- Statuses []string `json:"statuses"`- Priorities []string `json:"priorities"`- Actors []string `json:"actors"`- UnreadOnly bool `json:"unread_only"`+ ActivityTypes []string `json:"activity_types"`+ AgentActivityTypes []string `json:"agent_activity_types"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ Statuses []string `json:"statuses"`+ Priorities []string `json:"priorities"`+ Actors []string `json:"actors"`+ UnreadOnly bool `json:"unread_only"`}type ArchivedInboxFacetsRow struct {@@ -78,6 +84,8 @@ type ArchivedInboxFacetsRow struct {// Select narrow group representatives before loading bodies or comment anchors.func (q *Queries) ArchivedInboxFacets(ctx context.Context, arg ArchivedInboxFacetsParams) ([]ArchivedInboxFacetsRow, error) {rows, err := q.db.Query(ctx, archivedInboxFacets,+ arg.ActivityTypes,+ arg.AgentActivityTypes,arg.WorkspaceID,arg.RecipientID,arg.Statuses,@@ -106,16 +114,20 @@ func (q *Queries) ArchivedInboxFacets(ctx context.Context, arg ArchivedInboxFaceconst listArchivedInboxPage = `-- name: ListArchivedInboxPage :manyWITH newest AS MATERIALIZED (SELECT DISTINCT ON (COALESCE(i.issue_id, i.id))- i.id, i.issue_id, i.created_at, i.read,+ i.id, i.issue_id, i.created_at,+ -- Activity is never unread (inbox.Section); the caller passes+ -- inbox.ActivityTypes and inbox.AgentActivityTypes.+ (i.read OR COALESCE(i.section = 'activity', i.type = ANY($1::text[])+ OR (COALESCE(i.actor_type, '') = 'agent' AND i.type = ANY($2::text[])))) AS read,CASE WHEN i.actor_type = 'system' THEN 'system'ELSE i.actor_type || ':' || i.actor_id::text END AS actorFROM inbox_item i- WHERE i.workspace_id = $1::uuid+ WHERE i.workspace_id = $3::uuidAND i.recipient_type = 'member'- AND i.recipient_id = $2::uuid+ AND i.recipient_id = $4::uuidAND i.archived = true- AND ($3::uuid IS NULL OR i.issue_id = $3::uuid- OR (i.issue_id IS NULL AND i.id = $3::uuid))+ AND ($5::uuid IS NULL OR i.issue_id = $5::uuid+ OR (i.issue_id IS NULL AND i.id = $5::uuid))AND (i.issue_id IS NULL OR NOT EXISTS (SELECT 1 FROM inbox_item activeWHERE active.workspace_id = i.workspace_id@@ -128,24 +140,24 @@ WITH newest AS MATERIALIZED (SELECT newest.id, newest.issue_id, newest.created_at, newest.read, newest.actor, iss.status AS issue_status, iss.priority AS issue_priorityFROM newestLEFT JOIN issue iss ON iss.id = newest.issue_id- AND iss.workspace_id = $1::uuid+ AND iss.workspace_id = $3::uuid), matched AS (SELECT projected.id, projected.issue_id, projected.created_at, projected.read, projected.actor, projected.issue_status, projected.issue_priority,- (cardinality($4::text[]) = 0 OR issue_status = ANY($4::text[])) AS status_match,- (cardinality($5::text[]) = 0 OR issue_priority = ANY($5::text[])) AS priority_match,- (cardinality($6::text[]) = 0 OR actor = ANY($6::text[])) AS actor_match,- (NOT $7::boolean OR NOT read) AS read_match+ (cardinality($6::text[]) = 0 OR issue_status = ANY($6::text[])) AS status_match,+ (cardinality($7::text[]) = 0 OR issue_priority = ANY($7::text[])) AS priority_match,+ (cardinality($8::text[]) = 0 OR actor = ANY($8::text[])) AS actor_match,+ (NOT $9::boolean OR NOT read) AS read_matchFROM projected), selected AS (SELECT id, issue_id, created_at, read, actor, issue_status, issue_priority, status_match, priority_match, actor_match, read_match FROM matchedWHERE status_match AND priority_match AND actor_match AND read_match- AND ($8::timestamptz IS NULL OR- (created_at, id) < ($8::timestamptz, $9::uuid))+ AND ($10::timestamptz IS NULL OR+ (created_at, id) < ($10::timestamptz, $11::uuid))ORDER BY created_at DESC, id DESC- LIMIT $10::int+ LIMIT $12::int)-SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, selected.issue_status, selected.issue_priority,+SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section, selected.issue_status, selected.issue_priority,COALESCE(anchor.comment_id, '')::text AS comment_idFROM selectedJOIN inbox_item i ON i.id = selected.id@@ -162,16 +174,18 @@ ORDER BY i.created_at DESC, i.id DESC`type ListArchivedInboxPageParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- RecipientID pgtype.UUID `json:"recipient_id"`- GroupID pgtype.UUID `json:"group_id"`- Statuses []string `json:"statuses"`- Priorities []string `json:"priorities"`- Actors []string `json:"actors"`- UnreadOnly bool `json:"unread_only"`- BeforeTime pgtype.Timestamptz `json:"before_time"`- BeforeID pgtype.UUID `json:"before_id"`- PageLimit int32 `json:"page_limit"`+ ActivityTypes []string `json:"activity_types"`+ AgentActivityTypes []string `json:"agent_activity_types"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientID pgtype.UUID `json:"recipient_id"`+ GroupID pgtype.UUID `json:"group_id"`+ Statuses []string `json:"statuses"`+ Priorities []string `json:"priorities"`+ Actors []string `json:"actors"`+ UnreadOnly bool `json:"unread_only"`+ BeforeTime pgtype.Timestamptz `json:"before_time"`+ BeforeID pgtype.UUID `json:"before_id"`+ PageLimit int32 `json:"page_limit"`}type ListArchivedInboxPageRow struct {@@ -184,6 +198,8 @@ type ListArchivedInboxPageRow struct {// Select narrow group representatives before loading bodies or comment anchors.func (q *Queries) ListArchivedInboxPage(ctx context.Context, arg ListArchivedInboxPageParams) ([]ListArchivedInboxPageRow, error) {rows, err := q.db.Query(ctx, listArchivedInboxPage,+ arg.ActivityTypes,+ arg.AgentActivityTypes,arg.WorkspaceID,arg.RecipientID,arg.GroupID,@@ -218,6 +234,7 @@ func (q *Queries) ListArchivedInboxPage(ctx context.Context, arg ListArchivedInb&i.InboxItem.ActorType,&i.InboxItem.ActorID,&i.InboxItem.Details,+ &i.InboxItem.Section,&i.IssueStatus,&i.IssuePriority,&i.CommentID,diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 613baf2cb5..ae85089bf7 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -821,6 +821,7 @@ type InboxItem struct {ActorType pgtype.Text `json:"actor_type"`ActorID pgtype.UUID `json:"actor_id"`Details []byte `json:"details"`+ Section pgtype.Text `json:"section"`}type InstanceTelemetryState struct {diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sqlindex b5996db636..8276a377ff 100644--- a/server/pkg/db/queries/inbox.sql+++ b/server/pkg/db/queries/inbox.sql@@ -95,9 +95,9 @@ WHERE id = $1 AND workspace_id = $2;INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id,type, severity, issue_id, title, body,- actor_type, actor_id, details, id+ actor_type, actor_id, details, id, section)-SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())+SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE(sqlc.narg('id')::uuid, gen_random_uuid()), sqlc.narg('section')::textWHERE ($2::text = 'member' AND EXISTS (SELECT 1 FROM member WHERE workspace_id = $1 AND user_id = $3)) OR ($2::text = 'agent' AND EXISTS (@@ -111,14 +111,15 @@ WHERE id = $1RETURNING *;-- 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+-- Item-level: the inbox renders one row per issue and section 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. (Marking read, by contrast, also+-- settles the item's siblings; see the MarkInboxRead handler.)+-- A non-null section re-files the item; see the MarkInboxUnread handler.+UPDATE inbox_item SET read = false, section = COALESCE(sqlc.narg('section')::text, section)+WHERE id = @idRETURNING *;-- name: ArchiveInboxItem :one@@ -130,6 +131,29 @@ RETURNING *;UPDATE inbox_item SET archived = trueWHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_id = $4 AND archived = false;+-- name: ArchiveInboxActivityByIssue :execrows+-- Section-scoped counterpart of ArchiveInboxByIssue, used when the archived row+-- is activity: clearing routine progress must not take an unread action item+-- on the same issue (a mention, a failed run) with it. The activity predicate+-- mirrors inbox.ItemSection: a stored section wins, otherwise the type rule+-- the caller passes as inbox.ActivityTypes and inbox.AgentActivityTypes.+UPDATE inbox_item i SET archived = true+WHERE i.workspace_id = sqlc.arg('workspace_id')+ AND i.recipient_type = sqlc.arg('recipient_type')+ AND i.recipient_id = sqlc.arg('recipient_id')+ AND i.issue_id = sqlc.arg('issue_id')+ AND i.archived = false+ AND COALESCE(i.section = 'activity', i.type = ANY(sqlc.arg('activity_types')::text[])+ OR (COALESCE(i.actor_type, '') = 'agent' AND i.type = ANY(sqlc.arg('agent_activity_types')::text[])));++-- name: MarkInboxReadByIssue :execrows+-- Opening an issue anywhere (Work sidebar, search, a link) settles its inbox+-- notifications, so the same event is never cleared twice. Every active row is+-- marked, not just the newest, so no older sibling resurfaces as unread.+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: UnarchiveInboxItem :one-- Deliberately does not touch `read`: unarchiving restores an item to the main-- inbox in the exact read/unread state it was archived in, so restoring an@@ -151,8 +175,16 @@ WHERE workspace_id = $1 AND issue_id = $2 AND type = $3 AND archived = falseRETURNING recipient_type, recipient_id;-- name: CountUnreadInbox :one-SELECT count(*) FROM inbox_item-WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND read = false AND archived = false;+-- Activity rows never count as unread, whatever their stored `read` flag; see+-- inbox.ItemSection for the rule the predicate mirrors.+SELECT count(*) FROM inbox_item i+WHERE i.workspace_id = sqlc.arg('workspace_id')+ AND i.recipient_type = sqlc.arg('recipient_type')+ AND i.recipient_id = sqlc.arg('recipient_id')+ AND i.read = false+ AND i.archived = false+ AND NOT COALESCE(i.section = 'activity', i.type = ANY(sqlc.arg('activity_types')::text[])+ OR (COALESCE(i.actor_type, '') = 'agent' AND i.type = ANY(sqlc.arg('agent_activity_types')::text[])));-- name: CountUnreadInboxByWorkspace :many-- Per-workspace unread inbox counts for a recipient member, matching the@@ -165,6 +197,10 @@ WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND read =-- 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.+--+-- Only action rows take part (MUL-8483): activity is never unread, and it does+-- not decide a group's state either, so a routine status change landing after+-- an unread mention leaves the mention counted.SELECT newest.workspace_id, count(*) AS countFROM (SELECT DISTINCT ON (i.workspace_id, COALESCE(i.issue_id, i.id))@@ -172,8 +208,10 @@ FROM (FROM inbox_item iJOIN member m ON m.workspace_id = i.workspace_id AND m.user_id = i.recipient_idWHERE i.recipient_type = 'member'- AND i.recipient_id = $1+ AND i.recipient_id = sqlc.arg('recipient_id')AND i.archived = false+ AND NOT COALESCE(i.section = 'activity', i.type = ANY(sqlc.arg('activity_types')::text[])+ OR (COALESCE(i.actor_type, '') = 'agent' AND i.type = ANY(sqlc.arg('agent_activity_types')::text[])))ORDER BY i.workspace_id, COALESCE(i.issue_id, i.id), i.created_at DESC) newestWHERE newest.read = false@@ -188,33 +226,41 @@ UPDATE inbox_item SET archived = trueWHERE workspace_id = $1 AND recipient_type = 'member' AND recipient_id = $2 AND archived = false;-- name: ArchiveAllReadInbox :execrows--- "Read" is the state of the one issue row the inbox renders: the newest--- active notification in that issue group. Archive every row in groups whose--- newest row is read, and leave an unread group wholly untouched. Updating raw--- read rows instead makes an older unread sibling reappear after the newest--- row is archived (and can archive an older read sibling under an unread row).-WITH newest_groups AS (- SELECT DISTINCT ON (COALESCE(i.issue_id, i.id))+-- "Read" is the state of the one row the inbox renders per issue and section:+-- the newest active notification in that group. Action and activity group+-- separately (MUL-8483), and an activity group always counts as read. Archive+-- every row in qualifying groups and leave an unread action group wholly+-- untouched. Updating raw read rows instead makes an older unread sibling+-- reappear after the newest row is archived (and can archive an older read+-- sibling under an unread row).+WITH active AS (+ SELECT i.id,COALESCE(i.issue_id, i.id) AS group_id,- i.read+ i.created_at,+ i.read,+ COALESCE(i.section = 'activity', i.type = ANY(sqlc.arg('activity_types')::text[])+ OR (COALESCE(i.actor_type, '') = 'agent' AND i.type = ANY(sqlc.arg('agent_activity_types')::text[]))) AS is_activityFROM inbox_item i- WHERE i.workspace_id = $1+ WHERE i.workspace_id = sqlc.arg('workspace_id')AND i.recipient_type = 'member'- AND i.recipient_id = $2+ AND i.recipient_id = sqlc.arg('recipient_id')AND i.archived = false- ORDER BY COALESCE(i.issue_id, i.id), i.created_at DESC, i.id DESC+), newest_groups AS (+ SELECT DISTINCT ON (group_id, is_activity)+ group_id,+ is_activity,+ read+ FROM active+ ORDER BY group_id, is_activity, created_at DESC, id DESC), read_groups AS (- SELECT group_id+ SELECT group_id, is_activityFROM newest_groups- WHERE read = true+ WHERE read = true OR is_activity)UPDATE inbox_item i SET archived = true-FROM read_groups selected-WHERE i.workspace_id = $1- AND i.recipient_type = 'member'- AND i.recipient_id = $2- AND i.archived = false- AND COALESCE(i.issue_id, i.id) = selected.group_id;+FROM active a+JOIN read_groups selected USING (group_id, is_activity)+WHERE i.id = a.id;-- name: ArchiveCompletedInbox :execrowsUPDATE inbox_item i SET archived = truediff --git a/server/pkg/db/queries/inbox_archive.sql b/server/pkg/db/queries/inbox_archive.sqlindex ac56469558..c879b51c12 100644--- a/server/pkg/db/queries/inbox_archive.sql+++ b/server/pkg/db/queries/inbox_archive.sql@@ -2,7 +2,11 @@-- Select narrow group representatives before loading bodies or comment anchors.WITH newest AS MATERIALIZED (SELECT DISTINCT ON (COALESCE(i.issue_id, i.id))- i.id, i.issue_id, i.created_at, i.read,+ i.id, i.issue_id, i.created_at,+ -- Activity is never unread (inbox.Section); the caller passes+ -- inbox.ActivityTypes and inbox.AgentActivityTypes.+ (i.read OR COALESCE(i.section = 'activity', i.type = ANY(sqlc.arg(activity_types)::text[])+ OR (COALESCE(i.actor_type, '') = 'agent' AND i.type = ANY(sqlc.arg(agent_activity_types)::text[])))) AS read,CASE WHEN i.actor_type = 'system' THEN 'system'ELSE i.actor_type || ':' || i.actor_id::text END AS actorFROM inbox_item i@@ -60,7 +64,11 @@ ORDER BY i.created_at DESC, i.id DESC;-- Select narrow group representatives before loading bodies or comment anchors.WITH newest AS MATERIALIZED (SELECT DISTINCT ON (COALESCE(i.issue_id, i.id))- i.id, i.issue_id, i.created_at, i.read,+ i.id, i.issue_id, i.created_at,+ -- Activity is never unread (inbox.Section); the caller passes+ -- inbox.ActivityTypes and inbox.AgentActivityTypes.+ (i.read OR COALESCE(i.section = 'activity', i.type = ANY(sqlc.arg(activity_types)::text[])+ OR (COALESCE(i.actor_type, '') = 'agent' AND i.type = ANY(sqlc.arg(agent_activity_types)::text[])))) AS read,CASE WHEN i.actor_type = 'system' THEN 'system'ELSE i.actor_type || ':' || i.actor_id::text END AS actorFROM inbox_item i