Skip to content

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

Go

fix(inbox): keep archive and done toasts after moving to the next issue (MUL-9354) (#10691)

Jiayuan Zhangaa95208e8a82
diff --git a/packages/views/issues/actions/__tests__/inbox-restore.test.tsx b/packages/views/issues/actions/__tests__/inbox-restore.test.tsx
index 5d1ed16a29..06b114a8df 100644
--- a/packages/views/issues/actions/__tests__/inbox-restore.test.tsx
+++ b/packages/views/issues/actions/__tests__/inbox-restore.test.tsx
@@ -1,6 +1,8 @@
+import { useState } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { toast } from "sonner";
import { I18nProvider } from "@multica/core/i18n/react";
import { setApiInstance } from "@multica/core/api";
import type { ApiClient } from "@multica/core/api/client";
@@ -32,35 +34,61 @@ function Harness({ enabled }: { enabled: boolean }) {
);
}
-function setup(archived: InboxItem[], enabled = true) {
+/** A menu that closes on a pick, unmounting its items, as the issue menus do. */
+function ClosingHarness() {
+ const [open, setOpen] = useState(true);
+ const itemId = useArchivedInboxItemId("issue-1", true);
+ return (
+ <DropdownMenu open={open} onOpenChange={setOpen}>
+ <DropdownMenuTrigger>more</DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem>Pin to sidebar</DropdownMenuItem>
+ {itemId && <InboxRestoreMenuItem itemId={itemId} Item={DropdownMenuItem} />}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+function setup(
+ archived: InboxItem[],
+ { enabled = true, closing = false, unarchive }: { enabled?: boolean; closing?: boolean; unarchive?: () => Promise<InboxItem> } = {},
+) {
let rows = archived;
const listArchivedInboxPage = vi.fn(async (_filters: unknown, options: { groupId?: string }) => ({
items: rows.filter((row) => row.issue_id === options.groupId),
hasMore: false,
nextCursor: null,
}));
- const unarchiveInbox = vi.fn(async (id: string) => {
- rows = rows.filter((row) => row.id !== id);
- return notification({ id, archived: false });
- });
+ const unarchiveInbox = vi.fn(
+ unarchive ??
+ (async (id: string) => {
+ rows = rows.filter((row) => row.id !== id);
+ return notification({ id, archived: false });
+ }),
+ );
setApiInstance({
listArchivedInboxPage,
unarchiveInbox,
listInbox: async () => [],
getInboxUnreadSummary: async () => [],
} as unknown as ApiClient);
- const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity }, mutations: { retry: false } },
+ });
render(
<QueryClientProvider client={qc}>
<I18nProvider locale="en" resources={RESOURCES}>
- <Harness enabled={enabled} />
+ {closing ? <ClosingHarness /> : <Harness enabled={enabled} />}
</I18nProvider>
</QueryClientProvider>,
);
return { listArchivedInboxPage, unarchiveInbox };
}
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
describe("inbox restore menu entry", () => {
it("is absent when the issue is not archived in the reader's inbox", async () => {
@@ -72,7 +100,7 @@ describe("inbox restore menu entry", () => {
});
it("skips the lookup when the host owns inbox actions", async () => {
- const api = setup([notification({})], false);
+ const api = setup([notification({})], { enabled: false });
await screen.findByRole("menuitem", { name: "Pin to sidebar" });
expect(api.listArchivedInboxPage).not.toHaveBeenCalled();
expect(screen.queryByRole("menuitem", { name: "Restore to inbox" })).toBeNull();
@@ -84,4 +112,33 @@ describe("inbox restore menu entry", () => {
await waitFor(() => expect(api.unarchiveInbox).toHaveBeenCalledWith("item-1"));
await waitFor(() => expect(screen.queryByRole("menuitem", { name: "Restore to inbox" })).toBeNull());
});
+
+ it("still confirms the restore after the menu closes", async () => {
+ let finish!: () => void;
+ const api = setup([notification({})], {
+ closing: true,
+ unarchive: () => new Promise((resolve) => (finish = () => resolve(notification({ archived: false })))),
+ });
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Restore to inbox" }));
+ await waitFor(() => expect(screen.queryByRole("menuitem", { name: "Pin to sidebar" })).toBeNull());
+ await waitFor(() => expect(api.unarchiveInbox).toHaveBeenCalled());
+ await act(async () => finish());
+
+ expect(toast.success).toHaveBeenCalledWith("Notification restored");
+ });
+
+ it("still reports a failed restore after the menu closes", async () => {
+ let fail!: (err: Error) => void;
+ const api = setup([notification({})], {
+ closing: true,
+ unarchive: () => new Promise((_resolve, reject) => (fail = reject)),
+ });
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Restore to inbox" }));
+ await waitFor(() => expect(screen.queryByRole("menuitem", { name: "Pin to sidebar" })).toBeNull());
+ await waitFor(() => expect(api.unarchiveInbox).toHaveBeenCalled());
+ await act(async () => fail(new Error("Restore rejected")));
+
+ expect(toast.error).toHaveBeenCalledWith("Restore rejected");
+ expect(toast.success).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/views/issues/actions/__tests__/issue-inbox-actions.test.tsx b/packages/views/issues/actions/__tests__/issue-inbox-actions.test.tsx
index e50946c833..8636d64512 100644
--- a/packages/views/issues/actions/__tests__/issue-inbox-actions.test.tsx
+++ b/packages/views/issues/actions/__tests__/issue-inbox-actions.test.tsx
@@ -1,7 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { act, cleanup, fireEvent, screen } from "@testing-library/react";
+import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { toast } from "sonner";
import { agentTaskSnapshotOptions } from "@multica/core/agents";
+import { setApiInstance } from "@multica/core/api";
+import type { ApiClient } from "@multica/core/api/client";
import { useInboxFilterStore } from "@multica/core/inbox/filter-store";
import { inboxListOptions, snoozedInboxOptions } from "@multica/core/inbox/queries";
import { useInboxSelectionStore } from "@multica/core/inbox/selection-store";
@@ -11,7 +14,7 @@ import { NavigationProvider, type NavigationAdapter } from "../../../navigation"
import { IssueInboxActions } from "../issue-inbox-actions";
const state = vi.hoisted(() => ({
- archive: vi.fn(),
+ archiveInbox: vi.fn(),
snooze: vi.fn(() => Promise.resolve()),
unsnooze: vi.fn(() => Promise.resolve()),
}));
@@ -22,8 +25,10 @@ vi.mock("@multica/core/paths", async (importOriginal) => {
const actual = await importOriginal<typeof import("@multica/core/paths")>();
return { ...actual, useWorkspacePaths: () => actual.paths.workspace("acme") };
});
-vi.mock("@multica/core/inbox/mutations", () => ({
- useArchiveInbox: () => ({ mutate: state.archive }),
+// Archive runs through the real mutation, so the tests see React Query drop
+// per-call callbacks when the next issue's page replaces the header.
+vi.mock("@multica/core/inbox/mutations", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/inbox/mutations")>()),
useSnoozeInbox: () => ({ mutateAsync: state.snooze }),
useUnsnoozeInbox: () => ({ mutateAsync: state.unsnooze }),
cachedInboxSnoozedUntil: () => null,
@@ -78,25 +83,49 @@ function setup({
hash: "",
getShareableUrl: (path) => path,
};
- const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
+ setApiInstance({
+ archiveInbox: state.archiveInbox,
+ listInbox: async () => rows,
+ listSnoozedInbox: async () => snoozed,
+ getInboxUnreadSummary: async () => [],
+ getAgentTaskSnapshot: async () => [],
+ } as unknown as ApiClient);
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity }, mutations: { retry: false } },
+ });
qc.setQueryData(inboxListOptions("ws").queryKey, rows);
qc.setQueryData(snoozedInboxOptions("ws").queryKey, snoozed);
qc.setQueryData(agentTaskSnapshotOptions("ws").queryKey, []);
- const page = (id: string) => (
+ const page = (id: string | null) => (
<QueryClientProvider client={qc}>
<NavigationProvider value={nav}>
- <IssueInboxActions issueId={id} onMarkDone={onMarkDone} />
+ {id ? <IssueInboxActions issueId={id} onMarkDone={onMarkDone} /> : <span>Next issue</span>}
</NavigationProvider>
</QueryClientProvider>
);
const { rerender } = renderWithI18n(page(issueId));
/** The route reaching another issue, which the same header then shows. */
const arrive = (id: string) => rerender(page(id));
- return Object.assign(nav, { arrive });
+ /** The next page replacing this one, taking the header with it. */
+ const leave = () => rerender(page(null));
+ return Object.assign(nav, { arrive, leave });
+}
+
+/** An archive request the test settles by hand, after the header is gone. */
+function pendingArchive() {
+ let settle!: { resolve: (item: InboxItem) => void; reject: (err: Error) => void };
+ state.archiveInbox.mockImplementation(
+ () => new Promise<InboxItem>((resolve, reject) => (settle = { resolve, reject })),
+ );
+ return {
+ resolve: () => act(async () => settle.resolve(item({ id: "n-1", archived: true }))),
+ reject: (err: Error) => act(async () => settle.reject(err)),
+ };
}
beforeEach(() => {
vi.clearAllMocks();
+ state.archiveInbox.mockImplementation(async (id: string) => item({ id, archived: true }));
useInboxSelectionStore.setState({ sidebarIssueByWorkspace: { ws: "issue-1" }, sidebarTabIssuesByWorkspace: {} });
useInboxFilterStore.getState().clearFilters("ws");
});
@@ -109,27 +138,27 @@ describe("IssueInboxActions", () => {
expect(screen.queryByRole("button", { name: "Archive" })).toBeNull();
});
- it("stays on the open issue until the next notification's issue arrives", () => {
+ it("stays on the open issue until the next notification's issue arrives", async () => {
const nav = setup();
act(() => {
useInboxSelectionStore.getState().rememberSidebarIssue("ws", "issue-2");
});
fireEvent.click(screen.getByRole("button", { name: "Archive" }));
- expect(state.archive).toHaveBeenLastCalledWith("n-1", expect.anything());
+ await waitFor(() => expect(state.archiveInbox).toHaveBeenLastCalledWith("n-1"));
nav.arrive("issue-2");
fireEvent.click(screen.getByRole("button", { name: "Archive" }));
- expect(state.archive).toHaveBeenLastCalledWith("n-2", expect.anything());
+ await waitFor(() => expect(state.archiveInbox).toHaveBeenLastCalledWith("n-2"));
});
- it("shows on an issue the Inbox opened in another tab", () => {
+ it("shows on an issue the Inbox opened in another tab", async () => {
useInboxSelectionStore.setState({
sidebarIssueByWorkspace: { ws: "issue-1" },
sidebarTabIssuesByWorkspace: { ws: ["issue-2"] },
});
setup({ issueId: "issue-2" });
fireEvent.click(screen.getByRole("button", { name: "Archive" }));
- expect(state.archive).toHaveBeenCalledWith("n-2", expect.anything());
+ await waitFor(() => expect(state.archiveInbox).toHaveBeenCalledWith("n-2"));
});
it("leaves once the issue is opened from outside the Inbox", () => {
@@ -174,19 +203,43 @@ describe("IssueInboxActions", () => {
expect(state.unsnooze).toHaveBeenCalledWith({ id: "n-1" });
});
- it("archives and moves on to the next notification", () => {
+ it("archives and moves on to the next notification", async () => {
const nav = setup();
fireEvent.click(screen.getByRole("button", { name: "Archive" }));
- expect(state.archive).toHaveBeenCalledWith("n-1", expect.anything());
expect(nav.push).toHaveBeenCalledWith("/acme/issues/issue-2#comment-c-9");
expect(useInboxSelectionStore.getState().sidebarIssueByWorkspace.ws).toBe("issue-2");
+ await waitFor(() => expect(state.archiveInbox).toHaveBeenCalledWith("n-1"));
+ });
+
+ it("still confirms the archive after the next issue replaces this one", async () => {
+ const archive = pendingArchive();
+ const nav = setup();
+ fireEvent.click(screen.getByRole("button", { name: "Archive" }));
+ await waitFor(() => expect(state.archiveInbox).toHaveBeenCalledWith("n-1"));
+ nav.leave();
+ await archive.resolve();
+
+ expect(toast.success).toHaveBeenCalledWith("Notification archived");
+ expect(toast.error).not.toHaveBeenCalled();
});
- it("stays on the issue when it was the last notification", () => {
+ it("still reports a failed archive after the next issue replaces this one", async () => {
+ const archive = pendingArchive();
+ const nav = setup();
+ fireEvent.click(screen.getByRole("button", { name: "Archive" }));
+ await waitFor(() => expect(state.archiveInbox).toHaveBeenCalled());
+ nav.leave();
+ await archive.reject(new Error("Archive rejected"));
+
+ expect(toast.error).toHaveBeenCalledWith("Archive rejected");
+ expect(toast.success).not.toHaveBeenCalled();
+ });
+
+ it("stays on the issue when it was the last notification", async () => {
const nav = setup({ rows: [ROWS[0]!] });
fireEvent.click(screen.getByRole("button", { name: "Archive" }));
- expect(state.archive).toHaveBeenCalledWith("n-1", expect.anything());
expect(nav.push).not.toHaveBeenCalled();
+ await waitFor(() => expect(state.archiveInbox).toHaveBeenCalledWith("n-1"));
});
it("moves on to the next notification the Work panel lists under its filters", () => {
@@ -202,19 +255,31 @@ describe("IssueInboxActions", () => {
expect(nav.push).toHaveBeenCalledWith("/acme/issues/issue-3");
});
- it("marks the issue done, then archives and moves on once that is saved", () => {
+ it("marks the issue done, then archives and moves on once that is saved", async () => {
let saved: (() => void) | undefined;
const onMarkDone = vi.fn((onSaved: () => void) => { saved = onSaved; });
const nav = setup({ onMarkDone });
fireEvent.click(screen.getByRole("button", { name: "Mark as done" }));
expect(onMarkDone).toHaveBeenCalledTimes(1);
- expect(state.archive).not.toHaveBeenCalled();
+ expect(state.archiveInbox).not.toHaveBeenCalled();
expect(nav.push).not.toHaveBeenCalled();
- saved!();
- expect(state.archive).toHaveBeenCalledWith("n-1", expect.anything());
+ act(() => saved!());
expect(nav.push).toHaveBeenCalledWith("/acme/issues/issue-2#comment-c-9");
+ await waitFor(() => expect(state.archiveInbox).toHaveBeenCalledWith("n-1"));
+ });
+
+ it("still reports a failed archive after marking done moves on", async () => {
+ const archive = pendingArchive();
+ const nav = setup({ onMarkDone: (onSaved) => onSaved() });
+
+ fireEvent.click(screen.getByRole("button", { name: "Mark as done" }));
+ await waitFor(() => expect(state.archiveInbox).toHaveBeenCalled());
+ nav.leave();
+ await archive.reject(new Error("Archive rejected"));
+
+ expect(toast.error).toHaveBeenCalledWith("Archive rejected");
});
it("offers no done button when the issue cannot be marked done", () => {
@@ -222,9 +287,9 @@ describe("IssueInboxActions", () => {
expect(screen.queryByRole("button", { name: "Mark as done" })).toBeNull();
});
- it("archives with the Inbox shortcut", () => {
+ it("archives with the Inbox shortcut", async () => {
setup();
fireEvent.keyDown(document, { key: "e", code: "KeyE" });
- expect(state.archive).toHaveBeenCalledWith("n-1", expect.anything());
+ await waitFor(() => expect(state.archiveInbox).toHaveBeenCalledWith("n-1"));
});
});
diff --git a/packages/views/issues/actions/inbox-restore.tsx b/packages/views/issues/actions/inbox-restore.tsx
index b2480fad88..2ffe3733c6 100644
--- a/packages/views/issues/actions/inbox-restore.tsx
+++ b/packages/views/issues/actions/inbox-restore.tsx
@@ -25,19 +25,21 @@ export function useArchivedInboxItemId(issueId: string, enabled: boolean): strin
export function InboxRestoreMenuItem({ itemId, Item }: { itemId: string; Item: MenuPrimitives["Item"] }) {
const { t } = useT("issues");
const { t: tInbox } = useT("inbox");
- const unarchive = useUnarchiveInbox();
+ const { mutateAsync: unarchive } = useUnarchiveInbox();
return (
<Item
+ // The menu closes on click and unmounts this item, so the toasts follow
+ // the request's promise rather than per-call mutation callbacks.
onClick={() =>
- unarchive.mutate(itemId, {
- onSuccess: () => toast.success(tInbox(($) => $.toasts.unarchived)),
- onError: (err) =>
+ unarchive(itemId).then(
+ () => toast.success(tInbox(($) => $.toasts.unarchived)),
+ (err) =>
toast.error(
err instanceof Error && err.message
? err.message
: tInbox(($) => $.errors.unarchive_failed),
),
- })
+ )
}
>
<ArchiveRestore className="h-3.5 w-3.5" />
diff --git a/packages/views/issues/actions/issue-inbox-actions.tsx b/packages/views/issues/actions/issue-inbox-actions.tsx
index 39162deb99..8d6ed39db5 100644
--- a/packages/views/issues/actions/issue-inbox-actions.tsx
+++ b/packages/views/issues/actions/issue-inbox-actions.tsx
@@ -58,7 +58,7 @@ export function IssueInboxActions({
const { rows } = useFilteredInboxRows(wsId, issueId, fromInbox);
const index = fromInbox ? rows.findIndex((row) => row.issue_id === issueId) : -1;
const item = index >= 0 ? rows[index]! : null;
- const archive = useArchiveInbox();
+ const { mutateAsync: archiveAsync } = useArchiveInbox();
const { snooze, unsnooze } = useInboxSnooze();
const { data: snoozedList } = useQuery(snoozedInboxOptions(wsId));
const snoozed = item ? undefined : findSnoozedInboxIssue(snoozedList, issueId);
@@ -74,13 +74,15 @@ export function IssueInboxActions({
push(inboxRowHref(p, next));
};
+ // Toasts follow the request's promise: the next issue's page can replace
+ // this header first, and React Query drops per-call callbacks with it.
const archiveItem = () => {
if (!item) return;
const next = rows[index + 1] ?? rows[index - 1] ?? null;
- archive.mutate(item.id, {
- onSuccess: () => toast.success(t(($) => $.toasts.archived)),
- onError: failed(t(($) => $.errors.archive_failed)),
- });
+ archiveAsync(item.id).then(
+ () => toast.success(t(($) => $.toasts.archived)),
+ failed(t(($) => $.errors.archive_failed)),
+ );
openNext(next);
};
@@ -97,7 +99,7 @@ export function IssueInboxActions({
if (!item || !onMarkDone) return;
const next = rows[index + 1] ?? rows[index - 1] ?? null;
onMarkDone(() => {
- archive.mutate(item.id, { onError: failed(t(($) => $.errors.archive_failed)) });
+ archiveAsync(item.id).catch(failed(t(($) => $.errors.archive_failed)));
openNext(next);
});
};
diff --git a/packages/views/modals/add-child-issue.tsx b/packages/views/modals/add-child-issue.tsx
index 3ba3561919..4a6dd3c7fb 100644
--- a/packages/views/modals/add-child-issue.tsx
+++ b/packages/views/modals/add-child-issue.tsx
@@ -21,7 +21,7 @@ export function AddChildIssueModal({
const { t } = useT("modals");
const issueId = (data?.issueId as string) || "";
const wsId = useWorkspaceId();
- const updateIssue = useUpdateIssue();
+ const { mutateAsync: updateIssue } = useUpdateIssue();
const { data: issue = null } = useQuery({
...issueDetailOptions(wsId, issueId),
@@ -38,6 +38,8 @@ export function AddChildIssueModal({
...children.map((c) => c.id),
];
+ // The picker closes as soon as an issue is picked, unmounting this modal, so
+ // the toasts follow the request's promise rather than per-call callbacks.
return (
<IssuePickerModal
open
@@ -48,25 +50,22 @@ export function AddChildIssueModal({
description={t(($) => $.add_child.description)}
excludeIds={excludeIds}
onSelect={(selected) => {
- updateIssue.mutate(
- {
- id: selected.id,
- parent_issue_id: issueId,
- },
- {
- onSuccess: () =>
- toast.success(
- t(($) => $.add_child.toast_success, {
- identifier: selected.identifier,
- }),
- ),
- onError: (err) =>
- toast.error(
- err instanceof Error && err.message
- ? err.message
- : t(($) => $.add_child.toast_failed),
- ),
- },
+ updateIssue({
+ id: selected.id,
+ parent_issue_id: issueId,
+ }).then(
+ () =>
+ toast.success(
+ t(($) => $.add_child.toast_success, {
+ identifier: selected.identifier,
+ }),
+ ),
+ (err) =>
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.add_child.toast_failed),
+ ),
);
}}
/>
diff --git a/packages/views/modals/add-project-issue.tsx b/packages/views/modals/add-project-issue.tsx
index 00dee70e4c..2213c5bb4f 100644
--- a/packages/views/modals/add-project-issue.tsx
+++ b/packages/views/modals/add-project-issue.tsx
@@ -14,8 +14,10 @@ export function AddProjectIssueModal({
}) {
const { t } = useT("modals");
const projectId = (data?.projectId as string) || "";
- const updateIssue = useUpdateIssue();
+ const { mutateAsync: updateIssue } = useUpdateIssue();
+ // The picker closes as soon as an issue is picked, unmounting this modal, so
+ // the toasts follow the request's promise rather than per-call callbacks.
return (
<IssuePickerModal
open
@@ -27,22 +29,19 @@ export function AddProjectIssueModal({
excludeIds={[]}
isSelectable={(issue) => issue.project_id !== projectId}
onSelect={(selected) => {
- updateIssue.mutate(
- { id: selected.id, project_id: projectId },
- {
- onSuccess: () =>
- toast.success(
- t(($) => $.add_project_issue.toast_success, {
- identifier: selected.identifier,
- }),
- ),
- onError: (err) =>
- toast.error(
- err instanceof Error && err.message
- ? err.message
- : t(($) => $.add_project_issue.toast_failed),
- ),
- },
+ updateIssue({ id: selected.id, project_id: projectId }).then(
+ () =>
+ toast.success(
+ t(($) => $.add_project_issue.toast_success, {
+ identifier: selected.identifier,
+ }),
+ ),
+ (err) =>
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.add_project_issue.toast_failed),
+ ),
);
}}
/>
diff --git a/packages/views/modals/issue-parent-modals.test.tsx b/packages/views/modals/issue-parent-modals.test.tsx
index c5a6ffadf4..796d1b6498 100644
--- a/packages/views/modals/issue-parent-modals.test.tsx
+++ b/packages/views/modals/issue-parent-modals.test.tsx
@@ -1,17 +1,19 @@
-import { fireEvent, render, screen } from "@testing-library/react";
+import { useState, type ComponentType } from "react";
+import { act, fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AddChildIssueModal } from "./add-child-issue";
+import { AddProjectIssueModal } from "./add-project-issue";
import { SetParentIssueModal } from "./set-parent-issue";
const mocks = vi.hoisted(() => ({
- mutate: vi.fn(),
+ mutateAsync: vi.fn(),
toast: { success: vi.fn(), error: vi.fn() },
}));
vi.mock("sonner", () => ({ toast: mocks.toast }));
vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));
vi.mock("@multica/core/issues/mutations", () => ({
- useUpdateIssue: () => ({ mutate: mocks.mutate }),
+ useUpdateIssue: () => ({ mutateAsync: mocks.mutateAsync }),
}));
vi.mock("@multica/core/issues/queries", () => ({
issueDetailOptions: (_wsId: string, issueId: string) => ({
@@ -27,17 +29,21 @@ vi.mock("@tanstack/react-query", () => ({
? { data: { id: queryKey[2], revision: 7, parent_issue_id: null } }
: { data: [] },
}));
+// Like the real picker, picking an issue closes the modal straight away.
vi.mock("./issue-picker-modal", () => ({
IssuePickerModal: ({
onSelect,
+ onOpenChange,
}: {
onSelect: (issue: { id: string; identifier: string; revision: number }) => void;
+ onOpenChange: (open: boolean) => void;
}) => (
<button
type="button"
- onClick={() =>
- onSelect({ id: "selected-1", identifier: "MUL-2", revision: 5 })
- }
+ onClick={() => {
+ onSelect({ id: "selected-1", identifier: "MUL-2", revision: 5 });
+ onOpenChange(false);
+ }}
>
Select issue
</button>
@@ -62,59 +68,83 @@ vi.mock("../i18n", () => ({
toast_success: `Set ${String(vars?.identifier ?? "")}`,
toast_failed: "Set failed",
},
+ add_project_issue: {
+ title: "Add to project",
+ description: "Choose issue",
+ toast_success: `Moved ${String(vars?.identifier ?? "")}`,
+ toast_failed: "Move failed",
+ },
}),
}),
}));
+type ModalComponent = ComponentType<{ onClose: () => void; data: Record<string, unknown> | null }>;
+
+/** The modal host unmounts a modal as soon as it closes. */
+function Host({ Component, data }: { Component: ModalComponent; data: Record<string, unknown> }) {
+ const [open, setOpen] = useState(true);
+ return open ? <Component onClose={() => setOpen(false)} data={data} /> : <span>Closed</span>;
+}
+
+function deferred() {
+ let settle!: { resolve: () => void; reject: (err: Error) => void };
+ mocks.mutateAsync.mockImplementation(
+ () => new Promise<void>((resolve, reject) => (settle = { resolve, reject })),
+ );
+ return {
+ resolve: () => act(async () => settle.resolve()),
+ reject: (err: Error) => act(async () => settle.reject(err)),
+ };
+}
+
describe.each([
{
name: "AddChildIssueModal",
Component: AddChildIssueModal,
- expectedMutation: {
- id: "selected-1",
- parent_issue_id: "issue-1",
- },
+ data: { issueId: "issue-1" },
+ expectedMutation: { id: "selected-1", parent_issue_id: "issue-1" },
+ success: "Added MUL-2",
},
{
name: "SetParentIssueModal",
Component: SetParentIssueModal,
- expectedMutation: {
- id: "issue-1",
- parent_issue_id: "selected-1",
- },
+ data: { issueId: "issue-1" },
+ expectedMutation: { id: "issue-1", parent_issue_id: "selected-1" },
+ success: "Set MUL-2",
+ },
+ {
+ name: "AddProjectIssueModal",
+ Component: AddProjectIssueModal,
+ data: { projectId: "project-1" },
+ expectedMutation: { id: "selected-1", project_id: "project-1" },
+ success: "Moved MUL-2",
},
-])("$name", ({ Component, expectedMutation }) => {
+])("$name", ({ Component, data, expectedMutation, success }) => {
beforeEach(() => {
vi.clearAllMocks();
});
- it("shows success only after the mutation succeeds", () => {
- mocks.mutate.mockImplementation((_variables, callbacks) => {
- callbacks.onSuccess();
- });
-
- render(<Component onClose={vi.fn()} data={{ issueId: "issue-1" }} />);
+ it("shows success once the update saves, after the modal has closed", async () => {
+ const request = deferred();
+ render(<Host Component={Component} data={data} />);
fireEvent.click(screen.getByRole("button", { name: "Select issue" }));
- expect(mocks.mutate).toHaveBeenCalledWith(
- expectedMutation,
- expect.objectContaining({
- onSuccess: expect.any(Function),
- onError: expect.any(Function),
- }),
- );
- expect(mocks.toast.success).toHaveBeenCalledTimes(1);
+ expect(screen.getByText("Closed")).toBeInTheDocument();
+ expect(mocks.mutateAsync).toHaveBeenCalledWith(expectedMutation);
+ expect(mocks.toast.success).not.toHaveBeenCalled();
+
+ await request.resolve();
+ expect(mocks.toast.success).toHaveBeenCalledWith(success);
expect(mocks.toast.error).not.toHaveBeenCalled();
});
- it("does not report success when the mutation fails", () => {
- mocks.mutate.mockImplementation((_variables, callbacks) => {
- callbacks.onError(new Error("revision conflict"));
- });
-
- render(<Component onClose={vi.fn()} data={{ issueId: "issue-1" }} />);
+ it("reports a failure, not success, after the modal has closed", async () => {
+ const request = deferred();
+ render(<Host Component={Component} data={data} />);
fireEvent.click(screen.getByRole("button", { name: "Select issue" }));
+ expect(screen.getByText("Closed")).toBeInTheDocument();
+ await request.reject(new Error("revision conflict"));
expect(mocks.toast.success).not.toHaveBeenCalled();
expect(mocks.toast.error).toHaveBeenCalledWith("revision conflict");
});
diff --git a/packages/views/modals/set-parent-issue.tsx b/packages/views/modals/set-parent-issue.tsx
index 873606c551..b559005d36 100644
--- a/packages/views/modals/set-parent-issue.tsx
+++ b/packages/views/modals/set-parent-issue.tsx
@@ -20,7 +20,7 @@ export function SetParentIssueModal({
const { t } = useT("modals");
const issueId = (data?.issueId as string) || "";
const wsId = useWorkspaceId();
- const updateIssue = useUpdateIssue();
+ const { mutateAsync: updateIssue } = useUpdateIssue();
const { data: children = [] } = useQuery({
...childIssuesOptions(wsId, issueId),
@@ -29,6 +29,9 @@ export function SetParentIssueModal({
const excludeIds = [issueId, ...children.map((c) => c.id)];
+ // The picker closes as soon as an issue is picked, unmounting this modal, so
+ // the toasts follow the request's promise rather than per-call callbacks.
+
return (
<IssuePickerModal
open
@@ -39,25 +42,22 @@ export function SetParentIssueModal({
description={t(($) => $.set_parent.description)}
excludeIds={excludeIds}
onSelect={(selected) => {
- updateIssue.mutate(
- {
- id: issueId,
- parent_issue_id: selected.id,
- },
- {
- onSuccess: () =>
- toast.success(
- t(($) => $.set_parent.toast_success, {
- identifier: selected.identifier,
- }),
- ),
- onError: (err) =>
- toast.error(
- err instanceof Error && err.message
- ? err.message
- : t(($) => $.set_parent.toast_failed),
- ),
- },
+ updateIssue({
+ id: issueId,
+ parent_issue_id: selected.id,
+ }).then(
+ () =>
+ toast.success(
+ t(($) => $.set_parent.toast_success, {
+ identifier: selected.identifier,
+ }),
+ ),
+ (err) =>
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.set_parent.toast_failed),
+ ),
);
}}
/>
diff --git a/packages/views/modals/workflow-handoff.tsx b/packages/views/modals/workflow-handoff.tsx
index 45c4631e6d..d8be3180db 100644
--- a/packages/views/modals/workflow-handoff.tsx
+++ b/packages/views/modals/workflow-handoff.tsx
@@ -18,7 +18,7 @@ export function WorkflowHandoffModal({
data: Record<string, unknown> | null;
}) {
const { t } = useT("issues");
- const updateIssue = useUpdateIssue();
+ const { mutateAsync: updateIssue } = useUpdateIssue();
const issueId = typeof data?.issueId === "string" ? data.issueId : "";
const identifier = typeof data?.identifier === "string" ? data.identifier : "";
const status = typeof data?.status === "string" ? data.status : "";
@@ -30,12 +30,9 @@ export function WorkflowHandoffModal({
onCancel={onClose}
onConfirm={({ stopPreviousRuns }) => {
onClose();
- updateIssue.mutate(
- { id: issueId, status, ...(stopPreviousRuns ? { stop_previous_assignee_runs: true } : {}) },
- {
- onError: (err) =>
- toast.error(err instanceof Error && err.message ? err.message : t(($) => $.detail.update_failed)),
- },
+ // Closing unmounts this modal, so the failure follows the promise.
+ updateIssue({ id: issueId, status, ...(stopPreviousRuns ? { stop_previous_assignee_runs: true } : {}) }).catch(
+ (err) => toast.error(err instanceof Error && err.message ? err.message : t(($) => $.detail.update_failed)),
);
}}
/>