Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: preserve workspace agent route on refresh (#17361)

AmAzing-0fc09aa5b172
diff --git a/src/features/AgentTasks/shared/taskDetailPath.test.ts b/src/features/AgentTasks/shared/taskDetailPath.test.ts
index 32e0f11e711..3868733114b 100644
--- a/src/features/AgentTasks/shared/taskDetailPath.test.ts
+++ b/src/features/AgentTasks/shared/taskDetailPath.test.ts
@@ -18,6 +18,7 @@ vi.mock('react-router', () => ({
}));
vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ getActiveWorkspaceSlug: () => mocks.activeWorkspaceSlug,
useActiveWorkspaceSlug: () => mocks.activeWorkspaceSlug,
}));
diff --git a/src/features/Workspace/useWorkspaceAwareNavigate.ts b/src/features/Workspace/useWorkspaceAwareNavigate.ts
index c2da763f14b..e64e99162e5 100644
--- a/src/features/Workspace/useWorkspaceAwareNavigate.ts
+++ b/src/features/Workspace/useWorkspaceAwareNavigate.ts
@@ -3,7 +3,7 @@
import { useCallback } from 'react';
import { type NavigateFunction, type NavigateOptions, type To, useNavigate } from 'react-router';
-import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { buildWorkspaceAwarePath, type WorkspaceAwareNavigateOptions } from './workspaceAwarePath';
@@ -22,12 +22,14 @@ export interface WorkspaceAwareNavigateFunction extends NavigateFunction {
* Drop-in replacement for `useNavigate` that auto-prefixes absolute path
* strings with the active workspace slug. Numeric deltas (`navigate(-1)`),
* `Partial<Path>` objects, and relative path strings pass through unchanged.
+ * The active slug is read when navigation runs rather than captured during
+ * render, so synchronous store listeners cannot navigate with a stale scope
+ * while a workspace switch is triggering React updates.
*
* Pass `{ escape: true }` to bypass prefixing for personal-only destinations.
*/
export const useWorkspaceAwareNavigate = (): WorkspaceAwareNavigateFunction => {
const navigate = useNavigate();
- const activeSlug = useActiveWorkspaceSlug();
return useCallback(
((to: To | number, options?: WorkspaceAwareNavigateOptions) => {
@@ -38,7 +40,7 @@ export const useWorkspaceAwareNavigate = (): WorkspaceAwareNavigateFunction => {
// `Partial<Path>` object — pass through unchanged.
return navigate(to, options as NavigateOptions | undefined);
}
- const target = buildWorkspaceAwarePath(to, activeSlug, options);
+ const target = buildWorkspaceAwarePath(to, getActiveWorkspaceSlug(), options);
const { escape: _escape, ...rest } = options ?? {};
void _escape;
// Stay a transparent drop-in for `useNavigate`: only forward a second arg
@@ -46,6 +48,6 @@ export const useWorkspaceAwareNavigate = (): WorkspaceAwareNavigateFunction => {
// turn into `navigate(path, {})`.
return Object.keys(rest).length > 0 ? navigate(target, rest) : navigate(target);
}) as WorkspaceAwareNavigateFunction,
- [navigate, activeSlug],
+ [navigate],
);
};
diff --git a/src/hooks/useQueryRoute.test.ts b/src/hooks/useQueryRoute.test.ts
index f4be2599cfa..bea3e9e2ed2 100644
--- a/src/hooks/useQueryRoute.test.ts
+++ b/src/hooks/useQueryRoute.test.ts
@@ -12,6 +12,7 @@ vi.mock('react-router', () => ({
}));
vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ getActiveWorkspaceSlug: activeWorkspaceSlugMock,
useActiveWorkspaceSlug: activeWorkspaceSlugMock,
}));
diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx
index 787dfe20cdc..2d472abff42 100644
--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx
@@ -14,6 +14,7 @@ const setSearchParamsMock = vi.hoisted(() => vi.fn());
const useLocationMock = vi.hoisted(() => vi.fn());
const useParamsMock = vi.hoisted(() => vi.fn());
const useSearchParamsMock = vi.hoisted(() => vi.fn());
+const workspaceMock = vi.hoisted(() => ({ activeSlug: null as string | null }));
vi.hoisted(() => {
const storage = {
@@ -42,6 +43,11 @@ vi.mock('react-router', async () => {
};
});
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ getActiveWorkspaceSlug: () => workspaceMock.activeSlug,
+ useActiveWorkspaceSlug: () => workspaceMock.activeSlug,
+}));
+
describe('ChatHydration', () => {
beforeEach(() => {
navigateMock.mockReset();
@@ -49,6 +55,7 @@ describe('ChatHydration', () => {
useLocationMock.mockReset();
useParamsMock.mockReset();
useSearchParamsMock.mockReset();
+ workspaceMock.activeSlug = null;
useChatStore.setState(
{
@@ -155,4 +162,54 @@ describe('ChatHydration', () => {
});
});
});
+
+ it('preserves the routed topic when the workspace activates after mount', async () => {
+ useParamsMock.mockReturnValue({ aid: 'agt_test', topicId: 'tpc_previous' });
+ useLocationMock.mockReturnValue({
+ hash: '',
+ pathname: '/acme/agent/agt_test/tpc_previous',
+ search: '',
+ });
+ useSearchParamsMock.mockReturnValue([new URLSearchParams(''), setSearchParamsMock]);
+ useChatStore.setState({ activeTopicId: 'tpc_previous' }, false);
+
+ render(<ChatHydration />);
+ navigateMock.mockClear();
+
+ // Workspace URL sync updates the Zustand store before React can rerender
+ // consumers of the active slug. Resetting workspace-scoped chat state in
+ // that same call stack must rehydrate the routed topic without navigating.
+ workspaceMock.activeSlug = 'acme';
+ await act(async () => {
+ useChatStore.setState({ activeTopicId: undefined }, false);
+ });
+
+ await waitFor(() => {
+ expect(useChatStore.getState().activeTopicId).toBe('tpc_previous');
+ expect(navigateMock).not.toHaveBeenCalled();
+ });
+ });
+
+ it('still clears the routed topic after an explicit topic switch', async () => {
+ workspaceMock.activeSlug = 'acme';
+ useParamsMock.mockReturnValue({ aid: 'agt_test', topicId: 'tpc_previous' });
+ useLocationMock.mockReturnValue({
+ hash: '',
+ pathname: '/acme/agent/agt_test/tpc_previous',
+ search: '',
+ });
+ useSearchParamsMock.mockReturnValue([new URLSearchParams(''), setSearchParamsMock]);
+ useChatStore.setState({ activeTopicId: 'tpc_previous' }, false);
+
+ render(<ChatHydration />);
+ navigateMock.mockClear();
+
+ await act(async () => {
+ await useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });
+ });
+
+ await waitFor(() => {
+ expect(navigateMock).toHaveBeenCalledWith('/acme/agent/agt_test', { replace: true });
+ });
+ });
});
diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
index e72725a5b8b..12ac395573f 100644
--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.tsx
@@ -62,9 +62,25 @@ const ChatHydration = memo(() => {
const unsubscribeTopic = useChatStore.subscribe(
(s) => s.activeTopicId,
(state) => {
- const { aid } = paramsRef.current;
+ const { aid, topicId } = paramsRef.current;
if (!aid) return;
+ if (state === topicId) return;
+
+ // Workspace bootstrap clears scoped chat data with `undefined` before
+ // loading the new scope. On a topic deep link the URL remains the
+ // source of truth, so restore that routed topic instead of treating the
+ // reset as an explicit request to open a blank conversation.
+ // `switchTopic(null)` normalizes to `null`, so intentional topic
+ // changes still take the normal store-to-URL path below.
+ if (state === undefined && topicId) {
+ useChatStore.setState(
+ { activeTopicId: topicId },
+ false,
+ 'ChatHydration/restoreTopicAfterScopedReset',
+ );
+ return;
+ }
const nextSearchParams = new URLSearchParams(searchParamsRef.current);
nextSearchParams.delete('topic');