Skip to content

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

🐛 fix(project): chat input and agent picker on the project home, and ?message= links that send into the right topic (#21518)

LiJian9872c1703c89
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index 21bb39908e7..66093ad5630 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -156,6 +156,7 @@
"members.rolePlaceholder": "e.g. Researcher, Reviewer",
"members.updateFailed": "Could not update the agent",
"overview.activeTasks": "In progress",
+ "overview.agentSelect": "Choose an agent",
"overview.composerPlaceholder": "Tell the project what to move forward next…",
"overview.contextTitle": "Project context",
"overview.createTask": "Create task",
@@ -166,6 +167,7 @@
"overview.goalSummary": "Project goals",
"overview.goalsEmpty": "Add a goal to make project progress visible here.",
"overview.latestWorks": "Latest outputs",
+ "overview.messageNotSent": "The message was not sent. Your draft has been kept.",
"overview.mode.chat": "Chat",
"overview.mode.task": "Task",
"overview.needsAttention": "Needs your attention",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index ea60c8f36b3..7740223a24f 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -156,6 +156,7 @@
"members.rolePlaceholder": "例如:研究员、审核者",
"members.updateFailed": "更新 Agent 失败",
"overview.activeTasks": "正在推进",
+ "overview.agentSelect": "选择 Agent",
"overview.composerPlaceholder": "告诉项目接下来要推进什么…",
"overview.contextTitle": "项目上下文",
"overview.createTask": "创建任务",
@@ -166,6 +167,7 @@
"overview.goalSummary": "项目目标",
"overview.goalsEmpty": "添加目标后,可以在这里持续查看项目进度。",
"overview.latestWorks": "最新产物",
+ "overview.messageNotSent": "消息没有发出,草稿已保留。",
"overview.mode.chat": "对话",
"overview.mode.task": "任务",
"overview.needsAttention": "需要你处理",
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index 0bb490451f7..d596213a5ff 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -202,6 +202,7 @@ export default {
'list.viewAll': 'View all projects',
'overview.noDescription': 'A dedicated workspace for this long-running goal.',
'overview.activeTasks': 'In progress',
+ 'overview.agentSelect': 'Choose an agent',
'overview.contextTitle': 'Project context',
'overview.description': 'Start with a question, or review the project’s progress and outputs.',
'overview.goalCount': '{{completed}} of {{total}} goals completed',
@@ -311,6 +312,7 @@ export default {
'settings.members': 'Members',
'overview.createTask': 'Create task',
'overview.createTaskFailed': 'Could not create the task',
+ 'overview.messageNotSent': 'The message was not sent. Your draft has been kept.',
'overview.mode.chat': 'Chat',
'overview.mode.task': 'Task',
'overview.sendFailed': 'Could not create the topic',
diff --git a/src/features/Conversation/utils/isOnRouteTopic.test.ts b/src/features/Conversation/utils/isOnRouteTopic.test.ts
new file mode 100644
index 00000000000..5942091ee9e
--- /dev/null
+++ b/src/features/Conversation/utils/isOnRouteTopic.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { isOnRouteTopic } from './isOnRouteTopic';
+
+describe('isOnRouteTopic', () => {
+ /**
+ * @example Project home: `…/conversation/tpc_1?message=` was sent while the
+ * conversation still had no topic, so the send started a second topic outside
+ * the project and the page reported "topic not found".
+ */
+ it('holds a topic URL until the conversation is on that topic', () => {
+ expect(isOnRouteTopic('tpc_1', undefined)).toBe(false);
+ expect(isOnRouteTopic('tpc_1', null)).toBe(false);
+ expect(isOnRouteTopic('tpc_1', 'tpc_previous')).toBe(false);
+ expect(isOnRouteTopic('tpc_1', 'tpc_1')).toBe(true);
+ });
+
+ it('lets a URL without a topic start a new conversation', () => {
+ expect(isOnRouteTopic(undefined, undefined)).toBe(true);
+ expect(isOnRouteTopic(undefined, 'tpc_1')).toBe(true);
+ });
+});
diff --git a/src/features/Conversation/utils/isOnRouteTopic.ts b/src/features/Conversation/utils/isOnRouteTopic.ts
new file mode 100644
index 00000000000..c87112cbe8c
--- /dev/null
+++ b/src/features/Conversation/utils/isOnRouteTopic.ts
@@ -0,0 +1,10 @@
+/**
+ * A deferred send on a topic URL (`…/:topicId?message=`) belongs to that
+ * topic. The conversation context adopts the route's topic a render after the
+ * page mounts; a send before then reads "no topic" and starts a new one, which
+ * the page then navigates to instead of the topic the link named.
+ */
+export const isOnRouteTopic = (
+ routeTopicId: string | undefined,
+ contextTopicId: string | null | undefined,
+) => !routeTopicId || contextTopicId === routeTopicId;
diff --git a/src/features/Projects/Layout/navigation.test.ts b/src/features/Projects/Layout/navigation.test.ts
index c8e1b2eefdc..845e5846291 100644
--- a/src/features/Projects/Layout/navigation.test.ts
+++ b/src/features/Projects/Layout/navigation.test.ts
@@ -4,7 +4,6 @@ import {
getProjectAcceptancePath,
getProjectAgentPath,
getProjectConversationPath,
- getProjectConversationStartPath,
getProjectDashboardPath,
getProjectGoalsPath,
getProjectHomePath,
@@ -34,9 +33,6 @@ describe('project workspace navigation', () => {
it('builds new and existing conversation routes inside the project', () => {
expect(getProjectConversationPath('prj_1')).toBe('/project/prj_1/conversation');
expect(getProjectConversationPath('prj_1', 'tpc_1')).toBe('/project/prj_1/conversation/tpc_1');
- expect(getProjectConversationStartPath('prj_1', 'tpc_1', 'Plan Q3 & ship')).toBe(
- '/project/prj_1/conversation/tpc_1?message=Plan%20Q3%20%26%20ship',
- );
});
});
diff --git a/src/features/Projects/Layout/navigation.ts b/src/features/Projects/Layout/navigation.ts
index e5f3c19c63a..d79da351049 100644
--- a/src/features/Projects/Layout/navigation.ts
+++ b/src/features/Projects/Layout/navigation.ts
@@ -13,13 +13,6 @@ export const getProjectConversationPath = (projectId: string, topicId?: string)
export const getProjectDraftPath = (projectId: string, agentId: string, directoryId: string) =>
`${getProjectConversationPath(projectId)}?${new URLSearchParams({ agent: agentId, dir: directoryId })}`;
-/** Open a project conversation and send `message` in it once it has loaded. */
-export const getProjectConversationStartPath = (
- projectId: string,
- topicId: string,
- message: string,
-) => `${getProjectConversationPath(projectId, topicId)}?message=${encodeURIComponent(message)}`;
-
export const getProjectLibraryPath = (projectId: string, libraryId: string) =>
`/project/${projectId}/library/${libraryId}`;
diff --git a/src/features/Projects/Workspace/ProjectAgentSelect.tsx b/src/features/Projects/Workspace/ProjectAgentSelect.tsx
new file mode 100644
index 00000000000..eb188a6bb04
--- /dev/null
+++ b/src/features/Projects/Workspace/ProjectAgentSelect.tsx
@@ -0,0 +1,164 @@
+'use client';
+
+import { agentDisplayName } from '@lobechat/types';
+import { Block, Button, Flexbox, Popover, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ChevronDownIcon } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import Avatar from '@/components/Avatar';
+import { DEFAULT_AVATAR } from '@/const/meta';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+
+import type { ProjectComposerAgent } from './projectComposerAgents';
+
+const styles = stylex.create({
+ active: {
+ backgroundColor: cssVar.colorFillTertiary,
+ },
+ chevron: {
+ flexShrink: 0,
+ color: cssVar.colorTextDescription,
+ },
+ item: {
+ cursor: 'pointer',
+ paddingBlock: '6px',
+ paddingInline: '8px',
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: { 'default': null, ':hover': cssVar.colorFillSecondary },
+ },
+ list: {
+ overflowY: 'auto',
+ maxHeight: '320px',
+ padding: '8px',
+ },
+ name: {
+ flex: '1',
+ minWidth: 0,
+ },
+ trigger: {
+ maxWidth: '200px',
+ paddingInlineStart: '6px',
+ paddingInlineEnd: '8px',
+ },
+});
+
+/** A main agent without a member row (the LobeAI fallback) reads its meta from the agent store. */
+const useAgentMeta = (agent: ProjectComposerAgent) => {
+ const stored = useAgentStore(agentSelectors.getAgentMetaById(agent.id));
+ const { t } = useTranslation('common');
+ const source = agent.title || agent.name || agent.avatar ? agent : stored;
+ return {
+ avatar: (typeof source?.avatar === 'string' ? source.avatar : undefined) || DEFAULT_AVATAR,
+ background: source?.backgroundColor || undefined,
+ name: agentDisplayName(source, t('defaultAgent')),
+ };
+};
+
+const AgentRow = memo<{
+ active: boolean;
+ agent: ProjectComposerAgent;
+ onSelect: (id: string) => void;
+}>(({ active, agent, onSelect }) => {
+ const { t } = useTranslation('project');
+ const meta = useAgentMeta(agent);
+ return (
+ <Block
+ clickable
+ horizontal
+ align={'center'}
+ {...stylex.props(styles.item, active && styles.active)}
+ gap={8}
+ variant={'borderless'}
+ onClick={() => onSelect(agent.id)}
+ >
+ <Avatar
+ avatar={meta.avatar}
+ background={meta.background}
+ name={meta.name}
+ shape={'square'}
+ size={24}
+ />
+ <Text
+ ellipsis
+ type={active ? undefined : 'secondary'}
+ weight={active ? 600 : 500}
+ {...stylex.props(styles.name)}
+ >
+ {meta.name}
+ </Text>
+ {agent.isMain && <Tag size={'small'}>{t('directories.coordinator')}</Tag>}
+ </Block>
+ );
+});
+
+interface ProjectAgentSelectProps {
+ agents: ProjectComposerAgent[];
+ disabled?: boolean;
+ onChange: (agentId: string) => void;
+ value: string;
+}
+
+/** Picks which project agent the composer sends to; the main agent leads. */
+const ProjectAgentSelect = memo<ProjectAgentSelectProps>(
+ ({ agents, disabled, onChange, value }) => {
+ const { t } = useTranslation('project');
+ const [open, setOpen] = useState(false);
+ const selected = agents.find((agent) => agent.id === value) ?? agents[0];
+ const meta = useAgentMeta(selected);
+
+ return (
+ <Popover
+ open={open}
+ placement={'bottomLeft'}
+ styles={{ content: { padding: 0, width: 280 } }}
+ trigger={'click'}
+ content={
+ <Flexbox gap={2} {...stylex.props(styles.list)}>
+ {agents.map((agent) => (
+ <AgentRow
+ active={agent.id === selected.id}
+ agent={agent}
+ key={agent.id}
+ onSelect={(id) => {
+ setOpen(false);
+ onChange(id);
+ }}
+ />
+ ))}
+ </Flexbox>
+ }
+ onOpenChange={(next) => setOpen(disabled ? false : next)}
+ >
+ <Button
+ aria-expanded={open}
+ aria-haspopup={'dialog'}
+ aria-label={t('overview.agentSelect')}
+ {...stylex.props(styles.trigger)}
+ disabled={disabled}
+ size={'small'}
+ type={'text'}
+ >
+ <Avatar
+ avatar={meta.avatar}
+ background={meta.background}
+ name={meta.name}
+ shape={'square'}
+ size={18}
+ />
+ <Text ellipsis fontSize={13} style={{ minWidth: 0 }} weight={500}>
+ {meta.name}
+ </Text>
+ <ChevronDownIcon size={12} {...stylex.props(styles.chevron)} />
+ </Button>
+ </Popover>
+ );
+ },
+);
+
+ProjectAgentSelect.displayName = 'ProjectAgentSelect';
+
+export default ProjectAgentSelect;
diff --git a/src/features/Projects/Workspace/ProjectComposer.tsx b/src/features/Projects/Workspace/ProjectComposer.tsx
new file mode 100644
index 00000000000..fae84daef45
--- /dev/null
+++ b/src/features/Projects/Workspace/ProjectComposer.tsx
@@ -0,0 +1,153 @@
+'use client';
+
+import { cssVar, Flexbox, Segmented, toast } from '@lobehub/ui';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useUploadFiles } from '@/components/DragUploadZone';
+import {
+ type ActionKeys,
+ ChatInputProvider,
+ DesktopChatInput,
+ type SendButtonHandler,
+} from '@/features/ChatInput';
+import FileUpload from '@/features/ChatInput/ActionBar/Upload';
+import InputDragUpload from '@/features/Home/InputArea/InputDragUpload';
+import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import type { ProjectDetail } from '@/store/project';
+
+import ProjectAgentSelect from './ProjectAgentSelect';
+import { projectComposerAgents } from './projectComposerAgents';
+import {
+ AttachmentsNotReadyError,
+ MessageNotAcceptedError,
+ type ProjectComposerMode,
+ useProjectComposer,
+} from './useProjectComposer';
+
+const leftActions: ActionKeys[] = [];
+const rightActions: ActionKeys[] = [];
+
+const CONTAINER_RADIUS = 18;
+/** Clearance from the container edge to the round controls sitting in its corners. */
+const ACTION_BAR_INSET = 8;
+
+const inputContainerProps = {
+ minHeight: 88,
+ resize: false,
+ style: {
+ borderRadius: CONTAINER_RADIUS,
+ boxShadow: cssVar.boxShadowSecondary,
+ },
+};
+const actionBarStyle = { paddingBlockEnd: ACTION_BAR_INSET, paddingInline: ACTION_BAR_INSET };
+
+interface ProjectComposerProps {
+ detail: ProjectDetail;
+}
+
+/**
+ * The project home composer is the regular chat input — line breaks, pasted
+ * images and attachments behave as in any conversation — sending to a
+ * project agent (the main agent unless another is picked), or recording a task
+ * for it.
+ */
+const ProjectComposer = memo<ProjectComposerProps>(({ detail }) => {
+ const { project } = detail;
+ const { t } = useTranslation('project');
+ const { t: tHome } = useTranslation('home');
+ const [mode, setMode] = useState<ProjectComposerMode>('chat');
+ const agents = useMemo(() => projectComposerAgents(detail), [detail]);
+ const [pickedAgentId, setPickedAgentId] = useState<string>();
+ // A pick that left the project (disabled or removed) falls back to the main agent.
+ const agentId =
+ agents.find((agent) => agent.id === pickedAgentId)?.id ?? project.coordinatorAgentId;
+ const { send, sending } = useProjectComposer(project, mode, agentId);
+
+ useInitAgentConfig(agentId);
+ const isAgentConfigLoading = useAgentStore((s) =>
+ agentByIdSelectors.isAgentConfigLoadingById(agentId)(s),
+ );
+ const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
+ const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
+ const { handleUploadFiles } = useUploadFiles({ agentId, model, provider });
+
+ const submit: SendButtonHandler = async (params) => {
+ try {
+ await send(params);
+ } catch (error) {
+ if (error instanceof AttachmentsNotReadyError) {
+ toast.error(tHome('dashboard.task.attachmentsNotReady'));
+ return;
+ }
+ if (error instanceof MessageNotAcceptedError) {
+ toast.error(t('overview.messageNotSent'));
+ return;
+ }
+ console.error('Failed to send from the project home', error);
+ toast.error(t(mode === 'task' ? 'overview.createTaskFailed' : 'overview.sendFailed'));
+ }
+ };
+
+ const sendButtonProps = useMemo(
+ () => ({
+ disabled: sending || isAgentConfigLoading,
+ generating: sending,
+ onStop: () => {},
+ shape: 'round' as const,
+ }),
+ [sending, isAgentConfigLoading],
+ );
+
+ return (
+ <InputDragUpload radius={CONTAINER_RADIUS} onUploadFiles={handleUploadFiles}>
+ <ChatInputProvider
+ agentId={agentId}
+ allowExpand={false}
+ contextSelectionKey={`project-home:${project.id}`}
+ leftActions={leftActions}
+ rightActions={rightActions}
+ sendButtonProps={sendButtonProps}
+ slashPlacement="bottom"
+ topicId={null}
+ onSend={submit}
+ >
+ <DesktopChatInput
+ actionBarStyle={actionBarStyle}
+ dropdownPlacement="bottomLeft"
+ inputContainerProps={inputContainerProps}
+ showControlBar={false}
+ leftContent={
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Segmented
+ size={'small'}
+ value={mode}
+ options={[
+ { label: t('overview.mode.chat'), value: 'chat' },
+ { label: t('overview.mode.task'), value: 'task' },
+ ]}
+ onChange={(value) => setMode(value as ProjectComposerMode)}
+ />
+ <ProjectAgentSelect
+ agents={agents}
+ disabled={sending}
+ value={agentId}
+ onChange={setPickedAgentId}
+ />
+ <FileUpload includeKnowledge={false} />
+ </Flexbox>
+ }
+ placeholder={t(
+ mode === 'task' ? 'overview.taskPlaceholder' : 'overview.composerPlaceholder',
+ )}
+ />
+ </ChatInputProvider>
+ </InputDragUpload>
+ );
+});
+
+ProjectComposer.displayName = 'ProjectComposer';
+
+export default ProjectComposer;
diff --git a/src/features/Projects/Workspace/index.tsx b/src/features/Projects/Workspace/index.tsx
index 98a99201af1..1e342df0168 100644
--- a/src/features/Projects/Workspace/index.tsx
+++ b/src/features/Projects/Workspace/index.tsx
@@ -1,45 +1,21 @@
'use client';
-import {
- Button,
- createStaticStyles,
- cssVar,
- Flexbox,
- Segmented,
- Text,
- TextArea,
- toast,
-} from '@lobehub/ui';
-import { SendHorizontalIcon } from 'lucide-react';
-import { memo, useState } from 'react';
+import { createStaticStyles, cssVar, Flexbox, Text } from '@lobehub/ui';
+import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router';
import AsyncError from '@/components/AsyncError';
import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import ProjectDisabled from '@/features/Projects/ProjectDisabled';
-import type { ProjectDetail } from '@/store/project';
import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
+import ProjectComposer from './ProjectComposer';
import ProjectDashboard from './ProjectDashboard';
-import { type ProjectComposerMode, useProjectComposer } from './useProjectComposer';
const styles = createStaticStyles(({ css }) => ({
- composer: css`
- overflow: hidden;
-
- border: 1px solid ${cssVar.colorBorder};
- border-radius: 18px;
-
- background: ${cssVar.colorBgContainer};
- box-shadow: ${cssVar.boxShadowSecondary};
- `,
- composerFooter: css`
- padding-block: 6px 8px;
- padding-inline: 14px 8px;
- `,
content: css`
overflow: auto;
width: 100%;
@@ -68,77 +44,8 @@ const styles = createStaticStyles(({ css }) => ({
height: 100%;
background: ${cssVar.colorBgContainer};
`,
- textarea: css`
- padding-block: 15px 8px !important;
- padding-inline: 16px !important;
- border: 0 !important;
-
- font-size: 15px !important;
-
- background: transparent !important;
- box-shadow: none !important;
- `,
}));
-const ProjectComposer = ({ project }: { project: ProjectDetail['project'] }) => {
- const { t } = useTranslation('project');
- const [mode, setMode] = useState<ProjectComposerMode>('chat');
- const { draft: message, send, sending, setDraft: setMessage } = useProjectComposer(project);
-
- const submit = async () => {
- try {
- await send(mode);
- } catch (error) {
- console.error('Failed to send from the project home', error);
- toast.error(t(mode === 'task' ? 'overview.createTaskFailed' : 'overview.sendFailed'));
- }
- };
-
- return (
- <Flexbox className={styles.composer}>
- <TextArea
- autoFocus
- autoSize={{ maxRows: 7, minRows: 3 }}
- className={styles.textarea}
- disabled={sending}
- value={message}
- placeholder={t(
- mode === 'task' ? 'overview.taskPlaceholder' : 'overview.composerPlaceholder',
- )}
- onChange={(event) => setMessage(event.target.value)}
- onKeyDown={(event) => {
- if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') void submit();
- }}
- />
- <Flexbox
- horizontal
- align={'center'}
- className={styles.composerFooter}
- justify={'space-between'}
- >
- <Segmented
- size={'small'}
- value={mode}
- options={[
- { label: t('overview.mode.chat'), value: 'chat' },
- { label: t('overview.mode.task'), value: 'task' },
- ]}
- onChange={(value) => setMode(value as ProjectComposerMode)}
- />
- <Button
- aria-label={t(mode === 'task' ? 'overview.createTask' : 'overview.startConversation')}
- disabled={!message.trim()}
- icon={SendHorizontalIcon}
- loading={sending}
- shape={'circle'}
- type={'primary'}
- onClick={submit}
- />
- </Flexbox>
- </Flexbox>
- );
-};
-
const ProjectWorkspace = memo(() => {
const { t } = useTranslation('project');
const { projectId } = useParams<{ projectId: string }>();
@@ -162,7 +69,7 @@ const ProjectWorkspace = memo(() => {
</Text>
<Text type={'secondary'}>{t('overview.description')}</Text>
</Flexbox>
- <ProjectComposer key={detail.project.id} project={detail.project} />
+ <ProjectComposer detail={detail} key={detail.project.id} />
</Flexbox>
<ProjectDashboard detail={detail} projectId={detail.project.id} />
</Flexbox>
diff --git a/src/features/Projects/Workspace/projectComposerAgents.test.ts b/src/features/Projects/Workspace/projectComposerAgents.test.ts
new file mode 100644
index 00000000000..099be121e34
--- /dev/null
+++ b/src/features/Projects/Workspace/projectComposerAgents.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+
+import { projectComposerAgents } from './projectComposerAgents';
+
+const member = (id: string, enabled = true) => ({
+ agent: { avatar: null, backgroundColor: null, id, name: null, title: `Agent ${id}` },
+ binding: { enabled },
+});
+
+const detail = (coordinatorAgentId: string, agents: ReturnType<typeof member>[]) =>
+ ({ agents, project: { coordinatorAgentId } }) as unknown as Parameters<
+ typeof projectComposerAgents
+ >[0];
+
+describe('projectComposerAgents', () => {
+ it('lists the main agent first, then the enabled members', () => {
+ const agents = projectComposerAgents(
+ detail('main', [member('writer'), member('main'), member('paused', false)]),
+ );
+
+ expect(agents.map((agent) => [agent.id, agent.isMain])).toEqual([
+ ['main', true],
+ ['writer', false],
+ ]);
+ });
+
+ it('keeps a main agent without a member row, for the store to describe', () => {
+ const agents = projectComposerAgents(detail('inbox', [member('writer')]));
+
+ expect(agents[0]).toEqual({ id: 'inbox', isMain: true });
+ expect(agents.map((agent) => agent.id)).toEqual(['inbox', 'writer']);
+ });
+});
diff --git a/src/features/Projects/Workspace/projectComposerAgents.ts b/src/features/Projects/Workspace/projectComposerAgents.ts
new file mode 100644
index 00000000000..a396c7eecb1
--- /dev/null
+++ b/src/features/Projects/Workspace/projectComposerAgents.ts
@@ -0,0 +1,35 @@
+import type { ProjectDetail } from '@/store/project';
+
+export interface ProjectComposerAgent {
+ avatar?: string | null;
+ backgroundColor?: string | null;
+ id: string;
+ isMain: boolean;
+ name?: string | null;
+ title?: string | null;
+}
+
+/**
+ * Who the project home composer can hand a message to: the project's main
+ * agent first, then its enabled members. A main agent that fell back to LobeAI
+ * has no member row, so it is listed by id alone and the caller fills in its
+ * meta.
+ */
+export const projectComposerAgents = (
+ detail: Pick<ProjectDetail, 'agents' | 'project'>,
+): ProjectComposerAgent[] => {
+ const mainAgentId = detail.project.coordinatorAgentId;
+ const members = (detail.agents ?? [])
+ .filter(({ agent, binding }) => binding.enabled || agent.id === mainAgentId)
+ .map(({ agent }) => ({
+ avatar: agent.avatar,
+ backgroundColor: agent.backgroundColor,
+ id: agent.id,
+ isMain: agent.id === mainAgentId,
+ name: agent.name,
+ title: agent.title,
+ }));
+ const main = members.find((agent) => agent.isMain) ?? { id: mainAgentId, isMain: true };
+
+ return [main, ...members.filter((agent) => !agent.isMain)];
+};
diff --git a/src/features/Projects/Workspace/useProjectComposer.test.ts b/src/features/Projects/Workspace/useProjectComposer.test.ts
index 3d7368153df..7d89e756119 100644
--- a/src/features/Projects/Workspace/useProjectComposer.test.ts
+++ b/src/features/Projects/Workspace/useProjectComposer.test.ts
@@ -6,12 +6,34 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ProjectDetail } from '@/store/project';
-import { toConversationTitle, useProjectComposer } from './useProjectComposer';
+import {
+ AttachmentsNotReadyError,
+ MessageNotAcceptedError,
+ toConversationTitle,
+ useProjectComposer,
+} from './useProjectComposer';
const mocks = vi.hoisted(() => ({
+ agentMap: {} as Record<string, unknown>,
+ clearChatUploadFileList: vi.fn(),
createProjectTopic: vi.fn(),
createTask: vi.fn(),
+ fileList: [] as unknown[],
+ getAgentConfigById: vi.fn(),
+ internal_dispatchAgentMap: vi.fn(),
navigate: vi.fn(),
+ refreshProjectTopics: vi.fn(),
+ removeTopic: vi.fn(),
+ sendMessage: vi.fn(),
+ workspaceSlug: null as string | null,
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ useActiveWorkspaceSlug: () => mocks.workspaceSlug,
+}));
+
+vi.mock('@/services/topic', () => ({
+ topicService: { removeTopic: mocks.removeTopic },
}));
vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
@@ -20,7 +42,10 @@ vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
vi.mock('@/store/projectWorkingDirectory', () => ({
useProjectDirectoryStore: (selector: (state: unknown) => unknown) =>
- selector({ createProjectTopic: mocks.createProjectTopic }),
+ selector({
+ createProjectTopic: mocks.createProjectTopic,
+ refreshProjectTopics: mocks.refreshProjectTopics,
+ }),
}));
vi.mock('@/store/task', () => ({
@@ -28,95 +53,261 @@ vi.mock('@/store/task', () => ({
selector({ createTask: mocks.createTask }),
}));
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (state: unknown) => unknown) =>
+ selector({ sendMessage: mocks.sendMessage }),
+}));
+
+vi.mock('@/store/file', () => {
+ const state = () => ({
+ chatUploadFileList: mocks.fileList,
+ clearChatUploadFileList: mocks.clearChatUploadFileList,
+ });
+ const useFileStore = Object.assign((selector: (s: unknown) => unknown) => selector(state()), {
+ getState: state,
+ });
+ return {
+ fileChatSelectors: {
+ chatUploadFileList: (s: { chatUploadFileList: unknown[] }) => s.chatUploadFileList,
+ },
+ useFileStore,
+ };
+});
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: {
+ getState: () => ({
+ agentMap: mocks.agentMap,
+ internal_dispatchAgentMap: mocks.internal_dispatchAgentMap,
+ }),
+ },
+}));
+
+vi.mock('@/services/agent', () => ({
+ agentService: { getAgentConfigById: mocks.getAgentConfigById },
+}));
+
const project = {
coordinatorAgentId: 'coordinator',
id: 'prj_1',
slug: 'apollo',
} as ProjectDetail['project'];
+const editorData = { root: { children: [] } };
+const composer = (markdown: string) => ({
+ clearContent: vi.fn(),
+ editor: {} as never,
+ getEditorData: () => editorData,
+ getMarkdownContent: () => markdown,
+});
+
+const image = {
+ file: { name: 'shot.png', size: 1, type: 'image/png' },
+ fileUrl: 'https://cdn/shot.png',
+ id: 'file_1',
+ status: 'success',
+};
+
describe('useProjectComposer', () => {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.agentMap = { coordinator: {} };
+ mocks.fileList = [];
+ mocks.workspaceSlug = null;
+ mocks.removeTopic.mockResolvedValue(undefined);
+ // The conversation takes the message, then the run goes on in the background.
+ mocks.sendMessage.mockImplementation(({ onMessageAccepted }) => {
+ onMessageAccepted?.();
+ return new Promise(() => {});
+ });
});
- it('opens a coordinator conversation owned by the project and sends the message in it', async () => {
+ /**
+ * @example Project home: a sent message opened "topic not found" — the
+ * `?message=` auto-send fired before the page bound the project topic, so it
+ * created a second topic outside the project and lost the attachments.
+ */
+ it('sends the message and its attachments into the project conversation it creates', async () => {
mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
- const { result } = renderHook(() => useProjectComposer(project));
+ mocks.fileList = [image];
+ const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
+ const input = composer(' Plan the next milestone\nwith details ');
- act(() => result.current.setDraft(' Plan the next milestone\nwith details '));
- let sent = false;
await act(async () => {
- sent = await result.current.send('chat');
+ await result.current.send(input);
});
- expect(sent).toBe(true);
- expect(result.current.draft).toBe('');
expect(mocks.createProjectTopic).toHaveBeenCalledWith({
agentId: 'coordinator',
projectId: 'prj_1',
title: 'Plan the next milestone',
});
- expect(mocks.navigate).toHaveBeenCalledWith(
- '/project/apollo/conversation/tpc_1?message=Plan%20the%20next%20milestone%0Awith%20details',
- );
+ expect(mocks.sendMessage).toHaveBeenCalledWith({
+ context: { agentId: 'coordinator', topicId: 'tpc_1' },
+ editorData,
+ files: [image],
+ inputEditor: null,
+ message: 'Plan the next milestone\nwith details',
+ onMessageAccepted: expect.any(Function),
+ });
+ expect(mocks.navigate).toHaveBeenCalledWith('/project/apollo/conversation/tpc_1');
+ expect(input.clearContent).toHaveBeenCalled();
+ expect(mocks.clearChatUploadFileList).toHaveBeenCalled();
expect(mocks.createTask).not.toHaveBeenCalled();
});
- it('records a project task assigned to the coordinator in task mode', async () => {
+ it('sends to the project agent the user picked instead of the main agent', async () => {
+ mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
+ mocks.agentMap = { reviewer: {} };
+ const { result } = renderHook(() => useProjectComposer(project, 'chat', 'reviewer'));
+
+ await act(async () => {
+ await result.current.send(composer('Review the release notes'));
+ });
+
+ expect(mocks.createProjectTopic).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'reviewer', projectId: 'prj_1' }),
+ );
+ expect(mocks.sendMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ context: { agentId: 'reviewer', topicId: 'tpc_1' } }),
+ );
+ });
+
+ it('assigns a task to the picked project agent', async () => {
mocks.createTask.mockResolvedValue({ id: 'task_1', name: 'Ship it' });
- const { result } = renderHook(() => useProjectComposer(project));
+ const { result } = renderHook(() => useProjectComposer(project, 'task', 'reviewer'));
- act(() => result.current.setDraft('Ship it'));
await act(async () => {
- await result.current.send('task');
+ await result.current.send(composer('Ship it'));
});
- expect(mocks.createTask).toHaveBeenCalledWith({
- assigneeAgentId: 'coordinator',
- instruction: 'Ship it',
- projectId: 'prj_1',
+ expect(mocks.createTask).toHaveBeenCalledWith(
+ expect.objectContaining({ assigneeAgentId: 'reviewer', projectId: 'prj_1' }),
+ );
+ });
+
+ /**
+ * @example Codex review: a preflight rejection was fire-and-forget while the
+ * composer cleared itself and navigated, so the draft and attachments were lost.
+ */
+ it('keeps the draft and drops the empty topic when the send is refused before acceptance', async () => {
+ mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
+ mocks.fileList = [image];
+ mocks.sendMessage.mockRejectedValue(new Error('device offline'));
+ const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
+ const input = composer('Hello');
+
+ await act(async () => {
+ await expect(result.current.send(input)).rejects.toBeInstanceOf(MessageNotAcceptedError);
});
+
+ expect(input.clearContent).not.toHaveBeenCalled();
+ expect(mocks.clearChatUploadFileList).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ expect(mocks.removeTopic).toHaveBeenCalledWith('tpc_1');
+ expect(mocks.refreshProjectTopics).toHaveBeenCalledWith('prj_1');
+ expect(result.current.sending).toBe(false);
+ });
+
+ it('treats a send that resolves without accepting the message as refused', async () => {
+ mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
+ mocks.sendMessage.mockResolvedValue(undefined);
+ const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
+ const input = composer('Hello');
+
+ await act(async () => {
+ await expect(result.current.send(input)).rejects.toBeInstanceOf(MessageNotAcceptedError);
+ });
+
+ expect(input.clearContent).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ /** @example Codex review: desktop notifications from these sends linked outside the workspace. */
+ it('sends with the active workspace so its links stay inside it', async () => {
+ mocks.workspaceSlug = 'acme';
+ mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
+ const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
+
+ await act(async () => {
+ await result.current.send(composer('Hello'));
+ });
+
+ expect(mocks.sendMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ context: { agentId: 'coordinator', topicId: 'tpc_1', workspaceSlug: 'acme' },
+ }),
+ );
+ });
+
+ it('loads the main agent config before sending to it', async () => {
+ mocks.agentMap = {};
+ mocks.getAgentConfigById.mockResolvedValue({ model: 'm' });
+ mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
+ const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
+
+ await act(async () => {
+ await result.current.send(composer('Hello'));
+ });
+
+ expect(mocks.internal_dispatchAgentMap).toHaveBeenCalledWith('coordinator', { model: 'm' });
+ expect(mocks.sendMessage).toHaveBeenCalled();
+ });
+
+ it('records a project task with its attachments in task mode', async () => {
+ mocks.createTask.mockResolvedValue({ id: 'task_1', name: 'Ship it' });
+ mocks.fileList = [image];
+ const { result } = renderHook(() => useProjectComposer(project, 'task', 'coordinator'));
+
+ await act(async () => {
+ await result.current.send(composer('Ship it\nwith the changelog'));
+ });
+
+ expect(mocks.createTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ assigneeAgentId: 'coordinator',
+ instruction: 'Ship it\nwith the changelog',
+ name: 'Ship it',
+ projectId: 'prj_1',
+ }),
+ );
+ expect(mocks.clearChatUploadFileList).toHaveBeenCalledWith(['file_1']);
expect(mocks.navigate).toHaveBeenCalledWith('/task/task_1/ship-it');
expect(mocks.createProjectTopic).not.toHaveBeenCalled();
+ expect(mocks.sendMessage).not.toHaveBeenCalled();
});
- it('ignores a blank message and keeps a failed send in the composer', async () => {
+ it('ignores an empty composer and keeps a failed send in it', async () => {
mocks.createProjectTopic.mockRejectedValue(new Error('denied'));
- const { result } = renderHook(() => useProjectComposer(project));
+ const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
- act(() => result.current.setDraft(' '));
await act(async () => {
- expect(await result.current.send('chat')).toBe(false);
+ await result.current.send(composer(' '));
});
- act(() => result.current.setDraft('Hello'));
+ expect(mocks.createProjectTopic).not.toHaveBeenCalled();
+
+ const input = composer('Hello');
await act(async () => {
- await expect(result.current.send('chat')).rejects.toThrow('denied');
+ await expect(result.current.send(input)).rejects.toThrow('denied');
});
+ expect(mocks.sendMessage).not.toHaveBeenCalled();
expect(mocks.navigate).not.toHaveBeenCalled();
- expect(result.current.draft).toBe('Hello');
+ expect(input.clearContent).not.toHaveBeenCalled();
expect(result.current.sending).toBe(false);
});
- it('keeps a draft picked while the previous send was still pending', async () => {
- let resolveTopic!: (topic: { id: string }) => void;
- mocks.createProjectTopic.mockImplementation(
- () => new Promise((resolve) => (resolveTopic = resolve)),
- );
- const { result } = renderHook(() => useProjectComposer(project));
+ it('refuses to send while an attachment is still uploading', async () => {
+ mocks.fileList = [{ ...image, fileUrl: undefined, status: 'uploading' }];
+ const { result } = renderHook(() => useProjectComposer(project, 'chat', 'coordinator'));
- act(() => result.current.setDraft('First'));
- let pending!: Promise<boolean>;
- act(() => {
- pending = result.current.send('chat');
- });
- act(() => result.current.setDraft('Find the current blockers'));
await act(async () => {
- resolveTopic({ id: 'tpc_1' });
- await pending;
+ await expect(result.current.send(composer('Hello'))).rejects.toBeInstanceOf(
+ AttachmentsNotReadyError,
+ );
});
- expect(result.current.draft).toBe('Find the current blockers');
+ expect(mocks.createProjectTopic).not.toHaveBeenCalled();
});
it('titles a conversation by its first line', () => {
diff --git a/src/features/Projects/Workspace/useProjectComposer.ts b/src/features/Projects/Workspace/useProjectComposer.ts
index 27753f7ab46..e95ac89b8c3 100644
--- a/src/features/Projects/Workspace/useProjectComposer.ts
+++ b/src/features/Projects/Workspace/useProjectComposer.ts
@@ -1,16 +1,25 @@
import { useState } from 'react';
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
-import { getProjectConversationStartPath } from '@/features/Projects/Layout/navigation';
+import type { SendButtonHandler } from '@/features/ChatInput/store/initialState';
+import { appendTaskAttachments } from '@/features/Home/InputArea/taskAttachments';
+import { taskNameFromMessage } from '@/features/Home/InputArea/taskName';
+import { getProjectConversationPath } from '@/features/Projects/Layout/navigation';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { agentService } from '@/services/agent';
+import { topicService } from '@/services/topic';
+import { useAgentStore } from '@/store/agent';
+import { useChatStore } from '@/store/chat';
+import { fileChatSelectors, useFileStore } from '@/store/file';
import type { ProjectDetail } from '@/store/project';
import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
import { useTaskStore } from '@/store/task';
/**
- * `chat` hands the message to the project coordinator, which decides whether
- * to answer or to break it into project tasks. `task` records it as a task
- * straight away, without a model round trip.
+ * `chat` hands the message to the chosen project agent in a new project
+ * conversation. `task` records it as a task for that agent straight away,
+ * without a model round trip.
*/
export type ProjectComposerMode = 'chat' | 'task';
@@ -22,50 +31,116 @@ export const toConversationTitle = (message: string) => {
return firstLine.length > TITLE_LENGTH ? `${firstLine.slice(0, TITLE_LENGTH)}…` : firstLine;
};
-export const useProjectComposer = (project: ProjectDetail['project']) => {
+/** `sendMessage` reads the agent's model from `agentMap`; hydrate it first. */
+const ensureAgentConfigLoaded = async (agentId: string) => {
+ const agentState = useAgentStore.getState();
+ if (agentState.agentMap[agentId]) return;
+ const config = await agentService.getAgentConfigById(agentId);
+ if (config) agentState.internal_dispatchAgentMap(agentId, config);
+};
+
+export class AttachmentsNotReadyError extends Error {
+ constructor() {
+ super('Attachments are still uploading');
+ this.name = 'AttachmentsNotReadyError';
+ }
+}
+
+/** The send was refused before the message reached the conversation; the draft stays. */
+export class MessageNotAcceptedError extends Error {
+ constructor() {
+ super('The message was not accepted');
+ this.name = 'MessageNotAcceptedError';
+ }
+}
+
+export const useProjectComposer = (
+ project: ProjectDetail['project'],
+ mode: ProjectComposerMode,
+ /** The project agent the message goes to; the main agent unless the user picked another. */
+ agentId: string,
+) => {
const navigate = useWorkspaceAwareNavigate();
+ const workspaceSlug = useActiveWorkspaceSlug();
const createProjectTopic = useProjectDirectoryStore((s) => s.createProjectTopic);
+ const refreshProjectTopics = useProjectDirectoryStore((s) => s.refreshProjectTopics);
const createTask = useTaskStore((s) => s.createTask);
- const [draft, setDraft] = useState('');
+ const sendMessage = useChatStore((s) => s.sendMessage);
+ const clearChatUploadFileList = useFileStore((s) => s.clearChatUploadFileList);
const [sending, setSending] = useState(false);
- /** Resolves `true` once the draft has left the composer. */
- const send = async (mode: ProjectComposerMode) => {
- const submitted = draft;
- const message = submitted.trim();
- if (!message || sending) return false;
+ /** Rejects when nothing left the composer, so the caller can report it. */
+ const send: SendButtonHandler = async ({ clearContent, getEditorData, getMarkdownContent }) => {
+ const message = getMarkdownContent().trim();
+ const files = fileChatSelectors.chatUploadFileList(useFileStore.getState());
+ if ((!message && files.length === 0) || sending) return;
+ if (files.some((file) => file.status !== 'success' || !file.fileUrl))
+ throw new AttachmentsNotReadyError();
- // Clear the draft only if it still holds what was sent: the user may have
- // picked a prompt or typed again while the topic or task was being created.
- const clearSubmitted = () => setDraft((current) => (current === submitted ? '' : current));
+ const editorData = getEditorData();
+ const title = toConversationTitle(message || files[0].file.name);
setSending(true);
try {
if (mode === 'task') {
const task = await createTask({
- assigneeAgentId: project.coordinatorAgentId,
- instruction: message,
+ assigneeAgentId: agentId,
+ editorData: appendTaskAttachments(editorData, message, files),
+ instruction: message || title,
+ name: taskNameFromMessage(message || title),
projectId: project.id,
});
- clearSubmitted();
+ clearContent();
+ clearChatUploadFileList(files.map((file) => file.id));
if (task) navigate(taskDetailPath(task.id, undefined, task.name));
- return true;
+ return;
}
- // The conversation exists before the first message so the project owns it
- // from the start; the message is sent once the conversation has loaded.
- const topic = await createProjectTopic({
- agentId: project.coordinatorAgentId,
- projectId: project.id,
- title: toConversationTitle(message),
+ // The conversation is created inside the project first, so the project
+ // owns it from the start, and the message is sent into that exact topic.
+ // Sending here rather than after the page loads keeps the attachments,
+ // which cannot travel through the URL.
+ const [topic] = await Promise.all([
+ createProjectTopic({ agentId, projectId: project.id, title }),
+ ensureAgentConfigLoaded(agentId),
+ ]);
+ // Leave the composer only once the conversation owns the message. A send
+ // refused before that (access, device or preflight checks) either rejects
+ // or resolves without accepting, and with `inputEditor: null` nothing
+ // would put the draft back — so it stays here until then.
+ const accepted = await new Promise<boolean>((resolve) => {
+ sendMessage({
+ context: { agentId, topicId: topic.id, ...(workspaceSlug ? { workspaceSlug } : {}) },
+ editorData,
+ files,
+ inputEditor: null,
+ message,
+ onMessageAccepted: () => resolve(true),
+ }).then(
+ () => resolve(false),
+ (error) => {
+ console.error('[ProjectComposer] send failed', error);
+ resolve(false);
+ },
+ );
});
- clearSubmitted();
- navigate(getProjectConversationStartPath(project.slug ?? project.id, topic.id, message));
- return true;
+ if (!accepted) {
+ // Don't leave an empty conversation behind for every failed attempt.
+ await topicService
+ .removeTopic(topic.id)
+ .then(() => refreshProjectTopics(project.id))
+ .catch((error) =>
+ console.error('[ProjectComposer] failed to drop the empty topic', error),
+ );
+ throw new MessageNotAcceptedError();
+ }
+ clearContent();
+ clearChatUploadFileList();
+ navigate(getProjectConversationPath(project.slug ?? project.id, topic.id));
} finally {
setSending(false);
}
};
- return { draft, send, sending, setDraft };
+ return { send, sending };
};
diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx
index b632f6f9141..388f15d6a57 100644
--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx
@@ -163,6 +163,33 @@ describe('ChatHydration', () => {
});
});
+ /** @example ⌘K Ask AI: reloading the topic it created sent the question a second time. */
+ it('drops a consumed message param when the send moves to its new topic', async () => {
+ useParamsMock.mockReturnValue({ aid: 'agt_test' });
+ useLocationMock.mockReturnValue({
+ hash: '',
+ pathname: '/agent/agt_test',
+ search: '?message=hello&thread=thd_456',
+ });
+ useSearchParamsMock.mockReturnValue([
+ new URLSearchParams('message=hello&thread=thd_456'),
+ setSearchParamsMock,
+ ]);
+
+ render(<ChatHydration />);
+ navigateMock.mockClear();
+
+ await act(async () => {
+ useChatStore.setState({ activeTopicId: 'tpc_new' }, false);
+ });
+
+ await waitFor(() => {
+ expect(navigateMock).toHaveBeenCalledWith('/agent/agt_test/tpc_new?thread=thd_456', {
+ replace: true,
+ });
+ });
+ });
+
/** @example Edit changes topic and clears an already-absent thread without reverting the URL. */
it('does not rewrite the old URL when an edited topic clears an absent thread', async () => {
// ROOT CAUSE:
diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.ts b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.ts
index 7c9c621d571..3fa62712daa 100644
--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.ts
+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.ts
@@ -67,6 +67,9 @@ export const useChatRouteSync = (options: ChatRouteSyncOptions = {}) => {
const nextSearchParams = new URLSearchParams(searchParamsRef.current);
nextSearchParams.delete('topic');
+ // `?message=` is a one-shot send for the conversation the link opened.
+ // Carried onto the topic that send created, a reload would send it again.
+ nextSearchParams.delete('message');
const nextPath = state
? options.getTopicPath?.(routeAgentId, state) || AGENT_CHAT_TOPIC_URL(routeAgentId, state)
diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/MessageFromUrl.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/MessageFromUrl.tsx
index ad9af34e44e..762ee0a84b5 100644
--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/MessageFromUrl.tsx
+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/MessageFromUrl.tsx
@@ -1,10 +1,11 @@
'use client';
import { useEffect, useMemo, useRef } from 'react';
-import { useLocation, useSearchParams } from 'react-router';
+import { useLocation, useParams, useSearchParams } from 'react-router';
import { useConversationStore } from '@/features/Conversation';
import { useConversationResourceAccess } from '@/features/Conversation/hooks/useConversationResourceAccess';
+import { isOnRouteTopic } from '@/features/Conversation/utils/isOnRouteTopic';
import { overlayCaptureUploadPool } from '@/features/Electron/ScreenCapture/overlayCaptureUploadPool';
import { canConsumePendingOverlayDispatch } from '@/features/Electron/ScreenCapture/overlayDispatch';
import { useOverlayDispatchStore } from '@/features/Electron/ScreenCapture/overlayDispatchStore';
@@ -28,6 +29,7 @@ const MessageFromUrl = () => {
const agentId = context.agentId;
const [searchParams, setSearchParams] = useSearchParams();
const location = useLocation();
+ const { topicId: routeTopicId } = useParams<{ topicId?: string }>();
const isAgentConfigLoading = useAgentStore(agentSelectors.isAgentConfigLoading);
const { allowed: canCreate } = usePermission('create_content');
const { allowed: canEdit } = usePermission('edit_own_content');
@@ -61,6 +63,8 @@ const MessageFromUrl = () => {
// During agent switching, URL/searchParams may update before ConversationStore context updates.
// Only consume the param when the route agentId matches the ConversationStore agentId.
if (routeAgentId && routeAgentId !== agentId) return;
+ // Likewise wait for the topic the URL names, or the send starts a new one.
+ if (!isOnRouteTopic(routeTopicId, context.topicId)) return;
// Ensure required agent info is loaded before consuming the param.
// For existing conversations (topicId exists), also wait until messages are initialized
@@ -103,6 +107,7 @@ const MessageFromUrl = () => {
isAgentConfigLoading,
messagesInit,
routeAgentId,
+ routeTopicId,
]);
useEffect(() => {
diff --git a/src/routes/(main)/group/features/Conversation/MainChatInput/MessageFromUrl.tsx b/src/routes/(main)/group/features/Conversation/MainChatInput/MessageFromUrl.tsx
index d23e825d964..68e75b64332 100644
--- a/src/routes/(main)/group/features/Conversation/MainChatInput/MessageFromUrl.tsx
+++ b/src/routes/(main)/group/features/Conversation/MainChatInput/MessageFromUrl.tsx
@@ -1,10 +1,11 @@
'use client';
import { useEffect, useRef } from 'react';
-import { useSearchParams } from 'react-router';
+import { useParams, useSearchParams } from 'react-router';
import { useConversationStore } from '@/features/Conversation';
import { useConversationResourceAccess } from '@/features/Conversation/hooks/useConversationResourceAccess';
+import { isOnRouteTopic } from '@/features/Conversation/utils/isOnRouteTopic';
import { usePermission } from '@/hooks/usePermission';
/**
@@ -14,7 +15,12 @@ import { usePermission } from '@/hooks/usePermission';
* Uses ConversationStore for input and send operations.
*/
const MessageFromUrl = () => {
- const [sendMessage, agentId] = useConversationStore((s) => [s.sendMessage, s.context.agentId]);
+ const [sendMessage, agentId, topicId] = useConversationStore((s) => [
+ s.sendMessage,
+ s.context.agentId,
+ s.context.topicId,
+ ]);
+ const { topicId: routeTopicId } = useParams<{ topicId?: string }>();
const [searchParams, setSearchParams] = useSearchParams();
const { allowed: canCreate } = usePermission('create_content');
// Per-resource General access: view-only members must not auto-send into a
@@ -34,6 +40,9 @@ const MessageFromUrl = () => {
// Wait for agentId to be available before sending
if (!agentId) return;
+ // A topic URL's message belongs to that topic; sending before the
+ // conversation has switched to it would start a new topic instead.
+ if (!isOnRouteTopic(routeTopicId, topicId)) return;
if (!canCreate) return;
if (isAccessLoading) return;
@@ -63,6 +72,8 @@ const MessageFromUrl = () => {
canCreate,
canUseResource,
isAccessLoading,
+ routeTopicId,
+ topicId,
]);
return null;