Skip to content

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

Go

fix(rail): mark all chats read from the Chat rail menu (MUL-9499) (#10824)

Jiayuan Zhangba10632093a6
diff --git a/apps/docs/content/docs/chat.mdx b/apps/docs/content/docs/chat.mdx
index 87cd0d3e34..9b20c74e38 100644
--- a/apps/docs/content/docs/chat.mdx
+++ b/apps/docs/content/docs/chat.mdx
@@ -117,6 +117,8 @@ Conversations can be renamed, pinned, archived, and deleted:
If a conversation is bound to an external channel (such as Slack), archiving breaks the binding; unarchiving does not restore it — bind again.
+The number of unread replies across your conversations shows as a badge on **Chat** in the app rail. In the desktop app, right-click **Chat** for **Mark all as read**.
+
<Callout type="warning">
Deleting a conversation cannot be undone and stops any runs in it that haven't finished. Archive instead when you just don't need it for now.
</Callout>
diff --git a/apps/docs/content/docs/chat.zh.mdx b/apps/docs/content/docs/chat.zh.mdx
index a6d3e30891..1b2fab401f 100644
--- a/apps/docs/content/docs/chat.zh.mdx
+++ b/apps/docs/content/docs/chat.zh.mdx
@@ -117,6 +117,8 @@ import { ChatDemo } from "@/components/demos/chat-demo";
如果对话绑定了外部渠道(如 Slack),归档时绑定会断开,取消归档不会恢复,需要重新绑定。
+所有对话的未读回复数会以角标显示在应用侧栏的**聊天**上。在桌面端右键点击**聊天**可以**全部标为已读**。
+
<Callout type="warning">
删除对话无法撤销,并会停止其中尚未结束的执行。暂时不需要时用归档。
</Callout>
diff --git a/packages/core/chat/mutations.test.tsx b/packages/core/chat/mutations.test.tsx
index 3f75b9e395..84174beb64 100644
--- a/packages/core/chat/mutations.test.tsx
+++ b/packages/core/chat/mutations.test.tsx
@@ -2,18 +2,19 @@
* @vitest-environment jsdom
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { act, renderHook } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
import type { ReactNode } from "react";
import { setApiInstance } from "../api";
import type { ApiClient } from "../api/client";
import {
useConsumeChatDraftRestore,
+ useMarkAllChatSessionsRead,
useSetChatSessionArchived,
useSetChatSessionProject,
} from "./mutations";
-import { chatKeys } from "./queries";
+import { chatKeys, chatSessionsOptions } from "./queries";
import type { ChatSession } from "../types";
vi.mock("../hooks", () => ({
@@ -44,6 +45,99 @@ function createWrapper(qc: QueryClient) {
};
}
+describe("useMarkAllChatSessionsRead", () => {
+ let qc: QueryClient;
+ let markChatSessionRead: ReturnType<typeof vi.fn<(id: string) => Promise<void>>>;
+
+ beforeEach(() => {
+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ markChatSessionRead = vi.fn();
+ setApiInstance({ markChatSessionRead } as unknown as ApiClient);
+ });
+
+ afterEach(() => {
+ qc.clear();
+ vi.restoreAllMocks();
+ });
+
+ it("reads each session and zeroes their unread", async () => {
+ markChatSessionRead.mockResolvedValue(undefined);
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(WS_ID), [
+ makeSession({ id: "s1", unread_count: 3 }),
+ makeSession({ id: "s2", unread_count: 4 }),
+ makeSession({ id: "s3", unread_count: 0, has_unread: false }),
+ ]);
+
+ const { result } = renderHook(() => useMarkAllChatSessionsRead(), {
+ wrapper: createWrapper(qc),
+ });
+ await act(async () => {
+ await result.current.mutateAsync(["s1", "s2"]);
+ });
+
+ expect(markChatSessionRead.mock.calls.map(([id]) => id)).toEqual(["s1", "s2"]);
+ const rows = qc.getQueryData<ChatSession[]>(chatKeys.sessions(WS_ID))!;
+ expect(rows.map((s) => s.unread_count)).toEqual([0, 0, 0]);
+ expect(rows.every((s) => !s.has_unread)).toBe(true);
+ });
+
+ // One failed read must not stop the others; the failed row gets its unread
+ // back and the one that went through stays read.
+ it("restores only the sessions whose read failed", async () => {
+ markChatSessionRead.mockImplementation(async (id) => {
+ if (id === "s1") throw new Error("boom");
+ });
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(WS_ID), [
+ makeSession({ id: "s1", unread_count: 2 }),
+ makeSession({ id: "s2", unread_count: 5 }),
+ ]);
+
+ const { result } = renderHook(() => useMarkAllChatSessionsRead(), {
+ wrapper: createWrapper(qc),
+ });
+ await act(async () => {
+ await expect(result.current.mutateAsync(["s1", "s2"])).rejects.toThrow();
+ });
+
+ expect(markChatSessionRead).toHaveBeenCalledTimes(2);
+ const rows = qc.getQueryData<ChatSession[]>(chatKeys.sessions(WS_ID))!;
+ expect(rows.map((s) => [s.id, s.unread_count, s.has_unread])).toEqual([
+ ["s1", 2, true],
+ ["s2", 0, false],
+ ]);
+ });
+
+ // Offline: the read and the follow-up refetch both fail, so the rollback is
+ // all that keeps the badge (and the menu item) from hiding real unread.
+ it("keeps unread when the read and the refetch both fail", async () => {
+ const listChatSessions = vi.fn().mockRejectedValue(new Error("offline"));
+ markChatSessionRead.mockRejectedValue(new Error("offline"));
+ setApiInstance({ listChatSessions, markChatSessionRead } as unknown as ApiClient);
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(WS_ID), [
+ makeSession({ id: "s1", unread_count: 2 }),
+ ]);
+
+ const { result } = renderHook(
+ () => {
+ useQuery(chatSessionsOptions(WS_ID));
+ return useMarkAllChatSessionsRead();
+ },
+ { wrapper: createWrapper(qc) },
+ );
+ await act(async () => {
+ await expect(result.current.mutateAsync(["s1"])).rejects.toThrow();
+ });
+ await waitFor(() => {
+ expect(listChatSessions).toHaveBeenCalled();
+ expect(qc.isFetching()).toBe(0);
+ });
+
+ const row = qc.getQueryData<ChatSession[]>(chatKeys.sessions(WS_ID))![0]!;
+ expect(row.unread_count).toBe(2);
+ expect(row.has_unread).toBe(true);
+ });
+});
+
describe("useSetChatSessionArchived", () => {
let qc: QueryClient;
let setChatSessionArchived: ReturnType<
diff --git a/packages/core/chat/mutations.ts b/packages/core/chat/mutations.ts
index c03d00a3ec..42bba7bf20 100644
--- a/packages/core/chat/mutations.ts
+++ b/packages/core/chat/mutations.ts
@@ -218,6 +218,60 @@ export function useMarkChatSessionRead() {
});
}
+class MarkChatSessionsReadError extends Error {
+ constructor(readonly failedIds: string[], total: number) {
+ super(`failed to mark ${failedIds.length} of ${total} chats read`);
+ }
+}
+
+/**
+ * Clears unread on every chat session that has any, one read per session (the
+ * server has no bulk read, and each read broadcasts its own chat:session_read
+ * to other devices). All rows drop to 0 optimistically; if any read fails the
+ * mutation rejects and only the failed rows get their unread back, so the
+ * badge stays right even when the follow-up refetch fails too.
+ */
+export function useMarkAllChatSessionsRead() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+
+ return useMutation({
+ mutationFn: async (sessionIds: string[]) => {
+ logger.info("markAllChatSessionsRead.start", { count: sessionIds.length });
+ const results = await Promise.allSettled(sessionIds.map((id) => api.markChatSessionRead(id)));
+ const failedIds = sessionIds.filter((_, i) => results[i]!.status === "rejected");
+ if (failedIds.length > 0) throw new MarkChatSessionsReadError(failedIds, sessionIds.length);
+ },
+ onMutate: async (sessionIds) => {
+ await qc.cancelQueries({ queryKey: chatKeys.sessions(wsId) });
+ const ids = new Set(sessionIds);
+ const prevUnread = new Map<string, Pick<ChatSession, "has_unread" | "unread_count">>();
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), (old) =>
+ old?.map((s) => {
+ if (!ids.has(s.id)) return s;
+ prevUnread.set(s.id, { has_unread: s.has_unread, unread_count: s.unread_count });
+ return { ...s, has_unread: false, unread_count: 0 };
+ }),
+ );
+ return { prevUnread };
+ },
+ onError: (err, sessionIds, ctx) => {
+ logger.error("markAllChatSessionsRead.error.rollback", { err });
+ if (!ctx) return;
+ const failed = new Set(err instanceof MarkChatSessionsReadError ? err.failedIds : sessionIds);
+ qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), (old) =>
+ old?.map((s) => {
+ const prev = failed.has(s.id) ? ctx.prevUnread.get(s.id) : undefined;
+ return prev ? { ...s, ...prev } : s;
+ }),
+ );
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: chatKeys.sessions(wsId) });
+ },
+ });
+}
+
/**
* Renames a chat session. Optimistically swaps the title in the cached
* list so the dropdown reflects the new label immediately; rolls back on
diff --git a/packages/views/layout/app-rail.test.tsx b/packages/views/layout/app-rail.test.tsx
index b52e1d7328..a5e3d300f9 100644
--- a/packages/views/layout/app-rail.test.tsx
+++ b/packages/views/layout/app-rail.test.tsx
@@ -22,6 +22,9 @@ const state = vi.hoisted(() => ({
chatSessions: [] as { id: string; unread_count?: number }[],
chat: { activeSessionId: null as string | null, isOpen: false },
stuck: [] as unknown[],
+ desktop: false,
+ markAllInboxRead: vi.fn(),
+ markAllChatsRead: vi.fn(),
}));
vi.mock("../navigation", () => ({
@@ -39,7 +42,16 @@ vi.mock("../navigation", () => ({
pathname: state.pathname,
searchParams: new URLSearchParams(state.search),
push: vi.fn(),
+ openInNewTab: state.desktop ? vi.fn() : undefined,
+ getShareableUrl: (href: string) => href,
}),
+ useIntentNavigate: () => vi.fn(),
+}));
+vi.mock("@multica/core/inbox/mutations", () => ({
+ useMarkAllInboxRead: () => ({ mutate: state.markAllInboxRead }),
+}));
+vi.mock("@multica/core/chat/mutations", () => ({
+ useMarkAllChatSessionsRead: () => ({ mutate: state.markAllChatsRead }),
}));
vi.mock("@multica/core/paths", async (importOriginal) => {
const actual = await importOriginal<typeof import("@multica/core/paths")>();
@@ -132,6 +144,9 @@ beforeEach(() => {
state.chatSessions = [];
state.chat = { activeSessionId: null, isOpen: false };
state.stuck = [];
+ state.desktop = false;
+ state.markAllInboxRead.mockReset();
+ state.markAllChatsRead.mockReset();
useRailOrderStore.setState({ order: null });
useSidebarTreeStore.setState({ inboxSettings: DEFAULT_SIDEBAR_INBOX_SETTINGS });
});
@@ -380,6 +395,45 @@ describe("AppRail chat badge", () => {
});
});
+describe("AppRail space menu", () => {
+ const openMenu = async (href: string) => {
+ fireEvent.contextMenu(link(href)!, { clientX: 30, clientY: 300 });
+ return screen.findByRole("menu");
+ };
+ const markAllRead = (menu: HTMLElement) => within(menu).queryByRole("menuitem", { name: "Mark all as read" });
+
+ beforeEach(() => {
+ state.desktop = true;
+ });
+
+ it("marks every unread chat read from Chat", async () => {
+ state.chatSessions = [
+ { id: "a", unread_count: 3 },
+ { id: "b", unread_count: 0 },
+ { id: "c", unread_count: 22 },
+ ];
+ renderRail();
+ fireEvent.click(markAllRead(await openMenu("/acme/chat"))!);
+ expect(state.markAllChatsRead).toHaveBeenCalledWith(["a", "c"], expect.anything());
+ expect(state.markAllInboxRead).not.toHaveBeenCalled();
+ });
+
+ it("offers no Mark all as read on Chat when every chat is read", async () => {
+ state.chatSessions = [{ id: "a", unread_count: 0 }];
+ renderRail();
+ expect(markAllRead(await openMenu("/acme/chat"))).toBeNull();
+ });
+
+ it("marks the inbox read from Work", async () => {
+ state.inboxUnread = 4;
+ state.chatSessions = [{ id: "a", unread_count: 3 }];
+ renderRail();
+ fireEvent.click(markAllRead(await openMenu("/acme/issues"))!);
+ expect(state.markAllInboxRead).toHaveBeenCalledTimes(1);
+ expect(state.markAllChatsRead).not.toHaveBeenCalled();
+ });
+});
+
describe("AppRail panel peek", () => {
afterEach(() => {
vi.useRealTimers();
diff --git a/packages/views/layout/app-rail.tsx b/packages/views/layout/app-rail.tsx
index 642ed7d00d..73fa233920 100644
--- a/packages/views/layout/app-rail.tsx
+++ b/packages/views/layout/app-rail.tsx
@@ -16,6 +16,7 @@ import { CSS } from "@dnd-kit/utilities";
import { CheckCheck, ExternalLink, Link2, RotateCcw, Settings, Users, type IconComponent } from "@multica/ui/icons";
import { toast } from "sonner";
import { useChatStore } from "@multica/core/chat";
+import { useMarkAllChatSessionsRead } from "@multica/core/chat/mutations";
import { chatSessionsOptions } from "@multica/core/chat/queries";
import { countUnreadChatMessages } from "@multica/core/chat/unread";
import {
@@ -262,8 +263,15 @@ function RailSpaceMenu({
const copyLink = async () => {
if (await copyText(getShareableUrl(href))) toast.success(t(($) => $.rail.link_copied));
};
+ const wsId = useCurrentWorkspace()?.id;
const markAllRead = useMarkAllInboxRead();
- const inboxUnread = useInboxUnreadCount(useCurrentWorkspace()?.id);
+ const inboxUnread = useInboxUnreadCount(wsId);
+ const markAllChatsRead = useMarkAllChatSessionsRead();
+ const { data: chatSessions = [] } = useQuery({
+ ...chatSessionsOptions(wsId ?? ""),
+ enabled: space === "chat" && !!wsId,
+ });
+ const unreadChatIds = chatSessions.filter((s) => (s.unread_count ?? 0) > 0).map((s) => s.id);
const customOrder = useRailOrderStore((s) => s.order !== null);
const setOrder = useRailOrderStore((s) => s.setOrder);
return (
@@ -292,6 +300,21 @@ function RailSpaceMenu({
</DropdownMenuItem>
</>
)}
+ {space === "chat" && unreadChatIds.length > 0 && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() =>
+ markAllChatsRead.mutate(unreadChatIds, {
+ onError: () => toast.error(t(($) => $.rail.mark_all_read_failed)),
+ })
+ }
+ >
+ <CheckCheck />
+ {t(($) => $.rail.mark_all_read)}
+ </DropdownMenuItem>
+ </>
+ )}
<DropdownMenuSeparator />
<DropdownMenuItem disabled={!customOrder} onClick={() => setOrder(RAIL_SPACES)}>
<RotateCcw />