Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(desktop): route inbox notifications to the item's source workspace (#3797)
Nguyễn Phúc Lương93b93f58b547
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsxindex 406fe49448..a4b357f1cf 100644--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx@@ -1,4 +1,4 @@-import { useEffect, useSyncExternalStore } from "react";+import { useEffect, useRef, useSyncExternalStore } from "react";import { ChevronLeft, ChevronRight } from "lucide-react";import { cn } from "@multica/ui/lib/utils";import { useTabHistory } from "@/hooks/use-tab-history";@@ -14,6 +14,7 @@ import { AppSidebar } from "@multica/views/layout";import { SearchCommand, SearchTrigger } from "@multica/views/search";import { ChatFab, ChatWindow } from "@multica/views/chat";import { WorkspaceSlugProvider, paths, useCurrentWorkspace } from "@multica/core/paths";+import { useNavigation } from "@multica/views/navigation";import { getCurrentSlug, subscribeToCurrentSlug } from "@multica/core/platform";import { useDesktopUnreadBadge } from "@multica/views/platform";import { DesktopNavigationProvider } from "@/platform/navigation";@@ -127,18 +128,30 @@ function useInternalLinkHandler() {* 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).*/function DesktopInboxBridge() {const workspace = useCurrentWorkspace();useDesktopUnreadBadge(workspace?.id ?? null);+ const { push } = useNavigation();+ // The adapter identity changes with the active tab's location; the ref+ // keeps the main-process subscription stable across navigations.+ const pushRef = useRef(push);+ useEffect(() => {+ pushRef.current = push;+ }, [push]);useEffect(() => {return window.desktopAPI.onInboxOpen(({ slug, issueKey }) => {if (!slug) return;const inboxPath = `${paths.workspace(slug).inbox()}?issue=${encodeURIComponent(issueKey)}`;- window.dispatchEvent(- new CustomEvent("multica:navigate", { detail: { path: inboxPath } }),- );+ pushRef.current(inboxPath);});}, []);diff --git a/packages/core/realtime/use-realtime-sync.test.ts b/packages/core/realtime/use-realtime-sync.test.tsindex fc0d643961..c479906721 100644--- a/packages/core/realtime/use-realtime-sync.test.ts+++ b/packages/core/realtime/use-realtime-sync.test.ts@@ -1,18 +1,23 @@import { QueryClient, type InfiniteData } from "@tanstack/react-query";-import { describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { chatKeys } from "../chat/queries";+import { inboxKeys } from "../inbox/queries";import { issueKeys } from "../issues/queries";+import { notificationPreferenceKeys } from "../notification-preferences/queries";import { workspaceKeys } from "../workspace/queries";import type {ChatDonePayload,ChatMessage,ChatPendingTask,ChatMessagesPage,+ InboxItem,Workspace,} from "../types";import {applyChatDoneToCache,applyWorkspaceUpdatedToCache,+ handleInboxNew,+ resolveInboxSourceSlug,} from "./use-realtime-sync";const sessionId = "session-1";@@ -233,3 +238,165 @@ describe("applyChatDoneToCache paged messages", () => {expect(paged?.pages[1]?.messages.map((m) => m.id)).toEqual(["msg-user"]);});});+describe("resolveInboxSourceSlug", () => {+ function workspace(overrides: Partial<Workspace> = {}): Workspace {+ return {+ id: "ws-a",+ name: "Workspace A",+ slug: "workspace-a",+ description: null,+ context: null,+ settings: {},+ repos: [],+ issue_prefix: "WSA",+ avatar_url: null,+ created_at: "2026-05-18T00:00:00Z",+ updated_at: "2026-05-18T00:00:00Z",+ ...overrides,+ };+ }++ it("resolves the inbox item's source workspace, not another cached one", async () => {+ // Regression for #3766: an `inbox:new` from workspace A arriving while+ // workspace B is active must resolve A's slug for notification routing.+ const qc = createQueryClient();+ qc.setQueryData<Workspace[]>(workspaceKeys.list(), [+ workspace({ id: "ws-b", slug: "workspace-b", name: "Workspace B" }),+ workspace(),+ ]);++ await expect(resolveInboxSourceSlug(qc, "ws-a")).resolves.toBe("workspace-a");+ });++ it("returns null instead of falling back when the workspace is unknown", async () => {+ const qc = createQueryClient();+ qc.setQueryData<Workspace[]>(workspaceKeys.list(), [+ workspace({ id: "ws-b", slug: "workspace-b" }),+ ]);++ await expect(resolveInboxSourceSlug(qc, "ws-a")).resolves.toBeNull();+ });++ it("returns null for an empty workspace id without touching the cache", async () => {+ const qc = createQueryClient();+ const ensure = vi.spyOn(qc, "ensureQueryData");++ await expect(resolveInboxSourceSlug(qc, "")).resolves.toBeNull();+ expect(ensure).not.toHaveBeenCalled();+ });++ it("returns null when the workspace list cannot be fetched", async () => {+ const qc = createQueryClient();+ vi.spyOn(qc, "ensureQueryData").mockRejectedValueOnce(new Error("network down"));++ await expect(resolveInboxSourceSlug(qc, "ws-a")).resolves.toBeNull();+ });+});++describe("handleInboxNew", () => {+ function workspace(overrides: Partial<Workspace> = {}): Workspace {+ return {+ id: "ws-a",+ name: "Workspace A",+ slug: "workspace-a",+ description: null,+ context: null,+ settings: {},+ repos: [],+ issue_prefix: "WSA",+ avatar_url: null,+ created_at: "2026-05-18T00:00:00Z",+ updated_at: "2026-05-18T00:00:00Z",+ ...overrides,+ };+ }++ function inboxItem(overrides: Partial<InboxItem> = {}): InboxItem {+ return {+ id: "item-1",+ workspace_id: "ws-a",+ recipient_type: "member",+ recipient_id: "member-1",+ actor_type: "member",+ actor_id: "member-2",+ type: "mentioned",+ severity: "info",+ issue_id: "issue-1",+ title: "Mentioned you",+ body: "in a comment",+ issue_status: null,+ read: false,+ archived: false,+ created_at: "2026-05-18T00:00:00Z",+ details: null,+ ...overrides,+ };+ }++ function stubDesktopAPI() {+ const showNotification = vi.fn();+ (globalThis as Record<string, unknown>).desktopAPI = { showNotification };+ return showNotification;+ }++ afterEach(() => {+ delete (globalThis as Record<string, unknown>).desktopAPI;+ });++ it("still shows the banner when the slug can't be resolved, with an empty slug so the click is a no-op", async () => {+ const qc = createQueryClient();+ // Workspace list is cached but doesn't contain the item's workspace.+ qc.setQueryData<Workspace[]>(workspaceKeys.list(), [+ workspace({ id: "ws-b", slug: "workspace-b" }),+ ]);+ qc.setQueryData(notificationPreferenceKeys.all("ws-a"), {+ preferences: { system_notifications: "all" },+ });+ const showNotification = stubDesktopAPI();++ await handleInboxNew(qc, inboxItem());++ expect(showNotification).toHaveBeenCalledWith({+ slug: "",+ itemId: "item-1",+ issueKey: "issue-1",+ title: "Mentioned you",+ body: "in a comment",+ });+ });++ it("invalidates the ITEM's workspace inbox cache and resolves its slug, not the active workspace's", async () => {+ const qc = createQueryClient();+ qc.setQueryData<Workspace[]>(workspaceKeys.list(), [+ workspace({ id: "ws-b", slug: "workspace-b" }),+ workspace(),+ ]);+ qc.setQueryData(notificationPreferenceKeys.all("ws-a"), {+ preferences: { system_notifications: "all" },+ });+ const invalidate = vi.spyOn(qc, "invalidateQueries");+ const showNotification = stubDesktopAPI();++ await handleInboxNew(qc, inboxItem());++ expect(invalidate).toHaveBeenCalledWith({+ queryKey: inboxKeys.list("ws-a"),+ });+ expect(showNotification).toHaveBeenCalledWith(+ expect.objectContaining({ slug: "workspace-a" }),+ );+ });++ it("honors the SOURCE workspace's mute preference", async () => {+ const qc = createQueryClient();+ qc.setQueryData<Workspace[]>(workspaceKeys.list(), [workspace()]);+ qc.setQueryData(notificationPreferenceKeys.all("ws-a"), {+ preferences: { system_notifications: "muted" },+ });+ const showNotification = stubDesktopAPI();++ await handleInboxNew(qc, inboxItem());++ expect(showNotification).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 0a9777c4d3..a6a5098a67 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -49,6 +49,7 @@ import type {IssueLabelsChangedPayload,IssueMetadataChangedPayload,InboxNewPayload,+ InboxItem,CommentCreatedPayload,CommentUpdatedPayload,CommentDeletedPayload,@@ -170,6 +171,107 @@ export function applyWorkspaceUpdatedToCache(qc.invalidateQueries({ queryKey: workspaceKeys.list() });}+/**+ * Resolves the slug of the workspace an inbox item originated from, via the+ * cached workspace list (fetched once when the cache is cold).+ *+ * Desktop notification routing must pin to the *source* workspace of the+ * inbox item, not the currently active one: the user can be on workspace B+ * when an `inbox:new` for workspace A arrives, and macOS Notification Center+ * holds banners across workspace switches. Returns null when the workspace+ * cannot be resolved — callers must NOT fall back to the current slug (that+ * recreates the wrong-workspace routing this exists to prevent, #3766) and+ * should show the notification without a deep link instead.+ */+export async function resolveInboxSourceSlug(+ qc: QueryClient,+ workspaceId: string,+): Promise<string | null> {+ if (!workspaceId) return null;+ try {+ const workspaces = await qc.ensureQueryData(workspaceListOptions());+ return workspaces?.find((w) => w.id === workspaceId)?.slug ?? null;+ } catch {+ // Workspace list unavailable (e.g. network hiccup): degrade to a+ // link-less notification rather than guessing a slug.+ return null;+ }+}++/**+ * Handles an `inbox:new` event end-to-end: inbox cache invalidation, the+ * focus / mute checks, and the native OS banner. Exported so the handler+ * behavior (not just slug resolution) is testable.+ *+ * Every workspace-scoped read here keys on the ITEM's workspace+ * (`item.workspace_id`), never the currently active one (#3766): the cache+ * invalidation must refresh the source workspace's inbox list / unread+ * count / dock badge, the mute check must honor the source workspace's+ * preference, and the deep link must carry the source workspace's slug.+ */+export async function handleInboxNew(+ qc: QueryClient,+ item: InboxItem,+): Promise<void> {+ const sourceWsId = item.workspace_id;+ if (sourceWsId) onInboxNew(qc, sourceWsId, item);+ // Fire a native OS notification only when the app isn't focused. When+ // 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;+ // Respect the SOURCE workspace's system-notification preference. The+ // Settings page owns the only `useQuery` for this resource, so the cache+ // may be cold for a workspace whose Settings page was never visited —+ // `ensureQueryData` resolves from cache when present and otherwise+ // fetches once. Keying this on the active workspace would let a banner+ // fire for a muted workspace (and vice-versa). On network failure we+ // fall through to the default ("all") rather than swallow the banner.+ if (sourceWsId) {+ try {+ const prefData = await qc.ensureQueryData(+ notificationPreferenceOptions(sourceWsId),+ );+ if (prefData?.preferences?.system_notifications === "muted") return;+ } catch {+ // Fall through with default behavior.+ }+ }+ // Route the click to the workspace the inbox item BELONGS to — not the+ // currently active one. Reading `getCurrentSlug()` here was the source+ // of wrong-workspace routing (#3766): an `inbox:new` from workspace A+ // arriving while workspace B is active emitted a notification carrying+ // B's slug and A's issue id, deep-linking to an issue B doesn't have.+ const slug = await resolveInboxSourceSlug(qc, sourceWsId);+ const desktopAPI = (+ globalThis as unknown as {+ desktopAPI?: {+ showNotification?: (payload: {+ slug: string;+ itemId: string;+ issueKey: string;+ title: string;+ body: string;+ }) => void;+ };+ }+ ).desktopAPI;+ // `issueKey` matches the inbox page's URL selector (issue id when the+ // item is attached to an issue, otherwise the inbox item id). `itemId`+ // is the inbox row's own id, needed to fire markInboxRead on click.+ // A null slug (workspace list unavailable / item from a workspace this+ // client can't see) still shows the banner — the user should learn about+ // the inbox item — but with an empty slug so the click is a no-op+ // (DesktopInboxBridge ignores empty slugs) instead of routing wrong.+ desktopAPI?.showNotification?.({+ slug: slug ?? "",+ itemId: item.id,+ issueKey: item.issue_id ?? item.id,+ title: item.title,+ body: item.body ?? "",+ });+}+/*** Invalidates all workspace-scoped queries. Used after reconnect and when a* new WSClient instance is detected (workspace switch) to recover events@@ -472,59 +574,7 @@ export function useRealtimeSync(const unsubInboxNew = ws.on("inbox:new", async (p) => {const { item } = p as InboxNewPayload;if (!item) return;- const wsId = getCurrentWsId();- if (wsId) onInboxNew(qc, wsId, item);- // Fire a native OS notification only when the app isn't focused. When- // 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;- // Respect the user's system-notification preference. The Settings page- // owns the only `useQuery` for this resource, so on a fresh app start- // (or any session that hasn't visited Settings) the React Query cache- // is empty — using `getQueryData` would silently default to "all" and- // ignore the user's saved choice. `ensureQueryData` resolves to the- // cached value if present and otherwise fetches once, populating the- // cache for subsequent events. On network failure we fall through to- // the default ("all") rather than swallow the banner entirely.- if (wsId) {- try {- const prefData = await qc.ensureQueryData(notificationPreferenceOptions(wsId));- if (prefData?.preferences?.system_notifications === "muted") return;- } catch {- // Fall through with default behavior.- }- }- // Capture the source workspace slug at emit time. The user may switch- // workspaces before clicking the banner (macOS Notification Center- // holds banners), so routing must not read "current slug" at click- // time — otherwise notifications from workspace A click through to- // workspace B's inbox and 404.- const slug = getCurrentSlug();- if (!slug) return;- const desktopAPI = (- window as unknown as {- desktopAPI?: {- showNotification?: (payload: {- slug: string;- itemId: string;- issueKey: string;- title: string;- body: string;- }) => void;- };- }- ).desktopAPI;- // `issueKey` matches the inbox page's URL selector (issue id when the- // item is attached to an issue, otherwise the inbox item id). `itemId`- // is the inbox row's own id, needed to fire markInboxRead on click.- desktopAPI?.showNotification?.({- slug,- itemId: item.id,- issueKey: item.issue_id ?? item.id,- title: item.title,- body: item.body ?? "",- });+ await handleInboxNew(qc, item);});// --- Timeline event handlers (global fallback) ---