Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(chat): preserve workspace switches from open sessions (#8928)
Frezc4736a85d41b9
diff --git a/packages/views/chat/chat-page.test.tsx b/packages/views/chat/chat-page.test.tsxindex af1a8871e1..25f9f3a941 100644--- a/packages/views/chat/chat-page.test.tsx+++ b/packages/views/chat/chat-page.test.tsx@@ -3,7 +3,7 @@import { StrictMode } from "react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { describe, it, expect, vi, beforeEach } from "vitest";-import { fireEvent, render, screen } from "@testing-library/react";+import { act, fireEvent, render, screen } from "@testing-library/react";import type { Agent } from "@multica/core/types";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../locales/en/common.json";@@ -83,8 +83,14 @@ vi.mock("@multica/ui/hooks/use-mobile", () => ({useIsCompact: () => layout.width < 1024,}));vi.mock("@multica/core/paths", () => ({+ useRequiredWorkspaceSlug: () => "acme",useWorkspacePaths: () => ({ chat: () => "/acme/chat" }),}));+const platformWorkspace = vi.hoisted(() => ({ slug: "acme" }));+vi.mock("@multica/core/platform", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/platform")>()),+ getCurrentSlug: () => platformWorkspace.slug,+}));// The store mock is REACTIVE like real Zustand: setActiveSession replaces the// snapshot and notifies subscribers, and the controller mock subscribes via@@ -202,7 +208,7 @@ const NO_ACCESS_MSG = "You don't have access to chat with this agent.";function renderPage(search: string, { strict = false } = {}) {const replace = vi.fn();- const navigation: NavigationAdapter = {+ let navigation: NavigationAdapter = {push: vi.fn(),replace,back: vi.fn(),@@ -229,7 +235,20 @@ function renderPage(search: string, { strict = false } = {}) {return strict ? <StrictMode>{page}</StrictMode> : page;};const view = render(makeUi());- return { replace, rerender: () => view.rerender(makeUi()) };+ return {+ replace,+ rerender: (+ { pathname, search }: { pathname?: string; search?: string } = {},+ ) => {+ navigation = {+ ...navigation,+ pathname: pathname ?? navigation.pathname,+ searchParams:+ search === undefined ? navigation.searchParams : new URLSearchParams(search),+ };+ view.rerender(makeUi());+ },+ };}beforeEach(() => {@@ -238,9 +257,115 @@ beforeEach(() => {storeListeners.clear();availableAgentsRef.current = [agent];agentsSettledRef.current = true;+ platformWorkspace.slug = "acme";layout.width = DESKTOP;});+describe("ChatPage URL synchronization", () => {+ it.each(["/globex/issues", "/acme/issues"])(+ "does not redirect back to chat when the retained page observes %s",+ (pathname) => {+ const { replace, rerender } = renderPage("session=session-1");+ expect(storeRef.current.activeSessionId).toBe("session-1");+ mockSetActiveSession.mockClear();++ // App Router can retain the outgoing page after the shared navigation+ // adapter has already published the destination URL.+ rerender({ pathname, search: "" });++ expect(replace).not.toHaveBeenCalled();+ expect(mockSetActiveSession).not.toHaveBeenCalled();+ },+ );++ it.each([null, "session-3"])(+ "does not write the rehydrated session %s into the outgoing workspace's URL",+ (sessionId) => {+ const { replace, rerender } = renderPage("session=session-1");+ rerender({ pathname: "/globex/issues" });+ mockSetActiveSession.mockClear();+ replace.mockClear();++ act(() => {+ mockSetActiveSession(sessionId);+ });++ expect(storeRef.current.activeSessionId).toBe(sessionId);+ expect(mockSetActiveSession).toHaveBeenCalledTimes(1);+ expect(replace).not.toHaveBeenCalled();+ },+ );++ it.each([null, "session-3"])(+ "ignores rehydration to %s before the destination pathname commits",+ (sessionId) => {+ const { replace } = renderPage("session=session-1");+ mockSetActiveSession.mockClear();++ // The incoming layout can rehydrate the shared store while the+ // outgoing page's navigation adapter still reports /acme/chat.+ platformWorkspace.slug = "globex";+ act(() => {+ mockSetActiveSession(sessionId);+ });++ expect(storeRef.current.activeSessionId).toBe(sessionId);+ expect(mockSetActiveSession).toHaveBeenCalledTimes(1);+ expect(replace).not.toHaveBeenCalled();+ },+ );++ it("resumes synchronization when returning to the same chat URL", () => {+ const { replace, rerender } = renderPage("session=session-1");+ rerender({ pathname: "/globex/issues", search: "session=session-1" });+ act(() => {+ mockSetActiveSession("session-2");+ });+ replace.mockClear();+ mockSetActiveSession.mockClear();++ rerender({ pathname: "/acme/chat" });++ expect(mockSetActiveSession).toHaveBeenCalledWith("session-1");+ expect(storeRef.current.activeSessionId).toBe("session-1");+ expect(replace).not.toHaveBeenCalled();+ });++ it("mirrors thread selection and clearing while the chat route is current", () => {+ const { replace } = renderPage("session=session-1");++ act(() => {+ mockSetActiveSession("session-2");+ });+ expect(replace).toHaveBeenLastCalledWith("/acme/chat?session=session-2");++ act(() => {+ mockSetActiveSession(null);+ });+ expect(replace).toHaveBeenLastCalledWith("/acme/chat");+ });++ it.each(["pathname", "rehydration"])(+ "does not consume a pending agent link after workspace switching starts via %s",+ (transition) => {+ availableAgentsRef.current = [];+ agentsSettledRef.current = false;+ const { replace, rerender } = renderPage("agent=agent-1");++ availableAgentsRef.current = [agent];+ agentsSettledRef.current = true;+ if (transition === "rehydration") platformWorkspace.slug = "globex";+ rerender({+ pathname: transition === "pathname" ? "/globex/chat" : "/acme/chat",+ });++ expect(mockStartNewChat).not.toHaveBeenCalled();+ expect(mockToastError).not.toHaveBeenCalled();+ expect(replace).not.toHaveBeenCalled();+ },+ );+});+describe("ChatPage ?agent= deep link", () => {it("starts a new chat with the linked agent and strips the param", () => {const { replace } = renderPage("agent=agent-1");diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsxindex 3fc6eb1cd6..b84b2fddbc 100644--- a/packages/views/chat/chat-page.tsx+++ b/packages/views/chat/chat-page.tsx@@ -11,7 +11,8 @@ import {ResizableHandle,} from "@multica/ui/components/ui/resizable";import { useIsCompact } from "@multica/ui/hooks/use-mobile";-import { useWorkspacePaths } from "@multica/core/paths";+import { useRequiredWorkspaceSlug, useWorkspacePaths } from "@multica/core/paths";+import { getCurrentSlug } from "@multica/core/platform";import { useChatStore } from "@multica/core/chat";import { chatQuickActionsPendingOptions } from "@multica/core/chat/queries";import { useRegenerateChatQuickActions } from "@multica/core/chat/mutations";@@ -57,11 +58,19 @@ import { RuntimeRequiredBanner } from "./components/runtime-required-banner";*/export function ChatPage() {const { t } = useT("chat");- const { searchParams, replace } = useNavigation();+ const { pathname, searchParams, replace } = useNavigation();+ const workspaceSlug = useRequiredWorkspaceSlug();const wsPaths = useWorkspacePaths();+ // App Router can retain this page after navigation. Once the URL belongs+ // to another route, this instance must stop reconciling shared chat state.+ // Also check the live workspace mirror in each effect: the incoming layout+ // can rehydrate the store before this page observes the destination URL.+ const isCurrentChatRoute = pathname === wsPaths.chat();const isCompact = useIsCompact();- const c = useChatController({ isActive: true });+ const c = useChatController({+ isActive: isCurrentChatRoute && getCurrentSlug() === workspaceSlug,+ });const { data: quickActionsPending = null } = useQuery(chatQuickActionsPendingOptions(c.activeSessionId ?? ""),);@@ -100,22 +109,24 @@ export function ChatPage() {// URL → store: deep link, refresh, notification click, back/forward.useEffect(() => {+ if (!isCurrentChatRoute || getCurrentSlug() !== workspaceSlug) return;if (urlSession !== useChatStore.getState().activeSessionId) {c.setActiveSession(urlSession);}- // eslint-disable-next-line react-hooks/exhaustive-deps -- react to URL only- }, [urlSession]);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- reconcile URL/route changes, not store updates+ }, [isCurrentChatRoute, workspaceSlug, urlSession]);// store → URL: thread selection, "new chat", and sessions created by sending.useEffect(() => {+ if (!isCurrentChatRoute || getCurrentSlug() !== workspaceSlug) return;const live = useChatStore.getState().activeSessionId;const current = searchParams.get("session") || null;if (live !== current) {const base = wsPaths.chat();replace(live ? `${base}?session=${live}` : base);}- // eslint-disable-next-line react-hooks/exhaustive-deps -- react to store only- }, [c.activeSessionId]);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- reconcile store/route changes, not URL updates+ }, [isCurrentChatRoute, workspaceSlug, c.activeSessionId]);const { defaultLayout, onLayoutChanged } = useDefaultLayout({id: "multica_chat_layout",@@ -187,6 +198,7 @@ export function ChatPage() {// that surfaces the agent cannot start a chat without a fresh click. While// the queries are still loading the intent simply stays pending.useEffect(() => {+ if (!isCurrentChatRoute || getCurrentSlug() !== workspaceSlug) return;if (!urlAgent) {consumedAgentIntent.current = null;return;@@ -205,7 +217,7 @@ export function ChatPage() {replace(wsPaths.chat());}// eslint-disable-next-line react-hooks/exhaustive-deps -- consume when the URL param or the resolving agent list changes- }, [urlAgent, c.availableAgents, c.agentsSettled]);+ }, [isCurrentChatRoute, workspaceSlug, urlAgent, c.availableAgents, c.agentsSettled]);const newChatButton = (<NewChatButtondiff --git a/packages/views/chat/components/use-chat-controller.test.tsx b/packages/views/chat/components/use-chat-controller.test.tsxindex 4af687caf7..ca42c4d3f7 100644--- a/packages/views/chat/components/use-chat-controller.test.tsx+++ b/packages/views/chat/components/use-chat-controller.test.tsx@@ -84,6 +84,9 @@ const h = vi.hoisted(() => {});vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/platform", () => ({+ getCurrentWsId: () => "ws-1",+}));vi.mock("@multica/core/auth", () => ({useAuthStore: (sel: (s: { user: { id: string } }) => unknown) =>sel({ user: { id: "user-1" } }),diff --git a/packages/views/chat/components/use-chat-controller.ts b/packages/views/chat/components/use-chat-controller.tsindex 8018c63af4..8ecf5bfd54 100644--- a/packages/views/chat/components/use-chat-controller.ts+++ b/packages/views/chat/components/use-chat-controller.ts@@ -9,6 +9,7 @@ import {import { toast } from "sonner";import { useWorkspaceId } from "@multica/core/hooks";import { useAuthStore } from "@multica/core/auth";+import { getCurrentWsId } from "@multica/core/platform";import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";import { projectListOptions } from "@multica/core/projects/queries";import { canAssignAgent } from "../../issues/components/pickers/assignee-picker";@@ -313,12 +314,14 @@ export function useChatController(opts?: { isActive?: boolean }) {// A project may be deleted on another client while this workspace's next// chat preference is still persisted locally. Normalize it as soon as the// authoritative project list settles so a future send cannot carry a stale- // selection.+ // selection. An outgoing route can retain its queries after the shared+ // store has rehydrated another workspace; only clean up our own namespace.useEffect(() => {+ if (getCurrentWsId() !== wsId) return;if (!projectsLoaded || !selectedProjectId) return;if (projects.some((project) => project.id === selectedProjectId)) return;setSelectedProjectId(null);- }, [projectsLoaded, projects, selectedProjectId, setSelectedProjectId]);+ }, [wsId, projectsLoaded, projects, selectedProjectId, setSelectedProjectId]);const qc = useQueryClient();const createSession = useCreateChatSession();@@ -475,12 +478,13 @@ export function useChatController(opts?: { isActive?: boolean }) {// rendering an editable empty chat whose send would POST into a nonexistent// session. Lives in the shared controller so every surface self-heals.useEffect(() => {+ if (getCurrentWsId() !== wsId) return;if (!activeSessionId || !sessionsLoaded) return;if (sessions.some((s) => s.id === activeSessionId)) return;if (hasInFlightPendingTask(qc, activeSessionId)) return;uiLogger.info("clearing dangling activeSessionId", { sessionId: activeSessionId });setActiveSession(null);- }, [activeSessionId, sessionsLoaded, sessions, qc, setActiveSession]);+ }, [wsId, activeSessionId, sessionsLoaded, sessions, qc, setActiveSession]);// Upload transport moved into the coordinated-upload engine inside ChatInput// (MUL-5181 L2); surfaces only forward whether the affordance exists.diff --git a/packages/views/chat/components/use-chat-controller.workspace.test.tsx b/packages/views/chat/components/use-chat-controller.workspace.test.tsxnew file mode 100644index 0000000000..e8b1713862--- /dev/null+++ b/packages/views/chat/components/use-chat-controller.workspace.test.tsx@@ -0,0 +1,167 @@+import { useLayoutEffect, type ReactNode } from "react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createChatStore, registerChatStore } from "@multica/core/chat";+import { setCurrentWorkspace } from "@multica/core/platform";+import type { ChatSession, Project, StorageAdapter } from "@multica/core/types";+import { useChatController } from "./use-chat-controller";++const route = vi.hoisted(() => ({ workspaceId: "ws-source", isActive: true }));+const data = vi.hoisted(() => ({+ sessions: {} as Record<string, ChatSession[]>,+ projects: {} as Record<string, Project[]>,+}));++vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => route.workspaceId,+}));+vi.mock("@multica/core/auth", () => ({+ useAuthStore: (selector: (state: { user: { id: string } }) => unknown) =>+ selector({ user: { id: "user-1" } }),+}));+vi.mock("@multica/core/agents", () => ({+ isAgentRuntimeBound: () => false,+ useAgentPresenceDetail: () => ({ availability: "online" }),+ useCustomizeConversationStartersHref: () => null,+ useWorkspaceAgentAvailability: () => "available",+}));+vi.mock("../../common/use-app-foreground", () => ({+ useAppForeground: () => true,+}));+vi.mock("../../i18n", () => ({ useT: () => ({ t: () => "x" }) }));+vi.mock("@tanstack/react-query", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),+ useQuery: ({ queryKey }: { queryKey: readonly unknown[] }) => {+ const wsId = queryKey[1] as string;+ if (queryKey.includes("sessions")) {+ return { data: data.sessions[wsId] ?? [], isSuccess: true };+ }+ if (queryKey[0] === "projects") {+ return { data: data.projects[wsId] ?? [], isSuccess: true };+ }+ if (queryKey.includes("draft-restores") || queryKey.includes("pending-task")) {+ return { data: null, isSuccess: true };+ }+ return { data: [], isSuccess: true };+ },+ useInfiniteQuery: () => ({+ data: undefined,+ isLoading: false,+ fetchNextPage: vi.fn(),+ hasNextPage: false,+ isFetchingNextPage: false,+ }),+}));++function session(id: string, workspaceId: string): ChatSession {+ return {+ id,+ workspace_id: workspaceId,+ creator_id: "user-1",+ agent_id: "agent-1",+ title: id,+ status: "active",+ has_unread: false,+ unread_count: 0,+ last_message: null,+ pinned: false,+ created_at: "2026-09-28T00:00:00Z",+ updated_at: "2026-09-28T00:00:00Z",+ };+}++describe("useChatController workspace rehydration", () => {+ let storage: StorageAdapter;+ let store: ReturnType<typeof createChatStore>;+ let queryClient: QueryClient;+ const sourceSession = session("source-session", "ws-source");+ const targetSession = session("target-session", "ws-target");+ const targetProject = { id: "target-project", workspace_id: "ws-target" } as Project;++ function wrapper({ children }: { children: ReactNode }) {+ return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;+ }++ beforeEach(async () => {+ route.workspaceId = "ws-source";+ route.isActive = true;+ data.sessions = { "ws-source": [sourceSession], "ws-target": [targetSession] };+ data.projects = { "ws-source": [], "ws-target": [targetProject] };+ await act(async () => setCurrentWorkspace("source", "ws-source"));+ const values = new Map<string, string>([+ ["multica:chat:activeSessionId:source", sourceSession.id],+ ["multica:chat:activeSessionId:target", targetSession.id],+ ["multica:chat:selectedProjectId:target", targetProject.id],+ ]);+ storage = {+ getItem: (key) => values.get(key) ?? null,+ setItem: (key, value) => { values.set(key, value); },+ removeItem: (key) => { values.delete(key); },+ };+ store = createChatStore({ storage });+ registerChatStore(store);+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ });++ afterEach(async () => {+ cleanup();+ queryClient.clear();+ await act(async () => setCurrentWorkspace(null, null));+ });++ function expectTargetSelection() {+ expect(store.getState().activeSessionId).toBe(targetSession.id);+ expect(storage.getItem("multica:chat:activeSessionId:target")).toBe(targetSession.id);+ expect(store.getState().selectedProjectId).toBe(targetProject.id);+ expect(storage.getItem("multica:chat:selectedProjectId:target")).toBe(targetProject.id);+ expect(storage.getItem("multica:chat:activeSessionId:source")).toBe(sourceSession.id);+ }++ it.each([false, true])("preserves the target selection while the source controller remains mounted (isActive=%s)", async (isActive) => {+ const { result } = renderHook(() => useChatController({ isActive: route.isActive }), { wrapper });+ expect(result.current.currentSession?.id).toBe(sourceSession.id);++ await act(async () => {+ route.isActive = isActive;+ setCurrentWorkspace("target", "ws-target");+ });++ // The outgoing route still owns the source queries while the real store+ // has already read the target namespace through the rehydration callback.+ expectTargetSelection();+ });++ it("does not delete target storage when the workspace changes between render and effects", async () => {+ data.sessions["ws-source"] = [];+ function SwitchBeforeEffects({ children }: { children: ReactNode }) {+ useLayoutEffect(() => setCurrentWorkspace("target", "ws-target"), []);+ return wrapper({ children });+ }++ renderHook(() => useChatController({ isActive: true }), { wrapper: SwitchBeforeEffects });+ await act(async () => { await Promise.resolve(); });++ expectTargetSelection();+ });++ it("still clears deleted selections after the controller enters the target workspace", async () => {+ const { rerender } = renderHook(() => useChatController({ isActive: route.isActive }), { wrapper });+ await act(async () => {+ setCurrentWorkspace("target", "ws-target");+ });+ route.workspaceId = "ws-target";+ rerender();+ expectTargetSelection();++ data.sessions["ws-target"] = [];+ data.projects["ws-target"] = [];+ rerender();++ expect(store.getState().activeSessionId).toBeNull();+ expect(store.getState().selectedProjectId).toBeNull();+ expect(storage.getItem("multica:chat:activeSessionId:target")).toBeNull();+ expect(storage.getItem("multica:chat:selectedProjectId:target")).toBeNull();+ expect(storage.getItem("multica:chat:activeSessionId:source")).toBe(sourceSession.id);+ });+});