Skip to content

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

Go

fix(desktop): restore background chat alerts and Dock counts (MUL-9082) (#10443)

Bohan Jiangbe733f0cbd51
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 48a71d0a16..39492643c3 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -27,6 +27,7 @@ import { installContextMenu } from "./context-menu";
import { handleAppShortcut } from "./keyboard-shortcuts";
import { installNavigationGestures } from "./navigation-gestures";
import { installNavigationGuard } from "./navigation-guard";
+import { installWindowForegroundEvents, windowForeground } from "./window-foreground";
import { createRendererWebPreferences } from "./renderer-web-preferences";
import { getAppVersion } from "./app-version";
import { loadRuntimeConfig } from "./runtime-config-loader";
@@ -357,6 +358,7 @@ function getSystemLocale(): string {
}
function loadRenderer(window: BrowserWindow): void {
+ installWindowForegroundEvents(window);
const rendererEntry = join(__dirname, "../renderer/index.html");
const rendererURL =
is.dev && process.env["ELECTRON_RENDERER_URL"]
@@ -985,6 +987,10 @@ if (!gotTheLock) {
);
});
+ ipcMain.handle("window:foreground", (event) =>
+ windowForeground(BrowserWindow.fromWebContents(event.sender)),
+ );
+
// Main owns foreground detection and item-level dedupe. Every renderer
// has its own WebSocket and `document.hasFocus()` only describes that one
// window, so renderer-only gating can emit N duplicate system banners.
@@ -1002,9 +1008,7 @@ if (!gotTheLock) {
const payload = parseNativeNotificationPayload(value);
if (!payload || !Notification.isSupported()) return;
- const anyWindowFocused = BrowserWindow.getAllWindows().some(
- (window) => !window.isDestroyed() && window.isFocused(),
- );
+ const anyWindowFocused = BrowserWindow.getAllWindows().some(windowForeground);
if (!notificationGate.shouldShow(payload.itemId, anyWindowFocused)) {
return;
}
@@ -1033,6 +1037,10 @@ if (!gotTheLock) {
mainWindows.findByWorkspace(payload.slug),
);
});
+ notification.on("failed", (_event, error) => {
+ console.warn("Native notification delivery failed:", error);
+ });
+ notification.on("show", () => console.info("Native notification displayed"));
notification.show();
});
diff --git a/apps/desktop/src/main/window-foreground.test.ts b/apps/desktop/src/main/window-foreground.test.ts
new file mode 100644
index 0000000000..4fb3438b3d
--- /dev/null
+++ b/apps/desktop/src/main/window-foreground.test.ts
@@ -0,0 +1,39 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from "vitest";
+import type { BrowserWindow } from "electron";
+import { installWindowForegroundEvents, windowForeground } from "./window-foreground";
+
+describe("native window foreground", () => {
+ it("requires focus, visibility, and a restored live window", () => {
+ const state = { focused: true, visible: true, minimized: false, destroyed: false };
+ const window = {
+ isFocused: () => state.focused, isVisible: () => state.visible,
+ isMinimized: () => state.minimized, isDestroyed: () => state.destroyed,
+ } as BrowserWindow;
+ expect(windowForeground(window)).toBe(true);
+ for (const change of [{ focused: false }, { visible: false }, { minimized: true }, { destroyed: true }]) {
+ Object.assign(state, change);
+ expect(windowForeground(window)).toBe(false);
+ Object.assign(state, { focused: true, visible: true, minimized: false, destroyed: false });
+ }
+ expect(windowForeground(null)).toBe(false);
+ });
+
+ it("reports focus changes from the native window to its own renderer", () => {
+ const callbacks = new Map<string, () => void>();
+ const send = vi.fn();
+ let focused = true;
+ const window = {
+ isDestroyed: () => false, isVisible: () => true, isMinimized: () => false,
+ isFocused: () => focused, on: (event: string, callback: () => void) => callbacks.set(event, callback),
+ webContents: { send },
+ } as unknown as BrowserWindow;
+ installWindowForegroundEvents(window);
+ focused = false;
+ callbacks.get("blur")!();
+ expect(send).toHaveBeenLastCalledWith("window:foreground-changed", false);
+ focused = true;
+ callbacks.get("focus")!();
+ expect(send).toHaveBeenLastCalledWith("window:foreground-changed", true);
+ });
+});
diff --git a/apps/desktop/src/main/window-foreground.ts b/apps/desktop/src/main/window-foreground.ts
new file mode 100644
index 0000000000..87a25973f5
--- /dev/null
+++ b/apps/desktop/src/main/window-foreground.ts
@@ -0,0 +1,20 @@
+import type { BrowserWindow } from "electron";
+
+export function windowForeground(window: BrowserWindow | null): boolean {
+ return !!window && !window.isDestroyed() && window.isVisible() &&
+ !window.isMinimized() && window.isFocused();
+}
+
+export function installWindowForegroundEvents(window: BrowserWindow): void {
+ const report = () => {
+ if (!window.isDestroyed()) {
+ window.webContents.send("window:foreground-changed", windowForeground(window));
+ }
+ };
+ window.on("focus", report);
+ window.on("blur", report);
+ window.on("show", report);
+ window.on("hide", report);
+ window.on("minimize", report);
+ window.on("restore", report);
+}
diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.ts
index 7ca59ad56f..d4002d0baf 100644
--- a/apps/desktop/src/preload/index.d.ts
+++ b/apps/desktop/src/preload/index.d.ts
@@ -73,6 +73,8 @@ interface DesktopAPI {
title: string;
body: string;
}) => void;
+ getWindowForeground: () => Promise<boolean>;
+ onWindowForegroundChanged: (callback: (foreground: boolean) => void) => () => void;
/** Update the OS dock / taskbar unread badge. Pass 0 to clear. */
setUnreadBadge: (count: number) => void;
/** Listen for inbox/chat navigation from notification clicks. Returns an unsubscribe function. */
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index 60cba4533c..9e54738dd4 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -198,6 +198,14 @@ const desktopAPI = {
title: string;
body: string;
}) => ipcRenderer.send("notification:show", payload),
+ getWindowForeground: (): Promise<boolean> => ipcRenderer.invoke("window:foreground"),
+ onWindowForegroundChanged: (callback: (foreground: boolean) => void) => {
+ const handler = (_event: Electron.IpcRendererEvent, foreground: unknown) => {
+ if (typeof foreground === "boolean") callback(foreground);
+ };
+ ipcRenderer.on("window:foreground-changed", handler);
+ return () => ipcRenderer.removeListener("window:foreground-changed", handler);
+ },
/**
* Update the OS dock / taskbar unread badge. Pass 0 to clear. Values
* above 99 render as "99+" (capping is handled in the main process).
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
index 8450387874..18c0b0a58f 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
@@ -185,7 +185,7 @@ function useInternalLinkHandler() {
}
/**
- * Mirrors the inbox badge and routes native notification clicks. Chat alerts
+ * Mirrors Inbox and Chat unread badges and routes native notification clicks. Chat alerts
* open Chat directly; inbox alerts retain their row selector. The shared path
* resolver uses the source workspace, and the navigation adapter performs a
* workspace switch when needed. Each destination owns its mark-read behavior.
diff --git a/packages/core/platform/index.ts b/packages/core/platform/index.ts
index ebdf9d3566..9c907a8ae2 100644
--- a/packages/core/platform/index.ts
+++ b/packages/core/platform/index.ts
@@ -13,6 +13,7 @@ export {
requestWebNotificationPermission,
showWebNotification,
showSystemNotification,
+ systemNotificationSuppressedByFocus,
systemNotificationPath,
type SystemNotificationPayload,
type WebNotificationPermission,
diff --git a/packages/core/platform/system-notification.ts b/packages/core/platform/system-notification.ts
index f2bd0d9247..4e5e386e20 100644
--- a/packages/core/platform/system-notification.ts
+++ b/packages/core/platform/system-notification.ts
@@ -6,9 +6,8 @@ import { paths } from "../paths/paths";
//
// The desktop app renders OS banners through its Electron main process
// (`window.desktopAPI.showNotification`); the web app has no such bridge, so it
-// uses the browser Notification API here. Realtime sync checks focus and the
-// source workspace's preferences for inbox and direct-chat events before
-// calling `showSystemNotification`.
+// uses the browser Notification API here. Realtime sync checks source-workspace
+// preferences and browser focus; native main owns desktop focus and dedupe.
//
// Lives in `packages/core` (not `packages/views`) because the caller
// (`handleInboxNew`) lives in core and `views` cannot be imported from core
@@ -40,10 +39,20 @@ export function systemNotificationPath(
return issueKey ? `${paths.workspace(slug).inbox()}?issue=${encodeURIComponent(issueKey)}` : null;
}
-export function showSystemNotification(payload: SystemNotificationPayload): void {
- const desktopAPI = (globalThis as unknown as {
+function getNativeNotificationAPI() {
+ return (globalThis as unknown as {
desktopAPI?: { showNotification?: (value: SystemNotificationPayload) => void };
}).desktopAPI;
+}
+
+/** Native main owns app-wide focus; Electron's DOM focus can remain stale. */
+export function systemNotificationSuppressedByFocus(): boolean {
+ return !getNativeNotificationAPI()?.showNotification &&
+ typeof document !== "undefined" && document.hasFocus();
+}
+
+export function showSystemNotification(payload: SystemNotificationPayload): void {
+ const desktopAPI = getNativeNotificationAPI();
if (desktopAPI?.showNotification) desktopAPI.showNotification(payload);
else showWebNotification(payload);
}
diff --git a/packages/core/realtime/chat-reply-notification.test.ts b/packages/core/realtime/chat-reply-notification.test.ts
index 4c9dcf4a0a..9aff690234 100644
--- a/packages/core/realtime/chat-reply-notification.test.ts
+++ b/packages/core/realtime/chat-reply-notification.test.ts
@@ -66,7 +66,14 @@ describe("chat reply OS notifications", () => {
expect(qc.getQueryCache().getAll().some((query) => query.queryKey.includes("inbox"))).toBe(false);
});
- it("suppresses focused replies and does not replay them after switching away", async () => {
+ it("forwards a stale focused renderer to native main's focus gate", async () => {
+ hasFocus.mockReturnValue(true);
+ await notify(reply());
+ expect(showNotification).toHaveBeenCalledTimes(1);
+ });
+
+ it("suppresses focused browser replies and does not replay them after switching away", async () => {
+ vi.stubGlobal("desktopAPI", undefined);
hasFocus.mockReturnValue(true);
await notify(reply());
hasFocus.mockReturnValue(false);
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 775ec0a2a9..7f61e8e6b9 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -62,6 +62,7 @@ import { workspaceKeys, workspaceListOptions } from "../workspace/queries";
import { isWorkspaceDeletePending } from "../workspace/pending-delete";
import {
showSystemNotification,
+ systemNotificationSuppressedByFocus,
type SystemNotificationPayload,
} from "../platform/system-notification";
import type { Workspace } from "../types/workspace";
@@ -585,7 +586,7 @@ export async function handleInboxNew(
// the user is already looking at Multica, the inbox sidebar's unread
// styling is enough — no need to interrupt with a banner. `desktopAPI`
// is injected by the preload script; its absence (web app) skips silently.
- if (typeof document !== "undefined" && document.hasFocus()) return;
+ if (systemNotificationSuppressedByFocus()) return;
// Resolve the source workspace's slug once: it pins BOTH the mute check
// and the deep link to the workspace the inbox item BELONGS to, never the
// currently active one. Reading `getCurrentSlug()` here was the source of
@@ -644,7 +645,7 @@ export function createChatReplyNotifier(
if (!payload.workspace_id || !messageId || !payload.chat_session_id || !userId || seen.has(messageId)) return;
seen.add(messageId);
if (seen.size > 1_000) seen.delete(seen.values().next().value!);
- if (typeof document !== "undefined" && document.hasFocus()) return;
+ if (systemNotificationSuppressedByFocus()) return;
const slug = await resolveInboxSourceSlug(qc, payload.workspace_id);
if (!slug) return;
@@ -654,7 +655,7 @@ export function createChatReplyNotifier(
} catch {
// Match the existing default-on system-notification behavior.
}
- if (getUserId() !== userId || (typeof document !== "undefined" && document.hasFocus())) return;
+ if (getUserId() !== userId || systemNotificationSuppressedByFocus()) return;
showSystemNotification({
slug,
itemId: `chat:${messageId}`,
diff --git a/packages/views/common/use-app-foreground.test.tsx b/packages/views/common/use-app-foreground.test.tsx
new file mode 100644
index 0000000000..e11436bb4e
--- /dev/null
+++ b/packages/views/common/use-app-foreground.test.tsx
@@ -0,0 +1,48 @@
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import { useAppForeground } from "./use-app-foreground";
+
+afterEach(() => { cleanup(); vi.restoreAllMocks(); delete (window as unknown as Record<string, unknown>).desktopAPI; });
+
+it("uses native focus even when Electron's document still reports focus", async () => {
+ vi.spyOn(document, "hasFocus").mockReturnValue(true);
+ vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
+ let report!: (foreground: boolean) => void;
+ const unsubscribe = vi.fn();
+ Object.defineProperty(window, "desktopAPI", { configurable: true, value: {
+ getWindowForeground: async () => false,
+ onWindowForegroundChanged: (callback: typeof report) => { report = callback; return unsubscribe; },
+ } });
+ const view = renderHook(useAppForeground);
+ await waitFor(() => expect(report).toBeTypeOf("function"));
+ expect(view.result.current).toBe(false);
+ act(() => report(true));
+ expect(view.result.current).toBe(true);
+ act(() => report(false));
+ expect(view.result.current).toBe(false);
+ view.unmount();
+ expect(unsubscribe).toHaveBeenCalledOnce();
+});
+
+it("does not let an initial native query overwrite a newer blur event", async () => {
+ let resolve!: (foreground: boolean) => void;
+ let report!: (foreground: boolean) => void;
+ Object.defineProperty(window, "desktopAPI", { configurable: true, value: {
+ getWindowForeground: () => new Promise<boolean>(r => { resolve = r; }),
+ onWindowForegroundChanged: (callback: typeof report) => { report = callback; return () => {}; },
+ } });
+ const view = renderHook(useAppForeground);
+ act(() => report(false));
+ await act(async () => resolve(true));
+ expect(view.result.current).toBe(false);
+});
+
+it("keeps browser foreground behavior based on DOM visibility and focus", () => {
+ const focused = vi.spyOn(document, "hasFocus").mockReturnValue(true);
+ vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
+ const view = renderHook(useAppForeground);
+ expect(view.result.current).toBe(true);
+ focused.mockReturnValue(false);
+ act(() => window.dispatchEvent(new Event("blur")));
+ expect(view.result.current).toBe(false);
+});
diff --git a/packages/views/common/use-app-foreground.ts b/packages/views/common/use-app-foreground.ts
index a7cc488599..f85d3ed35a 100644
--- a/packages/views/common/use-app-foreground.ts
+++ b/packages/views/common/use-app-foreground.ts
@@ -1,4 +1,18 @@
-import { useSyncExternalStore } from "react";
+import { useEffect, useState, useSyncExternalStore } from "react";
+
+interface NativeForegroundAPI {
+ getWindowForeground: () => Promise<boolean>;
+ onWindowForegroundChanged: (callback: (foreground: boolean) => void) => () => void;
+}
+
+function nativeForegroundAPI(): NativeForegroundAPI | undefined {
+ if (typeof window === "undefined") return undefined;
+ const api = (window as unknown as { desktopAPI?: Partial<NativeForegroundAPI> }).desktopAPI;
+ if (typeof api?.getWindowForeground === "function" && typeof api.onWindowForegroundChanged === "function") {
+ return api as NativeForegroundAPI;
+ }
+ return undefined;
+}
/**
* Whether the app window is actually in front of the user right now: the
@@ -13,8 +27,10 @@ import { useSyncExternalStore } from "react";
* 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
+ * Desktop uses the native window signal because Electron's DOM focus can
+ * remain true after the application loses OS focus. Until the initial native
+ * query resolves, keep replies unread. In a browser the DOM is authoritative.
+ * The `true` fallbacks below only apply where there is no window — 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
@@ -46,5 +62,21 @@ function getServerSnapshot(): boolean {
}
export function useAppForeground(): boolean {
- return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
+ const domForeground = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
+ const api = nativeForegroundAPI();
+ const [nativeForeground, setNativeForeground] = useState(false);
+ useEffect(() => {
+ if (!api) return;
+ let live = true;
+ let receivedEvent = false;
+ const unsubscribe = api.onWindowForegroundChanged((foreground) => {
+ receivedEvent = true;
+ setNativeForeground(foreground);
+ });
+ void api.getWindowForeground().then((foreground) => {
+ if (live && !receivedEvent) setNativeForeground(foreground);
+ }).catch(() => { /* Keep unread until native focus can be confirmed. */ });
+ return () => { live = false; unsubscribe(); };
+ }, [api]);
+ return api ? nativeForeground : domForeground;
}
diff --git a/packages/views/platform/use-desktop-unread-badge.test.tsx b/packages/views/platform/use-desktop-unread-badge.test.tsx
new file mode 100644
index 0000000000..375dd4d208
--- /dev/null
+++ b/packages/views/platform/use-desktop-unread-badge.test.tsx
@@ -0,0 +1,42 @@
+import type { ReactNode } from "react";
+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider, focusManager } from "@tanstack/react-query";
+import { afterEach, expect, it, vi } from "vitest";
+import { setApiInstance } from "@multica/core/api";
+import type { ApiClient } from "@multica/core/api/client";
+import { chatKeys } from "@multica/core/chat/queries";
+import type { ChatSession } from "@multica/core/types";
+import { useDesktopUnreadBadge } from "./use-desktop-unread-badge";
+
+afterEach(() => {
+ cleanup(); focusManager.setFocused(undefined);
+ delete (window as unknown as Record<string, unknown>).desktopAPI;
+ setApiInstance(undefined as unknown as ApiClient);
+});
+
+it("adds Chat messages to Inbox unread while backgrounded and clears read/logout counts", async () => {
+ let chatUnread = 0;
+ const listChatSessions = vi.fn(async () => [{ id: "chat-a", unread_count: chatUnread }] as ChatSession[]);
+ setApiInstance({
+ getInboxUnreadSummary: async () => [{ workspace_id: "ws-a", count: 2 }],
+ listChatSessions,
+ } as unknown as ApiClient);
+ const setUnreadBadge = vi.fn();
+ Object.defineProperty(window, "desktopAPI", { configurable: true, value: { setUnreadBadge } });
+ focusManager.setFocused(false);
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
+ const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
+ const view = renderHook(({ wsId }: { wsId: string | null }) => useDesktopUnreadBadge(wsId), {
+ wrapper, initialProps: { wsId: "ws-a" as string | null },
+ });
+ await waitFor(() => expect(setUnreadBadge).toHaveBeenLastCalledWith(2));
+ chatUnread = 3;
+ await act(async () => { await qc.invalidateQueries({ queryKey: chatKeys.sessions("ws-a") }); });
+ await waitFor(() => expect(setUnreadBadge).toHaveBeenLastCalledWith(5));
+ chatUnread = 0;
+ await act(async () => { await qc.invalidateQueries({ queryKey: chatKeys.sessions("ws-a") }); });
+ await waitFor(() => expect(setUnreadBadge).toHaveBeenLastCalledWith(2));
+ view.rerender({ wsId: null });
+ await waitFor(() => expect(setUnreadBadge).toHaveBeenLastCalledWith(0));
+ qc.clear();
+});
diff --git a/packages/views/platform/use-desktop-unread-badge.ts b/packages/views/platform/use-desktop-unread-badge.ts
index 1852b71b5b..41bd38135f 100644
--- a/packages/views/platform/use-desktop-unread-badge.ts
+++ b/packages/views/platform/use-desktop-unread-badge.ts
@@ -1,4 +1,7 @@
import { useEffect } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { chatSessionsOptions } from "@multica/core/chat/queries";
+import { countUnreadChatMessages } from "@multica/core/chat/unread";
import { useInboxUnreadCount } from "@multica/core/inbox/queries";
type BadgeCapableAPI = {
@@ -11,13 +14,18 @@ function getDesktopAPI(): BadgeCapableAPI | undefined {
}
/**
- * Mirror the inbox unread count onto the OS dock/taskbar badge. No-op on web
+ * Mirror Inbox + Chat unread counts onto the OS dock/taskbar badge. No-op on web
* (no `desktopAPI`) and on the login screen (no workspace ⇒ count defaults
* to 0, which clears any stale badge from a previous session). The badge is
* on screen while the window is minimized, so it keeps the summary live then.
*/
export function useDesktopUnreadBadge(wsId: string | null | undefined): void {
- const count = useInboxUnreadCount(wsId, { whileHidden: true });
+ const inboxCount = useInboxUnreadCount(wsId, { whileHidden: true });
+ const { data: sessions } = useQuery({
+ ...chatSessionsOptions(wsId ?? ""),
+ enabled: !!wsId,
+ });
+ const count = inboxCount + (wsId ? countUnreadChatMessages(sessions) : 0);
useEffect(() => {
getDesktopAPI()?.setUnreadBadge?.(count);
}, [count]);