Skip to content

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

Go

fix(core): stop leaking recent issues across workspaces (#2403)

YYClaw2e5e3a71895c
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index b8561e83f1..e28d8ec709 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -109,7 +109,7 @@ export function useCreateIssue() {
);
// Surface the just-created issue in cmd+k's Recent list without
// requiring the user to open it first.
- useRecentIssuesStore.getState().recordVisit(newIssue.id);
+ useRecentIssuesStore.getState().recordVisit(wsId, newIssue.id);
// Invalidate parent's children query so sub-issues list updates immediately
if (newIssue.parent_issue_id) {
qc.invalidateQueries({ queryKey: issueKeys.children(wsId, newIssue.parent_issue_id) });
diff --git a/packages/core/issues/stores/index.ts b/packages/core/issues/stores/index.ts
index 3dd7302c79..a62c974b72 100644
--- a/packages/core/issues/stores/index.ts
+++ b/packages/core/issues/stores/index.ts
@@ -1,7 +1,11 @@
export { useIssueSelectionStore } from "./selection-store";
export { useCreateModeStore, type CreateMode } from "./create-mode-store";
export { useIssueDraftStore } from "./draft-store";
-export { useRecentIssuesStore, type RecentIssueEntry } from "./recent-issues-store";
+export {
+ useRecentIssuesStore,
+ selectRecentIssues,
+ type RecentIssueEntry,
+} from "./recent-issues-store";
export {
ViewStoreProvider,
useViewStore,
diff --git a/packages/core/issues/stores/recent-issues-store.test.ts b/packages/core/issues/stores/recent-issues-store.test.ts
new file mode 100644
index 0000000000..2cc21fc21f
--- /dev/null
+++ b/packages/core/issues/stores/recent-issues-store.test.ts
@@ -0,0 +1,74 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import { useRecentIssuesStore, selectRecentIssues } from "./recent-issues-store";
+
+beforeEach(() => {
+ useRecentIssuesStore.setState({ byWorkspace: {} });
+});
+
+describe("useRecentIssuesStore.recordVisit", () => {
+ it("keeps visits namespaced by workspace id", () => {
+ const { recordVisit } = useRecentIssuesStore.getState();
+ recordVisit("ws-a", "issue-1");
+ recordVisit("ws-b", "issue-2");
+
+ const state = useRecentIssuesStore.getState().byWorkspace;
+ expect(state["ws-a"]?.map((e) => e.id)).toEqual(["issue-1"]);
+ expect(state["ws-b"]?.map((e) => e.id)).toEqual(["issue-2"]);
+ });
+
+ it("moves the most recent visit to the front and dedupes", () => {
+ const { recordVisit } = useRecentIssuesStore.getState();
+ recordVisit("ws-a", "issue-1");
+ recordVisit("ws-a", "issue-2");
+ recordVisit("ws-a", "issue-1");
+
+ const ids = useRecentIssuesStore
+ .getState()
+ .byWorkspace["ws-a"]?.map((e) => e.id);
+ expect(ids).toEqual(["issue-1", "issue-2"]);
+ });
+
+ it("caps each workspace's bucket at 20 entries", () => {
+ const { recordVisit } = useRecentIssuesStore.getState();
+ for (let i = 0; i < 25; i++) recordVisit("ws-a", `issue-${i}`);
+ expect(useRecentIssuesStore.getState().byWorkspace["ws-a"]).toHaveLength(20);
+ });
+});
+
+describe("useRecentIssuesStore.pruneWorkspaces", () => {
+ it("drops buckets for workspaces not in the active set", () => {
+ const { recordVisit, pruneWorkspaces } = useRecentIssuesStore.getState();
+ recordVisit("ws-a", "issue-1");
+ recordVisit("ws-b", "issue-2");
+ recordVisit("ws-c", "issue-3");
+
+ pruneWorkspaces(["ws-a", "ws-c"]);
+ const state = useRecentIssuesStore.getState().byWorkspace;
+ expect(Object.keys(state).sort()).toEqual(["ws-a", "ws-c"]);
+ });
+
+ it("is a no-op when every bucket is still active", () => {
+ const { recordVisit, pruneWorkspaces } = useRecentIssuesStore.getState();
+ recordVisit("ws-a", "issue-1");
+ const before = useRecentIssuesStore.getState().byWorkspace;
+ pruneWorkspaces(["ws-a"]);
+ expect(useRecentIssuesStore.getState().byWorkspace).toBe(before);
+ });
+});
+
+describe("selectRecentIssues", () => {
+ it("returns the bucket for the given workspace", () => {
+ useRecentIssuesStore.getState().recordVisit("ws-a", "issue-1");
+ const items = selectRecentIssues("ws-a")(useRecentIssuesStore.getState());
+ expect(items.map((e) => e.id)).toEqual(["issue-1"]);
+ });
+
+ it("returns a stable empty array when wsId is null or unknown", () => {
+ const a = selectRecentIssues(null)(useRecentIssuesStore.getState());
+ const b = selectRecentIssues(null)(useRecentIssuesStore.getState());
+ const c = selectRecentIssues("missing")(useRecentIssuesStore.getState());
+ expect(a).toBe(b);
+ expect(a).toBe(c);
+ expect(a).toEqual([]);
+ });
+});
diff --git a/packages/core/issues/stores/recent-issues-store.ts b/packages/core/issues/stores/recent-issues-store.ts
index a77471219f..da74f2db46 100644
--- a/packages/core/issues/stores/recent-issues-store.ts
+++ b/packages/core/issues/stores/recent-issues-store.ts
@@ -2,13 +2,11 @@
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
-import {
- createWorkspaceAwareStorage,
- registerForWorkspaceRehydration,
-} from "../../platform/workspace-storage";
import { defaultStorage } from "../../platform/storage";
const MAX_RECENT_ISSUES = 20;
+const MAX_WORKSPACES = 50;
+const EMPTY: RecentIssueEntry[] = [];
export interface RecentIssueEntry {
id: string;
@@ -16,33 +14,82 @@ export interface RecentIssueEntry {
}
interface RecentIssuesState {
- items: RecentIssueEntry[];
- recordVisit: (id: string) => void;
+ byWorkspace: Record<string, RecentIssueEntry[]>;
+ recordVisit: (wsId: string, id: string) => void;
+ pruneWorkspaces: (activeWsIds: string[]) => void;
}
+// Namespace by workspace id (UUID) instead of namespacing the storage key by
+// slug. The storage-key approach (see createWorkspaceAwareStorage) breaks when
+// a setter fires from a child component's mount-effect before
+// WorkspaceRouteLayout's effect has set the current slug — child effects run
+// before parent effects, so writes land in the un-namespaced bare key and
+// leak across workspaces (bug surfaced by /<slug>/issues firing per-id GETs
+// for recents from other workspaces, most returning 404).
+//
+// Keying on wsId (rather than slug) means the data survives workspace renames
+// and matches the wsId that callers already have via useWorkspaceId().
export const useRecentIssuesStore = create<RecentIssuesState>()(
persist(
(set) => ({
- items: [],
- recordVisit: (id) =>
+ byWorkspace: {},
+ recordVisit: (wsId, id) =>
set((state) => {
- const filtered = state.items.filter((i) => i.id !== id);
+ const bucket = state.byWorkspace[wsId] ?? EMPTY;
+ const filtered = bucket.filter((i) => i.id !== id);
const updated: RecentIssueEntry = { id, visitedAt: Date.now() };
- return {
- items: [updated, ...filtered].slice(0, MAX_RECENT_ISSUES),
+ const nextBucket = [updated, ...filtered].slice(0, MAX_RECENT_ISSUES);
+
+ let nextByWorkspace = {
+ ...state.byWorkspace,
+ [wsId]: nextBucket,
};
+
+ // LRU defense: if pruneWorkspaces never gets a chance to run (offline,
+ // failed list query) and the user touches lots of workspaces, cap the
+ // total to avoid unbounded growth. Evict the workspace whose most
+ // recent visit is the oldest.
+ const ids = Object.keys(nextByWorkspace);
+ if (ids.length > MAX_WORKSPACES) {
+ const oldest = ids.reduce((oldestId, candidateId) => {
+ const a = nextByWorkspace[oldestId]?.[0]?.visitedAt ?? 0;
+ const b = nextByWorkspace[candidateId]?.[0]?.visitedAt ?? 0;
+ return b < a ? candidateId : oldestId;
+ });
+ const { [oldest]: _, ...rest } = nextByWorkspace;
+ nextByWorkspace = rest;
+ }
+
+ return { byWorkspace: nextByWorkspace };
+ }),
+ pruneWorkspaces: (activeWsIds) =>
+ set((state) => {
+ const allow = new Set(activeWsIds);
+ let changed = false;
+ const next: Record<string, RecentIssueEntry[]> = {};
+ for (const [wsId, items] of Object.entries(state.byWorkspace)) {
+ if (allow.has(wsId)) next[wsId] = items;
+ else changed = true;
+ }
+ return changed ? { byWorkspace: next } : state;
}),
}),
{
name: "multica_recent_issues",
- storage: createJSONStorage(() =>
- createWorkspaceAwareStorage(defaultStorage),
- ),
- partialize: (state) => ({ items: state.items }),
+ storage: createJSONStorage(() => defaultStorage),
+ partialize: (state) => ({ byWorkspace: state.byWorkspace }),
+ // v0 stored a flat `items` array under the bare key (or, when the
+ // workspace slug happened to be set at write time, under
+ // `multica_recent_issues:<slug>`). Both shapes are unsafe to surface
+ // because v0 entries don't know which workspace they belonged to —
+ // drop them and let the cache repopulate as the user visits issues.
+ version: 1,
+ migrate: () => ({ byWorkspace: {} }),
},
),
);
-registerForWorkspaceRehydration(() =>
- useRecentIssuesStore.persist.rehydrate(),
-);
+export function selectRecentIssues(wsId: string | null) {
+ return (state: RecentIssuesState) =>
+ wsId ? (state.byWorkspace[wsId] ?? EMPTY) : EMPTY;
+}
diff --git a/packages/core/platform/workspace-storage.test.ts b/packages/core/platform/workspace-storage.test.ts
index e6c26d64b5..b04ef6a547 100644
--- a/packages/core/platform/workspace-storage.test.ts
+++ b/packages/core/platform/workspace-storage.test.ts
@@ -20,13 +20,19 @@ afterEach(() => {
});
describe("workspace-aware storage", () => {
- it("uses plain key when no workspace is set", () => {
+ it("drops writes and returns null for reads when no workspace is set", () => {
const adapter = mockAdapter();
setCurrentWorkspace(null, null);
const storage = createWorkspaceAwareStorage(adapter);
storage.setItem("draft", "data");
- expect(adapter.setItem).toHaveBeenCalledWith("draft", "data");
+ expect(adapter.setItem).not.toHaveBeenCalled();
+
+ expect(storage.getItem("draft")).toBeNull();
+ expect(adapter.getItem).not.toHaveBeenCalled();
+
+ storage.removeItem("draft");
+ expect(adapter.removeItem).not.toHaveBeenCalled();
});
it("namespaces key with slug when workspace is set", () => {
diff --git a/packages/core/platform/workspace-storage.ts b/packages/core/platform/workspace-storage.ts
index 978b01c4d3..ae0993723b 100644
--- a/packages/core/platform/workspace-storage.ts
+++ b/packages/core/platform/workspace-storage.ts
@@ -94,14 +94,24 @@ export function registerForWorkspaceRehydration(fn: () => void) {
/**
* Storage that automatically namespaces keys with the current workspace slug.
* Reads _currentSlug at call time, so it follows workspace switches dynamically.
+ *
+ * When no workspace is active (e.g. zustand persist's initial hydration before
+ * WorkspaceRouteLayout has called setCurrentWorkspace, or a setter firing from
+ * a child component's mount-effect before the parent layout's effect has run),
+ * reads return null and writes are dropped — explicitly NOT a fallback to the
+ * un-namespaced bare key, which used to leak workspace-scoped data across
+ * workspaces. Persisted stores get a real read once setCurrentWorkspace
+ * triggers their registered rehydrate fn.
*/
export function createWorkspaceAwareStorage(adapter: StorageAdapter): StateStorage {
- const resolve = (key: string) =>
- _currentSlug ? `${key}:${_currentSlug}` : key;
-
return {
- getItem: (key) => adapter.getItem(resolve(key)),
- setItem: (key, value) => adapter.setItem(resolve(key), value),
- removeItem: (key) => adapter.removeItem(resolve(key)),
+ getItem: (key) =>
+ _currentSlug ? adapter.getItem(`${key}:${_currentSlug}`) : null,
+ setItem: (key, value) => {
+ if (_currentSlug) adapter.setItem(`${key}:${_currentSlug}`, value);
+ },
+ removeItem: (key) => {
+ if (_currentSlug) adapter.removeItem(`${key}:${_currentSlug}`);
+ },
};
}
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 71bab62cca..a6e7afb4f5 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -244,11 +244,18 @@ const mockRecordVisit = vi.fn();
vi.mock("@multica/core/issues/stores", () => ({
useRecentIssuesStore: Object.assign(
(selector?: any) => {
- const state = { items: [], recordVisit: mockRecordVisit };
+ const state = { byWorkspace: {}, recordVisit: mockRecordVisit, pruneWorkspaces: vi.fn() };
return selector ? selector(state) : state;
},
- { getState: () => ({ items: [], recordVisit: mockRecordVisit }) },
+ {
+ getState: () => ({
+ byWorkspace: {},
+ recordVisit: mockRecordVisit,
+ pruneWorkspaces: vi.fn(),
+ }),
+ },
),
+ selectRecentIssues: () => () => [],
useCommentCollapseStore: (selector?: any) => {
const state = {
collapsedByIssue: {},
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 2300190362..ab87e063d1 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -391,9 +391,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
const recordVisit = useRecentIssuesStore((s) => s.recordVisit);
useEffect(() => {
if (issue) {
- recordVisit(issue.id);
+ recordVisit(wsId, issue.id);
}
- }, [issue?.id]); // eslint-disable-line react-hooks/exhaustive-deps
+ }, [issue?.id, wsId]); // eslint-disable-line react-hooks/exhaustive-deps
// Fire `onDelete` once when the issue transitions from loaded to missing.
// Delete goes through a shell-level modal, so the caller (e.g. inbox) can't
diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsx
index ae562c25ad..075739b075 100644
--- a/packages/views/issues/components/issues-page.test.tsx
+++ b/packages/views/issues/components/issues-page.test.tsx
@@ -195,11 +195,18 @@ vi.mock("@multica/core/issues/stores/selection-store", () => ({
vi.mock("@multica/core/issues/stores/recent-issues-store", () => ({
useRecentIssuesStore: Object.assign(
(selector?: any) => {
- const state = { items: [], recordVisit: vi.fn() };
+ const state = { byWorkspace: {}, recordVisit: vi.fn(), pruneWorkspaces: vi.fn() };
return selector ? selector(state) : state;
},
- { getState: () => ({ items: [], recordVisit: vi.fn() }) },
+ {
+ getState: () => ({
+ byWorkspace: {},
+ recordVisit: vi.fn(),
+ pruneWorkspaces: vi.fn(),
+ }),
+ },
),
+ selectRecentIssues: () => () => [],
}));
vi.mock("@multica/core/modals", () => ({
diff --git a/packages/views/layout/use-dashboard-guard.ts b/packages/views/layout/use-dashboard-guard.ts
index e276a25ca7..40afcc5b3d 100644
--- a/packages/views/layout/use-dashboard-guard.ts
+++ b/packages/views/layout/use-dashboard-guard.ts
@@ -11,6 +11,7 @@ import {
useHasOnboarded,
} from "@multica/core/paths";
import { workspaceListOptions } from "@multica/core/workspace";
+import { useRecentIssuesStore } from "@multica/core/issues/stores";
import { useNavigation } from "../navigation";
/**
@@ -63,5 +64,15 @@ export function useDashboardGuard() {
useNavigationStore.getState().onPathChange(pathname);
}, [pathname]);
+ // Drop recent-issues buckets for workspaces the user no longer belongs to.
+ // Runs once the workspace list resolves, and again whenever membership
+ // changes (workspace deleted, user kicked, user left).
+ useEffect(() => {
+ if (!workspaceListFetched) return;
+ useRecentIssuesStore
+ .getState()
+ .pruneWorkspaces(workspaces.map((w) => w.id));
+ }, [workspaceListFetched, workspaces]);
+
return { user, isLoading, workspace };
}
diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsx
index 293a3c73e1..6438c04c35 100644
--- a/packages/views/search/search-command.test.tsx
+++ b/packages/views/search/search-command.test.tsx
@@ -67,12 +67,23 @@ vi.mock("@multica/core/api", () => ({
},
}));
-vi.mock("@multica/core/issues/stores", () => ({
- useRecentIssuesStore: (selector?: (state: { items: typeof mockRecentItems.current }) => unknown) => {
- const state = { items: mockRecentItems.current };
- return selector ? selector(state) : state;
- },
-}));
+vi.mock("@multica/core/issues/stores", () => {
+ const EMPTY: Array<{ id: string; visitedAt: number }> = [];
+ return {
+ useRecentIssuesStore: (
+ selector?: (state: {
+ byWorkspace: Record<string, typeof mockRecentItems.current>;
+ }) => unknown,
+ ) => {
+ const state = { byWorkspace: { "ws-test": mockRecentItems.current } };
+ return selector ? selector(state) : state;
+ },
+ selectRecentIssues:
+ (wsId: string | null) =>
+ (state: { byWorkspace: Record<string, typeof mockRecentItems.current> }) =>
+ wsId ? (state.byWorkspace[wsId] ?? EMPTY) : EMPTY,
+ };
+});
vi.mock("@multica/core", () => ({
useWorkspaceId: () => "ws-test",
diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsx
index 4c4947f22a..7ff4ff316a 100644
--- a/packages/views/search/search-command.tsx
+++ b/packages/views/search/search-command.tsx
@@ -28,7 +28,7 @@ import { useQueries, useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import type { SearchIssueResult, SearchProjectResult } from "@multica/core/types";
import { api } from "@multica/core/api";
-import { useRecentIssuesStore } from "@multica/core/issues/stores";
+import { selectRecentIssues, useRecentIssuesStore } from "@multica/core/issues/stores";
import { issueDetailOptions } from "@multica/core/issues/queries";
import { useWorkspaceId } from "@multica/core";
import { paths, useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
@@ -139,8 +139,8 @@ export function SearchCommand() {
const { push, pathname, getShareableUrl } = useNavigation();
const open = useSearchStore((s) => s.open);
const setOpen = useSearchStore((s) => s.setOpen);
- const recentItems = useRecentIssuesStore((s) => s.items);
const wsId = useWorkspaceId();
+ const recentItems = useRecentIssuesStore(selectRecentIssues(wsId));
const p: WorkspacePaths = useWorkspacePaths();
const { theme, setTheme } = useTheme();
const currentWorkspace = useCurrentWorkspace();