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(channel): open a sidebar thread as the page instead of a side panel (#22850)

Arvin Xucd107695322b
diff --git a/locales/en-US/channel.json b/locales/en-US/channel.json
index 58f84df4143..1ac3826c2b8 100644
--- a/locales/en-US/channel.json
+++ b/locales/en-US/channel.json
@@ -134,6 +134,7 @@
"openAgent": "Open Agent",
"openAgentNamed": "Open {{name}}",
"openThread": "Open thread",
+ "openThreadPage": "Open as page",
"otherAgents": "Other Agents",
"outgoing.discard": "Delete",
"outgoing.failed": "Not sent",
diff --git a/locales/zh-CN/channel.json b/locales/zh-CN/channel.json
index 9341d34e650..80947b7ceab 100644
--- a/locales/zh-CN/channel.json
+++ b/locales/zh-CN/channel.json
@@ -134,6 +134,7 @@
"openAgent": "打开 Agent",
"openAgentNamed": "打开 {{name}}",
"openThread": "打开线程",
+ "openThreadPage": "在页面中打开",
"otherAgents": "其他 Agent",
"outgoing.discard": "删除",
"outgoing.failed": "未发送",
diff --git a/packages/const/src/url.test.ts b/packages/const/src/url.test.ts
index af689740c46..e2292658171 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');
+ expect(CHANNEL_URL('chn_1', 'cht_1')).toBe('/channels/chn_1?thread=cht_1&view=page');
});
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',
+ '/project/pro_1/channels/chn_1?thread=cht_1&view=page',
);
});
});
diff --git a/packages/const/src/url.ts b/packages/const/src/url.ts
index c86fb67d9a6..1c16ecf9880 100644
--- a/packages/const/src/url.ts
+++ b/packages/const/src/url.ts
@@ -86,8 +86,9 @@ export const GROUP_CHAT_TOPIC_URL = (groupId: string, topicId: string) =>
urlJoin('/group', groupId, topicId);
/**
- * A Channel page; a thread opens beside its Channel. A project's Channel opens inside the
- * project so its sidebar stays in place.
+ * 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
+ * inside the project so its sidebar stays in place.
*/
export const CHANNEL_URL = (
channelId: string,
@@ -95,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)}` : path;
+ return threadId ? `${path}?thread=${encodeURIComponent(threadId)}&view=page` : path;
};
export const LIBRARY_URL = (id: string) => urlJoin('/resource/library', id);
diff --git a/packages/locales/src/default/channel.ts b/packages/locales/src/default/channel.ts
index b8fd6535827..807b2b4bc57 100644
--- a/packages/locales/src/default/channel.ts
+++ b/packages/locales/src/default/channel.ts
@@ -110,6 +110,7 @@ export default {
'main': 'Channel conversation',
'startThread': 'Start thread',
'openThread': 'Open thread',
+ 'openThreadPage': 'Open as page',
'closeThread': 'Close thread',
'thread': 'Thread',
'threadDivider': 'Replies in this thread',
diff --git a/src/features/Channels/ChannelList.tsx b/src/features/Channels/ChannelList.tsx
index cc69c556b76..8da04646d85 100644
--- a/src/features/Channels/ChannelList.tsx
+++ b/src/features/Channels/ChannelList.tsx
@@ -173,7 +173,9 @@ const EnabledChannelSection = ({ itemKey = 'channels', projectId }: ChannelSecti
const activeChannelId = matchChannel(pathname);
const create = () =>
openCreateChannel((id) => navigate(CHANNEL_URL(id, null, projectId)), projectId);
- const activeThreadId = new URLSearchParams(search).get('thread');
+ // 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 menuItems = useChannelMenu();
const renderChannel = (channel: ChannelListItem) => {
diff --git a/src/features/Channels/Composer.tsx b/src/features/Channels/Composer.tsx
index fa202e19eb6..49708591e2c 100644
--- a/src/features/Channels/Composer.tsx
+++ b/src/features/Channels/Composer.tsx
@@ -120,7 +120,7 @@ export function Composer({
/** The card the mention picker docks to, full width above the input like an IM. */
const [card, setCard] = useState<HTMLDivElement | null>(null);
const requests = useSingleton(createChannelSendRequest);
- const attachments = useAttachments();
+ const attachments = useAttachments(draftKey);
const { allowed } = usePermission('create_content');
const enableUpload = useServerConfigStore((s) => featureFlagsSelectors(s).enableKnowledgeBase);
const canUpload = allowed && enableUpload;
diff --git a/src/features/Channels/ThreadPageTitle.tsx b/src/features/Channels/ThreadPageTitle.tsx
new file mode 100644
index 00000000000..e9951a28c78
--- /dev/null
+++ b/src/features/Channels/ThreadPageTitle.tsx
@@ -0,0 +1,79 @@
+import type { ChannelDetail } from '@lobechat/types';
+import { ActionIcon, cssVar, DropdownMenu, Flexbox, Icon, Text } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { ChevronRight, GitBranch, Hash, MoreHorizontal } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { channelSelectors, useChannelStore } from '@/store/channel';
+
+import { styles } from './styles';
+import { ThreadFollowers } from './ThreadPanel';
+import { threadTitle } from './threadTitle';
+import { useThreadMenu } from './useThreadMenu';
+
+/** The header of a thread opened as the page: `# Channel › thread`, the Channel leading back. */
+export const ThreadPageTitle = ({
+ detail,
+ onBack,
+ threadId,
+}: {
+ detail: ChannelDetail;
+ onBack: () => void;
+ threadId: string;
+}) => {
+ const { t } = useTranslation('channel');
+ const channelId = detail.channel.id;
+ const threadView = useChannelStore(channelSelectors.detail({ channelId, threadId }));
+ const thread = detail.threads.find((entry) => entry.id === threadId);
+ const title =
+ threadTitle(
+ threadView?.rootMessage ??
+ detail.messages.find((message) => message.id === thread?.rootMessageId),
+ ) || t('thread');
+ const channelTitle = detail.channel.title || t('title');
+
+ return (
+ <Flexbox horizontal align="center" gap={6} style={{ minWidth: 0 }}>
+ <button type="button" {...stylex.props(styles.crumb)} onClick={onBack}>
+ <Hash color={cssVar.colorTextDescription} size={16} />
+ <Text ellipsis type="secondary">
+ {channelTitle}
+ </Text>
+ </button>
+ <Icon color={cssVar.colorTextDescription} icon={ChevronRight} size={14} />
+ <Icon icon={GitBranch} size={16} />
+ <Text ellipsis title={title} weight={500}>
+ {title}
+ </Text>
+ </Flexbox>
+ );
+};
+
+/** Followers and the thread menu, as the side panel shows them. */
+export const ThreadPageActions = ({
+ detail,
+ threadId,
+}: {
+ detail: ChannelDetail;
+ threadId: string;
+}) => {
+ const { t } = useTranslation('channel');
+ const threadMenu = useThreadMenu();
+ const thread = detail.threads.find((entry) => entry.id === threadId);
+ const menuItems = thread ? threadMenu(detail.channel, thread) : [];
+ return (
+ <Flexbox horizontal align="center" gap={8}>
+ <ThreadFollowers detail={detail} target={threadId} />
+ {menuItems.length > 0 && (
+ <DropdownMenu items={menuItems}>
+ <ActionIcon
+ aria-label={t('more', { ns: 'common' })}
+ icon={MoreHorizontal}
+ size="small"
+ title={t('more', { ns: 'common' })}
+ />
+ </DropdownMenu>
+ )}
+ </Flexbox>
+ );
+};
diff --git a/src/features/Channels/ThreadPanel.tsx b/src/features/Channels/ThreadPanel.tsx
index b4904c422af..739107a1509 100644
--- a/src/features/Channels/ThreadPanel.tsx
+++ b/src/features/Channels/ThreadPanel.tsx
@@ -1,7 +1,7 @@
import type { ChannelDetail } from '@lobechat/types';
import { ActionIcon, DropdownMenu, Flexbox, Icon, Text } from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
-import { GitBranch, MoreHorizontal, X } from 'lucide-react';
+import { GitBranch, Maximize2, MoreHorizontal, X } from 'lucide-react';
import { Activity, type ComponentProps, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -23,7 +23,7 @@ export const THREAD_FLOAT_BREAKPOINT = 760;
const MAX_FOLLOWER_AVATARS = 3;
-const ThreadFollowers = ({
+export const ThreadFollowers = ({
detail,
target,
}: {
@@ -69,12 +69,14 @@ export function ThreadPanel({
threadId,
draft,
onClose,
+ onOpenPage,
onSendDraft,
}: {
availableWidth?: number;
detail: ChannelDetail;
draft: ChannelThreadDraft | null;
onClose: () => void;
+ onOpenPage: (threadId: string) => void;
onSendDraft: ComponentProps<typeof DraftThreadConversation>['onSend'];
threadId: string | null;
}) {
@@ -155,6 +157,15 @@ export function ThreadPanel({
/>
</DropdownMenu>
)}
+ {threadId && (
+ <ActionIcon
+ aria-label={t('openThreadPage')}
+ icon={Maximize2}
+ size="small"
+ title={t('openThreadPage')}
+ onClick={() => onOpenPage(threadId)}
+ />
+ )}
<ActionIcon
aria-label={t('closeThread')}
icon={X}
diff --git a/src/features/Channels/index.tsx b/src/features/Channels/index.tsx
index 07bcc60db3d..35c8c6790d7 100644
--- a/src/features/Channels/index.tsx
+++ b/src/features/Channels/index.tsx
@@ -20,14 +20,16 @@ import { visibleChannelDetail } from './channelAccess';
import { ChannelConversation } from './ChannelConversation';
import { MEMBER_FLOAT_BREAKPOINT, MemberPanel } from './MemberPanel';
import { MemberStatus } from './MemberStatus';
+import { openTopic } from './openTopic';
import { DirectReplyStatus } from './ReplyActivity';
import { type ReplyTopic, ReplyTopicPanel } from './ReplyTopicPanel';
import { styles } from './styles';
+import { ThreadPageActions, ThreadPageTitle } from './ThreadPageTitle';
import { THREAD_FLOAT_BREAKPOINT, ThreadPanel } from './ThreadPanel';
import { useAcceptancePanelOpen } from './useAcceptancePanel';
import { useThreadPanel } from './useThreadPanel';
-/** One Channel: the main conversation, with a thread beside it. */
+/** One Channel: the main conversation, with a thread beside it, or one thread as the page. */
function EnabledChannelPage() {
const { t } = useTranslation('channel');
const { channelId } = useParams<{ channelId: string }>();
@@ -50,6 +52,7 @@ function EnabledChannelPage() {
// explicitly opening another panel closes the report.
const threadId = acceptanceOpen ? null : panel.threadId;
const threadDraft = acceptanceOpen ? null : panel.draft;
+ const pageThreadId = panel.pageThreadId;
// A direct conversation's side panel is its Agent's profile; a workspace group's is the roster.
const hasMemberPanel =
!!directAgent || (!!detail?.channel.workspaceId && !detail.channel.agentId);
@@ -59,11 +62,11 @@ function EnabledChannelPage() {
!threadId &&
!threadDraft &&
!acceptanceOpen;
- // A thread or the member list replaces the topic.
- const openTopic =
- topic?.channelId === channelId && !threadId && !threadDraft && !membersOpen && !acceptanceOpen
- ? topic
- : null;
+ const visibleTopic = openTopic(topic, channelId, {
+ acceptance: acceptanceOpen,
+ members: membersOpen,
+ thread: !!(threadId || threadDraft || pageThreadId),
+ });
if (!channelId) return null;
return (
@@ -72,70 +75,90 @@ function EnabledChannelPage() {
// A rule separates the header from the feed scrolling under it.
{...stylex.props(styles.threadHeader)}
left={
- <Flexbox horizontal align="center" gap={8}>
- {/* A direct conversation is titled by its Agent's name alone, like an IM chat. */}
- {!directAgent && <Hash color={cssVar.colorTextDescription} size={16} />}
- <Text ellipsis weight={500}>
- {detail?.channel.title || t('title')}
- </Text>
- {detail?.channel.status === 'archived' && <Tag size="small">{t('archived')}</Tag>}
- {directAgent && <DirectReplyStatus detail={detail!} />}
- </Flexbox>
+ pageThreadId && detail ? (
+ <ThreadPageTitle detail={detail} threadId={pageThreadId} onBack={panel.close} />
+ ) : (
+ <Flexbox horizontal align="center" gap={8}>
+ {/* A direct conversation is titled by its Agent's name alone, like an IM chat. */}
+ {!directAgent && <Hash color={cssVar.colorTextDescription} size={16} />}
+ <Text ellipsis weight={500}>
+ {detail?.channel.title || t('title')}
+ </Text>
+ {detail?.channel.status === 'archived' && <Tag size="small">{t('archived')}</Tag>}
+ {directAgent && <DirectReplyStatus detail={detail!} />}
+ </Flexbox>
+ )
}
right={
detail && (
- <MemberStatus
- detail={detail}
- memberPanel={
- hasMemberPanel
- ? {
- id: memberPanelId,
- open: membersOpen,
- onToggle: () => {
- if (!membersOpen) {
- panel.close();
- setTopic(null);
- clearPortalStack();
- }
- setMembersChannelId(membersOpen ? null : channelId);
- },
- }
- : undefined
- }
- />
+ <Flexbox horizontal align="center" gap={8}>
+ {pageThreadId && <ThreadPageActions detail={detail} threadId={pageThreadId} />}
+ <MemberStatus
+ detail={detail}
+ memberPanel={
+ hasMemberPanel
+ ? {
+ id: memberPanelId,
+ open: membersOpen,
+ onToggle: () => {
+ if (!membersOpen) {
+ // The roster sits beside a thread page; it only replaces a side panel.
+ if (!pageThreadId) panel.close();
+ setTopic(null);
+ clearPortalStack();
+ }
+ setMembersChannelId(membersOpen ? null : channelId);
+ },
+ }
+ : undefined
+ }
+ />
+ </Flexbox>
)
}
/>
<EntityLinkHostProvider portal={CHANNEL_ENTITY_PORTAL_SCOPE}>
<Flexbox horizontal ref={conversationRef} {...stylex.props(styles.conversations)}>
- <ChannelConversation
- channelId={channelId}
- key={channelId}
- inert={
- (!!(threadId || threadDraft || acceptanceOpen) &&
- (conversationWidth ?? 1000) < THREAD_FLOAT_BREAKPOINT) ||
- (membersOpen && (conversationWidth ?? 1000) < MEMBER_FLOAT_BREAKPOINT) ||
- (!!openTopic && (conversationWidth ?? 1000) < THREAD_FLOAT_BREAKPOINT)
- }
- onOpenThread={(nextThreadId, toggle) => {
- setTopic(null);
- // A send that finishes behind an open report (toggle: false) must not close it.
- if (toggle !== false) clearPortalStack();
- // Under a report the thread only looks closed, so bring it back, don't toggle it off.
- panel.openThread(nextThreadId, acceptanceOpen ? false : toggle);
- }}
- onOpenTopic={(next) => {
- panel.close();
- setMembersChannelId(null);
- clearPortalStack();
- setTopic({ ...next, channelId });
- }}
- onStartThread={(draft) => {
- setTopic(null);
- clearPortalStack();
- panel.openDraft(draft);
- }}
- />
+ {pageThreadId ? (
+ <ChannelConversation
+ channelId={channelId}
+ key={`${channelId}:${pageThreadId}`}
+ threadId={pageThreadId}
+ inert={
+ (membersOpen && (conversationWidth ?? 1000) < MEMBER_FLOAT_BREAKPOINT) ||
+ (acceptanceOpen && (conversationWidth ?? 1000) < THREAD_FLOAT_BREAKPOINT)
+ }
+ />
+ ) : (
+ <ChannelConversation
+ channelId={channelId}
+ key={channelId}
+ inert={
+ (!!(threadId || threadDraft || acceptanceOpen) &&
+ (conversationWidth ?? 1000) < THREAD_FLOAT_BREAKPOINT) ||
+ (membersOpen && (conversationWidth ?? 1000) < MEMBER_FLOAT_BREAKPOINT) ||
+ (!!visibleTopic && (conversationWidth ?? 1000) < THREAD_FLOAT_BREAKPOINT)
+ }
+ onOpenThread={(nextThreadId, toggle) => {
+ setTopic(null);
+ // A send that finishes behind an open report (toggle: false) must not close it.
+ if (toggle !== false) clearPortalStack();
+ // Under a report the thread only looks closed, so bring it back, don't toggle it off.
+ panel.openThread(nextThreadId, acceptanceOpen ? false : toggle);
+ }}
+ onOpenTopic={(next) => {
+ panel.close();
+ setMembersChannelId(null);
+ clearPortalStack();
+ setTopic({ ...next, channelId });
+ }}
+ onStartThread={(draft) => {
+ setTopic(null);
+ clearPortalStack();
+ panel.openDraft(draft);
+ }}
+ />
+ )}
{detail &&
membersOpen &&
(directAgent?.agentId ? (
@@ -157,7 +180,7 @@ function EnabledChannelPage() {
))}
<ReplyTopicPanel
availableWidth={conversationWidth}
- topic={openTopic}
+ topic={visibleTopic}
onClose={() => setTopic(null)}
/>
{detail && (
@@ -168,6 +191,7 @@ function EnabledChannelPage() {
key={`thread:${channelId}`}
threadId={threadId}
onClose={panel.close}
+ onOpenPage={panel.openPage}
onSendDraft={panel.send}
/>
)}
diff --git a/src/features/Channels/openTopic.test.ts b/src/features/Channels/openTopic.test.ts
new file mode 100644
index 00000000000..d4a114faa04
--- /dev/null
+++ b/src/features/Channels/openTopic.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+
+import { openTopic } from './openTopic';
+
+const topic = { channelId: 'ch-1' } as Parameters<typeof openTopic>[0];
+const none = { acceptance: false, members: false, thread: false };
+
+describe('openTopic', () => {
+ it('shows the topic of the current Channel when nothing covers it', () => {
+ expect(openTopic(topic, 'ch-1', none)).toBe(topic);
+ expect(openTopic(topic, 'ch-2', none)).toBeNull();
+ });
+
+ it('hides the topic once a thread opens, including a thread opened as the page', () => {
+ expect(openTopic(topic, 'ch-1', { ...none, thread: true })).toBeNull();
+ expect(openTopic(topic, 'ch-1', { ...none, members: true })).toBeNull();
+ expect(openTopic(topic, 'ch-1', { ...none, acceptance: true })).toBeNull();
+ });
+});
diff --git a/src/features/Channels/openTopic.ts b/src/features/Channels/openTopic.ts
new file mode 100644
index 00000000000..fd32c50869f
--- /dev/null
+++ b/src/features/Channels/openTopic.ts
@@ -0,0 +1,14 @@
+import type { ReplyTopic } from './ReplyTopicPanel';
+
+/**
+ * The reply topic shown beside the Channel. A thread, as the page or beside the Channel, the
+ * member list or a report replaces it; it belongs to the Channel it was opened from.
+ */
+export const openTopic = (
+ topic: (ReplyTopic & { channelId: string }) | null,
+ channelId: string | undefined,
+ covered: { acceptance: boolean; members: boolean; thread: boolean },
+) =>
+ topic?.channelId === channelId && !covered.thread && !covered.members && !covered.acceptance
+ ? topic
+ : null;
diff --git a/src/features/Channels/styles.ts b/src/features/Channels/styles.ts
index 2e7c1c1f61c..19e04c67a89 100644
--- a/src/features/Channels/styles.ts
+++ b/src/features/Channels/styles.ts
@@ -40,6 +40,28 @@ export const styles = stylex.create({
height: '100%',
minHeight: 0,
},
+ // The Channel half of a thread page's `# Channel › thread` title, leading back to the Channel.
+ crumb: {
+ display: 'flex',
+ flexShrink: 0,
+ gap: 8,
+ alignItems: 'center',
+ maxWidth: 200,
+ minWidth: 0,
+ marginBlock: 0,
+ marginInline: 0,
+ paddingBlock: 2,
+ paddingInline: 4,
+ borderWidth: 0,
+ borderStyle: 'none',
+ borderRadius: 6,
+ font: 'inherit',
+ backgroundColor: {
+ default: 'transparent',
+ [HOVER]: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },
+ },
+ cursor: 'pointer',
+ },
threadHeader: {
borderBlockEndWidth: 1,
borderBlockEndStyle: 'solid',
diff --git a/src/features/Channels/useAttachments.test.ts b/src/features/Channels/useAttachments.test.ts
index ec03fd5e352..58a3a10ad75 100644
--- a/src/features/Channels/useAttachments.test.ts
+++ b/src/features/Channels/useAttachments.test.ts
@@ -25,7 +25,7 @@ describe('useAttachments local image previews', () => {
const create = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:shot');
const revoke = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
upload.mockResolvedValue({ id: 'file-1', url: 'https://cdn/shot.png' });
- const { result } = renderHook(() => useAttachments());
+ const { result } = renderHook(() => useAttachments('channel:ch-1:main'));
await act(() =>
result.current.upload([
@@ -43,3 +43,50 @@ describe('useAttachments local image previews', () => {
expect(revoke).toHaveBeenCalledWith('blob:shot');
});
});
+
+describe('useAttachments across composers of one conversation', () => {
+ afterEach(() => vi.useRealTimers());
+
+ it('hands files and running uploads to the composer that takes over the thread', async () => {
+ vi.useFakeTimers();
+ let finish: (value: { id: string; url: string }) => void = () => {};
+ upload.mockReturnValue(new Promise((resolve) => (finish = resolve)));
+ const panel = renderHook(() => useAttachments('channel:ch-1:thread-1'));
+ act(() => {
+ void panel.result.current.upload([new File(['x'], 'notes.txt', { type: 'text/plain' })]);
+ });
+ await act(async () => {});
+ const signal = upload.mock.calls.at(-1)![0].abortController.signal as AbortSignal;
+
+ // Opening the thread as the page: the page composer mounts as the panel one goes away.
+ const page = renderHook(() => useAttachments('channel:ch-1:thread-1'));
+ panel.unmount();
+ await act(() => vi.runAllTimersAsync());
+
+ expect(signal.aborted).toBe(false);
+ expect(page.result.current.items).toHaveLength(1);
+ await act(async () => finish({ id: 'file-1', url: 'https://cdn/notes.txt' }));
+ expect(page.result.current.items[0]).toMatchObject({ fileId: 'file-1', status: 'success' });
+
+ // Nobody writes to the thread any more: its uploads stop and the draft is released.
+ page.unmount();
+ await act(() => vi.runAllTimersAsync());
+ const again = renderHook(() => useAttachments('channel:ch-1:thread-1'));
+ expect(again.result.current.items).toHaveLength(0);
+ });
+
+ it('aborts a running upload once its last composer is gone', async () => {
+ vi.useFakeTimers();
+ upload.mockReturnValue(new Promise(() => {}));
+ const composer = renderHook(() => useAttachments('channel:ch-1:thread-2'));
+ act(() => {
+ void composer.result.current.upload([new File(['x'], 'a.txt', { type: 'text/plain' })]);
+ });
+ await act(async () => {});
+ const signal = upload.mock.calls.at(-1)![0].abortController.signal as AbortSignal;
+
+ composer.unmount();
+ await act(() => vi.runAllTimersAsync());
+ expect(signal.aborted).toBe(true);
+ });
+});
diff --git a/src/features/Channels/useAttachments.ts b/src/features/Channels/useAttachments.ts
index 4ae2243b16e..7d9fc4d5578 100644
--- a/src/features/Channels/useAttachments.ts
+++ b/src/features/Channels/useAttachments.ts
@@ -1,7 +1,7 @@
import { CHANNEL_LIMITS, type UploadFileItem } from '@lobechat/types';
import { COMPRESSIBLE_IMAGE_TYPES, compressImageFile } from '@lobechat/utils/compressImage';
import { toast } from '@lobehub/ui';
-import { useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useSyncExternalStore } from 'react';
import { useTranslation } from 'react-i18next';
import { FILE_UPLOAD_BLACKLIST } from '@/const/file';
@@ -16,28 +16,65 @@ const releasePreview = (item: DraftFile) => {
if (item.previewUrl?.startsWith('blob:')) URL.revokeObjectURL(item.previewUrl);
};
-/** Each mounted Channel composer owns its uploads; ordinary chat's global draft is untouched. */
-export function useAttachments() {
+interface AttachmentDraft {
+ items: DraftFile[];
+ listeners: Set<() => void>;
+ mounts: number;
+}
+
+/**
+ * Attachments belong to the conversation a composer writes to, not to one mounted composer, so
+ * a thread moving between the side panel and the page keeps its files and running uploads.
+ */
+const drafts = new Map<string, AttachmentDraft>();
+
+const draftFor = (key: string) => {
+ let draft = drafts.get(key);
+ if (!draft) {
+ draft = { items: [], listeners: new Set(), mounts: 0 };
+ drafts.set(key, draft);
+ }
+ return draft;
+};
+
+/** Each Channel/Thread composer owns its uploads; ordinary chat's global draft is untouched. */
+export function useAttachments(draftKey: string) {
const { t } = useTranslation('channel');
const upload = useFileStore((s) => s.uploadWithProgress);
- const [items, setItems] = useState<DraftFile[]>([]);
- const current = useRef(items);
+ const draft = draftFor(draftKey);
+ const subscribe = useCallback(
+ (listener: () => void) => {
+ draft.listeners.add(listener);
+ return () => draft.listeners.delete(listener);
+ },
+ [draft],
+ );
+ const items = useSyncExternalStore(subscribe, () => draft.items);
const update = (next: DraftFile[]) => {
- current.current = next;
- setItems(next);
+ draft.items = next;
+ for (const listener of draft.listeners) listener();
};
const patch = (id: string, value: Partial<DraftFile>) =>
- update(current.current.map((item) => (item.id === id ? { ...item, ...value, id } : item)));
+ update(draft.items.map((item) => (item.id === id ? { ...item, ...value, id } : item)));
- useEffect(
- () => () => {
- for (const item of current.current) {
- item.abortController?.abort();
- releasePreview(item);
- }
- },
- [],
- );
+ useEffect(() => {
+ // A composer shown again after its draft was released starts it afresh.
+ if (!drafts.has(draftKey)) drafts.set(draftKey, draft);
+ draft.mounts += 1;
+ return () => {
+ draft.mounts -= 1;
+ // Wait a tick: the composer taking over this conversation mounts in the same commit.
+ setTimeout(() => {
+ if (draft.mounts > 0 || drafts.get(draftKey) !== draft) return;
+ drafts.delete(draftKey);
+ for (const item of draft.items) {
+ item.abortController?.abort();
+ releasePreview(item);
+ }
+ update([]);
+ });
+ };
+ }, [draft, draftKey]);
const run = async (item: DraftFile) => {
const abortController = new AbortController();
@@ -74,12 +111,12 @@ export function useAttachments() {
blocked: items.some((item) => item.status !== 'success'),
// Read synchronously so Enter cannot race a just-started upload before React renders.
readyFileIds: () =>
- current.current.every((item) => item.status === 'success' && item.fileId)
- ? current.current.map((item) => item.fileId!)
+ draft.items.every((item) => item.status === 'success' && item.fileId)
+ ? draft.items.map((item) => item.fileId!)
: undefined,
upload: async (files: File[]) => {
const accepted = files.filter((file) => !FILE_UPLOAD_BLACKLIST.includes(file.name));
- if (current.current.length + accepted.length > CHANNEL_LIMITS.attachments) {
+ if (draft.items.length + accepted.length > CHANNEL_LIMITS.attachments) {
toast.error(t('attachments.limit', { count: CHANNEL_LIMITS.attachments }));
return;
}
@@ -89,22 +126,22 @@ export function useAttachments() {
previewUrl: localPreview(file),
status: 'pending',
}));
- update([...current.current, ...added]);
+ update([...draft.items, ...added]);
await Promise.all(added.map(run));
},
remove: (id: string) => {
- const removed = current.current.find((item) => item.id === id);
+ const removed = draft.items.find((item) => item.id === id);
removed?.abortController?.abort();
if (removed) releasePreview(removed);
- update(current.current.filter((item) => item.id !== id));
+ update(draft.items.filter((item) => item.id !== id));
},
retry: (id: string) => {
- const item = current.current.find((item) => item.id === id);
+ const item = draft.items.find((item) => item.id === id);
if (item?.status === 'error') void run(item);
},
// A sent draft's images are shown from their uploaded URLs; the local copies can go.
clear: () => {
- for (const item of current.current) releasePreview(item);
+ for (const item of draft.items) releasePreview(item);
update([]);
},
};
diff --git a/src/features/Channels/useThreadPanel.test.ts b/src/features/Channels/useThreadPanel.test.ts
index fe748b66332..bc9a4ada10e 100644
--- a/src/features/Channels/useThreadPanel.test.ts
+++ b/src/features/Channels/useThreadPanel.test.ts
@@ -16,11 +16,11 @@ const draft = (id = 'root'): ChannelThreadDraft => ({
attachments: [],
root: { id } as ChannelPublicMessage,
});
-const setup = () =>
+const setup = (entry = '/channels/channel') =>
renderHook(({ channelId }) => useThreadPanel(channelId), {
initialProps: { channelId: 'channel' },
wrapper: ({ children }: { children: ReactNode }) =>
- createElement(MemoryRouter, { initialEntries: ['/channels/channel'] }, children),
+ createElement(MemoryRouter, { initialEntries: [entry] }, children),
});
describe('Local thread preview', () => {
@@ -130,3 +130,26 @@ describe('Local thread preview', () => {
expect(send).not.toHaveBeenCalled();
});
});
+
+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('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();
+ });
+});
diff --git a/src/features/Channels/useThreadPanel.ts b/src/features/Channels/useThreadPanel.ts
index 1a4bc12b6f0..2a89ce84348 100644
--- a/src/features/Channels/useThreadPanel.ts
+++ b/src/features/Channels/useThreadPanel.ts
@@ -18,6 +18,8 @@ interface DraftSelection {
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 location = useActiveLocation();
const scope = cacheScope.use();
const [selection, setSelection] = useState<DraftSelection | null>(null);
@@ -40,6 +42,7 @@ 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 },
@@ -66,6 +69,15 @@ export const useThreadPanel = (channelId: string) => {
clearDraft();
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;
+ });
+ };
const isCurrent = (draft: DraftSelection) =>
mounted.current &&
selected.current === draft &&
@@ -107,8 +119,11 @@ export const useThreadPanel = (channelId: string) => {
? selection.value
: null,
openDraft,
+ openPage,
openThread,
+ /** The thread shown as the page; `threadId` is then null, as no panel is open. */
+ pageThreadId: page ? threadId : null,
send,
- threadId,
+ threadId: page ? null : threadId,
};
};