Skip to content

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

Go

feat(inbox): archive issues you handle, asking existing users once (MUL-9788) (#11138)

Jiayuan Zhangccf12376b95d
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 0899c2be31..dfcac50a8f 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -3727,6 +3727,25 @@ export class ApiClient {
);
}
+ /**
+ * Answer the one-time auto-archive question for every workspace where it is
+ * pending. Answers with the active workspace's preferences.
+ */
+ async resolveAutoArchivePrompt(
+ preferences: NotificationPreferences,
+ ): Promise<NotificationPreferenceResponse> {
+ const raw = await this.fetch<unknown>("/api/notification-preferences/auto-archive-prompt", {
+ method: "POST",
+ body: JSON.stringify({ preferences }),
+ });
+ return parseWithFallback(
+ raw,
+ NotificationPreferenceResponseSchema,
+ EMPTY_NOTIFICATION_PREFERENCE_RESPONSE,
+ { endpoint: "POST /api/notification-preferences/auto-archive-prompt" },
+ );
+ }
+
// App Config
async getConfig(): Promise<AppConfigResponse> {
const raw = await this.fetch<unknown>("/api/config");
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 1592f6c580..3457ce3ef7 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -1476,6 +1476,7 @@ export const EMPTY_STORE_THEME_LIST: { themes: StoreTheme[] } = { themes: [] };
export const NotificationPreferenceResponseSchema = z.object({
workspace_id: z.string(),
preferences: z.record(z.string(), z.string()).default({}),
+ auto_archive_prompt: z.boolean().optional(),
}).loose();
export const EMPTY_NOTIFICATION_PREFERENCE_RESPONSE: NotificationPreferenceResponse = {
diff --git a/packages/core/inbox/auto-archive.test.ts b/packages/core/inbox/auto-archive.test.ts
new file mode 100644
index 0000000000..dd471c462c
--- /dev/null
+++ b/packages/core/inbox/auto-archive.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+import { noteInboxAutoArchive, takeInboxAutoArchive } from "./auto-archive";
+
+describe("inbox auto-archive records", () => {
+ it.each(["issue_status_terminal", "actor_acted"])("records an archive the user caused: %s", (reason) => {
+ noteInboxAutoArchive({ issue_id: `issue-${reason}`, reason }, 1_000);
+ expect(takeInboxAutoArchive(`issue-${reason}`, 2_000)).toBe(true);
+ expect(takeInboxAutoArchive(`issue-${reason}`, 2_000)).toBe(false);
+ });
+
+ it("ignores batches without a reason the user caused", () => {
+ noteInboxAutoArchive({ issue_id: "issue-a" }, 1_000);
+ noteInboxAutoArchive({ issue_id: "issue-b", reason: "retention" }, 1_000);
+ noteInboxAutoArchive({ reason: "actor_acted" }, 1_000);
+ expect(takeInboxAutoArchive("issue-a", 1_000)).toBe(false);
+ expect(takeInboxAutoArchive("issue-b", 1_000)).toBe(false);
+ });
+
+ it("forgets a record once it is stale", () => {
+ noteInboxAutoArchive({ issue_id: "issue-c", reason: "actor_acted" }, 1_000);
+ expect(takeInboxAutoArchive("issue-c", 1_000 + 30_001)).toBe(false);
+ });
+});
diff --git a/packages/core/inbox/auto-archive.ts b/packages/core/inbox/auto-archive.ts
new file mode 100644
index 0000000000..4d4c66344b
--- /dev/null
+++ b/packages/core/inbox/auto-archive.ts
@@ -0,0 +1,32 @@
+/**
+ * Issues whose notifications the server just archived because the user
+ * handled them: completed the issue, commented on it, changed its status or reassigned it
+ * (`inbox:batch-archived` with one of these reasons). The Inbox reads this to
+ * tell such an archive apart from any other way the open notification left,
+ * such as another window archiving it.
+ */
+const AUTO_ARCHIVE_REASONS = new Set(["issue_status_terminal", "actor_acted"]);
+
+/** The archive lands within moments of the action; anything older is stale. */
+const AUTO_ARCHIVE_TTL_MS = 30_000;
+
+const archivedAt = new Map<string, number>();
+
+/** Record an `inbox:batch-archived` payload, if it is an archive the user caused. */
+export function noteInboxAutoArchive(
+ payload: { issue_id?: string; reason?: string },
+ now = Date.now(),
+): void {
+ if (!payload.issue_id || !payload.reason || !AUTO_ARCHIVE_REASONS.has(payload.reason)) return;
+ for (const [issueId, at] of archivedAt) {
+ if (now - at > AUTO_ARCHIVE_TTL_MS) archivedAt.delete(issueId);
+ }
+ archivedAt.set(payload.issue_id, now);
+}
+
+/** Whether the user's own action just archived `issueId`'s notifications. Consumes the record. */
+export function takeInboxAutoArchive(issueId: string, now = Date.now()): boolean {
+ const at = archivedAt.get(issueId);
+ archivedAt.delete(issueId);
+ return at !== undefined && now - at <= AUTO_ARCHIVE_TTL_MS;
+}
diff --git a/packages/core/notification-preferences/auto-archive-presets.test.ts b/packages/core/notification-preferences/auto-archive-presets.test.ts
new file mode 100644
index 0000000000..cc2279049d
--- /dev/null
+++ b/packages/core/notification-preferences/auto-archive-presets.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from "vitest";
+import { autoArchivePreferences, autoArchivePreset } from "./auto-archive-presets";
+
+describe("autoArchivePreset", () => {
+ it.each([
+ [{}, "handled"],
+ [{ auto_archive_on_comment: "muted", auto_archive_on_status: "muted", auto_archive_on_assignee: "muted" }, "completed"],
+ [autoArchivePreferences([]), "never"],
+ [{ auto_archive_on_labels: "all" }, "custom"],
+ [{ auto_archive_completed: "muted" }, "custom"],
+ ] as const)("%j is %s", (preferences, preset) => {
+ expect(autoArchivePreset(preferences)).toBe(preset);
+ });
+});
+
+describe("autoArchivePreferences", () => {
+ it("sets every action, on or off", () => {
+ expect(autoArchivePreferences(["auto_archive_completed", "auto_archive_on_labels"])).toEqual({
+ auto_archive_completed: "all",
+ auto_archive_on_comment: "muted",
+ auto_archive_on_status: "muted",
+ auto_archive_on_assignee: "muted",
+ auto_archive_on_priority: "muted",
+ auto_archive_on_project: "muted",
+ auto_archive_on_dates: "muted",
+ auto_archive_on_labels: "all",
+ });
+ });
+});
diff --git a/packages/core/notification-preferences/auto-archive-presets.ts b/packages/core/notification-preferences/auto-archive-presets.ts
new file mode 100644
index 0000000000..6c1c42a240
--- /dev/null
+++ b/packages/core/notification-preferences/auto-archive-presets.ts
@@ -0,0 +1,52 @@
+import type { AutoArchiveKey, NotificationPreferences } from "../types";
+import { notificationPreferenceValue } from "./patch";
+
+export const AUTO_ARCHIVE_KEYS = [
+ "auto_archive_completed",
+ "auto_archive_on_comment",
+ "auto_archive_on_status",
+ "auto_archive_on_assignee",
+ "auto_archive_on_priority",
+ "auto_archive_on_project",
+ "auto_archive_on_dates",
+ "auto_archive_on_labels",
+] as const satisfies readonly AutoArchiveKey[];
+
+export type AutoArchivePreset = "never" | "completed" | "handled";
+
+/**
+ * The actions each preset archives on. `handled`, the default for members who
+ * never chose, is what the server does with no stored keys.
+ */
+export const AUTO_ARCHIVE_PRESETS: Record<AutoArchivePreset, readonly AutoArchiveKey[]> = {
+ never: [],
+ completed: ["auto_archive_completed"],
+ handled: [
+ "auto_archive_completed",
+ "auto_archive_on_comment",
+ "auto_archive_on_status",
+ "auto_archive_on_assignee",
+ ],
+};
+
+/** The auto-archive actions turned on in preferences. */
+export function autoArchiveActionsOn(preferences: NotificationPreferences): AutoArchiveKey[] {
+ return AUTO_ARCHIVE_KEYS.filter((key) => notificationPreferenceValue(preferences, key) === "all");
+}
+
+/** The preset preferences match, or "custom" when they match none. */
+export function autoArchivePreset(preferences: NotificationPreferences): AutoArchivePreset | "custom" {
+ const on = autoArchiveActionsOn(preferences);
+ const match = (Object.keys(AUTO_ARCHIVE_PRESETS) as AutoArchivePreset[]).find((preset) => {
+ const actions = AUTO_ARCHIVE_PRESETS[preset];
+ return actions.length === on.length && actions.every((key) => on.includes(key));
+ });
+ return match ?? "custom";
+}
+
+/** Every auto-archive key set on or off so exactly `on` archive. */
+export function autoArchivePreferences(on: readonly AutoArchiveKey[]): NotificationPreferences {
+ return Object.fromEntries(
+ AUTO_ARCHIVE_KEYS.map((key) => [key, on.includes(key) ? "all" : "muted"]),
+ ) as NotificationPreferences;
+}
diff --git a/packages/core/notification-preferences/index.ts b/packages/core/notification-preferences/index.ts
index 4b3efba544..4a6b841dad 100644
--- a/packages/core/notification-preferences/index.ts
+++ b/packages/core/notification-preferences/index.ts
@@ -1,3 +1,4 @@
export * from "./queries";
export * from "./mutations";
export * from "./patch";
+export * from "./auto-archive-presets";
diff --git a/packages/core/notification-preferences/mutations.ts b/packages/core/notification-preferences/mutations.ts
index f86bdd51cc..175ba3eec0 100644
--- a/packages/core/notification-preferences/mutations.ts
+++ b/packages/core/notification-preferences/mutations.ts
@@ -67,6 +67,27 @@ function mapMutationOptions(
};
}
+/**
+ * Answer the one-time auto-archive question. The server applies the answer to
+ * every workspace where it is still pending, so every workspace's cached
+ * preferences are refetched.
+ */
+export function useResolveAutoArchivePrompt() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+
+ return useMutation<NotificationPreferenceResponse, Error, NotificationPreferences>({
+ mutationFn: (preferences) => api.resolveAutoArchivePrompt(preferences),
+ onSuccess: (data) => {
+ qc.setQueryData(notificationPreferenceKeys.all(wsId), data);
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: notificationPreferenceKeys.root() });
+ qc.invalidateQueries({ queryKey: issueKeys.subscribersAll() });
+ },
+ });
+}
+
export function useUpdateNotificationPreferences() {
const qc = useQueryClient();
const wsId = useWorkspaceId();
diff --git a/packages/core/notification-preferences/patch.ts b/packages/core/notification-preferences/patch.ts
index 77f4fe0182..14205539a8 100644
--- a/packages/core/notification-preferences/patch.ts
+++ b/packages/core/notification-preferences/patch.ts
@@ -6,7 +6,8 @@ type PreferenceValues = Record<PreferenceKey, string | undefined>;
/**
* The value each key means when it is missing. Every key the settings UI can
* write must be listed, or its change is silently never sent. Must match the
- * server's defaults (`mutedByDefault` in server/internal/inbox/registry.go).
+ * server's defaults (`mutedByDefault` in server/internal/inbox/registry.go,
+ * `autoArchiveOnByDefault` in server/cmd/server/notification_listeners.go).
*/
const PREFERENCE_DEFAULTS: { [K in PreferenceKey]-?: NonNullable<NotificationPreferences[K]> } = {
assignments: "all",
@@ -20,7 +21,15 @@ const PREFERENCE_DEFAULTS: { [K in PreferenceKey]-?: NonNullable<NotificationPre
agent_activity: "all",
system_notifications: "all",
auto_archive_completed: "all",
+ auto_archive_on_comment: "all",
+ auto_archive_on_status: "all",
+ auto_archive_on_assignee: "all",
+ auto_archive_on_priority: "muted",
+ auto_archive_on_project: "muted",
+ auto_archive_on_dates: "muted",
+ auto_archive_on_labels: "muted",
others_issues: "key_updates",
+ after_auto_archive: "stay",
};
const PREFERENCE_KEYS = Object.keys(PREFERENCE_DEFAULTS) as PreferenceKey[];
diff --git a/packages/core/notification-preferences/queries.ts b/packages/core/notification-preferences/queries.ts
index 5700a36439..d38e1b3436 100644
--- a/packages/core/notification-preferences/queries.ts
+++ b/packages/core/notification-preferences/queries.ts
@@ -2,6 +2,7 @@ import { queryOptions } from "@tanstack/react-query";
import { api } from "../api";
export const notificationPreferenceKeys = {
+ root: () => ["notification-preferences"] as const,
all: (wsId: string) => ["notification-preferences", wsId] as const,
};
diff --git a/packages/core/package.json b/packages/core/package.json
index 5162cde9a6..b54081a7d0 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -76,6 +76,7 @@
"./inbox/filter-store": "./inbox/filter-store.ts",
"./inbox/selection-store": "./inbox/selection-store.ts",
"./inbox/open-row": "./inbox/open-row.ts",
+ "./inbox/auto-archive": "./inbox/auto-archive.ts",
"./inbox/ws-updaters": "./inbox/ws-updaters.ts",
"./inbox/snooze": "./inbox/snooze.ts",
"./inbox/use-snooze-wake": "./inbox/use-snooze-wake.ts",
@@ -83,6 +84,7 @@
"./notification-preferences/queries": "./notification-preferences/queries.ts",
"./notification-preferences/mutations": "./notification-preferences/mutations.ts",
"./notification-preferences/patch": "./notification-preferences/patch.ts",
+ "./notification-preferences/auto-archive-presets": "./notification-preferences/auto-archive-presets.ts",
"./chat": "./chat/index.ts",
"./chat/queries": "./chat/queries.ts",
"./chat/mutations": "./chat/mutations.ts",
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index fa14483d39..d458b0e2f5 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -66,6 +66,7 @@ import {
invalidateUpdatedAtSortedIssueLists,
} from "../issues/cache-coordinator";
import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged, onInboxIssueDeleted, onInboxSummaryInvalidate } from "../inbox/ws-updaters";
+import { noteInboxAutoArchive } from "../inbox/auto-archive";
import {
notificationPreferenceOptions,
notificationPreferenceKeys,
@@ -111,6 +112,7 @@ import type {
IssueMetadataChangedPayload,
IssuePropertiesChangedPayload,
InboxNewPayload,
+ InboxBatchArchivedPayload,
InboxItem,
NotificationPreferenceResponse,
CommentCreatedPayload,
@@ -1395,6 +1397,12 @@ export function useRealtimeSync(
await handleInboxNew(qc, item);
});
+ // Recorded before the refresh the generic inbox handler schedules, so the
+ // Inbox knows why the open notification left once the list drops it.
+ const unsubInboxBatchArchived = ws.on("inbox:batch-archived", (p) => {
+ noteInboxAutoArchive(p as InboxBatchArchivedPayload);
+ });
+
// --- Timeline event handlers (global fallback) ---
// These events are also handled granularly by useIssueTimeline when
// IssueDetail is mounted. This global handler exists to mark the
@@ -2145,6 +2153,7 @@ export function useRealtimeSync(
unsubIssuePropertiesChanged();
unsubPropertyChanged.forEach((unsub) => unsub());
unsubInboxNew();
+ unsubInboxBatchArchived();
docUnsubs.forEach(unsub => unsub());
unsubCommentCreated();
unsubCommentUpdated();
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index 9bf818ebf2..361afe1b44 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -273,6 +273,14 @@ export interface InboxBatchReadPayload {
export interface InboxBatchArchivedPayload {
recipient_id: string;
count: number;
+ /** Set when the batch is one issue's notifications. */
+ issue_id?: string;
+ /**
+ * Why the server archived them on its own: "issue_status_terminal" when the
+ * recipient completed the issue, "actor_acted" when they commented on it,
+ * changed its status or reassigned it. Other values may appear; absent for user-requested batches.
+ */
+ reason?: string;
}
export interface CommentCreatedPayload {
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index a21bc46fd1..bb3b3e0df1 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -148,7 +148,7 @@ export type {
PluginTokenIssue,
} from "./plugin";
export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread, ArchivedInboxPage, ArchivedInboxFacets, SnoozedInboxIssue } from "./inbox";
-export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse, OthersIssuesValue } from "./notification-preference";
+export type { AfterAutoArchiveValue, AutoArchiveKey, NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse, OthersIssuesValue } from "./notification-preference";
export type { Comment, CommentType, CommentAuthorType, CommentSupplementReceipt, CommentSupplementStatus, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, CommentTriggerOutcome, CommentTriggerStatus, Reaction } from "./comment";
export type { Label, LabelResourceType, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse, ResourceLabelsResponse } from "./label";
export type { IssueProperty, IssuePropertyType, ScalarIssuePropertyType, ListIssuePropertyType, IssuePropertyOption, IssuePropertyConfig, IssuePropertyValue, IssuePropertyValues, CreatePropertyRequest, UpdatePropertyRequest, ListPropertiesResponse, IssuePropertiesResponse, IssuePropertyActorKind, IssuePropertyActorRef, PropertyFilterOp, PropertyOperatorFilter, PropertyFilterValue } from "./property";
diff --git a/packages/core/types/notification-preference.ts b/packages/core/types/notification-preference.ts
index c5a5a79ed6..509c867410 100644
--- a/packages/core/types/notification-preference.ts
+++ b/packages/core/types/notification-preference.ts
@@ -9,7 +9,22 @@ export type NotificationGroupKey =
| "new_issues"
| "agent_activity"
| "system_notifications"
- | "auto_archive_completed";
+ | AutoArchiveKey;
+
+/**
+ * Each action you take on an issue that can archive your own notifications on
+ * it. `auto_archive_completed` is moving it to a done or closed status;
+ * `auto_archive_on_status` is any other status change.
+ */
+export type AutoArchiveKey =
+ | "auto_archive_completed"
+ | "auto_archive_on_comment"
+ | "auto_archive_on_status"
+ | "auto_archive_on_assignee"
+ | "auto_archive_on_priority"
+ | "auto_archive_on_project"
+ | "auto_archive_on_dates"
+ | "auto_archive_on_labels";
export type NotificationGroupValue = "all" | "muted";
@@ -20,11 +35,24 @@ export type NotificationGroupValue = "all" | "muted";
*/
export type OthersIssuesValue = "all" | "key_updates";
+/**
+ * Where the Inbox goes when the notification you are reading is archived
+ * because you handled its issue. Missing means "stay".
+ */
+export type AfterAutoArchiveValue = "stay" | "next";
+
export type NotificationPreferences = Partial<Record<NotificationGroupKey, NotificationGroupValue>> & {
others_issues?: OthersIssuesValue;
+ after_auto_archive?: AfterAutoArchiveValue;
};
export interface NotificationPreferenceResponse {
workspace_id: string;
preferences: NotificationPreferences;
+ /**
+ * The member has not yet chosen which of their actions archive notifications
+ * since replying, changing status and reassigning started doing so by
+ * default. Their auto-archive keys keep the old behavior until they answer.
+ */
+ auto_archive_prompt?: boolean;
}
diff --git a/packages/views/inbox/components/auto-archive-prompt-dialog.test.tsx b/packages/views/inbox/components/auto-archive-prompt-dialog.test.tsx
new file mode 100644
index 0000000000..0ee7dc434b
--- /dev/null
+++ b/packages/views/inbox/components/auto-archive-prompt-dialog.test.tsx
@@ -0,0 +1,83 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { I18nProvider } from "@multica/core/i18n/react";
+import { notificationPreferenceKeys } from "@multica/core/notification-preferences/queries";
+import enInbox from "../../locales/en/inbox.json";
+import enSettings from "../../locales/en/settings.json";
+import { AutoArchivePromptDialog } from "./auto-archive-prompt-dialog";
+
+const { resolve } = vi.hoisted(() => ({ resolve: vi.fn() }));
+vi.mock("@multica/core/notification-preferences/mutations", () => ({
+ useResolveAutoArchivePrompt: () => ({ mutate: resolve }),
+}));
+
+afterEach(() => {
+ cleanup();
+ resolve.mockReset();
+});
+
+function renderDialog({ prompt, active = true }: { prompt: boolean; active?: boolean }) {
+ const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } });
+ qc.setQueryData(notificationPreferenceKeys.all("ws-a"), {
+ workspace_id: "ws-a",
+ preferences: {},
+ auto_archive_prompt: prompt,
+ });
+ render(
+ <QueryClientProvider client={qc}>
+ <I18nProvider locale="en" resources={{ en: { inbox: enInbox, settings: enSettings } }}>
+ <AutoArchivePromptDialog wsId="ws-a" active={active} />
+ </I18nProvider>
+ </QueryClientProvider>,
+ );
+}
+
+const off = {
+ auto_archive_completed: "muted",
+ auto_archive_on_comment: "muted",
+ auto_archive_on_status: "muted",
+ auto_archive_on_assignee: "muted",
+ auto_archive_on_priority: "muted",
+ auto_archive_on_project: "muted",
+ auto_archive_on_dates: "muted",
+ auto_archive_on_labels: "muted",
+};
+
+describe("AutoArchivePromptDialog", () => {
+ it.each([
+ { prompt: false, active: true },
+ { prompt: true, active: false },
+ ])("stays closed unless the question is pending and a notification is open: %j", (props) => {
+ renderDialog(props);
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+
+ it("asks once a notification is open, with the recommended choice picked", () => {
+ renderDialog({ prompt: true });
+ expect(screen.getByRole("dialog", { name: "Archive notifications once you've handled them" })).toBeInTheDocument();
+ const choices = screen.getAllByRole("radio").map((radio) => [radio.textContent, radio.getAttribute("aria-checked")]);
+ expect(choices).toEqual([
+ ["After you reply, change status or reassignRecommendedIssues you've dealt with leave your Inbox", "true"],
+ ["When you complete itOnly completing or cancelling an issue archives it", "false"],
+ ["NeverYou archive notifications yourself", "false"],
+ ]);
+ });
+
+ it("saves the choice for every pending workspace and closes", async () => {
+ const user = userEvent.setup();
+ renderDialog({ prompt: true });
+ await user.click(screen.getByRole("radio", { name: /When you complete it/ }));
+ await user.click(screen.getByRole("button", { name: "Done" }));
+ expect(resolve).toHaveBeenCalledWith({ ...off, auto_archive_completed: "all" }, expect.anything());
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+
+ it("keeps what you have when you close it", async () => {
+ const user = userEvent.setup();
+ renderDialog({ prompt: true });
+ await user.keyboard("{Escape}");
+ expect(resolve).toHaveBeenCalledWith({}, expect.anything());
+ });
+});
diff --git a/packages/views/inbox/components/auto-archive-prompt-dialog.tsx b/packages/views/inbox/components/auto-archive-prompt-dialog.tsx
new file mode 100644
index 0000000000..6d8dcd5363
--- /dev/null
+++ b/packages/views/inbox/components/auto-archive-prompt-dialog.tsx
@@ -0,0 +1,121 @@
+"use client";
+
+import { useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { notificationPreferenceOptions } from "@multica/core/notification-preferences/queries";
+import { useResolveAutoArchivePrompt } from "@multica/core/notification-preferences/mutations";
+import {
+ AUTO_ARCHIVE_PRESETS,
+ autoArchivePreferences,
+ type AutoArchivePreset,
+} from "@multica/core/notification-preferences/auto-archive-presets";
+import type { NotificationPreferences } from "@multica/core/types";
+import { Badge } from "@multica/ui/components/ui/badge";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { cn } from "@multica/ui/lib/utils";
+import { toast } from "sonner";
+import { useT } from "../../i18n";
+
+const PROMPT_ORDER: readonly AutoArchivePreset[] = ["handled", "completed", "never"];
+
+/**
+ * Asks a member who archived notifications before auto-archive changed which
+ * of their actions should archive them now. Shown once, the first time they
+ * open a notification from the Inbox; the answer covers every workspace where
+ * it is pending. Closing it keeps what they have.
+ */
+export function AutoArchivePromptDialog({ wsId, active }: { wsId: string; active: boolean }) {
+ const { t } = useT("inbox");
+ const { t: tSettings } = useT("settings");
+ const { data } = useQuery(notificationPreferenceOptions(wsId));
+ const resolve = useResolveAutoArchivePrompt();
+ const [choice, setChoice] = useState<AutoArchivePreset>("handled");
+ const [answered, setAnswered] = useState(false);
+
+ const answer = (preferences: NotificationPreferences) => {
+ setAnswered(true);
+ resolve.mutate(preferences, {
+ onError: (err) =>
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : tSettings(($) => $.notifications.toast_failed),
+ ),
+ });
+ };
+
+ return (
+ <Dialog
+ open={active && !answered && data?.auto_archive_prompt === true}
+ onOpenChange={(open) => {
+ if (!open) answer({});
+ }}
+ >
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.auto_archive_prompt.title)}</DialogTitle>
+ <DialogDescription>{t(($) => $.auto_archive_prompt.description)}</DialogDescription>
+ </DialogHeader>
+ <div
+ role="radiogroup"
+ aria-label={t(($) => $.auto_archive_prompt.title)}
+ className="flex flex-col gap-2"
+ >
+ {PROMPT_ORDER.map((preset) => {
+ const selected = choice === preset;
+ return (
+ <button
+ key={preset}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ onClick={() => setChoice(preset)}
+ className={cn(
+ "flex flex-col gap-1 rounded-lg border border-border px-3 py-2.5 text-left transition-colors outline-none hover:bg-surface-hover focus-visible:ring-3 focus-visible:ring-ring/50",
+ selected && "border-primary ring-1 ring-primary hover:bg-transparent",
+ )}
+ >
+ <span className="flex items-center gap-2 text-body font-medium">
+ <span
+ aria-hidden
+ className={cn(
+ "grid size-4 shrink-0 place-content-center rounded-full border border-input",
+ selected && "border-primary",
+ )}
+ >
+ {selected && <span className="size-2 rounded-full bg-primary" />}
+ </span>
+ {tSettings(($) => $.notifications.leaving.auto_presets[preset])}
+ {preset === "handled" && (
+ <Badge variant="secondary">
+ {tSettings(($) => $.notifications.leaving.auto_recommended)}
+ </Badge>
+ )}
+ </span>
+ <span className="pl-6 text-caption text-muted-foreground">
+ {t(($) => $.auto_archive_prompt.options[preset])}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ <DialogFooter className="items-center sm:justify-between">
+ <span className="text-caption text-muted-foreground">
+ {t(($) => $.auto_archive_prompt.hint)}
+ </span>
+ <Button onClick={() => answer(autoArchivePreferences(AUTO_ARCHIVE_PRESETS[choice]))}>
+ {t(($) => $.auto_archive_prompt.confirm)}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsx
index 1e684da8dc..c9ef466c84 100644
--- a/packages/views/inbox/components/inbox-page.tsx
+++ b/packages/views/inbox/components/inbox-page.tsx
@@ -122,6 +122,7 @@ import { AutopilotQuotaNotice } from "./autopilot-quota-notice";
import { InboxKeptActions, useKeptInboxRowText } from "./inbox-kept-actions";
import { inboxListLoad, useFilteredInboxRows } from "./use-filtered-inbox-rows";
import { useKeptOpenInboxRow } from "./use-kept-open-inbox-row";
+import { useMoveOnAfterAutoArchive } from "./use-move-on-after-auto-archive";
import { useArchiveInboxBatchWithUndo, useArchiveInboxWithUndo, useRestoreInbox } from "./use-leave-inbox-row";
import { useInboxSnooze } from "./use-inbox-snooze";
import { InboxAppRequest } from "../../common/app-requests";
@@ -640,6 +641,14 @@ export function InboxPage() {
});
};
+ useMoveOnAfterAutoArchive({
+ settled: settledRow,
+ next: settledRow ? nextInboxRow(listedItems, settledRow.key) : null,
+ onNext: () => {
+ if (settledRow) advanceSelectionPast(settledRow.item.id, listedItems);
+ },
+ });
+
const unsubscribable = useInboxUnsubscribable(wsId);
const unsubscribeArchive = useUnsubscribeArchive();
const handleUnsubscribeArchive = (id: string, scope: InboxUnsubscribeScope = "issue") => {
diff --git a/packages/views/inbox/components/use-move-on-after-auto-archive.test.tsx b/packages/views/inbox/components/use-move-on-after-auto-archive.test.tsx
new file mode 100644
index 0000000000..afe0015c75
--- /dev/null
+++ b/packages/views/inbox/components/use-move-on-after-auto-archive.test.tsx
@@ -0,0 +1,114 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { ReactNode } from "react";
+import { toast } from "sonner";
+import { setApiInstance } from "@multica/core/api";
+import type { ApiClient } from "@multica/core/api/client";
+import { I18nProvider } from "@multica/core/i18n/react";
+import { noteInboxAutoArchive } from "@multica/core/inbox/auto-archive";
+import type { KeptInboxRow } from "@multica/core/inbox/open-row";
+import { useInboxSelectionStore } from "@multica/core/inbox/selection-store";
+import { notificationPreferenceKeys } from "@multica/core/notification-preferences/queries";
+import type { InboxItem } from "@multica/core/types";
+import { getTestResources } from "../../test/i18n";
+import { useMoveOnAfterAutoArchive } from "./use-move-on-after-auto-archive";
+
+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws" }));
+
+const api = { unarchiveInbox: vi.fn(async (id: string) => ({ id })) };
+
+function item(id: string, issueId: string): InboxItem {
+ return {
+ id,
+ workspace_id: "ws",
+ recipient_type: "member",
+ recipient_id: "member-1",
+ actor_type: "agent",
+ actor_id: "agent-1",
+ type: "new_comment",
+ severity: "info",
+ issue_id: issueId,
+ title: id,
+ body: null,
+ issue_status: "in_review",
+ issue_priority: "none",
+ read: true,
+ archived: false,
+ created_at: "2026-11-21T08:00:00Z",
+ details: null,
+ };
+}
+
+const archived = (issueId: string): KeptInboxRow => ({ key: issueId, item: item(`n-${issueId}`, issueId), reason: "archived" });
+const nextRow = item("n-next", "issue-next");
+
+function setup(preferences: Record<string, string>, initial: KeptInboxRow | null = null) {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
+ qc.setQueryData(notificationPreferenceKeys.all("ws"), { workspace_id: "ws", preferences });
+ const resources = getTestResources();
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <I18nProvider locale="en" resources={resources}>
+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>
+ </I18nProvider>
+ );
+ const onNext = vi.fn();
+ const view = renderHook(
+ ({ settled }: { settled: KeptInboxRow | null }) => useMoveOnAfterAutoArchive({ settled, next: nextRow, onNext }),
+ { wrapper, initialProps: { settled: initial } },
+ );
+ return { onNext, settle: (row: KeptInboxRow | null) => view.rerender({ settled: row }) };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ setApiInstance(api as unknown as ApiClient);
+ vi.spyOn(document, "hasFocus").mockReturnValue(true);
+});
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe("useMoveOnAfterAutoArchive", () => {
+ it("opens the next notification when your action archived the open one", () => {
+ const { onNext, settle } = setup({ after_auto_archive: "next" });
+ noteInboxAutoArchive({ issue_id: "issue-a", reason: "actor_acted" });
+ settle(archived("issue-a"));
+ expect(onNext).toHaveBeenCalledTimes(1);
+ expect(toast.success).toHaveBeenCalledWith("Notification archived", expect.anything());
+ });
+
+ it("undoes by restoring the notification and returning its row", async () => {
+ const returnRow = vi.spyOn(useInboxSelectionStore.getState(), "returnRow");
+ const { settle } = setup({ after_auto_archive: "next" });
+ noteInboxAutoArchive({ issue_id: "issue-b", reason: "issue_status_terminal" });
+ settle(archived("issue-b"));
+ const action = (vi.mocked(toast.success).mock.calls.at(-1)?.[1] as unknown as { action: { onClick: () => void } }).action;
+ await act(async () => action.onClick());
+ expect(returnRow).toHaveBeenCalledWith("ws", "issue-b");
+ expect(api.unarchiveInbox).toHaveBeenCalledWith("n-issue-b");
+ });
+
+ it("stays by default", () => {
+ const { onNext, settle } = setup({});
+ noteInboxAutoArchive({ issue_id: "issue-c", reason: "actor_acted" });
+ settle(archived("issue-c"));
+ expect(onNext).not.toHaveBeenCalled();
+ });
+
+ it("stays when something other than your action archived it", () => {
+ const { onNext, settle } = setup({ after_auto_archive: "next" });
+ settle(archived("issue-d"));
+ expect(onNext).not.toHaveBeenCalled();
+ });
+
+ it("stays when the action happened in another window", () => {
+ vi.mocked(document.hasFocus).mockReturnValue(false);
+ const { onNext, settle } = setup({ after_auto_archive: "next" });
+ noteInboxAutoArchive({ issue_id: "issue-e", reason: "actor_acted" });
+ settle(archived("issue-e"));
+ expect(onNext).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/inbox/components/use-move-on-after-auto-archive.ts b/packages/views/inbox/components/use-move-on-after-auto-archive.ts
new file mode 100644
index 0000000000..8598ee74c5
--- /dev/null
+++ b/packages/views/inbox/components/use-move-on-after-auto-archive.ts
@@ -0,0 +1,62 @@
+"use client";
+
+import { useEffect, useRef } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { takeInboxAutoArchive } from "@multica/core/inbox/auto-archive";
+import type { KeptInboxRow } from "@multica/core/inbox/open-row";
+import { useInboxSelectionStore } from "@multica/core/inbox/selection-store";
+import { notificationPreferenceOptions } from "@multica/core/notification-preferences/queries";
+import { notificationPreferenceValue } from "@multica/core/notification-preferences/patch";
+import type { InboxItem } from "@multica/core/types";
+import { useT } from "../../i18n";
+import { useRestoreInbox } from "./use-leave-inbox-row";
+
+/**
+ * Opens the next notification once the open one is archived because the user
+ * handled its issue (`takeInboxAutoArchive`), when their `after_auto_archive`
+ * preference says "next", and confirms it with a toast that can undo it.
+ * Otherwise the row stays in place, settled, as `keepOpenInboxRow` keeps it.
+ *
+ * Only the focused window moves on: acting in another window or tab must not
+ * pull this one away from what it shows.
+ */
+export function useMoveOnAfterAutoArchive({
+ settled,
+ next,
+ onNext,
+}: {
+ settled: KeptInboxRow | null;
+ next: InboxItem | null;
+ onNext: () => void;
+}) {
+ const { t } = useT("inbox");
+ const wsId = useWorkspaceId();
+ const { data } = useQuery(notificationPreferenceOptions(wsId));
+ const movesOn = notificationPreferenceValue(data?.preferences ?? {}, "after_auto_archive") === "next";
+ const restore = useRestoreInbox();
+ const archivedKey = settled?.reason === "archived" ? settled.key : null;
+
+ const latest = useRef({ settled, next, onNext, movesOn });
+ useEffect(() => {
+ latest.current = { settled, next, onNext, movesOn };
+ });
+
+ useEffect(() => {
+ if (!archivedKey) return;
+ const { settled: row, next: nextRow, onNext: moveOn, movesOn: moves } = latest.current;
+ if (!takeInboxAutoArchive(archivedKey)) return;
+ if (!moves || !row || !nextRow || !document.hasFocus()) return;
+ moveOn();
+ toast.success(t(($) => $.toasts.archived), {
+ action: {
+ label: t(($) => $.toasts.undo),
+ onClick: () => {
+ useInboxSelectionStore.getState().returnRow(wsId, archivedKey);
+ void restore(row.item.id, { quiet: true });
+ },
+ },
+ });
+ }, [archivedKey, wsId, restore, t]);
+}
diff --git a/packages/views/issues/actions/issue-inbox-actions.tsx b/packages/views/issues/actions/issue-inbox-actions.tsx
index d1792a450d..ef1a646566 100644
--- a/packages/views/issues/actions/issue-inbox-actions.tsx
+++ b/packages/views/issues/actions/issue-inbox-actions.tsx
@@ -26,6 +26,7 @@ import { useFilteredInboxRows } from "../../inbox/components/use-filtered-inbox-
import { useSidebarInboxIssue } from "../../inbox/components/use-sidebar-inbox-issue";
import { UnsubscribeArchiveButton } from "../../inbox/components/unsubscribe-archive-button";
import { useUnsubscribeArchive } from "../../inbox/components/use-unsubscribe-archive";
+import { useMoveOnAfterAutoArchive } from "../../inbox/components/use-move-on-after-auto-archive";
import {
useArchiveInboxWithUndo,
useLeaveInboxRow,
@@ -108,6 +109,7 @@ export function IssueInboxActions({
};
const moveOn = () => leave(issueId, next);
+ useMoveOnAfterAutoArchive({ settled, next, onNext: moveOn });
const archiveRef = useRef<(() => void) | null>(null);
const snoozeRef = useRef<(() => void) | null>(null);
diff --git a/packages/views/layout/panels/work-panel.tsx b/packages/views/layout/panels/work-panel.tsx
index 664f9bff33..490e8ff8ed 100644
--- a/packages/views/layout/panels/work-panel.tsx
+++ b/packages/views/layout/panels/work-panel.tsx
@@ -14,6 +14,7 @@ import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-st
import { projectListOptions } from "@multica/core/projects/queries";
import type { Project } from "@multica/core/types";
import { resolveClickIntent, useHeldUntilArrival, useNavigation } from "../../navigation";
+import { AutoArchivePromptDialog } from "../../inbox/components/auto-archive-prompt-dialog";
import { useSidebarInboxIssue } from "../../inbox/components/use-sidebar-inbox-issue";
import { IssueContextMenuProvider } from "../../issues/actions";
import { useIssueViewActions } from "../../issue-views/use-view-actions";
@@ -246,6 +247,7 @@ export function WorkPanel() {
activeIssueId={inboxClaimsIssue ? currentIssueId : null}
/>
)}
+ {wsId && <AutoArchivePromptDialog wsId={wsId} active={!!inboxOpenKey} />}
{wsId && (
<ViewsSection
diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.json
index 433bb14dc2..f334177a87 100644
--- a/packages/views/locales/en/inbox.json
+++ b/packages/views/locales/en/inbox.json
@@ -217,5 +217,16 @@
"view_empty_description": "Snooze an issue from your inbox and it waits here until it's time to come back.",
"col_updates": "While snoozed",
"col_back": "Back"
+ },
+ "auto_archive_prompt": {
+ "title": "Archive notifications once you've handled them",
+ "description": "The Inbox can now archive an issue's notifications when you act on it. Only your own actions count, and a later notification brings the issue back.",
+ "options": {
+ "handled": "Issues you've dealt with leave your Inbox",
+ "completed": "Only completing or cancelling an issue archives it",
+ "never": "You archive notifications yourself"
+ },
+ "hint": "You can change this in Settings › Notifications",
+ "confirm": "Done"
}
}
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 41d7132bda..df80f24581 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -860,8 +860,34 @@
"manual_label": "Archive by hand",
"manual_description": "From its row in the sidebar, or the top of the notification",
"manual_value": "Anytime",
- "done_label": "Archive issues you complete",
- "done_description": "When you move an issue to Done or Cancelled, its notifications are archived. Issues others complete stay in your Inbox.",
+ "auto_label": "Archive issues you handle",
+ "auto_description": "Only your own actions count. A later notification brings an issue back.",
+ "auto_presets": {
+ "never": "Never",
+ "completed": "When you complete it",
+ "handled": "After you reply, change status or reassign",
+ "custom": "Custom",
+ "custom_item": "Custom..."
+ },
+ "auto_recommended": "Recommended",
+ "auto_groups": {
+ "settle": "Handling it",
+ "tidy": "Tidying it"
+ },
+ "auto_actions": {
+ "completed": "Complete",
+ "comment": "Reply",
+ "status": "Change status",
+ "assignee": "Reassign",
+ "priority": "Change priority",
+ "project": "Change project",
+ "dates": "Change dates",
+ "labels": "Change labels"
+ },
+ "after_label": "After archiving",
+ "after_description": "When the notification you're reading is archived this way. Archiving by hand (E) still opens the next one.",
+ "after_stay": "Stay on the issue",
+ "after_next": "Open the next one",
"archived_label": "Archived notifications",
"archived_description": "Find them again and unarchive them",
"archived_action": "View archived"
diff --git a/packages/views/locales/es/inbox.json b/packages/views/locales/es/inbox.json
index ad55dce0f3..40f66788ff 100644
--- a/packages/views/locales/es/inbox.json
+++ b/packages/views/locales/es/inbox.json
@@ -217,5 +217,16 @@
"view_empty_description": "Pospón un issue desde tu bandeja de entrada y esperará aquí hasta que sea hora de volver.",
"col_updates": "Mientras estaba pospuesto",
"col_back": "Vuelve"
+ },
+ "auto_archive_prompt": {
+ "title": "Archiva las notificaciones cuando ya las has gestionado",
+ "description": "La bandeja de entrada ya puede archivar las notificaciones de una tarea cuando actúas sobre ella. Solo cuentan tus propias acciones, y una notificación posterior devuelve la tarea.",
+ "options": {
+ "handled": "Las tareas que ya gestionaste salen de tu bandeja",
+ "completed": "Solo completar o cancelar una tarea la archiva",
+ "never": "Archivas las notificaciones tú mismo"
+ },
+ "hint": "Puedes cambiarlo en Ajustes › Notificaciones",
+ "confirm": "Listo"
}
}
diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.json
index 807e020ffa..e27f10ba82 100644
--- a/packages/views/locales/es/settings.json
+++ b/packages/views/locales/es/settings.json
@@ -860,8 +860,34 @@
"manual_label": "Archivar a mano",
"manual_description": "Desde su fila en la barra lateral o desde la parte superior de la notificación",
"manual_value": "En cualquier momento",
- "done_label": "Archivar las tareas que completas",
- "done_description": "Cuando pasas una tarea a un estado Completado o Cancelado, sus notificaciones se archivan. Las que completan otros se quedan en la bandeja de entrada.",
+ "auto_label": "Archivar las tareas que gestionas",
+ "auto_description": "Solo cuentan tus propias acciones. Una notificación posterior devuelve la tarea.",
+ "auto_presets": {
+ "never": "Nunca",
+ "completed": "Cuando la completas",
+ "handled": "Al responder, cambiar el estado o reasignar",
+ "custom": "Personalizado",
+ "custom_item": "Personalizado..."
+ },
+ "auto_recommended": "Recomendado",
+ "auto_groups": {
+ "settle": "Resolverla",
+ "tidy": "Organizarla"
+ },
+ "auto_actions": {
+ "completed": "Completar",
+ "comment": "Responder",
+ "status": "Cambiar estado",
+ "assignee": "Reasignar",
+ "priority": "Cambiar prioridad",
+ "project": "Cambiar proyecto",
+ "dates": "Cambiar fechas",
+ "labels": "Cambiar etiquetas"
+ },
+ "after_label": "Después de archivar",
+ "after_description": "Cuando la notificación que estás leyendo se archiva así. Archivar a mano (E) sigue abriendo la siguiente.",
+ "after_stay": "Quedarse en la tarea",
+ "after_next": "Abrir la siguiente",
"archived_label": "Notificaciones archivadas",
"archived_description": "Encuéntralas de nuevo y desarchívalas",
"archived_action": "Ver archivadas"
diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.json
index 2422a1defe..984bf3cf46 100644
--- a/packages/views/locales/fr/inbox.json
+++ b/packages/views/locales/fr/inbox.json
@@ -217,5 +217,16 @@
"view_empty_description": "Reportez une tâche depuis votre boîte de réception : elle attend ici jusqu'à son retour.",
"col_updates": "Pendant le report",
"col_back": "Retour"
+ },
+ "auto_archive_prompt": {
+ "title": "Archiver les notifications une fois traitées",
+ "description": "La boîte de réception peut désormais archiver les notifications d'une tâche quand vous agissez dessus. Seules vos propres actions comptent, et une nouvelle notification fait revenir la tâche.",
+ "options": {
+ "handled": "Les tâches traitées quittent votre boîte de réception",
+ "completed": "Seul le fait de terminer ou d'annuler une tâche l'archive",
+ "never": "Vous archivez vous-même les notifications"
+ },
+ "hint": "Modifiable dans Paramètres › Notifications",
+ "confirm": "Terminé"
}
}
diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.json
index 0f4c50e9ac..86efd42399 100644
--- a/packages/views/locales/fr/settings.json
+++ b/packages/views/locales/fr/settings.json
@@ -860,8 +860,34 @@
"manual_label": "Archiver à la main",
"manual_description": "Depuis sa ligne dans la barre latérale ou le haut de la notification",
"manual_value": "À tout moment",
- "done_label": "Archiver les tâches que vous terminez",
- "done_description": "Quand vous passez une tâche à un statut Terminé ou Annulé, ses notifications sont archivées. Celles terminées par d'autres restent dans la boîte de réception.",
+ "auto_label": "Archiver les tâches que vous traitez",
+ "auto_description": "Seules vos propres actions comptent. Une nouvelle notification fait revenir la tâche.",
+ "auto_presets": {
+ "never": "Jamais",
+ "completed": "Quand vous la terminez",
+ "handled": "Après une réponse, un changement de statut ou une réattribution",
+ "custom": "Personnalisé",
+ "custom_item": "Personnalisé..."
+ },
+ "auto_recommended": "Recommandé",
+ "auto_groups": {
+ "settle": "La traiter",
+ "tidy": "La ranger"
+ },
+ "auto_actions": {
+ "completed": "Terminer",
+ "comment": "Répondre",
+ "status": "Changer le statut",
+ "assignee": "Réassigner",
+ "priority": "Changer la priorité",
+ "project": "Changer le projet",
+ "dates": "Changer les dates",
+ "labels": "Changer les libellés"
+ },
+ "after_label": "Après l'archivage",
+ "after_description": "Quand la notification que vous lisez est archivée ainsi. Archiver à la main (E) ouvre toujours la suivante.",
+ "after_stay": "Rester sur la tâche",
+ "after_next": "Ouvrir la suivante",
"archived_label": "Notifications archivées",
"archived_description": "Retrouvez-les et désarchivez-les",
"archived_action": "Voir les archivées"
diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.json
index 0d381d011f..2f3852a2db 100644
--- a/packages/views/locales/ja/inbox.json
+++ b/packages/views/locales/ja/inbox.json
@@ -212,5 +212,16 @@
"view_empty_description": "インボックスでタスクをスヌーズすると、戻る時間までここで待機します。",
"col_updates": "スヌーズ中",
"col_back": "戻る時間"
+ },
+ "auto_archive_prompt": {
+ "title": "対応済みの通知を自動でアーカイブ",
+ "description": "タスクに対応すると、その通知をインボックスから自動でアーカイブできるようになりました。自分の操作だけが対象で、新しい通知が届くとタスクは戻ってきます。",
+ "options": {
+ "handled": "対応したタスクはインボックスに残りません",
+ "completed": "タスクを完了またはキャンセルしたときだけアーカイブします",
+ "never": "通知は自分でアーカイブします"
+ },
+ "hint": "あとから 設定 › 通知 で変更できます",
+ "confirm": "完了"
}
}
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index d32b3f5850..9673607010 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -850,8 +850,34 @@
"manual_label": "手動でアーカイブ",
"manual_description": "サイドバーの行、または通知の上部から",
"manual_value": "いつでも",
- "done_label": "自分が完了したタスクをアーカイブ",
- "done_description": "タスクを完了系またはキャンセル系のステータスにすると、その通知はアーカイブされます。他の人が完了したタスクはインボックスに残ります。",
+ "auto_label": "自分が対応したタスクをアーカイブ",
+ "auto_description": "自分の操作だけが対象です。新しい通知が届くとタスクは戻ってきます。",
+ "auto_presets": {
+ "never": "しない",
+ "completed": "完了したとき",
+ "handled": "返信・ステータス変更・担当変更の後",
+ "custom": "カスタム",
+ "custom_item": "カスタム..."
+ },
+ "auto_recommended": "おすすめ",
+ "auto_groups": {
+ "settle": "対応",
+ "tidy": "整理"
+ },
+ "auto_actions": {
+ "completed": "完了",
+ "comment": "返信",
+ "status": "ステータス変更",
+ "assignee": "担当者変更",
+ "priority": "優先度変更",
+ "project": "プロジェクト変更",
+ "dates": "日付変更",
+ "labels": "ラベル変更"
+ },
+ "after_label": "アーカイブ後",
+ "after_description": "表示中の通知がこの方法でアーカイブされたとき。手動のアーカイブ(E)は従来どおり次を開きます。",
+ "after_stay": "このタスクに留まる",
+ "after_next": "次の通知を開く",
"archived_label": "アーカイブ済みの通知",
"archived_description": "ここから見つけてアーカイブを解除できます",
"archived_action": "アーカイブ済みを表示"
diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.json
index 9160f29f50..33575ad5bf 100644
--- a/packages/views/locales/ko/inbox.json
+++ b/packages/views/locales/ko/inbox.json
@@ -212,5 +212,16 @@
"view_empty_description": "인박스에서 태스크를 미루면 돌아올 시간까지 여기에서 기다립니다.",
"col_updates": "미뤄둔 동안",
"col_back": "돌아오는 시간"
+ },
+ "auto_archive_prompt": {
+ "title": "처리한 알림을 자동으로 보관하세요",
+ "description": "이제 태스크를 처리하면 그 알림을 인박스에서 자동으로 보관할 수 있습니다. 내 동작만 해당되며, 새 알림이 오면 태스크가 다시 돌아옵니다.",
+ "options": {
+ "handled": "처리한 태스크는 인박스에 남지 않습니다",
+ "completed": "태스크를 완료하거나 취소할 때만 보관합니다",
+ "never": "알림은 직접 보관합니다"
+ },
+ "hint": "나중에 설정 › 알림에서 바꿀 수 있습니다",
+ "confirm": "완료"
}
}
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index d36b4ed0fe..085c670b5a 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -850,8 +850,34 @@
"manual_label": "직접 보관",
"manual_description": "사이드바의 행이나 알림 상단에서",
"manual_value": "언제든지",
- "done_label": "내가 완료한 태스크 보관",
- "done_description": "태스크를 완료 또는 취소 계열 상태로 바꾸면 그 알림은 보관됩니다. 다른 사람이 완료한 태스크는 인박스에 남습니다.",
+ "auto_label": "내가 처리한 태스크 보관",
+ "auto_description": "내 동작만 해당됩니다. 새 알림이 오면 태스크가 다시 돌아옵니다.",
+ "auto_presets": {
+ "never": "안 함",
+ "completed": "완료했을 때",
+ "handled": "답글, 상태 변경, 담당자 변경 후",
+ "custom": "사용자 지정",
+ "custom_item": "사용자 지정..."
+ },
+ "auto_recommended": "추천",
+ "auto_groups": {
+ "settle": "처리",
+ "tidy": "정리"
+ },
+ "auto_actions": {
+ "completed": "완료",
+ "comment": "답글",
+ "status": "상태 변경",
+ "assignee": "담당자 변경",
+ "priority": "우선순위 변경",
+ "project": "프로젝트 변경",
+ "dates": "날짜 변경",
+ "labels": "라벨 변경"
+ },
+ "after_label": "보관한 뒤",
+ "after_description": "보고 있는 알림이 이렇게 보관될 때. 직접 보관(E)하면 지금처럼 다음 알림을 엽니다.",
+ "after_stay": "이 태스크에 머무르기",
+ "after_next": "다음 알림 열기",
"archived_label": "보관된 알림",
"archived_description": "여기서 다시 찾고 보관을 해제할 수 있습니다",
"archived_action": "보관된 알림 보기"
diff --git a/packages/views/locales/ru/inbox.json b/packages/views/locales/ru/inbox.json
index a2da1ce6b7..ad20cb44d8 100644
--- a/packages/views/locales/ru/inbox.json
+++ b/packages/views/locales/ru/inbox.json
@@ -227,5 +227,16 @@
"view_empty_description": "Отложите issue во входящих — оно подождёт здесь, пока не придёт время вернуться.",
"col_updates": "За время отсрочки",
"col_back": "Вернётся"
+ },
+ "auto_archive_prompt": {
+ "title": "Архивируйте уведомления, когда задача обработана",
+ "description": "Теперь «Входящие» могут архивировать уведомления задачи, когда вы с ней работаете. Учитываются только ваши действия, а новое уведомление вернёт задачу.",
+ "options": {
+ "handled": "Обработанные задачи уходят из «Входящих»",
+ "completed": "Архивируется только при завершении или отмене задачи",
+ "never": "Вы архивируете уведомления сами"
+ },
+ "hint": "Это можно изменить в Настройки › Уведомления",
+ "confirm": "Готово"
}
}
diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.json
index 4d2f6a51cd..c6eab6779d 100644
--- a/packages/views/locales/ru/settings.json
+++ b/packages/views/locales/ru/settings.json
@@ -880,8 +880,34 @@
"manual_label": "Архивировать вручную",
"manual_description": "Из строки на боковой панели или в верхней части уведомления",
"manual_value": "В любой момент",
- "done_label": "Архивировать задачи, которые вы завершили",
- "done_description": "Когда вы переводите задачу в статус «Выполнено» или «Отменено», её уведомления архивируются. Задачи, завершённые другими, остаются во «Входящих».",
+ "auto_label": "Архивировать задачи, с которыми вы работали",
+ "auto_description": "Учитываются только ваши действия. Новое уведомление вернёт задачу.",
+ "auto_presets": {
+ "never": "Никогда",
+ "completed": "Когда вы её завершаете",
+ "handled": "После ответа, смены статуса или переназначения",
+ "custom": "Свои настройки",
+ "custom_item": "Свои настройки..."
+ },
+ "auto_recommended": "Рекомендуется",
+ "auto_groups": {
+ "settle": "Решение",
+ "tidy": "Упорядочивание"
+ },
+ "auto_actions": {
+ "completed": "Завершить",
+ "comment": "Ответить",
+ "status": "Сменить статус",
+ "assignee": "Переназначить",
+ "priority": "Сменить приоритет",
+ "project": "Сменить проект",
+ "dates": "Сменить даты",
+ "labels": "Сменить метки"
+ },
+ "after_label": "После архивации",
+ "after_description": "Когда уведомление, которое вы читаете, архивируется таким образом. Ручная архивация (E) по-прежнему открывает следующее.",
+ "after_stay": "Остаться на задаче",
+ "after_next": "Открыть следующее",
"archived_label": "Архивные уведомления",
"archived_description": "Здесь их можно найти и вернуть из архива",
"archived_action": "Открыть архив"
diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.json
index d7d8eb8a0f..5a7fed85c5 100644
--- a/packages/views/locales/zh-Hans/inbox.json
+++ b/packages/views/locales/zh-Hans/inbox.json
@@ -212,5 +212,16 @@
"view_empty_description": "在收件箱里延后一个任务,它会在这里等到时间再回来。",
"col_updates": "延后期间",
"col_back": "恢复时间"
+ },
+ "auto_archive_prompt": {
+ "title": "处理完的通知,可以自动归档",
+ "description": "收件箱新增了自动归档:你处理完一个任务,它的通知就会移出收件箱。只算你自己的操作,有新动态会重新进收件箱。",
+ "options": {
+ "handled": "处理过的任务不再留在收件箱",
+ "completed": "只有完成或取消任务才归档",
+ "never": "自己手动归档"
+ },
+ "hint": "之后可以在 设置 › 通知 里修改",
+ "confirm": "确定"
}
}
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 85a74a19c7..c07463f3fa 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -850,8 +850,34 @@
"manual_label": "手动归档",
"manual_description": "在侧边栏行上或通知详情顶部点归档",
"manual_value": "随时",
- "done_label": "自动归档我完成的任务",
- "done_description": "你把任务改为\"已完成\"或\"已取消\"类状态时,它的通知自动归档。别人完成的任务会留在收件箱。",
+ "auto_label": "自动归档我处理过的任务",
+ "auto_description": "只算你自己的操作。归档后有新动态,会重新进收件箱。",
+ "auto_presets": {
+ "never": "从不",
+ "completed": "完成任务时",
+ "handled": "回复、改状态或转交后",
+ "custom": "自定义",
+ "custom_item": "自定义..."
+ },
+ "auto_recommended": "推荐",
+ "auto_groups": {
+ "settle": "处理",
+ "tidy": "整理"
+ },
+ "auto_actions": {
+ "completed": "完成",
+ "comment": "回复",
+ "status": "改状态",
+ "assignee": "转交",
+ "priority": "改优先级",
+ "project": "改项目",
+ "dates": "改日期",
+ "labels": "改标签"
+ },
+ "after_label": "归档后",
+ "after_description": "正在看的通知被自动归档时。手动归档(E)照旧打开下一条。",
+ "after_stay": "停在当前任务",
+ "after_next": "打开下一条",
"archived_label": "已归档的通知",
"archived_description": "可以在这里找回并取消归档",
"archived_action": "查看已归档"
diff --git a/packages/views/locales/zh-Hant/inbox.json b/packages/views/locales/zh-Hant/inbox.json
index 7ea00a93af..4b2e6a43a4 100644
--- a/packages/views/locales/zh-Hant/inbox.json
+++ b/packages/views/locales/zh-Hant/inbox.json
@@ -212,5 +212,16 @@
"view_empty_description": "在收件箱裡延後一個任務,它會在這裡等到時間再回來。",
"col_updates": "延後期間",
"col_back": "回來時間"
+ },
+ "auto_archive_prompt": {
+ "title": "處理完的通知,可以自動歸檔",
+ "description": "收件箱新增了自動歸檔:你處理完一個任務,它的通知就會移出收件箱。只算你自己的操作,有新動態會重新進收件箱。",
+ "options": {
+ "handled": "處理過的任務不再留在收件箱",
+ "completed": "只有完成或取消任務才歸檔",
+ "never": "自己手動歸檔"
+ },
+ "hint": "之後可以在 設定 › 通知 裡修改",
+ "confirm": "確定"
}
}
diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.json
index f25b6f959c..b1a670cd15 100644
--- a/packages/views/locales/zh-Hant/settings.json
+++ b/packages/views/locales/zh-Hant/settings.json
@@ -850,8 +850,34 @@
"manual_label": "手動歸檔",
"manual_description": "在側欄列上或通知詳情頂部點歸檔",
"manual_value": "隨時",
- "done_label": "自動歸檔我完成的任務",
- "done_description": "你把任務改為「已完成」或「已取消」類狀態時,它的通知自動歸檔。別人完成的任務會留在收件箱。",
+ "auto_label": "自動歸檔我處理過的任務",
+ "auto_description": "只算你自己的操作。歸檔後有新動態,會重新進收件箱。",
+ "auto_presets": {
+ "never": "從不",
+ "completed": "完成任務時",
+ "handled": "回覆、改狀態或轉交後",
+ "custom": "自訂",
+ "custom_item": "自訂..."
+ },
+ "auto_recommended": "推薦",
+ "auto_groups": {
+ "settle": "處理",
+ "tidy": "整理"
+ },
+ "auto_actions": {
+ "completed": "完成",
+ "comment": "回覆",
+ "status": "改狀態",
+ "assignee": "轉交",
+ "priority": "改優先級",
+ "project": "改專案",
+ "dates": "改日期",
+ "labels": "改標籤"
+ },
+ "after_label": "歸檔後",
+ "after_description": "正在看的通知被自動歸檔時。手動歸檔(E)照舊打開下一條。",
+ "after_stay": "停在目前任務",
+ "after_next": "打開下一條",
"archived_label": "已歸檔的通知",
"archived_description": "可以在這裡找回並取消歸檔",
"archived_action": "查看已歸檔"
diff --git a/packages/views/settings/components/notifications-tab.test.tsx b/packages/views/settings/components/notifications-tab.test.tsx
index 3b626b1486..033c3a1f76 100644
--- a/packages/views/settings/components/notifications-tab.test.tsx
+++ b/packages/views/settings/components/notifications-tab.test.tsx
@@ -20,20 +20,26 @@ vi.mock("../../navigation", () => ({
</a>
),
}));
-const { mutate } = vi.hoisted(() => ({ mutate: vi.fn() }));
+const { mutate, resolve } = vi.hoisted(() => ({ mutate: vi.fn(), resolve: vi.fn() }));
vi.mock("@multica/core/notification-preferences/mutations", () => ({
useUpdateNotificationPreferences: () => ({ mutate }),
+ useResolveAutoArchivePrompt: () => ({ mutate: resolve }),
}));
vi.mock("./browser-notification-setting", () => ({ BrowserNotificationSetting: () => null }));
afterEach(() => {
cleanup();
mutate.mockReset();
+ resolve.mockReset();
});
-function renderTab(preferences: Record<string, string> = {}) {
+function renderTab(preferences: Record<string, string> = {}, { prompt = false } = {}) {
const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity } } });
- qc.setQueryData(notificationPreferenceKeys.all("ws-a"), { workspace_id: "ws-a", preferences });
+ qc.setQueryData(notificationPreferenceKeys.all("ws-a"), {
+ workspace_id: "ws-a",
+ preferences,
+ auto_archive_prompt: prompt,
+ });
render(
<QueryClientProvider client={qc}>
<I18nProvider locale="en" resources={{ en: { settings: enSettings } }}>
@@ -103,22 +109,140 @@ describe("Inbox notification settings", () => {
renderTab();
const leaving = screen.getByRole("region", { name: "Leaving the Inbox" });
expect(leaving).toHaveTextContent("Reading a notification doesn't take it out of the Inbox.");
- expect(leaving).toHaveTextContent("Issues others complete stay in your Inbox.");
+ expect(leaving).toHaveTextContent("Only your own actions count.");
expect(within(leaving).getByRole("link", { name: "View archived" })).toHaveAttribute(
"href",
"/acme/inbox?view=archived",
);
});
- it.each<{ preferences: Record<string, string>; checked: boolean }>([
- { preferences: {}, checked: true },
- { preferences: { auto_archive_completed: "muted" }, checked: false },
- ])("toggles archiving issues you complete: %j", ({ preferences, checked }) => {
+ const ALL_ACTIONS_OFF = {
+ auto_archive_completed: "muted",
+ auto_archive_on_comment: "muted",
+ auto_archive_on_status: "muted",
+ auto_archive_on_assignee: "muted",
+ };
+ const ACTIONS_OFF_BUT = (on: string[]) =>
+ Object.fromEntries(
+ [
+ "auto_archive_completed",
+ "auto_archive_on_comment",
+ "auto_archive_on_status",
+ "auto_archive_on_assignee",
+ "auto_archive_on_priority",
+ "auto_archive_on_project",
+ "auto_archive_on_dates",
+ "auto_archive_on_labels",
+ ].map((key) => [key, on.includes(key) ? "all" : "muted"]),
+ );
+ const archiveChoice = () =>
+ within(screen.getByRole("region", { name: "Leaving the Inbox" })).getByRole("combobox", {
+ name: "Archive issues you handle",
+ });
+
+ it.each<{ preferences: Record<string, string>; shown: string; custom: boolean }>([
+ { preferences: {}, shown: "After you reply, change status or reassign", custom: false },
+ { preferences: { ...ALL_ACTIONS_OFF, auto_archive_completed: "all" }, shown: "When you complete it", custom: false },
+ { preferences: ALL_ACTIONS_OFF, shown: "Never", custom: false },
+ { preferences: { auto_archive_on_labels: "all" }, shown: "Custom", custom: true },
+ ])("names the choice your actions match: %j", ({ preferences, shown, custom }) => {
renderTab(preferences);
+ expect(archiveChoice()).toHaveTextContent(shown);
+ expect(screen.queryByRole("checkbox", { name: "Change labels" }) !== null).toBe(custom);
+ });
+
+ it("offers the presets, the recommended one marked, then a custom choice", async () => {
+ const user = userEvent.setup();
+ renderTab();
+ await user.click(archiveChoice());
+ const options = await screen.findAllByRole("option");
+ expect(options.map((option) => [option.textContent, option.getAttribute("aria-selected")])).toEqual([
+ ["Never", "false"],
+ ["When you complete it", "false"],
+ ["After you reply, change status or reassignRecommended", "true"],
+ ["Custom...", "false"],
+ ]);
+ });
+
+ it("saves every action when you pick a preset", async () => {
+ const user = userEvent.setup();
+ renderTab();
+ await user.click(archiveChoice());
+ await user.click(await screen.findByRole("option", { name: "When you complete it" }));
+ expect(mutate).toHaveBeenCalledWith(ACTIONS_OFF_BUT(["auto_archive_completed"]), expect.anything());
+ });
+
+ it("lists every action under a custom choice, grouped, with yours checked", async () => {
+ const user = userEvent.setup();
+ renderTab();
+ await user.click(archiveChoice());
+ await user.click(await screen.findByRole("option", { name: "Custom..." }));
+ expect(mutate).not.toHaveBeenCalled();
+ expect(archiveChoice()).toHaveTextContent("Custom");
const leaving = screen.getByRole("region", { name: "Leaving the Inbox" });
- const toggle = within(leaving).getByRole("switch", { name: "Archive issues you complete" });
- if (checked) expect(toggle).toBeChecked();
- else expect(toggle).not.toBeChecked();
+ expect(leaving).toHaveTextContent("Handling it");
+ expect(leaving).toHaveTextContent("Tidying it");
+ const checked = within(leaving)
+ .getAllByRole("checkbox")
+ .map((box) => [box.closest("label")?.textContent, box.getAttribute("aria-checked")]);
+ expect(checked).toEqual([
+ ["Complete", "true"],
+ ["Reply", "true"],
+ ["Change status", "true"],
+ ["Reassign", "true"],
+ ["Change priority", "false"],
+ ["Change project", "false"],
+ ["Change dates", "false"],
+ ["Change labels", "false"],
+ ]);
+
+ await user.click(within(leaving).getByRole("checkbox", { name: "Change labels" }));
+ expect(mutate).toHaveBeenCalledWith(
+ ACTIONS_OFF_BUT([
+ "auto_archive_completed",
+ "auto_archive_on_comment",
+ "auto_archive_on_status",
+ "auto_archive_on_assignee",
+ "auto_archive_on_labels",
+ ]),
+ expect.anything(),
+ );
+ });
+
+ it("answers the pending one-time question when you choose here", async () => {
+ const user = userEvent.setup();
+ renderTab({ ...ALL_ACTIONS_OFF, auto_archive_completed: "all" }, { prompt: true });
+ await user.click(archiveChoice());
+ await user.click(await screen.findByRole("option", { name: "Never" }));
+ expect(resolve).toHaveBeenCalledWith(ACTIONS_OFF_BUT([]), expect.anything());
+ expect(mutate).not.toHaveBeenCalled();
+ });
+
+ it("nests where to go after archiving under the archive choice, hidden while it is off", () => {
+ renderTab(ALL_ACTIONS_OFF);
+ const leaving = screen.getByRole("region", { name: "Leaving the Inbox" });
+ expect(within(leaving).queryByRole("combobox", { name: "After archiving" })).toBeNull();
+ });
+
+ it.each<{ preferences: Record<string, string>; shown: string }>([
+ { preferences: {}, shown: "Stay on the issue" },
+ { preferences: { after_auto_archive: "next" }, shown: "Open the next one" },
+ ])("shows where to go after archiving: %j", ({ preferences, shown }) => {
+ renderTab(preferences);
+ const leaving = screen.getByRole("region", { name: "Leaving the Inbox" });
+ expect(within(leaving).getByRole("combobox", { name: "After archiving" })).toHaveTextContent(shown);
+ });
+
+ it("saves opening the next notification after archiving", async () => {
+ const user = userEvent.setup();
+ renderTab();
+ const leaving = screen.getByRole("region", { name: "Leaving the Inbox" });
+ await user.click(within(leaving).getByRole("combobox", { name: "After archiving" }));
+ await user.click(await screen.findByRole("option", { name: "Open the next one" }));
+ expect(mutate).toHaveBeenCalledWith(
+ { after_auto_archive: "next" },
+ expect.anything(),
+ );
});
});
diff --git a/packages/views/settings/components/notifications-tab.tsx b/packages/views/settings/components/notifications-tab.tsx
index 8784aaf985..7c508005f6 100644
--- a/packages/views/settings/components/notifications-tab.tsx
+++ b/packages/views/settings/components/notifications-tab.tsx
@@ -1,22 +1,37 @@
"use client";
-import { Fragment } from "react";
+import { Fragment, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { notificationPreferenceOptions } from "@multica/core/notification-preferences/queries";
-import { useUpdateNotificationPreferences } from "@multica/core/notification-preferences/mutations";
+import {
+ useResolveAutoArchivePrompt,
+ useUpdateNotificationPreferences,
+} from "@multica/core/notification-preferences/mutations";
import { notificationPreferenceValue } from "@multica/core/notification-preferences/patch";
+import {
+ AUTO_ARCHIVE_PRESETS,
+ autoArchiveActionsOn,
+ autoArchivePreferences,
+ autoArchivePreset,
+ type AutoArchivePreset,
+} from "@multica/core/notification-preferences/auto-archive-presets";
import type {
+ AfterAutoArchiveValue,
+ AutoArchiveKey,
NotificationGroupKey,
NotificationPreferences,
OthersIssuesValue,
} from "@multica/core/types";
+import { Badge } from "@multica/ui/components/ui/badge";
import { buttonVariants } from "@multica/ui/components/ui/button";
+import { Checkbox } from "@multica/ui/components/ui/checkbox";
import {
Select,
SelectContent,
SelectItem,
+ SelectSeparator,
SelectTrigger,
SelectValue,
} from "@multica/ui/components/ui/select";
@@ -43,24 +58,51 @@ const INBOX_CATEGORIES = [
{ key: "agents", groups: ["agent_activity"] },
] as const;
+// The actions of yours that can archive an issue's notifications, one key
+// each, as the custom choice lists them: those that settle the issue, then
+// those that only tidy it.
+const AUTO_ARCHIVE_GROUPS = [
+ {
+ key: "settle",
+ actions: [
+ { key: "auto_archive_completed", label: "completed" },
+ { key: "auto_archive_on_comment", label: "comment" },
+ { key: "auto_archive_on_status", label: "status" },
+ { key: "auto_archive_on_assignee", label: "assignee" },
+ ],
+ },
+ {
+ key: "tidy",
+ actions: [
+ { key: "auto_archive_on_priority", label: "priority" },
+ { key: "auto_archive_on_project", label: "project" },
+ { key: "auto_archive_on_dates", label: "dates" },
+ { key: "auto_archive_on_labels", label: "labels" },
+ ],
+ },
+] as const satisfies readonly { key: string; actions: readonly { key: AutoArchiveKey; label: string }[] }[];
+
+const AUTO_ARCHIVE_PRESET_ORDER: readonly AutoArchivePreset[] = ["never", "completed", "handled"];
+
export function NotificationsTab() {
const { t } = useT("settings");
const wsId = useWorkspaceId();
const p = useWorkspacePaths();
const { data } = useQuery(notificationPreferenceOptions(wsId));
const mutation = useUpdateNotificationPreferences();
+ const resolvePrompt = useResolveAutoArchivePrompt();
+ const [autoArchiveCustom, setAutoArchiveCustom] = useState(false);
const preferences = data?.preferences ?? {};
+ const onSaveError = (err: unknown) =>
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.notifications.toast_failed),
+ );
const save = (updated: NotificationPreferences) => {
- mutation.mutate(updated, {
- onError: (err) =>
- toast.error(
- err instanceof Error && err.message
- ? err.message
- : t(($) => $.notifications.toast_failed),
- ),
- });
+ mutation.mutate(updated, { onError: onSaveError });
};
const handleToggle = (key: NotificationGroupKey, enabled: boolean) => {
@@ -78,6 +120,40 @@ export function NotificationsTab() {
{ value: "all", label: t(($) => $.notifications.others_issues.all) },
];
+ const autoArchiveOn = autoArchiveActionsOn(preferences);
+ const autoArchiveChoice: AutoArchivePreset | "custom" = autoArchiveCustom
+ ? "custom"
+ : autoArchivePreset(preferences);
+ const autoArchiveItems: { value: AutoArchivePreset | "custom"; label: string }[] = [
+ ...AUTO_ARCHIVE_PRESET_ORDER.map((preset) => ({
+ value: preset,
+ label: t(($) => $.notifications.leaving.auto_presets[preset]),
+ })),
+ { value: "custom", label: t(($) => $.notifications.leaving.auto_presets.custom) },
+ ];
+ // Until the member answers the one-time question, a choice made here is
+ // their answer, for every workspace where it is pending.
+ const saveAutoArchive = (on: readonly AutoArchiveKey[]) => {
+ const values = autoArchivePreferences(on);
+ if (data?.auto_archive_prompt) {
+ resolvePrompt.mutate(values, { onError: onSaveError });
+ } else {
+ save({ ...preferences, ...values });
+ }
+ };
+ const handleAutoArchivePreset = (next: AutoArchivePreset | "custom") => {
+ setAutoArchiveCustom(next === "custom");
+ if (next !== "custom") saveAutoArchive(AUTO_ARCHIVE_PRESETS[next]);
+ };
+ const handleAutoArchiveAction = (key: AutoArchiveKey, on: boolean) => {
+ setAutoArchiveCustom(true);
+ saveAutoArchive(on ? [...autoArchiveOn, key] : autoArchiveOn.filter((k) => k !== key));
+ };
+ const afterAutoArchiveItems: { value: AfterAutoArchiveValue; label: string }[] = [
+ { value: "stay", label: t(($) => $.notifications.leaving.after_stay) },
+ { value: "next", label: t(($) => $.notifications.leaving.after_next) },
+ ];
+
const systemEnabled = preferences.system_notifications !== "muted";
return (
@@ -159,17 +235,106 @@ export function NotificationsTab() {
{t(($) => $.notifications.leaving.manual_value)}
</span>
</SettingsRow>
- <SettingsRow
- anchor="auto_archive_completed"
- label={t(($) => $.notifications.leaving.done_label)}
- description={t(($) => $.notifications.leaving.done_description)}
- >
- <Switch
- checked={preferences.auto_archive_completed !== "muted"}
- aria-label={t(($) => $.notifications.leaving.done_label)}
- onCheckedChange={(checked) => handleToggle("auto_archive_completed", checked)}
- />
- </SettingsRow>
+ <div>
+ <SettingsRow
+ anchor="auto_archive_completed"
+ className={cn(autoArchiveChoice === "custom" && "pb-2")}
+ label={t(($) => $.notifications.leaving.auto_label)}
+ description={t(($) => $.notifications.leaving.auto_description)}
+ >
+ <Select
+ items={autoArchiveItems}
+ value={autoArchiveChoice}
+ onValueChange={(next) => next && handleAutoArchivePreset(next as AutoArchivePreset | "custom")}
+ >
+ <SelectTrigger
+ size="sm"
+ className="w-auto min-w-56"
+ aria-label={t(($) => $.notifications.leaving.auto_label)}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end" alignItemWithTrigger={false} className="w-auto min-w-(--anchor-width)">
+ {AUTO_ARCHIVE_PRESET_ORDER.map((preset) => (
+ <SelectItem key={preset} value={preset}>
+ {t(($) => $.notifications.leaving.auto_presets[preset])}
+ {preset === "handled" && (
+ <Badge variant="secondary">
+ {t(($) => $.notifications.leaving.auto_recommended)}
+ </Badge>
+ )}
+ </SelectItem>
+ ))}
+ <SelectSeparator />
+ <SelectItem value="custom">
+ {t(($) => $.notifications.leaving.auto_presets.custom_item)}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+ {autoArchiveChoice === "custom" && (
+ <div className="grid grid-cols-[auto_1fr] items-center gap-x-4 gap-y-2.5 px-4 pb-3.5">
+ {AUTO_ARCHIVE_GROUPS.map((group) => (
+ <Fragment key={group.key}>
+ <div className="text-caption text-muted-foreground">
+ {t(($) => $.notifications.leaving.auto_groups[group.key])}
+ </div>
+ <div className="flex flex-wrap gap-2">
+ {group.actions.map((action) => {
+ const on = autoArchiveOn.includes(action.key);
+ return (
+ <label
+ key={action.key}
+ className={cn(
+ "inline-flex h-7 cursor-pointer items-center gap-2 rounded-md border border-border pr-2.5 pl-2 text-label transition-colors hover:bg-surface-hover",
+ !on && "text-muted-foreground",
+ )}
+ >
+ <Checkbox
+ checked={on}
+ onCheckedChange={(checked) => handleAutoArchiveAction(action.key, checked)}
+ />
+ {t(($) => $.notifications.leaving.auto_actions[action.label])}
+ </label>
+ );
+ })}
+ </div>
+ </Fragment>
+ ))}
+ </div>
+ )}
+ </div>
+ {autoArchiveOn.length > 0 && (
+ <SettingsRow
+ anchor="after_auto_archive"
+ className="pl-8"
+ label={t(($) => $.notifications.leaving.after_label)}
+ description={t(($) => $.notifications.leaving.after_description)}
+ >
+ <Select
+ items={afterAutoArchiveItems}
+ value={notificationPreferenceValue(preferences, "after_auto_archive")}
+ onValueChange={(next) =>
+ next && save({ ...preferences, after_auto_archive: next as AfterAutoArchiveValue })
+ }
+ >
+ <SelectTrigger
+ size="sm"
+ className="w-56"
+ aria-label={t(($) => $.notifications.leaving.after_label)}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent align="end">
+ {afterAutoArchiveItems.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+ )}
<SettingsRow
anchor="archived"
label={t(($) => $.notifications.leaving.archived_label)}
diff --git a/packages/views/settings/components/use-settings-search-index.ts b/packages/views/settings/components/use-settings-search-index.ts
index 4329a27922..90ee8b2c88 100644
--- a/packages/views/settings/components/use-settings-search-index.ts
+++ b/packages/views/settings/components/use-settings-search-index.ts
@@ -191,8 +191,15 @@ export function useSettingsSearchIndex(
{
tab: "notifications",
anchor: "auto_archive_completed",
- title: t(($) => $.notifications.leaving.done_label),
- description: t(($) => $.notifications.leaving.done_description),
+ title: t(($) => $.notifications.leaving.auto_label),
+ description: t(($) => $.notifications.leaving.auto_description),
+ },
+ // Lands on the row above: this one is hidden while auto-archive is off.
+ {
+ tab: "notifications",
+ anchor: "auto_archive_completed",
+ title: t(($) => $.notifications.leaving.after_label),
+ description: t(($) => $.notifications.leaving.after_description),
},
{
tab: "notifications",
diff --git a/server/cmd/server/notification_listeners.go b/server/cmd/server/notification_listeners.go
index 3dd535f96e..53b9644e75 100644
--- a/server/cmd/server/notification_listeners.go
+++ b/server/cmd/server/notification_listeners.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"log/slog"
+ "slices"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
@@ -331,16 +332,70 @@ func archiveStaleTaskFailedInbox(
"row_count", len(rows), "recipient_count", count)
}
-// autoArchiveCompletedPref is the preference key for archiving your own
-// notifications when you move an issue to a done or closed status. It is on
-// unless set to "muted".
-const autoArchiveCompletedPref = "auto_archive_completed"
+// Preference keys, one per action you take on an issue, that archive your own
+// notifications on it. Completing means moving it to a done or closed status;
+// a status change means any other status. Settling actions are on unless
+// "muted"; edits that only tidy the issue are off unless "all".
+const (
+ autoArchiveCompletedPref = "auto_archive_completed"
+ autoArchiveCommentPref = "auto_archive_on_comment"
+ autoArchiveStatusPref = "auto_archive_on_status"
+ autoArchiveAssigneePref = "auto_archive_on_assignee"
+ autoArchivePriorityPref = "auto_archive_on_priority"
+ autoArchiveProjectPref = "auto_archive_on_project"
+ autoArchiveDatesPref = "auto_archive_on_dates"
+ autoArchiveLabelsPref = "auto_archive_on_labels"
+)
+
+var autoArchiveOnByDefault = map[string]bool{
+ autoArchiveCompletedPref: true,
+ autoArchiveCommentPref: true,
+ autoArchiveStatusPref: true,
+ autoArchiveAssigneePref: true,
+}
+
+// Why the actor's notifications were archived, sent as `reason` on
+// inbox:batch-archived so the client can tell its user's own action apart.
+const (
+ archiveReasonCompleted = "issue_status_terminal"
+ archiveReasonActed = "actor_acted"
+)
+
+// autoArchivesOn reports whether prefs archive the actor's notifications when
+// they take action. nil prefs, a member without a stored row, applies the
+// defaults.
+func autoArchivesOn(prefs map[string]string, action string) bool {
+ if autoArchiveOnByDefault[action] {
+ return prefs[action] != "muted"
+ }
+ return prefs[action] == "all"
+}
-// archiveTerminalIssueInbox archives the actor's own notifications for an
-// issue they moved to a done or closed status, read or not, the same set
-// "Archive completed" clears by hand. Other recipients keep theirs: someone
-// else finishing an issue is news they have not seen yet.
-func archiveTerminalIssueInbox(
+// issueFieldActions lists the auto-archive actions an issue:updated payload
+// took on fields other than status, which depends on the status category.
+// Title, description and parent edits archive nothing.
+func issueFieldActions(payload map[string]any) []string {
+ var actions []string
+ for _, field := range []struct{ changed, action string }{
+ {"assignee_changed", autoArchiveAssigneePref},
+ {"priority_changed", autoArchivePriorityPref},
+ {"project_changed", autoArchiveProjectPref},
+ {"start_date_changed", autoArchiveDatesPref},
+ {"due_date_changed", autoArchiveDatesPref},
+ } {
+ if changed, _ := payload[field.changed].(bool); changed {
+ actions = append(actions, field.action)
+ }
+ }
+ return actions
+}
+
+// archiveActorIssueInbox archives the actor's own notifications for an issue,
+// read or not, when their preferences archive on one of the actions they just
+// took on it. Completing archives the same set "Archive completed" clears by
+// hand. Other recipients keep theirs: someone else acting on an issue is news
+// they have not seen yet. A later notification brings the issue back.
+func archiveActorIssueInbox(
ctx context.Context,
queries *db.Queries,
bus *events.Bus,
@@ -348,8 +403,9 @@ func archiveTerminalIssueInbox(
issueID string,
actorType string,
actorID string,
+ actions ...string,
) {
- if actorType != "member" || actorID == "" {
+ if actorType != "member" || actorID == "" || issueID == "" || len(actions) == 0 {
return
}
@@ -358,23 +414,33 @@ func archiveTerminalIssueInbox(
WorkspaceID: parseUUID(workspaceID),
UserID: parseUUID(actorID),
})
+ var prefs map[string]string
switch {
case errors.Is(err, pgx.ErrNoRows):
case err != nil:
- slog.Warn("auto-archive terminal issue inbox: load preference failed; keeping rows",
- "workspace_id", workspaceID, "issue_id", issueID, "error", err)
+ slog.Warn("auto-archive actor issue inbox: load preference failed; keeping rows",
+ "workspace_id", workspaceID, "issue_id", issueID, "actions", actions, "error", err)
return
default:
- var prefs map[string]string
if err := json.Unmarshal(pref.Preferences, &prefs); err != nil {
- slog.Warn("auto-archive terminal issue inbox: bad preference JSON; keeping rows",
- "workspace_id", workspaceID, "issue_id", issueID, "error", err)
+ slog.Warn("auto-archive actor issue inbox: bad preference JSON; keeping rows",
+ "workspace_id", workspaceID, "issue_id", issueID, "actions", actions, "error", err)
return
}
- if prefs[autoArchiveCompletedPref] == "muted" {
- return
+ }
+ var archivedOn []string
+ for _, action := range actions {
+ if autoArchivesOn(prefs, action) {
+ archivedOn = append(archivedOn, action)
}
}
+ if len(archivedOn) == 0 {
+ return
+ }
+ reason := archiveReasonActed
+ if slices.Contains(archivedOn, autoArchiveCompletedPref) {
+ reason = archiveReasonCompleted
+ }
count, err := queries.ArchiveInboxByIssue(ctx, db.ArchiveInboxByIssueParams{
WorkspaceID: parseUUID(workspaceID),
@@ -383,8 +449,8 @@ func archiveTerminalIssueInbox(
IssueID: parseUUID(issueID),
})
if err != nil {
- slog.Error("auto-archive terminal issue inbox: query failed",
- "workspace_id", workspaceID, "issue_id", issueID, "error", err)
+ slog.Error("auto-archive actor issue inbox: query failed",
+ "workspace_id", workspaceID, "issue_id", issueID, "reason", reason, "error", err)
return
}
if count == 0 {
@@ -397,12 +463,12 @@ func archiveTerminalIssueInbox(
"recipient_id": actorID,
"count": count,
"issue_id": issueID,
- "reason": "issue_status_terminal",
+ "reason": reason,
},
})
- slog.Info("auto-archive terminal issue inbox: archived rows",
- "workspace_id", workspaceID, "issue_id", issueID, "row_count", count)
+ slog.Info("auto-archive actor issue inbox: archived rows",
+ "workspace_id", workspaceID, "issue_id", issueID, "reason", reason, "row_count", count)
}
type inboxArchivedRecipient struct {
@@ -970,6 +1036,7 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {
prevAssigneeType, _ := payload["prev_assignee_type"].(*string)
prevAssigneeID, _ := payload["prev_assignee_id"].(*string)
prevDescription, _ := payload["prev_description"].(*string)
+ archiveActions := issueFieldActions(payload)
if assigneeChanged {
// Build structured details for assignee change.
@@ -1070,16 +1137,18 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {
archiveStaleTaskFailedInbox(ctx, queries, bus, e.WorkspaceID, issue.ID)
}
- // After the status_changed rows above, so "moved to Done" leaves
- // the actor's inbox together with the rest of the issue's
- // notifications.
+ // Archived at the end of this listener, after the status_changed
+ // rows above, so "moved to Done" leaves the actor's inbox together
+ // with the rest of the issue's notifications.
category, categoryErr := issuestatus.CategoryWithError(ctx, queries, parseUUID(e.WorkspaceID), issue.Status)
switch {
case categoryErr != nil:
- slog.Warn("resolve issue status category for terminal-issue inbox archive; keeping rows",
+ slog.Warn("resolve issue status category for actor issue inbox archive; keeping rows",
"issue_id", issue.ID, "status", issue.Status, "error", categoryErr)
case category == issuestatus.CategoryDone, category == issuestatus.CategoryClosed:
- archiveTerminalIssueInbox(ctx, queries, bus, e.WorkspaceID, issue.ID, e.ActorType, e.ActorID)
+ archiveActions = append(archiveActions, autoArchiveCompletedPref)
+ default:
+ archiveActions = append(archiveActions, autoArchiveStatusPref)
}
}
@@ -1154,6 +1223,17 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {
issue.Title, "", skip, emptyDetails)
}
}
+
+ archiveActorIssueInbox(ctx, queries, bus, e.WorkspaceID, issue.ID, e.ActorType, e.ActorID, archiveActions...)
+ })
+
+ bus.Subscribe(protocol.EventIssueLabelsChanged, func(e events.Event) {
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ return
+ }
+ issueID, _ := payload["issue_id"].(string)
+ archiveActorIssueInbox(ctx, queries, bus, e.WorkspaceID, issueID, e.ActorType, e.ActorID, autoArchiveLabelsPref)
})
// comment:created — notify all subscribers except the commenter
@@ -1218,6 +1298,12 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {
mentioned, "new_comment", "info",
issueTitle, commentContent,
commentDetails)
+
+ // A quick action posts its prompt as the member's own comment, so
+ // running one counts the same as replying.
+ if authorType == "member" {
+ archiveActorIssueInbox(ctx, queries, bus, e.WorkspaceID, issueID, e.ActorType, e.ActorID, autoArchiveCommentPref)
+ }
})
// issue_reaction:added — notify the issue creator
diff --git a/server/cmd/server/notification_listeners_test.go b/server/cmd/server/notification_listeners_test.go
index 8b5b98bf3a..211fe8d202 100644
--- a/server/cmd/server/notification_listeners_test.go
+++ b/server/cmd/server/notification_listeners_test.go
@@ -1321,6 +1321,10 @@ func TestNotification_StatusChange_ArchivesStaleTaskFailed(t *testing.T) {
queries := db.New(testPool)
bus := newNotificationBus(t, queries)
+ // The actor's own status change would archive every row it has on the
+ // issue; this test is about which rows the change retires for everyone.
+ setNotificationPref(t, testUserID, "auto_archive_on_status", "muted")
+
subEmail := "[email protected]"
subID := createNotificationMember(t, subEmail)
t.Cleanup(func() { cleanupTestUser(t, subEmail) })
@@ -1552,8 +1556,10 @@ func TestNotification_StatusChange_DoneKeepsInboxWhenNotArchivedByActor(t *testi
// TestNotification_StatusChange_TerminalArchivesIssueInbox verifies that a
// closed status (cancelled) clears the inbox like done does, while a status
-// that is not done or closed keeps the issue's notifications.
+// that is not done or closed keeps the issue's notifications for a member who
+// turned off archiving on other status changes.
func TestNotification_StatusChange_TerminalArchivesIssueInbox(t *testing.T) {
+ setNotificationPref(t, testUserID, "auto_archive_on_status", "muted")
for _, tc := range []struct {
status string
wantActive int
@@ -1588,6 +1594,204 @@ func TestNotification_StatusChange_TerminalArchivesIssueInbox(t *testing.T) {
}
}
+func seedInboxRow(t *testing.T, recipientID, issueID string) {
+ t.Helper()
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, details)
+ VALUES ($1, 'member', $2, 'new_comment', 'info', $3, 'acted archive test', '{}')
+ `, testWorkspaceID, recipientID, issueID); err != nil {
+ t.Fatalf("seed notification: %v", err)
+ }
+}
+
+func publishCommentBy(bus *events.Bus, issueID, actorType, actorID string) {
+ bus.Publish(events.Event{
+ Type: protocol.EventCommentCreated,
+ WorkspaceID: testWorkspaceID,
+ ActorType: actorType,
+ ActorID: actorID,
+ Payload: map[string]any{
+ "comment": handler.CommentResponse{
+ ID: "00000000-0000-0000-0000-000000000000",
+ IssueID: issueID,
+ AuthorType: actorType,
+ AuthorID: actorID,
+ Content: "looks good, merging",
+ Type: "comment",
+ },
+ "issue_title": "acted archive test",
+ "issue_status": "in_review",
+ },
+ })
+}
+
+func publishIssueFieldsBy(bus *events.Bus, issueID, actorID string, changed ...string) {
+ payload := map[string]any{
+ "issue": handler.IssueResponse{
+ ID: issueID,
+ WorkspaceID: testWorkspaceID,
+ Title: "acted archive test",
+ Status: "in_review",
+ Priority: "high",
+ CreatorType: "member",
+ CreatorID: testUserID,
+ },
+ "prev_status": "in_review",
+ "prev_priority": "medium",
+ }
+ for _, key := range changed {
+ payload[key] = true
+ }
+ bus.Publish(events.Event{
+ Type: protocol.EventIssueUpdated,
+ WorkspaceID: testWorkspaceID,
+ ActorType: "member",
+ ActorID: actorID,
+ Payload: payload,
+ })
+}
+
+func publishLabelsChangedBy(bus *events.Bus, issueID, actorID string) {
+ bus.Publish(events.Event{
+ Type: protocol.EventIssueLabelsChanged,
+ WorkspaceID: testWorkspaceID,
+ ActorType: "member",
+ ActorID: actorID,
+ Payload: map[string]any{"issue_id": issueID},
+ })
+}
+
+// TestNotification_HandlingArchivesIssueInbox verifies that commenting on an
+// issue, changing its status or reassigning it archives the actor's own
+// notifications on it by default, that tidying edits do once turned on, and
+// that other recipients keep theirs.
+func TestNotification_HandlingArchivesIssueInbox(t *testing.T) {
+ queries := db.New(testPool)
+
+ defaultEmail := "[email protected]"
+ defaultID := createNotificationMember(t, defaultEmail)
+ t.Cleanup(func() { cleanupTestUser(t, defaultEmail) })
+
+ tidyEmail := "[email protected]"
+ tidyID := createNotificationMember(t, tidyEmail)
+ t.Cleanup(func() { cleanupTestUser(t, tidyEmail) })
+ for _, key := range []string{"auto_archive_on_priority", "auto_archive_on_project", "auto_archive_on_dates", "auto_archive_on_labels"} {
+ setNotificationPref(t, tidyID, key, "all")
+ }
+
+ for _, tc := range []struct {
+ name string
+ actor string
+ act func(bus *events.Bus, issueID, actorID string)
+ }{
+ {"comment", defaultID, func(bus *events.Bus, issueID, actorID string) { publishCommentBy(bus, issueID, "member", actorID) }},
+ {"status", defaultID, func(bus *events.Bus, issueID, actorID string) {
+ publishIssueFieldsBy(bus, issueID, actorID, "status_changed")
+ }},
+ {"assignee", defaultID, func(bus *events.Bus, issueID, actorID string) {
+ publishIssueFieldsBy(bus, issueID, actorID, "assignee_changed")
+ }},
+ {"priority", tidyID, func(bus *events.Bus, issueID, actorID string) {
+ publishIssueFieldsBy(bus, issueID, actorID, "priority_changed")
+ }},
+ {"project", tidyID, func(bus *events.Bus, issueID, actorID string) {
+ publishIssueFieldsBy(bus, issueID, actorID, "project_changed")
+ }},
+ {"due date", tidyID, func(bus *events.Bus, issueID, actorID string) {
+ publishIssueFieldsBy(bus, issueID, actorID, "due_date_changed")
+ }},
+ {"labels", tidyID, publishLabelsChangedBy},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ bus := newNotificationBus(t, queries)
+ issueID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() {
+ cleanupInboxForIssue(t, issueID)
+ cleanupTestIssue(t, issueID)
+ })
+ seedInboxRow(t, tc.actor, issueID)
+ seedInboxRow(t, testUserID, issueID)
+
+ var reasons []any
+ bus.Subscribe(protocol.EventInboxBatchArchived, func(e events.Event) {
+ payload, _ := e.Payload.(map[string]any)
+ if payload["issue_id"] == issueID && payload["recipient_id"] == tc.actor {
+ reasons = append(reasons, payload["reason"])
+ }
+ })
+
+ tc.act(bus, issueID, tc.actor)
+
+ if active := countActiveInboxForIssue(t, tc.actor, issueID); active != 0 {
+ t.Fatalf("actor: expected no active inbox rows after acting, got %d", active)
+ }
+ if active := countActiveInboxForIssue(t, testUserID, issueID); active != 1 {
+ t.Fatalf("other recipient: expected 1 active inbox row, got %d", active)
+ }
+ if len(reasons) != 1 || reasons[0] != "actor_acted" {
+ t.Fatalf("expected one inbox:batch-archived with reason actor_acted, got %v", reasons)
+ }
+ })
+ }
+}
+
+// TestNotification_HandlingKeepsInbox verifies that the inbox stays for
+// tidying edits by default, for an action the member turned off, and for an
+// agent actor. Completing stays off when muted even though status changes are
+// on: each action is its own choice.
+func TestNotification_HandlingKeepsInbox(t *testing.T) {
+ queries := db.New(testPool)
+
+ defaultEmail := "[email protected]"
+ defaultID := createNotificationMember(t, defaultEmail)
+ t.Cleanup(func() { cleanupTestUser(t, defaultEmail) })
+
+ mutedEmail := "[email protected]"
+ mutedID := createNotificationMember(t, mutedEmail)
+ t.Cleanup(func() { cleanupTestUser(t, mutedEmail) })
+ for _, key := range []string{"auto_archive_completed", "auto_archive_on_comment", "auto_archive_on_assignee"} {
+ setNotificationPref(t, mutedID, key, "muted")
+ }
+
+ for _, tc := range []struct {
+ name string
+ recipient string
+ act func(bus *events.Bus, issueID string)
+ }{
+ {"tidying edits by default", defaultID, func(bus *events.Bus, issueID string) {
+ publishIssueFieldsBy(bus, issueID, defaultID,
+ "title_changed", "priority_changed", "project_changed", "start_date_changed", "due_date_changed")
+ }},
+ {"labels by default", defaultID, func(bus *events.Bus, issueID string) { publishLabelsChangedBy(bus, issueID, defaultID) }},
+ {"agent actor", defaultID, func(bus *events.Bus, issueID string) {
+ publishCommentBy(bus, issueID, "agent", "00000000-0000-0000-0000-aaaaaaaaaaaa")
+ }},
+ {"comment turned off", mutedID, func(bus *events.Bus, issueID string) { publishCommentBy(bus, issueID, "member", mutedID) }},
+ {"assignee turned off", mutedID, func(bus *events.Bus, issueID string) {
+ publishIssueFieldsBy(bus, issueID, mutedID, "assignee_changed")
+ }},
+ {"completing turned off", mutedID, func(bus *events.Bus, issueID string) {
+ publishStatusChangeBy(bus, issueID, "done", "in_review", "member", mutedID)
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ bus := newNotificationBus(t, queries)
+ issueID := createTestIssue(t, testWorkspaceID, testUserID)
+ t.Cleanup(func() {
+ cleanupInboxForIssue(t, issueID)
+ cleanupTestIssue(t, issueID)
+ })
+ seedInboxRow(t, tc.recipient, issueID)
+
+ tc.act(bus, issueID)
+
+ if active := countActiveInboxForIssue(t, tc.recipient, issueID); active != 1 {
+ t.Fatalf("expected the notification to stay in the inbox, got %d active", active)
+ }
+ })
+ }
+}
+
// TestNotification_StatusChange_NonTerminalKeepsTaskFailed verifies that a
// transition to a non-terminal status (e.g. in_progress) does NOT archive
// existing task_failed inbox rows.
@@ -1595,6 +1799,10 @@ func TestNotification_StatusChange_NonTerminalKeepsTaskFailed(t *testing.T) {
queries := db.New(testPool)
bus := newNotificationBus(t, queries)
+ // The actor's own status change would archive every row it has on the
+ // issue; this test is about which rows the change retires for everyone.
+ setNotificationPref(t, testUserID, "auto_archive_on_status", "muted")
+
issueID := createTestIssue(t, testWorkspaceID, testUserID)
t.Cleanup(func() {
cleanupInboxForIssue(t, issueID)
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index c6c22bb615..90663802eb 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2833,6 +2833,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/", h.GetNotificationPreferences)
r.Patch("/", h.PatchNotificationPreferences)
r.Put("/", h.UpdateNotificationPreferences)
+ r.Post("/auto-archive-prompt", h.ResolveAutoArchivePrompt)
})
})
})
diff --git a/server/internal/handler/notification_preference.go b/server/internal/handler/notification_preference.go
index edf3e20777..13e3a46930 100644
--- a/server/internal/handler/notification_preference.go
+++ b/server/internal/handler/notification_preference.go
@@ -5,6 +5,7 @@ import (
"errors"
"log/slog"
"net/http"
+ "strings"
"github.com/jackc/pgx/v5"
"github.com/multica-ai/multica/server/internal/inbox"
@@ -17,21 +18,33 @@ import (
// not an inbox event group — it's a delivery-channel toggle controlling
// whether native OS notification banners fire — but it shares the same
// preferences map so a single endpoint covers all user notification
-// preferences. `auto_archive_completed` is not an event group either: "muted"
-// stops your notifications from being archived when you complete an issue.
+// preferences. The `auto_archive_*` keys are not event groups either: each
+// says whether one action you take on an issue archives your notifications on
+// it. Completing, commenting, other status changes and reassigning archive
+// unless "muted"; priority, project, date and label edits only with "all".
+// `after_auto_archive` is where the client goes when the notification you are
+// reading is archived that way.
var validNotifGroups = map[string]bool{
- "assignments": true,
- "status_changes": true,
- "comments": true,
- "chat_replies": true,
- "mentions": true,
- "reactions": true,
- "updates": true,
- "agent_activity": true,
- "new_issues": true,
- "system_notifications": true,
- "auto_archive_completed": true,
- "others_issues": true,
+ "assignments": true,
+ "status_changes": true,
+ "comments": true,
+ "chat_replies": true,
+ "mentions": true,
+ "reactions": true,
+ "updates": true,
+ "agent_activity": true,
+ "new_issues": true,
+ "system_notifications": true,
+ "auto_archive_completed": true,
+ "auto_archive_on_comment": true,
+ "auto_archive_on_status": true,
+ "auto_archive_on_assignee": true,
+ "auto_archive_on_priority": true,
+ "auto_archive_on_project": true,
+ "auto_archive_on_dates": true,
+ "auto_archive_on_labels": true,
+ "after_auto_archive": true,
+ "others_issues": true,
}
// validNotifValues is the set of allowed preference values for a group not
@@ -45,10 +58,21 @@ var validNotifValues = map[string]bool{
// `others_issues` is how much of someone else's issue a passive subscriber
// receives: absent or "key_updates" for mentions, thread replies and handoffs,
// "all" for every event. Muting it would only hide what still needs you.
+// `after_auto_archive` is absent or "stay" to keep the archived notification
+// open, "next" to open the next one.
var notifValuesByGroup = map[string]map[string]bool{
- "others_issues": {"all": true, "key_updates": true},
+ "others_issues": {"all": true, "key_updates": true},
+ "after_auto_archive": {"stay": true, "next": true},
}
+// autoArchivePromptKey marks a workspace where the member has not yet answered
+// the one-time question of which actions archive their notifications. Migration
+// 718 writes it for members who archived notifications before replying,
+// changing status and reassigning did so by default. It is stored with the
+// preferences but answered as the response's own `auto_archive_prompt` flag,
+// so no client ever echoes it back in a write.
+const autoArchivePromptKey = "auto_archive_prompt"
+
func validNotifValue(group, value string) bool {
if values, ok := notifValuesByGroup[group]; ok {
return values[value]
@@ -70,8 +94,9 @@ func (h *Handler) GetNotificationPreferences(w http.ResponseWriter, r *http.Requ
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
writeJSON(w, http.StatusOK, map[string]any{
- "workspace_id": workspaceID,
- "preferences": inbox.WithDefaults(nil),
+ "workspace_id": workspaceID,
+ "preferences": inbox.WithDefaults(nil),
+ "auto_archive_prompt": false,
})
return
}
@@ -135,10 +160,13 @@ func writeNotificationPreferenceResponse(
if err := json.Unmarshal(pref.Preferences, &prefs); err != nil {
prefs = map[string]string{}
}
+ _, prompt := prefs[autoArchivePromptKey]
+ delete(prefs, autoArchivePromptKey)
writeJSON(w, http.StatusOK, map[string]any{
- "workspace_id": workspaceID,
- "preferences": inbox.WithDefaults(prefs),
+ "workspace_id": workspaceID,
+ "preferences": inbox.WithDefaults(prefs),
+ "auto_archive_prompt": prompt,
})
}
@@ -203,3 +231,39 @@ func (h *Handler) PatchNotificationPreferences(w http.ResponseWriter, r *http.Re
}
writeNotificationPreferenceResponse(w, workspaceID, pref)
}
+
+// ResolveAutoArchivePrompt answers the one-time auto-archive question once for
+// all of the caller's workspaces: the supplied `auto_archive_*` values are
+// merged into every one of their preference rows still marked with
+// auto_archive_prompt, and the marker is dropped. An empty map keeps what each
+// workspace has. Answers with the current workspace's preferences.
+func (h *Handler) ResolveAutoArchivePrompt(w http.ResponseWriter, r *http.Request) {
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ prefs, ok := decodeNotificationPreferenceRequest(w, r)
+ if !ok {
+ return
+ }
+ for k := range prefs {
+ if !strings.HasPrefix(k, "auto_archive_") {
+ writeError(w, http.StatusBadRequest, "invalid preference group: "+k)
+ return
+ }
+ }
+ prefsJSON, ok := marshalNotificationPreferences(w, prefs)
+ if !ok {
+ return
+ }
+
+ if err := h.Queries.ResolveAutoArchivePrompt(r.Context(), db.ResolveAutoArchivePromptParams{
+ UserID: parseUUID(userID),
+ Preferences: prefsJSON,
+ }); err != nil {
+ slog.Warn("ResolveAutoArchivePrompt failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to update notification preferences")
+ return
+ }
+ h.GetNotificationPreferences(w, r)
+}
diff --git a/server/internal/handler/notification_preference_test.go b/server/internal/handler/notification_preference_test.go
index f97cb2fa2c..f4e989b476 100644
--- a/server/internal/handler/notification_preference_test.go
+++ b/server/internal/handler/notification_preference_test.go
@@ -289,8 +289,10 @@ func TestLegacyPutKeepsOmittedStatusChangesOn(t *testing.T) {
}
// TestPatchNotificationPreferencesAcceptsAddedGroups covers groups added after
-// the original set: mentions (#6468), reactions (MUL-9328) and
-// auto_archive_completed (MUL-9336). The whitelist rejects unknown keys, so a
+// the original set: mentions (#6468), reactions (MUL-9328),
+// auto_archive_completed (MUL-9336) and the per-action auto_archive_on_*
+// keys (MUL-9788).
+// The whitelist rejects unknown keys, so a
// client shipped ahead of the server would 400 on these keys — the reason the
// server must deploy first.
func TestPatchNotificationPreferencesAcceptsAddedGroups(t *testing.T) {
@@ -303,6 +305,8 @@ func TestPatchNotificationPreferencesAcceptsAddedGroups(t *testing.T) {
{"reactions"},
{"auto_archive_completed"},
{"reactions", "auto_archive_completed"},
+ {"auto_archive_on_comment", "auto_archive_on_status", "auto_archive_on_assignee"},
+ {"auto_archive_on_priority", "auto_archive_on_project", "auto_archive_on_dates", "auto_archive_on_labels"},
} {
t.Run(strings.Join(groups, "+"), func(t *testing.T) {
t.Cleanup(func() {
@@ -398,3 +402,147 @@ func TestPatchNotificationPreferencesValidatesOthersIssuesValues(t *testing.T) {
t.Fatalf("comments=key_updates: status=%d body=%s", recorder.Code, recorder.Body.String())
}
}
+
+func TestPatchNotificationPreferencesValidatesAfterAutoArchiveValues(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `
+ DELETE FROM notification_preference
+ WHERE workspace_id = $1 AND user_id = $2
+ `, testWorkspaceID, testUserID)
+ })
+
+ for value, want := range map[string]int{
+ "stay": http.StatusOK,
+ "next": http.StatusOK,
+ "all": http.StatusBadRequest,
+ "muted": http.StatusBadRequest,
+ } {
+ recorder := httptest.NewRecorder()
+ testHandler.PatchNotificationPreferences(
+ recorder,
+ notificationPreferenceRequest(t, http.MethodPatch, map[string]string{
+ "after_auto_archive": value,
+ }),
+ )
+ if recorder.Code != want {
+ t.Errorf("after_auto_archive=%q: status=%d want %d body=%s",
+ value, recorder.Code, want, recorder.Body.String())
+ }
+ }
+}
+
+// Members asked once which actions archive their notifications (migration 718)
+// answer for every workspace at once; the marker never reaches a client as a
+// preference it could write back.
+func TestAutoArchivePromptResolvesEveryPendingWorkspace(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ suffix := strings.ReplaceAll(t.Name(), "/", "-")
+ otherWorkspaceID := dbfx.Workspace(t, "Auto-archive prompt", strings.ToLower(suffix))
+ dbfx.Member(t, otherWorkspaceID, testUserID, "member")
+ otherUserID := dbfx.User(t, "Auto-archive teammate", strings.ToLower(suffix)+"@multica.test")
+ dbfx.Member(t, testWorkspaceID, otherUserID, "member")
+
+ pending := `{"auto_archive_on_comment": "muted", "auto_archive_on_status": "muted",
+ "auto_archive_on_assignee": "muted", "auto_archive_prompt": "pending", "updates": "muted"}`
+ rows := [][2]string{{testWorkspaceID, testUserID}, {otherWorkspaceID, testUserID}, {testWorkspaceID, otherUserID}}
+ for _, row := range rows {
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO notification_preference (workspace_id, user_id, preferences)
+ VALUES ($1, $2, $3::jsonb)
+ ON CONFLICT (workspace_id, user_id) DO UPDATE SET preferences = EXCLUDED.preferences
+ `, row[0], row[1], pending); err != nil {
+ t.Fatalf("seed preference: %v", err)
+ }
+ }
+ t.Cleanup(func() {
+ for _, row := range rows {
+ _, _ = testPool.Exec(context.Background(), `
+ DELETE FROM notification_preference WHERE workspace_id = $1 AND user_id = $2
+ `, row[0], row[1])
+ }
+ })
+
+ type response struct {
+ Preferences map[string]string `json:"preferences"`
+ AutoArchivePrompt bool `json:"auto_archive_prompt"`
+ }
+ decode := func(recorder *httptest.ResponseRecorder) response {
+ t.Helper()
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+ var got response
+ if err := json.NewDecoder(recorder.Body).Decode(&got); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ return got
+ }
+ stored := func(workspaceID, userID string) map[string]string {
+ t.Helper()
+ var raw []byte
+ if err := testPool.QueryRow(ctx, `
+ SELECT preferences FROM notification_preference WHERE workspace_id = $1 AND user_id = $2
+ `, workspaceID, userID).Scan(&raw); err != nil {
+ t.Fatalf("load preference: %v", err)
+ }
+ var prefs map[string]string
+ if err := json.Unmarshal(raw, &prefs); err != nil {
+ t.Fatalf("decode preference: %v", err)
+ }
+ return prefs
+ }
+
+ get := httptest.NewRecorder()
+ testHandler.GetNotificationPreferences(get, notificationPreferenceRequest(t, http.MethodGet, nil))
+ before := decode(get)
+ if !before.AutoArchivePrompt {
+ t.Fatal("auto_archive_prompt = false, want true while pending")
+ }
+ if _, ok := before.Preferences[autoArchivePromptKey]; ok {
+ t.Fatalf("preferences expose the prompt marker: %#v", before.Preferences)
+ }
+
+ for _, invalid := range []map[string]string{
+ {"updates": "all"},
+ {"after_auto_archive": "next"},
+ {"auto_archive_prompt": "pending"},
+ } {
+ recorder := httptest.NewRecorder()
+ testHandler.ResolveAutoArchivePrompt(recorder, notificationPreferenceRequest(t, http.MethodPost, invalid))
+ if recorder.Code != http.StatusBadRequest {
+ t.Errorf("resolve with %v: status=%d want 400", invalid, recorder.Code)
+ }
+ }
+
+ resolve := httptest.NewRecorder()
+ testHandler.ResolveAutoArchivePrompt(resolve, notificationPreferenceRequest(t, http.MethodPost, map[string]string{
+ "auto_archive_completed": "all",
+ "auto_archive_on_comment": "all",
+ "auto_archive_on_status": "all",
+ "auto_archive_on_assignee": "all",
+ }))
+ after := decode(resolve)
+ if after.AutoArchivePrompt {
+ t.Fatal("auto_archive_prompt still true after resolving")
+ }
+ if after.Preferences["auto_archive_on_comment"] != "all" || after.Preferences["updates"] != "muted" {
+ t.Fatalf("resolved preferences = %#v", after.Preferences)
+ }
+
+ for _, workspaceID := range []string{testWorkspaceID, otherWorkspaceID} {
+ prefs := stored(workspaceID, testUserID)
+ if _, ok := prefs[autoArchivePromptKey]; ok || prefs["auto_archive_on_status"] != "all" {
+ t.Errorf("workspace %s not resolved: %#v", workspaceID, prefs)
+ }
+ }
+ if prefs := stored(testWorkspaceID, otherUserID); prefs[autoArchivePromptKey] != "pending" ||
+ prefs["auto_archive_on_status"] != "muted" {
+ t.Errorf("another member's prompt changed: %#v", prefs)
+ }
+}
diff --git a/server/internal/migrations/auto_archive_prompt_migration_test.go b/server/internal/migrations/auto_archive_prompt_migration_test.go
new file mode 100644
index 0000000000..3e60cbc96f
--- /dev/null
+++ b/server/internal/migrations/auto_archive_prompt_migration_test.go
@@ -0,0 +1,163 @@
+package migrations
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+func TestAutoArchivePromptAsksOnlyMembersWhoArchived(t *testing.T) {
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ t.Skip("integration test requires Postgres at DATABASE_URL")
+ }
+
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ t.Fatalf("connect to Postgres: %v", err)
+ }
+ defer pool.Close()
+
+ schema := "auto_archive_prompt_" + strings.ReplaceAll(uuid.NewString(), "-", "")
+ quotedSchema := pgx.Identifier{schema}.Sanitize()
+ if _, err := pool.Exec(ctx, "CREATE SCHEMA "+quotedSchema); err != nil {
+ t.Fatalf("create schema: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA "+quotedSchema+" CASCADE")
+ })
+
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire connection: %v", err)
+ }
+ defer conn.Release()
+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, schema); err != nil {
+ t.Fatalf("set search path: %v", err)
+ }
+
+ const (
+ ws = "11111111-1111-1111-1111-111111111111"
+ otherWS = "22222222-2222-2222-2222-222222222222"
+ archiver = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
+ chooser = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
+ reader = "cccccccc-cccc-cccc-cccc-cccccccccccc"
+ formerMem = "dddddddd-dddd-dddd-dddd-dddddddddddd"
+ agent = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"
+ )
+ if _, err := conn.Exec(ctx, `
+ CREATE TABLE member (
+ workspace_id UUID NOT NULL,
+ user_id UUID NOT NULL,
+ UNIQUE (workspace_id, user_id)
+ );
+ CREATE TABLE inbox_item (
+ workspace_id UUID NOT NULL,
+ recipient_type TEXT NOT NULL,
+ recipient_id UUID NOT NULL,
+ archived BOOLEAN NOT NULL DEFAULT FALSE
+ );
+ CREATE TABLE notification_preference (
+ workspace_id UUID NOT NULL,
+ user_id UUID NOT NULL,
+ preferences JSONB NOT NULL DEFAULT '{}',
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (workspace_id, user_id)
+ );
+ `); err != nil {
+ t.Fatalf("create fixture tables: %v", err)
+ }
+ seed := strings.NewReplacer(
+ "$ws", ws, "$other", otherWS, "$archiver", archiver, "$chooser", chooser,
+ "$reader", reader, "$former", formerMem, "$agent", agent,
+ ).Replace(`
+ INSERT INTO member (workspace_id, user_id) VALUES
+ ('$ws', '$archiver'), ('$ws', '$chooser'), ('$ws', '$reader'), ('$other', '$archiver');
+ INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, archived) VALUES
+ ('$ws', 'member', '$archiver', TRUE),
+ ('$other', 'member', '$archiver', FALSE),
+ ('$ws', 'member', '$chooser', TRUE),
+ ('$ws', 'member', '$reader', FALSE),
+ ('$ws', 'member', '$former', TRUE),
+ ('$ws', 'agent', '$agent', TRUE);
+ INSERT INTO notification_preference (workspace_id, user_id, preferences) VALUES
+ ('$ws', '$chooser', '{"auto_archive_completed": "muted", "auto_archive_on_comment": "all", "updates": "muted"}');
+ `)
+ if _, err := conn.Exec(ctx, seed); err != nil {
+ t.Fatalf("seed fixture: %v", err)
+ }
+
+ if _, err := conn.Exec(ctx, readMigrationFile(t, "718_auto_archive_prompt.up.sql")); err != nil {
+ t.Fatalf("apply 718 up: %v", err)
+ }
+
+ stored := func() map[string]map[string]string {
+ t.Helper()
+ rows, err := conn.Query(ctx, `SELECT workspace_id::text || '/' || user_id::text, preferences FROM notification_preference`)
+ if err != nil {
+ t.Fatalf("load preferences: %v", err)
+ }
+ defer rows.Close()
+ result := map[string]map[string]string{}
+ for rows.Next() {
+ var key string
+ var raw []byte
+ if err := rows.Scan(&key, &raw); err != nil {
+ t.Fatalf("scan preference: %v", err)
+ }
+ var prefs map[string]string
+ if err := json.Unmarshal(raw, &prefs); err != nil {
+ t.Fatalf("decode preference: %v", err)
+ }
+ result[key] = prefs
+ }
+ return result
+ }
+
+ got := stored()
+ want := map[string]map[string]string{
+ ws + "/" + archiver: {
+ "auto_archive_on_comment": "muted",
+ "auto_archive_on_status": "muted",
+ "auto_archive_on_assignee": "muted",
+ "auto_archive_prompt": "pending",
+ },
+ ws + "/" + chooser: {
+ "auto_archive_completed": "muted",
+ "auto_archive_on_comment": "all",
+ "auto_archive_on_status": "muted",
+ "auto_archive_on_assignee": "muted",
+ "auto_archive_prompt": "pending",
+ "updates": "muted",
+ },
+ }
+ if len(got) != len(want) {
+ t.Fatalf("preference rows = %v, want only %v", got, want)
+ }
+ for key, prefs := range want {
+ for k, v := range prefs {
+ if got[key][k] != v {
+ t.Errorf("%s %s = %q, want %q (row %v)", key, k, got[key][k], v, got[key])
+ }
+ }
+ if len(got[key]) != len(prefs) {
+ t.Errorf("%s = %v, want %v", key, got[key], prefs)
+ }
+ }
+
+ if _, err := conn.Exec(ctx, readMigrationFile(t, "718_auto_archive_prompt.down.sql")); err != nil {
+ t.Fatalf("apply 718 down: %v", err)
+ }
+ for key, prefs := range stored() {
+ if _, ok := prefs["auto_archive_prompt"]; ok {
+ t.Errorf("%s still has the prompt after down: %v", key, prefs)
+ }
+ }
+}
diff --git a/server/migrations/718_auto_archive_prompt.down.sql b/server/migrations/718_auto_archive_prompt.down.sql
new file mode 100644
index 0000000000..20a124f342
--- /dev/null
+++ b/server/migrations/718_auto_archive_prompt.down.sql
@@ -0,0 +1,5 @@
+-- The muted auto_archive_on_* keys stay: code before 718 ignores them, and they
+-- may already be a member's own choice.
+UPDATE notification_preference
+SET preferences = preferences - 'auto_archive_prompt'
+WHERE preferences ? 'auto_archive_prompt';
diff --git a/server/migrations/718_auto_archive_prompt.up.sql b/server/migrations/718_auto_archive_prompt.up.sql
new file mode 100644
index 0000000000..5a93e44d7f
--- /dev/null
+++ b/server/migrations/718_auto_archive_prompt.up.sql
@@ -0,0 +1,20 @@
+-- MUL-9788: replying, changing status and reassigning now archive your own
+-- notifications on an issue by default. Members who have archived notifications
+-- in a workspace keep working the way they do today: those three stay off and
+-- the auto_archive_prompt marker asks them once which behavior they want. Their
+-- existing auto_archive_completed setting is left alone, and a value they
+-- already stored wins over the ones written here.
+INSERT INTO notification_preference (workspace_id, user_id, preferences)
+SELECT m.workspace_id, m.user_id,
+ '{"auto_archive_on_comment": "muted", "auto_archive_on_status": "muted", "auto_archive_on_assignee": "muted", "auto_archive_prompt": "pending"}'::jsonb
+FROM member m
+WHERE EXISTS (
+ SELECT 1 FROM inbox_item i
+ WHERE i.workspace_id = m.workspace_id
+ AND i.recipient_type = 'member'
+ AND i.recipient_id = m.user_id
+ AND i.archived
+)
+ON CONFLICT (workspace_id, user_id) DO UPDATE
+SET preferences = EXCLUDED.preferences || notification_preference.preferences,
+ updated_at = now();
diff --git a/server/pkg/db/generated/notification_preference.sql.go b/server/pkg/db/generated/notification_preference.sql.go
index e2714faf7e..1fd0541d99 100644
--- a/server/pkg/db/generated/notification_preference.sql.go
+++ b/server/pkg/db/generated/notification_preference.sql.go
@@ -99,6 +99,26 @@ func (q *Queries) PatchNotificationPreference(ctx context.Context, arg PatchNoti
return i, err
}
+const resolveAutoArchivePrompt = `-- name: ResolveAutoArchivePrompt :exec
+UPDATE notification_preference
+SET preferences = (preferences - 'auto_archive_prompt') || $1::jsonb,
+ updated_at = now()
+WHERE user_id = $2
+ AND preferences ->> 'auto_archive_prompt' IS NOT NULL
+`
+
+type ResolveAutoArchivePromptParams struct {
+ Preferences []byte `json:"preferences"`
+ UserID pgtype.UUID `json:"user_id"`
+}
+
+// Answers the one-time auto-archive question in every workspace where the
+// user still has it pending: merges their choice and drops the marker.
+func (q *Queries) ResolveAutoArchivePrompt(ctx context.Context, arg ResolveAutoArchivePromptParams) error {
+ _, err := q.db.Exec(ctx, resolveAutoArchivePrompt, arg.Preferences, arg.UserID)
+ return 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 92b0091433..ff2675f917 100644
--- a/server/pkg/db/queries/notification_preference.sql
+++ b/server/pkg/db/queries/notification_preference.sql
@@ -18,6 +18,15 @@ DO UPDATE SET
updated_at = now()
RETURNING *;
+-- name: ResolveAutoArchivePrompt :exec
+-- Answers the one-time auto-archive question in every workspace where the
+-- user still has it pending: merges their choice and drops the marker.
+UPDATE notification_preference
+SET preferences = (preferences - 'auto_archive_prompt') || sqlc.arg('preferences')::jsonb,
+ updated_at = now()
+WHERE user_id = sqlc.arg('user_id')
+ AND preferences ->> 'auto_archive_prompt' IS NOT NULL;
+
-- name: ListNotificationPreferencesByUsers :many
SELECT * FROM notification_preference
WHERE workspace_id = $1 AND user_id = ANY(sqlc.arg('user_ids')::uuid[]);