Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix: unify native notification copy (#825)
Gener66be4496653d
diff --git a/src/queue-worker/src/notification-payload.ts b/src/queue-worker/src/notification-payload.tsindex 9d2584be7..1690c800a 100644--- a/src/queue-worker/src/notification-payload.ts+++ b/src/queue-worker/src/notification-payload.ts@@ -1,6 +1,5 @@import {- stripInlineMarkup,- truncateMessagePreview,+ buildCommunityNotificationCopy,type queries,} from "@alook/shared"@@ -42,34 +41,6 @@ export async function deriveNotificationId(input: {return bytesToUuid(new Uint8Array(digest))}-function attachmentFallback(contentTypes: Array<string | null>): string {- if (contentTypes.some((value) => value?.startsWith("image/"))) return "Photo"- if (contentTypes.some((value) => value?.startsWith("video/"))) return "Video"- if (contentTypes.some((value) => value?.startsWith("audio/"))) return "Audio"- if (contentTypes.length > 0) return "Attachment"- return "New message"-}--function displayName(value: string | null, fallback: string): string {- return value?.trim() || fallback-}--function notificationTitle(- target: queries.communityNotificationTarget.PushNotificationTarget,- authorName: string,-): string {- if (target.conversationKind === "dm") return authorName-- const serverName = displayName(target.serverName, "Server")- if (target.conversationKind === "thread") {- const parentChannelName = displayName(target.parentChannelName, "Channel")- const threadName = displayName(target.channelName, "Thread")- return `${serverName} · #${parentChannelName} · ${threadName}`- }-- return `${serverName} · #${displayName(target.channelName, "Channel")}`-}-export async function buildPushNotificationPayload(target: queries.communityNotificationTarget.PushNotificationTarget,userId: string,@@ -78,19 +49,19 @@ export async function buildPushNotificationPayload(messageId: target.messageId,userId,})- const plainText = stripInlineMarkup(target.content)- .replace(/\s+/gu, " ")- .trim()- const authorName = target.authorName.trim() || "Alook"- const preview = plainText || attachmentFallback(target.attachmentContentTypes)- const body = target.conversationKind === "dm"- ? preview- : `${authorName}: ${preview}`+ const copy = buildCommunityNotificationCopy({+ conversationKind: target.conversationKind,+ authorName: target.authorName,+ content: target.content,+ attachmentContentTypes: target.attachmentContentTypes,+ serverName: target.serverName,+ channelName: target.channelName,+ parentChannelName: target.parentChannelName,+ })return {notificationId,- title: notificationTitle(target, authorName),- body: truncateMessagePreview(body),+ ...copy,route: {notificationId,messageId: target.messageId,diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 5c63ff30c..e75c254b9 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -758,6 +758,12 @@ export * from "./lib/native-oauth-contract";export * from "./lib/safe-redirect";export { generateWorkspaceSlug, sanitizeSlug, slugSuffix } from "./utils/slug";export { truncateTitle, stripInlineMarkup, deriveThreadName } from "./utils/title";+export {+ buildCommunityNotificationCopy,+ type CommunityNotificationConversationKind,+ type CommunityNotificationCopy,+ type CommunityNotificationCopyInput,+} from "./utils/community-notification-copy";export {canManageServer,isServerOwner,diff --git a/src/shared/src/utils/community-notification-copy.ts b/src/shared/src/utils/community-notification-copy.tsnew file mode 100644index 000000000..9fb54dd3b--- /dev/null+++ b/src/shared/src/utils/community-notification-copy.ts@@ -0,0 +1,59 @@+import { truncateMessagePreview } from "../constants/community";+import { stripInlineMarkup } from "./title";++export type CommunityNotificationConversationKind = "dm" | "channel" | "thread";++export interface CommunityNotificationCopyInput {+ conversationKind: CommunityNotificationConversationKind;+ authorName: string | null;+ content: string;+ attachmentContentTypes: ReadonlyArray<string | null | undefined>;+ serverName?: string | null;+ channelName?: string | null;+ parentChannelName?: string | null;+}++export interface CommunityNotificationCopy {+ title: string;+ body: string;+}++function displayName(value: string | null | undefined, fallback: string): string {+ return value?.trim() || fallback;+}++function attachmentFallback(contentTypes: ReadonlyArray<string | null | undefined>): string {+ const normalized = contentTypes.map((value) => value?.toLowerCase() ?? "");+ if (normalized.some((value) => value.startsWith("image/"))) return "Photo";+ if (normalized.some((value) => value.startsWith("video/"))) return "Video";+ if (normalized.some((value) => value.startsWith("audio/"))) return "Audio";+ if (normalized.length > 0) return "Attachment";+ return "New message";+}++export function buildCommunityNotificationCopy(+ input: CommunityNotificationCopyInput,+): CommunityNotificationCopy {+ const authorName = displayName(input.authorName, "Alook");+ const readable = stripInlineMarkup(input.content)+ .replace(/\s+/gu, " ")+ .trim();+ const preview = readable || attachmentFallback(input.attachmentContentTypes);++ if (input.conversationKind === "dm") {+ return {+ title: authorName,+ body: truncateMessagePreview(preview),+ };+ }++ const serverName = displayName(input.serverName, "Server");+ const title = input.conversationKind === "thread"+ ? `${serverName} · #${displayName(input.parentChannelName, "Channel")} · ${displayName(input.channelName, "Thread")}`+ : `${serverName} · #${displayName(input.channelName, "Channel")}`;++ return {+ title,+ body: truncateMessagePreview(`${authorName}: ${preview}`),+ };+}diff --git a/src/shared/test/utils/community-notification-copy.test.ts b/src/shared/test/utils/community-notification-copy.test.tsnew file mode 100644index 000000000..f02133dd8--- /dev/null+++ b/src/shared/test/utils/community-notification-copy.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it } from "vitest";+import { buildCommunityNotificationCopy } from "../../src/utils/community-notification-copy";++const base = {+ authorName: " Alice ",+ content: "**Hello** [there](https://example.test)\nnext line",+ attachmentContentTypes: [] as Array<string | null>,+};++describe("buildCommunityNotificationCopy", () => {+ it("uses sender plus preview for a DM", () => {+ expect(buildCommunityNotificationCopy({+ ...base,+ conversationKind: "dm",+ })).toEqual({+ title: "Alice",+ body: "Hello there next line",+ });+ });++ it.each([+ [+ "channel",+ {+ ...base,+ conversationKind: "channel" as const,+ serverName: "Studio",+ channelName: "general",+ },+ { title: "Studio · #general", body: "Alice: Hello there next line" },+ ],+ [+ "thread",+ {+ ...base,+ conversationKind: "thread" as const,+ serverName: "Studio",+ parentChannelName: "announcements",+ channelName: "Release notes",+ },+ {+ title: "Studio · #announcements · Release notes",+ body: "Alice: Hello there next line",+ },+ ],+ ])("uses conversation context for a %s", (_label, input, expected) => {+ expect(buildCommunityNotificationCopy(input)).toEqual(expected);+ });++ it("uses one fallback policy for missing names and attachments", () => {+ expect(buildCommunityNotificationCopy({+ conversationKind: "thread",+ authorName: " ",+ content: " ",+ attachmentContentTypes: ["application/pdf", "IMAGE/PNG"],+ serverName: null,+ channelName: null,+ parentChannelName: null,+ })).toEqual({+ title: "Server · #Channel · Thread",+ body: "Alook: Photo",+ });+ });++ it.each([+ [["video/mp4"], "Video"],+ [["audio/mpeg"], "Audio"],+ [["application/pdf"], "Attachment"],+ [[], "New message"],+ ] as const)("uses the shared attachment fallback for %j", (attachmentContentTypes, expected) => {+ expect(buildCommunityNotificationCopy({+ ...base,+ conversationKind: "dm",+ content: "",+ attachmentContentTypes,+ })).toEqual({+ title: "Alice",+ body: expected,+ });+ });++ it("caps the complete author-prefixed body without splitting surrogate pairs", () => {+ const copy = buildCommunityNotificationCopy({+ ...base,+ conversationKind: "channel",+ serverName: "Studio",+ channelName: "general",+ content: `${"x".repeat(118)}😀tail`,+ });+ expect(copy.body.startsWith("Alice: ")).toBe(true);+ expect(copy.body.length).toBeLessThanOrEqual(120);+ expect(copy.body).not.toContain("�");+ expect(copy.body.endsWith("…")).toBe(true);+ });+});diff --git a/src/web/src/hooks/community/community-ws/social-events.test.ts b/src/web/src/hooks/community/community-ws/social-events.test.tsindex 87d41c05d..f8a713e06 100644--- a/src/web/src/hooks/community/community-ws/social-events.test.ts+++ b/src/web/src/hooks/community/community-ws/social-events.test.ts@@ -23,15 +23,31 @@ import {unreadBump,} from "./test-harness"-const notificationMocks = vi.hoisted(() => ({ show: vi.fn(async () => undefined) }))+const desktopMode = vi.hoisted(() => ({ value: true }))+const notificationMocks = vi.hoisted(() => ({+ resolve: vi.fn(),+ show: vi.fn(async () => undefined),+}))+vi.mock("@alook/shared", async () => {+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")+ return { ...actual, isDesktop: vi.fn(() => desktopMode.value) }+})vi.mock("@/lib/community/desktop-system-notification", async () => {const actual = await vi.importActual<typeof import("@/lib/community/desktop-system-notification")>("@/lib/community/desktop-system-notification",)- return { ...actual, showDesktopSystemNotification: notificationMocks.show }+ notificationMocks.resolve.mockImplementation(actual.resolveDesktopSystemNotificationCandidate)+ return {+ ...actual,+ resolveDesktopSystemNotificationCandidate: notificationMocks.resolve,+ showDesktopSystemNotification: notificationMocks.show,+ }})-beforeEach(resetCommunityWsHarness)+beforeEach(async () => {+ desktopMode.value = true+ await resetCommunityWsHarness()+})afterEach(cleanupCommunityWsHarness)async function batchFor(messageId: string, events: readonly CommunityWsEvent[]) {@@ -195,6 +211,30 @@ describe("useCommunityWs — account unread projection", () => {expect(notificationMocks.show).not.toHaveBeenCalled()})+ it("does not resolve native copy outside the desktop shell", async () => {+ desktopMode.value = false+ await mountHook({ viewerUserId: "u_me" })+ capturedOnMessage!(await batchFor("message_1", [+ messageCreate("dm_1", "message_1"),+ unreadBump("dm_1", "u_me"),+ ]))++ expect(notificationMocks.resolve).not.toHaveBeenCalled()+ expect(notificationMocks.show).not.toHaveBeenCalled()+ })++ it("keeps a native-copy resolution rejection fail-closed", async () => {+ notificationMocks.resolve.mockRejectedValueOnce(new Error("metadata unavailable"))+ await mountHook({ viewerUserId: "u_me" })+ capturedOnMessage!(await batchFor("message_1", [+ messageCreate("dm_1", "message_1"),+ unreadBump("dm_1", "u_me"),+ ]))++ await vi.waitFor(() => expect(notificationMocks.resolve).toHaveBeenCalledOnce())+ expect(notificationMocks.show).not.toHaveBeenCalled()+ })+it("syncs focused content without refreshing notification surfaces", async () => {vi.useFakeTimers()try {diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.tsindex a74fa42c8..b4351fd80 100644--- a/src/web/src/hooks/community/community-ws/social-events.ts+++ b/src/web/src/hooks/community/community-ws/social-events.ts@@ -1,13 +1,14 @@-import type {- CommunityFriendAccept,- CommunityFriendBlock,- CommunityFriendReject,- CommunityFriendRemove,- CommunityFriendRequest,- CommunityMentionCreate,- CommunityInboxChanged,- CommunityReadStateAdvanced,- CommunityWsEvent,+import {+ isDesktop,+ type CommunityFriendAccept,+ type CommunityFriendBlock,+ type CommunityFriendReject,+ type CommunityFriendRemove,+ type CommunityFriendRequest,+ type CommunityMentionCreate,+ type CommunityInboxChanged,+ type CommunityReadStateAdvanced,+ type CommunityWsEvent,} from "@alook/shared"import type { SocialEventContext } from "@/hooks/community/community-ws/handler-context"import {@@ -24,8 +25,9 @@ import { removeDmReactionDetails } from "./reaction-details-invalidation"import { reconcileNotificationSettings } from "@/hooks/community/use-notification-settings"import { getFriendRequestActionController } from "@/hooks/community/use-friend-request-action-state"import { communityKeys } from "@/lib/query-keys"+import type { StructuralSnapshotV1 } from "@/lib/community/structural-snapshot"import {- buildDesktopSystemNotificationCandidate,+ resolveDesktopSystemNotificationCandidate,showDesktopSystemNotification,} from "@/lib/community/desktop-system-notification"@@ -95,13 +97,18 @@ export function handleUnreadBump(// Use the existing coalesced owner. This is also the sole authority// refresh for legacy/orphan bumps; the ledger itself performs no I/O.scheduleInboxInvalidate({ inbox: true, dms: !event.serverId })- if (evidence) {- const candidate = buildDesktopSystemNotificationCandidate(+ if (evidence && isDesktop()) {+ void resolveDesktopSystemNotificationCandidate(evidence.messageEvent,event,viewerId,- )- if (candidate) void showDesktopSystemNotification(candidate).catch(() => undefined)+ queryClient,+ queryClient.getQueryData<StructuralSnapshotV1>(communityKeys.structuralSnapshot()) ?? null,+ ).then((candidate) => {+ if (candidate && viewerUserIdRef.current === viewerId) {+ return showDesktopSystemNotification(candidate)+ }+ }).catch(() => undefined)}}}diff --git a/src/web/src/hooks/community/use-native-system-notifications.dom.test.ts b/src/web/src/hooks/community/use-native-system-notifications.dom.test.tsindex 25bdc9245..737304742 100644--- a/src/web/src/hooks/community/use-native-system-notifications.dom.test.ts+++ b/src/web/src/hooks/community/use-native-system-notifications.dom.test.ts@@ -322,7 +322,7 @@ describe("native system notification hook", () => {const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))await waitFor(() => expect(assign).toHaveBeenCalledWith(- "/c/channels/server_1/channel_1?msg=message_1",+ "/c/channels/server_1/channel_1",))expect(hookMocks.revalidate).toHaveBeenCalledWith(activation.target)@@ -411,7 +411,7 @@ describe("native system notification hook", () => {}).mockImplementation(async () => { calls.push("take"); return null })hookMocks.mobileRevalidate- .mockResolvedValueOnce({ href: "/c/me/channel_1?seq=9" })+ .mockResolvedValueOnce({ href: "/c/me/channel_1" }).mockResolvedValueOnce(null)const rendered = renderHook(() => useNativeSystemNotifications("viewer_1"))@@ -424,7 +424,7 @@ describe("native system notification hook", () => {"ack",]))expect(hookMocks.mobileListen).toHaveBeenCalledOnce()- expect(assign).toHaveBeenCalledWith("/c/me/channel_1?seq=9")+ expect(assign).toHaveBeenCalledWith("/c/me/channel_1")const button = document.createElement("button")button.setAttribute("aria-label", "Inbox")@@ -475,12 +475,12 @@ describe("native system notification hook", () => {targetId: "channel_1",}hookMocks.mobileTake.mockResolvedValueOnce(nextActivation)- hookMocks.mobileRevalidate.mockResolvedValueOnce({ href: "/c/me/channel_1?seq=4" })+ hookMocks.mobileRevalidate.mockResolvedValueOnce({ href: "/c/me/channel_1" })await act(async () => {window.dispatchEvent(new Event("online"))await vi.advanceTimersByTimeAsync(0)})- expect(assign).toHaveBeenCalledExactlyOnceWith("/c/me/channel_1?seq=4")+ expect(assign).toHaveBeenCalledExactlyOnceWith("/c/me/channel_1")rendered.unmount()visible.mockRestore()})diff --git a/src/web/src/hooks/community/use-native-system-notifications.ts b/src/web/src/hooks/community/use-native-system-notifications.tsindex f8681db3f..babd58204 100644--- a/src/web/src/hooks/community/use-native-system-notifications.ts+++ b/src/web/src/hooks/community/use-native-system-notifications.ts@@ -7,8 +7,8 @@ import {takeDesktopSystemNotificationActivation,} from "@/lib/community/desktop-system-notification"import {- desktopSystemNotificationHref,revalidateDesktopSystemNotificationTarget,+ systemNotificationHref,type DesktopSystemNotificationActivation,} from "@/lib/community/system-notification-route"import {@@ -179,7 +179,7 @@ export function createDesktopSystemNotificationActivationController(if (!activation || disposed) continueconst allowed = await deps.revalidate(activation).catch(() => false)if (disposed) continue- if (allowed) deps.navigate(desktopSystemNotificationHref(activation.target))+ if (allowed) deps.navigate(systemNotificationHref(activation.target))else await deps.openInbox()} while (rerun && !disposed)} finally {diff --git a/src/web/src/lib/community/desktop-system-notification.test.ts b/src/web/src/lib/community/desktop-system-notification.test.tsindex 579ff552f..3dbc7a144 100644--- a/src/web/src/lib/community/desktop-system-notification.test.ts+++ b/src/web/src/lib/community/desktop-system-notification.test.ts@@ -1,18 +1,28 @@import { afterEach, describe, expect, it, vi } from "vitest"import type { CommunityMessageCreate, CommunityWsEvent } from "@alook/shared"+import { QueryClient } from "@tanstack/react-query"+import type { StructuralSnapshotV1 } from "./structural-snapshot"import {buildDesktopSystemNotificationCandidate,listenDesktopSystemNotificationActivations,+ resolveDesktopSystemNotificationCandidate,showDesktopSystemNotification,takeDesktopSystemNotificationActivation,} from "./desktop-system-notification"const invoke = vi.hoisted(() => vi.fn())const desktopMode = vi.hoisted(() => ({ value: true }))+const channelMetadataMocks = vi.hoisted(() => ({ fetch: vi.fn() }))vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")return { ...actual, isDesktop: vi.fn(() => desktopMode.value), tauriInvoke: invoke }})+vi.mock("@/hooks/community/channel-metadata", async () => {+ const actual = await vi.importActual<typeof import("@/hooks/community/channel-metadata")>(+ "@/hooks/community/channel-metadata",+ )+ return { ...actual, fetchChannelMetadata: channelMetadataMocks.fetch }+})type UnreadBump = Extract<CommunityWsEvent, { type: "community:unread.bump" }>const create: CommunityMessageCreate = {@@ -36,6 +46,28 @@ const bump: UnreadBump = {channelId: "channel_1",serverId: "server_1",}+const snapshot: StructuralSnapshotV1 = {+ schemaVersion: 1,+ accountId: "viewer_1",+ capturedAt: 1,+ serverOrder: ["server_1"],+ folders: [],+ servers: [{+ id: "server_1",+ name: "Studio",+ discriminator: "0042",+ icon: null,+ categories: [],+ channels: [{ id: "channel_1", name: "general", type: "text", categoryId: null }],+ childRouteHints: [{+ id: "thread_1",+ name: "Release notes",+ type: "thread",+ parentChannelId: "channel_1",+ parentMessageId: "message_0",+ }],+ }],+}afterEach(() => {desktopMode.value = true@@ -45,10 +77,10 @@ afterEach(() => {describe("desktop system notification candidates", () => {it("derives a hygienic server notification from one paired bundle", () => {- expect(buildDesktopSystemNotificationCandidate(create, bump, "viewer_1")).toEqual({+ expect(buildDesktopSystemNotificationCandidate(create, bump, "viewer_1", snapshot)).toEqual({viewerUserId: "viewer_1",- title: "Ada",- body: "Hello there",+ title: "Studio · #general",+ body: "Ada: Hello there",target: {kind: "server",serverId: "server_1",@@ -59,6 +91,173 @@ describe("desktop system notification candidates", () => {})})+ it("uses the same server, parent channel, and thread title hierarchy as mobile", () => {+ expect(buildDesktopSystemNotificationCandidate({+ ...create,+ channelId: "thread_1",+ }, { ...bump, channelId: "thread_1" }, "viewer_1", snapshot)).toMatchObject({+ title: "Studio · #general · Release notes",+ body: "Ada: Hello there",+ })+ })++ it("does not reuse conversation names from another account's snapshot", () => {+ expect(buildDesktopSystemNotificationCandidate(+ create,+ bump,+ "viewer_1",+ { ...snapshot, accountId: "other" },+ )).toMatchObject({+ title: "Server · #Channel",+ body: "Ada: Hello there",+ })+ })++ it("resolves a cold channel name before formatting the desktop copy", async () => {+ const queryClient = new QueryClient()+ channelMetadataMocks.fetch.mockResolvedValue({+ id: "channel_1",+ serverId: "server_1",+ name: "general",+ type: "text",+ parentChannelId: null,+ parentMessageId: null,+ creatorId: null,+ archived: false,+ lastMessageAt: null,+ createdAt: "2026-09-12T00:00:00.000Z",+ })+ const coldSnapshot = {+ ...snapshot,+ servers: snapshot.servers.map((server) => ({+ ...server,+ channels: [],+ childRouteHints: [],+ })),+ }++ await expect(resolveDesktopSystemNotificationCandidate(+ create,+ bump,+ "viewer_1",+ queryClient,+ coldSnapshot,+ )).resolves.toMatchObject({+ title: "Studio · #general",+ body: "Ada: Hello there",+ })+ expect(channelMetadataMocks.fetch).toHaveBeenCalledWith("server_1", "channel_1")+ })++ it("uses the default empty snapshot while resolving cold channel metadata", async () => {+ const queryClient = new QueryClient()+ channelMetadataMocks.fetch.mockResolvedValue({+ id: "channel_1",+ serverId: "server_1",+ name: "general",+ type: "text",+ parentChannelId: null,+ parentMessageId: null,+ creatorId: null,+ archived: false,+ lastMessageAt: null,+ createdAt: "2026-09-12T00:00:00.000Z",+ })++ await expect(resolveDesktopSystemNotificationCandidate(+ create,+ bump,+ "viewer_1",+ queryClient,+ )).resolves.toMatchObject({+ title: "Server · #general",+ body: "Ada: Hello there",+ })+ expect(channelMetadataMocks.fetch).toHaveBeenCalledWith("server_1", "channel_1")+ })++ it("resolves cold thread and parent channel names before formatting the desktop copy", async () => {+ const queryClient = new QueryClient()+ channelMetadataMocks.fetch.mockResolvedValueOnce({+ id: "thread_1",+ serverId: "server_1",+ name: "Release notes",+ type: "thread",+ parentChannelId: "channel_1",+ parentMessageId: "message_0",+ creatorId: "author_1",+ archived: false,+ lastMessageAt: null,+ createdAt: "2026-09-12T00:00:00.000Z",+ }).mockResolvedValueOnce({+ id: "channel_1",+ serverId: "server_1",+ name: "general",+ type: "text",+ parentChannelId: null,+ parentMessageId: null,+ creatorId: null,+ archived: false,+ lastMessageAt: null,+ createdAt: "2026-09-12T00:00:00.000Z",+ })+ const coldSnapshot = {+ ...snapshot,+ servers: snapshot.servers.map((server) => ({+ ...server,+ channels: [],+ childRouteHints: [],+ })),+ }++ await expect(resolveDesktopSystemNotificationCandidate(+ { ...create, channelId: "thread_1" },+ { ...bump, channelId: "thread_1" },+ "viewer_1",+ queryClient,+ coldSnapshot,+ )).resolves.toMatchObject({+ title: "Studio · #general · Release notes",+ body: "Ada: Hello there",+ })+ expect(channelMetadataMocks.fetch.mock.calls).toEqual([+ ["server_1", "thread_1"],+ ["server_1", "channel_1"],+ ])+ })++ it("uses the complete current-account snapshot without metadata I/O", async () => {+ await expect(resolveDesktopSystemNotificationCandidate(+ create,+ bump,+ "viewer_1",+ new QueryClient(),+ snapshot,+ )).resolves.toMatchObject({+ title: "Studio · #general",+ body: "Ada: Hello there",+ })+ expect(channelMetadataMocks.fetch).not.toHaveBeenCalled()+ })++ it("keeps safe fallback copy when cold metadata resolution fails", async () => {+ channelMetadataMocks.fetch.mockRejectedValue(new Error("metadata unavailable"))+ await expect(resolveDesktopSystemNotificationCandidate(+ create,+ bump,+ "viewer_1",+ new QueryClient(),+ { ...snapshot, servers: snapshot.servers.map((server) => ({+ ...server,+ channels: [],+ childRouteHints: [],+ })) },+ )).resolves.toMatchObject({+ title: "Studio · #Channel",+ body: "Ada: Hello there",+ })+ })+it("rejects account, channel, scope, and own-author mismatches", () => {expect(buildDesktopSystemNotificationCandidate(create, bump, null)).toBeNull()expect(buildDesktopSystemNotificationCandidate(create, { ...bump, userId: "other" }, "viewer_1")).toBeNull()@@ -84,7 +283,7 @@ describe("desktop system notification candidates", () => {attachments: [{ id: "a", filename: "file", url: "/file", contentType }],},}, bump, "viewer_1")- expect(candidate?.body).toBe(expected)+ expect(candidate?.body).toBe(`Ada: ${expected}`)})it("uses the generic fallback and derives a DM target", () => {diff --git a/src/web/src/lib/community/desktop-system-notification.ts b/src/web/src/lib/community/desktop-system-notification.tsindex 7a592e7f0..dc2fae2d7 100644--- a/src/web/src/lib/community/desktop-system-notification.ts+++ b/src/web/src/lib/community/desktop-system-notification.ts@@ -1,11 +1,14 @@import {+ buildCommunityNotificationCopy,isDesktop,- stripInlineMarkup,tauriInvoke,- truncateMessagePreview,type CommunityMessageCreate,type CommunityWsEvent,} from "@alook/shared"+import type { QueryClient } from "@tanstack/react-query"+import { fetchChannelMetadata, type ChannelMetadata } from "@/hooks/community/channel-metadata"+import { communityKeys } from "@/lib/query-keys"+import type { StructuralSnapshotV1 } from "./structural-snapshot"import {parseDesktopSystemNotificationActivation,type DesktopSystemNotificationActivation,@@ -21,25 +24,46 @@ export type DesktopSystemNotificationCandidate = {target: DesktopSystemNotificationTarget}-function attachmentFallback(message: CommunityMessageCreate["message"]): string {- const contentType = message.attachments?.[0]?.contentType?.toLowerCase() ?? ""- if (contentType.startsWith("image/")) return "Photo"- if (contentType.startsWith("video/")) return "Video"- if (contentType.startsWith("audio/")) return "Audio"- if ((message.attachments?.length ?? 0) > 0) return "Attachment"- return "New message"+type DesktopSystemNotificationConversation = {+ conversationKind: "channel" | "thread"+ serverName?: string | null+ channelName?: string | null+ parentChannelName?: string | null+}++function snapshotConversation(+ create: CommunityMessageCreate,+ viewerUserId: string,+ snapshot: StructuralSnapshotV1 | null,+): DesktopSystemNotificationConversation | null {+ if (!create.serverId) return null+ const server = snapshot?.accountId === viewerUserId+ ? snapshot.servers.find((entry) => entry.id === create.serverId)+ : undefined+ const child = server?.childRouteHints.find((entry) => entry.id === create.channelId)+ const channel = server?.channels.find((entry) => entry.id === create.channelId)+ const parent = child+ ? server?.channels.find((entry) => entry.id === child.parentChannelId)+ : undefined+ return {+ conversationKind: child ? "thread" : "channel",+ serverName: server?.name,+ channelName: child?.name ?? channel?.name,+ parentChannelName: parent?.name,+ }}export function buildDesktopSystemNotificationCandidate(create: CommunityMessageCreate,bump: CommunityUnreadBump,viewerUserId: string | null,+ snapshot: StructuralSnapshotV1 | null = null,+ resolvedConversation: DesktopSystemNotificationConversation | null = null,): DesktopSystemNotificationCandidate | null {if (!viewerUserId || bump.userId !== viewerUserId) return nullif (create.channelId !== bump.channelId || create.serverId !== bump.serverId) return nullif (create.message.authorId === viewerUserId) return null- const readable = stripInlineMarkup(create.message.content).replace(/\s+/g, " ").trim()const target: DesktopSystemNotificationTarget = create.serverId? {kind: "server",@@ -54,15 +78,65 @@ export function buildDesktopSystemNotificationCandidate(messageId: create.message.id,seq: create.message.seq,}+ const conversation = resolvedConversation ?? snapshotConversation(create, viewerUserId, snapshot)+ const copy = buildCommunityNotificationCopy({+ conversationKind: create.serverId ? conversation?.conversationKind ?? "channel" : "dm",+ authorName: create.message.authorName,+ content: create.message.content,+ attachmentContentTypes: create.message.attachments?.map((attachment) => attachment.contentType) ?? [],+ serverName: conversation?.serverName,+ channelName: conversation?.channelName,+ parentChannelName: conversation?.parentChannelName,+ })return {viewerUserId,- title: create.message.authorName.trim() || "Alook",- body: truncateMessagePreview(readable || attachmentFallback(create.message)),+ ...copy,target,}}+export async function resolveDesktopSystemNotificationCandidate(+ create: CommunityMessageCreate,+ bump: CommunityUnreadBump,+ viewerUserId: string | null,+ queryClient: QueryClient,+ snapshot: StructuralSnapshotV1 | null = null,+): Promise<DesktopSystemNotificationCandidate | null> {+ const fallback = buildDesktopSystemNotificationCandidate(create, bump, viewerUserId, snapshot)+ if (!fallback || !viewerUserId || !create.serverId) return fallback++ const cached = snapshotConversation(create, viewerUserId, snapshot)+ if (+ cached?.channelName+ && (cached.conversationKind !== "thread" || cached.parentChannelName)+ ) return fallback++ try {+ const channel = await queryClient.fetchQuery({+ queryKey: communityKeys.channelMeta(create.serverId, create.channelId),+ queryFn: () => fetchChannelMetadata(create.serverId!, create.channelId),+ staleTime: Infinity,+ }) as ChannelMetadata+ const parent = channel.parentChannelId+ ? await queryClient.fetchQuery({+ queryKey: communityKeys.channelMeta(create.serverId, channel.parentChannelId),+ queryFn: () => fetchChannelMetadata(create.serverId!, channel.parentChannelId!),+ staleTime: Infinity,+ }) as ChannelMetadata+ : null++ return buildDesktopSystemNotificationCandidate(create, bump, viewerUserId, snapshot, {+ conversationKind: channel.parentChannelId ? "thread" : "channel",+ serverName: cached?.serverName,+ channelName: channel.name,+ parentChannelName: parent?.name,+ })+ } catch {+ return fallback+ }+}+export async function showDesktopSystemNotification(candidate: DesktopSystemNotificationCandidate,): Promise<void> {diff --git a/src/web/src/lib/community/mobile-system-notification.ts b/src/web/src/lib/community/mobile-system-notification.tsindex 768d99908..edbebf840 100644--- a/src/web/src/lib/community/mobile-system-notification.ts+++ b/src/web/src/lib/community/mobile-system-notification.ts@@ -1,4 +1,5 @@import { isMobile, isTauri, tauriInvoke } from "@alook/shared"+import { systemNotificationHref } from "./system-notification-route"export type MobileSystemNotificationPermission = "granted" | "denied" | "prompt"@@ -427,7 +428,7 @@ export async function revalidateMobileSystemNotificationActivation(if (receipt.surfaceKind === "dm") {return {- href: `/c/me/${encodeURIComponent(activation.targetId)}`,+ href: systemNotificationHref({ kind: "dm", channelId: activation.targetId }),}}@@ -446,7 +447,11 @@ export async function revalidateMobileSystemNotificationActivation(const expectedType = receipt.surfaceKind === "channel" ? "text" : receipt.surfaceKindif (channel.type !== expectedType) return nullreturn {- href: `/c/channels/${encodeURIComponent(channel.serverId)}/${encodeURIComponent(activation.targetId)}`,+ href: systemNotificationHref({+ kind: "server",+ serverId: channel.serverId,+ channelId: activation.targetId,+ }),}} catch {return nulldiff --git a/src/web/src/lib/community/system-notification-route.test.ts b/src/web/src/lib/community/system-notification-route.test.tsindex 5571242bd..4b260a742 100644--- a/src/web/src/lib/community/system-notification-route.test.ts+++ b/src/web/src/lib/community/system-notification-route.test.ts@@ -1,8 +1,8 @@import { afterEach, describe, expect, it, vi } from "vitest"import {- desktopSystemNotificationHref,parseDesktopSystemNotificationActivation,revalidateDesktopSystemNotificationTarget,+ systemNotificationHref,type DesktopSystemNotificationActivation,} from "./system-notification-route"@@ -59,15 +59,13 @@ describe("desktop system notification routes", () => {})it("derives only first-party server and DM routes", () => {- expect(desktopSystemNotificationHref(activation.target)).toBe(- "/c/channels/server_1/channel-2?msg=message_3",+ expect(systemNotificationHref(activation.target)).toBe(+ "/c/channels/server_1/channel-2",)- expect(desktopSystemNotificationHref({+ expect(systemNotificationHref({kind: "dm",channelId: "dm_1",- messageId: "message_4",- seq: 12,- })).toBe("/c/me/dm_1?seq=12")+ })).toBe("/c/me/dm_1")})it("revalidates the exact message through the authenticated API", async () => {diff --git a/src/web/src/lib/community/system-notification-route.ts b/src/web/src/lib/community/system-notification-route.tsindex 496c46459..e996c5c2e 100644--- a/src/web/src/lib/community/system-notification-route.ts+++ b/src/web/src/lib/community/system-notification-route.ts@@ -18,6 +18,10 @@ export type DesktopSystemNotificationActivation = {target: DesktopSystemNotificationTarget}+export type SystemNotificationRouteTarget =+ | { kind: "server"; serverId: string; channelId: string }+ | { kind: "dm"; channelId: string }+const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/const NOTIFICATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i@@ -79,11 +83,11 @@ export function parseDesktopSystemNotificationActivation(return null}-export function desktopSystemNotificationHref(target: DesktopSystemNotificationTarget): string {+export function systemNotificationHref(target: SystemNotificationRouteTarget): string {if (target.kind === "dm") {- return `/c/me/${encodeURIComponent(target.channelId)}?seq=${target.seq}`+ return `/c/me/${encodeURIComponent(target.channelId)}`}- return `/c/channels/${encodeURIComponent(target.serverId)}/${encodeURIComponent(target.channelId)}?msg=${encodeURIComponent(target.messageId)}`+ return `/c/channels/${encodeURIComponent(target.serverId)}/${encodeURIComponent(target.channelId)}`}export async function revalidateDesktopSystemNotificationTarget(diff --git a/src/web/src/test/e2e-ui/58-system-notifications.spec.ts b/src/web/src/test/e2e-ui/58-system-notifications.spec.tsindex 8d2e5b11d..26a71a4d5 100644--- a/src/web/src/test/e2e-ui/58-system-notifications.spec.ts+++ b/src/web/src/test/e2e-ui/58-system-notifications.spec.ts@@ -1,5 +1,5 @@import type { Page } from "@playwright/test"-import { expect, test } from "./_fixtures/community-fixture"+import { expect, test, userName } from "./_fixtures/community-fixture"import { gotoAfterUserWsAuth } from "./_fixtures/actions"import { seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"import { tid } from "./_fixtures/testids"@@ -75,19 +75,22 @@ async function shownNotifications(page: Page) {test.describe.serial("desktop system notifications", () => {test("a delivered message+bump bundle invokes the native command with the exact target", async ({ asUser }) => {const stamp = Date.now()- const serverId = await seedServer("alice", `notification-live-${stamp}`)- const channelId = await seedChannel("alice", serverId, `notification-live-${stamp}`)+ const serverName = `notification-live-${stamp}`+ const channelName = `notification-live-${stamp}`+ const serverId = await seedServer("alice", serverName)+ const channelId = await seedChannel("alice", serverId, channelName)await seedJoinServer("alice", "bob", serverId)const bob = await asUser("bob")await installDesktopNotificationBridge(bob.page)await gotoAfterUserWsAuth(bob.page, "/c/me/friends")+ await expect(bob.page.getByTestId(tid.serverIcon(serverId))).toBeVisible()const body = `Native notification ${stamp}`const messageId = await seedMessage("alice", channelId, body)await expect.poll(() => shownNotifications(bob.page)).toEqual([expect.objectContaining({- title: expect.any(String),- body,+ title: `${serverName} · #${channelName}`,+ body: `${userName("alice")}: ${body}`,target: {kind: "server",serverId,