Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(community): single-source the notif-level value<->label bijection (#5 T1)

Mellyeed522013db3
diff --git a/src/shared/src/constants/community.ts b/src/shared/src/constants/community.ts
index c7d60a38c..9e9fe8e4e 100644
--- a/src/shared/src/constants/community.ts
+++ b/src/shared/src/constants/community.ts
@@ -102,18 +102,58 @@ export const TYPING_INDICATOR_THROTTLE_MS = 3_000
export const MESSAGE_DEDUP_CACHE_MAX = 500
export const MESSAGE_DEDUP_CACHE_TRIM = 400
-// Notification levels
-export const NOTIF_LEVELS = {
- ALL: "All messages",
- MENTIONS: "Only @mentions",
- NONE: "Nothing",
-} as const
-export type NotifLevel = typeof NOTIF_LEVELS[keyof typeof NOTIF_LEVELS]
-
-// Notification setting level values (DB enum)
+// Notification setting level values (DB enum). Anchors
+// `community_notification_setting.level` (schema `.default("all")`) — the three
+// real, persisted levels. `NOTIF_LEVELS` below is the single value↔label source.
export const NOTIFICATION_LEVEL_VALUES = ["all", "mentions", "nothing"] as const
export type NotificationLevelValue = typeof NOTIFICATION_LEVEL_VALUES[number]
+// Single source of truth for the notification-level value↔label bijection.
+// Each row ties the DB `value` to the `display` string that flows through the
+// UI props + mutations, plus the menu `label`/`hint` shown in the dropdowns.
+// EVERY UI options array, the display mapper, and the reverse normalizer read
+// from here — previously the map was re-hand-rolled in ~5 places with THREE
+// inconsistent `display` spellings ("All messages" / "All Messages" /
+// "All messages"), so a value could round-trip wrong or fall through the
+// normalizer's silent default. Canonical display casing is "All Messages"
+// (what the live UI already renders — so consolidating is zero visible change).
+export const NOTIF_LEVELS = [
+ { value: "all", display: "All Messages", label: "Every message", hint: "Notify for every new message" },
+ { value: "mentions", display: "Only @mentions", label: "Mentions only", hint: "Notify when someone @s you" },
+ { value: "nothing", display: "Nothing", label: "Muted", hint: "No notifications, no badges" },
+] as const satisfies readonly { value: NotificationLevelValue; display: string; label: string; hint: string }[]
+
+// A message notification level's DISPLAY string (the identity string carried by
+// UI props). Derived from the single source so it can't drift from `value`.
+export type NotifLevel = typeof NOTIF_LEVELS[number]["display"]
+
+// UI-only sentinel for the CHANNEL notification dropdown: "inherit the server
+// default". NOT a persisted level — data-wise it means "no channel override
+// row". Kept as a named constant so the ~4 sites that reference it can't
+// misspell the string.
+export const USE_SERVER_DEFAULT = "Use Server Default" as const
+
+// value ("all"|…) → identity display string. Unknown input passes through
+// unchanged (forward-compat with a future level value) — NOT silently coerced.
+export function notifLevelDisplay(value: string): string {
+ return NOTIF_LEVELS.find((l) => l.value === value)?.display ?? value
+}
+
+// display string (or an already-normalized value) → DB value. Recognizes both
+// directions off the single source. Unknown input falls back to the safest
+// non-destructive default `"all"` (never silently MUTES — the old scattered
+// `normalizeNotifLevel` fell back to `"mentions"`, which could quietly demote a
+// user's notifications; in practice the input is always a known dropdown
+// display string so the fallback is unreachable, but "all" is the fail-open
+// choice if it ever isn't).
+export function normalizeNotifLevel(input: string): NotificationLevelValue {
+ const byDisplay = NOTIF_LEVELS.find((l) => l.display === input)
+ if (byDisplay) return byDisplay.value
+ const byValue = NOTIF_LEVELS.find((l) => l.value === input)
+ if (byValue) return byValue.value
+ return "all"
+}
+
// Cache headers
export const CACHE_IMMUTABLE = "public, max-age=31536000, immutable"
export const CACHE_SHORT = "public, max-age=3600"
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 709c21a26..fa386b244 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -162,6 +162,9 @@ export {
MESSAGE_DEDUP_CACHE_MAX,
MESSAGE_DEDUP_CACHE_TRIM,
NOTIF_LEVELS,
+ USE_SERVER_DEFAULT,
+ notifLevelDisplay,
+ normalizeNotifLevel,
CACHE_IMMUTABLE,
CACHE_SHORT,
CACHE_REVALIDATE,
diff --git a/src/shared/test/constants.test.ts b/src/shared/test/constants.test.ts
index 1fc743bee..afede2b58 100644
--- a/src/shared/test/constants.test.ts
+++ b/src/shared/test/constants.test.ts
@@ -6,6 +6,9 @@ import {
IssueStatus, ACTIVE_ISSUE_STATUSES, TERMINAL_ISSUE_STATUSES, isTerminalIssueStatus,
MeetingStatus, TERMINAL_MEETING_STATUSES,
} from "../src/constants"
+import {
+ NOTIF_LEVELS, NOTIFICATION_LEVEL_VALUES, notifLevelDisplay, normalizeNotifLevel,
+} from "../src/constants/community"
describe("constants", () => {
it("OFFLINE_THRESHOLD_MS is 30s", () => expect(OFFLINE_THRESHOLD_MS).toBe(30_000))
@@ -108,3 +111,39 @@ describe("MeetingStatus", () => {
expect(TERMINAL_MEETING_STATUSES).toContain("failed")
})
})
+
+describe("notification-level bijection (single source)", () => {
+ it("NOTIF_LEVELS values exactly match the DB enum NOTIFICATION_LEVEL_VALUES", () => {
+ expect(NOTIF_LEVELS.map((l) => l.value)).toEqual([...NOTIFICATION_LEVEL_VALUES])
+ })
+
+ it("every level has a unique, non-empty display string (no drift/dupes)", () => {
+ const displays = NOTIF_LEVELS.map((l) => l.display)
+ expect(new Set(displays).size).toBe(displays.length)
+ for (const d of displays) expect(d.length).toBeGreaterThan(0)
+ })
+
+ it("notifLevelDisplay maps each value to its display; unknown passes through", () => {
+ expect(notifLevelDisplay("all")).toBe("All Messages")
+ expect(notifLevelDisplay("mentions")).toBe("Only @mentions")
+ expect(notifLevelDisplay("nothing")).toBe("Nothing")
+ expect(notifLevelDisplay("bogus")).toBe("bogus")
+ })
+
+ it("normalizeNotifLevel round-trips display→value and value→value", () => {
+ for (const l of NOTIF_LEVELS) {
+ expect(normalizeNotifLevel(l.display)).toBe(l.value) // display → value
+ expect(normalizeNotifLevel(l.value)).toBe(l.value) // value → value (idempotent)
+ }
+ })
+
+ it("normalizeNotifLevel/notifLevelDisplay are inverse for every level", () => {
+ for (const l of NOTIF_LEVELS) {
+ expect(normalizeNotifLevel(notifLevelDisplay(l.value))).toBe(l.value)
+ }
+ })
+
+ it("normalizeNotifLevel falls back to 'all' (fail-open, NOT the old silent 'mentions' mute) on unknown input", () => {
+ expect(normalizeNotifLevel("totally unknown")).toBe("all")
+ })
+})
diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
index 831288f38..c28174e61 100644
--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
@@ -18,7 +18,7 @@ import { AddMembersDialog } from "@/components/community/add-members-dialog"
import type { RightPanel, Msg, OpenProfile, Role } from "@/components/community/_types"
import { canManageServer } from "@/components/community/_types"
import type { MentionType } from "@alook/shared"
-import { isForum as isForumType, deriveThreadName } from "@alook/shared"
+import { isForum as isForumType, deriveThreadName, USE_SERVER_DEFAULT } from "@alook/shared"
import { resolveRowPresence } from "@/lib/community/presence"
import { makeUserNameResolver } from "@/lib/community/display-name"
import { avatarInitial } from "@/lib/community/avatar"
@@ -968,7 +968,7 @@ function ChannelView() {
forum={isForumType(parentChannel?.type)}
rightPanel={rightPanel}
onToggle={togglePanel}
- notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? "Use Server Default"}
+ notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? USE_SERVER_DEFAULT}
onSetNotifLevel={(l) => setChannelNotifMut.mutate({ channelId, level: l }, {
onError: (e) => toastApiError(e, "Failed to update notification level"),
})}
@@ -1073,7 +1073,7 @@ function ChannelView() {
forum
rightPanel={rightPanel}
onToggle={togglePanel}
- notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? "Use Server Default"}
+ notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? USE_SERVER_DEFAULT}
onSetNotifLevel={(l) => setChannelNotifMut.mutate({ channelId, level: l }, {
onError: (e) => toastApiError(e, "Failed to update notification level"),
})}
@@ -1130,7 +1130,7 @@ function ChannelView() {
channel={channelName}
rightPanel={rightPanel}
onToggle={togglePanel}
- notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? "Use Server Default"}
+ notifLevel={(channelNotif[channelId] as ChannelNotifLevel) ?? USE_SERVER_DEFAULT}
onSetNotifLevel={(l) => setChannelNotifMut.mutate({ channelId, level: l }, {
onError: (e) => toastApiError(e, "Failed to update notification level"),
})}
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index 8fa7dbabf..052b298f7 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -18,7 +18,7 @@ import { ServerSettings } from "@/components/community/server-settings"
import { ImageCropDialog } from "@/components/community/image-crop-dialog"
import { validateIconSourceFile } from "@/lib/community/image-crop"
import type { MobileZone, SettingsSection } from "@/components/community/_types"
-import { canManageServer, type ChannelType } from "@alook/shared"
+import { canManageServer, notifLevelDisplay, type ChannelType } from "@alook/shared"
import { resolveRowPresence } from "@/lib/community/presence"
import {
useCommunityStore,
@@ -92,7 +92,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
const presence = usePresence(serverId)
const { online: initialOnline } = presence
const notifs = useNotificationSettings()
- const notifLevel = notifs.server[serverId] ?? "Only @mentions"
+ const notifLevel = notifs.server[serverId] ?? notifLevelDisplay("mentions")
const channelNotif = notifs.channel
const currentChannelId = useCurrentChannelId()
const currentChannelMeta = useCurrentChannelMeta()
diff --git a/src/web/src/components/community/channel-header.tsx b/src/web/src/components/community/channel-header.tsx
index 6f55a52be..34c705ada 100644
--- a/src/web/src/components/community/channel-header.tsx
+++ b/src/web/src/components/community/channel-header.tsx
@@ -3,6 +3,7 @@
import { useEffect, useState } from "react"
import type { LucideIcon } from "lucide-react"
import { Bell, BellOff, Pin, Users, MessagesSquare, ChevronLeft, Check, Pencil, MoreHorizontal } from "lucide-react"
+import { NOTIF_LEVELS, USE_SERVER_DEFAULT, type NotifLevel } from "@alook/shared"
import { Button } from "@/components/ui/button"
import { avatarInitial } from "@/lib/community/avatar"
import { Input } from "@/components/ui/input"
@@ -38,7 +39,10 @@ export function ChannelHeaderSkeleton({ onBack }: { onBack?: () => void }) {
)
}
-export type ChannelNotifLevel = "Use Server Default" | "All Messages" | "Only @mentions" | "Nothing"
+// A channel can inherit the server default (UI-only sentinel) or pin one of the
+// three real levels. Derived from the shared single-source so the strings can't
+// drift from the notif-level bijection.
+export type ChannelNotifLevel = typeof USE_SERVER_DEFAULT | NotifLevel
export function ChannelHeader({
channel, rightPanel, onToggle, notifLevel, onSetNotifLevel, onBack,
@@ -100,7 +104,7 @@ export function ChannelHeader({
<div className="ml-auto flex items-center text-muted-foreground">
{tools?.members !== false && tool("members", Users, "Member list")}
<span className="mx-1 h-5 w-px bg-border/60" aria-hidden />
- <ChannelNotifDropdown level={notifLevel ?? "Use Server Default"} onSetLevel={onSetNotifLevel} />
+ <ChannelNotifDropdown level={notifLevel ?? USE_SERVER_DEFAULT} onSetLevel={onSetNotifLevel} />
{(tools?.threads !== false || tools?.pinned !== false) && (
<ChannelOverflowMenu
rightPanel={rightPanel}
@@ -180,18 +184,22 @@ function ServerCrumb({ id, name, icon, size = 5, className = "" }: { id: string;
)
}
-const NOTIF_LEVELS: { value: ChannelNotifLevel; label: string; hint: string }[] = [
- { value: "Use Server Default", label: "Use server default", hint: "Inherit this server's setting" },
- { value: "All Messages", label: "Every message", hint: "Notify for every new message" },
- { value: "Only @mentions", label: "Mentions only", hint: "Notify when someone @s you" },
- { value: "Nothing", label: "Muted", hint: "No notifications, no badges" },
+// The channel dropdown = the inherit sentinel first, then the three shared
+// levels (menu label + hint straight from the single source).
+const CHANNEL_NOTIF_OPTIONS: { value: ChannelNotifLevel; label: string; hint: string }[] = [
+ { value: USE_SERVER_DEFAULT, label: "Use server default", hint: "Inherit this server's setting" },
+ ...NOTIF_LEVELS.map((l) => ({ value: l.display, label: l.label, hint: l.hint })),
]
+// The "Nothing" display string (the muted state's level) pulled from the single
+// source so the mute-toggle comparison can't drift.
+const MUTED_LEVEL: NotifLevel = NOTIF_LEVELS.find((l) => l.value === "nothing")!.display
+
function ChannelNotifDropdown({ level, onSetLevel }: {
level: ChannelNotifLevel
onSetLevel?: (l: ChannelNotifLevel) => void
}) {
- const isMuted = level === "Nothing"
+ const isMuted = level === MUTED_LEVEL
return (
<DropdownMenu>
<DropdownMenuTrigger
@@ -200,12 +208,12 @@ function ChannelNotifDropdown({ level, onSetLevel }: {
{isMuted ? <BellOff className="size-4" /> : <Bell className="size-4" />}
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-60">
- <DropdownMenuItem onClick={() => onSetLevel?.(isMuted ? "Use Server Default" : "Nothing")}>
+ <DropdownMenuItem onClick={() => onSetLevel?.(isMuted ? USE_SERVER_DEFAULT : MUTED_LEVEL)}>
{isMuted ? <Bell className="size-4" /> : <BellOff className="size-4" />}
{isMuted ? "Unmute channel" : "Mute channel"}
</DropdownMenuItem>
<DropdownMenuSeparator />
- {NOTIF_LEVELS.map((n) => (
+ {CHANNEL_NOTIF_OPTIONS.map((n) => (
<DropdownMenuItem key={n.value} onClick={() => onSetLevel?.(n.value)}>
<span className="min-w-0 flex-1 text-sm">{n.label}</span>
{level === n.value && <Check className="size-4 shrink-0 text-primary" />}
diff --git a/src/web/src/components/community/server-settings.tsx b/src/web/src/components/community/server-settings.tsx
index 778621b0c..400be2f0e 100644
--- a/src/web/src/components/community/server-settings.tsx
+++ b/src/web/src/components/community/server-settings.tsx
@@ -4,6 +4,7 @@ import { useEffect, useRef, useState } from "react"
import type { LucideIcon } from "lucide-react"
import { useVirtualizer } from "@tanstack/react-virtual"
import { Settings, Users, Link2, Bell, ScrollText, Trash2, X, Shield, Search, Camera } from "lucide-react"
+import { NOTIF_LEVELS, notifLevelDisplay } from "@alook/shared"
import { ConfirmDialog } from "@/components/ui/confirm-dialog"
import { Button } from "@/components/ui/button"
import { formatMessageTime, formatRelativeTime } from "./format-time"
@@ -120,7 +121,7 @@ export function ServerSettings({
<TabsContent value="overview"><SettingsOverview serverId={serverId} serverName={serverName} serverDescription={serverDescription} serverIcon={serverIcon} onUploadIcon={onUploadIcon} onUpdateServer={onUpdateServer} onRequestDelete={() => setConfirmDelete(true)} /></TabsContent>
<TabsContent value="members"><SettingsMembers members={members} loading={membersLoading} loadingMore={membersLoadingMore} hasMore={membersHasMore} total={membersTotal} onLoadMore={onLoadMoreMembers} onSearch={onSearchMembers} onOpenProfile={onOpenProfile} onKickMember={onKickMember} onSetRole={onSetRole} /></TabsContent>
<TabsContent value="invites"><SettingsInvites invites={invites} loading={invitesLoading} onRevokeInvite={onRevokeInvite} onCopyInvite={onCopyInvite} /></TabsContent>
- <TabsContent value="notifications"><SettingsNotifications level={notifLevel ?? "Only @mentions"} onSetLevel={onSetNotifLevel} /></TabsContent>
+ <TabsContent value="notifications"><SettingsNotifications level={notifLevel ?? notifLevelDisplay("mentions")} onSetLevel={onSetNotifLevel} /></TabsContent>
<TabsContent value="audit"><SettingsAudit auditLog={auditLog} loading={auditLogLoading} /></TabsContent>
</div>
</div>
@@ -384,11 +385,13 @@ function SettingsInvites({ invites, loading, onRevokeInvite, onCopyInvite }: {
}
function SettingsNotifications({ level, onSetLevel }: { level: string; onSetLevel?: (l: string) => void }) {
- const levels: { value: string; label: string; hint: string }[] = [
- { value: "All messages", label: "Every message", hint: "Notify for every new message on this server" },
- { value: "Only @mentions", label: "Mentions only", hint: "Notify when someone @s you" },
- { value: "Nothing", label: "Muted", hint: "No notifications, no badges" },
- ]
+ // Server-level dropdown = the three shared levels (no "Use Server Default"
+ // sentinel — that's channel-only). Value/label/hint from the single source.
+ const levels: { value: string; label: string; hint: string }[] = NOTIF_LEVELS.map((l) => ({
+ value: l.display,
+ label: l.label,
+ hint: l.value === "all" ? "Notify for every new message on this server" : l.hint,
+ }))
return (
<div className="mx-auto max-w-md space-y-2">
<div className="mb-3 text-sm text-muted-foreground">Default notifications for this server</div>
diff --git a/src/web/src/hooks/community/mutations/notifications.ts b/src/web/src/hooks/community/mutations/notifications.ts
index e0da4cc9d..41e8f2d39 100644
--- a/src/web/src/hooks/community/mutations/notifications.ts
+++ b/src/web/src/hooks/community/mutations/notifications.ts
@@ -1,25 +1,19 @@
"use client"
import { useMutation, useQueryClient } from "@tanstack/react-query"
+import { normalizeNotifLevel, USE_SERVER_DEFAULT } from "@alook/shared"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import type { NotificationSettings } from "@/hooks/community/use-notification-settings"
/**
* Notification-level mutations. UI presents display strings ("All Messages",
- * "Only @mentions", "Nothing", "Use Server Default"). The API only accepts
- * lowercase — normalise inside the mutation. "Use Server Default" for a
- * channel means "delete the override row".
+ * "Only @mentions", "Nothing", USE_SERVER_DEFAULT). The API only accepts the
+ * lowercase values — `normalizeNotifLevel` (shared single-source) maps
+ * display→value. USE_SERVER_DEFAULT for a channel means "delete the override
+ * row" and is handled at the call sites BEFORE normalization.
*/
-function normalizeNotifLevel(level: string): "all" | "mentions" | "nothing" {
- if (level === "All Messages") return "all"
- if (level === "Only @mentions") return "mentions"
- if (level === "Nothing") return "nothing"
- if (level === "all" || level === "mentions" || level === "nothing") return level
- return "mentions"
-}
-
// ── Set server notification level ─────────────────────────────────────────
export type SetServerNotifLevelArgs = { serverId: string; level: string }
@@ -66,7 +60,7 @@ export function useSetChannelNotif() {
{ snapshot: NotificationSettings | undefined }
>({
mutationFn: async ({ channelId, level }) => {
- if (level === "Use Server Default") {
+ if (level === USE_SERVER_DEFAULT) {
await apiFetch(`/api/community/users/me/notifications/channel/${channelId}`, {
method: "DELETE",
})
@@ -84,7 +78,7 @@ export function useSetChannelNotif() {
queryClient.setQueryData<NotificationSettings | undefined>(key, (prev) => {
if (!prev) return prev
const nextChannel = { ...prev.channel }
- if (args.level === "Use Server Default") {
+ if (args.level === USE_SERVER_DEFAULT) {
delete nextChannel[args.channelId]
} else {
nextChannel[args.channelId] = args.level
diff --git a/src/web/src/hooks/community/use-notification-settings.ts b/src/web/src/hooks/community/use-notification-settings.ts
index 6439b6dbd..b2e9438c2 100644
--- a/src/web/src/hooks/community/use-notification-settings.ts
+++ b/src/web/src/hooks/community/use-notification-settings.ts
@@ -1,6 +1,7 @@
"use client"
import { useQuery, type UseQueryResult } from "@tanstack/react-query"
+import { notifLevelDisplay } from "@alook/shared"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
@@ -28,13 +29,10 @@ export type NotificationSettings = {
const EMPTY_NOTIF_SERVER: Readonly<Record<string, string>> = Object.freeze({})
const EMPTY_NOTIF_CHANNEL: Readonly<Record<string, string>> = Object.freeze({})
-// API-level ("all"|"mentions"|"nothing") → display strings.
-function displayNotifLevel(level: string): string {
- if (level === "all") return "All Messages"
- if (level === "mentions") return "Only @mentions"
- if (level === "nothing") return "Nothing"
- return level
-}
+// API-level ("all"|"mentions"|"nothing") → display string, from the shared
+// single-source bijection (`notifLevelDisplay`). Was a hand-rolled map that
+// drifted on casing ("All Messages" vs the shared const's "All messages").
+const displayNotifLevel = notifLevelDisplay
export const notificationSettingsQueryFn = async (): Promise<NotificationSettings> => {
const rows = await apiFetch<NotificationSettingRow[]>(