Skip to content

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

Go

feat: add configurable chat reply notifications (MUL-9082) (#10424)

Bohan Jiang191e84be118c
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index d9c049831f..48a71d0a16 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -1026,7 +1026,9 @@ if (!gotTheLock) {
{
slug: payload.slug,
itemId: payload.itemId,
- issueKey: payload.issueKey,
+ ...(payload.chatSessionId
+ ? { chatSessionId: payload.chatSessionId }
+ : { issueKey: payload.issueKey }),
},
mainWindows.findByWorkspace(payload.slug),
);
diff --git a/apps/desktop/src/main/notification-gate.test.ts b/apps/desktop/src/main/notification-gate.test.ts
index 6d4b16fef6..c9a91f106b 100644
--- a/apps/desktop/src/main/notification-gate.test.ts
+++ b/apps/desktop/src/main/notification-gate.test.ts
@@ -33,6 +33,13 @@ describe("NotificationGate", () => {
});
describe("parseNativeNotificationPayload", () => {
+ it("accepts a direct Chat target without an inbox row", () => {
+ const payload = { slug: "acme", itemId: "chat:message-1", chatSessionId: "session-1", title: "Chat reply", body: "Done" };
+ expect(parseNativeNotificationPayload(payload)).toEqual(payload);
+ expect(parseNativeNotificationPayload({ ...payload, chatSessionId: "" })).toBeNull();
+ expect(parseNativeNotificationPayload({ ...payload, chatSessionId: 7 })).toBeNull();
+ });
+
it("rejects malformed renderer payloads before native side effects", () => {
expect(parseNativeNotificationPayload(null)).toBeNull();
expect(
diff --git a/apps/desktop/src/main/notification-gate.ts b/apps/desktop/src/main/notification-gate.ts
index c93d5420a2..034a5ed109 100644
--- a/apps/desktop/src/main/notification-gate.ts
+++ b/apps/desktop/src/main/notification-gate.ts
@@ -25,7 +25,8 @@ export class NotificationGate {
export interface NativeNotificationPayload {
slug: string;
itemId: string;
- issueKey: string;
+ issueKey?: string;
+ chatSessionId?: string;
title: string;
body: string;
}
@@ -35,15 +36,14 @@ export function parseNativeNotificationPayload(
): NativeNotificationPayload | null {
if (!value || typeof value !== "object") return null;
const candidate = value as Record<string, unknown>;
- const limits: Record<keyof NativeNotificationPayload, number> = {
+ const limits = {
slug: 256,
itemId: 256,
- issueKey: 256,
title: 512,
body: 2_000,
};
const result = {} as NativeNotificationPayload;
- for (const key of Object.keys(limits) as (keyof NativeNotificationPayload)[]) {
+ for (const key of Object.keys(limits) as (keyof typeof limits)[]) {
const field = candidate[key];
const mayBeEmpty = key === "slug" || key === "body";
if (
@@ -55,5 +55,9 @@ export function parseNativeNotificationPayload(
}
result[key] = field;
}
+ const targetKey = candidate.chatSessionId === undefined ? "issueKey" : "chatSessionId";
+ const target = candidate[targetKey];
+ if (typeof target !== "string" || !target.trim() || target.length > 256) return null;
+ result[targetKey] = target;
return result;
}
diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.ts
index a3fa134653..7ca59ad56f 100644
--- a/apps/desktop/src/preload/index.d.ts
+++ b/apps/desktop/src/preload/index.d.ts
@@ -64,22 +64,24 @@ interface DesktopAPI {
downloadURL: (url: string) => Promise<void>;
/** Hide macOS traffic lights for full-screen modals; restore when false. */
setImmersiveMode: (immersive: boolean) => Promise<void>;
- /** Show a native OS notification for a new inbox item. */
+ /** Show a native OS notification for an inbox item or chat reply. */
showNotification: (payload: {
slug: string;
itemId: string;
- issueKey: string;
+ issueKey?: string;
+ chatSessionId?: string;
title: string;
body: string;
}) => void;
/** Update the OS dock / taskbar unread badge. Pass 0 to clear. */
setUnreadBadge: (count: number) => void;
- /** Listen for "open inbox row" requests from notification clicks. Returns an unsubscribe function. */
+ /** Listen for inbox/chat navigation from notification clicks. Returns an unsubscribe function. */
onInboxOpen: (
callback: (payload: {
slug: string;
itemId: string;
- issueKey: string;
+ issueKey?: string;
+ chatSessionId?: string;
}) => void,
) => () => void;
/** Listen for native macOS back/forward swipe gestures. Returns an unsubscribe function. */
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index 22da568817..60cba4533c 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -186,18 +186,15 @@ const desktopAPI = {
setImmersiveMode: (immersive: boolean) =>
ipcRenderer.invoke("window:setImmersive", immersive),
/**
- * Show a native OS notification for a new inbox item. Fired from the
- * renderer only when the app is unfocused — in-focus feedback is the
- * inbox sidebar's unread styling. `slug`, `itemId`, and `issueKey` are
- * all round-tripped on click: slug pins routing to the source workspace
- * (the user may switch workspaces before clicking the banner), itemId
- * lets the renderer mark the row read, issueKey maps to the inbox URL
- * param.
+ * Show a native OS notification. The source workspace and either the inbox
+ * selector or chat session are round-tripped on click. Main owns focus
+ * gating and deduplication across windows.
*/
showNotification: (payload: {
slug: string;
itemId: string;
- issueKey: string;
+ issueKey?: string;
+ chatSessionId?: string;
title: string;
body: string;
}) => ipcRenderer.send("notification:show", payload),
@@ -208,16 +205,15 @@ const desktopAPI = {
setUnreadBadge: (count: number) =>
ipcRenderer.send("badge:set", Math.max(0, Math.floor(count))),
/**
- * Subscribe to "open this inbox row" requests sent by the main process
- * when the user clicks an OS notification banner. Returns an unsubscribe
- * function. The payload echoes the `slug`, `itemId`, and `issueKey` that
- * were passed to `showNotification`.
+ * Subscribe to inbox/chat navigation from an OS notification click.
+ * The existing channel also carries direct chat targets.
*/
onInboxOpen: (
callback: (payload: {
slug: string;
itemId: string;
- issueKey: string;
+ issueKey?: string;
+ chatSessionId?: string;
}) => void,
) => subscribeToMainRendererChannel("inbox:open", callback),
/** Listen for native macOS back/forward swipe gestures. */
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
index 87aae19536..8450387874 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
@@ -26,13 +26,13 @@ import {
import { SearchCommand } from "@multica/views/search";
import { FloatingChat } from "@multica/views/chat";
import { StarPrompt } from "@multica/views/star-prompt";
-import { WorkspaceSlugProvider, paths, useCurrentWorkspace } from "@multica/core/paths";
+import { WorkspaceSlugProvider, useCurrentWorkspace } from "@multica/core/paths";
import { workspaceListOptions } from "@multica/core/workspace";
import {
useNavigation,
type LinkClickIntent,
} from "@multica/views/navigation";
-import { getCurrentSlug, subscribeToCurrentSlug } from "@multica/core/platform";
+import { getCurrentSlug, subscribeToCurrentSlug, systemNotificationPath } from "@multica/core/platform";
import { useDesktopUnreadBadge } from "@multica/views/platform";
import { useT } from "@multica/views/i18n";
import {
@@ -185,26 +185,10 @@ function useInternalLinkHandler() {
}
/**
- * Bridge between the renderer and the Electron main process for inbox-level
- * OS integration. Mounted inside WorkspaceSlugProvider so it can resolve the
- * current workspace's id for the badge hook.
- *
- * Two responsibilities:
- * 1. Mirror the unread inbox count onto the dock/taskbar badge.
- * 2. When the user clicks an OS notification, open the notified
- * workspace's inbox focused on that item. The route uses the `slug`
- * that the notification was *emitted* with — not the currently active
- * workspace — so a notification from workspace A always opens A's
- * inbox even if the user has since switched to workspace B. Marking
- * the row read is handled by InboxPage's selected-item effect, which
- * covers both click-to-select and URL-param-select paths.
- *
- * The click routes through `useNavigation().push` — NOT the
- * `multica:navigate` event, whose handler `openTab`s into the ACTIVE
- * workspace's tab group. The navigation adapter detects a cross-workspace
- * path and translates it into `switchWorkspace(slug, path)`, so clicking a
- * workspace-A notification while B is active performs a real workspace
- * switch instead of mounting A's inbox inside B's tab group (#3766).
+ * Mirrors the inbox badge 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.
*/
function DesktopInboxBridge() {
const workspace = useCurrentWorkspace();
@@ -218,10 +202,9 @@ function DesktopInboxBridge() {
}, [push]);
useEffect(() => {
- return window.desktopAPI.onInboxOpen(({ slug, issueKey }) => {
- if (!slug) return;
- const inboxPath = `${paths.workspace(slug).inbox()}?issue=${encodeURIComponent(issueKey)}`;
- pushRef.current(inboxPath);
+ return window.desktopAPI.onInboxOpen((payload) => {
+ const path = systemNotificationPath(payload);
+ if (path) pushRef.current(path);
});
}, []);
diff --git a/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx b/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx
index 2209438f02..c2b2551bad 100644
--- a/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx
+++ b/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx
@@ -1,6 +1,6 @@
/**
- * Notification preferences subscreen. 6 inbox groups + system_notifications
- * toggle, each backed by an optimistic PATCH /api/notification-preferences.
+ * Notification preferences subscreen. Inbox groups and system delivery
+ * settings are backed by an optimistic PATCH /api/notification-preferences.
*
* Copy mirrors packages/views/settings/components/notifications-tab.tsx.
* Group labels describe the same server-side semantics as web; divergent
@@ -21,7 +21,7 @@ import { useUpdateNotificationPreferences } from "@/data/mutations/notification-
import { useT } from "@/lib/i18n";
const INBOX_GROUPS: {
- key: Exclude<NotificationGroupKey, "system_notifications">;
+ key: Exclude<NotificationGroupKey, "system_notifications" | "chat_replies">;
labelKey: string;
descriptionKey?: string;
}[] = [
@@ -137,25 +137,34 @@ 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">
{t("groups.system_notifications")}
</Text>
- <Text className="text-xs text-muted-foreground mt-0.5">
- {t("groups.system_description")}
- </Text>
</View>
<Switch
checked={systemEnabled}
- onCheckedChange={(checked) =>
- onToggle("system_notifications", checked)
- }
+ onCheckedChange={(checked) => onToggle("system_notifications", checked)}
/>
</View>
+ {systemEnabled && (
+ <>
+ <Separator />
+ <View className="flex-row items-center pl-8 pr-4 py-3 gap-3">
+ <View className="flex-1">
+ <Text className="text-base font-medium text-foreground">
+ {t("groups.chat_replies")}
+ </Text>
+ </View>
+ <Switch
+ checked={preferences.chat_replies !== "muted"}
+ onCheckedChange={(checked) => onToggle("chat_replies", checked)}
+ />
+ </View>
+ </>
+ )}
</Section>
</ScrollView>
);
diff --git a/apps/mobile/locales/en/settings.json b/apps/mobile/locales/en/settings.json
index 28926f9637..950b7ea572 100644
--- a/apps/mobile/locales/en/settings.json
+++ b/apps/mobile/locales/en/settings.json
@@ -82,6 +82,6 @@
"inbox_notifications": "Inbox notifications",
"system": "System",
"system_notifications": "System notifications",
- "system_description": "Account changes, security alerts, product updates."
+ "chat_replies": "Include chat replies"
}
}
diff --git a/apps/mobile/locales/zh-Hans/settings.json b/apps/mobile/locales/zh-Hans/settings.json
index bc9d2bedc3..87fa484152 100644
--- a/apps/mobile/locales/zh-Hans/settings.json
+++ b/apps/mobile/locales/zh-Hans/settings.json
@@ -82,7 +82,7 @@
"inbox_notifications": "收件箱通知",
"system": "系统",
"system_notifications": "系统通知",
- "system_description": "账号变更、安全提醒和产品更新。"
+ "chat_replies": "包含聊天回复"
},
"groups.assignments_description": "任务分配给我或取消分配给我时。",
"groups.mentions_description": "有人用 @ 提到你时,包括 @all 和 @squad。"
diff --git a/apps/mobile/locales/zh-Hant/settings.json b/apps/mobile/locales/zh-Hant/settings.json
index ced7545224..300b6ab88f 100644
--- a/apps/mobile/locales/zh-Hant/settings.json
+++ b/apps/mobile/locales/zh-Hant/settings.json
@@ -82,7 +82,7 @@
"inbox_notifications": "收件箱通知",
"system": "系統",
"system_notifications": "系統通知",
- "system_description": "帳號變更、安全提醒和產品更新。"
+ "chat_replies": "包含聊天回覆"
},
"groups.assignments_description": "任務分配給我或取消分配給我時。",
"groups.mentions_description": "有人用 @ 提到你時,包括 @all 和 @squad。"
diff --git a/apps/web/components/web-notification-bridge.tsx b/apps/web/components/web-notification-bridge.tsx
index f060a35787..52934b3ca6 100644
--- a/apps/web/components/web-notification-bridge.tsx
+++ b/apps/web/components/web-notification-bridge.tsx
@@ -3,22 +3,20 @@
import { useEffect, useRef } from "react";
import {
registerSystemNotificationClickHandler,
- type SystemNotificationPayload,
+ systemNotificationPath,
} from "@multica/core/platform";
-import { paths } from "@multica/core/paths";
import { useNavigation } from "@multica/views/navigation";
/**
- * Routes browser notification clicks to the source workspace's inbox, focused
- * on the clicked item. The web counterpart of the desktop `DesktopInboxBridge`:
+ * Routes browser notification clicks to the source workspace's inbox or chat.
+ * The web counterpart of the desktop `DesktopInboxBridge`:
* desktop receives the click via Electron IPC, web wires it through the
* Notification API's `onclick` (registered here into the core singleton).
*
* The route uses the `slug` the notification was emitted with — the SOURCE
- * workspace — not the active one, so a click always opens the right inbox even
+ * workspace — not the active one, so a click always opens the right target even
* after the user switches workspaces (#3766). An empty slug (unresolved
- * source) is ignored. Marking the row read is handled by InboxPage's
- * selected-item effect, which covers the `?issue=` URL-param path.
+ * source) is ignored. The destination handles its own mark-read behavior.
*/
export function WebNotificationBridge() {
const { push } = useNavigation();
@@ -31,10 +29,9 @@ export function WebNotificationBridge() {
useEffect(() => {
registerSystemNotificationClickHandler(
- ({ slug, issueKey }: SystemNotificationPayload) => {
- if (!slug) return;
- const inboxPath = `${paths.workspace(slug).inbox()}?issue=${encodeURIComponent(issueKey)}`;
- pushRef.current(inboxPath);
+ (payload) => {
+ const path = systemNotificationPath(payload);
+ if (path) pushRef.current(path);
},
);
return () => registerSystemNotificationClickHandler(null);
diff --git a/packages/core/notification-preferences/patch.test.ts b/packages/core/notification-preferences/patch.test.ts
index 76e75e0395..e1916cc19b 100644
--- a/packages/core/notification-preferences/patch.test.ts
+++ b/packages/core/notification-preferences/patch.test.ts
@@ -6,6 +6,16 @@ import {
} from "./patch";
describe("notification preference patches", () => {
+ it("persists, enables and rolls back chat replies independently of comments", () => {
+ const current = { comments: "muted" } as const;
+ const muted = { ...current, chat_replies: "muted" } as const;
+ expect(deriveNotificationPreferencePatch(current, muted)).toEqual({ chat_replies: "muted" });
+ expect(applyNotificationPreferencePatch(current, { chat_replies: "muted" })).toEqual(muted);
+ expect(deriveNotificationPreferencePatch(muted, current)).toEqual({ chat_replies: "all" });
+ expect(applyNotificationPreferencePatch(muted, { chat_replies: "all" })).toEqual(current);
+ expect(rollbackNotificationPreferencePatch(muted, { chat_replies: "muted" }, current)).toEqual(current);
+ });
+
it("sends only the changed key when another muted preference is present", () => {
expect(
deriveNotificationPreferencePatch(
diff --git a/packages/core/notification-preferences/patch.ts b/packages/core/notification-preferences/patch.ts
index cca2c0b024..c3d753bf0c 100644
--- a/packages/core/notification-preferences/patch.ts
+++ b/packages/core/notification-preferences/patch.ts
@@ -8,6 +8,7 @@ const NOTIFICATION_GROUP_KEYS: readonly NotificationGroupKey[] = [
"assignments",
"status_changes",
"comments",
+ "chat_replies",
"mentions",
"updates",
"new_issues",
diff --git a/packages/core/platform/index.ts b/packages/core/platform/index.ts
index aa82232cd8..ebdf9d3566 100644
--- a/packages/core/platform/index.ts
+++ b/packages/core/platform/index.ts
@@ -12,6 +12,8 @@ export {
getWebNotificationPermission,
requestWebNotificationPermission,
showWebNotification,
+ showSystemNotification,
+ systemNotificationPath,
type SystemNotificationPayload,
type WebNotificationPermission,
} from "./system-notification";
diff --git a/packages/core/platform/system-notification.test.ts b/packages/core/platform/system-notification.test.ts
index b0a52f2a5b..dcc12199df 100644
--- a/packages/core/platform/system-notification.test.ts
+++ b/packages/core/platform/system-notification.test.ts
@@ -5,6 +5,7 @@ import {
registerSystemNotificationClickHandler,
requestWebNotificationPermission,
showWebNotification,
+ systemNotificationPath,
type SystemNotificationPayload,
} from "./system-notification";
@@ -95,6 +96,24 @@ describe("requestWebNotificationPermission", () => {
});
describe("showWebNotification", () => {
+ it("opens a chat alert directly in Chat while preserving inbox routing", () => {
+ expect(systemNotificationPath({ slug: "workspace-a", chatSessionId: "session-1" })).toBe("/workspace-a/chat?session=session-1");
+ expect(systemNotificationPath({ slug: "workspace-a", issueKey: "issue-1" })).toBe("/workspace-a/inbox?issue=issue-1");
+ expect(systemNotificationPath({ slug: "", chatSessionId: "session-1" })).toBeNull();
+ expect(systemNotificationPath({ slug: "workspace-a" })).toBeNull();
+ });
+
+ it("routes browser chat notification clicks without an inbox selector", () => {
+ installWindow(FakeNotification);
+ const onClick = vi.fn();
+ registerSystemNotificationClickHandler(onClick);
+ const chat = { slug: "workspace-a", itemId: "chat:message-1", chatSessionId: "session-1", title: "Review changes", body: "Done" };
+ showWebNotification(chat);
+ created[0]?.instance.onclick?.();
+ expect(onClick).toHaveBeenCalledWith(chat);
+ expect(systemNotificationPath(onClick.mock.calls[0]![0])).toBe("/workspace-a/chat?session=session-1");
+ });
+
it("does nothing when the API is unavailable", () => {
expect(() => showWebNotification(payload())).not.toThrow();
expect(created).toHaveLength(0);
diff --git a/packages/core/platform/system-notification.ts b/packages/core/platform/system-notification.ts
index e692b15c17..f2bd0d9247 100644
--- a/packages/core/platform/system-notification.ts
+++ b/packages/core/platform/system-notification.ts
@@ -1,13 +1,14 @@
"use client";
+import { paths } from "../paths/paths";
+
// Native system notification bridge for the WEB app.
//
// 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. `handleInboxNew` (realtime sync) is
-// the single decision point — it already gates on focus + the source
-// workspace's mute preference — and calls `showWebNotification` as the web path
-// when no `desktopAPI` is present.
+// 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`.
//
// Lives in `packages/core` (not `packages/views`) because the caller
// (`handleInboxNew`) lives in core and `views` cannot be imported from core
@@ -21,14 +22,32 @@ export interface SystemNotificationPayload {
* then a no-op rather than routing to the wrong workspace (#3766).
*/
slug: string;
- /** Inbox row id — lets the click mark the item read. */
+ /** Stable delivery ID: an inbox row ID or a chat reply's message ID. */
itemId: string;
/** `?issue=<…>` selector for the inbox page (issue id, else the item id). */
- issueKey: string;
+ issueKey?: string;
+ /** Chat alerts open Chat directly, without an inbox item. */
+ chatSessionId?: string;
title: string;
body: string;
}
+export function systemNotificationPath(
+ { slug, issueKey, chatSessionId }: Pick<SystemNotificationPayload, "slug" | "issueKey" | "chatSessionId">,
+): string | null {
+ if (!slug) return null;
+ if (chatSessionId) return `${paths.workspace(slug).chat()}?session=${encodeURIComponent(chatSessionId)}`;
+ return issueKey ? `${paths.workspace(slug).inbox()}?issue=${encodeURIComponent(issueKey)}` : null;
+}
+
+export function showSystemNotification(payload: SystemNotificationPayload): void {
+ const desktopAPI = (globalThis as unknown as {
+ desktopAPI?: { showNotification?: (value: SystemNotificationPayload) => void };
+ }).desktopAPI;
+ if (desktopAPI?.showNotification) desktopAPI.showNotification(payload);
+ else showWebNotification(payload);
+}
+
type ClickHandler = (payload: SystemNotificationPayload) => void;
// Module-level singleton — mirrors how the desktop preload registers its
@@ -38,7 +57,7 @@ let clickHandler: ClickHandler | null = null;
/**
* Register how a clicked web notification routes (focus + navigate to the
- * source workspace's inbox, focused on the item). Called once by the web app
+ * source workspace's inbox or chat). Called once by the web app
* shell; pass `null` to unregister. Desktop does NOT use this — it routes
* through its own Electron IPC bridge (`onInboxOpen`).
*/
@@ -88,9 +107,9 @@ export async function requestWebNotificationPermission(): Promise<WebNotificatio
}
/**
- * Show a native browser notification for a new inbox item. No-op unless the
+ * Show a native browser notification. No-op unless the
* Notification API is supported AND permission is "granted" — the caller
- * (`handleInboxNew`) owns the WHETHER (focus + mute gating); this owns only the
+ * owns focus and mute checks; this owns only the
* rendering. Clicking the banner focuses the tab and routes via the registered
* click handler.
*/
@@ -101,8 +120,7 @@ export function showWebNotification(payload: SystemNotificationPayload): void {
try {
notification = new ctor(payload.title, {
body: payload.body,
- // Collapse repeat banners for the same inbox row (e.g. a reconnect
- // replays the `inbox:new` event).
+ // Collapse repeated delivery of the same inbox item or chat reply.
tag: payload.itemId,
});
} catch {
diff --git a/packages/core/realtime/chat-reply-notification.test.ts b/packages/core/realtime/chat-reply-notification.test.ts
new file mode 100644
index 0000000000..4c9dcf4a0a
--- /dev/null
+++ b/packages/core/realtime/chat-reply-notification.test.ts
@@ -0,0 +1,110 @@
+// @vitest-environment node
+import { QueryClient } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { notificationPreferenceKeys } from "../notification-preferences/queries";
+import type { NotificationPreferences } from "../types/notification-preference";
+import type { ChatReplyNotificationPayload } from "../types/events";
+import { workspaceKeys } from "../workspace/queries";
+import { createChatReplyNotifier } from "./use-realtime-sync";
+
+function reply(overrides: Partial<ChatReplyNotificationPayload> = {}): ChatReplyNotificationPayload {
+ return {
+ chat_session_id: "session-1", message_id: "message-1", body: "Review is complete",
+ workspace_id: "ws-a", title: "Review changes", ...overrides,
+ };
+}
+
+describe("chat reply OS notifications", () => {
+ let qc: QueryClient;
+ let userId: string | undefined;
+ let notify: ReturnType<typeof createChatReplyNotifier>;
+ const showNotification = vi.fn();
+ const hasFocus = vi.fn();
+ const workspaces = [{ id: "ws-a", slug: "workspace-a" }, { id: "ws-b", slug: "workspace-b" }];
+
+ function preferences(value: NotificationPreferences) {
+ qc.setQueryData(notificationPreferenceKeys.all("ws-a"), { workspace_id: "ws-a", preferences: value });
+ }
+
+ beforeEach(() => {
+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ qc.setQueryData(workspaceKeys.list(), workspaces);
+ preferences({});
+ userId = "user-a";
+ notify = createChatReplyNotifier(qc, () => userId);
+ showNotification.mockReset();
+ hasFocus.mockReset().mockReturnValue(false);
+ vi.stubGlobal("desktopAPI", { showNotification });
+ vi.stubGlobal("document", { hasFocus });
+ });
+
+ afterEach(() => {
+ qc.clear();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ it.each([
+ [{}, true],
+ [{ comments: "muted" }, true],
+ [{ chat_replies: "muted" }, false],
+ [{ system_notifications: "muted" }, false],
+ ] as [NotificationPreferences, boolean][])("respects source-workspace preferences %j", async (prefs, visible) => {
+ preferences(prefs);
+ qc.setQueryData(notificationPreferenceKeys.all("ws-b"), { preferences: { system_notifications: "muted" } });
+ await notify(reply());
+ expect(showNotification).toHaveBeenCalledTimes(visible ? 1 : 0);
+ if (visible) expect(showNotification).toHaveBeenCalledWith({
+ slug: "workspace-a", itemId: "chat:message-1", chatSessionId: "session-1", title: "Review changes", body: "Review is complete",
+ });
+ });
+
+ it("does not generate inbox side effects", async () => {
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+ await notify(reply());
+ expect(invalidate).not.toHaveBeenCalled();
+ 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 () => {
+ hasFocus.mockReturnValue(true);
+ await notify(reply());
+ hasFocus.mockReturnValue(false);
+ await notify(reply());
+ expect(showNotification).not.toHaveBeenCalled();
+ });
+
+ it("deduplicates completion replay while allowing the next reply", async () => {
+ await Promise.all([notify(reply()), notify(reply())]);
+ expect(showNotification).toHaveBeenCalledTimes(1);
+ await notify(reply({ message_id: "message-2" }));
+ expect(showNotification).toHaveBeenCalledTimes(2);
+ });
+
+ it("supports attachment-only replies", async () => {
+ await notify(reply({ body: "" }));
+ expect(showNotification).toHaveBeenCalledWith(expect.objectContaining({ body: "", chatSessionId: "session-1" }));
+ });
+
+ it("ignores alerts without a source workspace or message", async () => {
+ await notify(reply({ workspace_id: "" }));
+ await notify(reply({ message_id: "" }));
+ expect(showNotification).not.toHaveBeenCalled();
+ });
+
+ it("drops a pending alert after the account changes", async () => {
+ let resolveWorkspaces!: (value: unknown) => void;
+ vi.spyOn(qc, "ensureQueryData").mockImplementationOnce(() => new Promise((resolve) => { resolveWorkspaces = resolve; }));
+ const pending = notify(reply());
+ userId = "user-b";
+ resolveWorkspaces(workspaces);
+ await pending;
+ expect(showNotification).not.toHaveBeenCalled();
+ });
+
+ it("does not guess a workspace when the source is unavailable", async () => {
+ qc.setQueryData(workspaceKeys.list(), [workspaces[1]]);
+ await notify(reply());
+ expect(showNotification).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 95065f3fe1..775ec0a2a9 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -61,7 +61,7 @@ import {
import { workspaceKeys, workspaceListOptions } from "../workspace/queries";
import { isWorkspaceDeletePending } from "../workspace/pending-delete";
import {
- showWebNotification,
+ showSystemNotification,
type SystemNotificationPayload,
} from "../platform/system-notification";
import type { Workspace } from "../types/workspace";
@@ -120,6 +120,7 @@ import type {
TaskFailedPayload,
TaskCancelledPayload,
ChatDonePayload,
+ ChatReplyNotificationPayload,
ChatQuickActionsPayload,
ChatQuickActionsPendingState,
ChatQuickActionsFailureState,
@@ -629,21 +630,39 @@ export async function handleInboxNew(
title: item.title,
body: item.body ?? "",
};
- const desktopAPI = (
- globalThis as unknown as {
- desktopAPI?: {
- showNotification?: (payload: SystemNotificationPayload) => void;
- };
+ showSystemNotification(payload);
+}
+
+export function createChatReplyNotifier(
+ qc: QueryClient,
+ getUserId: () => string | undefined,
+): (payload: ChatReplyNotificationPayload) => Promise<void> {
+ const seen = new Set<string>();
+ return async (payload) => {
+ const messageId = payload.message_id;
+ const userId = getUserId();
+ 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;
+
+ const slug = await resolveInboxSourceSlug(qc, payload.workspace_id);
+ if (!slug) return;
+ try {
+ const { preferences } = await qc.ensureQueryData(notificationPreferenceOptions(payload.workspace_id, slug));
+ if (preferences.system_notifications === "muted" || preferences.chat_replies === "muted") return;
+ } catch {
+ // Match the existing default-on system-notification behavior.
}
- ).desktopAPI;
- if (desktopAPI?.showNotification) {
- // Desktop: native OS banner rendered by the Electron main process.
- desktopAPI.showNotification(payload);
- return;
- }
- // Web: the browser Notification API. No-op without granted permission or on
- // SSR — the in-app inbox + unread badge still reflect the new item.
- showWebNotification(payload);
+ if (getUserId() !== userId || (typeof document !== "undefined" && document.hasFocus())) return;
+ showSystemNotification({
+ slug,
+ itemId: `chat:${messageId}`,
+ chatSessionId: payload.chat_session_id,
+ title: payload.title,
+ body: payload.body,
+ });
+ };
}
/**
@@ -1103,7 +1122,7 @@ export function useRealtimeSync(
"subscriber:added", "subscriber:removed",
"daemon:heartbeat",
// Chat events are handled explicitly below; do not double-invalidate.
- "chat:message", "chat:done", "chat:quick_actions", "chat:cancel_finalized", "chat:session_read",
+ "chat:message", "chat:done", "chat:reply_notification", "chat:quick_actions", "chat:cancel_finalized", "chat:session_read",
"chat:session_created", "chat:session_deleted", "chat:session_updated",
// task:message stays out of the prefix path because it fires per
// streamed message during a long run — invalidating the snapshot on
@@ -1679,6 +1698,10 @@ export function useRealtimeSync(
// by the task lifecycle handlers below (MUL-4159).
});
+ const notifyChatReply = createChatReplyNotifier(qc, () => authStore.getState().user?.id);
+ const unsubChatReplyNotification = ws.on("chat:reply_notification", (p) => {
+ void notifyChatReply(p as ChatReplyNotificationPayload);
+ });
const unsubChatDone = ws.on("chat:done", (p) => {
const payload = p as ChatDonePayload;
chatWsLogger.info("chat:done (global)", {
@@ -1962,6 +1985,7 @@ export function useRealtimeSync(
unsubTaskMessage();
unsubChatMessage();
unsubChatDone();
+ unsubChatReplyNotification();
unsubChatQuickActions();
unsubChatCancelFinalized();
unsubTaskQueued();
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index 1dcdea400b..6a818bd85d 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -60,6 +60,7 @@ export type WSEventType =
| "issue_reaction:removed"
| "chat:message"
| "chat:done"
+ | "chat:reply_notification"
| "chat:quick_actions"
| "chat:cancel_finalized"
| "chat:session_created"
@@ -478,9 +479,20 @@ export interface ChatMessageEventPayload {
created_at: string;
}
+/** Owner-only system alert, also received while connected to another workspace. */
+export interface ChatReplyNotificationPayload {
+ workspace_id: string;
+ chat_session_id: string;
+ message_id: string;
+ title: string;
+ body: string;
+}
+
export interface ChatDonePayload {
chat_session_id: string;
task_id: string;
+ /** Optional OS-alert context for completed direct-chat replies. */
+ notification?: { workspace_id: string; title: string };
/**
* Server populates these from the freshly-persisted assistant ChatMessage
* row so the WS handler can write it into the messages cache inline. Older
@@ -681,6 +693,7 @@ export interface WSEventPayloadMap {
"activity:created": ActivityCreatedPayload;
"chat:message": ChatMessageEventPayload;
"chat:done": ChatDonePayload;
+ "chat:reply_notification": ChatReplyNotificationPayload;
"chat:quick_actions": ChatQuickActionsPayload;
"chat:cancel_finalized": ChatCancelFinalizedPayload;
"chat:session_created": ChatSessionCreatedPayload;
diff --git a/packages/core/types/notification-preference.ts b/packages/core/types/notification-preference.ts
index 979df5ff3a..9365017198 100644
--- a/packages/core/types/notification-preference.ts
+++ b/packages/core/types/notification-preference.ts
@@ -2,6 +2,7 @@ export type NotificationGroupKey =
| "assignments"
| "status_changes"
| "comments"
+ | "chat_replies"
| "mentions"
| "updates"
| "new_issues"
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 0e7564d6c8..ec7fd2b923 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -856,6 +856,9 @@
"agent_activity": {
"label": "Agent activity",
"description": "When an agent run fails"
+ },
+ "chat_replies": {
+ "label": "Include chat replies"
}
},
"system": {
@@ -864,7 +867,7 @@
},
"browser": {
"label": "Browser notifications",
- "hint": "Allow this browser to show notification banners for new inbox items.",
+ "hint": "Allow this browser to show banners for Inbox notifications and chat replies.",
"enable": "Enable",
"granted": "This browser can show notification banners.",
"denied": "Blocked by your browser. Enable notifications for this site in your browser settings.",
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index d8b342f50c..21dc29736d 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -856,6 +856,9 @@
"agent_activity": {
"label": "Actividad de agentes",
"description": "Cuando falla una ejecución de agente"
+ },
+ "chat_replies": {
+ "label": "Incluir respuestas del chat"
}
},
"system": {
@@ -864,7 +867,7 @@
},
"browser": {
"label": "Notificaciones del navegador",
- "hint": "Permite que este navegador muestre avisos de notificación para nuevos elementos de la bandeja.",
+ "hint": "Permite que este navegador muestre avisos para las notificaciones de la bandeja de entrada y las respuestas del chat.",
"enable": "Activar",
"granted": "Este navegador puede mostrar avisos de notificación.",
"denied": "Bloqueado por tu navegador. Activa las notificaciones para este sitio en la configuración del navegador.",
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index c353152e15..00a3e172e5 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -856,6 +856,9 @@
"agent_activity": {
"label": "Activité des agents",
"description": "Lorsqu'une exécution d'agent échoue"
+ },
+ "chat_replies": {
+ "label": "Inclure les réponses du chat"
}
},
"system": {
@@ -864,7 +867,7 @@
},
"browser": {
"label": "Notifications du navigateur",
- "hint": "Autoriser ce navigateur à afficher des bannières de notification pour les nouveaux éléments de la boîte de réception.",
+ "hint": "Autorisez ce navigateur à afficher des bannières pour les notifications de la boîte de réception et les réponses du chat.",
"enable": "Activer",
"granted": "Ce navigateur peut afficher des bannières de notification.",
"denied": "Bloqué par votre navigateur. Activez les notifications pour ce site dans ses réglages.",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 39b3ad9a56..0cbebd98e0 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -847,6 +847,9 @@
"agent_activity": {
"label": "エージェントのアクティビティ",
"description": "エージェントの実行が失敗したとき"
+ },
+ "chat_replies": {
+ "label": "チャットの返信を含める"
}
},
"system": {
@@ -855,7 +858,7 @@
},
"browser": {
"label": "ブラウザ通知",
- "hint": "このブラウザで新しいインボックス項目の通知バナーを表示できるようにします。",
+ "hint": "受信トレイの通知とチャットの返信のバナー表示を、このブラウザに許可します。",
"enable": "有効にする",
"granted": "このブラウザは通知バナーを表示できます。",
"denied": "ブラウザによってブロックされています。ブラウザの設定でこのサイトの通知を許可してください。",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 02f310f41c..c1ec96bbd9 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -847,6 +847,9 @@
"agent_activity": {
"label": "에이전트 활동",
"description": "에이전트 실행이 실패할 때"
+ },
+ "chat_replies": {
+ "label": "채팅 답변 포함"
}
},
"system": {
@@ -855,7 +858,7 @@
},
"browser": {
"label": "브라우저 알림",
- "hint": "이 브라우저에서 새 인박스 항목에 대한 알림 배너를 표시하도록 허용합니다.",
+ "hint": "이 브라우저에서 받은편지함 알림과 채팅 답변의 배너를 표시하도록 허용합니다.",
"enable": "사용",
"granted": "이 브라우저에서 알림 배너를 표시할 수 있습니다.",
"denied": "브라우저에서 차단되었습니다. 브라우저 설정에서 이 사이트의 알림을 허용하세요.",
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index 12f13295d7..8626bfc497 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -851,7 +851,7 @@
},
"browser": {
"label": "Уведомления браузера",
- "hint": "Разрешить этому браузеру показывать баннеры уведомлений для новых элементов во входящих.",
+ "hint": "Разрешите этому браузеру показывать баннеры для уведомлений входящих и ответов в чате.",
"enable": "Включить",
"granted": "Этот браузер может показывать баннеры уведомлений.",
"denied": "Заблокировано вашим браузером. Включите уведомления для этого сайта в настройках браузера.",
@@ -885,6 +885,9 @@
"new_issues": {
"label": "Новые задачи",
"description": "Когда в проекте, на который вы подписаны, создаётся задача"
+ },
+ "chat_replies": {
+ "label": "Включать ответы в чате"
}
}
},
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 5a5eb3ec80..77a2978fc4 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -847,6 +847,9 @@
"agent_activity": {
"label": "智能体活动",
"description": "智能体运行失败时"
+ },
+ "chat_replies": {
+ "label": "包含聊天回复"
}
},
"system": {
@@ -855,7 +858,7 @@
},
"browser": {
"label": "浏览器通知",
- "hint": "允许当前浏览器为新的收件箱条目弹出通知横幅。",
+ "hint": "允许此浏览器为收件箱通知和聊天回复显示横幅。",
"enable": "启用",
"granted": "当前浏览器可以弹出通知横幅。",
"denied": "已被浏览器拦截。请在浏览器设置中为本站点开启通知权限。",
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index f07eb2b9bc..590cbed8c5 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -847,6 +847,9 @@
"agent_activity": {
"label": "AI 代理活動",
"description": "AI 代理執行失敗時"
+ },
+ "chat_replies": {
+ "label": "包含聊天回覆"
}
},
"system": {
@@ -855,7 +858,7 @@
},
"browser": {
"label": "瀏覽器通知",
- "hint": "允許當前瀏覽器為新的收件箱條目彈出通知橫幅。",
+ "hint": "允許此瀏覽器為收件匣通知和聊天回覆顯示橫幅。",
"enable": "啟用",
"granted": "當前瀏覽器可以彈出通知橫幅。",
"denied": "已被瀏覽器攔截。請在瀏覽器設定中為本站點開啟通知權限。",
diff --git a/packages/views/settings/components/notifications-tab.test.tsx b/packages/views/settings/components/notifications-tab.test.tsx
new file mode 100644
index 0000000000..e6ac43e699
--- /dev/null
+++ b/packages/views/settings/components/notifications-tab.test.tsx
@@ -0,0 +1,56 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render, screen, within } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { I18nProvider } from "@multica/core/i18n/react";
+import { notificationPreferenceKeys } from "@multica/core/notification-preferences/queries";
+import enSettings from "../../locales/en/settings.json";
+import { NotificationsTab } from "./notifications-tab";
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-a" }));
+vi.mock("@multica/core/paths", () => ({ useCurrentWorkspace: () => ({ id: "ws-a", name: "Acme" }) }));
+vi.mock("@multica/core/notification-preferences/mutations", () => ({
+ useUpdateNotificationPreferences: () => ({ mutate: vi.fn() }),
+}));
+vi.mock("./browser-notification-setting", () => ({ BrowserNotificationSetting: () => null }));
+
+afterEach(cleanup);
+
+describe("notification setting hierarchy", () => {
+ it.each([
+ { systemMuted: false, chatMuted: false },
+ { systemMuted: false, chatMuted: true },
+ { systemMuted: true, chatMuted: false },
+ { systemMuted: true, chatMuted: true },
+ ])("nests chat replies under system notifications: %j", ({ systemMuted, chatMuted }) => {
+ const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } });
+ qc.setQueryData(notificationPreferenceKeys.all("ws-a"), {
+ workspace_id: "ws-a",
+ preferences: {
+ ...(systemMuted ? { system_notifications: "muted" } : {}),
+ ...(chatMuted ? { chat_replies: "muted" } : {}),
+ },
+ });
+ render(
+ <QueryClientProvider client={qc}>
+ <I18nProvider locale="en" resources={{ en: { settings: enSettings } }}>
+ <NotificationsTab />
+ </I18nProvider>
+ </QueryClientProvider>,
+ );
+ expect(screen.queryByRole("region", { name: "Chat" })).toBeNull();
+ const system = screen.getByRole("region", { name: "System Notifications" });
+ if (systemMuted) {
+ expect(within(system).queryByRole("switch", { name: "Include chat replies" })).toBeNull();
+ expect(within(system).getAllByRole("switch")).toHaveLength(1);
+ } else {
+ const replies = within(system).getByRole("switch", { name: "Include chat replies" });
+ if (chatMuted) expect(replies).not.toBeChecked();
+ else expect(replies).toBeChecked();
+ expect(within(system).getAllByRole("switch")).toHaveLength(2);
+ }
+ expect(within(system).queryByText("When an agent finishes replying in a chat.")).toBeNull();
+ expect(within(system).queryByText("Enable system notifications first.")).toBeNull();
+ expect(within(system).queryByText("Applies to Inbox notifications and chat replies.")).toBeNull();
+ qc.clear();
+ });
+});
diff --git a/packages/views/settings/components/notifications-tab.tsx b/packages/views/settings/components/notifications-tab.tsx
index 3b5c847d02..1b9b9e4e38 100644
--- a/packages/views/settings/components/notifications-tab.tsx
+++ b/packages/views/settings/components/notifications-tab.tsx
@@ -88,18 +88,32 @@ export function NotificationsTab() {
<SettingsSection
title={t(($) => $.notifications.system.title)}
+ anchor={systemEnabled ? undefined : "chat_replies"}
>
<SettingsCard>
<SettingsRow
anchor="system"
label={t(($) => $.notifications.system.label)}
>
+ <Switch
+ checked={systemEnabled}
+ aria-label={t(($) => $.notifications.system.label)}
+ onCheckedChange={(checked) => handleToggle("system_notifications", checked)}
+ />
+ </SettingsRow>
+ {systemEnabled && (
+ <SettingsRow
+ anchor="chat_replies"
+ className="pl-8"
+ label={t(($) => $.notifications.groups.chat_replies.label)}
+ >
<Switch
- checked={systemEnabled}
- aria-label={t(($) => $.notifications.system.label)}
- onCheckedChange={(checked) => handleToggle("system_notifications", checked)}
+ checked={preferences.chat_replies !== "muted"}
+ aria-label={t(($) => $.notifications.groups.chat_replies.label)}
+ onCheckedChange={(checked) => handleToggle("chat_replies", checked)}
/>
- </SettingsRow>
+ </SettingsRow>
+ )}
</SettingsCard>
{/* Web-only: the browser permission banners require. Renders nothing on
diff --git a/packages/views/settings/components/use-settings-search-index.ts b/packages/views/settings/components/use-settings-search-index.ts
index 1f956db3c0..65b208b236 100644
--- a/packages/views/settings/components/use-settings-search-index.ts
+++ b/packages/views/settings/components/use-settings-search-index.ts
@@ -181,6 +181,11 @@ export function useSettingsSearchIndex(
title: t(($) => $.notifications.groups[group].label),
description: t(($) => $.notifications.groups[group].description),
})),
+ {
+ tab: "notifications",
+ anchor: "chat_replies",
+ title: t(($) => $.notifications.groups.chat_replies.label),
+ },
{
tab: "notifications",
anchor: "system",
diff --git a/server/cmd/server/chat_reply_notifications.go b/server/cmd/server/chat_reply_notifications.go
new file mode 100644
index 0000000000..896c998a26
--- /dev/null
+++ b/server/cmd/server/chat_reply_notifications.go
@@ -0,0 +1,57 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "strings"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/realtime"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+type chatReplyMembership interface {
+ IsMember(context.Context, string, string) (bool, error)
+}
+
+// Completion content keeps its workspace-member scope. Only this bounded alert
+// reaches the owner's connections in other workspaces, after checking current
+// membership of the source workspace. It never creates an Inbox item.
+func registerChatReplyNotifications(bus *events.Bus, b realtime.Broadcaster, membership chatReplyMembership) {
+ bus.Subscribe(protocol.EventChatDone, func(e events.Event) {
+ p, ok := e.Payload.(protocol.ChatDonePayload)
+ if !ok || p.Notification == nil || p.MessageID == "" || p.ChatSessionID == "" ||
+ e.ChatSessionOwnerID == "" || e.WorkspaceID == "" || membership == nil ||
+ p.Notification.WorkspaceID != e.WorkspaceID || p.ChatSessionID != e.ChatSessionID {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ member, err := membership.IsMember(ctx, e.ChatSessionOwnerID, e.WorkspaceID)
+ if err != nil || !member {
+ if err != nil {
+ slog.Warn("chat reply alert membership lookup failed", "workspace_id", e.WorkspaceID, "error", err)
+ }
+ return
+ }
+ preview := []rune(strings.Join(strings.Fields(p.Content), " "))
+ if len(preview) > 200 {
+ preview = append(preview[:200], '…')
+ }
+ payload := protocol.ChatReplyNotificationPayload{
+ WorkspaceID: e.WorkspaceID, ChatSessionID: p.ChatSessionID, MessageID: p.MessageID,
+ Title: p.Notification.Title, Body: string(preview),
+ }
+ data, err := json.Marshal(map[string]any{
+ "type": protocol.EventChatReplyNotification, "payload": payload,
+ "actor_id": e.ActorID, "actor_type": e.ActorType,
+ })
+ if err != nil {
+ return
+ }
+ realtime.M.RecordEvent(protocol.EventChatReplyNotification)
+ b.SendToUser(e.ChatSessionOwnerID, data)
+ })
+}
diff --git a/server/cmd/server/chat_reply_notifications_test.go b/server/cmd/server/chat_reply_notifications_test.go
new file mode 100644
index 0000000000..db3df60d8a
--- /dev/null
+++ b/server/cmd/server/chat_reply_notifications_test.go
@@ -0,0 +1,168 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/realtime"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+type chatMembershipFunc func(context.Context, string, string) (bool, error)
+
+func (f chatMembershipFunc) IsMember(ctx context.Context, userID, workspaceID string) (bool, error) {
+ return f(ctx, userID, workspaceID)
+}
+
+func chatAlertEvent() events.Event {
+ return events.Event{
+ Type: protocol.EventChatDone, WorkspaceID: "source", ChatSessionOwnerID: "owner", ChatSessionID: "session",
+ Payload: protocol.ChatDonePayload{
+ ChatSessionID: "session", MessageID: "message", Content: "\n" + strings.Repeat("回", 250),
+ Notification: &protocol.ChatReplyNotification{WorkspaceID: "source", Title: "Private chat"},
+ },
+ }
+}
+
+func TestChatReplyAlertChecksSourceMembership(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ member bool
+ err error
+ }{
+ {"member", true, nil}, {"removed", false, nil}, {"lookup failure", false, errors.New("unavailable")},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ bus := events.New()
+ fb := &fakeBroadcaster{}
+ registerListeners(bus, fb)
+ registerChatReplyNotifications(bus, fb, chatMembershipFunc(func(ctx context.Context, userID, workspaceID string) (bool, error) {
+ if userID != "owner" || workspaceID != "source" {
+ t.Fatalf("membership checked against %s/%s", workspaceID, userID)
+ }
+ if _, bounded := ctx.Deadline(); !bounded {
+ t.Fatal("membership lookup must have a deadline")
+ }
+ return tc.member, tc.err
+ }))
+ bus.Publish(chatAlertEvent())
+ if len(fb.scopeCalls) != 1 || fb.scopeCalls[0].scopeID != realtime.WorkspaceMemberScopeID("source", "owner") {
+ t.Fatalf("full chat content changed scope: %+v", fb.scopeCalls)
+ }
+ if !tc.member || tc.err != nil {
+ if len(fb.userCalls) != 0 {
+ t.Fatal("alert delivered without source membership")
+ }
+ return
+ }
+ if len(fb.userCalls) != 1 || fb.userCalls[0].userID != "owner" || len(fb.userCalls[0].exclude) != 0 {
+ t.Fatalf("alert must reach only the owner's connections in every workspace: %+v", fb.userCalls)
+ }
+ var frame struct {
+ Type string `json:"type"`
+ Payload protocol.ChatReplyNotificationPayload `json:"payload"`
+ }
+ if err := json.Unmarshal(fb.userCalls[0].msg, &frame); err != nil {
+ t.Fatal(err)
+ }
+ if frame.Type != protocol.EventChatReplyNotification || frame.Payload.WorkspaceID != "source" ||
+ frame.Payload.ChatSessionID != "session" || frame.Payload.MessageID != "message" ||
+ frame.Payload.Body != strings.Repeat("回", 200)+"…" {
+ t.Fatalf("incorrect alert projection: %+v", frame)
+ }
+ })
+ }
+}
+
+func TestChatReplyAlertInvalidContextIsDropped(t *testing.T) {
+ for _, name := range []string{"owner", "workspace", "message", "context", "mismatch", "session"} {
+ t.Run(name, func(t *testing.T) {
+ e := chatAlertEvent()
+ p := e.Payload.(protocol.ChatDonePayload)
+ switch name {
+ case "owner":
+ e.ChatSessionOwnerID = ""
+ case "workspace":
+ e.WorkspaceID = ""
+ case "message":
+ p.MessageID = ""
+ case "context":
+ p.Notification = nil
+ case "mismatch":
+ p.Notification.WorkspaceID = "other"
+ case "session":
+ p.ChatSessionID = "other"
+ }
+ e.Payload = p
+ bus := events.New()
+ fb := &fakeBroadcaster{}
+ registerChatReplyNotifications(bus, fb, chatMembershipFunc(func(context.Context, string, string) (bool, error) {
+ t.Fatal("invalid context reached membership lookup")
+ return true, nil
+ }))
+ bus.Publish(e)
+ if len(fb.userCalls) != 0 {
+ t.Fatal("invalid alert delivered")
+ }
+ })
+ }
+}
+
+func TestChatReplyAlertReachesOtherWorkspaceConnection(t *testing.T) {
+ fx := workspaceFixture(t)
+ source := fx.Workspace(t, "Chat source", "chat-alert-source")
+ other := fx.Workspace(t, "Chat destination", "chat-alert-destination")
+ fx.Member(t, source, testUserID, "owner")
+ fx.Member(t, other, testUserID, "owner")
+ hub := realtime.NewHub()
+ go hub.Run()
+ bus := events.New()
+ registerListeners(bus, hub)
+ registerChatReplyNotifications(bus, hub, &membershipChecker{queries: db.New(testPool)})
+ router, _ := NewRouterWithOptions(testPool, hub, bus, analytics.NoopClient{}, nil, RouterOptions{})
+ server := httptest.NewServer(router)
+ defer server.Close()
+ conn, _ := realtimeMembershipConn(t, server, testUserID, other)
+ defer conn.Close()
+ e := chatAlertEvent()
+ e.WorkspaceID, e.ChatSessionOwnerID = source, testUserID
+ p := e.Payload.(protocol.ChatDonePayload)
+ p.Notification.WorkspaceID = source
+ e.Payload = p
+ bus.Publish(e)
+ _ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
+ _, raw, err := conn.ReadMessage()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var frame struct {
+ Type string `json:"type"`
+ Payload protocol.ChatReplyNotificationPayload `json:"payload"`
+ }
+ if err := json.Unmarshal(raw, &frame); err != nil {
+ t.Fatal(err)
+ }
+ if frame.Type != protocol.EventChatReplyNotification || frame.Payload.WorkspaceID != source {
+ t.Fatalf("other workspace must receive a bounded alert, not chat content: %s", raw)
+ }
+ // Leaving the source must stop alerts without disconnecting this user's
+ // still-authorized connection to the other workspace.
+ fx.Exec(t, "DELETE FROM member WHERE workspace_id = $1 AND user_id = $2", source, testUserID)
+ bus.Publish(e)
+ hub.SendToUser(testUserID, []byte(`{"type":"test:alert_barrier"}`))
+ _, raw, err = conn.ReadMessage()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := json.Unmarshal(raw, &frame); err != nil || frame.Type != "test:alert_barrier" {
+ t.Fatalf("removed source member received another alert: %s (%v)", raw, err)
+ }
+}
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index eb20754fb1..742ad7af2d 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -615,6 +615,7 @@ func main() {
registerSubscriberListeners(bus, pool)
registerActivityListeners(bus, queries)
registerNotificationListeners(bus, queries)
+ registerChatReplyNotifications(bus, broadcaster, &membershipChecker{queries: queries})
registerIssueUnreadListeners(bus, queries)
metricsConfig := obsmetrics.ConfigFromEnv()
diff --git a/server/cmd/server/notification_chat_reply_test.go b/server/cmd/server/notification_chat_reply_test.go
new file mode 100644
index 0000000000..4445ae0d67
--- /dev/null
+++ b/server/cmd/server/notification_chat_reply_test.go
@@ -0,0 +1,30 @@
+package main
+
+import (
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func TestChatCompletionDoesNotCreateInboxNotification(t *testing.T) {
+ queries := db.New(testPool)
+ bus := newNotificationBus(t, queries)
+ var inboxEvents int
+ bus.Subscribe(protocol.EventInboxNew, func(e events.Event) { inboxEvents++ })
+ fx := workspaceFixture(t)
+ agent := fx.Agent(t, "Chat agent", "")
+ session := fx.ChatSession(t, agent)
+ bus.Publish(events.Event{
+ Type: protocol.EventChatDone, WorkspaceID: testWorkspaceID, ChatSessionOwnerID: testUserID,
+ ChatSessionID: session,
+ Payload: protocol.ChatDonePayload{
+ ChatSessionID: session, MessageID: session, Content: "Reply finished",
+ Notification: &protocol.ChatReplyNotification{WorkspaceID: testWorkspaceID, Title: "Chat reply"},
+ },
+ })
+ if items := inboxItemsForRecipient(t, queries, testUserID); len(items) != 0 || inboxEvents != 0 {
+ t.Fatalf("chat completion must stay out of Inbox: items=%d events=%d", len(items), inboxEvents)
+ }
+}
diff --git a/server/internal/handler/notification_preference.go b/server/internal/handler/notification_preference.go
index 9df49066dc..d309522e01 100644
--- a/server/internal/handler/notification_preference.go
+++ b/server/internal/handler/notification_preference.go
@@ -21,6 +21,7 @@ var validNotifGroups = map[string]bool{
"assignments": true,
"status_changes": true,
"comments": true,
+ "chat_replies": true,
"mentions": true,
"updates": true,
"agent_activity": true,
diff --git a/server/internal/handler/notification_preference_test.go b/server/internal/handler/notification_preference_test.go
index 656ddd670e..af8e913768 100644
--- a/server/internal/handler/notification_preference_test.go
+++ b/server/internal/handler/notification_preference_test.go
@@ -71,7 +71,8 @@ func TestPatchNotificationPreferencesMergesWithoutReplacing(t *testing.T) {
testHandler.PatchNotificationPreferences(
patchRecorder,
notificationPreferenceRequest(t, http.MethodPatch, map[string]string{
- "comments": "muted",
+ "comments": "muted",
+ "chat_replies": "muted",
}),
)
if patchRecorder.Code != http.StatusOK {
@@ -94,6 +95,9 @@ func TestPatchNotificationPreferencesMergesWithoutReplacing(t *testing.T) {
if response.Preferences["comments"] != "muted" {
t.Fatalf("comments patch missing: %#v", response.Preferences)
}
+ if response.Preferences["chat_replies"] != "muted" {
+ t.Fatalf("chat_replies patch missing: %#v", response.Preferences)
+ }
enableRecorder := httptest.NewRecorder()
testHandler.PatchNotificationPreferences(
diff --git a/server/internal/service/chat_reply_notification_test.go b/server/internal/service/chat_reply_notification_test.go
new file mode 100644
index 0000000000..500b471350
--- /dev/null
+++ b/server/internal/service/chat_reply_notification_test.go
@@ -0,0 +1,84 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "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"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func TestChatReplyNotificationContext(t *testing.T) {
+ for _, name := range []string{"reply", "attachment only", "archived", "intro", "no response", "channel", "lifecycle only"} {
+ t.Run(name, func(t *testing.T) {
+ ctx := context.Background()
+ pool := sharedTestPool(t)
+ fx := testutil.New(pool, "", "")
+ owner := fx.User(t, "Chat owner", "[email protected]")
+ workspace := fx.Workspace(t, "Chat alerts", "chat-os-"+owner[:8])
+ fx.UserID, fx.WorkspaceID = owner, workspace
+ fx.Member(t, workspace, owner, "member")
+ runtime := fx.Runtime(t, "Reply runtime")
+ agent := fx.Agent(t, "Reply agent", runtime)
+ cols := testutil.Cols{"title": "Review changes"}
+ if name == "archived" {
+ cols["status"] = "archived"
+ }
+ if name == "intro" {
+ cols["is_agent_intro"] = true
+ }
+ session := fx.ChatSession(t, agent, cols)
+ taskID := fx.Task(t, agent, testutil.Cols{"runtime_id": runtime, "chat_session_id": session, "status": "completed"})
+ fx.Exec(t, "UPDATE agent_task_queue SET chat_input_task_id = id WHERE id = $1", taskID)
+ fx.Insert(t, "chat_message", testutil.Cols{
+ "chat_session_id": session, "role": "user", "content": "Please review", "task_id": taskID,
+ "channel_ingested": name == "channel",
+ })
+ messageCols := testutil.Cols{
+ "chat_session_id": session, "role": "assistant", "content": "Done", "task_id": taskID, "message_kind": "message",
+ }
+ if name == "attachment only" {
+ messageCols["content"] = ""
+ }
+ if name == "no response" {
+ messageCols["message_kind"] = "no_response"
+ }
+ messageID := fx.Insert(t, "chat_message", messageCols)
+ queries := db.New(pool)
+ task, err := queries.GetAgentTask(ctx, util.MustParseUUID(taskID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ message, err := queries.GetChatMessage(ctx, util.MustParseUUID(messageID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ bus := events.New()
+ var got events.Event
+ bus.Subscribe(protocol.EventChatDone, func(e events.Event) { got = e })
+ svc := &TaskService{Queries: queries, Bus: bus}
+ msg := &message
+ if name == "lifecycle only" {
+ msg = nil
+ }
+ svc.broadcastChatDone(ctx, task, msg, false)
+ payload, ok := got.Payload.(protocol.ChatDonePayload)
+ if !ok || got.ChatSessionOwnerID != owner || got.WorkspaceID != workspace {
+ t.Fatalf("reply lost its private source scope: %+v", got)
+ }
+ wantAlert := name == "reply" || name == "attachment only"
+ if !wantAlert {
+ if payload.Notification != nil {
+ t.Fatalf("unexpected OS notification context: %+v", payload.Notification)
+ }
+ return
+ }
+ if payload.Notification == nil || payload.Notification.WorkspaceID != workspace || payload.Notification.Title != "Review changes" || payload.MessageID != messageID {
+ t.Fatalf("incorrect OS notification context: %+v", payload)
+ }
+ })
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 2b62346dad..2d9643168d 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -7779,6 +7779,18 @@ func (s *TaskService) broadcastChatDone(ctx context.Context, task db.AgentTaskQu
if msg.ElapsedMs.Valid {
payload.ElapsedMs = msg.ElapsedMs.Int64
}
+ if msg.MessageKind == "message" {
+ session, sessionErr := s.Queries.GetChatSession(ctx, task.ChatSessionID)
+ origin, originErr := s.Queries.GetTaskChannelOrigin(ctx, task.ID)
+ if sessionErr == nil && originErr == nil && !origin.ChannelIngested &&
+ session.Status == "active" && !session.IsAgentIntro && util.UUIDToString(session.WorkspaceID) == workspaceID {
+ title := strings.TrimSpace(session.Title)
+ if title == "" {
+ title = "Chat reply"
+ }
+ payload.Notification = &protocol.ChatReplyNotification{WorkspaceID: workspaceID, Title: title}
+ }
+ }
}
s.Bus.Publish(events.Event{
Type: protocol.EventChatDone,
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index bde3e6fc39..908d85f66b 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -78,6 +78,8 @@ const (
// Chat events
EventChatMessage = "chat:message"
EventChatDone = "chat:done"
+ // Bounded owner-only alert; unlike chat content, delivered across workspaces.
+ EventChatReplyNotification = "chat:reply_notification"
// EventChatQuickActions supplements a finished turn with follow-up
// suggestions generated by the daemon's post-completion pass. Sent after
// chat:done; clients that don't know it simply never resolve the
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index f90584fe7c..17ba60f441 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -333,6 +333,22 @@ type ChatDonePayload struct {
// follow for this turn (render a placeholder). Never true when
// QuickActions is already populated.
QuickActionsPending bool `json:"quick_actions_pending,omitempty"`
+ // Present only for a completed direct-chat reply eligible for an OS alert.
+ // Older clients ignore it; older servers omit it without affecting chat.
+ Notification *ChatReplyNotification `json:"notification,omitempty"`
+}
+
+type ChatReplyNotification struct {
+ WorkspaceID string `json:"workspace_id"`
+ Title string `json:"title"`
+}
+
+type ChatReplyNotificationPayload struct {
+ WorkspaceID string `json:"workspace_id"`
+ ChatSessionID string `json:"chat_session_id"`
+ MessageID string `json:"message_id"`
+ Title string `json:"title"`
+ Body string `json:"body"`
}
// Outcome values carried by ChatCancelFinalizedPayload.