Skip to content

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

Go

MUL-4798: make Inbox notification preference updates atomic (#5451)

Jiayuan Zhang19e52e007c4e
diff --git a/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx b/apps/mobile/app/(app)/[workspace]/more/settings/notifications.tsx
index 3652160941..aaf106a11e 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. 5 inbox groups + system_notifications
- * toggle, each backed by an optimistic PUT /api/notification-preferences.
+ * toggle, each backed by an optimistic PATCH /api/notification-preferences.
*
* Copy mirrors packages/views/settings/components/notifications-tab.tsx but
* hardcoded English (mobile has no i18n infra yet). The group labels MUST
diff --git a/apps/mobile/data/api.ts b/apps/mobile/data/api.ts
index 1c50770789..50e1843dcc 100644
--- a/apps/mobile/data/api.ts
+++ b/apps/mobile/data/api.ts
@@ -211,7 +211,7 @@ class ApiClient {
// Backend middleware (server/internal/middleware/workspace.go) resolves
// slug → ws UUID and gates membership. Mirrors packages/core/api/client.ts.
const slug = getCurrentSlug();
- if (slug) {
+ if (slug && !headers["X-Workspace-Slug"]) {
headers["X-Workspace-Slug"] = slug;
}
@@ -411,12 +411,19 @@ class ApiClient {
async updateNotificationPreferences(
preferences: NotificationPreferences,
+ workspaceSlug?: string,
): Promise<NotificationPreferenceResponse> {
return this.fetchValidatedWith(
"/api/notification-preferences",
NotificationPreferenceResponseSchema,
EMPTY_NOTIFICATION_PREFERENCES,
- { method: "PUT", body: JSON.stringify({ preferences }) },
+ {
+ method: "PATCH",
+ headers: workspaceSlug
+ ? { "X-Workspace-Slug": workspaceSlug }
+ : undefined,
+ body: JSON.stringify({ preferences }),
+ },
{ endpoint: "updateNotificationPreferences" },
);
}
diff --git a/apps/mobile/data/mutations/notification-preferences.ts b/apps/mobile/data/mutations/notification-preferences.ts
index c80485e782..a6cdd4235e 100644
--- a/apps/mobile/data/mutations/notification-preferences.ts
+++ b/apps/mobile/data/mutations/notification-preferences.ts
@@ -4,43 +4,179 @@
* "Mobile-owned updaters" rule (don't import web mutations; key shape is
* independent and may drift).
*
- * Optimistic policy: patch cache → fire PUT → rollback on error → invalidate
+ * Optimistic policy: patch cache → fire PATCH → rollback on error → invalidate
* on settle (mirrors mobile inbox mutations + CLAUDE.md "Mutations are
* optimistic by default"). Toggle latency on cellular is real — the Switch
* snapping back if the request hangs would look broken.
*/
-import { useMutation, useQueryClient } from "@tanstack/react-query";
+import {
+ useMutation,
+ useQueryClient,
+ type MutateOptions,
+} from "@tanstack/react-query";
+import { useCallback, useRef } from "react";
import type {
NotificationPreferenceResponse,
NotificationPreferences,
} from "@multica/core/types";
+import {
+ applyNotificationPreferencePatch,
+ deriveNotificationPreferencePatch,
+ rollbackNotificationPreferencePatch,
+} from "@multica/core/notification-preferences/patch";
import { api } from "@/data/api";
import { useWorkspaceStore } from "@/data/workspace-store";
import { notificationPreferenceKeys } from "@/data/queries/notification-preferences";
+interface NotificationPreferenceMutationVariables {
+ preferences: NotificationPreferences;
+ patch: NotificationPreferences;
+ workspaceId: string | null;
+ workspaceSlug: string | null;
+}
+
+interface NotificationPreferenceMutationContext {
+ previous: NotificationPreferenceResponse | undefined;
+ key: readonly unknown[];
+}
+
+type ExternalMutationOptions = MutateOptions<
+ NotificationPreferenceResponse,
+ Error,
+ NotificationPreferences,
+ NotificationPreferenceMutationContext
+>;
+
+type InternalMutationOptions = MutateOptions<
+ NotificationPreferenceResponse,
+ Error,
+ NotificationPreferenceMutationVariables,
+ NotificationPreferenceMutationContext
+>;
+
+function mapMutationOptions(
+ preferences: NotificationPreferences,
+ options: ExternalMutationOptions | undefined,
+): InternalMutationOptions | undefined {
+ if (!options) return undefined;
+
+ return {
+ onSuccess: options.onSuccess
+ ? (data, _variables, result, context) =>
+ options.onSuccess?.(data, preferences, result, context)
+ : undefined,
+ onError: options.onError
+ ? (error, _variables, result, context) =>
+ options.onError?.(error, preferences, result, context)
+ : undefined,
+ onSettled: options.onSettled
+ ? (data, error, _variables, result, context) =>
+ options.onSettled?.(data, error, preferences, result, context)
+ : undefined,
+ };
+}
+
export function useUpdateNotificationPreferences() {
const qc = useQueryClient();
const wsId = useWorkspaceStore((s) => s.currentWorkspaceId);
+ const workspaceSlug = useWorkspaceStore((s) => s.currentWorkspaceSlug);
+ const key = notificationPreferenceKeys.all(wsId);
+ const renderedPreferences =
+ qc.getQueryData<NotificationPreferenceResponse>(key)?.preferences ?? {};
+ const renderedPreferencesRef = useRef(renderedPreferences);
+ renderedPreferencesRef.current = renderedPreferences;
- return useMutation({
- mutationFn: (preferences: NotificationPreferences) =>
- api.updateNotificationPreferences(preferences),
- onMutate: async (preferences) => {
- const key = notificationPreferenceKeys.all(wsId);
- await qc.cancelQueries({ queryKey: key });
- const prev = qc.getQueryData<NotificationPreferenceResponse>(key);
- qc.setQueryData<NotificationPreferenceResponse>(key, (old) =>
- old
- ? { ...old, preferences }
- : { workspace_id: wsId ?? "", preferences },
- );
- return { prev, key };
+ // Match Core's concurrency contract: serialize writes per workspace and
+ // capture the slug so queued work cannot follow a later workspace switch.
+ const mutation = useMutation<
+ NotificationPreferenceResponse,
+ Error,
+ NotificationPreferenceMutationVariables,
+ NotificationPreferenceMutationContext
+ >({
+ mutationKey: key,
+ scope: { id: `notification-preferences:${wsId ?? "unscoped"}` },
+ mutationFn: ({ patch, workspaceSlug: targetWorkspaceSlug }) => {
+ if (!targetWorkspaceSlug) {
+ throw new Error(
+ "Workspace context is required to update notifications",
+ );
+ }
+ return api.updateNotificationPreferences(patch, targetWorkspaceSlug);
+ },
+ onMutate: async ({ patch, workspaceId }) => {
+ const targetKey = notificationPreferenceKeys.all(workspaceId);
+ await qc.cancelQueries({ queryKey: targetKey });
+ const previous =
+ qc.getQueryData<NotificationPreferenceResponse>(targetKey);
+ qc.setQueryData<NotificationPreferenceResponse>(targetKey, (old) => ({
+ ...(old ?? { workspace_id: workspaceId ?? "" }),
+ preferences: applyNotificationPreferencePatch(
+ old?.preferences ?? {},
+ patch,
+ ),
+ }));
+ return { previous, key: targetKey };
},
- onError: (_err, _vars, ctx) => {
- if (ctx?.prev) qc.setQueryData(ctx.key, ctx.prev);
+ onError: (_error, { patch, workspaceId }, context) => {
+ const targetKey =
+ context?.key ?? notificationPreferenceKeys.all(workspaceId);
+ qc.setQueryData<NotificationPreferenceResponse>(targetKey, (old) => ({
+ ...(old ?? { workspace_id: workspaceId ?? "" }),
+ preferences: rollbackNotificationPreferencePatch(
+ old?.preferences ?? {},
+ patch,
+ context?.previous?.preferences ?? {},
+ ),
+ }));
},
- onSettled: (_d, _e, _v, ctx) => {
- qc.invalidateQueries({ queryKey: ctx?.key ?? notificationPreferenceKeys.all(wsId) });
+ onSettled: (_data, _error, { workspaceId }, context) => {
+ const mutationKey = notificationPreferenceKeys.all(workspaceId);
+ // The settling mutation is still counted; only the final queued write
+ // should trigger an authoritative refetch.
+ if (qc.isMutating({ mutationKey }) > 1) return;
+ qc.invalidateQueries({ queryKey: context?.key ?? mutationKey });
},
});
+
+ const mutate = useCallback(
+ (
+ preferences: NotificationPreferences,
+ options?: ExternalMutationOptions,
+ ) => {
+ const patch = deriveNotificationPreferencePatch(
+ renderedPreferencesRef.current,
+ preferences,
+ );
+ mutation.mutate(
+ { preferences, patch, workspaceId: wsId, workspaceSlug },
+ mapMutationOptions(preferences, options),
+ );
+ },
+ [mutation, workspaceSlug, wsId],
+ );
+
+ const mutateAsync = useCallback(
+ (
+ preferences: NotificationPreferences,
+ options?: ExternalMutationOptions,
+ ) => {
+ const patch = deriveNotificationPreferencePatch(
+ renderedPreferencesRef.current,
+ preferences,
+ );
+ return mutation.mutateAsync(
+ { preferences, patch, workspaceId: wsId, workspaceSlug },
+ mapMutationOptions(preferences, options),
+ );
+ },
+ [mutation, workspaceSlug, wsId],
+ );
+
+ return {
+ ...mutation,
+ variables: mutation.variables?.preferences,
+ mutate,
+ mutateAsync,
+ };
}
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 787259b11e..e8496de8b0 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -44,6 +44,70 @@ describe("ApiClient label response schemas", () => {
});
});
+describe("ApiClient notification preferences", () => {
+ it("sends atomic preference updates with PATCH", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ workspace_id: "workspace-1",
+ preferences: {
+ status_changes: "muted",
+ comments: "muted",
+ },
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+ await expect(
+ client.updateNotificationPreferences(
+ { comments: "muted" },
+ "workspace-one",
+ ),
+ ).resolves.toEqual({
+ workspace_id: "workspace-1",
+ preferences: {
+ status_changes: "muted",
+ comments: "muted",
+ },
+ });
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls[0]?.[0]).toBe(
+ "https://api.example.test/api/notification-preferences",
+ );
+ expect(fetchMock.mock.calls[0]?.[1]).toEqual(
+ expect.objectContaining({
+ method: "PATCH",
+ headers: expect.objectContaining({
+ "X-Workspace-Slug": "workspace-one",
+ }),
+ body: JSON.stringify({ preferences: { comments: "muted" } }),
+ }),
+ );
+ });
+
+ it("falls back safely when a preference response is malformed", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({ workspace_id: "workspace-1", preferences: [] }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ ),
+ );
+
+ const client = new ApiClient("https://api.example.test");
+ await expect(client.getNotificationPreferences()).resolves.toEqual({
+ workspace_id: "",
+ preferences: {},
+ });
+ });
+});
+
describe("ApiClient", () => {
it("preserves HTTP status on failed requests", async () => {
vi.stubGlobal(
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index c075626985..d3ced64a18 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -238,6 +238,8 @@ import {
EMPTY_CREATE_FEEDBACK_RESPONSE,
InboxUnreadSummarySchema,
EMPTY_INBOX_UNREAD_SUMMARY,
+ NotificationPreferenceResponseSchema,
+ EMPTY_NOTIFICATION_PREFERENCE_RESPONSE,
LabelSchema,
ListLabelsResponseSchema,
IssuePropertySchema,
@@ -1615,17 +1617,35 @@ export class ApiClient {
// preferences — e.g. honoring the mute setting of the workspace an inbox
// notification came from while the user is viewing a different one (#3766).
async getNotificationPreferences(workspaceSlug?: string): Promise<NotificationPreferenceResponse> {
- return this.fetch(
+ const raw = await this.fetch<unknown>(
"/api/notification-preferences",
workspaceSlug ? { headers: { "X-Workspace-Slug": workspaceSlug } } : undefined,
);
+ return parseWithFallback(
+ raw,
+ NotificationPreferenceResponseSchema,
+ EMPTY_NOTIFICATION_PREFERENCE_RESPONSE,
+ { endpoint: "GET /api/notification-preferences" },
+ );
}
- async updateNotificationPreferences(preferences: NotificationPreferences): Promise<NotificationPreferenceResponse> {
- return this.fetch("/api/notification-preferences", {
- method: "PUT",
+ async updateNotificationPreferences(
+ preferences: NotificationPreferences,
+ workspaceSlug?: string,
+ ): Promise<NotificationPreferenceResponse> {
+ const raw = await this.fetch<unknown>("/api/notification-preferences", {
+ method: "PATCH",
+ headers: workspaceSlug
+ ? { "X-Workspace-Slug": workspaceSlug }
+ : undefined,
body: JSON.stringify({ preferences }),
});
+ return parseWithFallback(
+ raw,
+ NotificationPreferenceResponseSchema,
+ EMPTY_NOTIFICATION_PREFERENCE_RESPONSE,
+ { endpoint: "PATCH /api/notification-preferences" },
+ );
}
// App Config
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 3162b530f7..58fe66d9f0 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -26,6 +26,7 @@ import type {
ListIssuesResponse,
ListLabelsResponse,
ListWebhookDeliveriesResponse,
+ NotificationPreferenceResponse,
ResourceLabelsResponse,
SearchIssuesResponse,
SearchProjectsResponse,
@@ -339,6 +340,18 @@ export const EMPTY_APP_CONFIG: AppConfigResponse = {
feature_flags: {},
};
+// Preference keys may grow over time, so keep both the key and value spaces
+// forward-compatible while still rejecting non-string persisted data.
+export const NotificationPreferenceResponseSchema = z.object({
+ workspace_id: z.string(),
+ preferences: z.record(z.string(), z.string()).default({}),
+}).loose();
+
+export const EMPTY_NOTIFICATION_PREFERENCE_RESPONSE: NotificationPreferenceResponse = {
+ workspace_id: "",
+ preferences: {},
+};
+
export const CreateFeedbackResponseSchema = z.object({
id: z.string(),
created_at: z.string(),
diff --git a/packages/core/notification-preferences/index.ts b/packages/core/notification-preferences/index.ts
index 868bf87e53..4b3efba544 100644
--- a/packages/core/notification-preferences/index.ts
+++ b/packages/core/notification-preferences/index.ts
@@ -1,2 +1,3 @@
export * from "./queries";
export * from "./mutations";
+export * from "./patch";
diff --git a/packages/core/notification-preferences/mutations.test.tsx b/packages/core/notification-preferences/mutations.test.tsx
new file mode 100644
index 0000000000..4a5e247df7
--- /dev/null
+++ b/packages/core/notification-preferences/mutations.test.tsx
@@ -0,0 +1,267 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+
+import { setApiInstance } from "../api";
+import type { ApiClient } from "../api/client";
+import type {
+ NotificationPreferenceResponse,
+ NotificationPreferences,
+} from "../types";
+import { useUpdateNotificationPreferences } from "./mutations";
+import { notificationPreferenceKeys } from "./queries";
+
+vi.mock("../hooks", () => ({
+ useWorkspaceId: () => "workspace-1",
+}));
+
+const WORKSPACE_ID = "workspace-1";
+const WORKSPACE_SLUG = "workspace-one";
+let activeWorkspaceSlug = WORKSPACE_SLUG;
+
+vi.mock("../paths", () => ({
+ useRequiredWorkspaceSlug: () => activeWorkspaceSlug,
+}));
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+ return { promise, resolve };
+}
+
+function createWrapper(queryClient: QueryClient) {
+ return function Wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>
+ {children}
+ </QueryClientProvider>
+ );
+ };
+}
+
+describe("useUpdateNotificationPreferences", () => {
+ let queryClient: QueryClient;
+ let updateNotificationPreferences: ReturnType<
+ typeof vi.fn<
+ (
+ preferences: NotificationPreferences,
+ workspaceSlug?: string,
+ ) => Promise<NotificationPreferenceResponse>
+ >
+ >;
+
+ beforeEach(() => {
+ activeWorkspaceSlug = WORKSPACE_SLUG;
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ updateNotificationPreferences = vi.fn(async (preferences) => ({
+ workspace_id: WORKSPACE_ID,
+ preferences,
+ }));
+ setApiInstance({ updateNotificationPreferences } as unknown as ApiClient);
+ });
+
+ afterEach(() => {
+ queryClient.clear();
+ vi.restoreAllMocks();
+ });
+
+ it("preserves an existing status mute when another group changes", async () => {
+ queryClient.setQueryData(notificationPreferenceKeys.all(WORKSPACE_ID), {
+ workspace_id: WORKSPACE_ID,
+ preferences: { status_changes: "muted" },
+ });
+ const { result } = renderHook(
+ () => useUpdateNotificationPreferences(),
+ { wrapper: createWrapper(queryClient) },
+ );
+
+ act(() => {
+ result.current.mutate({
+ status_changes: "muted",
+ comments: "muted",
+ });
+ });
+
+ await waitFor(() => {
+ expect(updateNotificationPreferences).toHaveBeenCalledWith(
+ { comments: "muted" },
+ WORKSPACE_SLUG,
+ );
+ });
+ });
+
+ it("sends all explicitly when a muted group is enabled", async () => {
+ queryClient.setQueryData(notificationPreferenceKeys.all(WORKSPACE_ID), {
+ workspace_id: WORKSPACE_ID,
+ preferences: {
+ status_changes: "muted",
+ comments: "muted",
+ },
+ });
+ const { result } = renderHook(
+ () => useUpdateNotificationPreferences(),
+ { wrapper: createWrapper(queryClient) },
+ );
+
+ act(() => {
+ result.current.mutate({ comments: "muted" });
+ });
+
+ await waitFor(() => {
+ expect(updateNotificationPreferences).toHaveBeenCalledWith(
+ { status_changes: "all" },
+ WORKSPACE_SLUG,
+ );
+ });
+ });
+
+ it("derives independent patches for rapid toggles from one render", async () => {
+ queryClient.setQueryData(notificationPreferenceKeys.all(WORKSPACE_ID), {
+ workspace_id: WORKSPACE_ID,
+ preferences: { status_changes: "muted" },
+ });
+ const { result } = renderHook(
+ () => useUpdateNotificationPreferences(),
+ { wrapper: createWrapper(queryClient) },
+ );
+
+ act(() => {
+ result.current.mutate({
+ status_changes: "muted",
+ comments: "muted",
+ });
+ result.current.mutate({
+ status_changes: "muted",
+ updates: "muted",
+ });
+ });
+
+ await waitFor(() => {
+ expect(updateNotificationPreferences).toHaveBeenCalledTimes(2);
+ });
+ expect(updateNotificationPreferences.mock.calls).toEqual([
+ [{ comments: "muted" }, WORKSPACE_SLUG],
+ [{ updates: "muted" }, WORKSPACE_SLUG],
+ ]);
+ });
+
+ it("serializes same-key toggles and keeps queued writes in their workspace", async () => {
+ const first = deferred<NotificationPreferenceResponse>();
+ const second = deferred<NotificationPreferenceResponse>();
+ updateNotificationPreferences
+ .mockImplementationOnce(() => first.promise)
+ .mockImplementationOnce(() => second.promise);
+ queryClient.setQueryData(notificationPreferenceKeys.all(WORKSPACE_ID), {
+ workspace_id: WORKSPACE_ID,
+ preferences: {},
+ });
+ const { result, rerender } = renderHook(
+ () => useUpdateNotificationPreferences(),
+ { wrapper: createWrapper(queryClient) },
+ );
+
+ act(() => {
+ result.current.mutate({ status_changes: "muted" });
+ });
+ await waitFor(() => {
+ expect(
+ queryClient.getQueryData<NotificationPreferenceResponse>(
+ notificationPreferenceKeys.all(WORKSPACE_ID),
+ )?.preferences,
+ ).toEqual({ status_changes: "muted" });
+ });
+
+ rerender();
+ act(() => {
+ result.current.mutate({});
+ });
+
+ await waitFor(() => {
+ expect(
+ queryClient.getQueryData<NotificationPreferenceResponse>(
+ notificationPreferenceKeys.all(WORKSPACE_ID),
+ )?.preferences,
+ ).toEqual({});
+ });
+ expect(updateNotificationPreferences).toHaveBeenCalledTimes(1);
+
+ activeWorkspaceSlug = "workspace-two";
+ rerender();
+ first.resolve({
+ workspace_id: WORKSPACE_ID,
+ preferences: { status_changes: "muted" },
+ });
+ await waitFor(() => {
+ expect(updateNotificationPreferences).toHaveBeenCalledTimes(2);
+ });
+ expect(updateNotificationPreferences.mock.calls[1]).toEqual([
+ { status_changes: "all" },
+ WORKSPACE_SLUG,
+ ]);
+
+ second.resolve({ workspace_id: WORKSPACE_ID, preferences: {} });
+ await waitFor(() => {
+ expect(result.current.isPending).toBe(false);
+ });
+ });
+
+ it("keeps later optimistic patches until the final mutation settles", async () => {
+ const first = deferred<NotificationPreferenceResponse>();
+ const second = deferred<NotificationPreferenceResponse>();
+ updateNotificationPreferences
+ .mockImplementationOnce(() => first.promise)
+ .mockImplementationOnce(() => second.promise);
+ queryClient.setQueryData(notificationPreferenceKeys.all(WORKSPACE_ID), {
+ workspace_id: WORKSPACE_ID,
+ preferences: {},
+ });
+ const invalidateQueries = vi.spyOn(queryClient, "invalidateQueries");
+ const { result } = renderHook(
+ () => useUpdateNotificationPreferences(),
+ { wrapper: createWrapper(queryClient) },
+ );
+
+ act(() => {
+ result.current.mutate({ comments: "muted" });
+ result.current.mutate({ updates: "muted" });
+ });
+ await waitFor(() => {
+ expect(
+ queryClient.getQueryData<NotificationPreferenceResponse>(
+ notificationPreferenceKeys.all(WORKSPACE_ID),
+ )?.preferences,
+ ).toEqual({ comments: "muted", updates: "muted" });
+ });
+ expect(updateNotificationPreferences).toHaveBeenCalledTimes(1);
+
+ first.resolve({
+ workspace_id: WORKSPACE_ID,
+ preferences: { comments: "muted" },
+ });
+ await waitFor(() => {
+ expect(updateNotificationPreferences).toHaveBeenCalledTimes(2);
+ });
+ expect(invalidateQueries).not.toHaveBeenCalled();
+ expect(
+ queryClient.getQueryData<NotificationPreferenceResponse>(
+ notificationPreferenceKeys.all(WORKSPACE_ID),
+ )?.preferences,
+ ).toEqual({ comments: "muted", updates: "muted" });
+
+ second.resolve({
+ workspace_id: WORKSPACE_ID,
+ preferences: { comments: "muted", updates: "muted" },
+ });
+ await waitFor(() => {
+ expect(invalidateQueries).toHaveBeenCalledTimes(1);
+ });
+ });
+});
diff --git a/packages/core/notification-preferences/mutations.ts b/packages/core/notification-preferences/mutations.ts
index 025e2c91ea..1b822d526e 100644
--- a/packages/core/notification-preferences/mutations.ts
+++ b/packages/core/notification-preferences/mutations.ts
@@ -1,34 +1,167 @@
-import { useMutation, useQueryClient } from "@tanstack/react-query";
+import {
+ useMutation,
+ useQueryClient,
+ type MutateOptions,
+} from "@tanstack/react-query";
+import { useCallback, useRef } from "react";
import { api } from "../api";
import { useWorkspaceId } from "../hooks";
+import { useRequiredWorkspaceSlug } from "../paths";
import { notificationPreferenceKeys } from "./queries";
-import type { NotificationPreferences, NotificationPreferenceResponse } from "../types";
+import type {
+ NotificationPreferences,
+ NotificationPreferenceResponse,
+} from "../types";
+import {
+ applyNotificationPreferencePatch,
+ deriveNotificationPreferencePatch,
+ rollbackNotificationPreferencePatch,
+} from "./patch";
+
+interface NotificationPreferenceMutationVariables {
+ preferences: NotificationPreferences;
+ patch: NotificationPreferences;
+ workspaceId: string;
+ workspaceSlug: string;
+}
+
+interface NotificationPreferenceMutationContext {
+ previous: NotificationPreferenceResponse | undefined;
+ key: readonly unknown[];
+}
+
+type ExternalMutationOptions = MutateOptions<
+ NotificationPreferenceResponse,
+ Error,
+ NotificationPreferences,
+ NotificationPreferenceMutationContext
+>;
+
+type InternalMutationOptions = MutateOptions<
+ NotificationPreferenceResponse,
+ Error,
+ NotificationPreferenceMutationVariables,
+ NotificationPreferenceMutationContext
+>;
+
+function mapMutationOptions(
+ preferences: NotificationPreferences,
+ options: ExternalMutationOptions | undefined,
+): InternalMutationOptions | undefined {
+ if (!options) return undefined;
+
+ return {
+ onSuccess: options.onSuccess
+ ? (data, _variables, result, context) =>
+ options.onSuccess?.(data, preferences, result, context)
+ : undefined,
+ onError: options.onError
+ ? (error, _variables, result, context) =>
+ options.onError?.(error, preferences, result, context)
+ : undefined,
+ onSettled: options.onSettled
+ ? (data, error, _variables, result, context) =>
+ options.onSettled?.(data, error, preferences, result, context)
+ : undefined,
+ };
+}
export function useUpdateNotificationPreferences() {
const qc = useQueryClient();
const wsId = useWorkspaceId();
+ const workspaceSlug = useRequiredWorkspaceSlug();
+ const key = notificationPreferenceKeys.all(wsId);
+ const renderedPreferences =
+ qc.getQueryData<NotificationPreferenceResponse>(key)?.preferences ?? {};
+ const renderedPreferencesRef = useRef(renderedPreferences);
+ renderedPreferencesRef.current = renderedPreferences;
- return useMutation({
- mutationFn: (preferences: NotificationPreferences) =>
- api.updateNotificationPreferences(preferences),
- onMutate: async (preferences) => {
- await qc.cancelQueries({ queryKey: notificationPreferenceKeys.all(wsId) });
- const prev = qc.getQueryData<NotificationPreferenceResponse>(
- notificationPreferenceKeys.all(wsId),
- );
- qc.setQueryData<NotificationPreferenceResponse>(
- notificationPreferenceKeys.all(wsId),
- (old) => old ? { ...old, preferences } : { workspace_id: wsId, preferences },
- );
- return { prev };
+ // Serialize the workspace's preference writes so a slower earlier PATCH
+ // cannot overwrite the user's latest toggle. Variables also capture the
+ // workspace slug because a queued mutation may execute after navigation.
+ const mutation = useMutation<
+ NotificationPreferenceResponse,
+ Error,
+ NotificationPreferenceMutationVariables,
+ NotificationPreferenceMutationContext
+ >({
+ mutationKey: key,
+ scope: { id: `notification-preferences:${wsId}` },
+ mutationFn: ({ patch, workspaceSlug: targetWorkspaceSlug }) =>
+ api.updateNotificationPreferences(patch, targetWorkspaceSlug),
+ onMutate: async ({ patch, workspaceId }) => {
+ const targetKey = notificationPreferenceKeys.all(workspaceId);
+ await qc.cancelQueries({ queryKey: targetKey });
+ const previous =
+ qc.getQueryData<NotificationPreferenceResponse>(targetKey);
+ qc.setQueryData<NotificationPreferenceResponse>(targetKey, (old) => ({
+ ...(old ?? { workspace_id: workspaceId }),
+ preferences: applyNotificationPreferencePatch(
+ old?.preferences ?? {},
+ patch,
+ ),
+ }));
+ return { previous, key: targetKey };
},
- onError: (_err, _vars, ctx) => {
- if (ctx?.prev) {
- qc.setQueryData(notificationPreferenceKeys.all(wsId), ctx.prev);
- }
+ onError: (_error, { patch, workspaceId }, context) => {
+ const targetKey =
+ context?.key ?? notificationPreferenceKeys.all(workspaceId);
+ qc.setQueryData<NotificationPreferenceResponse>(targetKey, (old) => ({
+ ...(old ?? { workspace_id: workspaceId }),
+ preferences: rollbackNotificationPreferencePatch(
+ old?.preferences ?? {},
+ patch,
+ context?.previous?.preferences ?? {},
+ ),
+ }));
},
- onSettled: () => {
- qc.invalidateQueries({ queryKey: notificationPreferenceKeys.all(wsId) });
+ onSettled: (_data, _error, { workspaceId }, context) => {
+ const mutationKey = notificationPreferenceKeys.all(workspaceId);
+ // The current mutation is still counted during onSettled. Reconcile
+ // only after every queued optimistic patch for this workspace finishes.
+ if (qc.isMutating({ mutationKey }) > 1) return;
+ qc.invalidateQueries({ queryKey: context?.key ?? mutationKey });
},
});
+
+ const mutate = useCallback(
+ (
+ preferences: NotificationPreferences,
+ options?: ExternalMutationOptions,
+ ) => {
+ const patch = deriveNotificationPreferencePatch(
+ renderedPreferencesRef.current,
+ preferences,
+ );
+ mutation.mutate(
+ { preferences, patch, workspaceId: wsId, workspaceSlug },
+ mapMutationOptions(preferences, options),
+ );
+ },
+ [mutation, workspaceSlug, wsId],
+ );
+
+ const mutateAsync = useCallback(
+ (
+ preferences: NotificationPreferences,
+ options?: ExternalMutationOptions,
+ ) => {
+ const patch = deriveNotificationPreferencePatch(
+ renderedPreferencesRef.current,
+ preferences,
+ );
+ return mutation.mutateAsync(
+ { preferences, patch, workspaceId: wsId, workspaceSlug },
+ mapMutationOptions(preferences, options),
+ );
+ },
+ [mutation, workspaceSlug, wsId],
+ );
+
+ return {
+ ...mutation,
+ variables: mutation.variables?.preferences,
+ mutate,
+ mutateAsync,
+ };
}
diff --git a/packages/core/notification-preferences/patch.test.ts b/packages/core/notification-preferences/patch.test.ts
new file mode 100644
index 0000000000..d2763452c4
--- /dev/null
+++ b/packages/core/notification-preferences/patch.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vitest";
+import {
+ applyNotificationPreferencePatch,
+ deriveNotificationPreferencePatch,
+ rollbackNotificationPreferencePatch,
+} from "./patch";
+
+describe("notification preference patches", () => {
+ it("sends only the changed key when another muted preference is present", () => {
+ expect(
+ deriveNotificationPreferencePatch(
+ { status_changes: "muted" },
+ { status_changes: "muted", comments: "muted" },
+ ),
+ ).toEqual({ comments: "muted" });
+ });
+
+ it("uses an explicit all value when enabling a previously muted group", () => {
+ expect(
+ deriveNotificationPreferencePatch(
+ { status_changes: "muted", comments: "muted" },
+ { comments: "muted" },
+ ),
+ ).toEqual({ status_changes: "all" });
+ });
+
+ it("merges optimistic patches without dropping unrelated preferences", () => {
+ expect(
+ applyNotificationPreferencePatch(
+ { status_changes: "muted" },
+ { comments: "muted" },
+ ),
+ ).toEqual({ status_changes: "muted", comments: "muted" });
+ });
+
+ it("does not roll back a key that a later mutation already changed", () => {
+ expect(
+ rollbackNotificationPreferencePatch(
+ { comments: "muted" },
+ { comments: "muted" },
+ {},
+ ),
+ ).toEqual({});
+
+ expect(
+ rollbackNotificationPreferencePatch(
+ {},
+ { comments: "muted" },
+ {},
+ ),
+ ).toEqual({});
+ });
+});
diff --git a/packages/core/notification-preferences/patch.ts b/packages/core/notification-preferences/patch.ts
new file mode 100644
index 0000000000..34f27b18ce
--- /dev/null
+++ b/packages/core/notification-preferences/patch.ts
@@ -0,0 +1,92 @@
+import type {
+ NotificationGroupKey,
+ NotificationGroupValue,
+ NotificationPreferences,
+} from "../types";
+
+const NOTIFICATION_GROUP_KEYS: readonly NotificationGroupKey[] = [
+ "assignments",
+ "status_changes",
+ "comments",
+ "updates",
+ "agent_activity",
+ "system_notifications",
+];
+
+function preferenceValue(
+ preferences: NotificationPreferences,
+ key: NotificationGroupKey,
+): NotificationGroupValue {
+ return preferences[key] ?? "all";
+}
+
+/**
+ * Convert the full preference object produced by the settings UI into the
+ * smallest atomic patch. Missing keys mean the default value ("all").
+ */
+export function deriveNotificationPreferencePatch(
+ previous: NotificationPreferences,
+ next: NotificationPreferences,
+): NotificationPreferences {
+ const patch: NotificationPreferences = {};
+
+ for (const key of NOTIFICATION_GROUP_KEYS) {
+ const previousValue = preferenceValue(previous, key);
+ const nextValue = preferenceValue(next, key);
+ if (previousValue !== nextValue) {
+ patch[key] = nextValue;
+ }
+ }
+
+ return patch;
+}
+
+/** Apply a preference patch while keeping default "all" values sparse. */
+export function applyNotificationPreferencePatch(
+ current: NotificationPreferences,
+ patch: NotificationPreferences,
+): NotificationPreferences {
+ const next = { ...current };
+
+ for (const key of NOTIFICATION_GROUP_KEYS) {
+ const value = patch[key];
+ if (value === "muted") {
+ next[key] = value;
+ } else if (value === "all") {
+ delete next[key];
+ }
+ }
+
+ return next;
+}
+
+/**
+ * Roll back only values that still match this mutation's optimistic patch.
+ * A later toggle that touched the same key wins.
+ */
+export function rollbackNotificationPreferencePatch(
+ current: NotificationPreferences,
+ patch: NotificationPreferences,
+ previous: NotificationPreferences,
+): NotificationPreferences {
+ const next = { ...current };
+
+ for (const key of NOTIFICATION_GROUP_KEYS) {
+ const patchedValue = patch[key];
+ if (
+ patchedValue === undefined ||
+ preferenceValue(current, key) !== patchedValue
+ ) {
+ continue;
+ }
+
+ const previousValue = preferenceValue(previous, key);
+ if (previousValue === "all") {
+ delete next[key];
+ } else {
+ next[key] = previousValue;
+ }
+ }
+
+ return next;
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index a8ada0bf17..4d28e47227 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -48,6 +48,7 @@
"./notification-preferences": "./notification-preferences/index.ts",
"./notification-preferences/queries": "./notification-preferences/queries.ts",
"./notification-preferences/mutations": "./notification-preferences/mutations.ts",
+ "./notification-preferences/patch": "./notification-preferences/patch.ts",
"./chat": "./chat/index.ts",
"./chat/queries": "./chat/queries.ts",
"./chat/mutations": "./chat/mutations.ts",
diff --git a/server/cmd/server/notification_listeners_test.go b/server/cmd/server/notification_listeners_test.go
index f292bbae27..7267bbddc6 100644
--- a/server/cmd/server/notification_listeners_test.go
+++ b/server/cmd/server/notification_listeners_test.go
@@ -316,6 +316,65 @@ func TestNotification_StatusChanged(t *testing.T) {
}
}
+// TestNotification_StatusChanged_Muted verifies that status_changes="muted"
+// prevents a new Inbox row without affecting other subscribers.
+func TestNotification_StatusChanged_Muted(t *testing.T) {
+ queries := db.New(testPool)
+ bus := newNotificationBus(t, queries)
+
+ mutedEmail := "[email protected]"
+ mutedID := createTestUser(t, mutedEmail)
+ t.Cleanup(func() { cleanupTestUser(t, mutedEmail) })
+
+ normalEmail := "[email protected]"
+ normalID := createTestUser(t, normalEmail)
+ t.Cleanup(func() { cleanupTestUser(t, normalEmail) })
+
+ issueID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() {
+ cleanupInboxForIssue(t, issueID)
+ cleanupTestIssue(t, issueID)
+ })
+
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO notification_preference (workspace_id, user_id, preferences)
+ VALUES ($1, $2, '{"status_changes":"muted"}'::jsonb)
+ `, testWorkspaceID, mutedID); err != nil {
+ t.Fatalf("seed muted notification preference: %v", err)
+ }
+
+ addTestSubscriber(t, issueID, "member", mutedID, "commenter")
+ addTestSubscriber(t, issueID, "member", normalID, "commenter")
+
+ bus.Publish(events.Event{
+ Type: protocol.EventIssueUpdated,
+ WorkspaceID: testWorkspaceID,
+ ActorType: "member",
+ ActorID: testUserID,
+ Payload: map[string]any{
+ "issue": handler.IssueResponse{
+ ID: issueID,
+ WorkspaceID: testWorkspaceID,
+ Title: "muted status test issue",
+ Status: "in_progress",
+ Priority: "medium",
+ CreatorType: "member",
+ CreatorID: testUserID,
+ },
+ "assignee_changed": false,
+ "status_changed": true,
+ "prev_status": "todo",
+ },
+ })
+
+ if items := inboxItemsForRecipient(t, queries, mutedID); len(items) != 0 {
+ t.Fatalf("expected muted subscriber to receive 0 items, got %d", len(items))
+ }
+ if items := inboxItemsForRecipient(t, queries, normalID); len(items) != 1 {
+ t.Fatalf("expected normal subscriber to receive 1 item, got %d", len(items))
+ }
+}
+
// TestNotification_CommentCreated verifies that all subscribers except the
// commenter receive a "new_comment" notification.
func TestNotification_CommentCreated(t *testing.T) {
@@ -538,8 +597,8 @@ func TestNotification_AssigneeChanged(t *testing.T) {
AssigneeType: &newAssigneeType,
AssigneeID: &newAssigneeID,
},
- "assignee_changed": true,
- "status_changed": false,
+ "assignee_changed": true,
+ "status_changed": false,
"prev_assignee_type": &oldAssigneeType,
"prev_assignee_id": &oldAssigneeID,
},
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 93f91f651a..eb2d70bb6c 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1371,6 +1371,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Notification preferences
r.Route("/api/notification-preferences", func(r chi.Router) {
r.Get("/", h.GetNotificationPreferences)
+ r.Patch("/", h.PatchNotificationPreferences)
r.Put("/", h.UpdateNotificationPreferences)
})
})
diff --git a/server/internal/handler/notification_preference.go b/server/internal/handler/notification_preference.go
index 3cc5669402..91fc043d1b 100644
--- a/server/internal/handler/notification_preference.go
+++ b/server/internal/handler/notification_preference.go
@@ -71,38 +71,63 @@ type updateNotifPrefRequest struct {
Preferences map[string]string `json:"preferences"`
}
-func (h *Handler) UpdateNotificationPreferences(w http.ResponseWriter, r *http.Request) {
- userID, ok := requireUserID(w, r)
- if !ok {
- return
- }
- workspaceID := ctxWorkspaceID(r.Context())
-
+func decodeNotificationPreferenceRequest(w http.ResponseWriter, r *http.Request) ([]byte, bool) {
var req updateNotifPrefRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
- return
+ return nil, false
}
if req.Preferences == nil {
writeError(w, http.StatusBadRequest, "preferences field is required")
- return
+ return nil, false
}
for k, v := range req.Preferences {
if !validNotifGroups[k] {
writeError(w, http.StatusBadRequest, "invalid preference group: "+k)
- return
+ return nil, false
}
if !validNotifValues[v] {
writeError(w, http.StatusBadRequest, "invalid preference value: "+v)
- return
+ return nil, false
}
}
prefsJSON, err := json.Marshal(req.Preferences)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to marshal preferences")
+ return nil, false
+ }
+ return prefsJSON, true
+}
+
+func writeNotificationPreferenceResponse(
+ w http.ResponseWriter,
+ workspaceID string,
+ pref db.NotificationPreference,
+) {
+ var prefs map[string]string
+ if err := json.Unmarshal(pref.Preferences, &prefs); err != nil {
+ prefs = map[string]string{}
+ }
+
+ writeJSON(w, http.StatusOK, map[string]any{
+ "workspace_id": workspaceID,
+ "preferences": prefs,
+ })
+}
+
+// UpdateNotificationPreferences preserves the original replace-all PUT
+// contract for compatibility with installed clients.
+func (h *Handler) UpdateNotificationPreferences(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+ prefsJSON, ok := decodeNotificationPreferenceRequest(w, r)
+ if !ok {
return
}
@@ -116,14 +141,31 @@ func (h *Handler) UpdateNotificationPreferences(w http.ResponseWriter, r *http.R
writeError(w, http.StatusInternalServerError, "failed to update notification preferences")
return
}
+ writeNotificationPreferenceResponse(w, workspaceID, pref)
+}
- var prefs map[string]string
- if err := json.Unmarshal(pref.Preferences, &prefs); err != nil {
- prefs = map[string]string{}
+// PatchNotificationPreferences atomically merges only the supplied keys. This
+// prevents stale tabs or devices from replacing unrelated mute settings.
+func (h *Handler) PatchNotificationPreferences(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ workspaceID := ctxWorkspaceID(r.Context())
+ prefsJSON, ok := decodeNotificationPreferenceRequest(w, r)
+ if !ok {
+ return
}
- writeJSON(w, http.StatusOK, map[string]any{
- "workspace_id": workspaceID,
- "preferences": prefs,
+ pref, err := h.Queries.PatchNotificationPreference(r.Context(), db.PatchNotificationPreferenceParams{
+ WorkspaceID: parseUUID(workspaceID),
+ UserID: parseUUID(userID),
+ Preferences: prefsJSON,
})
+ if err != nil {
+ slog.Warn("PatchNotificationPreference failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to update notification preferences")
+ return
+ }
+ writeNotificationPreferenceResponse(w, workspaceID, pref)
}
diff --git a/server/internal/handler/notification_preference_test.go b/server/internal/handler/notification_preference_test.go
new file mode 100644
index 0000000000..33bc13e195
--- /dev/null
+++ b/server/internal/handler/notification_preference_test.go
@@ -0,0 +1,141 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/middleware"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func notificationPreferenceRequest(
+ t *testing.T,
+ method string,
+ preferences map[string]string,
+) *http.Request {
+ t.Helper()
+
+ member, err := testHandler.Queries.GetMemberByUserAndWorkspace(
+ context.Background(),
+ db.GetMemberByUserAndWorkspaceParams{
+ UserID: parseUUID(testUserID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ },
+ )
+ if err != nil {
+ t.Fatalf("load test member: %v", err)
+ }
+
+ req := newRequest(method, "/api/notification-preferences", map[string]any{
+ "preferences": preferences,
+ })
+ return req.WithContext(
+ middleware.SetMemberContext(req.Context(), testWorkspaceID, member),
+ )
+}
+
+func TestPatchNotificationPreferencesMergesWithoutReplacing(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ if _, err := testPool.Exec(ctx, `
+ DELETE FROM notification_preference
+ WHERE workspace_id = $1 AND user_id = $2
+ `, testWorkspaceID, testUserID); err != nil {
+ t.Fatalf("reset notification preference: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `
+ DELETE FROM notification_preference
+ WHERE workspace_id = $1 AND user_id = $2
+ `, testWorkspaceID, testUserID)
+ })
+
+ putRecorder := httptest.NewRecorder()
+ testHandler.UpdateNotificationPreferences(
+ putRecorder,
+ notificationPreferenceRequest(t, http.MethodPut, map[string]string{
+ "status_changes": "muted",
+ }),
+ )
+ if putRecorder.Code != http.StatusOK {
+ t.Fatalf("seed preference: status=%d body=%s", putRecorder.Code, putRecorder.Body.String())
+ }
+
+ patchRecorder := httptest.NewRecorder()
+ testHandler.PatchNotificationPreferences(
+ patchRecorder,
+ notificationPreferenceRequest(t, http.MethodPatch, map[string]string{
+ "comments": "muted",
+ }),
+ )
+ if patchRecorder.Code != http.StatusOK {
+ t.Fatalf("patch preference: status=%d body=%s", patchRecorder.Code, patchRecorder.Body.String())
+ }
+
+ var response struct {
+ WorkspaceID string `json:"workspace_id"`
+ Preferences map[string]string `json:"preferences"`
+ }
+ if err := json.NewDecoder(patchRecorder.Body).Decode(&response); err != nil {
+ t.Fatalf("decode patch response: %v", err)
+ }
+ if response.WorkspaceID != testWorkspaceID {
+ t.Fatalf("workspace_id = %q, want %q", response.WorkspaceID, testWorkspaceID)
+ }
+ if response.Preferences["status_changes"] != "muted" {
+ t.Fatalf("status_changes was replaced: %#v", response.Preferences)
+ }
+ if response.Preferences["comments"] != "muted" {
+ t.Fatalf("comments patch missing: %#v", response.Preferences)
+ }
+
+ enableRecorder := httptest.NewRecorder()
+ testHandler.PatchNotificationPreferences(
+ enableRecorder,
+ notificationPreferenceRequest(t, http.MethodPatch, map[string]string{
+ "status_changes": "all",
+ }),
+ )
+ if enableRecorder.Code != http.StatusOK {
+ t.Fatalf("enable preference: status=%d body=%s", enableRecorder.Code, enableRecorder.Body.String())
+ }
+
+ var persisted []byte
+ if err := testPool.QueryRow(ctx, `
+ SELECT preferences
+ FROM notification_preference
+ WHERE workspace_id = $1 AND user_id = $2
+ `, testWorkspaceID, testUserID).Scan(&persisted); err != nil {
+ t.Fatalf("load persisted preference: %v", err)
+ }
+ var preferences map[string]string
+ if err := json.Unmarshal(persisted, &preferences); err != nil {
+ t.Fatalf("decode persisted preference: %v", err)
+ }
+ if preferences["status_changes"] != "all" || preferences["comments"] != "muted" {
+ t.Fatalf("unexpected persisted preferences: %#v", preferences)
+ }
+}
+
+func TestPatchNotificationPreferencesRejectsUnknownGroups(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ recorder := httptest.NewRecorder()
+ testHandler.PatchNotificationPreferences(
+ recorder,
+ notificationPreferenceRequest(t, http.MethodPatch, map[string]string{
+ "unknown_group": "muted",
+ }),
+ )
+ if recorder.Code != http.StatusBadRequest {
+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+}
diff --git a/server/pkg/db/generated/notification_preference.sql.go b/server/pkg/db/generated/notification_preference.sql.go
index 1209e1455d..e2714faf7e 100644
--- a/server/pkg/db/generated/notification_preference.sql.go
+++ b/server/pkg/db/generated/notification_preference.sql.go
@@ -70,6 +70,35 @@ func (q *Queries) ListNotificationPreferencesByUsers(ctx context.Context, arg Li
return items, nil
}
+const patchNotificationPreference = `-- name: PatchNotificationPreference :one
+INSERT INTO notification_preference (workspace_id, user_id, preferences)
+VALUES ($1, $2, $3)
+ON CONFLICT (workspace_id, user_id)
+DO UPDATE SET
+ preferences = notification_preference.preferences || EXCLUDED.preferences,
+ updated_at = now()
+RETURNING id, workspace_id, user_id, preferences, updated_at
+`
+
+type PatchNotificationPreferenceParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ UserID pgtype.UUID `json:"user_id"`
+ Preferences []byte `json:"preferences"`
+}
+
+func (q *Queries) PatchNotificationPreference(ctx context.Context, arg PatchNotificationPreferenceParams) (NotificationPreference, error) {
+ row := q.db.QueryRow(ctx, patchNotificationPreference, arg.WorkspaceID, arg.UserID, arg.Preferences)
+ var i NotificationPreference
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.UserID,
+ &i.Preferences,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
const upsertNotificationPreference = `-- name: UpsertNotificationPreference :one
INSERT INTO notification_preference (workspace_id, user_id, preferences)
VALUES ($1, $2, $3)
diff --git a/server/pkg/db/queries/notification_preference.sql b/server/pkg/db/queries/notification_preference.sql
index a3fc538dce..92b0091433 100644
--- a/server/pkg/db/queries/notification_preference.sql
+++ b/server/pkg/db/queries/notification_preference.sql
@@ -9,6 +9,15 @@ ON CONFLICT (workspace_id, user_id)
DO UPDATE SET preferences = $3, updated_at = now()
RETURNING *;
+-- name: PatchNotificationPreference :one
+INSERT INTO notification_preference (workspace_id, user_id, preferences)
+VALUES ($1, $2, $3)
+ON CONFLICT (workspace_id, user_id)
+DO UPDATE SET
+ preferences = notification_preference.preferences || EXCLUDED.preferences,
+ updated_at = now()
+RETURNING *;
+
-- name: ListNotificationPreferencesByUsers :many
SELECT * FROM notification_preference
WHERE workspace_id = $1 AND user_id = ANY(sqlc.arg('user_ids')::uuid[]);