Skip to content

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

Go

fix(chat): badge unread chat replies that arrive while backgrounded (MUL-4485) (#5356)

Bohan Jiangace0f16cadad
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index 2f61426cc1..c53e9ecba4 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -21,6 +21,7 @@ import { api } from "@multica/core/api";
import { useAgentPresenceDetail, useWorkspaceAgentAvailability } from "@multica/core/agents";
import { useFileUpload } from "@multica/core/hooks/use-file-upload";
import { ActorAvatar } from "../../common/actor-avatar";
+import { useAppForeground } from "../../common/use-app-foreground";
import {
PickerEmpty,
PickerItem,
@@ -325,19 +326,23 @@ export function ChatWindow() {
// stays current even when this window is closed. See packages/core/realtime/.
// Auto mark-as-read whenever the user is looking at a session with unread
- // state: window open + a session active + has_unread → PATCH.
- // has_unread comes from the list query; WS handlers invalidate it on
- // chat:done so a reply arriving while the user watches triggers this
- // effect again and is instantly cleared.
+ // state: window open + app in the foreground + a session active + has_unread
+ // → PATCH. has_unread comes from the list query; WS handlers invalidate it on
+ // chat:done so a reply arriving while the user watches triggers this effect
+ // again and is instantly cleared. `appForeground` gates the "is looking"
+ // assumption: a reply landing while the window is open but the app is
+ // backgrounded must stay unread so the sidebar badges it (MUL-4485), then
+ // clears when the user refocuses and this effect re-runs.
+ const appForeground = useAppForeground();
const currentHasUnread =
sessions.find((s) => s.id === activeSessionId)?.has_unread ?? false;
useEffect(() => {
- if (!isOpen || !activeSessionId) return;
+ if (!isOpen || !appForeground || !activeSessionId) return;
if (!currentHasUnread) return;
uiLogger.info("auto markRead", { sessionId: activeSessionId });
markRead.mutate(activeSessionId);
// eslint-disable-next-line react-hooks/exhaustive-deps -- markRead ref stable
- }, [isOpen, activeSessionId, currentHasUnread]);
+ }, [isOpen, appForeground, activeSessionId, currentHasUnread]);
const { uploadWithToast } = useFileUpload(api);
diff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsx
index 6c2861552e..3285c15d44 100644
--- a/packages/views/chat/components/use-chat-controller.test.tsx
+++ b/packages/views/chat/components/use-chat-controller.test.tsx
@@ -17,6 +17,9 @@ const h = vi.hoisted(() => {
return {
store,
archivedMutate: vi.fn(),
+ markReadMutate: vi.fn(),
+ // Foreground gate for the auto mark-read effect; tests flip it.
+ appForeground: { value: true },
// useQuery reads these so each test can vary the loaded data.
sessions: [] as ChatSession[],
agents: [] as Agent[],
@@ -45,9 +48,12 @@ vi.mock("@multica/core/hooks/use-file-upload", () => ({
}));
vi.mock("@multica/core/chat/mutations", () => ({
useCreateChatSession: () => ({ mutateAsync: vi.fn() }),
- useMarkChatSessionRead: () => ({ mutate: vi.fn() }),
+ useMarkChatSessionRead: () => ({ mutate: h.markReadMutate }),
useSetChatSessionArchived: () => ({ mutate: h.archivedMutate }),
}));
+vi.mock("../../common/use-app-foreground", () => ({
+ useAppForeground: () => h.appForeground.value,
+}));
vi.mock("@multica/core/chat", () => ({
useChatStore: Object.assign(
(sel: (s: typeof h.store) => unknown) => sel(h.store),
@@ -193,3 +199,43 @@ describe("useChatController.archiveSession", () => {
expect(h.archivedMutate).toHaveBeenCalledWith({ sessionId: "sA", archived: true });
});
});
+
+describe("useChatController auto mark-read — foreground gating (MUL-4485)", () => {
+ const unreadActive = makeSession({ id: "sU", agent_id: "agent-a", has_unread: true });
+
+ beforeEach(() => {
+ h.markReadMutate.mockClear();
+ h.appForeground.value = true;
+ });
+
+ function renderController(activeSessionId: string | null, sessions: ChatSession[]) {
+ h.store.activeSessionId = activeSessionId;
+ h.store.selectedAgentId = null;
+ h.sessions = sessions;
+ h.agents = [agentA];
+ return renderHook(() => useChatController({ isActive: true }));
+ }
+
+ it("marks the active unread session read while the app is in the foreground", () => {
+ renderController("sU", [unreadActive]);
+ expect(h.markReadMutate).toHaveBeenCalledWith("sU");
+ });
+
+ it("does NOT mark read while the app is backgrounded, so the reply stays unread", () => {
+ h.appForeground.value = false;
+ renderController("sU", [unreadActive]);
+ expect(h.markReadMutate).not.toHaveBeenCalled();
+ });
+
+ it("marks read once the user returns to the foreground", () => {
+ h.appForeground.value = false;
+ const { rerender } = renderController("sU", [unreadActive]);
+ expect(h.markReadMutate).not.toHaveBeenCalled();
+
+ act(() => {
+ h.appForeground.value = true;
+ rerender();
+ });
+ expect(h.markReadMutate).toHaveBeenCalledWith("sU");
+ });
+});
diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.ts
index 74aedea202..5457a168d2 100644
--- a/packages/views/chat/components/use-chat-controller.ts
+++ b/packages/views/chat/components/use-chat-controller.ts
@@ -38,6 +38,7 @@ import type {
ChatPendingTask,
} from "@multica/core/types";
import { useT } from "../../i18n";
+import { useAppForeground } from "../../common/use-app-foreground";
const uiLogger = createLogger("chat.ui");
const apiLogger = createLogger("chat.api");
@@ -307,16 +308,20 @@ export function useChatController(opts?: { isActive?: boolean }) {
// Auto mark-as-read whenever the user is actively looking at a session with
// unread state. `isActive` lets the caller say "my surface is on screen":
- // the floating overlay passes `isOpen`, the tab passes `true`.
+ // the floating overlay passes `isOpen`, the tab passes `true`. `appForeground`
+ // additionally requires the window to be visible and focused: a reply landing
+ // while the app is backgrounded must stay unread so the sidebar badges it
+ // (MUL-4485); it clears the moment the user returns and this effect re-runs.
+ const appForeground = useAppForeground();
const currentHasUnread =
sessions.find((s) => s.id === activeSessionId)?.has_unread ?? false;
useEffect(() => {
- if (!isActive || !activeSessionId) return;
+ if (!isActive || !appForeground || !activeSessionId) return;
if (!currentHasUnread) return;
uiLogger.info("auto markRead", { sessionId: activeSessionId });
markRead.mutate(activeSessionId);
// eslint-disable-next-line react-hooks/exhaustive-deps -- markRead ref stable
- }, [isActive, activeSessionId, currentHasUnread]);
+ }, [isActive, appForeground, activeSessionId, currentHasUnread]);
const { uploadWithToast } = useFileUpload(api);
diff --git a/packages/views/common/use-app-foreground.test.ts b/packages/views/common/use-app-foreground.test.ts
new file mode 100644
index 0000000000..7800bfb556
--- /dev/null
+++ b/packages/views/common/use-app-foreground.test.ts
@@ -0,0 +1,70 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { useAppForeground } from "./use-app-foreground";
+
+/** Drive jsdom's visibility + focus, then fire the event the hook listens on. */
+function setEnv(visible: boolean, focused: boolean) {
+ Object.defineProperty(document, "visibilityState", {
+ configurable: true,
+ get: () => (visible ? "visible" : "hidden"),
+ });
+ vi.spyOn(document, "hasFocus").mockReturnValue(focused);
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ Object.defineProperty(document, "visibilityState", {
+ configurable: true,
+ get: () => "visible",
+ });
+});
+
+describe("useAppForeground", () => {
+ it("is true when the document is visible and focused", () => {
+ setEnv(true, true);
+ const { result } = renderHook(() => useAppForeground());
+ expect(result.current).toBe(true);
+ });
+
+ it("is false when the window loses focus (another app / window on top)", () => {
+ setEnv(true, false);
+ const { result } = renderHook(() => useAppForeground());
+ expect(result.current).toBe(false);
+ });
+
+ it("is false when the tab is hidden even if it still reports focus", () => {
+ setEnv(false, true);
+ const { result } = renderHook(() => useAppForeground());
+ expect(result.current).toBe(false);
+ });
+
+ it("reacts to blur and focus events", () => {
+ setEnv(true, true);
+ const { result } = renderHook(() => useAppForeground());
+ expect(result.current).toBe(true);
+
+ act(() => {
+ setEnv(true, false);
+ window.dispatchEvent(new Event("blur"));
+ });
+ expect(result.current).toBe(false);
+
+ act(() => {
+ setEnv(true, true);
+ window.dispatchEvent(new Event("focus"));
+ });
+ expect(result.current).toBe(true);
+ });
+
+ it("reacts to visibilitychange events", () => {
+ setEnv(true, true);
+ const { result } = renderHook(() => useAppForeground());
+ expect(result.current).toBe(true);
+
+ act(() => {
+ setEnv(false, true);
+ document.dispatchEvent(new Event("visibilitychange"));
+ });
+ expect(result.current).toBe(false);
+ });
+});
diff --git a/packages/views/common/use-app-foreground.ts b/packages/views/common/use-app-foreground.ts
new file mode 100644
index 0000000000..a7cc488599
--- /dev/null
+++ b/packages/views/common/use-app-foreground.ts
@@ -0,0 +1,50 @@
+import { useSyncExternalStore } from "react";
+
+/**
+ * Whether the app window is actually in front of the user right now: the
+ * document is visible (not a background browser tab / minimized window) AND the
+ * window holds OS focus (not sitting behind another app or another window).
+ *
+ * Callers use it to answer "is the user really looking at this surface". A chat
+ * reply that lands while the app is NOT in the foreground must not be
+ * auto-marked-read and must still raise the unread badge — otherwise the
+ * notification is silently eaten while the user is away (MUL-4485). The chat
+ * sidebar badge and the auto mark-read effects share this signal so they stay
+ * consistent: while backgrounded the active session both counts toward the
+ * badge and keeps its unread; on return the badge clears and mark-read fires.
+ *
+ * In the browser the value is always measured from the real DOM. The `true`
+ * fallbacks below only apply where there is no window to measure — SSR and
+ * other non-DOM contexts — which also have no live surface or WS traffic to act
+ * on. `true` (foreground) is chosen there only so the SSR snapshot matches the
+ * first client snapshot of a freshly opened, focused window and hydration
+ * doesn't flip the value; the real focus/visibility state takes over
+ * immediately on the client, flipping to `false` the moment either is lost.
+ */
+function subscribe(onStoreChange: () => void): () => void {
+ if (typeof document === "undefined") return () => {};
+ document.addEventListener("visibilitychange", onStoreChange);
+ window.addEventListener("focus", onStoreChange);
+ window.addEventListener("blur", onStoreChange);
+ return () => {
+ document.removeEventListener("visibilitychange", onStoreChange);
+ window.removeEventListener("focus", onStoreChange);
+ window.removeEventListener("blur", onStoreChange);
+ };
+}
+
+function getSnapshot(): boolean {
+ if (typeof document === "undefined") return true;
+ return document.visibilityState === "visible" && document.hasFocus();
+}
+
+// Server render has no window to be in the foreground of; default to visible so
+// the first client paint matches SSR, then useSyncExternalStore reconciles to
+// the real value on hydration.
+function getServerSnapshot(): boolean {
+ return true;
+}
+
+export function useAppForeground(): boolean {
+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
+}
diff --git a/packages/views/layout/app-sidebar.test.tsx b/packages/views/layout/app-sidebar.test.tsx
index bb0af436b1..9d3da66cce 100644
--- a/packages/views/layout/app-sidebar.test.tsx
+++ b/packages/views/layout/app-sidebar.test.tsx
@@ -3,7 +3,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { ApiError } from "@multica/core/api";
import { AppSidebar } from "./app-sidebar";
-const { chatSessions, chatStore, detail, deletePin, navigation, pins, summary, workspaces } = vi.hoisted(() => ({
+const { appForeground, chatSessions, chatStore, detail, deletePin, navigation, pins, summary, workspaces } = vi.hoisted(() => ({
+ appForeground: { current: true },
chatSessions: { current: [] as { id?: string; unread_count?: number }[] },
chatStore: { current: { activeSessionId: null as string | null, isOpen: false } },
detail: { current: { isPending: false, isError: false, data: null as unknown, error: null as unknown } },
@@ -85,6 +86,9 @@ vi.mock("@multica/ui/components/ui/tooltip", () => ({
TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
TooltipTrigger: ({ children }: { children: React.ReactNode }) => <button type="button">{children}</button>,
}));
+vi.mock("../common/use-app-foreground", () => ({
+ useAppForeground: () => appForeground.current,
+}));
vi.mock("./help-launcher", () => ({ HelpLauncher: () => null }));
vi.mock("../auth", () => ({ useLogout: () => vi.fn() }));
vi.mock("../issues/components/status-icon", () => ({ StatusIcon: () => <span /> }));
@@ -296,6 +300,7 @@ describe("personal nav — Chat", () => {
chatSessions.current = [];
navigation.current = { pathname: "/acme/issues" };
chatStore.current = { activeSessionId: null, isOpen: false };
+ appForeground.current = true;
});
// The mocked SidebarMenuButton exposes the AppLink target as `data-href`
@@ -350,4 +355,25 @@ describe("personal nav — Chat", () => {
const { container } = render(<AppSidebar />);
expect(chatBadge(container)).toHaveAttribute("aria-label", "5");
});
+
+ it("counts the active session while the floating window is open but the app is backgrounded", () => {
+ // A reply landing while the app is not in the foreground is NOT auto
+ // marked-read (MUL-4485), so its unread must still badge — otherwise the
+ // notification is silently eaten while the user is away.
+ chatSessions.current = [{ id: "a", unread_count: 2 }, { id: "b", unread_count: 3 }];
+ navigation.current = { pathname: "/acme/issues" };
+ chatStore.current = { activeSessionId: "a", isOpen: true };
+ appForeground.current = false;
+ const { container } = render(<AppSidebar />);
+ expect(chatBadge(container)).toHaveAttribute("aria-label", "5");
+ });
+
+ it("counts the active session on the chat route while the app is backgrounded", () => {
+ chatSessions.current = [{ id: "a", unread_count: 2 }, { id: "b", unread_count: 3 }];
+ navigation.current = { pathname: "/acme/chat" };
+ chatStore.current = { activeSessionId: "a", isOpen: false };
+ appForeground.current = false;
+ const { container } = render(<AppSidebar />);
+ expect(chatBadge(container)).toHaveAttribute("aria-label", "5");
+ });
});
diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsx
index a51cc4bd4e..85c9e88a01 100644
--- a/packages/views/layout/app-sidebar.tsx
+++ b/packages/views/layout/app-sidebar.tsx
@@ -91,6 +91,7 @@ import {
useShortcut,
} from "@multica/core/shortcuts";
import { ShortcutKeycaps } from "../common/shortcut-keycaps";
+import { useAppForeground } from "../common/use-app-foreground";
// Top-level nav items stay active when the user is on a child route
// (e.g. "Projects" stays lit on /:slug/projects/:id). Pinned items keep
@@ -386,15 +387,19 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }
// The session the user is reading right now must not count: the thread list
// renders its row badge as 0 (auto mark-read is about to clear it), and a
// reply landing in the open conversation would otherwise flash a sidebar
- // count with no matching row. "Reading right now" = a session is active AND
- // a chat surface is actually showing it (chat page route or the floating
- // window). A remembered selection while both surfaces are closed still
- // counts — auto mark-read won't fire there, so the badge must.
+ // count with no matching row. "Reading right now" = a session is active, a
+ // chat surface is actually showing it (chat page route or the floating
+ // window), AND the app is in the foreground. When the app is backgrounded,
+ // auto mark-read is suppressed (MUL-4485) so the reply stays unread — the
+ // badge must count it, or the notification is silently eaten while the user
+ // is away. A remembered selection while both surfaces are closed also still
+ // counts, for the same reason.
const activeChatSessionId = useChatStore((s) => s.activeSessionId);
const floatingChatOpen = useChatStore((s) => s.isOpen);
+ const appForeground = useAppForeground();
const chatHref = p.chat();
const viewedChatSessionId =
- floatingChatOpen || isNavActive(pathname, chatHref)
+ appForeground && (floatingChatOpen || isNavActive(pathname, chatHref))
? activeChatSessionId
: null;
const chatUnreadCount = React.useMemo(