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(chat): collapse FloatingChatPanel into a slim strip by default (#15991)

Innei9d4bb09aa5e4
diff --git a/apps/server/src/routers/lambda/__tests__/agentDocument.chatTopic.test.ts b/apps/server/src/routers/lambda/__tests__/agentDocument.chatTopic.test.ts
new file mode 100644
index 00000000000..cfbf6e59af1
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/agentDocument.chatTopic.test.ts
@@ -0,0 +1,146 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as AgentDocumentModels from '@/database/models/agentDocuments';
+import { createCallerFactory } from '@/libs/trpc/lambda';
+import { createContextInner } from '@/libs/trpc/lambda/context';
+import { AgentDocumentsService } from '@/server/services/agentDocuments';
+
+import { agentDocumentRouter } from '../agentDocument';
+
+const mocks = vi.hoisted(() => ({
+ associate: vi.fn(),
+ createTopic: vi.fn(),
+ findByAgentAndDocumentTrigger: vi.fn(),
+ findRowByDocumentId: vi.fn(),
+ getServerDB: vi.fn(),
+}));
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: mocks.getServerDB,
+}));
+
+vi.mock('@/database/models/agentDocuments', async (importOriginal) => {
+ const actual = await importOriginal<typeof AgentDocumentModels>();
+
+ return {
+ ...actual,
+ AgentDocumentModel: vi.fn(),
+ };
+});
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(() => ({
+ create: mocks.createTopic,
+ findByAgentAndDocumentTrigger: mocks.findByAgentAndDocumentTrigger,
+ })),
+}));
+
+vi.mock('@/database/models/topicDocument', () => ({
+ TopicDocumentModel: vi.fn().mockImplementation(() => ({
+ associate: mocks.associate,
+ })),
+}));
+
+vi.mock('@/server/services/agentDocuments', () => ({
+ AgentDocumentsService: vi.fn(),
+}));
+
+vi.mock('@/server/services/agentDocumentVfs', () => ({
+ AgentDocumentVfsService: vi.fn(),
+}));
+
+vi.mock('@/server/services/agentDocuments/toolOutcome', () => ({
+ emitAgentDocumentToolOutcomeSafely: vi.fn(),
+}));
+
+const createCaller = createCallerFactory(agentDocumentRouter);
+
+describe('agentDocumentRouter.getOrCreateChatTopic', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getServerDB.mockResolvedValue({ kind: 'server-db' });
+
+ vi.mocked(AgentDocumentsService).mockImplementation(
+ () =>
+ ({ findRowByDocumentId: mocks.findRowByDocumentId }) as unknown as AgentDocumentsService,
+ );
+ });
+
+ it('returns the existing topic when a doc-anchored row is already linked', async () => {
+ mocks.findByAgentAndDocumentTrigger.mockResolvedValue({ id: 'topic-existing' });
+
+ const caller = createCaller(await createContextInner({ userId: 'user-1' }));
+ const result = await caller.getOrCreateChatTopic({
+ agentId: 'agent-1',
+ documentId: 'docs_abc',
+ });
+
+ expect(result).toEqual({ topicId: 'topic-existing' });
+ expect(mocks.findByAgentAndDocumentTrigger).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ documentId: 'docs_abc',
+ trigger: 'document',
+ });
+ expect(mocks.createTopic).not.toHaveBeenCalled();
+ expect(mocks.associate).not.toHaveBeenCalled();
+ });
+
+ it('creates a new doc-anchored topic and associates it when none exists', async () => {
+ mocks.findByAgentAndDocumentTrigger.mockResolvedValue(undefined);
+ mocks.findRowByDocumentId.mockResolvedValue({
+ filename: 'spec.md',
+ id: 'agent-document-1',
+ title: 'Spec',
+ });
+ mocks.createTopic.mockResolvedValue({ id: 'topic-new' });
+
+ const caller = createCaller(await createContextInner({ userId: 'user-1' }));
+ const result = await caller.getOrCreateChatTopic({
+ agentId: 'agent-1',
+ documentId: 'docs_abc',
+ });
+
+ expect(result).toEqual({ topicId: 'topic-new' });
+ expect(mocks.createTopic).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ title: 'Spec',
+ trigger: 'document',
+ });
+ expect(mocks.associate).toHaveBeenCalledWith({
+ documentId: 'docs_abc',
+ topicId: 'topic-new',
+ });
+ });
+
+ it('falls back to the filename when the document has no title', async () => {
+ mocks.findByAgentAndDocumentTrigger.mockResolvedValue(undefined);
+ mocks.findRowByDocumentId.mockResolvedValue({
+ filename: 'fallback.md',
+ id: 'agent-document-1',
+ title: undefined,
+ });
+ mocks.createTopic.mockResolvedValue({ id: 'topic-new' });
+
+ const caller = createCaller(await createContextInner({ userId: 'user-1' }));
+ await caller.getOrCreateChatTopic({ agentId: 'agent-1', documentId: 'docs_abc' });
+
+ expect(mocks.createTopic).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ title: 'fallback.md',
+ trigger: 'document',
+ });
+ });
+
+ it('throws NOT_FOUND when the document is missing or not owned by the agent', async () => {
+ mocks.findByAgentAndDocumentTrigger.mockResolvedValue(undefined);
+ mocks.findRowByDocumentId.mockResolvedValue(undefined);
+
+ const caller = createCaller(await createContextInner({ userId: 'user-1' }));
+ await expect(
+ caller.getOrCreateChatTopic({ agentId: 'agent-1', documentId: 'docs_missing' }),
+ ).rejects.toThrow(/Document not found/);
+ expect(mocks.createTopic).not.toHaveBeenCalled();
+ expect(mocks.associate).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentDocument.ts b/apps/server/src/routers/lambda/agentDocument.ts
index 64919e37ee4..45df9546a89 100644
--- a/apps/server/src/routers/lambda/agentDocument.ts
+++ b/apps/server/src/routers/lambda/agentDocument.ts
@@ -8,6 +8,7 @@ import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { TopicTrigger } from '@/const/topic';
import { AgentDocumentModel } from '@/database/models/agentDocuments';
import { TopicModel } from '@/database/models/topic';
import { TopicDocumentModel } from '@/database/models/topicDocument';
@@ -254,6 +255,56 @@ export const agentDocumentRouter = router({
return ctx.agentDocumentService.getDocument(input.agentId, input.filename);
}),
+ /**
+ * Return the chat topic that anchors the doc-scoped conversation for this
+ * `(documentId, agentId)` pair, creating it idempotently on the first call.
+ *
+ * Topics are marked with `trigger='document'` so they stay out of the main
+ * sidebar history (`MAIN_SIDEBAR_EXCLUDE_TRIGGERS` already excludes them).
+ * The mapping is persisted through `topic_documents`, so subsequent calls
+ * resolve the same topic id.
+ */
+ getOrCreateChatTopic: agentDocumentProcedure
+ .input(
+ z.object({
+ agentId: z.string(),
+ documentId: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const existing = await ctx.topicModel.findByAgentAndDocumentTrigger({
+ agentId: input.agentId,
+ documentId: input.documentId,
+ trigger: TopicTrigger.Document,
+ });
+ if (existing) return { topicId: existing.id };
+
+ const document = await ctx.agentDocumentService.findRowByDocumentId(
+ input.agentId,
+ input.documentId,
+ );
+ if (!document) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: `Document not found for agentId=${input.agentId}`,
+ });
+ }
+
+ const title = document.title || document.filename || 'Document chat';
+ const topic = await ctx.topicModel.create({
+ agentId: input.agentId,
+ title,
+ trigger: TopicTrigger.Document,
+ });
+
+ await ctx.topicDocumentModel.associate({
+ documentId: input.documentId,
+ topicId: topic.id,
+ });
+
+ return { topicId: topic.id };
+ }),
+
/**
* Create or update a document
*/
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 9c2161dffe4..de6bb470bb5 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -176,6 +176,8 @@
"extendParams.title": "Model Extension Features",
"extendParams.urlContext.desc": "When enabled, web links will be automatically parsed to retrieve the actual webpage context content",
"extendParams.urlContext.title": "Extract Webpage Link Content",
+ "floatingChatPanel.collapse": "Collapse chat",
+ "floatingChatPanel.expand": "Expand chat",
"followUpPlaceholder": "Follow up.",
"followUpPlaceholderHeterogeneous": "Follow up.",
"gatewayMode.beta": "Beta",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 576e0394550..eeb610f413d 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -176,6 +176,8 @@
"extendParams.title": "模型扩展功能",
"extendParams.urlContext.desc": "开启后会自动解析网页链接,提取网页内容作为上下文",
"extendParams.urlContext.title": "提取网页链接内容",
+ "floatingChatPanel.collapse": "收起聊天",
+ "floatingChatPanel.expand": "展开聊天",
"followUpPlaceholder": "继续跟进。",
"followUpPlaceholderHeterogeneous": "继续跟进。",
"gatewayMode.beta": "Beta",
diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.ts
index dfbc04b91e9..0469c7d8384 100644
--- a/packages/database/src/models/recent.ts
+++ b/packages/database/src/models/recent.ts
@@ -21,7 +21,7 @@ export interface RecentDbItem {
// Mirrors `MAIN_SIDEBAR_EXCLUDE_TRIGGERS` in `src/const/topic.ts` plus the
// legacy `task_manager` trigger from the previous Task Manager panel.
// System-trigger topics live in their own surfaces and would clutter Recent.
-const SYSTEM_TOPIC_TRIGGERS = ['cron', 'eval', 'task_manager', 'task'];
+const SYSTEM_TOPIC_TRIGGERS = ['cron', 'eval', 'task_manager', 'task', 'document'];
// Excluded so tool-owned document rows don't surface as generic recent docs;
// only user-authored pages ('api') and legacy 'topic' rows remain.
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index dc1fc8b5d9a..2f6793a8bd5 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -30,7 +30,7 @@ import {
} from 'drizzle-orm';
import type { TopicItem } from '../schemas';
-import { agents, messagePlugins, messages, threads, topics } from '../schemas';
+import { agents, messagePlugins, messages, threads, topicDocuments, topics } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { sanitizeBm25Query } from '../utils/bm25';
import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../utils/genWhere';
@@ -452,6 +452,33 @@ export class TopicModel {
});
};
+ /**
+ * Find the unique topic an agent shares with a document for a given trigger
+ * (e.g. the doc-anchored chat topic provisioned by
+ * `agentDocument.getOrCreateChatTopic`). Joins through `topic_documents`.
+ */
+ findByAgentAndDocumentTrigger = async (params: {
+ agentId: string;
+ documentId: string;
+ trigger: string;
+ }): Promise<TopicItem | undefined> => {
+ const result = await this.db
+ .select({ topic: topics })
+ .from(topics)
+ .innerJoin(topicDocuments, eq(topicDocuments.topicId, topics.id))
+ .where(
+ and(
+ this.ownership(),
+ eq(topics.agentId, params.agentId),
+ eq(topics.trigger, params.trigger),
+ eq(topicDocuments.documentId, params.documentId),
+ ),
+ )
+ .limit(1);
+
+ return result[0]?.topic;
+ };
+
/**
* Query the current user's topics, optionally filtered by status. Used by the
* Fleet view to list actively-running topics across all agents without
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 4c5fd4b2bbf..dd5b2975000 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -554,6 +554,8 @@ export default {
'searchAgentPlaceholder': 'Search agents...',
'searchAgents': 'Search agents...',
'selectedAgents': 'Selected agents',
+ 'floatingChatPanel.collapse': 'Collapse chat',
+ 'floatingChatPanel.expand': 'Expand chat',
'followUpPlaceholder': 'Follow up.',
'followUpPlaceholderHeterogeneous': 'Follow up.',
'sendPlaceholder': 'Ask, create, or start a task, <hotkey><hotkey/>',
diff --git a/src/const/topic.ts b/src/const/topic.ts
index bc84246fac3..ca0d0381334 100644
--- a/src/const/topic.ts
+++ b/src/const/topic.ts
@@ -3,19 +3,25 @@
*
* `RunTask` is what `TaskRunnerService` writes when starting an agent run for
* a task; the literal `'task'` is intentional and matches existing DB rows.
+ * `Document` marks topics auto-provisioned for an agent ↔ document chat panel
+ * (see `agentDocument.getOrCreateChatTopic`); these are surfaced through the
+ * document UI and should stay out of the main agent chat history.
*/
export const TopicTrigger = {
Cron: 'cron',
+ Document: 'document',
Eval: 'eval',
RunTask: 'task',
} as const;
/**
* Triggers to exclude from the main chat sidebar so system-owned topics
- * (cron jobs, evals, task runs) don't pollute the user's main history.
+ * (cron jobs, evals, task runs, doc-anchored chat) don't pollute the user's
+ * main history.
*/
export const MAIN_SIDEBAR_EXCLUDE_TRIGGERS: string[] = [
TopicTrigger.Cron,
+ TopicTrigger.Document,
TopicTrigger.Eval,
TopicTrigger.RunTask,
];
diff --git a/src/features/AgentDocumentPage/index.test.tsx b/src/features/AgentDocumentPage/index.test.tsx
new file mode 100644
index 00000000000..960923a3a84
--- /dev/null
+++ b/src/features/AgentDocumentPage/index.test.tsx
@@ -0,0 +1,136 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import AgentDocumentPage from './index';
+
+vi.mock('react-router-dom', () => ({
+ useParams: () => ({ aid: 'agent-from-url' }),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...(props as Record<string, unknown>)}>{children}</div>
+ ),
+}));
+
+vi.mock('@/features/PageEditor', () => ({
+ PageEditor: ({ pageId, header }: { header?: ReactNode; pageId?: string }) => (
+ <div data-page-id={pageId} data-testid="page-editor">
+ {header}
+ </div>
+ ),
+}));
+
+vi.mock('@/features/WideScreenContainer', () => ({
+ default: ({ children }: { children?: ReactNode }) => (
+ <div data-testid="wide-screen-container">{children}</div>
+ ),
+}));
+
+vi.mock('./Header', () => ({
+ default: ({ documentId }: { documentId?: string }) => (
+ <div data-document-id={documentId} data-testid="header" />
+ ),
+}));
+
+vi.mock('./useAgentDocumentItem', () => ({
+ useAgentDocumentItem: () => ({
+ item: { filename: 'spec.md', id: 'agent-document-1', title: 'Spec' },
+ mutate: vi.fn(),
+ }),
+}));
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => vi.fn(),
+}));
+
+const docChatTopicState = vi.hoisted(() => ({
+ current: {
+ error: undefined as Error | undefined,
+ isLoading: false,
+ topicId: 'doc-topic-1' as string | undefined,
+ },
+}));
+vi.mock('@/features/FloatingChatPanel/useDocumentChatTopic', () => ({
+ useDocumentChatTopic: () => docChatTopicState.current,
+}));
+
+const panelProps = vi.hoisted(() => ({
+ current: undefined as undefined | Record<string, unknown>,
+}));
+
+vi.mock('@/features/FloatingChatPanel', () => ({
+ default: (props: Record<string, unknown>) => {
+ panelProps.current = props;
+ return <div data-testid="floating-chat-panel" />;
+ },
+}));
+
+const mockUserState = vi.hoisted(() => ({
+ current: {
+ preference: { lab: { enableAgentDocumentFloatingChatPanel: false } },
+ },
+}));
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: any) => selector(mockUserState.current),
+}));
+
+vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: {
+ enableAgentDocumentFloatingChatPanel: (s: any) =>
+ s.preference.lab.enableAgentDocumentFloatingChatPanel,
+ },
+}));
+
+describe('AgentDocumentPage', () => {
+ beforeEach(() => {
+ mockUserState.current.preference.lab.enableAgentDocumentFloatingChatPanel = false;
+ docChatTopicState.current = {
+ error: undefined,
+ isLoading: false,
+ topicId: 'doc-topic-1',
+ };
+ panelProps.current = undefined;
+ });
+
+ afterEach(() => {
+ panelProps.current = undefined;
+ });
+
+ it('renders the PageEditor wired to the supplied documentId', () => {
+ render(<AgentDocumentPage documentId="docs_abc" />);
+ expect(screen.getByTestId('page-editor').dataset.pageId).toBe('docs_abc');
+ expect(screen.getByTestId('header').dataset.documentId).toBe('docs_abc');
+ });
+
+ it('does not render FloatingChatPanel when the lab feature is disabled', () => {
+ render(<AgentDocumentPage documentId="docs_abc" />);
+ expect(screen.queryByTestId('floating-chat-panel')).toBeNull();
+ });
+
+ it('renders FloatingChatPanel anchored on the URL agent + doc-scoped topic', () => {
+ mockUserState.current.preference.lab.enableAgentDocumentFloatingChatPanel = true;
+ render(<AgentDocumentPage documentId="docs_abc" />);
+
+ const container = screen.getByTestId('wide-screen-container');
+ const panel = screen.getByTestId('floating-chat-panel');
+ expect(container).toContainElement(panel);
+ expect(panelProps.current).toMatchObject({
+ agentDocumentId: 'agent-document-1',
+ agentId: 'agent-from-url',
+ documentId: 'docs_abc',
+ topicId: 'doc-topic-1',
+ });
+ });
+
+ it('skips the panel until the doc-anchored topic id resolves', () => {
+ mockUserState.current.preference.lab.enableAgentDocumentFloatingChatPanel = true;
+ docChatTopicState.current = { error: undefined, isLoading: true, topicId: undefined };
+ render(<AgentDocumentPage documentId="docs_abc" />);
+ expect(screen.queryByTestId('floating-chat-panel')).toBeNull();
+ });
+});
diff --git a/src/features/AgentDocumentPage/index.tsx b/src/features/AgentDocumentPage/index.tsx
index cbc44f1a1b7..ef950b36930 100644
--- a/src/features/AgentDocumentPage/index.tsx
+++ b/src/features/AgentDocumentPage/index.tsx
@@ -1,10 +1,16 @@
'use client';
+import { Flexbox } from '@lobehub/ui';
import { memo, useCallback, useMemo } from 'react';
import { useParams } from 'react-router-dom';
+import FloatingChatPanel from '@/features/FloatingChatPanel';
+import { useDocumentChatTopic } from '@/features/FloatingChatPanel/useDocumentChatTopic';
import { PageEditor } from '@/features/PageEditor';
+import WideScreenContainer from '@/features/WideScreenContainer';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useUserStore } from '@/store/user';
+import { labPreferSelectors } from '@/store/user/selectors';
import Header from './Header';
import { useAgentDocumentItem } from './useAgentDocumentItem';
@@ -27,6 +33,18 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {
const navigate = useWorkspaceAwareNavigate();
const { item, mutate, skillBundle } = useAgentDocumentItem(agentId, documentId);
+ const enableFloatingChatPanel = useUserStore(
+ labPreferSelectors.enableAgentDocumentFloatingChatPanel,
+ );
+ // The route owns the agent — `useChatStore.activeAgentId` can be a different
+ // agent (the user's main chat context). Pulling that one would 404 the
+ // doc-anchored topic lookup whenever the active agent doesn't own this doc.
+ const chatAgentId = agentId;
+ const { topicId: docChatTopicId } = useDocumentChatTopic({
+ agentId: enableFloatingChatPanel ? chatAgentId : undefined,
+ documentId: enableFloatingChatPanel ? documentId : undefined,
+ });
+
const backToChat = useCallback(
() => navigate(agentId ? `/agent/${agentId}` : '/agent'),
[agentId, navigate],
@@ -54,23 +72,38 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {
);
return (
- <PageEditor
- fullWidthHeader
- header={header}
- key={documentId}
- // A skill index's visible name is the bundle title; renaming must go
- // through the skill APIs, so lock the page title/emoji here. A plain
- // title save would overwrite the `SKILL.md` filename and desync the
- // bundle (and the bundle rename API rejects managed skill docs anyway).
- metaReadOnly={isSkillIndex}
- pageId={documentId}
- rightPanel={false}
- syncPageAgentActiveState={false}
- title={title}
- // Refresh the list so the breadcrumb and working-sidebar entry pick up
- // the new title after the shared page save persists it.
- onTitleChange={() => mutate()}
- />
+ <Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }} width={'100%'}>
+ <Flexbox flex={1} style={{ minHeight: 0 }} width={'100%'}>
+ <PageEditor
+ fullWidthHeader
+ header={header}
+ key={documentId}
+ // A skill index's visible name is the bundle title; renaming must go
+ // through the skill APIs, so lock the page title/emoji here. A plain
+ // title save would overwrite the `SKILL.md` filename and desync the
+ // bundle (and the bundle rename API rejects managed skill docs anyway).
+ metaReadOnly={isSkillIndex}
+ pageId={documentId}
+ rightPanel={false}
+ syncPageAgentActiveState={false}
+ title={title}
+ // Refresh the list so the breadcrumb and working-sidebar entry pick up
+ // the new title after the shared page save persists it.
+ onTitleChange={() => mutate()}
+ />
+ </Flexbox>
+ {enableFloatingChatPanel && chatAgentId && docChatTopicId && (
+ <WideScreenContainer>
+ <FloatingChatPanel
+ agentDocumentId={item?.id}
+ agentId={chatAgentId}
+ documentId={documentId}
+ key={`${chatAgentId}:${docChatTopicId}:${documentId}`}
+ topicId={docChatTopicId}
+ />
+ </WideScreenContainer>
+ )}
+ </Flexbox>
);
});
diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsx
index e7adc46316e..8fff8003205 100644
--- a/src/features/ChatInput/Desktop/index.tsx
+++ b/src/features/ChatInput/Desktop/index.tsx
@@ -62,6 +62,13 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
interface DesktopChatInputProps extends ActionToolbarProps {
actionBarStyle?: React.CSSProperties;
+ /**
+ * Collapse the editor to a single bordered row by dropping the action bar footer.
+ * Send still works through the Enter keybinding; the rest of the chrome
+ * (control bar / footnote) is independently gated by `showControlBar` /
+ * `showFootnote`. Defaults to false — other surfaces stay untouched.
+ */
+ compact?: boolean;
/**
* Custom node to render in place of the default ControlBar.
* When provided, used instead of `<ControlBar />` (ignores `showControlBar`).
@@ -89,6 +96,7 @@ const DesktopChatInput = memo<DesktopChatInputProps>(
({
showFootnote,
showControlBar = true,
+ compact = false,
controlBarSlot,
inputContainerProps,
extentHeaderContent,
@@ -168,31 +176,33 @@ const DesktopChatInput = memo<DesktopChatInputProps>(
resize={true}
slashMenuRef={slashMenuRef}
footer={
- <ChatInputActionBar
- style={actionBarStyle ?? { paddingRight: 8 }}
- left={
- loadingLeftSlot ??
- leftContent ?? (
- <ActionBar
- borderRadius={borderRadius}
- dropdownPlacement={dropdownPlacement}
- extraActionItems={extraActionItems}
- />
- )
- }
- right={
- loadingRightSlot ??
- rightContent ??
- (sendAreaPrefix ? (
- <Flexbox horizontal align={'center'} gap={6}>
- {sendAreaPrefix}
+ compact ? undefined : (
+ <ChatInputActionBar
+ style={actionBarStyle ?? { paddingRight: 8 }}
+ left={
+ loadingLeftSlot ??
+ leftContent ?? (
+ <ActionBar
+ borderRadius={borderRadius}
+ dropdownPlacement={dropdownPlacement}
+ extraActionItems={extraActionItems}
+ />
+ )
+ }
+ right={
+ loadingRightSlot ??
+ rightContent ??
+ (sendAreaPrefix ? (
+ <Flexbox horizontal align={'center'} gap={6}>
+ {sendAreaPrefix}
+ <SendArea />
+ </Flexbox>
+ ) : (
<SendArea />
- </Flexbox>
- ) : (
- <SendArea />
- ))
- }
- />
+ ))
+ }
+ />
+ )
}
header={
<Flexbox gap={0}>
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index ae52acc5628..376d7f4bb33 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -109,6 +109,12 @@ export interface ChatInputProps {
* Use this to add custom UI like error alerts, MessageFromUrl, etc.
*/
children?: ReactNode;
+ /**
+ * Render the editor as a single-row strip by dropping the action bar footer.
+ * Send still works through Enter; pair with `showControlBar={false}` to also
+ * drop the control bar. Defaults to false — other chat surfaces stay untouched.
+ */
+ compact?: boolean;
/**
* Custom node to render in place of the default ControlBar
* (Local/Cloud/Approval). When provided, replaces the default bar.
@@ -197,6 +203,7 @@ const ChatInput = memo<ChatInputProps>(
({
actionBarStyle,
allowExpand,
+ compact = false,
disableFollowUpVariant,
disableQueue,
disableSend,
@@ -400,6 +407,7 @@ const ChatInput = memo<ChatInputProps>(
<DesktopChatInput
actionBarStyle={actionBarStyle}
borderRadius={12}
+ compact={compact}
controlBarSlot={controlBarSlot}
extraActionItems={extraActionItems}
hidden={hasPendingInterventions}
diff --git a/src/features/FloatingChatPanel/ChatBody.test.tsx b/src/features/FloatingChatPanel/ChatBody.test.tsx
index cb7002ffa14..c873ddbe553 100644
--- a/src/features/FloatingChatPanel/ChatBody.test.tsx
+++ b/src/features/FloatingChatPanel/ChatBody.test.tsx
@@ -36,25 +36,20 @@ vi.mock('@lobehub/ui', () => ({
}));
vi.mock('@/features/Conversation', () => ({
- ChatInput: () => <div data-testid="floating-chat-input">chat input</div>,
ChatList: () => <div data-testid="floating-chat-list">chat list</div>,
}));
describe('FloatingChatPanel ChatBody', () => {
- it('keeps the chat input after the list while leaving scroll ownership to the virtual list', () => {
+ it('renders only the ChatList — the input row is owned by InputRow now', () => {
render(<ChatBody />);
const body = screen.getByTestId('floating-chat-panel-body');
- const list = screen.getByTestId('floating-chat-panel-list');
- const input = screen.getByTestId('floating-chat-input');
+ const list = screen.getByTestId('floating-chat-list');
expect(body).toHaveAttribute('data-flex', '1');
expect(body).toHaveAttribute('data-height', '100%');
- expect(list).toHaveAttribute('data-flex', '1');
expect(body).toContainElement(list);
- expect(body).toContainElement(input);
expect(body).toHaveStyle({ overflow: 'hidden' });
- expect(list).toHaveStyle({ overflow: 'hidden' });
- expect(list.compareDocumentPosition(input)).toBe(Node.DOCUMENT_POSITION_FOLLOWING);
+ expect(screen.queryByTestId('floating-chat-input')).toBeNull();
});
});
diff --git a/src/features/FloatingChatPanel/ChatBody.tsx b/src/features/FloatingChatPanel/ChatBody.tsx
index 91904f6eabd..153bc1601fa 100644
--- a/src/features/FloatingChatPanel/ChatBody.tsx
+++ b/src/features/FloatingChatPanel/ChatBody.tsx
@@ -3,7 +3,7 @@
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
-import { ChatInput, ChatList } from '@/features/Conversation';
+import { ChatList } from '@/features/Conversation';
const ChatBody = memo(() => {
return (
@@ -11,22 +11,10 @@ const ChatBody = memo(() => {
data-testid="floating-chat-panel-body"
flex={1}
height={'100%'}
- style={{ minHeight: 0, overflow: 'hidden' }}
+ style={{ minHeight: 0, overflow: 'hidden', position: 'relative' }}
width={'100%'}
>
- <Flexbox
- data-testid="floating-chat-panel-list"
- flex={1}
- width={'100%'}
- style={{
- minHeight: 0,
- overflow: 'hidden',
- position: 'relative',
- }}
- >
- <ChatList />
- </Flexbox>
- <ChatInput leftActions={['typo']} rightActions={['contextWindow']} />
+ <ChatList />
</Flexbox>
);
});
diff --git a/src/features/FloatingChatPanel/HoverExpandBar.tsx b/src/features/FloatingChatPanel/HoverExpandBar.tsx
new file mode 100644
index 00000000000..d8cb8d5a373
--- /dev/null
+++ b/src/features/FloatingChatPanel/HoverExpandBar.tsx
@@ -0,0 +1,102 @@
+'use client';
+
+import { Icon } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { ChevronUp } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ bar: css`
+ pointer-events: auto;
+
+ position: absolute;
+ inset-block-end: 100%;
+ inset-inline: 0;
+ transform: translateY(4px);
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ height: 28px;
+ padding-block-end: 4px;
+
+ opacity: 0;
+ background: transparent;
+
+ transition:
+ opacity 160ms ease-out,
+ transform 160ms ease-out;
+ `,
+ visible: css`
+ transform: translateY(0);
+ opacity: 1;
+ `,
+ trigger: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ gap: 6px;
+ align-items: center;
+
+ height: 24px;
+ padding-inline: 10px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 12px;
+
+ font-size: 12px;
+ line-height: 1;
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorBgElevated};
+ box-shadow: ${cssVar.boxShadowTertiary};
+
+ transition:
+ color 160ms,
+ border-color 160ms,
+ background 160ms;
+
+ &:hover {
+ border-color: ${cssVar.colorBorder};
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorBgContainer};
+ }
+ `,
+ hidden: css`
+ pointer-events: none;
+ `,
+}));
+
+export interface HoverExpandBarProps {
+ onExpand: () => void;
+ visible: boolean;
+}
+
+const HoverExpandBar = memo<HoverExpandBarProps>(({ visible, onExpand }) => {
+ const { t } = useTranslation('chat');
+ const s = styles;
+
+ return (
+ <div
+ aria-hidden={!visible}
+ className={`${s.bar} ${visible ? s.visible : s.hidden}`}
+ data-testid="floating-chat-panel-hover-bar"
+ >
+ <button
+ className={s.trigger}
+ data-testid="floating-chat-panel-expand-button"
+ tabIndex={visible ? 0 : -1}
+ type="button"
+ onClick={onExpand}
+ >
+ <Icon icon={ChevronUp} size={12} />
+ {t('floatingChatPanel.expand', { defaultValue: 'Expand' })}
+ </button>
+ </div>
+ );
+});
+
+HoverExpandBar.displayName = 'FloatingChatPanelHoverExpandBar';
+
+export default HoverExpandBar;
diff --git a/src/features/FloatingChatPanel/InputRow.test.tsx b/src/features/FloatingChatPanel/InputRow.test.tsx
new file mode 100644
index 00000000000..d45bf8dc404
--- /dev/null
+++ b/src/features/FloatingChatPanel/InputRow.test.tsx
@@ -0,0 +1,151 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import InputRow from './InputRow';
+
+vi.mock('@/features/Conversation', () => ({
+ ChatInput: ({
+ compact,
+ leftActions,
+ rightActions,
+ showControlBar,
+ }: {
+ compact?: boolean;
+ leftActions?: string[];
+ rightActions?: string[];
+ showControlBar?: boolean;
+ }) => (
+ <div
+ data-compact={String(compact ?? false)}
+ data-left-actions={JSON.stringify(leftActions ?? [])}
+ data-right-actions={JSON.stringify(rightActions ?? [])}
+ data-show-control-bar={String(showControlBar ?? true)}
+ data-testid="chat-input"
+ />
+ ),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Icon: ({ icon }: { icon: () => void }) => <span data-testid="icon">{icon.name}</span>,
+}));
+
+describe('FloatingChatPanel InputRow', () => {
+ it('renders ChatInput in compact mode with empty actions and no control bar while collapsed', () => {
+ render(<InputRow isCollapsed onExpand={() => {}} />);
+ const input = screen.getByTestId('chat-input');
+ expect(input.dataset.compact).toBe('true');
+ expect(input.dataset.leftActions).toBe('[]');
+ expect(input.dataset.rightActions).toBe('[]');
+ expect(input.dataset.showControlBar).toBe('false');
+ });
+
+ it('renders ChatInput at full size with all actions while expanded', () => {
+ render(<InputRow isCollapsed={false} onExpand={() => {}} />);
+ const input = screen.getByTestId('chat-input');
+ expect(input.dataset.compact).toBe('false');
+ expect(input.dataset.leftActions).toBe(JSON.stringify(['typo']));
+ expect(input.dataset.rightActions).toBe(JSON.stringify(['contextWindow']));
+ expect(input.dataset.showControlBar).toBe('true');
+ });
+
+ it('keeps the expand bar hidden while collapsed and unfocused — hover alone never reveals it', () => {
+ render(<InputRow isCollapsed onExpand={() => {}} />);
+ const row = screen.getByTestId('floating-chat-panel-input-row');
+ const bar = screen.getByTestId('floating-chat-panel-hover-bar');
+
+ expect(bar.getAttribute('aria-hidden')).toBe('true');
+
+ fireEvent.mouseEnter(row);
+ expect(bar.getAttribute('aria-hidden')).toBe('true');
+ });
+
+ it('reveals the expand bar once the collapsed strip takes focus', () => {
+ render(
+ <div>
+ <InputRow isCollapsed onExpand={() => {}} />
+ <button data-testid="outside" type="button">
+ outside
+ </button>
+ </div>,
+ );
+ const row = screen.getByTestId('floating-chat-panel-input-row');
+ const bar = screen.getByTestId('floating-chat-panel-hover-bar');
+
+ fireEvent.focus(row);
+ expect(bar.getAttribute('aria-hidden')).toBe('false');
+
+ fireEvent.blur(row, { relatedTarget: screen.getByTestId('outside') });
+ expect(bar.getAttribute('aria-hidden')).toBe('true');
+ });
+
+ it('keeps the expand bar hidden while the panel is already expanded', () => {
+ render(<InputRow isCollapsed={false} onExpand={() => {}} />);
+ const row = screen.getByTestId('floating-chat-panel-input-row');
+ const bar = screen.getByTestId('floating-chat-panel-hover-bar');
+
+ fireEvent.focus(row);
+ expect(bar.getAttribute('aria-hidden')).toBe('true');
+ });
+
+ it('fires onExpand when the expand button is clicked', () => {
+ const onExpand = vi.fn();
+ render(<InputRow isCollapsed onExpand={onExpand} />);
+ const row = screen.getByTestId('floating-chat-panel-input-row');
+ fireEvent.focus(row);
+ fireEvent.click(screen.getByTestId('floating-chat-panel-expand-button'));
+ expect(onExpand).toHaveBeenCalledTimes(1);
+ });
+
+ it('releases compact rendering while the row holds focus inside the collapsed strip', () => {
+ render(
+ <div>
+ <InputRow isCollapsed onExpand={() => {}} />
+ <button data-testid="outside" type="button">
+ outside
+ </button>
+ </div>,
+ );
+ const input = screen.getByTestId('chat-input');
+ expect(input.dataset.compact).toBe('true');
+
+ fireEvent.focus(screen.getByTestId('floating-chat-panel-input-row'));
+ expect(input.dataset.compact).toBe('false');
+ expect(input.dataset.leftActions).toBe(JSON.stringify(['typo']));
+ expect(input.dataset.rightActions).toBe(JSON.stringify(['contextWindow']));
+ expect(input.dataset.showControlBar).toBe('true');
+ });
+
+ it('restores compact rendering once focus leaves the row entirely', () => {
+ render(
+ <div>
+ <InputRow isCollapsed onExpand={() => {}} />
+ <button data-testid="outside" type="button">
+ outside
+ </button>
+ </div>,
+ );
+ const row = screen.getByTestId('floating-chat-panel-input-row');
+ fireEvent.focus(row);
+ expect(screen.getByTestId('chat-input').dataset.compact).toBe('false');
+
+ fireEvent.blur(row, { relatedTarget: screen.getByTestId('outside') });
+ expect(screen.getByTestId('chat-input').dataset.compact).toBe('true');
+ });
+
+ it('keeps compact off when focus moves between elements inside the row', () => {
+ render(
+ <div>
+ <InputRow isCollapsed onExpand={() => {}} />
+ </div>,
+ );
+ const row = screen.getByTestId('floating-chat-panel-input-row');
+ fireEvent.focus(row);
+ expect(screen.getByTestId('chat-input').dataset.compact).toBe('false');
+
+ fireEvent.blur(row, { relatedTarget: screen.getByTestId('chat-input') });
+ expect(screen.getByTestId('chat-input').dataset.compact).toBe('false');
+ });
+});
diff --git a/src/features/FloatingChatPanel/InputRow.tsx b/src/features/FloatingChatPanel/InputRow.tsx
new file mode 100644
index 00000000000..3d8fcbaed88
--- /dev/null
+++ b/src/features/FloatingChatPanel/InputRow.tsx
@@ -0,0 +1,119 @@
+'use client';
+
+import { createGlobalStyle, createStaticStyles } from 'antd-style';
+import { type FocusEvent, memo, useCallback, useEffect, useRef, useState } from 'react';
+import { flushSync } from 'react-dom';
+
+import { ChatInput } from '@/features/Conversation';
+
+import HoverExpandBar from './HoverExpandBar';
+
+const styles = createStaticStyles(({ css }) => ({
+ row: css`
+ position: relative;
+ flex-shrink: 0;
+ `,
+ surface: css`
+ view-transition-name: floating-chat-panel-input;
+ `,
+}));
+
+const InputRowViewTransitionStyle = createGlobalStyle`
+ ::view-transition-old(floating-chat-panel-input),
+ ::view-transition-new(floating-chat-panel-input) {
+ animation-duration: 240ms;
+ animation-timing-function: cubic-bezier(0.32, 0.72, 0, 1);
+ }
+`;
+
+const supportsViewTransition =
+ typeof document !== 'undefined' &&
+ typeof (document as Document & { startViewTransition?: unknown }).startViewTransition ===
+ 'function';
+
+const startViewTransition = (callback: () => void) => {
+ (document as Document & { startViewTransition: (cb: () => void) => unknown }).startViewTransition(
+ callback,
+ );
+};
+
+// View Transition snapshots the DOM before and after this callback. The DOM mutation
+// must commit synchronously inside it, otherwise the "after" snapshot is identical
+// to the "before" one and nothing animates.
+const commitWithViewTransition = (commit: () => void) => {
+ if (!supportsViewTransition) {
+ commit();
+ return;
+ }
+ startViewTransition(() => {
+ // eslint-disable-next-line @eslint-react/dom/no-flush-sync
+ flushSync(commit);
+ });
+};
+
+const EMPTY_ACTIONS: never[] = [];
+const EXPANDED_LEFT_ACTIONS: 'typo'[] = ['typo'];
+const EXPANDED_RIGHT_ACTIONS: 'contextWindow'[] = ['contextWindow'];
+
+export interface InputRowProps {
+ isCollapsed: boolean;
+ onExpand: () => void;
+}
+
+const InputRow = memo<InputRowProps>(({ isCollapsed, onExpand }) => {
+ const s = styles;
+ const [renderedCollapsed, setRenderedCollapsed] = useState(isCollapsed);
+ const [focused, setFocused] = useState(false);
+ const focusedRef = useRef(false);
+
+ useEffect(() => {
+ if (renderedCollapsed === isCollapsed) return;
+ commitWithViewTransition(() => setRenderedCollapsed(isCollapsed));
+ }, [isCollapsed, renderedCollapsed]);
+
+ // Focus inside the collapsed strip releases the compact rendering so the action bar
+ // (Send + actions) shows while the panel itself stays collapsed. Blurring back outside
+ // the row returns to compact. View Transition makes the footer enter / leave smoothly.
+ const handleFocus = useCallback(() => {
+ if (focusedRef.current) return;
+ focusedRef.current = true;
+ commitWithViewTransition(() => setFocused(true));
+ }, []);
+
+ const handleBlur = useCallback((event: FocusEvent<HTMLDivElement>) => {
+ const next = event.relatedTarget as Node | null;
+ if (next && event.currentTarget.contains(next)) return;
+ if (!focusedRef.current) return;
+ focusedRef.current = false;
+ commitWithViewTransition(() => setFocused(false));
+ }, []);
+
+ const effectiveCompact = renderedCollapsed && !focused;
+
+ return (
+ <>
+ <InputRowViewTransitionStyle />
+ <div
+ className={s.row}
+ data-collapsed={isCollapsed}
+ data-testid="floating-chat-panel-input-row"
+ onBlur={handleBlur}
+ onFocus={handleFocus}
+ >
+ <HoverExpandBar visible={isCollapsed && focused} onExpand={onExpand} />
+ <div className={s.surface}>
+ <ChatInput
+ compact={effectiveCompact}
+ leftActions={effectiveCompact ? EMPTY_ACTIONS : EXPANDED_LEFT_ACTIONS}
+ rightActions={effectiveCompact ? EMPTY_ACTIONS : EXPANDED_RIGHT_ACTIONS}
+ showControlBar={!effectiveCompact}
+ />
+ </div>
+ </div>
+ </>
+ );
+});
+
+InputRow.displayName = 'FloatingChatPanelInputRow';
+
+export default InputRow;
diff --git a/src/features/FloatingChatPanel/index.test.tsx b/src/features/FloatingChatPanel/index.test.tsx
index 66cc8bea560..a9bf11106e6 100644
--- a/src/features/FloatingChatPanel/index.test.tsx
+++ b/src/features/FloatingChatPanel/index.test.tsx
@@ -1,4 +1,4 @@
-import { render } from '@testing-library/react';
+import { act, fireEvent, render } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -9,42 +9,124 @@ vi.mock('./ChatBody', () => ({
default: () => <div data-testid="chat-body">body</div>,
}));
+const sheetHandlers = vi.hoisted(() => ({
+ current: {
+ onOpenChange: undefined as ((open: boolean) => void) | undefined,
+ onSnapPointChange: undefined as ((point: number) => void) | undefined,
+ },
+}));
+
vi.mock('@lobehub/ui/base-ui', () => ({
FloatingSheet: ({
children,
dismissible,
headerActions,
+ open,
+ activeSnapPoint,
snapPoints,
title,
variant,
+ onOpenChange,
+ onSnapPointChange,
}: {
+ activeSnapPoint?: number;
children: ReactNode;
dismissible?: boolean;
headerActions?: ReactNode;
+ onOpenChange?: (open: boolean) => void;
+ onSnapPointChange?: (point: number) => void;
+ open?: boolean;
snapPoints?: number[];
title?: ReactNode;
variant?: string;
+ }) => {
+ sheetHandlers.current.onOpenChange = onOpenChange;
+ sheetHandlers.current.onSnapPointChange = onSnapPointChange;
+ return (
+ <div
+ data-active-snap={activeSnapPoint}
+ data-dismissible={String(dismissible)}
+ data-open={String(open)}
+ data-snap-points={JSON.stringify(snapPoints ?? [])}
+ data-testid="floating-panel-shell"
+ data-variant={variant ?? ''}
+ >
+ <div data-testid="sheet-title">{title}</div>
+ <div data-testid="sheet-actions">{headerActions}</div>
+ {children}
+ </div>
+ );
+ },
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: ({
+ onClick,
+ title,
+ ...rest
+ }: {
+ onClick?: () => void;
+ title?: string;
+ [key: string]: unknown;
}) => (
- <div
- data-dismissible={String(dismissible)}
- data-snap-points={JSON.stringify(snapPoints ?? [])}
- data-testid="floating-panel-shell"
- data-variant={variant ?? ''}
+ <button
+ data-testid={(rest as any)['data-testid']}
+ title={title}
+ type="button"
+ onClick={onClick}
>
- <div data-testid="sheet-title">{title}</div>
- <div data-testid="sheet-actions">{headerActions}</div>
- {children}
- </div>
+ {title}
+ </button>
),
+ Icon: ({ icon }: { icon: () => void }) => <span data-icon={icon.name} />,
+}));
+
+const mergedHooksCaptured = vi.hoisted(() => ({
+ current: undefined as undefined | { onBeforeSendMessage?: () => Promise<void> },
}));
vi.mock('@/features/Conversation', () => ({
- ChatList: () => null,
- ConversationProvider: ({ children, context }: any) => (
- <div data-context={JSON.stringify(context)} data-testid="provider">
- {children}
- </div>
+ ChatInput: ({
+ compact,
+ leftActions,
+ rightActions,
+ showControlBar,
+ }: {
+ compact?: boolean;
+ leftActions?: string[];
+ rightActions?: string[];
+ showControlBar?: boolean;
+ }) => (
+ <div
+ data-compact={String(compact ?? false)}
+ data-left-actions={JSON.stringify(leftActions ?? [])}
+ data-right-actions={JSON.stringify(rightActions ?? [])}
+ data-show-control-bar={String(showControlBar ?? true)}
+ data-testid="chat-input"
+ />
),
+ ChatList: () => null,
+ ConversationProvider: ({
+ children,
+ context,
+ hooks,
+ skipFetch,
+ hasInitMessages,
+ messages,
+ }: any) => {
+ mergedHooksCaptured.current = hooks;
+ return (
+ <div
+ data-context={JSON.stringify(context)}
+ data-has-init-messages={String(hasInitMessages ?? false)}
+ data-has-messages-prop={String(messages !== undefined)}
+ data-skip-fetch={String(skipFetch ?? false)}
+ data-testid="provider"
+ >
+ {children}
+ </div>
+ );
+ },
}));
vi.mock('@/routes/(main)/agent/features/Conversation/useActionsBarConfig', () => ({
@@ -55,125 +137,90 @@ vi.mock('@/hooks/useOperationState', () => ({
useOperationState: () => undefined,
}));
-const mockChatState = vi.hoisted(() => ({
- current: {
- dbMessagesMap: {} as Record<string, Array<{ id: string; threadId?: string | null }>>,
- portalThreadId: undefined as string | undefined,
- replaceMessages: vi.fn(),
- },
+vi.mock('@/features/Conversation/hooks/useChatFollowUp', () => ({
+ useChatFollowUp: () => ({}),
}));
-vi.mock('@/store/chat', () => {
- const useChatStore: any = (selector: any) => selector(mockChatState.current);
- useChatStore.getState = () => mockChatState.current;
- useChatStore.setState = (patch: any) => {
- Object.assign(
- mockChatState.current,
- typeof patch === 'function' ? patch(mockChatState.current) : patch,
- );
- };
- return { useChatStore };
-});
+vi.mock('@/store/agent', () => ({
+ useAgentStore: () => undefined,
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ chatConfigByIdSelectors: {
+ getChatConfigById: () => () => undefined,
+ },
+}));
vi.mock('@/store/chat/utils/messageMapKey', () => ({
messageMapKey: (ctx: any) => `${ctx.agentId}:${ctx.topicId}:${ctx.threadId}`,
}));
+const mockChatState = vi.hoisted(() => ({
+ current: {
+ dbMessagesMap: {} as Record<string, Array<{ id: string }>>,
+ replaceMessages: vi.fn(),
+ },
+}));
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: any) => selector(mockChatState.current),
+}));
+
describe('FloatingChatPanel', () => {
beforeEach(() => {
__resetFloatingChatPanelRegistry();
+ sheetHandlers.current.onOpenChange = undefined;
+ sheetHandlers.current.onSnapPointChange = undefined;
+ mergedHooksCaptured.current = undefined;
mockChatState.current.dbMessagesMap = {};
- mockChatState.current.portalThreadId = undefined;
+ mockChatState.current.replaceMessages = vi.fn();
});
- it('builds an ephemeral thread context by default from agentId + topicId', () => {
+ it('builds a main-scope context anchored on the supplied topicId', () => {
const { getByTestId } = render(<FloatingChatPanel agentId="agent-1" topicId="topic-1" />);
const ctx = JSON.parse(getByTestId('provider').dataset.context!);
expect(ctx).toEqual({
agentId: 'agent-1',
- isNew: true,
- scope: 'thread',
+ scope: 'main',
threadId: null,
topicId: 'topic-1',
});
});
- it('drops isNew when an existing threadId is supplied', () => {
+ it('forwards documentId / agentDocumentId into the context for document-aware injection', () => {
const { getByTestId } = render(
- <FloatingChatPanel agentId="agent-1" threadId="thread-1" topicId="topic-1" />,
- );
- const ctx = JSON.parse(getByTestId('provider').dataset.context!);
- expect(ctx).toEqual({
- agentId: 'agent-1',
- scope: 'thread',
- threadId: 'thread-1',
- topicId: 'topic-1',
- });
- });
-
- it('builds a main-scope context when scope is forced to main', () => {
- const { getByTestId } = render(
- <FloatingChatPanel agentId="agent-1" scope="main" topicId="topic-1" />,
+ <FloatingChatPanel
+ agentDocumentId="agent-doc-1"
+ agentId="agent-1"
+ documentId="doc-1"
+ topicId="topic-1"
+ />,
);
const ctx = JSON.parse(getByTestId('provider').dataset.context!);
expect(ctx).toEqual({
+ agentDocumentId: 'agent-doc-1',
agentId: 'agent-1',
+ documentId: 'doc-1',
scope: 'main',
threadId: null,
topicId: 'topic-1',
});
});
- it('anchors a new thread on the topic last main message when one is present', () => {
- mockChatState.current.dbMessagesMap = {
- // mocked messageMapKey: `${agentId}:${topicId}:${threadId}`; main scope
- // omits threadId so it serializes as "agent-1:topic-1:undefined".
- 'agent-1:topic-1:undefined': [
- { id: 'msg-1', threadId: null },
- { id: 'msg-2', threadId: null },
- ],
- };
-
+ it('lets ConversationProvider drive the fetch when the chat store has no slice yet', () => {
const { getByTestId } = render(<FloatingChatPanel agentId="agent-1" topicId="topic-1" />);
- const ctx = JSON.parse(getByTestId('provider').dataset.context!);
- expect(ctx).toEqual({
- agentId: 'agent-1',
- isNew: true,
- scope: 'thread',
- sourceMessageId: 'msg-2',
- threadId: null,
- threadType: 'standalone',
- topicId: 'topic-1',
- });
+ const provider = getByTestId('provider');
+ expect(provider.dataset.skipFetch).toBe('false');
+ expect(provider.dataset.hasInitMessages).toBe('false');
});
- it('skips thread-scoped rows when picking the source message anchor', () => {
+ it('syncs the chat store slice into ConversationProvider when the topic already has messages', () => {
mockChatState.current.dbMessagesMap = {
- 'agent-1:topic-1:undefined': [
- { id: 'msg-1', threadId: null },
- { id: 'msg-2', threadId: null },
- { id: 'msg-3', threadId: 'thread-x' },
- ],
+ 'agent-1:topic-1:null': [{ id: 'msg-1' }],
};
-
const { getByTestId } = render(<FloatingChatPanel agentId="agent-1" topicId="topic-1" />);
- const ctx = JSON.parse(getByTestId('provider').dataset.context!);
- expect(ctx.sourceMessageId).toBe('msg-2');
- });
-
- it('forwards documentId into the conversation context for document-aware injection', () => {
- const { getByTestId } = render(
- <FloatingChatPanel agentId="agent-1" documentId="doc-1" topicId="topic-1" />,
- );
- const ctx = JSON.parse(getByTestId('provider').dataset.context!);
- expect(ctx).toEqual({
- agentId: 'agent-1',
- documentId: 'doc-1',
- isNew: true,
- scope: 'thread',
- threadId: null,
- topicId: 'topic-1',
- });
+ const provider = getByTestId('provider');
+ expect(provider.dataset.hasInitMessages).toBe('true');
+ expect(provider.dataset.hasMessagesProp).toBe('true');
});
it('forwards title and headerActions to floating panel header', () => {
@@ -186,14 +233,110 @@ describe('FloatingChatPanel', () => {
/>,
);
expect(getByTestId('sheet-title').textContent).toBe('My Title');
- expect(getByTestId('sheet-actions').textContent).toBe('Action');
+ expect(getByTestId('sheet-actions').textContent).toContain('Action');
});
- it('applies default shell props', () => {
+ it('starts collapsed and ships a seamless dismissible sheet with two snap points', () => {
const { getByTestId } = render(<FloatingChatPanel agentId="a" topicId="t" />);
const sheet = getByTestId('floating-panel-shell');
- expect(sheet.dataset.snapPoints).toBe(JSON.stringify([180, 320, 520, 800]));
- expect(sheet.dataset.variant).toBe('embedded');
- expect(sheet.dataset.dismissible).toBe('false');
+ expect(sheet.dataset.snapPoints).toBe(JSON.stringify([420, 800]));
+ expect(sheet.dataset.variant).toBe('elevated');
+ expect(sheet.dataset.dismissible).toBe('true');
+ expect(sheet.dataset.open).toBe('false');
+ expect(sheet.dataset.activeSnap).toBe('420');
+ expect(getByTestId('floating-chat-panel').dataset.collapsed).toBe('true');
+ });
+
+ it('renders a minimal ChatInput while collapsed (no left/right actions)', () => {
+ const { getByTestId } = render(<FloatingChatPanel agentId="a" topicId="t" />);
+ const input = getByTestId('chat-input');
+ expect(input.dataset.leftActions).toBe('[]');
+ expect(input.dataset.rightActions).toBe('[]');
+ });
+
+ it('expands to the mid snap when the Send hook fires', async () => {
+ const { getByTestId } = render(<FloatingChatPanel agentId="a" topicId="t" />);
+ expect(getByTestId('floating-panel-shell').dataset.open).toBe('false');
+
+ await act(async () => {
+ await mergedHooksCaptured.current?.onBeforeSendMessage?.();
+ });
+
+ const sheet = getByTestId('floating-panel-shell');
+ expect(sheet.dataset.open).toBe('true');
+ expect(sheet.dataset.activeSnap).toBe('420');
+ expect(getByTestId('floating-chat-panel').dataset.collapsed).toBe('false');
+ const input = getByTestId('chat-input');
+ expect(input.dataset.leftActions).toBe(JSON.stringify(['typo']));
+ expect(input.dataset.rightActions).toBe(JSON.stringify(['contextWindow']));
+ });
+
+ it('collapses back when the sheet reports onOpenChange(false)', async () => {
+ const { getByTestId } = render(<FloatingChatPanel agentId="a" topicId="t" />);
+
+ await act(async () => {
+ await mergedHooksCaptured.current?.onBeforeSendMessage?.();
+ });
+ expect(getByTestId('floating-panel-shell').dataset.open).toBe('true');
+
+ act(() => {
+ sheetHandlers.current.onOpenChange?.(false);
+ });
+
+ expect(getByTestId('floating-panel-shell').dataset.open).toBe('false');
+ expect(getByTestId('floating-chat-panel').dataset.collapsed).toBe('true');
+ expect(getByTestId('floating-panel-shell').dataset.activeSnap).toBe('420');
+ });
+
+ it('expands when the header collapse button is clicked from expanded state', async () => {
+ const { getByTestId } = render(<FloatingChatPanel agentId="a" topicId="t" />);
+
+ await act(async () => {
+ await mergedHooksCaptured.current?.onBeforeSendMessage?.();
+ });
+ expect(getByTestId('floating-chat-panel').dataset.collapsed).toBe('false');
+
+ fireEvent.click(getByTestId('floating-chat-panel-collapse-button'));
+ expect(getByTestId('floating-chat-panel').dataset.collapsed).toBe('true');
+ });
+
+ it('expands via the hover bar expand button', () => {
+ const { getByTestId } = render(<FloatingChatPanel agentId="a" topicId="t" />);
+ expect(getByTestId('floating-chat-panel').dataset.collapsed).toBe('true');
+
+ fireEvent.click(getByTestId('floating-chat-panel-expand-button'));
+ expect(getByTestId('floating-chat-panel').dataset.collapsed).toBe('false');
+ expect(getByTestId('floating-panel-shell').dataset.activeSnap).toBe('420');
+ });
+
+ it('reflects user-driven snap changes through onSnapPointChange', async () => {
+ const { getByTestId } = render(<FloatingChatPanel agentId="a" topicId="t" />);
+
+ await act(async () => {
+ await mergedHooksCaptured.current?.onBeforeSendMessage?.();
+ });
+ expect(getByTestId('floating-panel-shell').dataset.activeSnap).toBe('420');
+
+ act(() => {
+ sheetHandlers.current.onSnapPointChange?.(800);
+ });
+ expect(getByTestId('floating-panel-shell').dataset.activeSnap).toBe('800');
+ });
+
+ it('keeps the ChatInput element identity stable across state changes', async () => {
+ const { getByTestId } = render(<FloatingChatPanel agentId="a" topicId="t" />);
+ const beforeNode = getByTestId('chat-input');
+
+ await act(async () => {
+ await mergedHooksCaptured.current?.onBeforeSendMessage?.();
+ });
+ const afterExpand = getByTestId('chat-input');
+ expect(afterExpand).toBe(beforeNode);
+
+ act(() => {
+ sheetHandlers.current.onOpenChange?.(false);
+ });
+ const afterCollapse = getByTestId('chat-input');
+ expect(afterCollapse).toBe(beforeNode);
});
});
diff --git a/src/features/FloatingChatPanel/index.tsx b/src/features/FloatingChatPanel/index.tsx
index d4aeb959b0f..48d8c486600 100644
--- a/src/features/FloatingChatPanel/index.tsx
+++ b/src/features/FloatingChatPanel/index.tsx
@@ -1,10 +1,13 @@
'use client';
-import { ThreadType, type UIChatMessage } from '@lobechat/types';
+import { type UIChatMessage } from '@lobechat/types';
+import { ActionIcon } from '@lobehub/ui';
import { FloatingSheet, type FloatingSheetProps } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
+import { ChevronDown } from 'lucide-react';
import type { ReactNode } from 'react';
-import { memo, useEffect, useMemo, useState } from 'react';
+import { memo, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
import {
type ActionsBarConfig,
@@ -23,40 +26,41 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import ChatBody from './ChatBody';
import { useSingleInstanceGuard } from './guard';
+import InputRow from './InputRow';
-const SNAP_POINTS = [180, 320, 520, 800] as const;
+const SNAP_POINTS = [420, 800] as const;
+const MID_SNAP_POINT = SNAP_POINTS[0];
const MAX_SNAP_POINT = SNAP_POINTS.at(-1)!;
-const REST_SNAP_POINT = SNAP_POINTS[0];
-const styles = createStaticStyles(({ css }) => ({
- sheet: css`
- overflow: hidden;
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ panel: css`
display: flex;
- flex: 1;
flex-direction: column;
-
- min-height: 0;
- `,
- header: css`
- display: flex;
flex-shrink: 0;
- gap: 8px;
- align-items: center;
- justify-content: space-between;
- `,
- title: css`
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- `,
- body: css`
- overflow: hidden;
- display: flex;
- flex-direction: column;
+ align-self: stretch;
width: 100%;
- height: 100%;
- min-height: 0;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+
+ background: ${cssVar.colorBgContainer};
+
+ transition:
+ border-block-start-color 240ms cubic-bezier(0.32, 0.72, 0, 1),
+ background 240ms cubic-bezier(0.32, 0.72, 0, 1);
+
+ &[data-collapsed='true'] {
+ border-block-start-color: transparent;
+ background: transparent;
+ }
+ `,
+ sheetSeamless: css`
+ border: none;
+ border-radius: 0;
+ background: transparent;
+ box-shadow: none;
+ `,
+ titleSpacer: css`
+ flex: 1;
`,
}));
@@ -97,20 +101,15 @@ export interface FloatingChatPanelProps {
onOpenChange?: (open: boolean) => void;
onSnapPointChange?: (point: number) => void;
open?: boolean;
- /**
- * Conversation scope. Defaults to `'thread'` for ephemeral side-chat usage.
- * When `'thread'` and `threadId` is absent, the context is marked `isNew`
- * so a fresh thread can be created on first send (caller must supply
- * `sourceMessageId` + `threadType` via `hooks` / context override if real
- * thread persistence is required).
- */
- scope?: 'main' | 'thread';
snapPoints?: number[];
- /** Opens an existing thread when set; otherwise the panel starts ephemeral. */
- threadId?: string | null;
title?: ReactNode;
- /** Topic identifier. `null` means a new / unpersisted conversation. */
- topicId: string | null;
+ /**
+ * Topic identifier. Must be the doc-anchored topic resolved through
+ * `useDocumentChatTopic` so the panel renders the conversation tied to the
+ * `(documentId, agentId)` pair instead of whatever topic happens to be
+ * active. Callers should gate on a non-null value before rendering.
+ */
+ topicId: string;
variant?: 'elevated' | 'embedded';
width?: number | string;
}
@@ -119,9 +118,8 @@ export interface FloatingChatPanelProps {
* FloatingChatPanel
*
* Reusable floating conversation panel — composes `ChatList` + `ChatInput`
- * inside a `FloatingSheet`. Consumers provide conversation coordinates via
- * flat `agentId` / `topicId` / `threadId` props; the panel builds its own
- * `ConversationContext` internally.
+ * inside a `FloatingSheet`. The conversation is always main-scope on the
+ * supplied `topicId`; `ConversationProvider` owns message loading.
*
* Single instance per page (see `./guard.ts`).
*/
@@ -129,125 +127,77 @@ const FloatingChatPanel = memo<FloatingChatPanelProps>(
({
agentId,
topicId,
- threadId = null,
documentId,
agentDocumentId,
- scope = 'thread',
actionsBar,
hooks,
- minHeight: _minHeight = 240,
- maxHeight: _maxHeight = 0.9,
-
width = '100%',
title,
headerActions,
}) => {
useSingleInstanceGuard();
-
- // Adopt the global portal-thread state so streaming AI chunks (which the
- // lifecycle writes under the persisted `_<threadId>` key the moment the
- // server returns `createdThreadId`) become visible in this panel without
- // waiting for the post-stream `onAfterMessageCreate` hook. `lifecycle.ts`
- // calls `syncThreadInPortal` *before* stream chunks start arriving, so
- // subscribing here flips this panel's chatKey from `_new` to the persisted
- // thread in time to render the stream.
- const storePortalThreadId = useChatStore((s) => s.portalThreadId);
- const effectiveThreadId = threadId ?? storePortalThreadId ?? null;
-
- // Clear any stale `portalThreadId` left by a sibling portal session so a
- // fresh mount starts in `isNew` state. Body's `key` already remounts the
- // panel when `(agentId, topicId, documentId)` changes; this guards the
- // first paint of that fresh mount against a leftover thread id.
- useEffect(() => {
- if (threadId) return;
- if (useChatStore.getState().portalThreadId) {
- useChatStore.setState({ portalThreadId: undefined });
- }
- }, [threadId]);
-
- // Source message for `newThread`: the latest message of the topic's main
- // scope. Without this, `conversationLifecycle.ts:215` treats the send as a
- // plain topic message and never creates a thread row. Falls back to
- // ephemeral (no source) when the topic has no messages yet.
- const isCreatingNewThread = scope === 'thread' && !effectiveThreadId;
- const sourceMessageId = useChatStore((s) => {
- if (!isCreatingNewThread || !topicId) return undefined;
- const mainKey = messageMapKey({ agentId, topicId });
- const mainMessages = s.dbMessagesMap[mainKey];
- if (!mainMessages?.length) return undefined;
- // Anchor on the latest main-scope message (ignore thread-scoped rows).
- for (let i = mainMessages.length - 1; i >= 0; i -= 1) {
- const msg = mainMessages[i]!;
- if (!msg.threadId) return msg.id;
- }
- return undefined;
- });
+ const { t } = useTranslation('chat');
const context = useMemo<ConversationContext>(
() => ({
agentId,
...(agentDocumentId ? { agentDocumentId } : {}),
...(documentId ? { documentId } : {}),
- ...(isCreatingNewThread && sourceMessageId
- ? { isNew: true, sourceMessageId, threadType: ThreadType.Standalone }
- : isCreatingNewThread
- ? { isNew: true }
- : {}),
- scope,
- threadId: effectiveThreadId,
+ scope: 'main',
+ threadId: null,
topicId,
}),
- [
- agentId,
- agentDocumentId,
- documentId,
- effectiveThreadId,
- isCreatingNewThread,
- scope,
- sourceMessageId,
- topicId,
- ],
+ [agentId, agentDocumentId, documentId, topicId],
);
const chatKey = useMemo(() => messageMapKey(context), [context]);
- const rawMessages = useChatStore((s) => s.dbMessagesMap[chatKey]);
- const replaceMessages = useChatStore((s) => s.replaceMessages);
- // Document portal chat is an isolated doc-anchored side conversation —
- // never the continuation of the main topic. Pre-send (no thread yet) we
- // render empty regardless of whatever the `_new` thread key may hold from
- // a sibling flow; post-send we keep only the thread's own rows, since
- // `lifecycle.ts:replaceMessages(data.messages, { context: { threadId } })`
- // also dumps every main-topic parent message into the thread key for the
- // Portal/Thread parent → divider → thread layout we don't want here.
- const messages = useMemo(() => {
- if (!effectiveThreadId) return [];
- if (!rawMessages) return rawMessages;
- return rawMessages.filter((m) => m.threadId === effectiveThreadId);
- }, [rawMessages, effectiveThreadId]);
+ // ConversationProvider runs an isolated message store per panel — read the
+ // shared chat store's `dbMessagesMap` for this key and wire the standard
+ // `messages` / `onMessagesChange` sync pattern (mirrors `ConversationArea`
+ // in the main agent route). Without this loop the lifecycle's
+ // `chatStore.replaceMessages` after a send wouldn't propagate back into
+ // the panel's local message slice and the UI would stay empty.
+ const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);
+ const replaceMessages = useChatStore((s) => s.replaceMessages);
+ const handleMessagesChange = useCallback(
+ (next: UIChatMessage[], ctx: ConversationContext) => {
+ replaceMessages(next, { context: ctx });
+ },
+ [replaceMessages],
+ );
const operationState = useOperationState(context);
const defaultActionsBar = useActionsBarConfig();
const resolvedActionsBar = actionsBar ?? defaultActionsBar;
- const handleMessagesChange = useMemo(
- () => (next: UIChatMessage[], ctx: ConversationContext) => {
- replaceMessages(next, { context: ctx });
+ const [isCollapsed, setIsCollapsed] = useState(true);
+ const [activeSnapPoint, setActiveSnapPoint] = useState<number>(MID_SNAP_POINT);
+
+ const expand = useCallback(() => {
+ setActiveSnapPoint(MID_SNAP_POINT);
+ setIsCollapsed(false);
+ }, []);
+
+ const collapse = useCallback(() => {
+ setIsCollapsed(true);
+ setActiveSnapPoint(MID_SNAP_POINT);
+ }, []);
+
+ const handleOpenChange = useCallback(
+ (open: boolean) => {
+ if (!open) collapse();
},
- [replaceMessages],
+ [collapse],
);
- const [open, setOpen] = useState(true);
- const [activeSnapPoint, setActiveSnapPoint] = useState<number>(REST_SNAP_POINT);
-
const agentChatConfig = useAgentStore(chatConfigByIdSelectors.getChatConfigById(agentId));
const chatFollowUpHooks = useChatFollowUp({
agentChatConfig,
conversationKey: chatKey,
- threadId: effectiveThreadId ?? undefined,
- topicId: topicId ?? undefined,
+ topicId,
});
const mergedHooks = useMemo<ConversationHooks>(
@@ -255,61 +205,74 @@ const FloatingChatPanel = memo<FloatingChatPanelProps>(
mergeConversationHooks(
hooks,
{
- // Expand the sheet the moment the user presses Send, so the chat grows
- // into view before the AI response streams in — not after it finishes.
onBeforeSendMessage: async () => {
- setActiveSnapPoint(MAX_SNAP_POINT);
+ expand();
},
},
chatFollowUpHooks,
),
- [hooks, chatFollowUpHooks],
+ [hooks, chatFollowUpHooks, expand],
+ );
+
+ const collapseAction = (
+ <ActionIcon
+ data-testid="floating-chat-panel-collapse-button"
+ icon={ChevronDown}
+ size="small"
+ title={t('floatingChatPanel.collapse', { defaultValue: 'Collapse' })}
+ onClick={collapse}
+ />
);
const sheetProps: FloatingSheetProps = {
activeSnapPoint,
- className: 'floating-sheet-demo-inline',
- closeThreshold: 0.3,
- defaultOpen: true,
- dismissible: false,
- headerActions,
-
+ className: styles.sheetSeamless,
+ closeThreshold: 0.5,
+ defaultOpen: false,
+ dismissible: true,
+ headerActions: (
+ <>
+ {headerActions}
+ {collapseAction}
+ </>
+ ),
maxHeight: MAX_SNAP_POINT,
- minHeight: SNAP_POINTS[1],
+ minHeight: MID_SNAP_POINT,
mode: 'inline',
- onOpenChange: setOpen,
+ onOpenChange: handleOpenChange,
onSnapPointChange: setActiveSnapPoint,
- open,
- restingHeight: REST_SNAP_POINT,
+ open: !isCollapsed,
+ restingHeight: MID_SNAP_POINT,
snapPoints: [...SNAP_POINTS],
- title,
-
- variant: 'embedded',
+ // Always render a title slot — `space-between` on the header pulls the
+ // single child (headerActions) to the start otherwise, putting the
+ // collapse button on the left.
+ title: title ?? <span className={styles.titleSpacer} />,
+ variant: 'elevated',
width,
};
return (
- <FloatingSheet {...sheetProps}>
- <div className={styles.body}>
- <ConversationProvider
- // Doc-anchored side chat owns its messages via the external
- // `messages` prop (filtered from `dbMessagesMap` above). Letting
- // ConversationProvider fire its own `useFetchMessages` here would
- // pull the main-topic history from the server and drop it into
- // this panel — exactly the parent dump A-mode is meant to avoid.
- hasInitMessages
- skipFetch
- actionsBar={resolvedActionsBar}
- context={context}
- hooks={mergedHooks}
- messages={messages ?? []}
- operationState={operationState}
- onMessagesChange={handleMessagesChange}
- >
+ <ConversationProvider
+ actionsBar={resolvedActionsBar}
+ context={context}
+ hasInitMessages={!!messages}
+ hooks={mergedHooks}
+ messages={messages}
+ operationState={operationState}
+ onMessagesChange={handleMessagesChange}
+ >
+ <div
+ className={styles.panel}
+ data-collapsed={isCollapsed}
+ data-testid="floating-chat-panel"
+ >
+ <FloatingSheet {...sheetProps}>
<ChatBody />
- </ConversationProvider>
+ </FloatingSheet>
+ <InputRow isCollapsed={isCollapsed} onExpand={expand} />
</div>
- </FloatingSheet>
+ </ConversationProvider>
);
},
);
diff --git a/src/features/FloatingChatPanel/useDocumentChatTopic.ts b/src/features/FloatingChatPanel/useDocumentChatTopic.ts
new file mode 100644
index 00000000000..725acbbcdd5
--- /dev/null
+++ b/src/features/FloatingChatPanel/useDocumentChatTopic.ts
@@ -0,0 +1,56 @@
+import debug from 'debug';
+import { useEffect } from 'react';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { agentDocumentService, agentDocumentSWRKeys } from '@/services/agentDocument';
+
+const log = debug('lobe-chat:useDocumentChatTopic');
+
+/**
+ * Resolve the doc-anchored chat topic for an `(agentId, documentId)` pair.
+ *
+ * Backed by `agentDocument.getOrCreateChatTopic`, which is idempotent and
+ * marks the topic with `trigger='document'` so it is filtered out of the
+ * regular chat sidebar. The first call provisions the topic + the
+ * `topic_documents` association; subsequent calls return the same topic id.
+ *
+ * Returns `topicId: undefined` until the request resolves; callers should gate
+ * rendering on a non-undefined value to avoid mounting a chat panel without a
+ * topic anchor.
+ */
+export const useDocumentChatTopic = (params: {
+ agentId: string | undefined;
+ documentId: string | undefined;
+}) => {
+ const { agentId, documentId } = params;
+ const enabled = !!agentId && !!documentId;
+ const { data, error, isLoading } = useClientDataSWR(
+ enabled ? agentDocumentSWRKeys.documentChatTopic(agentId, documentId) : null,
+ () =>
+ agentDocumentService.getOrCreateChatTopic({
+ agentId: agentId!,
+ documentId: documentId!,
+ }),
+ );
+
+ useEffect(() => {
+ if (!enabled) {
+ log('skipped — agentId=%o documentId=%o', agentId, documentId);
+ return;
+ }
+ if (error) {
+ // Surface to the regular console as well so the panel's silent gating
+ // doesn't hide a real procedure failure (e.g. NOT_FOUND when the agent
+ // doesn't own the document).
+ console.error('[useDocumentChatTopic] getOrCreateChatTopic failed', {
+ agentId,
+ documentId,
+ error,
+ });
+ return;
+ }
+ if (data?.topicId) log('resolved topicId=%s for (%s, %s)', data.topicId, agentId, documentId);
+ }, [enabled, agentId, documentId, data?.topicId, error]);
+
+ return { error, isLoading, topicId: data?.topicId };
+};
diff --git a/src/features/Portal/Document/Body.test.tsx b/src/features/Portal/Document/Body.test.tsx
index 4fb2bdc9f30..ae3cf7273bb 100644
--- a/src/features/Portal/Document/Body.test.tsx
+++ b/src/features/Portal/Document/Body.test.tsx
@@ -88,6 +88,17 @@ vi.mock('@/features/FloatingChatPanel', () => ({
default: () => <div data-testid="floating-chat-panel" />,
}));
+const docChatTopicState = vi.hoisted(() => ({
+ current: {
+ error: undefined as Error | undefined,
+ isLoading: false,
+ topicId: 'doc-topic-1' as string | undefined,
+ },
+}));
+vi.mock('@/features/FloatingChatPanel/useDocumentChatTopic', () => ({
+ useDocumentChatTopic: () => docChatTopicState.current,
+}));
+
const mockChatState = vi.hoisted(() => ({
current: {
activeTopicId: 'topic-1',
@@ -149,6 +160,11 @@ describe('DocumentBody', () => {
mockUserState.current.preference.lab.enableAgentDocumentFloatingChatPanel = false;
mockDocumentMeta.current = { content: '', filename: 'doc.md' };
mockUpdateDocument.mockClear();
+ docChatTopicState.current = {
+ error: undefined,
+ isLoading: false,
+ topicId: 'doc-topic-1',
+ };
vi.useFakeTimers();
});
@@ -162,7 +178,7 @@ describe('DocumentBody', () => {
expect(screen.queryByTestId('floating-chat-panel')).toBeNull();
});
- it('renders FloatingChatPanel when the lab feature is enabled', () => {
+ it('renders FloatingChatPanel when the lab feature is enabled and the doc topic resolves', () => {
mockUserState.current.preference.lab.enableAgentDocumentFloatingChatPanel = true;
render(<DocumentBody />);
@@ -170,6 +186,15 @@ describe('DocumentBody', () => {
expect(screen.getByTestId('floating-chat-panel')).toBeDefined();
});
+ it('holds the panel until the doc-anchored topic id resolves', () => {
+ mockUserState.current.preference.lab.enableAgentDocumentFloatingChatPanel = true;
+ docChatTopicState.current = { error: undefined, isLoading: true, topicId: undefined };
+
+ render(<DocumentBody />);
+
+ expect(screen.queryByTestId('floating-chat-panel')).toBeNull();
+ });
+
it('renders highlight editor for non-markdown files', () => {
mockDocumentMeta.current = { content: 'raw log content', filename: 'topic_call.txt' };
diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsx
index e9add3a2b58..6d0b316db95 100644
--- a/src/features/Portal/Document/Body.tsx
+++ b/src/features/Portal/Document/Body.tsx
@@ -11,12 +11,12 @@ import { useTranslation } from 'react-i18next';
import CodeEditorPane from '@/components/CodeEditorPane';
import FloatingChatPanel from '@/features/FloatingChatPanel';
+import { useDocumentChatTopic } from '@/features/FloatingChatPanel/useDocumentChatTopic';
import WideScreenContainer from '@/features/WideScreenContainer';
import { useClientDataSWR } from '@/libs/swr';
import { portalKeys } from '@/libs/swr/keys';
import { documentService } from '@/services/document';
import { useAgentStore } from '@/store/agent';
-import { useChatStore } from '@/store/chat';
import { useDocumentStore } from '@/store/document';
import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
@@ -324,10 +324,14 @@ const DocumentBody = memo(() => {
const agentDocumentId = useResolvedAgentDocumentId();
const fullPage = useDocumentViewFullPage();
const activeAgentId = useAgentStore((s) => s.activeAgentId);
- const activeTopicId = useChatStore((s) => s.activeTopicId);
const enableFloatingChatPanel = useUserStore(
labPreferSelectors.enableAgentDocumentFloatingChatPanel,
);
+ const panelEligible = !fullPage && enableFloatingChatPanel && !!activeAgentId && !!documentId;
+ const { topicId: docChatTopicId } = useDocumentChatTopic({
+ agentId: panelEligible ? activeAgentId : undefined,
+ documentId: panelEligible ? documentId : undefined,
+ });
const [skillFrontmatter, contentFormat] = useDocumentStore((s) =>
documentId
? [s.documents[documentId]?.skillFrontmatter ?? '', s.documents[documentId]?.contentFormat]
@@ -377,15 +381,17 @@ const DocumentBody = memo(() => {
{fullPage ? <WideScreenContainer>{editorContent}</WideScreenContainer> : editorContent}
</div>
<TodoList />
- {/* The full-page route surfaces chat through the working sidebar, so the
- floating panel only belongs to the compact in-chat portal. */}
- {!fullPage && enableFloatingChatPanel && activeAgentId && (
+ {/* The full-page route hosts its own panel through `AgentDocumentPage`, so
+ the in-portal panel only renders for the compact view. Both call sites
+ drive a doc-anchored chat topic via `useDocumentChatTopic`, so the panel
+ renders once that topic id resolves. */}
+ {panelEligible && docChatTopicId && (
<FloatingChatPanel
agentDocumentId={agentDocumentId}
agentId={activeAgentId}
documentId={documentId ?? undefined}
- key={`${activeAgentId}:${activeTopicId ?? 'none'}:${documentId ?? 'none'}`}
- topicId={activeTopicId ?? null}
+ key={`${activeAgentId}:${docChatTopicId}:${documentId ?? 'none'}`}
+ topicId={docChatTopicId}
/>
)}
</Flexbox>
diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.ts
index f1610442b94..579d0d2e7a1 100644
--- a/src/services/agentDocument.ts
+++ b/src/services/agentDocument.ts
@@ -66,6 +66,10 @@ class AgentDocumentService {
return lambdaClient.agentDocument.listDocuments.query(params);
};
+ getOrCreateChatTopic = async (params: { agentId: string; documentId: string }) => {
+ return lambdaClient.agentDocument.getOrCreateChatTopic.mutate(params);
+ };
+
associateDocument = async (params: { agentId: string; documentId: string }) => {
const result = await lambdaClient.agentDocument.associateDocument.mutate(params);
await invalidateDocumentMutation({
diff --git a/src/services/document/swrKeys.ts b/src/services/document/swrKeys.ts
index 99f32121a33..e9331f76a26 100644
--- a/src/services/document/swrKeys.ts
+++ b/src/services/document/swrKeys.ts
@@ -9,6 +9,8 @@ export const agentDocumentSWRKeys = {
* under that key, which drops those fields.
*/
documentsList: (agentId: string) => ['agent:documentsList', agentId] as const,
+ documentChatTopic: (agentId: string, documentId: string) =>
+ ['agent:documentChatTopic', agentId, documentId] as const,
readDocument: (agentId: string, id: string) => ['agent:documentEditor', agentId, id] as const,
};