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.

✨ feat(agent-share): open visitor topics by URL and title the tab (#19267)

YuTengjingfc1dee9f6a14
diff --git a/src/features/AgentShareVisitor/Page.tsx b/src/features/AgentShareVisitor/Page.tsx
index ee683dec36b..066c94f450b 100644
--- a/src/features/AgentShareVisitor/Page.tsx
+++ b/src/features/AgentShareVisitor/Page.tsx
@@ -61,7 +61,7 @@ const VisitorShell = ({
*/
const AgentShareVisitorPage = memo(() => {
const { t } = useTranslation('agent');
- const { slugOrId } = useParams<{ slugOrId: string }>();
+ const { slugOrId, topicId } = useParams<{ slugOrId: string; topicId: string }>();
const navigate = useNavigate();
const isMobile = useIsMobile();
const RouteSkeleton = useRouteSkeleton();
@@ -79,7 +79,7 @@ const AgentShareVisitorPage = memo(() => {
const state = resolveShareAccessState(error);
if (state === 'signIn') {
- const signInUrl = buildAgentShareSignInUrl(slugOrId ?? '');
+ const signInUrl = buildAgentShareSignInUrl(slugOrId ?? '', topicId);
return (
<VisitorShell slugOrId={slugOrId}>
diff --git a/src/features/AgentShareVisitor/TopicPanel.tsx b/src/features/AgentShareVisitor/TopicPanel.tsx
index 16bfe88f9ae..7b6c5d334e6 100644
--- a/src/features/AgentShareVisitor/TopicPanel.tsx
+++ b/src/features/AgentShareVisitor/TopicPanel.tsx
@@ -8,10 +8,10 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
-import { useChatStore } from '@/store/chat';
import { getTopicPanelViewState } from './topicPanelViewState';
import { isTopicRowActivationKey } from './topicRowActivation';
+import { useVisitorTopicRoute } from './useVisitorTopicRoute';
import { useVisitorTopics } from './useVisitorTopics';
/** Placeholder rows shown while the visitor's topic list is loading, sized like a typical topic title. */
@@ -34,8 +34,8 @@ const styles = createStaticStyles(({ css }) => ({
/**
* The visitor's topic list under the current share (server-scoped by
- * senderId). Selecting a topic drives the chat store's activeTopicId — the
- * same signal the conversation surface and composer key off.
+ * senderId). Selection follows the URL so bookmarks, refreshes, and browser
+ * history open the same conversation as the highlighted row.
*/
const TopicPanel = memo<{
/** Off for a non-interactive share (owner preview): skips the fetch that would only 403. */
@@ -45,12 +45,12 @@ const TopicPanel = memo<{
showTitle?: boolean;
}>(({ enabled = true, onSelect, shareId, showTitle = true }) => {
const { t } = useTranslation('agent');
- const activeTopicId = useChatStore((s) => s.activeTopicId);
+ const { topicId: activeTopicId, selectTopic: navigateToTopic } = useVisitorTopicRoute();
const { data: topics, error, isLoading, mutate } = useVisitorTopics(shareId, enabled);
const viewState = getTopicPanelViewState(topics, error, isLoading);
const selectTopic = (topicId?: string) => {
- useChatStore.setState({ activeTopicId: topicId }, false, 'AgentShareVisitor/selectTopic');
+ navigateToTopic(topicId);
onSelect?.();
};
diff --git a/src/features/AgentShareVisitor/VisitorConversation.tsx b/src/features/AgentShareVisitor/VisitorConversation.tsx
index 1c7832598ed..847afbf298e 100644
--- a/src/features/AgentShareVisitor/VisitorConversation.tsx
+++ b/src/features/AgentShareVisitor/VisitorConversation.tsx
@@ -4,12 +4,12 @@ import type { SharedAgentData } from '@lobechat/types';
import { memo } from 'react';
import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
-import { useChatStore } from '@/store/chat';
import ReadOnlyConversationArea from './ReadOnlyConversationArea';
import { resolveVisitorRunningOperation } from './resolveVisitorRunningOperation';
import { isShareInteractive } from './shareInteractivity';
import { useVisitorConversationSeed } from './useVisitorConversationSeed';
+import { useVisitorTopicRoute } from './useVisitorTopicRoute';
import { useVisitorTopics } from './useVisitorTopics';
import VisitorComposer from './VisitorComposer';
@@ -20,8 +20,8 @@ import VisitorComposer from './VisitorComposer';
*/
const VisitorConversation = memo<{ data: SharedAgentData }>(({ data }) => {
const { agentId, shareId } = data;
- const seeded = useVisitorConversationSeed(data);
- const activeTopicId = useChatStore((s) => s.activeTopicId);
+ const { topicId: activeTopicId, onTopicCreated } = useVisitorTopicRoute();
+ const seeded = useVisitorConversationSeed(data, activeTopicId);
const interactive = isShareInteractive(data.visibility);
const { data: topics, mutate: refreshVisitorTopics } = useVisitorTopics(shareId, interactive);
@@ -51,7 +51,10 @@ const VisitorConversation = memo<{ data: SharedAgentData }>(({ data }) => {
// The gateway transport already switched the store to the new topic
// (`switchTopic`); refreshing the list makes it show up in the panel.
topicId={activeTopicId}
- onTopicCreated={() => void refreshVisitorTopics()}
+ onTopicCreated={(createdTopicId) => {
+ onTopicCreated(createdTopicId);
+ void refreshVisitorTopics();
+ }}
/>
</>
);
diff --git a/src/features/AgentShareVisitor/VisitorTopBar.tsx b/src/features/AgentShareVisitor/VisitorTopBar.tsx
index b92428c48a6..e8b327ed771 100644
--- a/src/features/AgentShareVisitor/VisitorTopBar.tsx
+++ b/src/features/AgentShareVisitor/VisitorTopBar.tsx
@@ -4,7 +4,7 @@ import { Flexbox } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
-import { Link } from 'react-router';
+import { Link, useParams } from 'react-router';
import { ProductLogo } from '@/components/Branding';
import UserAvatar from '@/features/User/UserAvatar';
@@ -62,7 +62,8 @@ interface VisitorTopBarProps {
const VisitorTopBar = memo<VisitorTopBarProps>(({ slugOrId }) => {
const { t } = useTranslation('agent');
const isSignedIn = useUserStore(authSelectors.isLogin);
- const homePath = isSignedIn ? '/' : buildAgentShareSignInUrl(slugOrId ?? '');
+ const { topicId } = useParams<{ topicId: string }>();
+ const homePath = isSignedIn ? '/' : buildAgentShareSignInUrl(slugOrId ?? '', topicId);
return (
<Flexbox
diff --git a/src/features/AgentShareVisitor/routeMeta.ts b/src/features/AgentShareVisitor/routeMeta.ts
index d8086407c0b..826a1f68d24 100644
--- a/src/features/AgentShareVisitor/routeMeta.ts
+++ b/src/features/AgentShareVisitor/routeMeta.ts
@@ -1,14 +1,15 @@
import { MessageSquareShareIcon } from 'lucide-react';
+import { lazy } from 'react';
import AgentShareVisitorSkeleton from '@/components/Skeleton/AgentShareVisitor';
import { routeMeta } from '@/spa/router/routeMeta';
/**
- * Agent-share visitor surface (`/a/:slugOrId`). The shared agent's name only
- * becomes known after `getSharedAgent` resolves, so the tab title stays on the
- * generic share label rather than flashing a placeholder name.
+ * Keep visitor data fetching out of the initial router chunk. The static share
+ * label remains the fallback until the visitor-facing metadata is available.
*/
export const agentShareVisitorRouteMeta = routeMeta({
+ DynamicMeta: lazy(() => import('./useAgentShareVisitorRouteMeta')),
icon: MessageSquareShareIcon,
Skeleton: AgentShareVisitorSkeleton,
titleKey: 'navigation.sharedAgent',
diff --git a/src/features/AgentShareVisitor/useAgentShareVisitorRouteMeta.test.ts b/src/features/AgentShareVisitor/useAgentShareVisitorRouteMeta.test.ts
new file mode 100644
index 00000000000..61904d58c8d
--- /dev/null
+++ b/src/features/AgentShareVisitor/useAgentShareVisitorRouteMeta.test.ts
@@ -0,0 +1,139 @@
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import type { DynamicRouteMeta } from '@/spa/router/routeMeta';
+
+import { useAgentShareVisitorRouteMeta } from './useAgentShareVisitorRouteMeta';
+import { useSharedAgent } from './useSharedAgent';
+
+const { getSharedAgent } = vi.hoisted(() => ({ getSharedAgent: vi.fn() }));
+
+vi.mock('@/services/agentShare', () => ({ agentShareService: { getSharedAgent } }));
+
+const createWrapper = () => {
+ const cache = new Map();
+
+ return ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => cache, shouldRetryOnError: false } },
+ children,
+ );
+};
+
+describe('useAgentShareVisitorRouteMeta', () => {
+ afterEach(() => {
+ cleanup();
+ vi.resetAllMocks();
+ });
+
+ it('resolves the agent name from the same request as the visitor page', async () => {
+ let resolveAgent!: (data: { agentMeta: { name: string; title: string } }) => void;
+ getSharedAgent.mockReturnValue(
+ new Promise((resolve) => {
+ resolveAgent = resolve;
+ }),
+ );
+ const onResolve = vi.fn<(meta: DynamicRouteMeta) => void>();
+
+ renderHook(
+ () => {
+ useSharedAgent('alice');
+ useAgentShareVisitorRouteMeta({ onResolve, params: { slugOrId: 'alice' } });
+ },
+ { wrapper: createWrapper() },
+ );
+
+ expect(onResolve.mock.lastCall?.[0].title).toBeUndefined();
+
+ await act(async () => {
+ resolveAgent({ agentMeta: { name: 'Alice', title: 'Writing Assistant' } });
+ });
+
+ await waitFor(() => expect(onResolve.mock.lastCall?.[0].title).toBe('Alice'));
+ expect(getSharedAgent).toHaveBeenCalledTimes(1);
+ });
+
+ it('reads cached metadata without counting another view when the title mounts later', async () => {
+ getSharedAgent.mockResolvedValue({ agentMeta: { name: 'Alice' } });
+ const wrapper = createWrapper();
+ const page = renderHook(() => useSharedAgent('alice'), { wrapper });
+
+ await waitFor(() => expect(page.result.current.data).toBeDefined());
+ page.unmount();
+
+ const onResolve = vi.fn<(meta: DynamicRouteMeta) => void>();
+ renderHook(() => useAgentShareVisitorRouteMeta({ onResolve, params: { slugOrId: 'alice' } }), {
+ wrapper,
+ });
+
+ await waitFor(() => expect(onResolve.mock.lastCall?.[0].title).toBe('Alice'));
+ expect(getSharedAgent).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ [{ name: '', title: 'Writing Assistant' }, 'Writing Assistant'],
+ [{ name: ' ', title: ' ' }, undefined],
+ [{}, undefined],
+ ])('resolves display name or allows the static fallback for %j', async (agentMeta, title) => {
+ getSharedAgent.mockResolvedValue({ agentMeta });
+ const onResolve = vi.fn<(meta: DynamicRouteMeta) => void>();
+
+ const { result } = renderHook(
+ () => {
+ const shared = useSharedAgent('alice');
+ useAgentShareVisitorRouteMeta({ onResolve, params: { slugOrId: 'alice' } });
+ return shared;
+ },
+ { wrapper: createWrapper() },
+ );
+
+ await waitFor(() => expect(result.current.data).toBeDefined());
+ expect(onResolve.mock.lastCall?.[0].title).toBe(title);
+ });
+
+ it('clears the previous agent name when navigating to an unavailable share', async () => {
+ getSharedAgent.mockResolvedValueOnce({ agentMeta: { name: 'Alice' } });
+ getSharedAgent.mockRejectedValueOnce(new Error('Share unavailable'));
+ const onResolve = vi.fn<(meta: DynamicRouteMeta) => void>();
+
+ const { rerender, result } = renderHook(
+ ({ slugOrId }) => {
+ const shared = useSharedAgent(slugOrId);
+ useAgentShareVisitorRouteMeta({ onResolve, params: { slugOrId } });
+ return shared;
+ },
+ { initialProps: { slugOrId: 'alice' }, wrapper: createWrapper() },
+ );
+
+ await waitFor(() => expect(onResolve.mock.lastCall?.[0].title).toBe('Alice'));
+ rerender({ slugOrId: 'unavailable' });
+ await waitFor(() => expect(result.current.error).toBeDefined());
+ expect(onResolve.mock.lastCall?.[0].title).toBeUndefined();
+ });
+
+ it('falls back after a failed refresh even when SWR retains cached metadata', async () => {
+ getSharedAgent.mockResolvedValue({ agentMeta: { name: 'Alice' } });
+ const onResolve = vi.fn<(meta: DynamicRouteMeta) => void>();
+
+ const { result } = renderHook(
+ () => {
+ const shared = useSharedAgent('alice');
+ useAgentShareVisitorRouteMeta({ onResolve, params: { slugOrId: 'alice' } });
+ return shared;
+ },
+ { wrapper: createWrapper() },
+ );
+
+ await waitFor(() => expect(onResolve.mock.lastCall?.[0].title).toBe('Alice'));
+ getSharedAgent.mockRejectedValue(new Error('Share unavailable'));
+ await act(async () => {
+ await result.current.mutate();
+ });
+
+ expect(result.current.data?.agentMeta.name).toBe('Alice');
+ await waitFor(() => expect(onResolve.mock.lastCall?.[0].title).toBeUndefined());
+ });
+});
diff --git a/src/features/AgentShareVisitor/useAgentShareVisitorRouteMeta.ts b/src/features/AgentShareVisitor/useAgentShareVisitorRouteMeta.ts
new file mode 100644
index 00000000000..1aaf260d34e
--- /dev/null
+++ b/src/features/AgentShareVisitor/useAgentShareVisitorRouteMeta.ts
@@ -0,0 +1,30 @@
+import { agentDisplayName } from '@lobechat/types';
+import useSWR from 'swr';
+
+import { usePublishDynamicRouteMeta } from '@/features/RouteMeta/usePublishDynamicRouteMeta';
+import { shareKeys } from '@/libs/swr/keys';
+import type { DynamicRouteMetaProps } from '@/spa/router/routeMeta';
+
+import type { useSharedAgent } from './useSharedAgent';
+
+export const useAgentShareVisitorRouteMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
+ /** The page owns fetching because fetching a share also counts a page view. */
+ const { data, error } = useSWR<ReturnType<typeof useSharedAgent>['data']>(
+ params.slugOrId ? shareKeys.agentInfo(params.slugOrId) : null,
+ null,
+ { revalidateOnMount: false },
+ );
+
+ usePublishDynamicRouteMeta(
+ { title: error ? undefined : agentDisplayName(data?.agentMeta) },
+ onResolve,
+ );
+};
+
+const AgentShareVisitorDynamicMeta = (props: DynamicRouteMetaProps) => {
+ useAgentShareVisitorRouteMeta(props);
+
+ return null;
+};
+
+export default AgentShareVisitorDynamicMeta;
diff --git a/src/features/AgentShareVisitor/useVisitorConversationSeed.test.ts b/src/features/AgentShareVisitor/useVisitorConversationSeed.test.ts
new file mode 100644
index 00000000000..dae12750bf8
--- /dev/null
+++ b/src/features/AgentShareVisitor/useVisitorConversationSeed.test.ts
@@ -0,0 +1,70 @@
+import type { SharedAgentData } from '@lobechat/types';
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useVisitorConversationSeed } from './useVisitorConversationSeed';
+
+const mocks = vi.hoisted(() => ({
+ chatState: {} as Record<string, unknown>,
+ seedAgent: vi.fn(),
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: {
+ getState: () => ({ internal_dispatchAgentMap: mocks.seedAgent }),
+ setState: vi.fn(),
+ },
+}));
+vi.mock('@/store/chat', () => ({
+ useChatStore: {
+ setState: (state: Record<string, unknown>) => Object.assign(mocks.chatState, state),
+ },
+}));
+
+const agentMeta = (name: string): SharedAgentData['agentMeta'] => ({
+ avatar: null,
+ backgroundColor: null,
+ description: null,
+ name,
+ title: null,
+});
+
+const identity: Pick<SharedAgentData, 'agentId' | 'agentMeta' | 'shareId'> = {
+ agentId: 'agt_shared',
+ agentMeta: agentMeta('Shared assistant'),
+ shareId: 'share_1',
+};
+
+describe('useVisitorConversationSeed', () => {
+ beforeEach(() => {
+ mocks.chatState = { activeAgentId: 'agt_previous', activeTopicId: 'tpc_previous' };
+ });
+
+ it('restores the URL topic on direct entry and follows history navigation', () => {
+ const { result, rerender } = renderHook(
+ ({ topicId }: { topicId?: string }) => useVisitorConversationSeed(identity, topicId),
+ { initialProps: { topicId: 'tpc_1' } as { topicId?: string } },
+ );
+ expect(result.current).toBe(true);
+ expect(mocks.chatState).toMatchObject({ activeAgentId: 'agt_shared', activeTopicId: 'tpc_1' });
+ rerender({ topicId: 'tpc_2' });
+ expect(mocks.chatState.activeTopicId).toBe('tpc_2');
+ rerender({ topicId: 'tpc_1' });
+ expect(mocks.chatState.activeTopicId).toBe('tpc_1');
+ rerender({ topicId: undefined });
+ expect(mocks.chatState.activeTopicId).toBeUndefined();
+ });
+
+ it('does not reset a newly created topic when share metadata revalidates', () => {
+ const { rerender } = renderHook((data) => useVisitorConversationSeed(data), {
+ initialProps: identity,
+ });
+ act(() => {
+ mocks.chatState.activeTopicId = 'tpc_created';
+ });
+ rerender({ ...identity, agentMeta: agentMeta('Renamed assistant') });
+ expect(mocks.chatState.activeTopicId).toBe('tpc_created');
+ rerender({ ...identity, agentId: 'agt_other', shareId: 'share_2' });
+ expect(mocks.chatState.activeTopicId).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentShareVisitor/useVisitorConversationSeed.ts b/src/features/AgentShareVisitor/useVisitorConversationSeed.ts
index 489f259a651..ef44475b018 100644
--- a/src/features/AgentShareVisitor/useVisitorConversationSeed.ts
+++ b/src/features/AgentShareVisitor/useVisitorConversationSeed.ts
@@ -24,24 +24,26 @@ const seedAgentMap = (agentId: string, agentMeta: SharedAgentIdentity['agentMeta
/**
* Seeds the agent/chat stores for the visitor-facing share surface and reports
- * whether the one-time destructive init has landed yet.
+ * whether the URL selection has landed before mounting the conversation.
*
* Split into two effects with different dependencies on purpose:
- * - **identity effect** (`agentId`/`shareId`): the one destructive init —
- * resets chat-store selection state (`activeTopicId` and friends). Must
- * only fire when the agent/share identity actually changes.
+ * - **selection effect** (`agentId`/`shareId`/`topicId`): initializes the
+ * chat-store selection from the URL, including browser history navigation.
* - **metadata effect** (`agentMeta`): non-destructive agentMap re-seed so
* the header avatar/name/title stay fresh. An SWR revalidation hands back a
* brand-new `agentMeta` object even when the identity hasn't changed;
* folding this into the identity effect would wipe `activeTopicId` on every
* metadata refresh and yank the visitor into a new conversation mid-chat.
*/
-export const useVisitorConversationSeed = ({
- agentId,
- agentMeta,
- shareId,
-}: SharedAgentIdentity): boolean => {
- const [seeded, setSeeded] = useState(false);
+export const useVisitorConversationSeed = (
+ { agentId, agentMeta, shareId }: SharedAgentIdentity,
+ topicId?: string,
+): boolean => {
+ const [seeded, setSeeded] = useState<{
+ agentId: string;
+ shareId: string;
+ topicId?: string;
+ }>();
useLayoutEffect(() => {
seedAgentMap(agentId, agentMeta);
@@ -51,20 +53,18 @@ export const useVisitorConversationSeed = ({
activeAgentId: agentId,
activeGroupId: undefined,
activeThreadId: undefined,
- activeTopicId: undefined,
+ activeTopicId: topicId,
},
false,
'AgentShareVisitor/sync',
);
- setSeeded(true);
- // Deliberately keyed on the agent/share identity only — the metadata
- // effect below handles `agentMeta` changes without touching chat-store
- // selection state. See the doc comment above for why.
- }, [agentId, shareId]);
+ setSeeded({ agentId, shareId, topicId });
+ // Metadata refreshes must not reset selection while a new topic is being created.
+ }, [agentId, shareId, topicId]);
useLayoutEffect(() => {
seedAgentMap(agentId, agentMeta);
}, [agentId, agentMeta]);
- return seeded;
+ return seeded?.agentId === agentId && seeded?.shareId === shareId && seeded?.topicId === topicId;
};
diff --git a/src/features/AgentShareVisitor/useVisitorTopicRoute.test.ts b/src/features/AgentShareVisitor/useVisitorTopicRoute.test.ts
new file mode 100644
index 00000000000..be629ad2047
--- /dev/null
+++ b/src/features/AgentShareVisitor/useVisitorTopicRoute.test.ts
@@ -0,0 +1,65 @@
+import { act, renderHook } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { createMemoryRouter, RouterProvider } from 'react-router';
+import { describe, expect, it } from 'vitest';
+
+import { useVisitorTopicRoute } from './useVisitorTopicRoute';
+
+const setup = (initialEntry = '/a/my-bot/tpc_1') => {
+ let router: ReturnType<typeof createMemoryRouter>;
+ const wrapper = ({ children }: PropsWithChildren) => {
+ router = createMemoryRouter([{ element: children, path: '/a/:slugOrId/:topicId?' }], {
+ initialEntries: [initialEntry],
+ });
+ return createElement(RouterProvider, { router });
+ };
+ const hook = renderHook(useVisitorTopicRoute, { wrapper });
+ return { ...hook, getRouter: () => router };
+};
+
+describe('useVisitorTopicRoute', () => {
+ it('updates the URL for selection and restores topics through back/forward', async () => {
+ const { result, getRouter } = setup();
+ expect(result.current.topicId).toBe('tpc_1');
+ await act(() => result.current.selectTopic('tpc_2'));
+ expect(getRouter().state.location.pathname).toBe('/a/my-bot/tpc_2');
+ expect(result.current.topicId).toBe('tpc_2');
+ await act(() => getRouter().navigate(-1));
+ expect(result.current.topicId).toBe('tpc_1');
+ await act(() => getRouter().navigate(1));
+ expect(result.current.topicId).toBe('tpc_2');
+ await act(() => result.current.selectTopic());
+ expect(getRouter().state.location.pathname).toBe('/a/my-bot');
+ expect(result.current.topicId).toBeUndefined();
+ });
+
+ it('replaces the blank conversation URL once a topic is created', async () => {
+ const { result, getRouter } = setup();
+ await act(() => result.current.selectTopic());
+ await act(() => result.current.onTopicCreated('tpc_created'));
+ expect(getRouter().state.location.pathname).toBe('/a/my-bot/tpc_created');
+ await act(() => getRouter().navigate(-1));
+ expect(result.current.topicId).toBe('tpc_1');
+ });
+
+ it('does not push a duplicate entry when the destination is already current', async () => {
+ const { result, getRouter } = setup('/a/my-bot');
+ const initialKey = getRouter().state.location.key;
+ await act(() => result.current.selectTopic());
+ expect(getRouter().state.location.key).toBe(initialKey);
+ // A first message that was still creating its topic must still land in the URL.
+ await act(() => result.current.onTopicCreated('tpc_created'));
+ expect(getRouter().state.location.pathname).toBe('/a/my-bot/tpc_created');
+ const createdKey = getRouter().state.location.key;
+ await act(() => result.current.selectTopic('tpc_created'));
+ expect(getRouter().state.location.key).toBe(createdKey);
+ });
+
+ it('does not navigate back when a send finishes after selecting another topic', async () => {
+ const { result, getRouter } = setup('/a/my-bot');
+ const onTopicCreated = result.current.onTopicCreated;
+ await act(() => result.current.selectTopic('tpc_other'));
+ await act(() => onTopicCreated('tpc_late'));
+ expect(getRouter().state.location.pathname).toBe('/a/my-bot/tpc_other');
+ });
+});
diff --git a/src/features/AgentShareVisitor/useVisitorTopicRoute.ts b/src/features/AgentShareVisitor/useVisitorTopicRoute.ts
new file mode 100644
index 00000000000..54a25b4c7c0
--- /dev/null
+++ b/src/features/AgentShareVisitor/useVisitorTopicRoute.ts
@@ -0,0 +1,42 @@
+import { useLayoutEffect, useRef } from 'react';
+import { useLocation, useNavigate, useParams } from 'react-router';
+
+import { buildAgentShareVisitorPath } from './visitorPath';
+
+/** The URL owns selection; a created topic replaces its blank conversation entry. */
+export const useVisitorTopicRoute = () => {
+ const { slugOrId = '', topicId } = useParams<{ slugOrId: string; topicId: string }>();
+ const location = useLocation();
+ const navigate = useNavigate();
+ const currentLocationKey = useRef<string | undefined>(location.key);
+
+ useLayoutEffect(() => {
+ currentLocationKey.current = location.key;
+ return () => {
+ currentLocationKey.current = undefined;
+ };
+ }, [location.key]);
+
+ /**
+ * Re-selecting the current topic (or "new topic" while already on the blank
+ * conversation) must not push a duplicate history entry: Back would look
+ * inert, and the new location key would make a still-pending
+ * `onTopicCreated` think the visitor left and skip the URL replacement.
+ */
+ const navigateIfChanged = (path: string, options?: { replace?: boolean }) => {
+ if (path === location.pathname) return;
+ navigate(path, options);
+ };
+
+ return {
+ onTopicCreated: (createdTopicId: string) => {
+ /** A delayed send must not pull the visitor back after they navigate away. */
+ if (currentLocationKey.current !== location.key) return;
+ navigateIfChanged(buildAgentShareVisitorPath(slugOrId, createdTopicId), { replace: true });
+ },
+ selectTopic: (nextTopicId?: string) => {
+ navigateIfChanged(buildAgentShareVisitorPath(slugOrId, nextTopicId));
+ },
+ topicId,
+ };
+};
diff --git a/src/features/AgentShareVisitor/visitorPath.test.ts b/src/features/AgentShareVisitor/visitorPath.test.ts
index fcbbbfc1477..6e4d9ec4843 100644
--- a/src/features/AgentShareVisitor/visitorPath.test.ts
+++ b/src/features/AgentShareVisitor/visitorPath.test.ts
@@ -15,6 +15,13 @@ describe('visitorPath', () => {
expect(buildAgentShareSignInUrl('my-bot')).toBe('/signin?callbackUrl=%2Fa%2Fmy-bot');
});
+ it('builds a bookmarkable topic path and preserves it through sign-in', () => {
+ expect(buildAgentShareVisitorPath('my-bot', 'tpc_1')).toBe('/a/my-bot/tpc_1');
+ expect(buildAgentShareSignInUrl('my-bot', 'tpc_1')).toBe(
+ '/signin?callbackUrl=%2Fa%2Fmy-bot%2Ftpc_1',
+ );
+ });
+
describe('buildAgentShareOwnerPath', () => {
it('sends the creator to the share settings on desktop', () => {
expect(buildAgentShareOwnerPath('agt_1')).toBe('/agent/agt_1/share');
diff --git a/src/features/AgentShareVisitor/visitorPath.ts b/src/features/AgentShareVisitor/visitorPath.ts
index 73adbe72298..d044feadb5b 100644
--- a/src/features/AgentShareVisitor/visitorPath.ts
+++ b/src/features/AgentShareVisitor/visitorPath.ts
@@ -7,16 +7,16 @@
export const AGENT_SHARE_VISITOR_PATH = '/a';
/** Visitor page of an agent share, by custom slug or raw share id. */
-export const buildAgentShareVisitorPath = (slugOrId: string) =>
- `${AGENT_SHARE_VISITOR_PATH}/${slugOrId}`;
+export const buildAgentShareVisitorPath = (slugOrId: string, topicId?: string) =>
+ `${AGENT_SHARE_VISITOR_PATH}/${slugOrId}${topicId ? `/${topicId}` : ''}`;
/**
* Sign-in URL that returns the visitor to the same share once signed in.
* `/signin` is an auth shell outside the SPA router, so callers navigate to it
* with a full document load.
*/
-export const buildAgentShareSignInUrl = (slugOrId: string) =>
- `/signin?callbackUrl=${encodeURIComponent(buildAgentShareVisitorPath(slugOrId))}`;
+export const buildAgentShareSignInUrl = (slugOrId: string, topicId?: string) =>
+ `/signin?callbackUrl=${encodeURIComponent(buildAgentShareVisitorPath(slugOrId, topicId))}`;
/**
* Where the CREATOR lands when they open their own share link: the share
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index 57d071890ef..b263f6e391c 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -1598,7 +1598,7 @@ export const createSharedDesktopRoutes = ({
),
errorElement: <ErrorBoundary />,
handle: { meta: agentShareVisitorRouteMeta },
- path: `${AGENT_SHARE_VISITOR_PATH}/:slugOrId`,
+ path: `${AGENT_SHARE_VISITOR_PATH}/:slugOrId/:topicId?`,
},
...BusinessDesktopRoutesWithoutMainLayout,
...platformRoutes,
diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index 6c3b0efa9f8..954ec8fed4f 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -285,8 +285,8 @@ describe('desktop router shared definition', () => {
// …and the agent-share visitor surface lives at `/a/:slugOrId`, a sibling
// of the main layout on every platform (Web, Electron, and the mobile
// router — see mobileRouter.test.tsx).
- expect(webPaths).toContain('/a/:slugOrId');
- expect(electronPaths).toContain('/a/:slugOrId');
+ expect(webPaths).toContain('/a/:slugOrId/:topicId?');
+ expect(electronPaths).toContain('/a/:slugOrId/:topicId?');
expect(webPaths).not.toContain('/verify');
expect(webPaths).toContain('/acceptance');
expect(webPaths).toContain('/onboarding');
@@ -552,8 +552,12 @@ describe('desktop router shared definition', () => {
const matches = matchRoutes(routes, '/a/my-bot');
expect(matches).toHaveLength(1);
- expect(matches?.[0]?.route.path).toBe('/a/:slugOrId');
+ expect(matches?.[0]?.route.path).toBe('/a/:slugOrId/:topicId?');
expect(matches?.[0]?.params).toMatchObject({ slugOrId: 'my-bot' });
+
+ const topicMatches = matchRoutes(routes, '/a/my-bot/tpc_saved');
+ expect(topicMatches).toHaveLength(1);
+ expect(topicMatches?.[0]?.params).toEqual({ slugOrId: 'my-bot', topicId: 'tpc_saved' });
},
);
diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsx
index 35de285cb70..363a097b805 100644
--- a/src/spa/router/mobileRouter.config.tsx
+++ b/src/spa/router/mobileRouter.config.tsx
@@ -627,7 +627,7 @@ export const mobileRoutes: RouteObject[] = [
),
errorElement: <ErrorBoundary />,
handle: { meta: agentShareVisitorRouteMeta },
- path: `${AGENT_SHARE_VISITOR_PATH}/:slugOrId`,
+ path: `${AGENT_SHARE_VISITOR_PATH}/:slugOrId/:topicId?`,
},
// Messenger verify route (outside main layout)
diff --git a/src/spa/router/mobileRouter.test.tsx b/src/spa/router/mobileRouter.test.tsx
index b9d4e2e2ca5..26f9c32182b 100644
--- a/src/spa/router/mobileRouter.test.tsx
+++ b/src/spa/router/mobileRouter.test.tsx
@@ -12,10 +12,16 @@ describe('mobileRouter agent share route', () => {
const matches = matchRoutes(mobileRoutes, '/a/my-agent');
expect(matches).toHaveLength(1);
- expect(matches?.[0]?.route.path).toBe('/a/:slugOrId');
+ expect(matches?.[0]?.route.path).toBe('/a/:slugOrId/:topicId?');
expect(matches?.[0]?.params).toMatchObject({ slugOrId: 'my-agent' });
});
+ it('opens a visitor topic directly without the owner layout', () => {
+ const matches = matchRoutes(mobileRoutes, '/a/my-agent/tpc_saved');
+ expect(matches).toHaveLength(1);
+ expect(matches?.[0]?.params).toEqual({ slugOrId: 'my-agent', topicId: 'tpc_saved' });
+ });
+
it('keeps the creator agent surface on /agent/:aid', () => {
const matches = matchRoutes(mobileRoutes, '/agent/my-agent');