Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
EDEN-20: add confirmed deletion of inbox entries (#10356)
happice4dc251a47d59
diff --git a/apps/mobile/data/realtime/use-inbox-realtime.test.ts b/apps/mobile/data/realtime/use-inbox-realtime.test.tsnew file mode 100644index 0000000000..ae0d04938f--- /dev/null+++ b/apps/mobile/data/realtime/use-inbox-realtime.test.ts@@ -0,0 +1,54 @@+// @vitest-environment node+import { QueryClient } from "@tanstack/react-query";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { inboxKeys } from "@/data/queries/inbox";+import { useInboxRealtime } from "./use-inbox-realtime";++interface MockWS {+ on: ReturnType<typeof vi.fn>;+ onReconnect: ReturnType<typeof vi.fn>;+}+type SubscriptionSetup = (ws: MockWS, wsId: string) => (() => void)[];+const state = vi.hoisted(() => ({+ qc: undefined as unknown as QueryClient,+ setup: undefined as unknown as SubscriptionSetup,+}));++vi.mock("@tanstack/react-query", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),+ useQueryClient: () => state.qc,+}));+vi.mock("@/lib/use-ws-subscriptions", () => ({+ useWSSubscriptions: (setup: SubscriptionSetup) => { state.setup = setup; },+}));+vi.mock("@/data/api", () => ({ api: {} }));++describe("mobile inbox realtime", () => {+ beforeEach(() => { state.qc = new QueryClient(); });++ it("refreshes both the list and unread summary on deletion from another client", async () => {+ const listKey = inboxKeys.list("workspace-1");+ const summaryKey = inboxKeys.unreadSummary();+ state.qc.setQueryData(listKey, [{ id: "notification-1" }]);+ state.qc.setQueryData(summaryKey, [{ workspace_id: "workspace-1", count: 1 }]);+ const handlers = new Map<string, () => void>();+ const ws: MockWS = {+ on: vi.fn((event: string, handler: () => void) => {+ handlers.set(event, handler);+ return () => handlers.delete(event);+ }),+ onReconnect: vi.fn(() => () => {}),+ };+ useInboxRealtime();+ const unsubs = state.setup(ws, "workspace-1");+ const deleted = handlers.get("inbox:deleted");+ expect(deleted).toBeDefined();+ deleted!();+ await vi.waitFor(() => {+ expect(state.qc.getQueryState(listKey)?.isInvalidated).toBe(true);+ expect(state.qc.getQueryState(summaryKey)?.isInvalidated).toBe(true);+ });+ for (const unsubscribe of unsubs) unsubscribe();+ expect(handlers.has("inbox:deleted")).toBe(false);+ });+});diff --git a/apps/mobile/data/realtime/use-inbox-realtime.ts b/apps/mobile/data/realtime/use-inbox-realtime.tsindex aa18618173..e428a50c3e 100644--- a/apps/mobile/data/realtime/use-inbox-realtime.ts+++ b/apps/mobile/data/realtime/use-inbox-realtime.ts@@ -60,6 +60,7 @@ export function useInboxRealtime() {// unarchive there restores the item to THIS list — without refetching,// mobile keeps showing the pre-restore list.ws.on("inbox:unarchived", invalidate),+ ws.on("inbox:deleted", invalidate),ws.on("inbox:batch-read", invalidate),ws.on("inbox:batch-archived", invalidate),diff --git a/e2e/inbox-delete.spec.ts b/e2e/inbox-delete.spec.tsnew file mode 100644index 0000000000..5e902a08c0--- /dev/null+++ b/e2e/inbox-delete.spec.ts@@ -0,0 +1,141 @@+import { test, expect } from "@playwright/test";+import pg from "pg";+import { TestApiClient } from "./fixtures";++test("delete a failed inbox entry with confirmation, retry, and cross-session refresh", async ({ page, context }, testInfo) => {+ test.setTimeout(120000);+ const consoleErrors: string[] = [];+ page.on("console", (message) => { if (message.type() === "error") consoleErrors.push(message.text()); });+ const api = new TestApiClient();+ const run = `${Date.now()}-${process.pid}`;+ const login = await api.login(`inbox-delete-${run}@localhost`, "Inbox deletion test");+ const workspace = await api.ensureWorkspace("Inbox deletion", `inbox-delete-${run}`);+ await api.markUserOnboarded();+ const db = new pg.Client(process.env.DATABASE_URL);+ await db.connect();+ try {+ const seeded = await db.query(+ `INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, type, title, body)+ VALUES ($1, 'member', $2, 'quick_create_failed', 'Failed test run', 'This failed test notification is no longer needed.'),+ ($1, 'member', $2, 'system', 'Keep this notification', 'Other notifications are not deleted.')+ RETURNING id`,+ [workspace.id, login.user.id],+ );+ const id = seeded.rows[0].id;+ await context.addInitScript((token) => {+ localStorage.setItem("multica_token", token!);+ localStorage.setItem("multica:chat:isOpen", "false");+ }, api.getToken());+ await page.setViewportSize({ width: 1280, height: 850 });+ await page.goto(`/${workspace.slug}/inbox`, { waitUntil: "domcontentloaded" });+ const row = page.locator('[data-mc="inbox-item"]').filter({ hasText: "Failed test run" });+ await expect(row).toBeVisible({ timeout: 60000 });+ const other = await context.newPage();+ await other.goto(`/${workspace.slug}/inbox`);+ const otherRow = other.locator('[data-mc="inbox-item"]').filter({ hasText: "Failed test run" });+ await expect(otherRow).toBeVisible();++ await row.click();+ await row.click({ button: "right" });+ await expect(page.getByRole("menuitem", { name: "Delete", exact: true })).toBeVisible();+ await page.screenshot({ path: testInfo.outputPath("inbox-delete-menu.png") });+ await page.getByRole("menuitem", { name: "Delete", exact: true }).click();+ const dialog = page.getByRole("alertdialog", { name: "Delete notification?" });+ await expect(dialog).toBeVisible();+ await expect(dialog).toHaveCSS("opacity", "1");+ await expect(page.getByRole("menuitem", { name: "Delete", exact: true })).not.toBeVisible();+ await page.screenshot({ path: testInfo.outputPath("inbox-delete-confirm.png") });+ await dialog.getByRole("button", { name: "Cancel" }).click();+ await expect(row).toBeVisible();+ expect((await db.query("SELECT id FROM inbox_item WHERE id = $1", [id])).rowCount).toBe(1);++ await row.click({ button: "right" });+ await page.getByRole("menuitem", { name: "Delete", exact: true }).click();+ const route = `**/api/inbox/${id}`;+ await page.route(route, async (request) => {+ if (request.request().method() === "DELETE") {+ await request.fulfill({ status: 500, contentType: "application/json", body: JSON.stringify({ error: "Test failure" }) });+ } else await request.continue();+ });+ await dialog.getByRole("button", { name: "Delete", exact: true }).click();+ await expect(dialog.getByRole("alert")).toContainText("Failed to delete notification");+ await expect(row).toBeVisible();+ await page.screenshot({ path: testInfo.outputPath("inbox-delete-retry.png") });+ await page.unroute(route);+ await dialog.getByRole("button", { name: "Delete", exact: true }).click();+ await expect(dialog).not.toBeVisible();+ await expect(row).toHaveCount(0);+ await expect(otherRow).toHaveCount(0);+ await expect(page.locator('[data-mc="inbox-item"]').filter({ hasText: "Keep this notification" })).toBeVisible();+ expect((await db.query("SELECT id FROM inbox_item WHERE id = $1", [id])).rowCount).toBe(0);+ await page.screenshot({ path: testInfo.outputPath("inbox-delete-after.png") });+ await page.reload();+ await expect(row).toHaveCount(0);+ await other.close();+ } finally {+ await testInfo.attach("console-errors", { body: consoleErrors.join("\n"), contentType: "text/plain" });+ await db.end();+ await api.deleteWorkspace();+ }+});++test("deleting active issue notifications restores archived history with explicit confirmation", async ({ page, context }, testInfo) => {+ test.setTimeout(120000);+ const api = new TestApiClient();+ const run = `${Date.now()}-${process.pid}`;+ const login = await api.login(`inbox-history-${run}@localhost`, "Inbox history test");+ const workspace = await api.ensureWorkspace("Inbox history", `inbox-history-${run}`);+ await api.markUserOnboarded();+ const issue = await api.createIssue("Issue with archived history");+ const db = new pg.Client(process.env.DATABASE_URL);+ await db.connect();+ try {+ const history = await db.query(+ `INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, issue_id, type, title, archived, created_at)+ VALUES ($1, 'member', $2, $3, 'task_failed', 'Issue with archived history', true, now() - interval '1 day') RETURNING id`,+ [workspace.id, login.user.id, issue.id],+ );+ const active = await db.query(+ `INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, issue_id, type, title)+ VALUES ($1, 'member', $2, $3, 'task_failed', 'Issue with archived history') RETURNING id`,+ [workspace.id, login.user.id, issue.id],+ );+ await context.addInitScript((token) => {+ localStorage.setItem("multica_token", token!);+ localStorage.setItem("multica:chat:isOpen", "false");+ }, api.getToken());+ await page.setViewportSize({ width: 1280, height: 850 });+ await page.goto(`/${workspace.slug}/inbox`, { waitUntil: "domcontentloaded" });+ const row = page.locator('[data-mc="inbox-item"]').filter({ hasText: "Issue with archived history" });+ await expect(row).toBeVisible({ timeout: 60000 });+ await row.click({ button: "right" });+ await page.getByRole("menuitem", { name: "Delete", exact: true }).click();+ const dialog = page.getByRole("alertdialog", { name: "Delete notification?" });+ await expect(dialog).toContainText("Previously archived notifications remain and will be visible again in Archived.");+ await expect(dialog).toHaveCSS("opacity", "1");+ await expect(page.getByRole("menuitem", { name: "Delete", exact: true })).not.toBeVisible();+ await page.screenshot({ path: testInfo.outputPath("inbox-delete-history-warning.png") });+ await dialog.getByRole("button", { name: "Delete", exact: true }).click();+ await expect(dialog).not.toBeVisible();+ await expect(row).toHaveCount(0);+ expect((await db.query("SELECT id FROM inbox_item WHERE id = $1", [active.rows[0].id])).rowCount).toBe(0);+ expect((await db.query("SELECT id FROM inbox_item WHERE id = $1", [history.rows[0].id])).rowCount).toBe(1);++ await page.getByRole("button", { name: "Inbox", exact: true }).click();+ await page.getByRole("menuitemradio", { name: "Archived", exact: true }).click();+ await expect(row).toBeVisible();+ await page.screenshot({ path: testInfo.outputPath("inbox-delete-retained-archive.png") });+ await row.click({ button: "right" });+ await page.getByRole("menuitem", { name: "Delete", exact: true }).click();+ await expect(dialog).not.toContainText("Previously archived notifications");+ await dialog.getByRole("button", { name: "Delete", exact: true }).click();+ await expect(dialog).not.toBeVisible();+ await expect(row).toHaveCount(0);+ expect((await db.query("SELECT id FROM inbox_item WHERE id = $1", [history.rows[0].id])).rowCount).toBe(0);+ expect((await db.query("SELECT id FROM issue WHERE id = $1", [issue.id])).rowCount).toBe(1);+ } finally {+ await db.end();+ await api.cleanup();+ await api.deleteWorkspace();+ }+});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 04b9c6812d..7bbd7cf1af 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -471,6 +471,7 @@ import {SubscribedIssueIdsSchema,InvolvedSquadIdsSchema,IssueInboxReadSchema,+ InboxDeleteSchema,InboxItemListSchema,ArchivedInboxPageSchema,ArchivedInboxFacetsSchema,@@ -3133,6 +3134,13 @@ export class ApiClient {return this.fetch(`/api/inbox/${id}/archive`, { method: "POST" });}+ async deleteInbox(id: string): Promise<{ count: number | null }> {+ const raw = await this.fetch<unknown>(`/api/inbox/${id}`, { method: "DELETE" });+ return parseWithFallback<{ count: number | null }>(raw, InboxDeleteSchema, { count: null }, {+ endpoint: "DELETE /api/inbox/{id}",+ });+ }+// Archived notifications, backing the inbox's "Archived" sub-view. Capped// server-side (no pagination in v1). Schema-guarded so a contract drift// renders an empty archive instead of taking the inbox down with it.diff --git a/packages/core/api/delete-inbox.test.ts b/packages/core/api/delete-inbox.test.tsnew file mode 100644index 0000000000..1657dc0c5d--- /dev/null+++ b/packages/core/api/delete-inbox.test.ts@@ -0,0 +1,26 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from "vitest";+import { ApiClient } from "./client";++afterEach(() => vi.unstubAllGlobals());++describe("deleteInbox", () => {+ it("deletes the selected entry and parses the confirmed count", async () => {+ const fetch = vi.fn().mockResolvedValue(Response.json({ count: 2 }));+ vi.stubGlobal("fetch", fetch);+ await expect(new ApiClient("https://api.example.test").deleteInbox("item-1")).resolves.toEqual({ count: 2 });+ const [url, init] = fetch.mock.calls[0]!;+ expect(new URL(url).pathname).toBe("/api/inbox/item-1");+ expect(init.method).toBe("DELETE");+ });++ it.each([null, {}, { count: "2" }, { count: -1 }, { count: 0.5 }])("treats a malformed response as an unknown count: %j", async (body) => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json(body)));+ await expect(new ApiClient("https://api.example.test").deleteInbox("item-1")).resolves.toEqual({ count: null });+ });++ it("rejects a failed deletion", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ error: "not found" }, { status: 404 })));+ await expect(new ApiClient("https://api.example.test").deleteInbox("item-1")).rejects.toThrow();+ });+});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 9f8969fd75..4948957266 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -3095,6 +3095,11 @@ export const IssueInboxReadSchema = z}).loose();+// Deletion returns the number of notifications removed from the selected view.+export const InboxDeleteSchema = z+ .object({ count: z.number().int().nonnegative() })+ .loose();+// The viewer's subscribed issue ids (`/api/issues/subscribed` GET), behind the// "subscribed" relation filter on client-filtered surfaces. A non-string entry// is dropped; a body without the list has no safe fallback — an empty setdiff --git a/packages/core/inbox/mutations.test.tsx b/packages/core/inbox/mutations.test.tsxindex d0d49cd894..3ca0d260a3 100644--- a/packages/core/inbox/mutations.test.tsx+++ b/packages/core/inbox/mutations.test.tsx@@ -9,7 +9,7 @@ import type { ReactNode } from "react";import { setApiInstance } from "../api";import type { ApiClient } from "../api/client";import type { InboxItem, InboxWorkspaceUnread } from "../types";-import { useMarkInboxRead, useMarkInboxUnread, useMarkIssueInboxRead, useUnarchiveInbox } from "./mutations";+import { useDeleteInbox, useMarkInboxRead, useMarkInboxUnread, useMarkIssueInboxRead, useUnarchiveInbox } from "./mutations";import { inboxKeys, useInboxUnreadCount } from "./queries";import { onInboxSummaryInvalidate } from "./ws-updaters";import { createQueryClient } from "../query-client";@@ -65,6 +65,39 @@ function summaryCount(qc: QueryClient) {return summary?.find((e) => e.workspace_id === WORKSPACE_ID)?.count;}+describe("useDeleteInbox", () => {+ it("does not remove cached rows before confirmation and refreshes both views and unread summary on success", async () => {+ const qc = createQueryClient();+ let confirm!: () => void;+ setApiInstance({ deleteInbox: vi.fn(() => new Promise<{ count: number }>((resolve) => {+ confirm = () => resolve({ count: 1 });+ })) } as unknown as ApiClient);+ const keys = [inboxKeys.list(WORKSPACE_ID), inboxKeys.archived(WORKSPACE_ID), inboxKeys.unreadSummary()];+ for (const key of keys) qc.setQueryData(key, [item()]);+ const { result } = renderHook(() => useDeleteInbox(), { wrapper: createWrapper(qc) });+ act(() => result.current.mutate("inbox-1"));+ await waitFor(() => expect(result.current.isPending).toBe(true));+ expect(archivedCache(qc)).toHaveLength(1);+ expect(listCache(qc)).toHaveLength(1);+ await act(async () => confirm());+ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ await waitFor(() => {+ for (const key of keys) expect(qc.getQueryState(key)?.isInvalidated).toBe(true);+ });+ });++ it("keeps caches untouched on failure", async () => {+ const qc = createQueryClient();+ setApiInstance({ deleteInbox: vi.fn().mockRejectedValue(new Error("offline")) } as unknown as ApiClient);+ qc.setQueryData(inboxKeys.list(WORKSPACE_ID), [item()]);+ const { result } = renderHook(() => useDeleteInbox(), { wrapper: createWrapper(qc) });+ act(() => result.current.mutate("inbox-1"));+ await waitFor(() => expect(result.current.isError).toBe(true));+ expect(listCache(qc)).toHaveLength(1);+ expect(qc.getQueryState(inboxKeys.list(WORKSPACE_ID))?.isInvalidated).toBe(false);+ });+});+describe("useMarkInboxRead", () => {let queryClient: QueryClient;diff --git a/packages/core/inbox/mutations.ts b/packages/core/inbox/mutations.tsindex 6774510512..72d3d3160e 100644--- a/packages/core/inbox/mutations.ts+++ b/packages/core/inbox/mutations.ts@@ -170,6 +170,16 @@ export function useArchiveInbox() {});}+export function useDeleteInbox() {+ const qc = useQueryClient();+ const wsId = useWorkspaceId();+ return useMutation({+ mutationFn: (id: string) => api.deleteInbox(id),+ // Deletion is not optimistic: keep the row and selection on failure.+ onSuccess: () => refreshInboxAfterWrite(qc, wsId),+ });+}+/*** Restore an archived notification to the main inbox.*diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex 6a818bd85d..56661d82dc 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -39,6 +39,7 @@ export type WSEventType =| "inbox:unread"| "inbox:archived"| "inbox:unarchived"+ | "inbox:deleted"| "inbox:batch-read"| "inbox:batch-archived"| "workspace:updated"@@ -681,6 +682,7 @@ export interface WSEventPayloadMap {"inbox:unread": InboxUnreadPayload;"inbox:archived": InboxArchivedPayload;"inbox:unarchived": InboxUnarchivedPayload;+ "inbox:deleted": { item_id: string; recipient_id: string; count: number };"inbox:batch-read": InboxBatchReadPayload;"inbox:batch-archived": InboxBatchArchivedPayload;"workspace:updated": WorkspaceUpdatedPayload;diff --git a/packages/views/inbox/components/inbox-context-menu.test.tsx b/packages/views/inbox/components/inbox-context-menu.test.tsxindex 2e0f44e4df..06bada0442 100644--- a/packages/views/inbox/components/inbox-context-menu.test.tsx+++ b/packages/views/inbox/components/inbox-context-menu.test.tsx@@ -95,6 +95,7 @@ function renderRow({onMarkRead: vi.fn(),onMarkUnread: vi.fn(),onAction: vi.fn(),+ onDelete: vi.fn(),...actions,};render(@@ -116,6 +117,13 @@ function renderRow({}describe("inbox row context menu", () => {+ it.each(["inbox", "archived"] as const)("offers deletion in the %s view", async (view) => {+ const onDelete = vi.fn();+ const { row } = renderRow({ view, actions: { onDelete } });+ fireEvent.contextMenu(row);+ fireEvent.click(await screen.findByText("Delete"));+ expect(onDelete).toHaveBeenCalledWith("inbox-1");+ });it("offers mark-as-unread on a read row and reports the item id", async () => {const onMarkUnread = vi.fn();const { row } = renderRow({@@ -200,6 +208,13 @@ describe("inbox row context menu", () => {// A touch pointer has neither hover nor right-click, so the row's compact menu// is the only way in. It must therefore offer what right-click offers.describe("inbox row compact menu", () => {+ it("offers deletion without selecting the row", async () => {+ const onDelete = vi.fn();+ renderRow({ actions: { onDelete } });+ fireEvent.click(screen.getByRole("button", { name: "Notification actions" }));+ fireEvent.click(await screen.findByText("Delete"));+ expect(onDelete).toHaveBeenCalledWith("inbox-1");+ });const openMenu = () =>fireEvent.click(screen.getByRole("button", { name: "Notification actions" }));@@ -251,7 +266,7 @@ describe("inbox row compact menu", () => {wrap(<InboxContextMenuProviderview="inbox"- actions={{ onMarkRead: vi.fn(), onMarkUnread: vi.fn(), onAction: vi.fn() }}+ actions={{ onMarkRead: vi.fn(), onMarkUnread: vi.fn(), onAction: vi.fn(), onDelete: vi.fn() }}><InboxListItemitem={item()}diff --git a/packages/views/inbox/components/inbox-context-menu.tsx b/packages/views/inbox/components/inbox-context-menu.tsxindex 8c05f9f7db..d42c0ac5a6 100644--- a/packages/views/inbox/components/inbox-context-menu.tsx+++ b/packages/views/inbox/components/inbox-context-menu.tsx@@ -159,7 +159,11 @@ function InboxContextMenuSingleton({<Fragment key={group[0]?.key ?? index}>{index > 0 && <ContextMenuSeparator />}{group.map((action) => (- <ContextMenuItem key={action.key} onClick={action.onSelect}>+ <ContextMenuItem+ key={action.key}+ variant={action.danger ? "destructive" : "default"}+ onClick={action.onSelect}+ >{action.icon}{action.label}</ContextMenuItem>diff --git a/packages/views/inbox/components/inbox-delete-dialog.test.tsx b/packages/views/inbox/components/inbox-delete-dialog.test.tsxnew file mode 100644index 0000000000..d6bc787c51--- /dev/null+++ b/packages/views/inbox/components/inbox-delete-dialog.test.tsx@@ -0,0 +1,83 @@+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { I18nProvider } from "@multica/core/i18n/react";+import { setApiInstance } from "@multica/core/api";+import type { ApiClient } from "@multica/core/api/client";+import type { InboxItem } from "@multica/core/types";+import enInbox from "../../locales/en/inbox.json";+import { InboxDeleteDialog } from "./inbox-delete-dialog";+import type { InboxView } from "./inbox-view";++vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));++const entry = { id: "notification-1", title: "Create with agent failed", issue_id: null } as InboxItem;+function setup(remove = vi.fn(async () => ({ count: 1 })), issueId: string | null = null, view: InboxView = "inbox") {+ setApiInstance({ deleteInbox: remove } as unknown as ApiClient);+ const onClose = vi.fn();+ const onDeleted = vi.fn();+ const qc = new QueryClient({ defaultOptions: { mutations: { retry: false } } });+ render(+ <QueryClientProvider client={qc}>+ <I18nProvider locale="en" resources={{ en: { inbox: enInbox } }}>+ <InboxDeleteDialog item={{ ...entry, issue_id: issueId }} view={view} onClose={onClose} onDeleted={onDeleted} />+ </I18nProvider>+ </QueryClientProvider>,+ );+ return { remove, onClose, onDeleted };+}++describe("inbox deletion confirmation", () => {+ it("cancels without deleting", () => {+ const { remove, onClose, onDeleted } = setup();+ expect(screen.getByRole("alertdialog")).toHaveAccessibleName("Delete notification?");+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ expect(onClose).toHaveBeenCalledOnce();+ expect(remove).not.toHaveBeenCalled();+ expect(onDeleted).not.toHaveBeenCalled();+ });++ it("keeps the dialog and selection until the server confirms, blocking repeated clicks", async () => {+ let resolve!: (value: { count: number }) => void;+ const remove = vi.fn(() => new Promise<{ count: number }>((done) => { resolve = done; }));+ const { onClose, onDeleted } = setup(remove);+ fireEvent.click(screen.getByRole("button", { name: "Delete" }));+ await waitFor(() => expect(remove).toHaveBeenCalledWith("notification-1"));+ expect(screen.getByRole("button", { name: "Delete" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "Cancel" })).toBeDisabled();+ expect(onClose).not.toHaveBeenCalled();+ expect(onDeleted).not.toHaveBeenCalled();+ await act(async () => resolve({ count: 1 }));+ await waitFor(() => expect(onDeleted).toHaveBeenCalledWith("notification-1"));+ expect(onClose).toHaveBeenCalledOnce();+ });++ it("shows a retryable error without closing or moving selection", async () => {+ const remove = vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce({ count: 1 });+ const { onClose, onDeleted } = setup(remove);+ fireEvent.click(screen.getByRole("button", { name: "Delete" }));+ expect(await screen.findByRole("alert")).toHaveTextContent("Failed to delete notification. Try again.");+ expect(onClose).not.toHaveBeenCalled();+ expect(onDeleted).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Delete" }));+ await waitFor(() => expect(onDeleted).toHaveBeenCalledWith("notification-1"));+ expect(remove).toHaveBeenCalledTimes(2);+ });++ it("explains that deleting active issue notifications makes old archived history visible again", () => {+ setup(undefined, "issue-1", "inbox");+ expect(screen.getByRole("alertdialog")).toHaveTextContent("Previously archived notifications remain and will be visible again in Archived.");+ });++ it("explains the archived group scope without promising to retain the deleted history", () => {+ setup(undefined, "issue-1", "archived");+ expect(screen.getByText(enInbox.delete_dialog.issue_description)).toBeInTheDocument();+ expect(screen.getByRole("alertdialog")).not.toHaveTextContent("Previously archived notifications");+ });++ it("does not mention archived history for an issue-less active notification", () => {+ setup();+ expect(screen.getByText(enInbox.delete_dialog.description)).toBeInTheDocument();+ expect(screen.getByRole("alertdialog")).not.toHaveTextContent("Previously archived notifications");+ });+});diff --git a/packages/views/inbox/components/inbox-delete-dialog.tsx b/packages/views/inbox/components/inbox-delete-dialog.tsxnew file mode 100644index 0000000000..592c80f103--- /dev/null+++ b/packages/views/inbox/components/inbox-delete-dialog.tsx@@ -0,0 +1,83 @@+"use client";++import { useState } from "react";+import type { InboxItem } from "@multica/core/types";+import { useDeleteInbox } from "@multica/core/inbox/mutations";+import {+ AlertDialog,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@multica/ui/components/ui/alert-dialog";+import { Button } from "@multica/ui/components/ui/button";+import { useT } from "../../i18n";+import type { InboxView } from "./inbox-view";++export function InboxDeleteDialog({+ item,+ view,+ onClose,+ onDeleted,+}: {+ item: InboxItem;+ view: InboxView;+ onClose: () => void;+ onDeleted: (id: string) => void;+}) {+ const { t } = useT("inbox");+ const mutation = useDeleteInbox();+ const [failed, setFailed] = useState(false);++ const confirm = async () => {+ setFailed(false);+ try {+ await mutation.mutateAsync(item.id);+ onDeleted(item.id);+ onClose();+ } catch {+ setFailed(true);+ }+ };++ return (+ <AlertDialog+ open+ onOpenChange={(open) => {+ if (!open && !mutation.isPending) onClose();+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>{t(($) => $.delete_dialog.title)}</AlertDialogTitle>+ <AlertDialogDescription>+ {item.issue_id+ ? view === "inbox"+ ? t(($) => $.delete_dialog.active_issue_description)+ : t(($) => $.delete_dialog.issue_description)+ : t(($) => $.delete_dialog.description)}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <p className="text-body font-medium wrap-anywhere">{item.title}</p>+ {failed && (+ <p role="alert" className="text-body text-destructive">+ {t(($) => $.errors.delete_failed)}+ </p>+ )}+ <AlertDialogFooter>+ <AlertDialogCancel disabled={mutation.isPending}>{t(($) => $.delete_dialog.cancel)}</AlertDialogCancel>+ <Button+ variant="destructive"+ disabled={mutation.isPending}+ aria-busy={mutation.isPending}+ onClick={confirm}+ >+ {t(($) => $.context_menu.delete)}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/packages/views/inbox/components/inbox-item-actions.tsx b/packages/views/inbox/components/inbox-item-actions.tsxindex f7bcf6f58f..5f4dcf2400 100644--- a/packages/views/inbox/components/inbox-item-actions.tsx+++ b/packages/views/inbox/components/inbox-item-actions.tsx@@ -1,6 +1,6 @@"use client";-import { Archive, ArchiveRestore, Check, CircleDot, ExternalLink } from "@multica/ui/icons";+import { Archive, ArchiveRestore, Check, CircleDot, ExternalLink, Trash2 } from "@multica/ui/icons";import { paths, useWorkspaceSlug } from "@multica/core/paths";import type { InboxItem } from "@multica/core/types";import type { RowActionItem } from "../../common/row-actions-menu";@@ -17,6 +17,7 @@ export interface InboxRowActions {* reversal-of-the-current-view the row's inline button performs.*/onAction: (id: string) => void;+ onDelete: (id: string) => void;}/**@@ -100,5 +101,15 @@ export function useInboxItemActions(},]);+ groups.push([+ {+ key: "delete",+ label: t(($) => $.context_menu.delete),+ icon: <Trash2 className="h-4 w-4" />,+ danger: true,+ onSelect: () => actions.onDelete(item.id),+ },+ ]);+return groups;}diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex 408d988631..e676e3b98c 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -97,6 +97,7 @@ import { cn } from "@multica/ui/lib/utils";import { CollapsedNavTrigger, PAGE_GUTTER, PageHeader } from "../../layout/page-header";import { PanelHeader } from "../../layout/panel-nav";import { useListColumnCollapsed } from "../../layout/app-shell-context";+import { InboxDeleteDialog } from "./inbox-delete-dialog";import { ListColumn } from "../../layout/list-column";import { useTimeAgo } from "./inbox-list-item";import { InboxList } from "./inbox-list";@@ -377,6 +378,7 @@ export function InboxPage() {const unreadCount = useInboxUnreadCount(wsId);const markReadMutation = useMarkInboxRead();+ const [deleteTarget, setDeleteTarget] = useState<InboxItem | null>(null);const markUnreadMutation = useMarkInboxUnread();const archiveMutation = useArchiveInbox();const unarchiveMutation = useUnarchiveInbox();@@ -779,6 +781,7 @@ export function InboxPage() {onMarkRead: handleMarkRead,onMarkUnread: handleMarkUnread,onAction: isArchivedView ? handleUnarchive : handleArchive,+ onDelete: (id) => setDeleteTarget(selectionItems.find((item) => item.id === id) ?? null),}}><InboxList@@ -807,6 +810,18 @@ export function InboxPage() {) : undefined}/>+ {deleteTarget && (+ <InboxDeleteDialog+ key={deleteTarget.id}+ item={deleteTarget}+ view={view}+ onClose={() => setDeleteTarget(null)}+ onDeleted={(id) => {+ advanceSelectionPast(id, selectionItems);+ toast.success(t(($) => $.toasts.deleted));+ }}+ />+ )}</InboxContextMenuProvider>);diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.jsonindex 74fda6318b..f39e51e7e6 100644--- a/packages/views/locales/en/inbox.json+++ b/packages/views/locales/en/inbox.json@@ -41,7 +41,8 @@"mark_unread": "Mark as unread","archive": "Archive","unarchive": "Unarchive",- "open_in_new_tab": "Open in new tab"+ "open_in_new_tab": "Open in new tab",+ "delete": "Delete"},"list": {"loading_selection": "Loading notification…",@@ -120,7 +121,8 @@"toasts": {"source_context_retry_started": "Retry started with the original context","archived": "Notification archived",- "unarchived": "Notification restored"+ "unarchived": "Notification restored",+ "deleted": "Notification deleted"},"errors": {"archived_lookup_failed": "Failed to load the linked notification",@@ -136,6 +138,14 @@"archive_completed_failed": "Failed to archive completed","unarchive_failed": "Failed to unarchive","archived_load_failed": "Failed to load archived notifications",- "filters_load_failed": "Could not load filters"+ "filters_load_failed": "Could not load filters",+ "delete_failed": "Failed to delete notification. Try again."+ },+ "delete_dialog": {+ "title": "Delete notification?",+ "description": "This permanently deletes this notification. Related issues and runs are kept.",+ "issue_description": "This permanently deletes the notifications for this issue in this view. The issue and its runs are kept.",+ "cancel": "Cancel",+ "active_issue_description": "This permanently deletes the active notifications for this issue. Previously archived notifications remain and will be visible again in Archived. The issue and its runs are kept."}}diff --git a/packages/views/locales/es/inbox.json b/packages/views/locales/es/inbox.jsonindex 2dbc65f457..08772f113f 100644--- a/packages/views/locales/es/inbox.json+++ b/packages/views/locales/es/inbox.json@@ -41,7 +41,8 @@"mark_unread": "Marcar como no leído","archive": "Archivar","unarchive": "Desarchivar",- "open_in_new_tab": "Abrir en una pestaña nueva"+ "open_in_new_tab": "Abrir en una pestaña nueva",+ "delete": "Eliminar"},"list": {"loading_selection": "Cargando notificación…",@@ -120,7 +121,8 @@"toasts": {"source_context_retry_started": "Reintento iniciado con el contexto original","archived": "Notificación archivada",- "unarchived": "Notificación restaurada"+ "unarchived": "Notificación restaurada",+ "deleted": "Notificación eliminada"},"errors": {"archived_lookup_failed": "No se ha podido cargar la notificación enlazada",@@ -136,6 +138,14 @@"archive_completed_failed": "No se ha podido archivar lo completado","unarchive_failed": "No se ha podido desarchivar","archived_load_failed": "No se han podido cargar las notificaciones archivadas",- "filters_load_failed": "No se han podido cargar los filtros"+ "filters_load_failed": "No se han podido cargar los filtros",+ "delete_failed": "No se pudo eliminar la notificación. Inténtalo de nuevo."+ },+ "delete_dialog": {+ "title": "¿Eliminar notificación?",+ "description": "Esta notificación se eliminará permanentemente. Las tareas y ejecuciones relacionadas se conservarán.",+ "issue_description": "Las notificaciones de esta tarea en esta vista se eliminarán permanentemente. La tarea y sus ejecuciones se conservarán.",+ "cancel": "Cancelar",+ "active_issue_description": "Las notificaciones activas de esta tarea se eliminarán permanentemente. Las notificaciones archivadas anteriormente se conservarán y volverán a aparecer en Archivadas. La tarea y sus ejecuciones se conservarán."}}diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.jsonindex fe0ce2e087..9b888fe750 100644--- a/packages/views/locales/fr/inbox.json+++ b/packages/views/locales/fr/inbox.json@@ -41,7 +41,8 @@"mark_unread": "Marquer comme non lu","archive": "Archiver","unarchive": "Désarchiver",- "open_in_new_tab": "Ouvrir dans un nouvel onglet"+ "open_in_new_tab": "Ouvrir dans un nouvel onglet",+ "delete": "Supprimer"},"list": {"loading_selection": "Chargement de la notification…",@@ -120,7 +121,8 @@"toasts": {"source_context_retry_started": "Nouvelle tentative démarrée avec le contexte d'origine","archived": "Notification archivée",- "unarchived": "Notification restaurée"+ "unarchived": "Notification restaurée",+ "deleted": "Notification supprimée"},"errors": {"archived_lookup_failed": "Échec du chargement de la notification liée",@@ -136,6 +138,14 @@"archive_completed_failed": "Échec de l'archivage des éléments terminés","unarchive_failed": "Échec du désarchivage","archived_load_failed": "Échec du chargement des notifications archivées",- "filters_load_failed": "Impossible de charger les filtres"+ "filters_load_failed": "Impossible de charger les filtres",+ "delete_failed": "Impossible de supprimer la notification. Réessayez."+ },+ "delete_dialog": {+ "title": "Supprimer la notification ?",+ "description": "Cette notification sera supprimée définitivement. Les tâches et exécutions associées seront conservées.",+ "issue_description": "Les notifications de cette tâche dans cette vue seront supprimées définitivement. La tâche et ses exécutions seront conservées.",+ "cancel": "Annuler",+ "active_issue_description": "Les notifications actives de cette tâche seront supprimées définitivement. Les notifications précédemment archivées seront conservées et réapparaîtront dans les archives. La tâche et ses exécutions seront conservées."}}diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.jsonindex 3e26e6622d..e2751b2d95 100644--- a/packages/views/locales/ja/inbox.json+++ b/packages/views/locales/ja/inbox.json@@ -39,7 +39,8 @@"mark_unread": "未読にする","archive": "アーカイブ","unarchive": "アーカイブ解除",- "open_in_new_tab": "新しいタブで開く"+ "open_in_new_tab": "新しいタブで開く",+ "delete": "削除"},"list": {"loading_selection": "通知を読み込み中…",@@ -118,7 +119,8 @@"toasts": {"source_context_retry_started": "元のコンテキストで再試行を開始しました","archived": "通知をアーカイブしました",- "unarchived": "通知を元に戻しました"+ "unarchived": "通知を元に戻しました",+ "deleted": "通知を削除しました"},"errors": {"archived_lookup_failed": "リンク先の通知を読み込めませんでした",@@ -134,6 +136,14 @@"archive_completed_failed": "完了した項目をアーカイブできませんでした","unarchive_failed": "アーカイブ解除に失敗しました","archived_load_failed": "アーカイブ済み通知を読み込めませんでした",- "filters_load_failed": "フィルターを読み込めませんでした"+ "filters_load_failed": "フィルターを読み込めませんでした",+ "delete_failed": "通知を削除できませんでした。もう一度お試しください。"+ },+ "delete_dialog": {+ "title": "通知を削除しますか?",+ "description": "この通知は完全に削除されます。関連するタスクと実行記録は残ります。",+ "issue_description": "このビューにあるこのタスクの通知は完全に削除されます。タスクと実行記録は残ります。",+ "cancel": "キャンセル",+ "active_issue_description": "このタスクの受信トレイ内の通知は完全に削除されます。以前アーカイブした通知は残り、アーカイブに再表示されます。タスクと実行記録は残ります。"}}diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.jsonindex b732e379fb..91865f7b4a 100644--- a/packages/views/locales/ko/inbox.json+++ b/packages/views/locales/ko/inbox.json@@ -39,7 +39,8 @@"mark_unread": "읽지 않음으로 표시","archive": "보관","unarchive": "보관 해제",- "open_in_new_tab": "새 탭에서 열기"+ "open_in_new_tab": "새 탭에서 열기",+ "delete": "삭제"},"list": {"loading_selection": "알림을 불러오는 중…",@@ -118,7 +119,8 @@"toasts": {"source_context_retry_started": "원본 컨텍스트로 재시도를 시작했습니다","archived": "알림을 보관했습니다",- "unarchived": "알림을 복원했습니다"+ "unarchived": "알림을 복원했습니다",+ "deleted": "알림이 삭제되었습니다"},"errors": {"archived_lookup_failed": "링크된 알림을 불러오지 못했습니다",@@ -134,6 +136,14 @@"archive_completed_failed": "완료된 항목을 보관하지 못했습니다","unarchive_failed": "보관 해제에 실패했습니다","archived_load_failed": "보관된 알림을 불러오지 못했습니다",- "filters_load_failed": "필터를 불러올 수 없습니다"+ "filters_load_failed": "필터를 불러올 수 없습니다",+ "delete_failed": "알림을 삭제하지 못했습니다. 다시 시도해 주세요."+ },+ "delete_dialog": {+ "title": "알림을 삭제할까요?",+ "description": "이 알림은 영구적으로 삭제됩니다. 관련 작업과 실행 기록은 유지됩니다.",+ "issue_description": "이 보기에서 해당 작업의 알림이 영구적으로 삭제됩니다. 작업과 실행 기록은 유지됩니다.",+ "cancel": "취소",+ "active_issue_description": "이 작업의 받은편지함 알림은 영구적으로 삭제됩니다. 이전에 보관한 알림은 유지되며 보관함에 다시 표시됩니다. 작업과 실행 기록은 유지됩니다."}}diff --git a/packages/views/locales/ru/inbox.json b/packages/views/locales/ru/inbox.jsonindex a0e0e53322..d71f252454 100644--- a/packages/views/locales/ru/inbox.json+++ b/packages/views/locales/ru/inbox.json@@ -45,7 +45,8 @@"mark_unread": "Отметить как непрочитанное","archive": "Архивировать","unarchive": "Восстановить из архива",- "open_in_new_tab": "Открыть в новой вкладке"+ "open_in_new_tab": "Открыть в новой вкладке",+ "delete": "Удалить"},"list": {"loading_selection": "Загрузка уведомления…",@@ -124,7 +125,8 @@"toasts": {"source_context_retry_started": "Повтор запущен с исходным контекстом","archived": "Уведомление архивировано",- "unarchived": "Уведомление восстановлено"+ "unarchived": "Уведомление восстановлено",+ "deleted": "Уведомление удалено"},"errors": {"archived_lookup_failed": "Не удалось загрузить связанное уведомление",@@ -140,6 +142,14 @@"archive_completed_failed": "Не удалось архивировать завершённые","unarchive_failed": "Не удалось восстановить из архива","archived_load_failed": "Не удалось загрузить архивные уведомления",- "filters_load_failed": "Не удалось загрузить фильтры"+ "filters_load_failed": "Не удалось загрузить фильтры",+ "delete_failed": "Не удалось удалить уведомление. Попробуйте снова."+ },+ "delete_dialog": {+ "title": "Удалить уведомление?",+ "description": "Уведомление будет удалено навсегда. Связанные задачи и запуски сохранятся.",+ "issue_description": "Уведомления этой задачи в текущем представлении будут удалены навсегда. Задача и её запуски сохранятся.",+ "cancel": "Отмена",+ "active_issue_description": "Активные уведомления этой задачи будут удалены навсегда. Ранее архивированные уведомления сохранятся и снова появятся в архиве. Задача и её запуски сохранятся."}}diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.jsonindex edd833baec..b80d37e7b7 100644--- a/packages/views/locales/zh-Hans/inbox.json+++ b/packages/views/locales/zh-Hans/inbox.json@@ -39,7 +39,8 @@"mark_unread": "标为未读","archive": "归档","unarchive": "取消归档",- "open_in_new_tab": "在新标签页打开"+ "open_in_new_tab": "在新标签页打开",+ "delete": "删除"},"list": {"loading_selection": "正在加载通知…",@@ -118,7 +119,8 @@"toasts": {"source_context_retry_started": "已使用原始上下文开始重试","archived": "已归档通知",- "unarchived": "已恢复通知"+ "unarchived": "已恢复通知",+ "deleted": "通知已删除"},"errors": {"archived_lookup_failed": "无法加载链接指向的通知",@@ -134,6 +136,14 @@"archive_completed_failed": "归档已完成失败","unarchive_failed": "取消归档失败","archived_load_failed": "无法加载已归档通知",- "filters_load_failed": "无法加载筛选项"+ "filters_load_failed": "无法加载筛选项",+ "delete_failed": "无法删除通知,请重试。"+ },+ "delete_dialog": {+ "title": "删除通知?",+ "description": "此通知将被永久删除,关联任务和运行记录不受影响。",+ "issue_description": "当前视图中此任务的通知将被永久删除,任务和运行记录不受影响。",+ "cancel": "取消",+ "active_issue_description": "此任务在收件箱中的通知将被永久删除。此前归档的通知会保留,并重新显示在归档视图中。任务和运行记录不受影响。"}}diff --git a/packages/views/locales/zh-Hant/inbox.json b/packages/views/locales/zh-Hant/inbox.jsonindex cc70b47927..6c5bd9b2fa 100644--- a/packages/views/locales/zh-Hant/inbox.json+++ b/packages/views/locales/zh-Hant/inbox.json@@ -39,7 +39,8 @@"mark_unread": "標為未讀","archive": "歸檔","unarchive": "取消歸檔",- "open_in_new_tab": "在新標籤頁開啟"+ "open_in_new_tab": "在新標籤頁開啟",+ "delete": "刪除"},"list": {"loading_selection": "正在載入通知…",@@ -118,7 +119,8 @@"toasts": {"source_context_retry_started": "已使用原始上下文開始重試","archived": "已歸檔通知",- "unarchived": "已恢復通知"+ "unarchived": "已恢復通知",+ "deleted": "通知已刪除"},"errors": {"archived_lookup_failed": "無法載入連結指向的通知",@@ -134,6 +136,14 @@"archive_completed_failed": "歸檔已完成失敗","unarchive_failed": "取消歸檔失敗","archived_load_failed": "無法載入已歸檔通知",- "filters_load_failed": "無法載入篩選項"+ "filters_load_failed": "無法載入篩選項",+ "delete_failed": "無法刪除通知,請重試。"+ },+ "delete_dialog": {+ "title": "刪除通知?",+ "description": "此通知將被永久刪除,相關任務和執行記錄不受影響。",+ "issue_description": "目前檢視中此任務的通知將被永久刪除,任務和執行記錄不受影響。",+ "cancel": "取消",+ "active_issue_description": "此任務在收件箱中的通知將被永久刪除。先前歸檔的通知會保留,並重新顯示在已歸檔檢視中。任務和執行記錄不受影響。"}}diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.goindex 3c61af80fc..5bf71e4b3d 100644--- a/server/cmd/server/listeners.go+++ b/server/cmd/server/listeners.go@@ -114,6 +114,7 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster, audience ...privprotocol.EventInboxRead: true,protocol.EventInboxArchived: true,protocol.EventInboxUnarchived: true,+ protocol.EventInboxDeleted: true,protocol.EventInboxBatchRead: true,protocol.EventInboxBatchArchived: true,protocol.EventInvitationCreated: true,@@ -153,6 +154,7 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster, audience ...priv// top-level payloadfor _, eventType := range []string{protocol.EventInboxRead, protocol.EventInboxArchived, protocol.EventInboxUnarchived,+ protocol.EventInboxDeleted,protocol.EventInboxBatchRead, protocol.EventInboxBatchArchived,protocol.EventIssueUnreadChanged,} {diff --git a/server/cmd/server/listeners_frame_test.go b/server/cmd/server/listeners_frame_test.goindex dde779316f..845564a5d6 100644--- a/server/cmd/server/listeners_frame_test.go+++ b/server/cmd/server/listeners_frame_test.go@@ -19,6 +19,18 @@ func TestRegisterListeners_FrameContainsActorType(t *testing.T) {checkUser bool // true = check SendToUser, false = check BroadcastToWorkspaceuserID string}{+ {+ name: "inbox deletion is recipient-only",+ event: events.Event{+ Type: protocol.EventInboxDeleted,+ WorkspaceID: "ws-1",+ ActorID: "user-1",+ ActorType: "member",+ Payload: map[string]any{"item_id": "inbox-1", "recipient_id": "user-1", "count": int64(1)},+ },+ checkUser: true,+ userID: "user-1",+ },{name: "workspace broadcast carries actor_type",event: events.Event{@@ -55,10 +67,16 @@ func TestRegisterListeners_FrameContainsActorType(t *testing.T) {var raw []byteif tc.checkUser {+ if len(fb.workspaceCalls) != 0 {+ t.Fatal("personal event broadcast to workspace")+ }if len(fb.userCalls) == 0 {t.Fatal("expected SendToUser call, got none")}raw = fb.userCalls[0].msg+ if fb.userCalls[0].userID != tc.userID {+ t.Fatalf("recipient = %q, want %q", fb.userCalls[0].userID, tc.userID)+ }} else {if len(fb.workspaceCalls) == 0 {t.Fatal("expected BroadcastToWorkspace call, got none")diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 2a2b4f508a..57a54485ae 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -2663,6 +2663,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/{id}/unread", h.MarkInboxUnread)r.Post("/{id}/archive", h.ArchiveInboxItem)r.Post("/{id}/unarchive", h.UnarchiveInboxItem)+ r.Delete("/{id}", h.DeleteInboxItem)})// Notification preferencesdiff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.goindex 3867b10dad..9ad39f3557 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -320,6 +320,31 @@ func (h *Handler) MarkInboxUnread(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, resp)}+func (h *Handler) DeleteInboxItem(w http.ResponseWriter, r *http.Request) {+ item, ok := h.loadInboxItemForUser(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ if !h.requireIssueIDVisible(w, r, uuidToString(item.WorkspaceID), item.IssueID, http.StatusNotFound, "inbox item not found") {+ return+ }+ count, err := h.Queries.DeleteInboxGroup(r.Context(), db.DeleteInboxGroupParams{+ ID: item.ID,+ WorkspaceID: item.WorkspaceID,+ RecipientID: item.RecipientID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to delete notification")+ return+ }+ h.publish(protocol.EventInboxDeleted, uuidToString(item.WorkspaceID), "member", requestUserID(r), map[string]any{+ "item_id": uuidToString(item.ID),+ "recipient_id": uuidToString(item.RecipientID),+ "count": count,+ })+ writeJSON(w, http.StatusOK, map[string]any{"count": count})+}+func (h *Handler) ArchiveInboxItem(w http.ResponseWriter, r *http.Request) {id := chi.URLParam(r, "id")prev, ok := h.loadInboxItemForUser(w, r, id)diff --git a/server/internal/handler/inbox_delete_test.go b/server/internal/handler/inbox_delete_test.gonew file mode 100644index 0000000000..9c774a4d40--- /dev/null+++ b/server/internal/handler/inbox_delete_test.go@@ -0,0 +1,154 @@+package handler++import (+ "net/http"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestDeleteInboxItem(t *testing.T) {+ ws := dbfx.Workspace(t, "Inbox deletion", "inbox-delete-"+uuid.NewString())+ dbfx.Member(t, ws, testUserID, "owner")+ issue := dbfx.Issue(t, "Keep the issue", testutil.Cols{"workspace_id": ws})+ otherWS := dbfx.Workspace(t, "Other inbox", "inbox-delete-other-"+uuid.NewString())+ dbfx.Member(t, otherWS, testUserID, "owner")+ otherUser := dbfx.User(t, "Other recipient", "inbox-delete-"+uuid.NewString()+"@example.test")+ dbfx.Member(t, ws, otherUser, "member")++ insert := func(workspace, recipient string, issueID any, archived bool) string {+ return dbfx.Insert(t, "inbox_item", testutil.Cols{+ "workspace_id": workspace, "recipient_type": "member", "recipient_id": recipient,+ "type": "task_failed", "severity": "info", "title": "Failed run",+ "issue_id": issueID, "archived": archived,+ })+ }+ target := insert(ws, testUserID, issue, false)+ sibling := insert(ws, testUserID, issue, false)+ history := insert(ws, testUserID, issue, true)+ otherRecipient := insert(ws, otherUser, issue, false)+ foreign := insert(otherWS, testUserID, nil, false)+ standalone := insert(ws, testUserID, nil, false)+ anotherStandalone := insert(ws, testUserID, nil, false)+ agent := dbfx.Agent(t, "Deletion test agent", "", testutil.Cols{"workspace_id": ws})+ task := dbfx.Task(t, agent, testutil.Cols{"issue_id": issue, "status": "failed", "completed_at": time.Now()})++ published := 0+ testHandler.Bus.Subscribe(protocol.EventInboxDeleted, func(e events.Event) {+ payload := e.Payload.(map[string]any)+ if payload["item_id"] == target {+ published+++ if payload["recipient_id"] != testUserID || payload["count"] != int64(2) {+ t.Errorf("deletion payload = %+v", payload)+ }+ }+ })++ remove := func(id, workspace string, status int) int64 {+ var out struct {+ Count int64 `json:"count"`+ }+ call := testutil.Call(t, inboxWorkspaceHandler(testHandler.DeleteInboxItem),+ withURLParam(inboxRequest(http.MethodDelete, "/api/inbox/"+id, workspace), "id", id)).Want(status)+ if status == http.StatusOK {+ call.JSON(&out)+ }+ return out.Count+ }+ remove(otherRecipient, ws, http.StatusNotFound)+ remove(foreign, ws, http.StatusNotFound)+ remove("not-a-uuid", ws, http.StatusBadRequest)+ remove(uuid.NewString(), ws, http.StatusNotFound)+ listArchived := func() []InboxItemResponse {+ var items []InboxItemResponse+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListArchivedInbox),+ inboxRequest(http.MethodGet, "/api/inbox/archived", ws)).Want(http.StatusOK).JSON(&items)+ return items+ }+ if items := listArchived(); len(items) != 0 {+ t.Fatalf("issue with active notifications appeared in archive: %+v", items)+ }+ if count := remove(target, ws, http.StatusOK); count != 2 {+ t.Fatalf("deleted %d notifications, want 2", count)+ }+ if published != 1 {+ t.Fatalf("deletion events = %d, want 1", published)+ }+ if items := listArchived(); len(items) != 1 || items[0].ID != history {+ t.Fatalf("archived history should reappear after deleting active notifications: %+v", items)+ }+ for _, id := range []string{target, sibling} {+ if n := dbfx.Count(t, "SELECT count(*) FROM inbox_item WHERE id = $1", id); n != 0 {+ t.Errorf("deleted notification %s remains", id)+ }+ }+ for _, id := range []string{history, otherRecipient, foreign, standalone, anotherStandalone} {+ if n := dbfx.Count(t, "SELECT count(*) FROM inbox_item WHERE id = $1", id); n != 1 {+ t.Errorf("unrelated notification %s removed", id)+ }+ }+ if n := dbfx.Count(t, "SELECT count(*) FROM issue WHERE id = $1", issue); n != 1 {+ t.Error("underlying issue removed")+ }+ if n := dbfx.Count(t, "SELECT count(*) FROM agent_task_queue WHERE id = $1", task); n != 1 {+ t.Error("underlying run removed")+ }+ remove(target, ws, http.StatusNotFound)+ if count := remove(standalone, ws, http.StatusOK); count != 1 {+ t.Errorf("standalone delete count = %d", count)+ }+ if n := dbfx.Count(t, "SELECT count(*) FROM inbox_item WHERE id = $1", anotherStandalone); n != 1 {+ t.Error("deleting a standalone notification removed another")+ }+ if count := remove(history, ws, http.StatusOK); count != 1 {+ t.Errorf("archived delete count = %d", count)+ }+}++func TestDeleteInboxItemPrivateProjectAfterRevocation(t *testing.T) {+ for _, archived := range []bool{false, true} {+ name := "active"+ if archived {+ name = "archived"+ }+ t.Run(name, func(t *testing.T) {+ f := newPrivateProjectFixture(t)+ id := dbfx.Insert(t, "inbox_item", testutil.Cols{+ "workspace_id": testWorkspaceID, "recipient_type": "member", "recipient_id": f.insider,+ "type": "mentioned", "severity": "info", "title": "Private notification",+ "issue_id": f.secretIssue, "archived": archived,+ })+ removeProjectMemberAsOwner(t, f, f.insider)+ published := 0+ testHandler.Bus.Subscribe(protocol.EventInboxDeleted, func(e events.Event) {+ if e.Payload.(map[string]any)["item_id"] == id {+ published+++ }+ })+ remove := func(itemID string, want int) *testutil.Response {+ return testutil.Call(t, inboxWorkspaceHandler(testHandler.DeleteInboxItem),+ withURLParam(asUser(inboxRequest(http.MethodDelete, "/api/inbox/"+itemID, testWorkspaceID), f.insider), "id", itemID)).Want(want)+ }+ hiddenBody := remove(id, http.StatusNotFound).Text()+ missingBody := remove(uuid.NewString(), http.StatusNotFound).Text()+ if hiddenBody != missingBody {+ t.Fatalf("hidden notification differs from a missing one: %s vs %s", hiddenBody, missingBody)+ }+ if n := dbfx.Count(t, "SELECT count(*) FROM inbox_item WHERE id = $1", id); n != 1 {+ t.Error("hidden notification was deleted")+ }+ if published != 0 {+ t.Error("hidden notification deletion published an event")+ }+ addProjectMemberRow(t, f.projectID, f.insider)+ remove(id, http.StatusOK)+ if n := dbfx.Count(t, "SELECT count(*) FROM inbox_item WHERE id = $1", id); n != 0 {+ t.Error("project member could not delete their notification")+ }+ })+ }+}diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.goindex 4a91c1b69b..16d3841611 100644--- a/server/pkg/db/generated/inbox.sql.go+++ b/server/pkg/db/generated/inbox.sql.go@@ -372,6 +372,37 @@ func (q *Queries) CreateInboxItem(ctx context.Context, arg CreateInboxItemParamsreturn i, err}+const deleteInboxGroup = `-- name: DeleteInboxGroup :execrows+WITH target AS (+ SELECT selected.id, selected.workspace_id, selected.recipient_type, selected.recipient_id, selected.type, selected.severity, selected.issue_id, selected.title, selected.body, selected.read, selected.archived, selected.created_at, selected.actor_type, selected.actor_id, selected.details, selected.section FROM inbox_item selected+ WHERE selected.id = $1 AND selected.workspace_id = $2+ AND selected.recipient_type = 'member' AND selected.recipient_id = $3+)+DELETE FROM inbox_item item USING target+WHERE item.workspace_id = target.workspace_id+ AND item.recipient_type = target.recipient_type+ AND item.recipient_id = target.recipient_id+ AND item.archived = target.archived+ AND (item.id = target.id OR item.issue_id = target.issue_id)+`++type DeleteInboxGroupParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ RecipientID pgtype.UUID `json:"recipient_id"`+}++// A visible inbox row groups notifications on an issue. Remove that group+// only in the selected view, so older siblings cannot bring the row back and+// deleting an active row does not erase its archived history.+func (q *Queries) DeleteInboxGroup(ctx context.Context, arg DeleteInboxGroupParams) (int64, error) {+ result, err := q.db.Exec(ctx, deleteInboxGroup, arg.ID, arg.WorkspaceID, arg.RecipientID)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const getInboxItem = `-- name: GetInboxItem :oneSELECT id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section FROM inbox_itemWHERE id = $1diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sqlindex f3d2d7d97c..50b4f1e415 100644--- a/server/pkg/db/queries/inbox.sql+++ b/server/pkg/db/queries/inbox.sql@@ -190,6 +190,22 @@ UPDATE inbox_item SET archived = trueWHERE id = $1RETURNING *;+-- name: DeleteInboxGroup :execrows+-- A visible inbox row groups notifications on an issue. Remove that group+-- only in the selected view, so older siblings cannot bring the row back and+-- deleting an active row does not erase its archived history.+WITH target AS (+ SELECT selected.* FROM inbox_item selected+ WHERE selected.id = $1 AND selected.workspace_id = $2+ AND selected.recipient_type = 'member' AND selected.recipient_id = $3+)+DELETE FROM inbox_item item USING target+WHERE item.workspace_id = target.workspace_id+ AND item.recipient_type = target.recipient_type+ AND item.recipient_id = target.recipient_id+ AND item.archived = target.archived+ AND (item.id = target.id OR item.issue_id = target.issue_id);+-- name: ArchiveInboxByIssue :execrowsUPDATE inbox_item SET archived = trueWHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_id = $4 AND archived = false;diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 908d85f66b..36047d5e71 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -51,6 +51,7 @@ const (EventInboxUnread = "inbox:unread"EventInboxArchived = "inbox:archived"EventInboxUnarchived = "inbox:unarchived"+ EventInboxDeleted = "inbox:deleted"EventInboxBatchRead = "inbox:batch-read"EventInboxBatchArchived = "inbox:batch-archived"