Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8541: revert the two-section Inbox (#9815, #9864) (#9875)
Bohan Jiang4e22663a6170
diff --git a/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsx b/apps/mobile/app/(app)/[workspace]/(tabs)/inbox.tsxindex 294b62f9af..d44fb0cc94 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, useState } from "react";+import { useCallback, useMemo } from "react";import {ActionSheetIOS,Alert,@@ -8,13 +8,11 @@ import {import { useQuery } from "@tanstack/react-query";import { router } from "expo-router";import { Ionicons } from "@expo/vector-icons";-import type { InboxItem, InboxSection } from "@multica/core/types";-import { isInboxItemUnread } from "@multica/core/inbox/section";+import type { InboxItem } from "@multica/core/types";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";@@ -31,10 +29,9 @@ 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() {@@ -45,15 +42,12 @@ export default function Inbox() {const { data: rawItems, isLoading, error, refetch, isRefetching } = useQuery(inboxListOptions(wsId),);- // 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 ?? []),+ // Dedup + drop archived to match web/desktop. See CLAUDE.md+ // "Behavioral parity" → inbox dedup incident.+ const data = useMemo(+ () => deduplicateInboxItems(rawItems ?? []),[rawItems],);- const data = sections[section];- const unreadCount = useInboxUnreadCount(wsId);const markRead = useMarkInboxRead();const markAllRead = useMarkAllInboxRead();const archive = useArchiveInbox();@@ -62,7 +56,7 @@ export default function Inbox() {const archiveCompleted = useArchiveCompletedInbox();const onPressItem = useCallback((item: InboxItem) => {- if (isInboxItemUnread(item)) {+ if (!item.read) {// Optimistic read flip lives in useMarkInboxRead.onMutate — fires// setQueryData synchronously before the cancelQueries await, so the// row is already styled "read" by the time iOS captures the source@@ -129,24 +123,6 @@ 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 ? (@@ -161,10 +137,7 @@ export default function Inbox() {</Button></View>) : !data || data.length === 0 ? (- <InboxEmpty- section={section}- iconColor={THEME[colorScheme].mutedForeground}- />+ <InboxEmpty iconColor={THEME[colorScheme].mutedForeground} />) : (<FlatListdata={data}@@ -207,27 +180,17 @@ function InboxLoading() {);}-function InboxEmpty({- section,- iconColor,-}: {- section: InboxSection;- iconColor: string;-}) {+function InboxEmpty({ iconColor }: { 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">- {section === "activity"- ? t("sections.activity_empty")- : t("empty.title")}+ {t("empty.title")}</Text><Text className="text-sm text-muted-foreground text-center">- {section === "activity"- ? t("sections.activity_empty_body")- : t("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 753af24add..91f2b8e4dc 100644--- a/apps/mobile/app/(app)/[workspace]/issue/[id].tsx+++ b/apps/mobile/app/(app)/[workspace]/issue/[id].tsx@@ -40,7 +40,6 @@ 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";@@ -79,8 +78,6 @@ 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 df0c3a30b9..1acf056f8c 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 — Inbox routing per kind + system toggle+ * - more/settings/notifications — per-group inbox + system toggles** 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 149457641f..0bef74efa7 100644--- a/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx+++ b/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx@@ -1,72 +1,82 @@/**- * 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.+ * Notification preferences subscreen. 6 inbox groups + system_notifications+ * toggle, each backed by an optimistic PATCH /api/notification-preferences.*- * 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.+ * 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).*/-import { ActivityIndicator, Pressable, ScrollView, View } from "react-native";+import { ActivityIndicator, 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 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}- />- );-}+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",+ },+];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) {@@ -87,109 +97,34 @@ export default function NotificationsSettingsScreen() {);}- const routesAreDefault = notificationRoutesAreDefault(preferences);-return (<ScrollViewclassName="flex-1 bg-background"contentContainerClassName="px-4 py-4 gap-6"><Section- 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>- }+ title={t("groups.inbox_notifications")}>- {NOTIFICATION_ROUTE_KINDS.map((kind, idx) => {- const route = resolveNotificationRoute(preferences, kind);- const isLast = idx === NOTIFICATION_ROUTE_KINDS.length - 1;+ {INBOX_GROUPS.map((group, idx) => {+ const enabled = preferences[group.key] !== "muted";+ const isLast = idx === INBOX_GROUPS.length - 1;return (- <View key={kind.key}>+ <View key={group.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(`routing.kinds.${kind.key}.label`)}- </Text>- <Text className="text-xs text-muted-foreground mt-0.5">- {t(`routing.kinds.${kind.key}.description`)}+ {t(group.labelKey)}</Text>+ {group.descriptionKey ? (+ <Text className="text-xs text-muted-foreground mt-0.5">+ {t(group.descriptionKey)}+ </Text>+ ) : null}</View>- <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>+ <Switch+ checked={enabled}+ onCheckedChange={(checked) => onToggle(group.key, checked)}+ /></View>{!isLast ? <Separator /> : null}</View>@@ -197,7 +132,9 @@ 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">@@ -209,12 +146,9 @@ export default function NotificationsSettingsScreen() {</View><Switchchecked={systemEnabled}- onCheckedChange={(checked) => {- const next: NotificationPreferences = { ...preferences };- if (checked) delete next.system_notifications;- else next.system_notifications = "muted";- mutation.mutate(next);- }}+ onCheckedChange={(checked) =>+ onToggle("system_notifications", checked)+ }/></View></Section>@@ -225,23 +159,18 @@ 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">- <View className="flex-row items-center justify-between gap-3">- <Text className="text-xs uppercase tracking-wider text-muted-foreground">- {title}- </Text>- {action}- </View>+ <Text className="text-xs uppercase tracking-wider text-muted-foreground">+ {title}+ </Text>{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 599fb5374c..ff59f40a6d 100644--- a/apps/mobile/components/inbox/inbox-row.tsx+++ b/apps/mobile/components/inbox/inbox-row.tsx@@ -12,7 +12,6 @@*/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";@@ -28,7 +27,7 @@ interface Props {}export function InboxRow({ item, onPress }: Props) {- const isUnread = isInboxItemUnread(item);+ const isUnread = !item.read;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 9004f800ab..9d89a10d19 100644--- a/apps/mobile/data/api.ts+++ b/apps/mobile/data/api.ts@@ -27,7 +27,6 @@ import type {CreateProjectResourceRequest,InboxItem,InboxWorkspaceUnread,- MarkIssueInboxReadResult,Issue,IssueLabelsResponse,Label,@@ -100,7 +99,6 @@ 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,@@ -117,7 +115,6 @@ import {EMPTY_WORKSPACE_LIST,InboxListSchema,InboxUnreadSummarySchema,- MarkIssueInboxReadResultSchema,NotificationPreferenceResponseSchema,ListLabelsResponseSchema,ListProjectResourcesResponseSchema,@@ -540,20 +537,6 @@ 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 1d34d00c71..bf3086abd6 100644--- a/apps/mobile/data/inbox-schema.test.ts+++ b/apps/mobile/data/inbox-schema.test.ts@@ -1,11 +1,5 @@import { describe, expect, it } from "vitest";-import { parseWithFallback } from "@/lib/parse-response";-import {- InboxListSchema,- InboxUnreadSummarySchema,- MarkIssueInboxReadResultSchema,- UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT,-} from "./schemas";+import { InboxListSchema, InboxUnreadSummarySchema } from "./schemas";/*** Tests for mobile's CLIENT-SIDE parsing of GET /api/inbox.@@ -54,29 +48,6 @@ 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",@@ -172,23 +143,3 @@ 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 696e28214f..ef0f2c4426 100644--- a/apps/mobile/data/mutations/inbox.ts+++ b/apps/mobile/data/mutations/inbox.ts@@ -18,9 +18,6 @@* 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@@ -31,7 +28,6 @@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 {@@ -98,20 +94,16 @@ export function useArchiveInbox() {const key = inboxKeys.list(wsId);await qc.cancelQueries({ queryKey: key });const prev = qc.getQueryData<InboxItem[]>(key);- // 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.+ // 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 = ?).// 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 &&- (!activityOnly || inboxItemSection(item) === "activity"))+ item.id === id || (issueId && item.issue_id === issueId)? { ...item, archived: true }: item,),@@ -127,40 +119,6 @@ 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 2240c51df2..aa18618173 100644--- a/apps/mobile/data/realtime/use-inbox-realtime.ts+++ b/apps/mobile/data/realtime/use-inbox-realtime.ts@@ -25,7 +25,6 @@* 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,@@ -49,13 +48,7 @@ export function useInboxRealtime() {return [// Inbox-domain events: refetch the inbox list and the badge count.- // 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:new", invalidate),ws.on("inbox:read", invalidate),// Mobile has no mark-unread affordance yet (web/desktop right-click// only), but a mark-unread there must un-read the row here too —diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.tsindex 16050d4055..8f914d86e4 100644--- a/apps/mobile/data/schemas.ts+++ b/apps/mobile/data/schemas.ts@@ -21,7 +21,6 @@ import type {Comment,InboxItem,InboxWorkspaceUnread,- MarkIssueInboxReadResult,IssueLabelsResponse,Label,ListLabelsResponse,@@ -583,10 +582,6 @@ 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(""),@@ -614,16 +609,6 @@ 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 0a78cff01d..25b5376e8d 100644--- a/apps/mobile/lib/inbox-display.test.ts+++ b/apps/mobile/lib/inbox-display.test.ts@@ -5,7 +5,6 @@ import {getAutopilotQuotaBody,getInboxDisplayTitle,getInboxNavigationTarget,- groupInboxItemsBySection,} from "./inbox-display";function item(overrides: Partial<InboxItem>): InboxItem {@@ -59,21 +58,6 @@ 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 c125edcec0..5cff69fa12 100644--- a/apps/mobile/lib/inbox-display.ts+++ b/apps/mobile/lib/inbox-display.ts@@ -6,8 +6,7 @@* 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, InboxSection } from "@multica/core/types";-import { inboxItemSection } from "@multica/core/inbox/section";+import type { InboxItem } from "@multica/core/types";import { i18n } from "@/lib/i18n/singleton";function formatResetAt(value: string | undefined): string {@@ -136,30 +135,7 @@ 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.tsdeleted file mode 100644index bae160a2b9..0000000000--- a/apps/mobile/lib/use-mark-inbox-read-on-open.test.ts+++ /dev/null@@ -1,116 +0,0 @@-// @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.tsdeleted file mode 100644index c8a59ef542..0000000000--- a/apps/mobile/lib/use-mark-inbox-read-on-open.ts+++ /dev/null@@ -1,54 +0,0 @@-/**- * 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 bf5f91c8fc..62520d96d6 100644--- a/apps/mobile/locales/en/inbox.json+++ b/apps/mobile/locales/en/inbox.json@@ -4,12 +4,6 @@"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 6dcbf67ce6..4c582d3acd 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": "Inbox",+ "notifications": "Notifications","search": "Search","issue": "Issue","project": "Project",diff --git a/apps/mobile/locales/en/settings.json b/apps/mobile/locales/en/settings.jsonindex 2c9600c3a8..83e97f3aae 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": "Where notifications go, system notifications",+ "notifications_subtitle": "Inbox and system alerts","load_failed": "Failed to load workspaces"},"profile": {@@ -31,7 +31,7 @@"chinese_traditional": "Traditional Chinese"},"notifications": {- "title": "Inbox",+ "title": "Notifications","issues": "Issues","inbox": "Inbox","chat": "Chat",@@ -66,61 +66,20 @@},"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"- },- "comments_without_mentions": {- "label": "Comments without mentions",- "description": "When someone comments on an issue you follow without @mentioning anyone"- },- "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"- },- "comments_mentioning_others": {- "label": "Comments mentioning others",- "description": "When a comment on an issue you follow @mentions other people or agents, but not you"- }- }}}diff --git a/apps/mobile/locales/zh-Hans/inbox.json b/apps/mobile/locales/zh-Hans/inbox.jsonindex 5d18761ce7..4c95d9d92a 100644--- a/apps/mobile/locales/zh-Hans/inbox.json+++ b/apps/mobile/locales/zh-Hans/inbox.json@@ -4,12 +4,6 @@"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 f5d4a2db57..0259dc8f7f 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 f2d6e4668c..b347ca1ddc 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,61 +66,22 @@},"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": "账号变更、安全提醒和产品更新。"},- "routing": {- "title": "通知去向",- "description": "更改只影响之后的新通知。",- "reset": "恢复默认",- "routes": {- "action": {- "label": "需要处理",- "description": "计入未读"- },- "activity": {- "label": "动态",- "description": "安静记录,不计未读"- },- "muted": {- "label": "关闭",- "description": "不进收件箱,在任务里仍能看到"- }- },- "kinds": {- "assigned": {- "label": "分配给我",- "description": "任务分配给你时"- },- "mentions": {- "label": "提及",- "description": "有人 @ 你时,包括 @all 和 @squad"- },- "comments_without_mentions": {- "label": "未 @ 任何人的评论",- "description": "有人在你订阅的任务里评论,且没有 @ 任何人时"- },- "agent_failures": {- "label": "智能体出错",- "description": "智能体运行失败或被阻塞、需要你介入时"- },- "status_changes": {- "label": "状态变更",- "description": "你订阅的任务状态变化时"- },- "assignee_changes": {- "label": "负责人变更",- "description": "任务换了负责人,或你被取消分配时"- },- "updates": {- "label": "优先级与日期",- "description": "优先级、开始日期或截止日期变化时"- },- "comments_mentioning_others": {- "label": "@ 了其他人的评论",- "description": "你订阅的任务里的评论 @ 了其他成员或智能体、但没有 @ 你时"- }- }- }+ "groups.assignments_description": "任务分配给我或取消分配给我时。",+ "groups.mentions_description": "有人用 @ 提到你时,包括 @all 和 @squad。"}diff --git a/apps/mobile/locales/zh-Hant/inbox.json b/apps/mobile/locales/zh-Hant/inbox.jsonindex 7574a25381..657378c89c 100644--- a/apps/mobile/locales/zh-Hant/inbox.json+++ b/apps/mobile/locales/zh-Hant/inbox.json@@ -4,12 +4,6 @@"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 33a1b4d713..1db2a6e2ba 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 8282e6a227..3b36d7b700 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,61 +66,22 @@},"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": "帳號變更、安全提醒和產品更新。"},- "routing": {- "title": "通知去向",- "description": "變更只影響之後的新通知。",- "reset": "恢復預設",- "routes": {- "action": {- "label": "需要處理",- "description": "計入未讀"- },- "activity": {- "label": "動態",- "description": "安靜記錄,不計未讀"- },- "muted": {- "label": "關閉",- "description": "不進收件箱,在任務裡仍能看到"- }- },- "kinds": {- "assigned": {- "label": "分配給我",- "description": "任務分配給你時"- },- "mentions": {- "label": "提及",- "description": "有人 @ 你時,包括 @all 和 @squad"- },- "comments_without_mentions": {- "label": "未 @ 任何人的評論",- "description": "有人在你訂閱的任務裡評論,且沒有 @ 任何人時"- },- "agent_failures": {- "label": "AI 代理出錯",- "description": "AI 代理執行失敗或被阻塞、需要你介入時"- },- "status_changes": {- "label": "狀態變更",- "description": "你訂閱的任務狀態變化時"- },- "assignee_changes": {- "label": "負責人變更",- "description": "任務換了負責人,或你被取消分配時"- },- "updates": {- "label": "優先順序與日期",- "description": "優先順序、開始日期或截止日期變化時"- },- "comments_mentioning_others": {- "label": "@ 了其他人的評論",- "description": "你訂閱的任務裡的評論 @ 了其他成員或 AI 代理、但沒有 @ 你時"- }- }- }+ "groups.assignments_description": "任務分配給我或取消分配給我時。",+ "groups.mentions_description": "有人用 @ 提到你時,包括 @all 和 @squad。"}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex c1b116e255..d50098e8c2 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -54,7 +54,6 @@ import type {UpdateRuntimeProfileRequest,InboxItem,InboxWorkspaceUnread,- MarkIssueInboxReadResult,IssueSubscriber,IssueUnread,Comment,@@ -416,8 +415,6 @@ import {EMPTY_CREATE_FEEDBACK_RESPONSE,InboxUnreadSummarySchema,EMPTY_INBOX_UNREAD_SUMMARY,- MarkIssueInboxReadResultSchema,- UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT,IssueUnreadPageSchema,EMPTY_ISSUE_UNREAD_PAGE,InboxItemListSchema,@@ -2967,14 +2964,6 @@ 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 4decea67ff..53af0e1581 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -46,8 +46,6 @@ import {InboxItemListSchema,InboxUnreadSummarySchema,IssueTriggerPreviewSchema,- MarkIssueInboxReadResultSchema,- UNKNOWN_MARK_ISSUE_INBOX_READ_RESULT,ListIssuesResponseSchema,ListPropertiesResponseSchema,MALFORMED_RUNTIME_MODEL_LIST_REQUEST,@@ -81,24 +79,6 @@ 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 28314789b0..bae7b5cdd7 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -57,7 +57,6 @@ import type {IssuePullRequestsResponse,InboxItem,InboxWorkspaceUnread,- MarkIssueInboxReadResult,IssueUnread,Label,MemberWithUser,@@ -2765,13 +2764,6 @@ 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.@@ -2821,9 +2813,6 @@ 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 0be35241bd..d44b66d4e5 100644--- a/packages/core/inbox/filter-store.test.ts+++ b/packages/core/inbox/filter-store.test.ts@@ -161,19 +161,6 @@ 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 b341b208d5..1444a933ea 100644--- a/packages/core/inbox/filter-store.ts+++ b/packages/core/inbox/filter-store.ts@@ -1,6 +1,5 @@import { create } from "zustand";import type { InboxItem, IssuePriority, IssueStatus } from "../types";-import { isInboxItemUnread } from "./section";export interface InboxFilters {readonly statuses: readonly IssueStatus[];@@ -237,8 +236,7 @@ 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 whether the rendered row is unread, which an- * activity row never is. The unread badge+ * `unreadOnly` likewise reads the rendered row's `read`. 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.@@ -284,7 +282,7 @@ export function filterInboxItems(const key = item.issue_id ?? item.id;const matchesUnread =!filters.unreadOnly ||- isInboxItemUnread(item) ||+ item.read !== true ||(pinnedUnreadKey != null && key === pinnedUnreadKey);const matchesIdle =!filters.idleOnly ||diff --git a/packages/core/inbox/mutations.test.tsx b/packages/core/inbox/mutations.test.tsxindex ce802adf07..493d5fe7d2 100644--- a/packages/core/inbox/mutations.test.tsx+++ b/packages/core/inbox/mutations.test.tsx@@ -9,13 +9,7 @@ import type { ReactNode } from "react";import { setApiInstance } from "../api";import type { ApiClient } from "../api/client";import type { InboxItem, InboxWorkspaceUnread } from "../types";-import {- useArchiveInbox,- useMarkInboxRead,- useMarkInboxUnread,- useMarkIssueInboxRead,- useUnarchiveInbox,-} from "./mutations";+import { useMarkInboxRead, useMarkInboxUnread, useUnarchiveInbox } from "./mutations";import { inboxKeys, useInboxUnreadCount } from "./queries";import { onInboxSummaryInvalidate } from "./ws-updaters";import { createQueryClient } from "../query-client";@@ -71,103 +65,6 @@ 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 79f8462d7f..b4becc22f7 100644--- a/packages/core/inbox/mutations.ts+++ b/packages/core/inbox/mutations.ts@@ -1,13 +1,7 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import type { QueryClient } from "@tanstack/react-query";import { api } from "../api";-import {- inboxItemSection,- inboxKeys,- mapArchivedInboxCache,- patchArchivedInboxCaches,- type ArchivedInboxCache,-} from "./queries";+import { inboxKeys, mapArchivedInboxCache, patchArchivedInboxCaches, type ArchivedInboxCache } from "./queries";import { onInboxInvalidate, onInboxSummaryInvalidate } from "./ws-updaters";import { useWorkspaceId } from "../hooks";import type { InboxItem } from "../types";@@ -109,15 +103,12 @@ export function useArchiveInbox() {onMutate: async (id) => {await qc.cancelQueries({ queryKey: inboxKeys.list(wsId) });const prev = qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId));- // 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.+ // Archive all items for the same issue (same behavior as store)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 && (!activityOnly || inboxItemSection(item) === "activity"))+ item.id === id || (issueId && item.issue_id === issueId)? { ...item, archived: true }: item,),@@ -174,35 +165,6 @@ 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 4b6d0eac6e..4ce1406666 100644--- a/packages/core/inbox/queries.test.ts+++ b/packages/core/inbox/queries.test.ts@@ -6,10 +6,7 @@ import {archivedInboxPagesOptions,deduplicateArchivedInboxItems,deduplicateInboxItems,- groupInboxItemsBySection,hasOtherWorkspaceUnread,- inboxItemSection,- isInboxItemUnread,inboxKeys,unreadCountForWorkspace,unreadWorkspaceIds,@@ -37,32 +34,6 @@ 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 4599c806d1..290389b6c8 100644--- a/packages/core/inbox/queries.ts+++ b/packages/core/inbox/queries.ts@@ -3,11 +3,8 @@ 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, InboxSection, InboxWorkspaceUnread } from "../types";+import type { InboxItem, 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,@@ -192,20 +189,6 @@ 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.tsdeleted file mode 100644index 309d1829b1..0000000000--- a/packages/core/inbox/section.ts+++ /dev/null@@ -1,14 +0,0 @@-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 9865f0237f..4b3efba544 100644--- a/packages/core/notification-preferences/index.ts+++ b/packages/core/notification-preferences/index.ts@@ -1,4 +1,3 @@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 545a58bca6..c0c0a331de 100644--- a/packages/core/notification-preferences/patch.ts+++ b/packages/core/notification-preferences/patch.ts@@ -5,16 +5,11 @@ import type {} from "../types";const NOTIFICATION_GROUP_KEYS: readonly NotificationGroupKey[] = [- "assigned",- "mentions",- "comments_without_mentions",- "agent_failures",- "status_changes",- "assignee_changes",- "updates",- "comments_mentioning_others","assignments",+ "status_changes","comments",+ "mentions",+ "updates","agent_activity","system_notifications",];@@ -56,10 +51,10 @@ export function applyNotificationPreferencePatch(for (const key of NOTIFICATION_GROUP_KEYS) {const value = patch[key];- if (value === "all") {- delete next[key];- } else if (value !== undefined) {+ if (value === "muted") {next[key] = value;+ } else if (value === "all") {+ delete next[key];}}@@ -68,7 +63,7 @@ export function applyNotificationPreferencePatch(/*** Roll back only values that still match this mutation's optimistic patch.- * A later change that touched the same key wins.+ * A later toggle 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.tsdeleted file mode 100644index b1b7018a14..0000000000--- a/packages/core/notification-preferences/routes.test.ts+++ /dev/null@@ -1,100 +0,0 @@-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",- comments_without_mentions: "action",- agent_failures: "action",- status_changes: "activity",- assignee_changes: "activity",- updates: "activity",- comments_mentioning_others: "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",- comments_mentioning_others: "activity",- };- expect(resolveNotificationRoute(prefs, kind("comments_without_mentions"))).toBe("muted");- expect(resolveNotificationRoute(prefs, kind("comments_mentioning_others"))).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("comments_without_mentions"),- "action",- );- expect(next).toEqual({ comments_mentioning_others: "muted", system_notifications: "muted" });- expect(resolveNotificationRoute(next, kind("comments_without_mentions"))).toBe("action");- expect(resolveNotificationRoute(next, kind("comments_mentioning_others"))).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.tsdeleted file mode 100644index 19994d5f50..0000000000--- a/packages/core/notification-preferences/routes.ts+++ /dev/null@@ -1,92 +0,0 @@-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.- *- * Comments route by who they are written to, not who wrote them: one that- * @mentions nobody, or one that @mentions others but not the recipient. A- * comment that @mentions the recipient follows `mentions`.- */-export const NOTIFICATION_ROUTE_KINDS: readonly NotificationRouteKind[] = [- { key: "assigned", default: "action", legacy: "assignments" },- { key: "mentions", default: "action" },- { key: "comments_without_mentions", 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: "comments_mentioning_others", 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 1b8e4d3d9f..19331012ad 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -62,7 +62,6 @@"./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",@@ -70,7 +69,6 @@"./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 8109e36d8e..965021a85d 100644--- a/packages/core/realtime/use-realtime-sync.test.ts+++ b/packages/core/realtime/use-realtime-sync.test.ts@@ -816,24 +816,6 @@ 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 93fee1b412..660359c837 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -52,7 +52,6 @@ import {invalidateUpdatedAtSortedIssueLists,} from "../issues/cache-coordinator";import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged, onInboxIssueDeleted, onInboxSummaryInvalidate } from "../inbox/ws-updaters";-import { inboxItemSection } from "../inbox/queries";import {notificationPreferenceOptions,notificationPreferenceKeys,@@ -574,9 +573,6 @@ 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 5af9595197..473ed003a8 100644--- a/packages/core/types/inbox.ts+++ b/packages/core/types/inbox.ts@@ -44,19 +44,6 @@ 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;@@ -76,12 +63,6 @@ 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 1642b6a592..cc2d90d352 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, InboxSection, InboxSeverity, InboxItemType, InboxWorkspaceUnread, MarkIssueInboxReadResult, ArchivedInboxPage, ArchivedInboxFacets } from "./inbox";-export type { NotificationGroupKey, NotificationGroupValue, NotificationLegacyGroupKey, NotificationPreferences, NotificationPreferenceResponse, NotificationRoute, NotificationRouteKey } from "./notification-preference";+export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread, ArchivedInboxPage, ArchivedInboxFacets } from "./inbox";+export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } 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 17f5918bf9..204dbaa8ec 100644--- a/packages/core/types/notification-preference.ts+++ b/packages/core/types/notification-preference.ts@@ -1,27 +1,13 @@-/** A kind of notification whose Inbox section the recipient chooses. */-export type NotificationRouteKey =- | "assigned"- | "mentions"- | "comments_without_mentions"- | "agent_failures"+export type NotificationGroupKey =+ | "assignments"| "status_changes"- | "assignee_changes"+ | "comments"+ | "mentions"| "updates"- | "comments_mentioning_others";--/** 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+ | "agent_activity"| "system_notifications";-/** "all" (or an absent key) means the kind's default. */-export type NotificationGroupValue = "all" | NotificationRoute;+export type NotificationGroupValue = "all" | "muted";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 69f9dad895..2e0f44e4df 100644--- a/packages/views/inbox/components/inbox-context-menu.test.tsx+++ b/packages/views/inbox/components/inbox-context-menu.test.tsx@@ -140,16 +140,6 @@ 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 a69bb6a524..f7bcf6f58f 100644--- a/packages/views/inbox/components/inbox-item-actions.tsx+++ b/packages/views/inbox/components/inbox-item-actions.tsx@@ -1,7 +1,6 @@"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";@@ -67,9 +66,8 @@ 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. Activity is never- // unread at all, so it has no toggle either.- if (!isArchivedView && inboxItemSection(item) === "action") {+ // would report success and change nothing on screen.+ if (!isArchivedView) {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 e73447eb49..07344c6fe6 100644--- a/packages/views/inbox/components/inbox-list-item.tsx+++ b/packages/views/inbox/components/inbox-list-item.tsx@@ -1,7 +1,6 @@"use client";import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";-import { isInboxItemUnread } from "@multica/core/inbox/queries";import { StatusIcon } from "../../issues/components";import {IssueAgentActivityIndicator,@@ -81,7 +80,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 = isInboxItemUnread(item) && !isArchivedView;+ const showUnread = item.read !== true && !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 16f142b6a2..514c60055f 100644--- a/packages/views/inbox/components/inbox-page.test.tsx+++ b/packages/views/inbox/components/inbox-page.test.tsx@@ -74,16 +74,8 @@ 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"] }),- 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"),- };- },+ deduplicateInboxItems: (items: InboxItem[]) => items.filter((i) => !i.archived),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,}));@@ -1122,47 +1114,3 @@ 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 8673204b09..0f3745bb48 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -26,9 +26,8 @@ import {inboxListOptions,archivedInboxPagesOptions,archivedInboxLookupOptions,- groupInboxItemsBySection,+ deduplicateInboxItems,deduplicateArchivedInboxItems,- isInboxItemUnread,useInboxUnreadCount,} from "@multica/core/inbox/queries";import {@@ -72,8 +71,7 @@ import {ListChecks,ArrowLeft,} from "@multica/ui/icons";-import type { InboxItem, InboxSection } from "@multica/core/types";-import { Tabs, TabsList, TabsTrigger } from "@multica/ui/components/ui/tabs";+import type { InboxItem } from "@multica/core/types";import { Button } from "@multica/ui/components/ui/button";import { IconButton } from "@multica/ui/components/common/icon-button";import {@@ -102,7 +100,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 { ACTIVITY_SECTION_PARAM, ARCHIVED_VIEW_PARAM, type InboxView } from "./inbox-view";+import { ARCHIVED_VIEW_PARAM, type InboxView } from "./inbox-view";import { useTypeLabels } from "./inbox-detail-label";import {getInboxDisplayTitle,@@ -127,13 +125,10 @@ 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.@@ -151,9 +146,6 @@ export function InboxPage() {useEffect(() => {setViewState(urlView);}, [urlView]);- useEffect(() => {- setSectionState(urlSection);- }, [urlSection]);const wsId = useWorkspaceId();const isArchivedView = view === "archived";@@ -162,8 +154,7 @@ export function InboxPage() {const { data: rawItems = [], isLoading: loading } = useQuery({...inboxListOptions(wsId), enabled: !isArchivedView,});- const sections = useMemo(() => groupInboxItemsBySection(rawItems), [rawItems]);- const items = sections[section];+ const items = useMemo(() => deduplicateInboxItems(rawItems), [rawItems]);const archiveQuery = useInfiniteQuery({...archivedInboxPagesOptions(wsId, filters), enabled: isArchivedView,});@@ -229,8 +220,6 @@ export function InboxPage() {// leaves; opening an already-empty inbox shows it at rest. Archived and// filtered views are not inbox zero, so they never arm it.const inboxZeroCount = isArchivedView || hasActiveFilters ? -1 : visibleItems.length;- const activityWaiting =- inboxZeroCount === 0 && section === "action" ? sections.activity.length : 0;const [prevInboxZeroCount, setPrevInboxZeroCount] = useState(inboxZeroCount);const [inboxZeroRises, setInboxZeroRises] = useState(false);if (inboxZeroCount !== prevInboxZeroCount) {@@ -272,10 +261,9 @@ 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, nextSection: InboxSection) => {+ (nextView: InboxView, key: string) => {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();@@ -286,8 +274,8 @@ export function InboxPage() {const setSelectedKey = useCallback((key: string) => {setSelectedKeyState(key);- replace(buildInboxUrl(view, key, section));- }, [replace, buildInboxUrl, view, section]);+ replace(buildInboxUrl(view, key));+ }, [replace, buildInboxUrl, view]);// Switching views always clears the selection: the two lists are mutually// exclusive, so a key carried across would never resolve, and the fallback@@ -295,16 +283,7 @@ export function InboxPage() {const setView = useCallback((nextView: InboxView) => {setViewState(nextView);setSelectedKeyState("");- 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(nextView, ""));}, [replace, buildInboxUrl]);// Applying a filter can remove the open row from the list. Clear that local@@ -336,22 +315,10 @@ 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,@@ -394,7 +361,7 @@ export function InboxPage() {// in handleSelect so URL-driven selection triggers it too.const markReadMutate = markReadMutation.mutate;const selectedId = selected?.id;- const selectedRead = selected ? !isInboxItemUnread(selected) : undefined;+ const selectedRead = selected?.read;useEffect(() => {if (!selectedId || selectedRead) return;if (manualUnreadIdRef.current === selectedId) return;@@ -594,7 +561,7 @@ export function InboxPage() {};const handleArchiveAllRead = () => {- const readKeys = items.filter((i) => !isInboxItemUnread(i)).map((i) => i.issue_id ?? i.id);+ const readKeys = items.filter((i) => i.read).map((i) => i.issue_id ?? i.id);if (readKeys.includes(selectedKey)) setSelectedKey("");archiveAllReadMutation.mutate(undefined, {onError: (err) =>@@ -777,11 +744,7 @@ export function InboxPage() {emptyLabel={hasActiveFilters && visibleItems.length === 0? t(($) => $.filters.empty)- : isArchivedView- ? undefined- : section === "activity"- ? t(($) => $.sections.activity_empty)- : t(($) => $.sections.action_empty)+ : undefined}emptyAction={hasActiveFilters && visibleItems.length === 0 ? (@@ -798,28 +761,9 @@ 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)}@@ -1138,22 +1082,8 @@ export function InboxPage() {? t(($) => $.detail.select_prompt): isArchivedView? t(($) => $.list.archived_empty)- : rawItems.some((i) => !i.archived)- ? section === "activity"- ? t(($) => $.sections.activity_empty)- : t(($) => $.sections.action_empty)- : t(($) => $.detail.empty)}+ : t(($) => $.detail.empty)}</p>- {activityWaiting > 0 ? (- <div className="relative mt-1 flex flex-col items-center gap-3">- <p className="text-label">- {t(($) => $.sections.activity_waiting, { count: activityWaiting })}- </p>- <Button variant="outline" size="sm" onClick={() => setSection("activity")}>- {t(($) => $.sections.open_activity)}- </Button>- </div>- ) : null}</div></>)}diff --git a/packages/views/inbox/components/inbox-view.ts b/packages/views/inbox/components/inbox-view.tsindex bcb744e0ef..a8d729c666 100644--- a/packages/views/inbox/components/inbox-view.ts+++ b/packages/views/inbox/components/inbox-view.ts@@ -13,10 +13,3 @@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 405c815208..e702917769 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -167,7 +167,6 @@ 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 {@@ -1562,7 +1561,6 @@ 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.tsxdeleted file mode 100644index 0a7128f0f3..0000000000--- a/packages/views/issues/hooks/use-mark-inbox-read-while-viewing.test.tsx+++ /dev/null@@ -1,151 +0,0 @@-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.tsdeleted file mode 100644index 14c8d0b56b..0000000000--- a/packages/views/issues/hooks/use-mark-inbox-read-while-viewing.ts+++ /dev/null@@ -1,52 +0,0 @@-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 c48fb69416..6bf6512f98 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 {- groupInboxItemsBySection,+ deduplicateInboxItems,inboxListOptions,useInboxUnreadCount,} from "@multica/core/inbox/queries";@@ -33,9 +33,8 @@ const EMPTY_SESSIONS: ChatSession[] = [];const EMPTY_AGENTS: Agent[] = [];/**- * 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.+ * 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.*/export function InboxPeek() {const { t } = useT("inbox");@@ -50,7 +49,7 @@ export function InboxPeek() {const items = useMemo(() => {const effective = inboxFiltersForPrioritySupport(filters, inboxPriorityFilterSupport(rawItems));- return filterInboxItems(groupInboxItemsBySection(rawItems).action, effective, {+ return filterInboxItems(deduplicateInboxItems(rawItems), 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 e92f01bebc..ceb7c6ac9d 100644--- a/packages/views/locales/en/inbox.json+++ b/packages/views/locales/en/inbox.json@@ -3,15 +3,6 @@"title": "Inbox","back": "Inbox"},- "sections": {- "action": "Needs action",- "activity": "Activity",- "action_empty": "You're all caught up",- "activity_empty": "No recent activity",- "activity_waiting_other": "{{count}} updates are waiting in Activity.",- "open_activity": "View activity",- "activity_waiting_one": "{{count}} update is waiting in 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 ddcbe9d3f7..9f2073396f 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": "Inbox",+ "notifications": "Notifications","tokens": "API Tokens","general": "General","github": "GitHub",@@ -652,61 +652,38 @@"toast_profile_failed": "Failed to update profile"},"notifications": {- "title": "Routing",- "description": "Changes apply to new notifications.",- "reset": "Restore defaults",+ "title": "Inbox Notifications",+ "description": "Muted events remain visible on the issue.","toast_failed": "Failed to update notification settings",- "routes": {- "action": {- "label": "Needs action",- "description": "Counts as unread, can send a system notification"+ "groups": {+ "assignments": {+ "label": "Assignments",+ "description": "When you are assigned or unassigned from an issue"},- "activity": {- "label": "Activity",- "description": "Recorded quietly, never unread"+ "status_changes": {+ "label": "Status changes",+ "description": "When an issue you follow changes status (e.g. todo, in progress, done)"},- "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"+ "comments": {+ "label": "Comments",+ "description": "New comments on issues you follow"},"mentions": {"label": "Mentions","description": "When someone @mentions you, including @all and @squad"},- "comments_without_mentions": {- "label": "Comments without mentions",- "description": "When someone comments on an issue you follow without @mentioning anyone"- },- "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"+ "label": "Priority & Due date",+ "description": "When priority or due date changes on issues you follow"},- "comments_mentioning_others": {- "label": "Comments mentioning others",- "description": "When a comment on an issue you follow @mentions other people or agents, but not you"+ "agent_activity": {+ "label": "Agent activity",+ "description": "When an agent run fails"}},"system": {"title": "System Notifications",- "label": "Send a system notification for Needs action items while Multica is in the background"+ "label": "Show system notifications when 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 9d34a7f5e0..5d48ee2d52 100644--- a/packages/views/locales/fr/inbox.json+++ b/packages/views/locales/fr/inbox.json@@ -3,15 +3,6 @@"title": "Boîte de réception","back": "Boîte de réception"},- "sections": {- "action": "À traiter",- "activity": "Activité",- "action_empty": "Vous êtes à jour",- "activity_empty": "Aucune activité récente",- "activity_waiting_other": "{{count}} mises à jour vous attendent dans Activité.",- "open_activity": "Voir l'activité",- "activity_waiting_one": "{{count}} mise à jour vous attend dans Activité."- },"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 a8aeb23809..415edae931 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": "Boîte de réception",+ "notifications": "Notifications","tokens": "Jetons d'API","general": "Général","github": "GitHub",@@ -652,61 +652,38 @@"toast_profile_failed": "Échec de la mise à jour du profil"},"notifications": {- "title": "Tri des notifications",- "description": "Les changements s'appliquent aux nouvelles notifications.",- "reset": "Rétablir les valeurs par défaut",+ "title": "Notifications de la boîte de réception",+ "description": "Les événements désactivés restent visibles dans la tâche.","toast_failed": "Échec de la mise à jour des réglages de notification",- "routes": {- "action": {- "label": "À traiter",- "description": "Compte comme non lu, peut envoyer une notification système"+ "groups": {+ "assignments": {+ "label": "Assignations",+ "description": "Quand une tâche vous est assignée ou retirée"},- "activity": {- "label": "Activité",- "description": "Consigné discrètement, jamais non lu"+ "status_changes": {+ "label": "Changements de statut",+ "description": "Quand une tâche que vous suivez change de statut (à faire, en cours, terminé…)"},- "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"+ "comments": {+ "label": "Commentaires",+ "description": "Nouveaux commentaires sur les tâches que vous suivez"},"mentions": {"label": "Mentions",- "description": "Quand quelqu'un vous @mentionne, y compris @all et @squad"- },- "comments_without_mentions": {- "label": "Commentaires sans mention",- "description": "Quand quelqu'un commente une tâche que vous suivez sans @mentionner personne"- },- "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é"+ "description": "Quand quelqu'un vous @mentionne, y compris via @all et @squad"},"updates": {- "label": "Priorité et dates",- "description": "Quand la priorité, la date de début ou l'échéance change"+ "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"},- "comments_mentioning_others": {- "label": "Commentaires mentionnant d'autres",- "description": "Quand un commentaire sur une tâche que vous suivez @mentionne d'autres personnes ou agents, mais pas vous"+ "agent_activity": {+ "label": "Activité des agents",+ "description": "Lorsqu'une exécution d'agent échoue"}},"system": {"title": "Notifications système",- "label": "Envoyer une notification système pour les éléments « À traiter » quand Multica est en arrière-plan"+ "label": "Afficher les notifications système lorsque 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 0cdc797a3e..5b154dd71e 100644--- a/packages/views/locales/ja/inbox.json+++ b/packages/views/locales/ja/inbox.json@@ -3,14 +3,6 @@"title": "インボックス","back": "インボックス"},- "sections": {- "action": "要対応",- "activity": "アクティビティ",- "action_empty": "対応が必要なものはすべて片付きました",- "activity_empty": "最近のアクティビティはありません",- "activity_waiting_other": "アクティビティに {{count}} 件の更新があります。",- "open_activity": "アクティビティを見る"- },"menu": {"mark_all_read": "すべて既読にする","archive_all": "すべてアーカイブ",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex a85075e9be..449db9c309 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,61 +647,38 @@"toast_profile_failed": "プロフィールを更新できませんでした"},"notifications": {- "title": "通知の振り分け",- "description": "変更はこれからの通知に適用されます。",- "reset": "デフォルトに戻す",+ "title": "インボックス通知",+ "description": "通知をオフにしても、タスク上で履歴を確認できます。","toast_failed": "通知設定を更新できませんでした",- "routes": {- "action": {- "label": "要対応",- "description": "未読に数え、システム通知を送れる"+ "groups": {+ "assignments": {+ "label": "担当の割り当て",+ "description": "タスクの担当者に割り当てられたとき、または解除されたとき"},- "activity": {- "label": "アクティビティ",- "description": "静かに記録し、未読に数えない"+ "status_changes": {+ "label": "ステータス変更",+ "description": "フォロー中のタスクのステータスが変わったとき(例: todo、in progress、done)"},- "muted": {- "label": "オフ",- "description": "インボックスに入らない。タスクでは引き続き表示"- }- },- "kinds": {- "assigned": {- "label": "自分への割り当て",- "description": "タスクが自分に割り当てられたとき"+ "comments": {+ "label": "コメント",+ "description": "フォロー中のタスクに新しいコメントが付いたとき"},"mentions": {"label": "メンション",- "description": "誰かがあなたを @ したとき(@all と @squad を含む)"- },- "comments_without_mentions": {- "label": "メンションなしのコメント",- "description": "フォロー中のタスクに、誰も @ していないコメントが付いたとき"- },- "agent_failures": {- "label": "エージェントのエラー",- "description": "エージェントの実行が失敗またはブロックされ、対応が必要なとき"- },- "status_changes": {- "label": "ステータス変更",- "description": "フォロー中のタスクのステータスが変わったとき"- },- "assignee_changes": {- "label": "担当者の変更",- "description": "タスクの担当者が変わったとき、または割り当てが外れたとき"+ "description": "誰かがあなたを @メンションしたとき(@all と @squad を含む)"},"updates": {- "label": "優先度と日付",- "description": "優先度、開始日、期日が変わったとき"+ "label": "優先度と期限",+ "description": "フォロー中のタスクの優先度や期限が変わったとき"},- "comments_mentioning_others": {- "label": "他の人をメンションしたコメント",- "description": "フォロー中のタスクのコメントが、あなたではなく他の人やエージェントを @ したとき"+ "agent_activity": {+ "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 a0d06e8aa0..dc66eb8d09 100644--- a/packages/views/locales/ko/inbox.json+++ b/packages/views/locales/ko/inbox.json@@ -3,14 +3,6 @@"title": "인박스","back": "인박스"},- "sections": {- "action": "처리 필요",- "activity": "활동",- "action_empty": "처리할 항목을 모두 처리했습니다",- "activity_empty": "최근 활동이 없습니다",- "activity_waiting_other": "활동에 업데이트 {{count}}개가 있습니다.",- "open_activity": "활동 보기"- },"menu": {"mark_all_read": "모두 읽음으로 표시","archive_all": "모두 보관",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex ddf1e74916..c9b3196cdd 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,61 +647,38 @@"toast_profile_failed": "프로필을 업데이트하지 못했습니다"},"notifications": {- "title": "알림 분류",- "description": "변경 사항은 이후 새 알림에 적용됩니다.",- "reset": "기본값 복원",+ "title": "인박스 알림",+ "description": "알림을 꺼도 태스크에서 관련 활동을 볼 수 있습니다.","toast_failed": "알림 설정을 업데이트하지 못했습니다",- "routes": {- "action": {- "label": "처리 필요",- "description": "읽지 않음으로 집계, 시스템 알림 가능"+ "groups": {+ "assignments": {+ "label": "할당",+ "description": "태스크에 할당되거나 할당 해제될 때"},- "activity": {- "label": "활동",- "description": "조용히 기록, 읽지 않음 아님"+ "status_changes": {+ "label": "상태 변경",+ "description": "팔로우 중인 태스크의 상태가 바뀔 때(예: 할 일, 진행 중, 완료)"},- "muted": {- "label": "끄기",- "description": "인박스에 들어오지 않음. 태스크에서는 계속 표시"- }- },- "kinds": {- "assigned": {- "label": "나에게 할당",- "description": "태스크가 나에게 할당될 때"+ "comments": {+ "label": "댓글",+ "description": "팔로우 중인 태스크에 새 댓글이 달릴 때"},"mentions": {"label": "멘션",- "description": "누군가 나를 @ 멘션할 때(@all, @squad 포함)"- },- "comments_without_mentions": {- "label": "멘션 없는 댓글",- "description": "팔로우 중인 태스크에 아무도 @ 멘션하지 않은 댓글이 달릴 때"- },- "agent_failures": {- "label": "에이전트 오류",- "description": "에이전트 실행이 실패하거나 막혀 내 개입이 필요할 때"- },- "status_changes": {- "label": "상태 변경",- "description": "팔로우 중인 태스크의 상태가 바뀔 때"- },- "assignee_changes": {- "label": "담당자 변경",- "description": "태스크 담당자가 바뀌거나 내 할당이 해제될 때"+ "description": "누군가 나를 @멘션할 때(@all, @squad 포함)"},"updates": {- "label": "우선순위와 날짜",- "description": "우선순위, 시작일, 마감일이 바뀔 때"+ "label": "우선순위 및 마감일",+ "description": "팔로우 중인 태스크의 우선순위나 마감일이 바뀔 때"},- "comments_mentioning_others": {- "label": "다른 사람을 멘션한 댓글",- "description": "팔로우 중인 태스크의 댓글이 내가 아닌 다른 사람이나 에이전트를 @ 멘션할 때"+ "agent_activity": {+ "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 664382bc81..e2568ccfc0 100644--- a/packages/views/locales/zh-Hans/inbox.json+++ b/packages/views/locales/zh-Hans/inbox.json@@ -3,14 +3,6 @@"title": "收件箱","back": "收件箱"},- "sections": {- "action": "需要处理",- "activity": "动态",- "action_empty": "需要你处理的都处理完了",- "activity_empty": "暂无动态",- "activity_waiting_other": "动态里还有 {{count}} 条更新,随时可以看。",- "open_activity": "查看动态"- },"menu": {"mark_all_read": "全部标为已读","archive_all": "归档全部",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 97beac4591..090b7b8c58 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,61 +647,38 @@"toast_profile_failed": "更新资料失败"},"notifications": {- "title": "通知去向",- "description": "更改只影响之后的新通知。",- "reset": "恢复默认",+ "title": "收件箱通知",+ "description": "关闭通知后,仍可在任务中查看相关动态。","toast_failed": "更新通知设置失败",- "routes": {- "action": {- "label": "需要处理",- "description": "计入未读,可弹出系统通知"+ "groups": {+ "assignments": {+ "label": "分配",+ "description": "你被分配或取消分配某个任务时"},- "activity": {- "label": "动态",- "description": "安静记录,不计未读"+ "status_changes": {+ "label": "状态变更",+ "description": "你订阅的任务状态变化时(例如 todo、in_progress、done)"},- "muted": {- "label": "关闭",- "description": "不进收件箱,在任务里仍能看到"- }- },- "kinds": {- "assigned": {- "label": "分配给我",- "description": "任务分配给你时"+ "comments": {+ "label": "评论",+ "description": "你订阅的任务有新评论时"},"mentions": {"label": "提及","description": "有人 @ 你时,包括 @all 和 @squad"},- "comments_without_mentions": {- "label": "未 @ 任何人的评论",- "description": "有人在你订阅的任务里评论,且没有 @ 任何人时"- },- "agent_failures": {- "label": "智能体出错",- "description": "智能体运行失败或被阻塞、需要你介入时"- },- "status_changes": {- "label": "状态变更",- "description": "你订阅的任务状态变化时"- },- "assignee_changes": {- "label": "负责人变更",- "description": "任务换了负责人,或你被取消分配时"- },"updates": {- "label": "优先级与日期",- "description": "优先级、开始日期或截止日期变化时"+ "label": "优先级与截止日期",+ "description": "你订阅的任务优先级或截止日期变更时"},- "comments_mentioning_others": {- "label": "@ 了其他人的评论",- "description": "你订阅的任务里的评论 @ 了其他成员或智能体、但没有 @ 你时"+ "agent_activity": {+ "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 7df568b962..4b80c5d00a 100644--- a/packages/views/locales/zh-Hant/inbox.json+++ b/packages/views/locales/zh-Hant/inbox.json@@ -3,14 +3,6 @@"title": "收件箱","back": "收件箱"},- "sections": {- "action": "需要處理",- "activity": "動態",- "action_empty": "需要你處理的都處理完了",- "activity_empty": "暫無動態",- "activity_waiting_other": "動態裡還有 {{count}} 條更新,隨時可以看。",- "open_activity": "查看動態"- },"menu": {"mark_all_read": "全部標為已讀","archive_all": "歸檔全部",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex d99a190564..ae04bef93d 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,61 +647,38 @@"toast_profile_failed": "更新資料失敗"},"notifications": {- "title": "通知去向",- "description": "變更只影響之後的新通知。",- "reset": "恢復預設",+ "title": "收件箱通知",+ "description": "關閉通知後,仍可在任務中檢視相關動態。","toast_failed": "更新通知設定失敗",- "routes": {- "action": {- "label": "需要處理",- "description": "計入未讀,可彈出系統通知"+ "groups": {+ "assignments": {+ "label": "分配",+ "description": "你被分配或取消分配某個任務時"},- "activity": {- "label": "動態",- "description": "安靜記錄,不計未讀"+ "status_changes": {+ "label": "狀態變更",+ "description": "你訂閱的任務狀態變化時(例如 todo、in_progress、done)"},- "muted": {- "label": "關閉",- "description": "不進收件箱,在任務裡仍能看到"- }- },- "kinds": {- "assigned": {- "label": "分配給我",- "description": "任務分配給你時"+ "comments": {+ "label": "評論",+ "description": "你訂閱的任務有新評論時"},"mentions": {"label": "提及","description": "有人 @ 你時,包括 @all 和 @squad"},- "comments_without_mentions": {- "label": "未 @ 任何人的評論",- "description": "有人在你訂閱的任務裡評論,且沒有 @ 任何人時"- },- "agent_failures": {- "label": "AI 代理出錯",- "description": "AI 代理執行失敗或被阻塞、需要你介入時"- },- "status_changes": {- "label": "狀態變更",- "description": "你訂閱的任務狀態變化時"- },- "assignee_changes": {- "label": "負責人變更",- "description": "任務換了負責人,或你被取消分配時"- },"updates": {- "label": "優先順序與日期",- "description": "優先順序、開始日期或截止日期變化時"+ "label": "優先順序與截止日期",+ "description": "你訂閱的任務優先順序或截止日期變更時"},- "comments_mentioning_others": {- "label": "@ 了其他人的評論",- "description": "你訂閱的任務裡的評論 @ 了其他成員或 AI 代理、但沒有 @ 你時"+ "agent_activity": {+ "label": "AI 代理活動",+ "description": "AI 代理執行失敗時"}},"system": {"title": "系統通知",- "label": "Multica 在背景時,為「需要處理」的通知彈出系統通知"+ "label": "Multica 在背景時顯示系統通知"},"browser": {"label": "瀏覽器通知",@@ -1169,11 +1146,11 @@"scan_error_generate_failed": "未能從企業微信取得 QR 碼,請稍後再試。","scan_error_integration_unconfigured": "此伺服器未啟用掃碼安裝。","scan_error_installation_conflict": "這個機器人已在別處連線。請先在那裡斷開,再重新掃碼。",- "scan_error_bind_failed": "機器人已在企業微信裡建立,但沒能連到這個AI 代理。請在企業微信裡刪掉它,再重新掃碼。",+ "scan_error_bind_failed": "機器人已在企業微信裡建立,但沒能連到這個智慧體。請在企業微信裡刪掉它,再重新掃碼。","scan_error_wecom_protocol_error": "企業微信回傳了異常回應。","scan_error_internal_error": "發生問題,請再試一次。","scan_error_session_lost": "此安裝工作階段已失效,請重新取得 QR 碼。",- "scan_error_already_connected": "這個AI 代理已經連線了企業微信機器人,請先斷開。",+ "scan_error_already_connected": "這個智慧體已經連線了企業微信機器人,請先斷開。","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.tsxdeleted file mode 100644index 39897d369a..0000000000--- a/packages/views/settings/components/notifications-tab.test.tsx+++ /dev/null@@ -1,116 +0,0 @@-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.comments_without_mentions.label)).toHaveTextContent(routes.action.label);- expect(select(kinds.comments_mentioning_others.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.comments_without_mentions.label)).toHaveTextContent(routes.muted.label);- expect(select(kinds.comments_mentioning_others.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.comments_without_mentions.label));- await user.click(await screen.findByRole("option", { name: new RegExp(`^${routes.action.label}`) }));-- await waitFor(() =>- expect(mutate).toHaveBeenCalledWith({ comments_mentioning_others: "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 f7911fe2b4..bab94ad457 100644--- a/packages/views/settings/components/notifications-tab.tsx+++ b/packages/views/settings/components/notifications-tab.tsx@@ -4,24 +4,7 @@ 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 {- 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 type { NotificationGroupKey, NotificationPreferences } from "@multica/core/types";import { Switch } from "@multica/ui/components/ui/switch";import { toast } from "sonner";import { useT } from "../../i18n";@@ -33,19 +16,17 @@ import {SettingsTab,} from "./settings-layout";-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" />;-}+// 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];export function NotificationsTab() {const { t } = useT("settings");@@ -55,8 +36,16 @@ export function NotificationsTab() {const preferences = data?.preferences ?? {};- const save = (next: NotificationPreferences) => {- mutation.mutate(next, {+ 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, {onError: (err) =>toast.error(err instanceof Error && err.message@@ -66,58 +55,6 @@ 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 (@@ -126,19 +63,26 @@ 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>{NOTIFICATION_ROUTE_KINDS.map(routeSelect)}</SettingsCard>+ <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></SettingsSection><SettingsSection@@ -152,12 +96,7 @@ export function NotificationsTab() {<Switchchecked={systemEnabled}aria-label={t(($) => $.notifications.system.label)}- onCheckedChange={(checked) => {- const next: NotificationPreferences = { ...preferences };- if (checked) delete next.system_notifications;- else next.system_notifications = "muted";- save(next);- }}+ onCheckedChange={(checked) => handleToggle("system_notifications", checked)}/></SettingsRow></SettingsCard>diff --git a/packages/views/settings/components/settings-page.test.tsx b/packages/views/settings/components/settings-page.test.tsxindex 5fbd8f19c0..fed899b782 100644--- a/packages/views/settings/components/settings-page.test.tsx+++ b/packages/views/settings/components/settings-page.test.tsx@@ -189,7 +189,6 @@ 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" },@@ -522,7 +521,7 @@ describe("SettingsPage search for the browser notifications row", () => {search("notifi");const results = screen.getByRole("listbox", { name: "Search settings" });expect(- within(results).getByRole("option", { name: /Send a system notification/ }),+ within(results).getByRole("option", { name: /Show system notifications/ }),).toBeInTheDocument();});});diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsxindex d81bfd5c07..e80bf23145 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),- Inbox,+ Bell,<NotificationsTab />,),entry(diff --git a/packages/views/settings/components/use-settings-search-index.ts b/packages/views/settings/components/use-settings-search-index.tsindex 98b0d05a06..61ea6d7a1d 100644--- a/packages/views/settings/components/use-settings-search-index.ts+++ b/packages/views/settings/components/use-settings-search-index.ts@@ -1,12 +1,20 @@"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";import { browserNotificationSettingAvailable } from "./browser-notification-setting";+const NOTIFICATION_GROUPS = [+ "assignments",+ "status_changes",+ "comments",+ "mentions",+ "updates",+ "agent_activity",+] as const;+export interface SettingsSearchPage {value: string;label: string;@@ -83,17 +91,11 @@ export function useSettingsSearchIndex(title: t(($) => $.preferences.issue_fields_title),description: t(($) => $.issue.description),},- {- tab: "notifications",- anchor: "inbox",- title: t(($) => $.notifications.title),- description: t(($) => $.notifications.description),- },- ...NOTIFICATION_ROUTE_KINDS.map(({ key }) => ({+ ...NOTIFICATION_GROUPS.map((group) => ({tab: "notifications",- anchor: key,- title: t(($) => $.notifications.kinds[key].label),- description: t(($) => $.notifications.kinds[key].description),+ anchor: group,+ title: t(($) => $.notifications.groups[group].label),+ description: t(($) => $.notifications.groups[group].description),})),{tab: "notifications",diff --git a/server/cmd/server/integration_test.go b/server/cmd/server/integration_test.goindex 13eceef1e9..70fb7f7590 100644--- a/server/cmd/server/integration_test.go+++ b/server/cmd/server/integration_test.go@@ -1394,13 +1394,12 @@ func TestInboxUnreadSummaryDedupesByIssue(t *testing.T) {})// Older sibling stays unread; newer sibling is read (the one "opening the- // issue" would have marked read). Both are action rows: activity never- // takes part in the unread count.+ // issue" would have marked read).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, 'mentioned', 'newer', $3, true, now())+ ($1, 'member', $2, 'new_comment', 'older', $3, false, now() - interval '1 hour'),+ ($1, 'member', $2, 'status_changed', '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_comment_audience_test.go b/server/cmd/server/notification_comment_audience_test.godeleted file mode 100644index 465a14882c..0000000000--- a/server/cmd/server/notification_comment_audience_test.go+++ /dev/null@@ -1,210 +0,0 @@-package main--import (- "context"- "fmt"- "strings"- "testing"-- "github.com/google/uuid"- "github.com/multica-ai/multica/server/internal/events"- "github.com/multica-ai/multica/server/internal/handler"- "github.com/multica-ai/multica/server/internal/inbox"- "github.com/multica-ai/multica/server/internal/util"- db "github.com/multica-ai/multica/server/pkg/db/generated"- "github.com/multica-ai/multica/server/pkg/protocol"-)--// TestNotification_CommentRoutedByAudience covers MUL-8541: a comment lands in-// Needs action for a subscriber it @mentions or when it @mentions nobody, and-// in Activity for a subscriber it does not @mention while it @mentions someone-// else. Who wrote the comment does not matter, so every case is posted by an-// agent, the author whose replies used to default to Activity.-func TestNotification_CommentRoutedByAudience(t *testing.T) {- ctx := context.Background()- queries := db.New(testPool)- bus := newNotificationBus(t, queries)-- var agentID string- if err := testPool.QueryRow(ctx,- `SELECT id::text FROM agent WHERE workspace_id = $1 ORDER BY created_at ASC LIMIT 1`,- testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("load agent: %v", err)- }-- suffix := uuid.NewString()[:8]- member := func(name string) string {- email := fmt.Sprintf("notif-audience-%s-%[email protected]", name, suffix)- id := createNotificationMember(t, email)- t.Cleanup(func() { cleanupTestUser(t, email) })- return id- }- target := member("target")- bystander := member("bystander")- optedIn := member("opted-in")- if _, err := testPool.Exec(ctx, `- INSERT INTO notification_preference (workspace_id, user_id, preferences)- VALUES ($1, $2, '{"comments_mentioning_others":"action"}'::jsonb)- `, testWorkspaceID, optedIn); err != nil {- t.Fatalf("seed preference: %v", err)- }-- // A squad with target as its only human member.- var squadID string- if err := testPool.QueryRow(ctx, `- INSERT INTO squad (workspace_id, name, description, leader_id, creator_id)- VALUES ($1, $2, '', $3, $4) RETURNING id- `, testWorkspaceID, "Audience squad "+suffix, agentID, testUserID).Scan(&squadID); err != nil {- t.Fatalf("create squad: %v", err)- }- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM squad WHERE id = $1`, squadID) })- if _, err := testPool.Exec(ctx, `- INSERT INTO squad_member (squad_id, member_type, member_id) VALUES ($1, 'member', $2), ($1, 'agent', $3)- `, squadID, target, agentID); err != nil {- t.Fatalf("add squad members: %v", err)- }-- mentionMember := func(id string) string { return fmt.Sprintf("[@M](mention://member/%s)", id) }- cases := []struct {- name string- content string- // want is the new_comment section per subscriber.- want map[string]string- // mentioned lists who also gets a "mentioned" row.- mentioned []string- }{- {- name: "nobody mentioned",- content: "Done, the PR is up.",- want: map[string]string{target: "action", bystander: "action", optedIn: "action"},- },- {- name: "issue link is not a mention",- content: "Related to [MUL-1](mention://issue/" + uuid.NewString() + ").",- want: map[string]string{target: "action", bystander: "action", optedIn: "action"},- },- {- name: "member mentioned",- content: mentionMember(target) + " can you confirm?",- want: map[string]string{target: "action", bystander: "activity", optedIn: "action"},- mentioned: []string{target},- },- {- // The mention parser accepts these forms; they must still reach- // the member they name.- name: "member mentioned in uppercase",- content: fmt.Sprintf("[@M](mention://member/%s) can you confirm?", strings.ToUpper(target)),- want: map[string]string{target: "action", bystander: "activity", optedIn: "action"},- mentioned: []string{target},- },- {- name: "member mentioned without hyphens",- content: fmt.Sprintf("[@M](mention://member/%s) can you confirm?", strings.ReplaceAll(target, "-", "")),- want: map[string]string{target: "action", bystander: "activity", optedIn: "action"},- mentioned: []string{target},- },- {- name: "only an agent mentioned",- content: fmt.Sprintf("[@A](mention://agent/%s) please take this", agentID),- want: map[string]string{target: "activity", bystander: "activity", optedIn: "action"},- },- {- name: "recipient and others mentioned",- content: mentionMember(target) + fmt.Sprintf(" and [@A](mention://agent/%s)", agentID),- want: map[string]string{target: "action", bystander: "activity", optedIn: "action"},- mentioned: []string{target},- },- {- name: "squad reaches its human members",- content: fmt.Sprintf("[@S](mention://squad/%s) over to you", squadID),- want: map[string]string{target: "action", bystander: "activity", optedIn: "action"},- mentioned: []string{target},- },- {- name: "@all reaches everyone",- content: "[@all](mention://all/all) heads up",- want: map[string]string{target: "action", bystander: "action", optedIn: "action"},- mentioned: []string{target, bystander, optedIn},- },- }-- for _, c := range cases {- t.Run(c.name, func(t *testing.T) {- issueID := createTestIssue(t, testWorkspaceID, testUserID)- t.Cleanup(func() {- cleanupInboxForIssue(t, issueID)- cleanupTestIssue(t, issueID)- })- for _, id := range []string{target, bystander, optedIn} {- addTestSubscriber(t, issueID, "member", id, "commenter")- }-- bus.Publish(events.Event{- Type: protocol.EventCommentCreated,- WorkspaceID: testWorkspaceID,- ActorType: "agent",- ActorID: agentID,- Payload: map[string]any{- "comment": handler.CommentResponse{- ID: uuid.NewString(),- IssueID: issueID,- AuthorType: "agent",- AuthorID: agentID,- Content: c.content,- Type: "comment",- },- "issue_title": "audience test issue",- "issue_status": "todo",- },- })-- mentioned := map[string]bool{}- for _, id := range c.mentioned {- mentioned[id] = true- }- for id, want := range c.want {- var comment, mention int- for _, item := range inboxItemsForRecipient(t, queries, id) {- if util.UUIDToString(item.IssueID) != issueID {- continue- }- switch item.Type {- case "new_comment":- comment++- if !item.Section.Valid || item.Section.String != want {- t.Errorf("%s: new_comment section = %+v, want %q", id, item.Section, want)- }- case "mentioned":- mention++- }- }- if comment != 1 {- t.Errorf("%s: new_comment rows = %d, want 1", id, comment)- }- if wantMention := map[bool]int{true: 1}[mentioned[id]]; mention != wantMention {- t.Errorf("%s: mentioned rows = %d, want %d", id, mention, wantMention)- }- }- })- }-}--// TestCommentAudienceCanonicalizesMemberIDs guards the comparison behind-// commentAudience: subscriber IDs are canonical (lowercase, hyphenated), and a-// member mention written in another accepted form must match them, so the-// comment follows the member's mentions choice instead of landing in-// Activity as if it were written to someone else.-func TestCommentAudienceCanonicalizesMemberIDs(t *testing.T) {- const member = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"- for _, id := range []string{member, strings.ToUpper(member), strings.ReplaceAll(member, "-", "")} {- mentioned := expandMentionedMembers(context.Background(), nil, "",- parseMentions(fmt.Sprintf("[@M](mention://member/%s) please look", id)))- if got := mentioned.commentAudience(member); got != inbox.CommentToRecipient {- t.Errorf("mention of %q: audience = %v, want CommentToRecipient", id, got)- }- section, ok := inbox.RouteComment(map[string]string{"mentions": "muted"}, mentioned.commentAudience(member))- if ok {- t.Errorf("mention of %q with mentions muted: route = (%q, delivered), want muted", id, section)- }- }-}diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.goindex a51097c2b6..e5fcccee68 100644--- a/server/cmd/server/notification_listeners.go+++ b/server/cmd/server/notification_listeners.go@@ -170,6 +170,34 @@ 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(@@ -263,18 +291,6 @@ func archiveStaleTaskFailedInbox("row_count", len(rows), "recipient_count", len(counts))}-// subscriberRoute decides which Inbox section a notification lands in for one-// member subscriber, given their preferences. ok is false when they muted it.-type subscriberRoute func(memberID string, prefs map[string]string) (section string, ok bool)--// routeByType routes on the notification type alone, which is enough for-// every kind except comments.-func routeByType(notifType string) subscriberRoute {- return func(_ string, prefs map[string]string) (string, bool) {- return inbox.Route(prefs, notifType)- }-}-// notifySubscribers queries the subscriber table for an issue, excludes the// actor and any extra IDs, and creates inbox items for each remaining member// subscriber. Publishes an inbox:new event for each notification.@@ -295,33 +311,10 @@ func notifySubscribers(title string,body string,details []byte,-) {- notifySubscribersRouted(ctx, queries, bus, issueID, issueStatus, workspaceID, e, exclude,- notifType, severity, title, body, details, routeByType(notifType))-}--// notifySubscribersRouted is notifySubscribers with a caller-chosen route per-// subscriber. Comments use it: where a comment lands depends on whether it-// @mentions the subscriber, someone else, or nobody.-func notifySubscribersRouted(- ctx context.Context,- queries *db.Queries,- bus *events.Bus,- issueID string,- issueStatus string,- workspaceID string,- e events.Event,- exclude map[string]bool,- notifType string,- severity string,- title string,- body string,- details []byte,- route subscriberRoute,) {notified, tierSuppressed := notifyIssueSubscribers(ctx, queries, bus,issueID, issueID, issueStatus, workspaceID, e, exclude,- notifType, severity, title, body, details, route)+ notifType, severity, title, body, details)// Only a small allowlist of event types bubbles to parent subscribers.if !parentBubbleNotifTypes[notifType] {@@ -363,7 +356,7 @@ func notifySubscribersRouted(parentID := util.UUIDToString(issue.ParentIssueID)notifyIssueSubscribers(ctx, queries, bus,parentID, issueID, issueStatus, workspaceID, e, parentExclude,- notifType, severity, title, body, details, route)+ notifType, severity, title, body, details)}// notifyIssueSubscribers sends inbox notifications to subscribers of@@ -390,7 +383,6 @@ func notifyIssueSubscribers(title string,body string,details []byte,- route subscriberRoute,) (map[string]bool, map[string]bool) {notified := map[string]bool{}tierSuppressed := map[string]bool{}@@ -444,9 +436,8 @@ func notifyIssueSubscribers(continue}- // The recipient decides which Inbox section this lands in, or mutes it.- section, routed := route(subID, userPrefs[subID])- if !routed {+ // Skip if this notification type is muted by the user+ if prefs, ok := userPrefs[subID]; ok && isNotifMuted(prefs, notifType) {continue}@@ -470,7 +461,6 @@ 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",@@ -519,13 +509,10 @@ func notifyDirect(return}- // Member recipients route the notification through their preferences.- section := inbox.DefaultSection(notifType)+ // Check notification preferences for member recipients.if recipientType == "member" {prefs := loadUserPrefs(ctx, queries, workspaceID, []string{recipientID})- var routed bool- section, routed = inbox.Route(prefs[recipientID], notifType)- if !routed {+ if p, ok := prefs[recipientID]; ok && isNotifMuted(p, notifType) {return}}@@ -543,7 +530,6 @@ 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",@@ -565,134 +551,74 @@ func notifyDirect(})}-// mentionedMembers is the set of workspace members a piece of content-// @mentions: by name, through a squad they belong to, or through @all.-type mentionedMembers struct {- ids map[string]bool- // addressesPeople is true when the content @mentions anyone at all — a- // member, an agent, a squad or @all. Issue links do not count.- addressesPeople bool- // complete is false when a squad or @all could not be expanded, so a- // member missing from ids may still have been mentioned.- complete bool-}--// expandMentionedMembers resolves mentions to the members they reach. Agent-// members of a squad are reached via comment-trigger / assignment paths, not-// the mention-inbox path, so only member-typed squad members are included.-func expandMentionedMembers(ctx context.Context, queries *db.Queries, workspaceID string, mentions []mention) mentionedMembers {- out := mentionedMembers{ids: map[string]bool{}, complete: true}+// notifyMentionedMembers creates inbox items for each @mentioned member,+// excluding the actor and any IDs in the skip set. When an @all mention is+// present, all workspace members are notified (excluding agents).+func notifyMentionedMembers(+ bus *events.Bus,+ queries *db.Queries,+ e events.Event,+ mentions []mention,+ issueID string,+ issueTitle string,+ issueStatus string,+ title string,+ skip map[string]bool,+ details []byte,+) {+ // Collect the set of member IDs to notify.+ recipientIDs := map[string]bool{}hasAll := false- var squadIDs []pgtype.UUID+ var squadIDs []stringfor _, m := range mentions {- switch m.Type {- case "all":+ if m.Type == "all" {hasAll = true- out.addressesPeople = true- case "member":- memberUUID, err := util.ParseUUID(m.ID)- if err != nil {- continue- }- // Keyed by the canonical form, which is how subscriber and actor- // IDs read: the parser also accepts uppercase or unhyphenated- // UUIDs, and those must still match the member they name.- out.ids[util.UUIDToString(memberUUID)] = true- out.addressesPeople = true- case "agent":+ continue+ }+ if m.Type == "member" {if _, err := util.ParseUUID(m.ID); err != nil {continue}- out.addressesPeople = true- case "squad":- squadUUID, err := util.ParseUUID(m.ID)- if err != nil {- continue- }- squadIDs = append(squadIDs, squadUUID)- out.addressesPeople = true+ recipientIDs[m.ID] = true+ }+ if m.Type == "squad" {+ squadIDs = append(squadIDs, m.ID)}}- for _, squadUUID := range squadIDs {- members, err := queries.ListSquadMembers(ctx, squadUUID)+ // Expand each @squad mention to its human members. Agent members of a+ // squad are reached via comment-trigger / assignment paths, not the+ // mention-inbox path, so we only seed member-typed recipients here.+ for _, sid := range squadIDs {+ squadUUID, err := util.ParseUUID(sid)if err != nil {- slog.Error("failed to list squad members for @squad mention",- "squad_id", util.UUIDToString(squadUUID), "error", err)- out.complete = false+ continue+ }+ members, err := queries.ListSquadMembers(context.Background(), squadUUID)+ if err != nil {+ slog.Error("failed to list squad members for @squad mention", "squad_id", sid, "error", err)continue}for _, sm := range members {if sm.MemberType == "member" {- out.ids[util.UUIDToString(sm.MemberID)] = true+ recipientIDs[util.UUIDToString(sm.MemberID)] = true}}}+ // If @all is present, expand to all workspace members.if hasAll {- members, err := queries.ListMembers(ctx, parseUUID(workspaceID))+ members, err := queries.ListMembers(context.Background(), parseUUID(e.WorkspaceID))if err != nil {- slog.Error("failed to list members for @all mention", "workspace_id", workspaceID, "error", err)- out.complete = false+ slog.Error("failed to list members for @all mention", "workspace_id", e.WorkspaceID, "error", err)} else {for _, m := range members {- out.ids[util.UUIDToString(m.UserID)] = true+ recipientIDs[util.UUIDToString(m.UserID)] = true}}}- return out-}--// commentAudience is who a comment is written to, as one subscriber sees it-// (see inbox.CommentAudience). When a squad or @all could not be expanded, a-// subscriber the comment may have reached is treated as if nobody was-// mentioned: a comment meant for them then still waits in Needs action-// instead of slipping into Activity.-func (m mentionedMembers) commentAudience(memberID string) inbox.CommentAudience {- switch {- case m.ids[memberID]:- return inbox.CommentToRecipient- case !m.addressesPeople || !m.complete:- return inbox.CommentToNobody- default:- return inbox.CommentToOthers- }-}--// notifyMentionedMembers creates inbox items for each @mentioned member,-// excluding the actor and any IDs in the skip set. When an @all mention is-// present, all workspace members are notified (excluding agents).-func notifyMentionedMembers(- bus *events.Bus,- queries *db.Queries,- e events.Event,- mentions []mention,- issueID string,- issueTitle string,- issueStatus string,- title string,- skip map[string]bool,- details []byte,-) {- mentioned := expandMentionedMembers(context.Background(), queries, e.WorkspaceID, mentions)- notifyMentionedMemberIDs(bus, queries, e, mentioned.ids, issueID, issueStatus, title, skip, details)-}--// notifyMentionedMemberIDs creates a "mentioned" inbox item for each member in-// recipientIDs, excluding the actor and any IDs in the skip set.-func notifyMentionedMemberIDs(- bus *events.Bus,- queries *db.Queries,- e events.Event,- recipientIDs map[string]bool,- issueID string,- issueStatus string,- title string,- skip map[string]bool,- details []byte,-) {// Batch-load notification preferences for all mention recipients.var mentionUserIDs []stringfor id := range recipientIDs {@@ -706,10 +632,10 @@ func notifyMentionedMemberIDs(if id == e.ActorID || skip[id] {continue}- // 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")- if !routed {+ // 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") {continue}item, inserted, err := inbox.CreateIfEligible(context.Background(), queries, db.CreateInboxItemParams{@@ -724,7 +650,6 @@ func notifyMentionedMemberIDs(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)@@ -1028,22 +953,16 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {})}- // Where a comment lands depends on who it is written to, not who wrote- // it: one that @mentions the subscriber or nobody waits on them, one- // that @mentions only others is activity for them.- mentioned := expandMentionedMembers(ctx, queries, e.WorkspaceID, parseMentions(commentContent))- notifySubscribersRouted(ctx, queries, bus, issueID, issueStatus, e.WorkspaceID, e,+ notifySubscribers(ctx, queries, bus, issueID, issueStatus, e.WorkspaceID, e,nil, "new_comment", "info",issueTitle, commentContent,- commentDetails,- func(memberID string, prefs map[string]string) (string, bool) {- return inbox.RouteComment(prefs, mentioned.commentAudience(memberID))- })+ commentDetails)// Notify @mentions in comment content.- if len(mentioned.ids) > 0 {+ mentions := parseMentions(commentContent)+ if len(mentions) > 0 {skip := map[string]bool{e.ActorID: true}- notifyMentionedMemberIDs(bus, queries, e, mentioned.ids, issueID, issueStatus,+ notifyMentionedMembers(bus, queries, e, mentions, issueID, issueTitle, issueStatus,issueTitle, skip, commentDetails)}})@@ -1171,7 +1090,6 @@ 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),"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 f6fe04ae3e..465048c12b 100644--- a/server/cmd/server/notification_listeners_test.go+++ b/server/cmd/server/notification_listeners_test.go@@ -325,88 +325,6 @@ 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.gonew file mode 100644index 0000000000..d50a6673fb--- /dev/null+++ b/server/cmd/server/notification_mute_group_test.go@@ -0,0 +1,47 @@+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 228b06b8f5..f50159461f 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2564,7 +2564,6 @@ 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 2ccb852532..15b0c756c9 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -8,7 +8,6 @@ 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"@@ -21,7 +20,6 @@ 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"`@@ -43,7 +41,6 @@ func inboxToResponse(i db.InboxItem) InboxItemResponse {RecipientID: uuidToString(i.RecipientID),Type: i.Type,Severity: i.Severity,- Section: inbox.ItemSection(i.Section, i.Type),IssueID: uuidToPtr(i.IssueID),Title: i.Title,Body: textToPtr(i.Body),@@ -120,7 +117,6 @@ func inboxRowToResponse(r db.ListInboxItemsRow) InboxItemResponse {RecipientID: uuidToString(r.RecipientID),Type: r.Type,Severity: r.Severity,- Section: inbox.ItemSection(r.Section, r.Type),IssueID: uuidToPtr(r.IssueID),Title: r.Title,Body: inboxListBody(r.Type, r.IssueID, r.Body),@@ -243,27 +239,6 @@ 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)}@@ -280,14 +255,7 @@ func (h *Handler) MarkInboxUnread(w http.ResponseWriter, r *http.Request) {if !ok {return}- // 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) == inbox.SectionActivity {- params.Section = inbox.SectionText(inbox.SectionAction)- }- item, err := h.Queries.MarkInboxUnread(r.Context(), params)+ item, err := h.Queries.MarkInboxUnread(r.Context(), prev.ID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to mark unread")return@@ -316,27 +284,14 @@ func (h *Handler) ArchiveInboxItem(w http.ResponseWriter, r *http.Request) {return}- // 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)+ // Archive all sibling inbox items for the same issue (issue-level archive)if item.IssueID.Valid {- 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,- })- } else {- h.Queries.ArchiveInboxByIssue(r.Context(), db.ArchiveInboxByIssueParams{- WorkspaceID: item.WorkspaceID,- RecipientType: item.RecipientType,- RecipientID: item.RecipientID,- IssueID: item.IssueID,- })- }+ h.Queries.ArchiveInboxByIssue(r.Context(), db.ArchiveInboxByIssueParams{+ WorkspaceID: item.WorkspaceID,+ RecipientType: item.RecipientType,+ RecipientID: item.RecipientID,+ IssueID: item.IssueID,+ })}userID := requestUserID(r)@@ -344,7 +299,6 @@ 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),})@@ -409,7 +363,6 @@ func (h *Handler) CountUnreadInbox(w http.ResponseWriter, r *http.Request) {WorkspaceID: wsUUID,RecipientType: "member",RecipientID: parseUUID(userID),- ActivityTypes: inbox.ActivityTypes,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to count unread inbox")@@ -438,10 +391,7 @@ func (h *Handler) UnreadInboxSummary(w http.ResponseWriter, r *http.Request) {return}- rows, err := h.Queries.CountUnreadInboxByWorkspace(r.Context(), db.CountUnreadInboxByWorkspaceParams{- RecipientID: parseUUID(userID),- ActivityTypes: inbox.ActivityTypes,- })+ rows, err := h.Queries.CountUnreadInboxByWorkspace(r.Context(), parseUUID(userID))if err != nil {writeError(w, http.StatusInternalServerError, "failed to summarize unread inbox")return@@ -487,39 +437,6 @@ 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 {@@ -561,9 +478,8 @@ func (h *Handler) ArchiveAllReadInbox(w http.ResponseWriter, r *http.Request) {}count, err := h.Queries.ArchiveAllReadInbox(r.Context(), db.ArchiveAllReadInboxParams{- WorkspaceID: wsUUID,- RecipientID: parseUUID(userID),- ActivityTypes: inbox.ActivityTypes,+ WorkspaceID: wsUUID,+ RecipientID: parseUUID(userID),})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 43118f0409..bdf33694bb 100644--- a/server/internal/handler/inbox_archive.go+++ b/server/internal/handler/inbox_archive.go@@ -12,7 +12,6 @@ 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")@@ -97,7 +96,6 @@ 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,}limit := 50if raw := r.URL.Query().Get("limit"); raw != "" {@@ -178,9 +176,6 @@ 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 = inbox.ActivityTypesrows, 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.godeleted file mode 100644index ef6445500f..0000000000--- a/server/internal/handler/inbox_section_test.go+++ /dev/null@@ -1,397 +0,0 @@-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'")- // Rows from before sections store none; a comment among them is action- // whoever wrote it, since the row does not record whom it @mentioned.- 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'")- // A comment routed to activity (it @mentioned someone else) keeps that.- f.routed(issueID, "new_comment", "member", "comment to others", "activity", "now() - interval '30 seconds'")-- 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": "action",- "member comment": "action",- "comment to others": "activity",- }- 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.routed(quietIssue, "new_comment", "agent", "quiet comment", "activity", "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 comment without a stored section is action, whoever wrote it.- commentIssue := f.issue("Agent comment")- f.item(commentIssue, "new_comment", "agent", "agent 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 + agent 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.routed(issueID, "new_comment", "agent", "agent comment", "activity", "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 bab505712d..898c649f00 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": "issue_assigned",+ "type": "status_changed","severity": "info","issue_id": issueID,"title": title,diff --git a/server/internal/handler/notification_preference.go b/server/internal/handler/notification_preference.goindex 5c37625fd0..afaed3d08a 100644--- a/server/internal/handler/notification_preference.go+++ b/server/internal/handler/notification_preference.go@@ -7,7 +7,6 @@ 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")@@ -34,27 +33,6 @@ 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 {@@ -107,12 +85,11 @@ func decodeNotificationPreferenceRequest(w http.ResponseWriter, r *http.Request)}for k, v := range req.Preferences {- validKey, validValue := validNotifPreference(k, v)- if !validKey {+ if !validNotifGroups[k] {writeError(w, http.StatusBadRequest, "invalid preference group: "+k)return nil, false}- if !validValue {+ if !validNotifValues[v] {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 f2f0587f85..656ddd670e 100644--- a/server/internal/handler/notification_preference_test.go+++ b/server/internal/handler/notification_preference_test.go@@ -176,72 +176,3 @@ 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",- "comments_mentioning_others": "muted",- "comments_without_mentions": "activity",- "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",- "comments_mentioning_others": "muted",- "comments_without_mentions": "activity",- "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"},- // The author-based comment keys were replaced by audience-based ones.- {"member_comments": "action"},- {"agent_comments": "muted"},- } {- 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.godeleted file mode 100644index b26ff425af..0000000000--- a/server/internal/inbox/routing.go+++ /dev/null@@ -1,148 +0,0 @@-package inbox--// 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"-)--// Preference keys of the routable kinds a comment can fall under.-const (- RouteKeyMentions = "mentions"- RouteKeyCommentsWithoutMentions = "comments_without_mentions"- RouteKeyCommentsMentioningOthers = "comments_mentioning_others"-)--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: RouteKeyMentions, Default: SectionAction},- {Key: RouteKeyCommentsWithoutMentions, 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: RouteKeyCommentsMentioningOthers, 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-}()--// commentToRecipientKind routes a comment that @mentions the recipient. It-// follows the recipient's mentions choice, since the same comment also sends-// them a "mentioned" notification and the two should land together. Unlike-// the "mentioned" kind it keeps the legacy comments mute: before routing, a-// recipient who muted comments got only the mention for such a comment.-var commentToRecipientKind = routeKind{Key: RouteKeyMentions, Default: SectionAction, Legacy: "comments"}--// CommentAudience is who a comment is written to, as one recipient sees it.-// Only people count as an audience: @member, @agent, @squad and @all. Issue-// and project links do not.-type CommentAudience int--const (- // CommentToNobody: the comment @mentions nobody. It is usually a reply- // to whoever is following the conversation, so it waits on them.- CommentToNobody CommentAudience = iota- // CommentToRecipient: the comment @mentions the recipient, directly,- // through a squad they belong to, or through @all. This wins when the- // comment also @mentions others.- CommentToRecipient- // CommentToOthers: the comment @mentions someone, and not the recipient.- CommentToOthers-)--// 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. A new_comment routed-// without an audience is treated as written to nobody; RouteComment is the-// audience-aware entry point.-func RouteKindKey(notifType string) string {- switch notifType {- case "issue_assigned":- return "assigned"- case "mentioned":- return RouteKeyMentions- case "new_comment":- return RouteKeyCommentsWithoutMentions- 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) (section string, ok bool) {- kind, routable := routeKindByKey[RouteKindKey(notifType)]- if !routable {- return DefaultSection(notifType), true- }- return routeTo(prefs, kind)-}--// RouteComment resolves where a new_comment goes for a recipient, given who-// the comment is written to. Who wrote it does not matter: a person's comment-// and an agent's reply are routed the same way. ok is false when the-// recipient muted it.-func RouteComment(prefs map[string]string, audience CommentAudience) (section string, ok bool) {- switch audience {- case CommentToRecipient:- return routeTo(prefs, commentToRecipientKind)- case CommentToOthers:- return routeTo(prefs, routeKindByKey[RouteKeyCommentsMentioningOthers])- default:- return routeTo(prefs, routeKindByKey[RouteKeyCommentsWithoutMentions])- }-}--func routeTo(prefs map[string]string, kind routeKind) (section string, ok bool) {- 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.godeleted file mode 100644index 863e51615a..0000000000--- a/server/internal/inbox/routing_test.go+++ /dev/null@@ -1,141 +0,0 @@-package inbox--import (- "testing"-- "github.com/jackc/pgx/v5/pgtype"-)--func TestRoute(t *testing.T) {- muted := ""-- cases := []struct {- name string- prefs map[string]string- notifType string- want string // muted means not delivered- }{- // Defaults match DefaultSection, so an untouched account sees no change.- {"default assigned", nil, "issue_assigned", SectionAction},- {"default mention", nil, "mentioned", SectionAction},- {"default comment without audience", nil, "new_comment", SectionAction},- {"default agent failure", nil, "task_failed", SectionAction},- {"default status", nil, "status_changed", SectionActivity},- {"default assignee change", nil, "unassigned", SectionActivity},- {"default update", nil, "due_date_changed", SectionActivity},- {"explicit all is the default", map[string]string{"status_changes": "all"}, "status_changed", SectionActivity},-- // The recipient's choice wins.- {"status routed to action", map[string]string{"status_changes": "action"}, "status_changed", SectionAction},- {"mentions routed to activity", map[string]string{"mentions": "activity"}, "mentioned", SectionActivity},- {"updates muted", map[string]string{"updates": "muted"}, "priority_changed", muted},-- // Muting comment volume never silences someone asking for you by name.- {"muted comments still delivers mentions", map[string]string{"comments": "muted"}, "mentioned", SectionAction},- {"muted mentions drops mentioned", map[string]string{"mentions": "muted"}, "mentioned", muted},- {"muted mentions still delivers new_comment", map[string]string{"mentions": "muted"}, "new_comment", SectionAction},-- // A muted pre-routing group mutes both halves until the new key is set.- {"legacy comments muted drops comment", map[string]string{"comments": "muted"}, "new_comment", muted},- {"legacy assignments muted drops assigned", map[string]string{"assignments": "muted"}, "issue_assigned", muted},- {"legacy assignments muted drops unassigned", map[string]string{"assignments": "muted"}, "unassigned", muted},- {"legacy agent_activity muted drops failure", map[string]string{"agent_activity": "muted"}, "task_failed", muted},- {"muting comments leaves assignments alone", map[string]string{"comments": "muted"}, "issue_assigned", SectionAction},-- // Types outside the routable kinds always land in their default section.- {"unroutable reaction", map[string]string{"comments": "muted"}, "reaction_added", SectionActivity},- {"unroutable review request", map[string]string{"assigned": "muted"}, "review_requested", SectionAction},- {"unknown value falls back to default", map[string]string{"status_changes": "loud"}, "status_changed", SectionActivity},- }- for _, c := range cases {- t.Run(c.name, func(t *testing.T) {- assertRoute(t, c.want, muted)(Route(c.prefs, c.notifType))- })- }-}--func TestRouteComment(t *testing.T) {- muted := ""-- cases := []struct {- name string- prefs map[string]string- audience CommentAudience- want string // muted means not delivered- }{- // Defaults: only a comment written to someone else is activity.- {"default to nobody", nil, CommentToNobody, SectionAction},- {"default to recipient", nil, CommentToRecipient, SectionAction},- {"default to others", nil, CommentToOthers, SectionActivity},-- // Each audience follows its own key.- {"to nobody routed to activity", map[string]string{"comments_without_mentions": "activity"}, CommentToNobody, SectionActivity},- {"to others routed to action", map[string]string{"comments_mentioning_others": "action"}, CommentToOthers, SectionAction},- {"to others muted", map[string]string{"comments_mentioning_others": "muted"}, CommentToOthers, muted},- {"to others choice leaves to nobody alone", map[string]string{"comments_mentioning_others": "muted"}, CommentToNobody, SectionAction},- {"to nobody choice leaves to others alone", map[string]string{"comments_without_mentions": "muted"}, CommentToOthers, SectionActivity},-- // A comment that @mentions the recipient follows the mentions choice,- // so it lands with the "mentioned" notification it also sends.- {"to recipient follows mentions", map[string]string{"mentions": "activity"}, CommentToRecipient, SectionActivity},- {"to recipient muted with mentions", map[string]string{"mentions": "muted"}, CommentToRecipient, muted},- {"to recipient ignores comment keys", map[string]string{"comments_without_mentions": "muted", "comments_mentioning_others": "muted"}, CommentToRecipient, SectionAction},-- // A muted pre-routing comments group still mutes every comment until- // the recipient sets the new key.- {"legacy comments muted drops to nobody", map[string]string{"comments": "muted"}, CommentToNobody, muted},- {"legacy comments muted drops to others", map[string]string{"comments": "muted"}, CommentToOthers, muted},- {"legacy comments muted drops to recipient", map[string]string{"comments": "muted"}, CommentToRecipient, muted},- {"new key overrides muted legacy group", map[string]string{"comments": "muted", "comments_mentioning_others": "activity"}, CommentToOthers, SectionActivity},- {"mentions key overrides muted legacy group", map[string]string{"comments": "muted", "mentions": "action"}, CommentToRecipient, SectionAction},- }- for _, c := range cases {- t.Run(c.name, func(t *testing.T) {- assertRoute(t, c.want, muted)(RouteComment(c.prefs, c.audience))- })- }-}--func assertRoute(t *testing.T, want, muted string) func(string, bool) {- t.Helper()- return func(got string, ok bool) {- t.Helper()- if want == muted {- if ok {- t.Fatalf("route = (%q, delivered), want muted", got)- }- return- }- if !ok || got != want {- t.Fatalf("route = (%q, %v), want (%q, delivered)", got, ok, want)- }- }-}--func TestRouteKeysAreRouteKinds(t *testing.T) {- for _, key := range []string{RouteKeyMentions, RouteKeyCommentsWithoutMentions, RouteKeyCommentsMentioningOthers} {- if !IsRouteKey(key) {- t.Errorf("%q is not a route kind", key)- }- }- for _, retired := range []string{"member_comments", "agent_comments"} {- if IsRouteKey(retired) {- t.Errorf("%q should no longer be a route kind", retired)- }- }-}--func TestItemSection(t *testing.T) {- if got := ItemSection(SectionText(SectionAction), "status_changed"); got != SectionAction {- t.Errorf("stored action = %q", got)- }- if got := ItemSection(SectionText(SectionActivity), "new_comment"); got != SectionActivity {- t.Errorf("stored activity = %q", got)- }- if got := ItemSection(pgtype.Text{}, "status_changed"); got != SectionActivity {- t.Errorf("unset falls back to default, got %q", got)- }- if got := ItemSection(SectionText("bogus"), "mentioned"); 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.godeleted file mode 100644index 8fa85e9fa6..0000000000--- a/server/internal/inbox/section.go+++ /dev/null@@ -1,72 +0,0 @@-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 comment-// written to them or to nobody in particular — and is the only section that-// counts as unread. "activity" is routine progress the Work sidebar already-// tracks live (status moves, property edits) and comments written to someone-// else; 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.-//-// new_comment is not here: whether a comment is activity depends on who it-// @mentions (see RouteComment), which a row without a stored section does not-// record, so such rows stay action.-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",-}--var activityTypeSet = func() map[string]bool {- set := make(map[string]bool, len(ActivityTypes))- for _, v := range ActivityTypes {- 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; keep the two in step.-func DefaultSection(notifType string) string {- if activityTypeSet[notifType] {- 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) string {- if stored.Valid && (stored.String == SectionAction || stored.String == SectionActivity) {- return stored.String- }- return DefaultSection(notifType)-}--// 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.godeleted file mode 100644index c562693e92..0000000000--- a/server/internal/inbox/section_test.go+++ /dev/null@@ -1,32 +0,0 @@-package inbox--import "testing"--func TestDefaultSection(t *testing.T) {- cases := []struct {- notifType string- want string- }{- {"issue_assigned", SectionAction},- {"mentioned", SectionAction},- {"task_failed", SectionAction},- {"children_done", SectionAction},- {"quick_create_failed", SectionAction},- {"autopilot_paused", SectionAction},- // A row without a stored section does not record who the comment- // @mentioned, so it stays action whoever wrote it.- {"new_comment", SectionAction},- {"status_changed", SectionActivity},- {"priority_changed", SectionActivity},- {"assignee_changed", SectionActivity},- {"reaction_added", SectionActivity},- {"quick_create_done", SectionActivity},- {"task_completed", SectionActivity},- {"some_future_type", SectionAction},- }- for _, c := range cases {- if got := DefaultSection(c.notifType); got != c.want {- t.Errorf("DefaultSection(%q) = %q, want %q", c.notifType, got, c.want)- }- }-}diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 412f40dab3..5b7de029d3 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -944,7 +944,6 @@ func (s *AutopilotService) notifyAutopilotSubscribersOnCreate("recipient_id": util.UUIDToString(item.RecipientID),"type": item.Type,"severity": item.Severity,- "section": inbox.ItemSection(item.Section, item.Type),"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 6eea1c25ba..ea69f8d254 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, "section": inbox.ItemSection(item.Section, item.Type), "issue_id": nil,+ "type": item.Type, "severity": item.Severity, "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.godeleted file mode 100644index eaec60505e..0000000000--- a/server/internal/service/delegated_failure_recovery_routing_test.go+++ /dev/null@@ -1,80 +0,0 @@-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) != "activity" {- t.Errorf("agent_failures=activity produced section %q", inbox.ItemSection(item.Section, item.Type))- }- }- 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 99b1d2cb2d..ccab4a4a4a 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, "section": inboxwriter.ItemSection(item.Section, item.Type), "issue_id": util.UUIDToPtr(item.IssueID),+ "type": item.Type, "severity": item.Severity, "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 8606db9536..016ce3fc20 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -6740,9 +6740,7 @@ 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, routed by- // their agent-failure preference like every other task_failed. The- // system comment above explains the outcome either way.+ // who originated (or is accountable for) the delegated work._, recipient := delegatedFailureRecoveryAttribution(target)if recipient.Valid {_, err = qtx.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{@@ -6756,22 +6754,6 @@ 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")- 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),@@ -6791,10 +6773,9 @@ func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, targeIssueID: target.issue.ID,Title: target.issue.Title,Body: pgtype.Text{String: exhaustedComment.Content, Valid: true},- ActorType: actorType,+ ActorType: pgtype.Text{String: "system", Valid: true},ActorID: pgtype.UUID{},Details: details,- Section: inbox.SectionText(section),})if err != nil {return fmt.Errorf("create delegated failure exhaustion inbox item: %w", err)@@ -6831,7 +6812,6 @@ 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),"issue_id": util.UUIDToPtr(exhaustedInbox.IssueID),"title": exhaustedInbox.Title,"body": util.TextToPtr(exhaustedInbox.Body),@@ -8378,7 +8358,6 @@ 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),"issue_id": util.UUIDToPtr(item.IssueID),"title": item.Title,"body": util.TextToPtr(item.Body),diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.goindex f4794efc50..9457f6939f 100644--- a/server/pkg/db/generated/inbox.sql.go+++ b/server/pkg/db/generated/inbox.sql.go@@ -30,50 +30,42 @@ func (q *Queries) ArchiveAllInbox(ctx context.Context, arg ArchiveAllInboxParams}const archiveAllReadInbox = `-- name: ArchiveAllReadInbox :execrows-WITH active AS (- SELECT i.id,+WITH newest_groups AS (+ SELECT DISTINCT ON (COALESCE(i.issue_id, i.id))COALESCE(i.issue_id, i.id) AS group_id,- i.created_at,- i.read,- COALESCE(i.section = 'activity', i.type = ANY($1::text[])) AS is_activity+ i.readFROM inbox_item i- WHERE i.workspace_id = $2+ WHERE i.workspace_id = $1AND i.recipient_type = 'member'- AND i.recipient_id = $3+ AND i.recipient_id = $2AND i.archived = false-), 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+ ORDER BY COALESCE(i.issue_id, i.id), i.created_at DESC, i.id DESC), read_groups AS (- SELECT group_id, is_activity+ SELECT group_idFROM newest_groups- WHERE read = true OR is_activity+ WHERE read = true)UPDATE inbox_item i SET archived = true-FROM active a-JOIN read_groups selected USING (group_id, is_activity)-WHERE i.id = a.id+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`type ArchiveAllReadInboxParams struct {- ActivityTypes []string `json:"activity_types"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- RecipientID pgtype.UUID `json:"recipient_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientID pgtype.UUID `json:"recipient_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).+// "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).func (q *Queries) ArchiveAllReadInbox(ctx context.Context, arg ArchiveAllReadInboxParams) (int64, error) {- result, err := q.db.Exec(ctx, archiveAllReadInbox, arg.ActivityTypes, arg.WorkspaceID, arg.RecipientID)+ result, err := q.db.Exec(ctx, archiveAllReadInbox, arg.WorkspaceID, arg.RecipientID)if err != nil {return 0, err}@@ -104,43 +96,6 @@ 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[]))-`--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"`-}--// 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.-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,- )- 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@@ -234,31 +189,18 @@ func (q *Queries) ArchiveInboxItem(ctx context.Context, id pgtype.UUID) (InboxIt}const countUnreadInbox = `-- name: CountUnreadInbox :one-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[]))+SELECT count(*) FROM inbox_item+WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND read = false AND archived = false`type CountUnreadInboxParams struct {WorkspaceID pgtype.UUID `json:"workspace_id"`RecipientType string `json:"recipient_type"`RecipientID pgtype.UUID `json:"recipient_id"`- ActivityTypes []string `json:"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,- arg.ActivityTypes,- )+ row := q.db.QueryRow(ctx, countUnreadInbox, arg.WorkspaceID, arg.RecipientType, arg.RecipientID)var count int64err := row.Scan(&count)return count, err@@ -274,18 +216,12 @@ 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[]))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"`-}-type CountUnreadInboxByWorkspaceRow struct {WorkspaceID pgtype.UUID `json:"workspace_id"`Count int64 `json:"count"`@@ -301,12 +237,8 @@ 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.-//-// 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)+func (q *Queries) CountUnreadInboxByWorkspace(ctx context.Context, recipientID pgtype.UUID) ([]CountUnreadInboxByWorkspaceRow, error) {+ rows, err := q.db.Query(ctx, countUnreadInboxByWorkspace, recipientID)if err != nil {return nil, err}@@ -329,9 +261,9 @@ 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, section+ actor_type, actor_id, details, id)-SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE($12::uuid, gen_random_uuid()), $13::text+SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE($12::uuid, gen_random_uuid())WHERE ($2::text = 'member' AND EXISTS (SELECT 1 FROM member WHERE workspace_id = $1 AND user_id = $3)) OR ($2::text = 'agent' AND EXISTS (@@ -353,7 +285,6 @@ 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.@@ -372,7 +303,6 @@ func (q *Queries) CreateInboxItem(ctx context.Context, arg CreateInboxItemParamsarg.ActorID,arg.Details,arg.ID,- arg.Section,)var i InboxItemerr := row.Scan(@@ -724,49 +654,20 @@ func (q *Queries) MarkInboxRead(ctx context.Context, id pgtype.UUID) (InboxItem,return i, err}-const markInboxReadByIssue = `-- name: MarkInboxReadByIssue :execrows-UPDATE inbox_item SET read = true-WHERE workspace_id = $1 AND recipient_type = 'member' AND recipient_id = $2 AND issue_id = $3- AND archived = false AND read = false-`--type MarkInboxReadByIssueParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- RecipientID pgtype.UUID `json:"recipient_id"`- IssueID pgtype.UUID `json:"issue_id"`-}--// 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, section = COALESCE($1::text, section)-WHERE id = $2+UPDATE inbox_item SET read = false+WHERE id = $1RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section`-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)+// Exact inverse of MarkInboxRead, and item-level for the same reason it is:+// the inbox renders one row per issue carrying that group's NEWEST item, and+// the group's read state is that item's read state. Flipping the whole group+// unread would resurrect older siblings the user already dealt with and+// inflate CountUnreadInbox (which counts raw rows), while changing nothing the+// UI shows.+func (q *Queries) MarkInboxUnread(ctx context.Context, id pgtype.UUID) (InboxItem, error) {+ row := q.db.QueryRow(ctx, markInboxUnread, id)var i InboxItemerr := row.Scan(&i.ID,diff --git a/server/pkg/db/generated/inbox_archive.sql.go b/server/pkg/db/generated/inbox_archive.sql.goindex e964a49ff6..d02cf19da6 100644--- a/server/pkg/db/generated/inbox_archive.sql.go+++ b/server/pkg/db/generated/inbox_archive.sql.go@@ -14,16 +14,13 @@ 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,- -- Activity is never unread (inbox.Section); the caller passes- -- inbox.ActivityTypes.- (i.read OR COALESCE(i.section = 'activity', i.type = ANY($1::text[]))) AS read,+ i.id, i.issue_id, i.created_at, i.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 = $2::uuid+ WHERE i.workspace_id = $1::uuidAND i.recipient_type = 'member'- AND i.recipient_id = $3::uuid+ AND i.recipient_id = $2::uuidAND i.archived = trueAND (i.issue_id IS NULL OR NOT EXISTS (SELECT 1 FROM inbox_item active@@ -37,13 +34,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 = $2::uuid+ AND iss.workspace_id = $1::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($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_matchFROM projected)SELECT 'statuses'::text AS dimension, issue_status::text AS key,@@ -64,13 +61,12 @@ FROM matched`type ArchivedInboxFacetsParams struct {- ActivityTypes []string `json:"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"`+ 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 {@@ -82,7 +78,6 @@ 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.WorkspaceID,arg.RecipientID,arg.Statuses,@@ -111,19 +106,16 @@ 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,- -- Activity is never unread (inbox.Section); the caller passes- -- inbox.ActivityTypes.- (i.read OR COALESCE(i.section = 'activity', i.type = ANY($1::text[]))) AS read,+ i.id, i.issue_id, i.created_at, i.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 = $2::uuid+ WHERE i.workspace_id = $1::uuidAND i.recipient_type = 'member'- AND i.recipient_id = $3::uuid+ AND i.recipient_id = $2::uuidAND i.archived = true- AND ($4::uuid IS NULL OR i.issue_id = $4::uuid- OR (i.issue_id IS NULL AND i.id = $4::uuid))+ AND ($3::uuid IS NULL OR i.issue_id = $3::uuid+ OR (i.issue_id IS NULL AND i.id = $3::uuid))AND (i.issue_id IS NULL OR NOT EXISTS (SELECT 1 FROM inbox_item activeWHERE active.workspace_id = i.workspace_id@@ -136,22 +128,22 @@ 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 = $2::uuid+ AND iss.workspace_id = $1::uuid), matched AS (SELECT projected.id, projected.issue_id, projected.created_at, projected.read, projected.actor, projected.issue_status, projected.issue_priority,- (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_match+ (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_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 ($9::timestamptz IS NULL OR- (created_at, id) < ($9::timestamptz, $10::uuid))+ AND ($8::timestamptz IS NULL OR+ (created_at, id) < ($8::timestamptz, $9::uuid))ORDER BY created_at DESC, id DESC- LIMIT $11::int+ LIMIT $10::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, i.section, selected.issue_status, selected.issue_priority,COALESCE(anchor.comment_id, '')::text AS comment_id@@ -170,17 +162,16 @@ ORDER BY i.created_at DESC, i.id DESC`type ListArchivedInboxPageParams struct {- ActivityTypes []string `json:"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"`+ 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 {@@ -193,7 +184,6 @@ 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.WorkspaceID,arg.RecipientID,arg.GroupID,diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sqlindex b0a8b14013..b5996db636 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, section+ actor_type, actor_id, details, id)-SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE(sqlc.narg('id')::uuid, gen_random_uuid()), sqlc.narg('section')::text+SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())WHERE ($2::text = 'member' AND EXISTS (SELECT 1 FROM member WHERE workspace_id = $1 AND user_id = $3)) OR ($2::text = 'agent' AND EXISTS (@@ -111,15 +111,14 @@ WHERE id = $1RETURNING *;-- name: MarkInboxUnread :one--- 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 = @id+-- 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 = $1RETURNING *;-- name: ArchiveInboxItem :one@@ -131,28 +130,6 @@ 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.-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[]));---- 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@@ -174,15 +151,8 @@ WHERE workspace_id = $1 AND issue_id = $2 AND type = $3 AND archived = falseRETURNING recipient_type, recipient_id;-- name: CountUnreadInbox :one--- 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[]));+SELECT count(*) FROM inbox_item+WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND read = false AND archived = false;-- name: CountUnreadInboxByWorkspace :many-- Per-workspace unread inbox counts for a recipient member, matching the@@ -195,10 +165,6 @@ WHERE i.workspace_id = sqlc.arg('workspace_id')-- 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))@@ -206,9 +172,8 @@ 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 = sqlc.arg('recipient_id')+ AND i.recipient_id = $1AND i.archived = false- AND NOT COALESCE(i.section = 'activity', i.type = ANY(sqlc.arg('activity_types')::text[]))ORDER BY i.workspace_id, COALESCE(i.issue_id, i.id), i.created_at DESC) newestWHERE newest.read = false@@ -223,40 +188,33 @@ 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 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,+-- "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))COALESCE(i.issue_id, i.id) AS group_id,- i.created_at,- i.read,- COALESCE(i.section = 'activity', i.type = ANY(sqlc.arg('activity_types')::text[])) AS is_activity+ i.readFROM inbox_item i- WHERE i.workspace_id = sqlc.arg('workspace_id')+ WHERE i.workspace_id = $1AND i.recipient_type = 'member'- AND i.recipient_id = sqlc.arg('recipient_id')+ AND i.recipient_id = $2AND i.archived = false-), 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+ ORDER BY COALESCE(i.issue_id, i.id), i.created_at DESC, i.id DESC), read_groups AS (- SELECT group_id, is_activity+ SELECT group_idFROM newest_groups- WHERE read = true OR is_activity+ WHERE read = true)UPDATE inbox_item i SET archived = true-FROM active a-JOIN read_groups selected USING (group_id, is_activity)-WHERE i.id = a.id;+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;-- 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 8a40ae4f8f..ac56469558 100644--- a/server/pkg/db/queries/inbox_archive.sql+++ b/server/pkg/db/queries/inbox_archive.sql@@ -2,10 +2,7 @@-- 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,- -- Activity is never unread (inbox.Section); the caller passes- -- inbox.ActivityTypes.- (i.read OR COALESCE(i.section = 'activity', i.type = ANY(sqlc.arg(activity_types)::text[]))) AS read,+ i.id, i.issue_id, i.created_at, i.read,CASE WHEN i.actor_type = 'system' THEN 'system'ELSE i.actor_type || ':' || i.actor_id::text END AS actorFROM inbox_item i@@ -63,10 +60,7 @@ 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,- -- Activity is never unread (inbox.Section); the caller passes- -- inbox.ActivityTypes.- (i.read OR COALESCE(i.section = 'activity', i.type = ANY(sqlc.arg(activity_types)::text[]))) AS read,+ i.id, i.issue_id, i.created_at, i.read,CASE WHEN i.actor_type = 'system' THEN 'system'ELSE i.actor_type || ':' || i.actor_id::text END AS actorFROM inbox_item i