Skip to content

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

Go

fix(inbox): prune inbox caches when this client deletes issues (#10403)

LuckVdedd74320aa94
diff --git a/packages/core/inbox/ws-updaters.test.ts b/packages/core/inbox/ws-updaters.test.ts
index 134a143141..20f65e809f 100644
--- a/packages/core/inbox/ws-updaters.test.ts
+++ b/packages/core/inbox/ws-updaters.test.ts
@@ -5,6 +5,7 @@ import {
cancelInboxLists,
onInboxInvalidate,
onInboxIssueDeleted,
+ onInboxIssuesDeleted,
onInboxNew,
onInboxIssueStatusChanged,
onInboxSummaryInvalidate,
@@ -393,3 +394,109 @@ describe("inbox list refresh during the first load", () => {
}
});
});
+
+// The delete mutations call onInboxIssuesDeleted directly — their WS echo is a
+// backstop, not the plan — so it owes the same discipline as the update
+// writes: cancel before pruning, and re-read a list whose request the cancel
+// interrupted (MUL-7286).
+describe("onInboxIssuesDeleted", () => {
+ it("removes all inbox items referencing any deleted issue, from both lists", async () => {
+ const qc = new QueryClient();
+ qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), [
+ makeItem("i1", "issue-a"),
+ makeItem("i2", "issue-a"),
+ makeItem("i3", "issue-b"),
+ makeItem("i4", null),
+ ]);
+ qc.setQueryData<InboxItem[]>(inboxKeys.archived(wsId), [
+ makeItem("a1", "issue-a", { archived: true }),
+ makeItem("a2", "issue-b", { archived: true }),
+ ]);
+
+ await onInboxIssuesDeleted(qc, wsId, ["issue-a", "issue-b"]);
+
+ expect(
+ qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId))?.map((i) => i.id),
+ ).toEqual(["i4"]);
+ expect(
+ qc.getQueryData<InboxItem[]>(inboxKeys.archived(wsId))?.map((i) => i.id),
+ ).toEqual([]);
+ });
+
+ it("is a no-op without ids", async () => {
+ const qc = new QueryClient();
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+
+ await onInboxIssuesDeleted(qc, wsId, []);
+
+ expect(invalidate).not.toHaveBeenCalled();
+ });
+
+ it("refreshes the unread summary, which the dropped rows can change", async () => {
+ const qc = new QueryClient();
+ const spy = vi.spyOn(qc, "invalidateQueries");
+ qc.setQueryData<InboxItem[]>(inboxKeys.list(wsId), [
+ makeItem("i1", "issue-a", { read: false }),
+ ]);
+
+ await onInboxIssuesDeleted(qc, wsId, ["issue-a"]);
+
+ expect(spy).toHaveBeenCalledWith({ queryKey: inboxKeys.unreadSummary() });
+ });
+
+ it("re-reads a list whose request the prune interrupted", async () => {
+ // A pre-delete response landing after the prune would resurrect the
+ // deleted rows; the cancel drops it, and the interrupted list is owed a
+ // re-read whose response no longer contains them.
+ const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });
+ let releaseFirst!: (rows: InboxItem[]) => void;
+ const firstResponse = new Promise<InboxItem[]>((resolve) => {
+ releaseFirst = resolve;
+ });
+ const server: InboxItem[] = [makeItem("n2", "issue-c", { read: false })];
+ const queryFn = vi
+ .fn<() => Promise<InboxItem[]>>()
+ .mockImplementationOnce(() => firstResponse)
+ .mockImplementation(async () => server);
+ const observer = new QueryObserver(qc, { queryKey: inboxKeys.list(wsId), queryFn });
+ const unsubscribe = observer.subscribe(() => {});
+
+ try {
+ expect(queryFn).toHaveBeenCalledTimes(1);
+ expect(qc.getQueryState(inboxKeys.list(wsId))?.fetchStatus).toBe("fetching");
+
+ await onInboxIssuesDeleted(qc, wsId, ["issue-a"]);
+ releaseFirst([makeItem("n1", "issue-a", { read: false })]);
+
+ await vi.waitFor(() =>
+ expect(qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId))?.map((i) => i.id)).toEqual(["n2"]),
+ );
+ expect(queryFn.mock.calls.length).toBeGreaterThan(1);
+ } finally {
+ releaseFirst([]);
+ unsubscribe();
+ qc.clear();
+ }
+ });
+
+ it("adds no list request when none was interrupted", async () => {
+ const qc = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false } } });
+ const queryFn = vi.fn(async () => [makeItem("i1", "issue-a")]);
+ const options = { queryKey: inboxKeys.list(wsId), queryFn };
+ await qc.fetchQuery(options);
+ const observer = new QueryObserver(qc, options);
+ const unsubscribe = observer.subscribe(() => {});
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+
+ try {
+ await onInboxIssuesDeleted(qc, wsId, ["issue-a"]);
+
+ expect(qc.getQueryData<InboxItem[]>(inboxKeys.list(wsId))?.map((i) => i.id)).toEqual([]);
+ expect(queryFn).toHaveBeenCalledTimes(1);
+ expect(invalidate).not.toHaveBeenCalledWith({ queryKey: inboxKeys.all(wsId) });
+ } finally {
+ unsubscribe();
+ qc.clear();
+ }
+ });
+});
diff --git a/packages/core/inbox/ws-updaters.ts b/packages/core/inbox/ws-updaters.ts
index de8de52d07..d74647cb9f 100644
--- a/packages/core/inbox/ws-updaters.ts
+++ b/packages/core/inbox/ws-updaters.ts
@@ -169,6 +169,37 @@ export async function onInboxIssueDeleted(
]);
}
+// The delete mutations' own inbox cleanup. The deleting client cannot count
+// on its `issue:deleted` echo arriving (a proxied deployment can drop the
+// socket silently), and the inbox list it loaded before the delete keeps rows
+// whose issue no longer exists — clicking one routes to a 404. Mirrors
+// `onInboxIssueDeleted`'s DB-cascade prune for a batch, plus the mutation
+// write discipline the update mutations already follow: a list response that
+// was on the wire before the delete lands on top of the prune and
+// resurrects the rows, so the lists are cancelled first and owed a re-read
+// when that interrupted a request (see `cancelInboxLists`).
+export async function onInboxIssuesDeleted(
+ qc: QueryClient,
+ wsId: string,
+ issueIds: string[],
+) {
+ if (issueIds.length === 0) return;
+ const interrupted = cancelInboxLists(qc, wsId);
+ const deleted = new Set(issueIds);
+ patchInboxLists(qc, wsId, (items) => {
+ const next = items.filter((i) => i.issue_id === null || !deleted.has(i.issue_id));
+ return next.length === items.length ? items : next;
+ });
+ const refreshes: Promise<unknown>[] = [
+ onInboxSummaryInvalidate(qc),
+ refreshInboxQuery(qc, inboxKeys.pages(wsId)),
+ refreshInboxQuery(qc, inboxKeys.lookup(wsId)),
+ refreshInboxQuery(qc, inboxKeys.facets(wsId)),
+ ];
+ if (interrupted) refreshes.push(onInboxInvalidate(qc, wsId));
+ await Promise.all(refreshes);
+}
+
// An issue field the archive filters and counts on changed. Loaded rows are
// patched in place, but which groups match and the facet counts are decided
// by the server: an issue that newly matches a filter would never appear, and
diff --git a/packages/core/issues/mutations.test.tsx b/packages/core/issues/mutations.test.tsx
index de37f6dd66..090714b8a5 100644
--- a/packages/core/issues/mutations.test.tsx
+++ b/packages/core/issues/mutations.test.tsx
@@ -11,10 +11,12 @@ import { configStore } from "../config";
import type { ApiClient } from "../api/client";
import { createQueryClient } from "../query-client";
import {
+ useBatchDeleteIssues,
useBatchUpdateIssues,
useCreateComment,
useCreateCommentSubIssue,
useDeleteComment,
+ useDeleteIssue,
useResolveComment,
useUpdateComment,
useUpdateIssue,
@@ -826,6 +828,124 @@ describe("useBatchUpdateIssues — optimistic patch covers filtered boards too",
// request was carrying — here a new notification — must be re-read once the
// write settles, or the unread badge counts a row the list never shows. The
// cancel primitive itself is covered in inbox/ws-updaters.test.ts.
+describe("deleting issues prunes the deleting client's Inbox list", () => {
+ // Regression: an inbox loaded before the delete kept rows whose issue no
+ // longer existed once the delete committed. The WS echo (`issue:deleted` →
+ // `onInboxIssueDeleted`) is the backstop, not the plan — a proxied
+ // deployment can drop the socket silently, and clicking a leftover row
+ // routed to a 404. The delete mutations now prune the inbox caches
+ // themselves, with no WS event involved in these tests.
+ const kept = makeInboxItem("n1", "issue-3");
+ const doomed = makeInboxItem("n2", "issue-1");
+ const doomedArchived = makeInboxItem("n3", "issue-2", { archived: true });
+
+ let qc: QueryClient;
+ const unmounts: Array<() => void> = [];
+
+ function renderDeleteHooks() {
+ const hooks = renderHook(
+ () => ({ single: useDeleteIssue(), batch: useBatchDeleteIssues() }),
+ { wrapper: createWrapper(qc) },
+ );
+ unmounts.push(hooks.unmount);
+ return hooks.result;
+ }
+ type DeleteHooks = ReturnType<typeof renderDeleteHooks>["current"];
+
+ function seedInbox() {
+ qc.setQueryData<InboxItem[]>(inboxKeys.list(WS_ID), [kept, doomed]);
+ qc.setQueryData<InboxItem[]>(inboxKeys.archived(WS_ID), [doomedArchived]);
+ }
+
+ function mockDeleteApi({
+ fail = false,
+ deleted = 2,
+ }: { fail?: boolean; deleted?: number } = {}) {
+ const settle = <T,>(value: T) =>
+ fail ? Promise.reject(new Error("boom")) : Promise.resolve(value);
+ setApiInstance({
+ listInbox: () => Promise.resolve([kept]),
+ deleteIssue: () => settle(undefined),
+ batchDeleteIssues: () => settle({ deleted }),
+ } as unknown as ApiClient);
+ }
+
+ beforeEach(() => {
+ qc = createQueryClient();
+ });
+
+ afterEach(() => {
+ unmounts.splice(0).forEach((unmount) => unmount());
+ qc.clear();
+ });
+
+ it.each([
+ {
+ name: "useDeleteIssue",
+ del: (hooks: DeleteHooks) => hooks.single.mutateAsync("issue-1"),
+ // Only issue-1 went: the archived row for issue-2 survives it.
+ archivedAfter: ["n3"],
+ },
+ {
+ name: "useBatchDeleteIssues",
+ del: (hooks: DeleteHooks) =>
+ hooks.batch.mutateAsync(["issue-1", "issue-2"]),
+ archivedAfter: [],
+ },
+ ])("$name removes the deleted issues' inbox rows without any WS event", async ({ del, archivedAfter }) => {
+ mockDeleteApi();
+ seedInbox();
+ const hooks = renderDeleteHooks();
+
+ await act(async () => {
+ await del(hooks.current);
+ });
+
+ expect(
+ qc.getQueryData<InboxItem[]>(inboxKeys.list(WS_ID))?.map((i) => i.id),
+ ).toEqual(["n1"]);
+ expect(
+ qc.getQueryData<InboxItem[]>(inboxKeys.archived(WS_ID))?.map((i) => i.id),
+ ).toEqual(archivedAfter);
+ });
+
+ it("useBatchDeleteIssues re-reads the whole inbox when the server skipped part of the batch", async () => {
+ mockDeleteApi({ deleted: 1 });
+ seedInbox();
+ const hooks = renderDeleteHooks();
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
+
+ await act(async () => {
+ await hooks.current.batch.mutateAsync(["issue-1", "issue-2"]);
+ });
+
+ // Which rows survived is unknowable client-side (the server reports only
+ // the count), so nothing is pruned by id — the lists and the unread
+ // summary are simply re-read.
+ await waitFor(() =>
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: inboxKeys.all(WS_ID) }),
+ );
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: inboxKeys.unreadSummary() });
+ });
+
+ it("a failed delete leaves the inbox rows untouched", async () => {
+ mockDeleteApi({ fail: true });
+ seedInbox();
+ const hooks = renderDeleteHooks();
+
+ await act(async () => {
+ await hooks.current.single.mutateAsync("issue-1").catch(() => {});
+ });
+
+ expect(
+ qc.getQueryData<InboxItem[]>(inboxKeys.list(WS_ID))?.map((i) => i.id),
+ ).toEqual(["n1", "n2"]);
+ expect(
+ qc.getQueryData<InboxItem[]>(inboxKeys.archived(WS_ID))?.map((i) => i.id),
+ ).toEqual(["n3"]);
+ });
+});
+
describe("status / priority writes re-read an Inbox list they left behind", () => {
const readItem = makeInboxItem("n1", "issue-1", {
read: true,
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index 9577927935..f43a3d6fa8 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -14,6 +14,8 @@ import {
cancelInboxLists,
isInboxListRequestInFlight,
onInboxInvalidate,
+ onInboxIssuesDeleted,
+ onInboxSummaryInvalidate,
} from "../inbox/ws-updaters";
import {
applyIssueChange,
@@ -504,6 +506,10 @@ export function useDeleteIssue() {
onSuccess: (_data, id, ctx) => {
useRecentContextStore.getState().forgetContext(wsId, { type: "issue", id });
cleanupDeletedIssueCaches(qc, wsId, id, ctx?.metadata);
+ // The deleting client's own inbox rows go with the issue; the WS echo
+ // (`issue:deleted` → `onInboxIssueDeleted`) is the backstop, not the
+ // plan — a dropped socket would leave ghost rows that 404 on click.
+ void onInboxIssuesDeleted(qc, wsId, [id]);
},
onSettled: (_data, _err, _id, ctx) => {
qc.invalidateQueries({ queryKey: issueKeys.list(wsId) });
@@ -799,6 +805,9 @@ export function useBatchDeleteIssues() {
forgetContext(wsId, { type: "issue", id });
cleanupDeletedIssueCaches(qc, wsId, id, ctx?.metadataById.get(id));
}
+ // Same inbox ownership as the single delete: prune this client's rows
+ // now instead of waiting for the `issue:deleted` echoes.
+ void onInboxIssuesDeleted(qc, wsId, ids);
return;
}
@@ -827,6 +836,11 @@ export function useBatchDeleteIssues() {
}
qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });
invalidateDeletedIssueDependentCaches(qc, wsId);
+ // The server skipped some of the batch and only reports the count, so
+ // which inbox rows survived is unknowable client-side — re-read the
+ // inbox instead of pruning by id.
+ void onInboxInvalidate(qc, wsId);
+ void onInboxSummaryInvalidate(qc);
},
onSettled: (_data, _err, _ids, ctx) => {
qc.invalidateQueries({ queryKey: issueKeys.list(wsId) });