Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(inbox): retain selection recognition across page mounts (#10530)
Bohan Jiang43a849e96fe6
diff --git a/packages/core/inbox/selection-store.ts b/packages/core/inbox/selection-store.tsnew file mode 100644index 0000000000..3a26f3227b--- /dev/null+++ b/packages/core/inbox/selection-store.ts@@ -0,0 +1,18 @@+"use client";++import { create } from "zustand";++interface InboxSelectionState {+ lastResolvedKeyByWorkspace: Record<string, string>;+ rememberResolvedKey: (wsId: string, key: string) => void;+}++// Keep only the last resolved pointer per workspace, for this client run.+// Notification data and its cache lifetime remain owned by TanStack Query.+export const useInboxSelectionStore = create<InboxSelectionState>()((set) => ({+ lastResolvedKeyByWorkspace: {},+ rememberResolvedKey: (wsId, key) =>+ set((state) => state.lastResolvedKeyByWorkspace[wsId] === key ? state : {+ lastResolvedKeyByWorkspace: { ...state.lastResolvedKeyByWorkspace, [wsId]: key },+ }),+}));diff --git a/packages/core/package.json b/packages/core/package.jsonindex 98d94e01e0..a4a1a9c6b3 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -71,6 +71,7 @@"./inbox/queries": "./inbox/queries.ts","./inbox/mutations": "./inbox/mutations.ts","./inbox/filter-store": "./inbox/filter-store.ts",+ "./inbox/selection-store": "./inbox/selection-store.ts","./inbox/ws-updaters": "./inbox/ws-updaters.ts","./notification-preferences": "./notification-preferences/index.ts","./notification-preferences/queries": "./notification-preferences/queries.ts",diff --git a/packages/views/inbox/components/inbox-page-query.test.tsx b/packages/views/inbox/components/inbox-page-query.test.tsxindex 3e6db23784..04c9f7f8c6 100644--- a/packages/views/inbox/components/inbox-page-query.test.tsx+++ b/packages/views/inbox/components/inbox-page-query.test.tsx@@ -6,13 +6,15 @@ import { setApiInstance } from "@multica/core/api";import type { ApiClient } from "@multica/core/api/client";import { EMPTY_INBOX_FILTERS, filterInboxItems, useInboxFilterStore, type InboxFilters } from "@multica/core/inbox/filter-store";import { archivedInboxLookupOptions, inboxKeys } from "@multica/core/inbox/queries";+import { useInboxSelectionStore } from "@multica/core/inbox/selection-store";import { onInboxIssueDeleted, patchInboxIssueProjection } from "@multica/core/inbox/ws-updaters";import type { ArchivedInboxPage } from "@multica/core/types/inbox";import type { InboxItem } from "@multica/core/types";import { InboxPage } from "./inbox-page";vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));-vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));+let workspaceId = "workspace-1";+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => workspaceId }));vi.mock("@multica/core/paths", () => ({useWorkspacePaths: () => ({inbox: () => "/acme/inbox",@@ -79,6 +81,8 @@ function item(overrides: Partial<InboxItem> = {}): InboxItem {let qc: QueryClient;beforeEach(() => {+ workspaceId = "workspace-1";+ useInboxSelectionStore.setState({ lastResolvedKeyByWorkspace: {} });qc = new QueryClient({ defaultOptions: {queries: { retry: false, staleTime: Infinity, gcTime: 0 },mutations: { retry: false },@@ -104,6 +108,107 @@ function deferred<T>() {}const page = (items: InboxItem[]): ArchivedInboxPage => ({ items, hasMore: false, nextCursor: null });+it("stays in Inbox after a failed first load and opens the selection when retry succeeds", async () => {+ useInboxFilterStore.setState({ filtersByWorkspace: {} });+ searchParams.set("issue", "issue-a");+ const listInbox = vi.fn()+ .mockRejectedValueOnce(new Error("Inbox unavailable"))+ .mockResolvedValue([item({ read: true })]);+ setApiInstance({ listInbox, markInboxRead: async () => item({ read: true }), getInboxUnreadSummary: async () => [] } as unknown as ApiClient);++ renderPage();+ await waitFor(() => expect(qc.getQueryState(inboxKeys.list("workspace-1"))?.status).toBe("error"));+ expect(replace).not.toHaveBeenCalled();++ await act(async () => { await qc.refetchQueries({ queryKey: inboxKeys.list("workspace-1") }); });+ expect(await screen.findByTestId("detail")).toHaveTextContent("issue-a");+ expect(replace).not.toHaveBeenCalled();+});++it("clears a remembered selection after leaving Inbox, archiving the read notification and evicting its cache", async () => {+ useInboxFilterStore.setState({ filtersByWorkspace: {} });+ let rows = [item({ read: true })];+ setApiInstance({ listInbox: async () => rows, markInboxRead: async () => rows[0]!, getInboxUnreadSummary: async () => [] } as unknown as ApiClient);+ const first = renderPage();+ fireEvent.click(await screen.findByText("inbox-a"));+ expect(await screen.findByTestId("detail")).toHaveTextContent("issue-a");+ await waitFor(() => expect(qc.isMutating()).toBe(0));+ first.unmount();++ // Cmd+K archive-all-read outside Inbox, or an archive on another client.+ rows = [];+ qc.removeQueries({ queryKey: inboxKeys.list("workspace-1") });+ searchParams = new URLSearchParams("issue=issue-a");+ replace.mockClear();+ renderPage();++ await waitFor(() => expect(replace).toHaveBeenLastCalledWith("/acme/inbox"));+ expect(replace).not.toHaveBeenCalledWith("/acme/issues/issue-a");+});++it.each(["inbox", "archived"])("preserves an unknown shared link in %s", async (view) => {+ useInboxFilterStore.setState({ filtersByWorkspace: {} });+ searchParams = new URLSearchParams(view === "archived" ? "view=archived" : "");+ searchParams.set("issue", "shared-issue");+ setApiInstance({+ listInbox: async () => [],+ listArchivedInboxPage: async () => page([]),+ getInboxUnreadSummary: async () => [],+ } as unknown as ApiClient);+ renderPage();++ await waitFor(() => expect(replace).toHaveBeenLastCalledWith("/acme/issues/shared-issue"));+});++it("remembers workspace A after visiting workspace B and losing A's cached notifications", async () => {+ useInboxFilterStore.setState({ filtersByWorkspace: {} });+ let rows = [item({ read: true })];+ setApiInstance({ listInbox: async () => rows, markInboxRead: async () => rows[0]!, getInboxUnreadSummary: async () => [] } as unknown as ApiClient);+ const first = renderPage();+ fireEvent.click(await screen.findByText("inbox-a"));+ expect(await screen.findByTestId("detail")).toHaveTextContent("issue-a");+ await waitFor(() => expect(qc.isMutating()).toBe(0));+ first.unmount();++ workspaceId = "workspace-2";+ rows = [item({ id: "inbox-b", issue_id: "issue-b", workspace_id: workspaceId, read: true })];+ const second = renderPage();+ fireEvent.click(await screen.findByText("inbox-b"));+ expect(await screen.findByTestId("detail")).toHaveTextContent("issue-b");+ await waitFor(() => expect(qc.isMutating()).toBe(0));+ second.unmount();++ // Switching workspaces lets A's inactive query expire after ten minutes.+ qc.removeQueries({ queryKey: inboxKeys.list("workspace-1") });+ workspaceId = "workspace-1";+ rows = [];+ searchParams = new URLSearchParams("issue=issue-a");+ replace.mockClear();+ renderPage();++ await waitFor(() => expect(replace).toHaveBeenLastCalledWith("/acme/inbox"));+ expect(replace).not.toHaveBeenCalledWith("/acme/issues/issue-a");+});++it("does not reuse another workspace's recognition for an unknown shared link", async () => {+ useInboxFilterStore.setState({ filtersByWorkspace: {} });+ let rows = [item({ read: true })];+ setApiInstance({ listInbox: async () => rows, markInboxRead: async () => rows[0]!, getInboxUnreadSummary: async () => [] } as unknown as ApiClient);+ const first = renderPage();+ fireEvent.click(await screen.findByText("inbox-a"));+ expect(await screen.findByTestId("detail")).toHaveTextContent("issue-a");+ await waitFor(() => expect(qc.isMutating()).toBe(0));+ first.unmount();++ workspaceId = "workspace-2";+ rows = [];+ searchParams = new URLSearchParams("issue=issue-a");+ replace.mockClear();+ renderPage();++ await waitFor(() => expect(replace).toHaveBeenLastCalledWith("/acme/issues/issue-a"));+});+it.each([false, true])("clears an older unread assignment when opening a read row via URL=%s", async (viaUrl) => {useInboxFilterStore.setState({ filtersByWorkspace: {} });if (viaUrl) searchParams.set("issue", "issue-a");diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsxindex a2349f114c..a27897741f 100644--- a/packages/views/inbox/components/inbox-page.test.tsx+++ b/packages/views/inbox/components/inbox-page.test.tsx@@ -4,6 +4,7 @@ import { toast } from "sonner";import { ApiError } from "@multica/core/api";import type { AgentTask, InboxItem } from "@multica/core/types";import { useInboxFilterStore } from "@multica/core/inbox/filter-store";+import { useInboxSelectionStore } from "@multica/core/inbox/selection-store";import { InboxPage } from "./inbox-page";vi.mock("sonner", () => ({@@ -250,6 +251,7 @@ function item(overrides: Partial<InboxItem> = {}): InboxItem {}function reset() {+ useInboxSelectionStore.setState({ lastResolvedKeyByWorkspace: {} });listData.active = [];listData.archived = [];listData.lookup = undefined;diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex e676e3b98c..20e4f735db 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -22,6 +22,7 @@ import {} from "@multica/core/shortcuts";import { isImeComposing } from "@multica/core/utils";import { useIssueDraftStore } from "@multica/core/issues/stores/draft-store";+import { useInboxSelectionStore } from "@multica/core/inbox/selection-store";import {inboxListOptions,archivedInboxPagesOptions,@@ -157,9 +158,10 @@ export function InboxPage() {const isArchivedView = view === "archived";const filters = useInboxFilters(wsId);const clearFilters = useInboxFilterStore((state) => state.clearFilters);- const { data: rawItems = [], isLoading: loading } = useQuery({+ const inboxQuery = useQuery({...inboxListOptions(wsId), enabled: !isArchivedView,});+ const { data: rawItems = [], isLoading: loading } = inboxQuery;const items = useMemo(() => deduplicateInboxItems(rawItems), [rawItems]);// The filters read every notification of an issue, not just its newest.const activeRows = useMemo(() => rawItems.filter((item) => !item.archived), [rawItems]);@@ -291,14 +293,12 @@ export function InboxPage() {// the shell's progress bar covers the swap on both platforms.useReportNavigating(detailSwapping);- // Track the last key we actually resolved against the inbox list. Lets the- // fallback effect distinguish "shared-link to a notification not in our- // inbox" (never resolved → redirect to the issue page) from "item was in- // our inbox and just got removed" (was resolved → stay on /inbox).- const lastResolvedKeyRef = useRef<string>("");+ // Keep recognition across page mounts and query-cache eviction. A remembered+ // selection that disappears stays in Inbox; an unknown shared link still+ // falls back to the issue page.useEffect(() => {- if (selected) lastResolvedKeyRef.current = selectedKey;- }, [selected, selectedKey]);+ if (selected) useInboxSelectionStore.getState().rememberResolvedKey(wsId, selectedKey);+ }, [wsId, selected, selectedKey]);// Both the view and the selection live in the URL, so every write has to// carry the other one — a bare `?issue=` would silently drop the user out of@@ -339,6 +339,7 @@ export function InboxPage() {// A targeted lookup must not hide pages that have already loaded. Its// pending/error states only block resolution of the off-page selection.const viewLoading = isArchivedView ? archivedLoading : loading;+ const viewError = isArchivedView ? archivedError : inboxQuery.isError && !inboxQuery.data;const needsLookup = isArchivedView && !!selectedKey && !selectedOnPage;const lookupLoading = needsLookup && (lookup.isLoading || presence.isLoading);const lookupError = needsLookup && (lookup.isError || presence.isError) && !selected;@@ -350,19 +351,18 @@ export function InboxPage() {// and `onInboxIssueDeleted` pruned the cache), the issue detail would 404// too — clear the selection and stay on /inbox instead.useEffect(() => {- if (viewLoading || lookupLoading || lookupError || (isArchivedView && archivedError)) return;+ if (viewLoading || viewError || lookupLoading || lookupError) return;if (!selectedKey) return;if (selected) return;if (selectionFilteredOut) return;- if (lastResolvedKeyRef.current === selectedKey) {+ if (useInboxSelectionStore.getState().lastResolvedKeyByWorkspace[wsId] === selectedKey) {setSelectedKey("");return;}replace(wsPaths.issueDetail(selectedKey));}, [viewLoading,- isArchivedView,- archivedError,+ viewError,lookupLoading,lookupError,selectedKey,@@ -370,6 +370,7 @@ export function InboxPage() {selectionFilteredOut,replace,wsPaths,+ wsId,setSelectedKey,]);