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.

♻️ refactor(channel): give thread pages their own path (#22929)

Arvin Xuac1d5fe1b01c
diff --git a/packages/const/src/url.test.ts b/packages/const/src/url.test.ts
index e2292658171..322763af7a0 100644
--- a/packages/const/src/url.test.ts
+++ b/packages/const/src/url.test.ts
@@ -44,13 +44,13 @@ describe('GitHub links', () => {
describe('CHANNEL_URL', () => {
it('builds the channel and thread paths', () => {
expect(CHANNEL_URL('chn_1')).toBe('/channels/chn_1');
- expect(CHANNEL_URL('chn_1', 'cht_1')).toBe('/channels/chn_1?thread=cht_1&view=page');
+ expect(CHANNEL_URL('chn_1', 'cht_1')).toBe('/channels/chn_1/threads/cht_1');
});
it('opens a project Channel inside its project', () => {
expect(CHANNEL_URL('chn_1', null, 'pro_1')).toBe('/project/pro_1/channels/chn_1');
expect(CHANNEL_URL('chn_1', 'cht_1', 'pro_1')).toBe(
- '/project/pro_1/channels/chn_1?thread=cht_1&view=page',
+ '/project/pro_1/channels/chn_1/threads/cht_1',
);
});
});
diff --git a/packages/const/src/url.ts b/packages/const/src/url.ts
index 1c16ecf9880..ddb04bc1b85 100644
--- a/packages/const/src/url.ts
+++ b/packages/const/src/url.ts
@@ -86,8 +86,8 @@ export const GROUP_CHAT_TOPIC_URL = (groupId: string, topicId: string) =>
urlJoin('/group', groupId, topicId);
/**
- * A Channel page. A thread link opens the thread as the page (`view=page`); opening one from
- * a message instead shows it beside the Channel (`?thread=` alone). A project's Channel opens
+ * A Channel page. A thread link opens the thread as the page (`/threads/:threadId`); opening one
+ * from a message instead shows it beside the Channel (`?thread=`). A project's Channel opens
* inside the project so its sidebar stays in place.
*/
export const CHANNEL_URL = (
@@ -96,7 +96,7 @@ export const CHANNEL_URL = (
projectId?: string | null,
) => {
const path = projectId ? `/project/${projectId}/channels/${channelId}` : `/channels/${channelId}`;
- return threadId ? `${path}?thread=${encodeURIComponent(threadId)}&view=page` : path;
+ return threadId ? `${path}/threads/${encodeURIComponent(threadId)}` : path;
};
export const LIBRARY_URL = (id: string) => urlJoin('/resource/library', id);
diff --git a/src/features/Channels/ChannelList.tsx b/src/features/Channels/ChannelList.tsx
index 53bf374cbe0..6b21ea7b16e 100644
--- a/src/features/Channels/ChannelList.tsx
+++ b/src/features/Channels/ChannelList.tsx
@@ -35,7 +35,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import { channelsInScope } from './channelScope';
import { openCreateChannel } from './CreateChannel';
-import { matchChannel } from './paths';
+import { matchChannel, matchChannelThread } from './paths';
import { sortChannels } from './sortChannels';
import { threadTitle } from './threadTitle';
import { useChannelEvents } from './useChannelEvents';
@@ -200,7 +200,7 @@ interface ChannelSectionProps {
*/
const EnabledChannelSection = ({ itemKey = 'channels', projectId }: ChannelSectionProps) => {
const { t } = useTranslation('channel');
- const { pathname, search } = useActiveLocation();
+ const { pathname } = useActiveLocation();
const navigate = useWorkspaceAwareNavigate();
const slug = useActiveWorkspaceSlug();
const sync = channelActions.useFetchList();
@@ -218,8 +218,7 @@ const EnabledChannelSection = ({ itemKey = 'channels', projectId }: ChannelSecti
const create = () =>
openCreateChannel((id) => navigate(CHANNEL_URL(id, null, projectId)), projectId);
// Only a thread opened as the page is the current entry; one beside the Channel is not.
- const query = new URLSearchParams(search);
- const activeThreadId = query.get('view') === 'page' ? query.get('thread') : null;
+ const activeThreadId = matchChannelThread(pathname) ?? null;
const menuItems = useChannelMenu();
const setSort = (channelListSort: ChannelListSort) => updateSystemStatus({ channelListSort });
// Name sorts read as A–Z / Z–A; time sorts as newest / oldest first.
diff --git a/src/features/Channels/index.tsx b/src/features/Channels/index.tsx
index 80679fe0e24..dc08993970d 100644
--- a/src/features/Channels/index.tsx
+++ b/src/features/Channels/index.tsx
@@ -4,7 +4,7 @@ import { useSize } from 'ahooks';
import { Hash } from 'lucide-react';
import { useId, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useParams } from 'react-router';
+import { Navigate, useParams } from 'react-router';
import NotFound from '@/components/404';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
@@ -64,6 +64,7 @@ function EnabledChannelPage() {
thread: !!(threadId || threadDraft || pageThreadId),
});
if (!channelId) return null;
+ if (panel.legacyPageUrl) return <Navigate replace to={panel.legacyPageUrl} />;
return (
<Flexbox {...stylex.props(styles.layout)}>
diff --git a/src/features/Channels/paths.test.ts b/src/features/Channels/paths.test.ts
index 17534d19529..745be179f09 100644
--- a/src/features/Channels/paths.test.ts
+++ b/src/features/Channels/paths.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { matchChannel } from './paths';
+import { channelBasePath, matchChannel, matchChannelThread } from './paths';
describe('matchChannel', () => {
it.each([
@@ -11,6 +11,8 @@ describe('matchChannel', () => {
['/acme/project/pro_1/channels/chn_1/', 'chn_1'],
['/channels/chn_1/settings', 'chn_1'],
['/acme/project/pro_1/channels/chn_1/settings/', 'chn_1'],
+ ['/channels/chn_1/threads/cht_1', 'chn_1'],
+ ['/acme/project/pro_1/channels/chn_1/threads/cht_1/', 'chn_1'],
])('reads %s as an open Channel', (pathname, expected) => {
expect(matchChannel(pathname)).toBe(expected);
});
@@ -21,7 +23,34 @@ describe('matchChannel', () => {
'/group/grp_1',
'/agent/agt_1/channels/telegram',
'/project/pro_1/channels',
+ '/channels/chn_1/threads',
])('finds no Channel in %s', (pathname) => {
expect(matchChannel(pathname)).toBeUndefined();
});
});
+
+describe('matchChannelThread', () => {
+ it.each([
+ ['/channels/chn_1/threads/cht_1', 'cht_1'],
+ ['/acme/project/pro_1/channels/chn_1/threads/cht_1/', 'cht_1'],
+ ])('reads %s as a thread page', (pathname, expected) => {
+ expect(matchChannelThread(pathname)).toBe(expected);
+ });
+
+ it.each(['/channels/chn_1', '/channels/chn_1/settings', '/channels/chn_1/threads'])(
+ 'finds no thread page in %s',
+ (pathname) => {
+ expect(matchChannelThread(pathname)).toBeUndefined();
+ },
+ );
+});
+
+describe('channelBasePath', () => {
+ it.each([
+ ['/channels/chn_1', '/channels/chn_1'],
+ ['/channels/chn_1/threads/cht_1', '/channels/chn_1'],
+ ['/acme/project/pro_1/channels/chn_1/threads/cht_1/', '/acme/project/pro_1/channels/chn_1'],
+ ])('keeps the Channel page of %s', (pathname, expected) => {
+ expect(channelBasePath(pathname)).toBe(expected);
+ });
+});
diff --git a/src/features/Channels/paths.ts b/src/features/Channels/paths.ts
index 885fe5325a3..7625f2ce214 100644
--- a/src/features/Channels/paths.ts
+++ b/src/features/Channels/paths.ts
@@ -1,6 +1,17 @@
// An optional leading segment is the workspace slug, then an optional project scope.
-const CHANNEL_PATH = /^(?:\/[^/]+)?(?:\/project\/[^/]+)?\/channels\/([^/]+)(?:\/settings)?\/?$/;
+const CHANNEL_PATH =
+ /^((?:\/[^/]+)?(?:\/project\/[^/]+)?\/channels\/([^/]+))(?:\/settings|\/threads\/([^/]+))?\/?$/;
/** Which Channel a (possibly workspace-prefixed or project-scoped) pathname opens, if any. */
export const matchChannel = (pathname: string): string | undefined =>
+ CHANNEL_PATH.exec(pathname)?.[2];
+
+/** The thread a Channel pathname opens as the page (`…/channels/:id/threads/:threadId`), if any. */
+export const matchChannelThread = (pathname: string): string | undefined => {
+ const threadId = CHANNEL_PATH.exec(pathname)?.[3];
+ return threadId && decodeURIComponent(threadId);
+};
+
+/** The Channel page a Channel pathname belongs to, keeping its workspace and project prefix. */
+export const channelBasePath = (pathname: string): string | undefined =>
CHANNEL_PATH.exec(pathname)?.[1];
diff --git a/src/features/Channels/useThreadMenu.test.ts b/src/features/Channels/useThreadMenu.test.ts
index 4966a9dfdad..62f1644b563 100644
--- a/src/features/Channels/useThreadMenu.test.ts
+++ b/src/features/Channels/useThreadMenu.test.ts
@@ -46,7 +46,7 @@ describe('useThreadMenu', () => {
await item(items, 'copyThreadLink').onClick();
expect(copyToClipboard).toHaveBeenCalledWith(
- 'https://app.lobehub.com/acme/project/prj_1/channels/chn_abcdefghijkl?thread=cht_thread1&view=page',
+ 'https://app.lobehub.com/acme/project/prj_1/channels/chn_abcdefghijkl/threads/cht_thread1',
);
expect(success).toHaveBeenCalledWith('copyThreadLinkSuccess');
diff --git a/src/features/Channels/useThreadPanel.test.ts b/src/features/Channels/useThreadPanel.test.ts
index bc9a4ada10e..bcb36bd43ed 100644
--- a/src/features/Channels/useThreadPanel.test.ts
+++ b/src/features/Channels/useThreadPanel.test.ts
@@ -1,7 +1,7 @@
import type { ChannelPublicMessage } from '@lobechat/types';
import { act, cleanup, renderHook } from '@testing-library/react';
import { createElement, type ReactNode } from 'react';
-import { MemoryRouter } from 'react-router';
+import { MemoryRouter, useLocation } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ChannelThreadDraft } from './threadDraft';
@@ -22,6 +22,12 @@ const setup = (entry = '/channels/channel') =>
wrapper: ({ children }: { children: ReactNode }) =>
createElement(MemoryRouter, { initialEntries: [entry] }, children),
});
+const setupWithLocation = (entry: string) =>
+ renderHook(({ channelId }) => ({ location: useLocation(), panel: useThreadPanel(channelId) }), {
+ initialProps: { channelId: 'channel' },
+ wrapper: ({ children }: { children: ReactNode }) =>
+ createElement(MemoryRouter, { initialEntries: [entry] }, children),
+ });
describe('Local thread preview', () => {
beforeEach(() => {
@@ -134,22 +140,35 @@ describe('Local thread preview', () => {
describe('Thread opened as the page', () => {
afterEach(() => cleanup());
- it('shows a sidebar thread link as the page, not beside the Channel', () => {
- const { result } = setup('/channels/channel?thread=t1&view=page');
- expect(result.current.pageThreadId).toBe('t1');
- expect(result.current.threadId).toBeNull();
+ it.each(['/channels/channel/threads/t1', '/acme/project/p1/channels/channel/threads/t1'])(
+ 'shows the thread at %s as the page, not beside the Channel',
+ (entry) => {
+ const { result } = setup(entry);
+ expect(result.current.pageThreadId).toBe('t1');
+ expect(result.current.threadId).toBeNull();
+ expect(result.current.legacyPageUrl).toBeNull();
+ },
+ );
+
+ it('expands a side panel into the thread path and closes back to the Channel', () => {
+ const { result } = setupWithLocation('/acme/project/p1/channels/channel');
+ act(() => result.current.panel.openThread('t1'));
+ expect(result.current.panel.threadId).toBe('t1');
+ expect(result.current.panel.pageThreadId).toBeNull();
+ act(() => result.current.panel.openPage('t1'));
+ expect(result.current.location.pathname).toBe('/acme/project/p1/channels/channel/threads/t1');
+ expect(result.current.location.search).toBe('');
+ expect(result.current.panel.pageThreadId).toBe('t1');
+ expect(result.current.panel.threadId).toBeNull();
+ act(() => result.current.panel.close());
+ expect(result.current.location.pathname).toBe('/acme/project/p1/channels/channel');
+ expect(result.current.panel.pageThreadId).toBeNull();
+ expect(result.current.panel.threadId).toBeNull();
});
- it('expands a side panel into the page and closes back to the Channel', () => {
- const { result } = setup();
- act(() => result.current.openThread('t1'));
- expect(result.current.threadId).toBe('t1');
- expect(result.current.pageThreadId).toBeNull();
- act(() => result.current.openPage('t1'));
- expect(result.current.pageThreadId).toBe('t1');
- expect(result.current.threadId).toBeNull();
- act(() => result.current.close());
- expect(result.current.pageThreadId).toBeNull();
- expect(result.current.threadId).toBeNull();
+ it('points an old `?thread=…&view=page` link at the thread path', () => {
+ const { result } = setup('/acme/channels/channel?thread=t1&view=page');
+ expect(result.current.legacyPageUrl).toBe('/acme/channels/channel/threads/t1');
+ expect(setup('/channels/channel?thread=t1').result.current.legacyPageUrl).toBeNull();
});
});
diff --git a/src/features/Channels/useThreadPanel.ts b/src/features/Channels/useThreadPanel.ts
index 2a89ce84348..73205e7e6e6 100644
--- a/src/features/Channels/useThreadPanel.ts
+++ b/src/features/Channels/useThreadPanel.ts
@@ -1,10 +1,11 @@
import { useEffect, useRef, useState } from 'react';
-import { useSearchParams } from 'react-router';
+import { useNavigate, useSearchParams } from 'react-router';
import { useActiveLocation } from '@/hooks/useActiveLocation';
import { cacheScope } from '@/libs/replica';
import { channelActions } from '@/store/channel';
+import { channelBasePath, matchChannelThread } from './paths';
import type { ChannelThreadDraft } from './threadDraft';
interface DraftSelection {
@@ -17,18 +18,24 @@ interface DraftSelection {
/** Opening/closing a preview is local; only its first send creates a persisted thread. */
export const useThreadPanel = (channelId: string) => {
const [params, setParams] = useSearchParams();
- const threadId = params.get('thread');
- // A thread link from the sidebar opens the thread as the page instead of beside the Channel.
- const page = !!threadId && params.get('view') === 'page';
+ const navigate = useNavigate();
const location = useActiveLocation();
+ // A thread link from the sidebar opens the thread as the page (`…/threads/:threadId`); one
+ // opened from a message shows beside the Channel (`?thread=`).
+ const pageThreadId = matchChannelThread(location.pathname) ?? null;
+ const threadId = pageThreadId ? null : params.get('thread');
+ const basePath = channelBasePath(location.pathname) ?? location.pathname;
+ // Links shared before thread pages had their own path (`?thread=…&view=page`).
+ const legacyPageThreadId =
+ !pageThreadId && params.get('view') === 'page' ? params.get('thread') : null;
const scope = cacheScope.use();
const [selection, setSelection] = useState<DraftSelection | null>(null);
const selected = useRef(selection);
const selectionRevision = useRef(0);
const renderedRevision = selectionRevision.current;
const mounted = useRef(false);
- const latest = useRef({ channelId, pathname: location.pathname, setParams, threadId });
- latest.current = { channelId, pathname: location.pathname, setParams, threadId };
+ const latest = useRef({ basePath, channelId, pathname: location.pathname, setParams, threadId });
+ latest.current = { basePath, channelId, pathname: location.pathname, setParams, threadId };
useEffect(() => {
mounted.current = true;
return () => {
@@ -42,7 +49,6 @@ export const useThreadPanel = (channelId: string) => {
const next = new URLSearchParams(current);
if (id) next.set('thread', id);
else next.delete('thread');
- next.delete('view');
return next;
},
{ replace },
@@ -67,16 +73,12 @@ export const useThreadPanel = (channelId: string) => {
};
const close = () => {
clearDraft();
- if (threadId) setThread(null);
+ if (pageThreadId) navigate(basePath);
+ else if (threadId) setThread(null);
};
const openPage = (id: string) => {
clearDraft();
- latest.current.setParams((current) => {
- const next = new URLSearchParams(current);
- next.set('thread', id);
- next.set('view', 'page');
- return next;
- });
+ navigate(`${latest.current.basePath}/threads/${encodeURIComponent(id)}`);
};
const isCurrent = (draft: DraftSelection) =>
mounted.current &&
@@ -121,9 +123,13 @@ export const useThreadPanel = (channelId: string) => {
openDraft,
openPage,
openThread,
+ /** Where an old `?thread=…&view=page` link now lives; the page redirects there. */
+ legacyPageUrl: legacyPageThreadId
+ ? `${basePath}/threads/${encodeURIComponent(legacyPageThreadId)}`
+ : null,
/** The thread shown as the page; `threadId` is then null, as no panel is open. */
- pageThreadId: page ? threadId : null,
+ pageThreadId,
send,
- threadId: page ? null : threadId,
+ threadId,
};
};
diff --git a/src/spa/router/collaborationRoutes.tsx b/src/spa/router/collaborationRoutes.tsx
index 65693c6312a..7440f621b85 100644
--- a/src/spa/router/collaborationRoutes.tsx
+++ b/src/spa/router/collaborationRoutes.tsx
@@ -79,12 +79,16 @@ export const collaborationRoutes: RouteObject[] = [
path: 'dashboard',
},
- // Channels are listed in the home sidebar; a thread opens beside its Channel via `?thread=`.
+ // Channels are listed in the home sidebar; a thread opens beside its Channel via `?thread=`,
+ // or as the page at `threads/:threadId`.
{
children: [
// No collection page: old `/channels` links return home, where the list lives.
{ element: redirectElement('..'), index: true },
{
+ // A thread opened as the page. The Channel page reads it from the path, so moving
+ // between the thread beside the Channel and the thread page keeps the page mounted.
+ children: [{ path: 'threads/:threadId' }],
element: dynamicElement(
() => import('@/routes/(main)/channels/[channelId]'),
'Desktop > Channel',
diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index ce79a63b2a0..3fa33c041c7 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -237,6 +237,16 @@ describe('desktop router shared definition', () => {
'/project/project-1/channels/chn_1',
);
expect(channelMatches?.at(-1)?.params.channelId).toBe('chn_1');
+ // A thread page stays inside its Channel's route, so the Channel page keeps rendering it.
+ const threadMatches = matchRoutes(
+ createMainAreaRoutes(factory),
+ '/project/project-1/channels/chn_1/threads/cht_1',
+ );
+ expect(threadMatches?.at(-2)?.route.path).toBe('channels/:channelId');
+ expect(threadMatches?.at(-1)?.params).toMatchObject({
+ channelId: 'chn_1',
+ threadId: 'cht_1',
+ });
// The project root is its home page (composer + overview), not a redirect.
expect(
(projectIndexRoute?.element as ReactElement<{ to?: string }> | undefined)?.props.to,
@@ -245,6 +255,16 @@ describe('desktop router shared definition', () => {
},
);
+ it.each(mainAreaVariants)(
+ '%s opens a Channel thread as a page under its Channel',
+ (_, factory) => {
+ const matches = matchRoutes(createMainAreaRoutes(factory), '/channels/chn_1/threads/cht_1');
+
+ expect(matches?.at(-2)?.route.path).toBe(':channelId');
+ expect(matches?.at(-1)?.params).toMatchObject({ channelId: 'chn_1', threadId: 'cht_1' });
+ },
+ );
+
it.each(mainAreaVariants)(
'%s opens a project acceptance record inside the project section',
(_, factory) => {
diff --git a/src/spa/router/mobileWorkspaceRoutes.tsx b/src/spa/router/mobileWorkspaceRoutes.tsx
index e0da1a727b3..0321b2cd00e 100644
--- a/src/spa/router/mobileWorkspaceRoutes.tsx
+++ b/src/spa/router/mobileWorkspaceRoutes.tsx
@@ -88,6 +88,11 @@ const projectRoutes: RouteObject[] = [
element: redirectElement('..'),
handle: undefined,
}),
+ 'channels/:channelId/threads/:threadId': (route) => ({
+ ...route,
+ element: redirectElement('../..'),
+ handle: undefined,
+ }),
'channels/:channelId/settings': (route) => ({
...route,
element: redirectElement('../..'),
diff --git a/src/spa/router/projectWorkspaceRoutes.tsx b/src/spa/router/projectWorkspaceRoutes.tsx
index 71affd96676..73ed8998cc1 100644
--- a/src/spa/router/projectWorkspaceRoutes.tsx
+++ b/src/spa/router/projectWorkspaceRoutes.tsx
@@ -49,6 +49,9 @@ export const projectWorkspaceRoute: RouteObject = {
},
{ element: <LegacyProjectConversationRedirect />, path: 'conversation/:topicId?' },
{
+ // A thread opened as the page. The Channel page reads it from the path, so moving
+ // between the thread beside the Channel and the thread page keeps the page mounted.
+ children: [{ path: 'threads/:threadId' }],
element: dynamicElement(
() => import('@/routes/(main)/project/[projectId]/channels/[channelId]'),
'Desktop > Project Channel',