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(project): project home with a coordinator composer (#21345)

Arvin Xudfaa9431d4fd
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index 1eefd903384..47682cd5c06 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -149,12 +149,16 @@
"overview.composerPlaceholder": "Tell the project what to move forward next…",
"overview.contextEnabled": "Project context loaded",
"overview.contextTitle": "Project context",
+ "overview.createTask": "Create task",
+ "overview.createTaskFailed": "Could not create the task",
"overview.description": "Start with a question, or review the project’s progress and outputs.",
"overview.goalCount": "{{completed}} of {{total}} goals completed",
"overview.goalProgress": "Goal progress",
"overview.goalSummary": "Project goals",
"overview.goalsEmpty": "Add a goal to make project progress visible here.",
"overview.latestWorks": "Latest outputs",
+ "overview.mode.chat": "Ask coordinator",
+ "overview.mode.task": "New task",
"overview.needsAttention": "Needs your attention",
"overview.nextActionDescription": "Tell {{name}} what you want to achieve. Its coordinator will use the project context to move it forward.",
"overview.nextActionTitle": "What should we move forward next?",
@@ -167,9 +171,12 @@
"overview.prompts.planMilestone": "Plan the next milestone",
"overview.prompts.summarizeProgress": "Summarize recent progress",
"overview.reviewProject": "Review project completion",
+ "overview.sendFailed": "Could not create the topic",
"overview.sendHint": "⌘ ↵ to send",
"overview.startConversation": "Start moving",
"overview.taskFailed": "This task needs recovery",
+ "overview.taskModeHint": "Added to the project's task list",
+ "overview.taskPlaceholder": "Describe the task to add to this project…",
"overview.taskWaiting": "Waiting for your decision",
"overview.tasksEmpty": "No tasks belong to this project yet.",
"overview.tasksTitle": "Project tasks",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index cb251fe2c65..085041a2a0b 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -149,12 +149,16 @@
"overview.composerPlaceholder": "告诉项目接下来要推进什么…",
"overview.contextEnabled": "已载入项目上下文",
"overview.contextTitle": "项目上下文",
+ "overview.createTask": "创建任务",
+ "overview.createTaskFailed": "创建任务失败",
"overview.description": "从一个问题开始,或查看项目当前的进度与产物。",
"overview.goalCount": "{{total}} 个目标中 {{completed}} 个已完成",
"overview.goalProgress": "目标进度",
"overview.goalSummary": "项目目标",
"overview.goalsEmpty": "添加目标后,可以在这里持续查看项目进度。",
"overview.latestWorks": "最新产物",
+ "overview.mode.chat": "问协调 Agent",
+ "overview.mode.task": "新建任务",
"overview.needsAttention": "需要你处理",
"overview.nextActionDescription": "告诉 {{name}} 你想达成什么,Project Coordinator 会结合项目上下文继续推进。",
"overview.nextActionTitle": "接下来推进什么?",
@@ -167,9 +171,12 @@
"overview.prompts.planMilestone": "规划下一个里程碑",
"overview.prompts.summarizeProgress": "总结最近进展",
"overview.reviewProject": "验收项目完成情况",
+ "overview.sendFailed": "无法新建话题",
"overview.sendHint": "⌘ ↵ 发送",
"overview.startConversation": "开始推进",
"overview.taskFailed": "这个任务需要恢复处理",
+ "overview.taskModeHint": "将加入项目任务列表",
+ "overview.taskPlaceholder": "描述要加入这个项目的任务…",
"overview.taskWaiting": "正在等待你的决定",
"overview.tasksEmpty": "这个项目还没有关联任务。",
"overview.tasksTitle": "项目任务",
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index 1047fa26338..4021bc6e992 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -295,4 +295,11 @@ export default {
'members.updateFailed': 'Could not update the agent',
'settings.knowledgeBases': 'Libraries',
'settings.members': 'Members',
+ 'overview.createTask': 'Create task',
+ 'overview.createTaskFailed': 'Could not create the task',
+ 'overview.mode.chat': 'Ask coordinator',
+ 'overview.mode.task': 'New task',
+ 'overview.sendFailed': 'Could not create the topic',
+ 'overview.taskModeHint': "Added to the project's task list",
+ 'overview.taskPlaceholder': 'Describe the task to add to this project…',
};
diff --git a/src/features/Projects/Conversation/index.tsx b/src/features/Projects/Conversation/index.tsx
index 19440fe33fa..28a85e04273 100644
--- a/src/features/Projects/Conversation/index.tsx
+++ b/src/features/Projects/Conversation/index.tsx
@@ -3,7 +3,7 @@
import { Center, Flexbox, Spin, Text } from '@lobehub/ui';
import { memo, useCallback, useLayoutEffect } from 'react';
import { useTranslation } from 'react-i18next';
-import { useParams } from 'react-router';
+import { Navigate, useParams } from 'react-router';
import AsyncError from '@/components/AsyncError';
import TopicActions from '@/features/AgentSidebar/Topic/List/Item/Actions';
@@ -76,12 +76,8 @@ const ProjectConversation = memo(() => {
return (
<AsyncError error={topicsRequest.error} variant="page" onRetry={topicsRequest.revalidate} />
);
- if (!topicId)
- return (
- <Center height="100%">
- <Text>{t('topics.chooseTopic')}</Text>
- </Center>
- );
+ // New project conversations start from the project home composer.
+ if (!topicId) return <Navigate replace relative="path" to=".." />;
if (topicsRequest.hasData && !selectedTopic)
return (
<Center height="100%">
diff --git a/src/features/Projects/Layout/Sidebar.tsx b/src/features/Projects/Layout/Sidebar.tsx
index 063d6cf35e7..422af635666 100644
--- a/src/features/Projects/Layout/Sidebar.tsx
+++ b/src/features/Projects/Layout/Sidebar.tsx
@@ -3,6 +3,7 @@
import { Flexbox } from '@lobehub/ui';
import {
ClipboardCheckIcon,
+ HouseIcon,
LayoutDashboardIcon,
ListTodoIcon,
SettingsIcon,
@@ -26,8 +27,10 @@ import {
getProjectAcceptancePath,
getProjectDashboardPath,
getProjectGoalsPath,
+ getProjectHomePath,
getProjectTasksPath,
isProjectSectionActive,
+ toProjectPathname,
} from './navigation';
import ProjectHeader from './ProjectHeader';
@@ -35,10 +38,11 @@ const ProjectSidebarContent = memo(() => {
const { t } = useTranslation('project');
const { projectId } = useActiveRouteParams<{ projectId: string }>();
const navigate = useWorkspaceAwareNavigate();
- const { pathname } = useLocation();
+ const pathname = toProjectPathname(useLocation().pathname);
const detail = useCurrentProjectDetail(projectId);
const detailSWR = useProjectStore((s) => s.useFetchProjectDetail)(projectId);
const { enabled: dashboardEnabled } = useDashboardFeature();
+ const projectHomePath = getProjectHomePath(projectId!);
const projectTasksPath = getProjectTasksPath(projectId!);
const projectGoalsPath = getProjectGoalsPath(projectId!);
const projectAcceptancePath = getProjectAcceptancePath(projectId!);
@@ -61,6 +65,12 @@ const ProjectSidebarContent = memo(() => {
header={header}
body={
<Flexbox gap={1} paddingInline={4}>
+ <NavItem
+ active={pathname === projectHomePath}
+ icon={HouseIcon}
+ title={t('sections.home')}
+ onClick={() => navigate(projectHomePath)}
+ />
<NavItem
active={pathname === projectTasksPath}
icon={ListTodoIcon}
diff --git a/src/features/Projects/Layout/navigation.test.ts b/src/features/Projects/Layout/navigation.test.ts
index 6e0a26cc95f..c8e1b2eefdc 100644
--- a/src/features/Projects/Layout/navigation.test.ts
+++ b/src/features/Projects/Layout/navigation.test.ts
@@ -7,18 +7,23 @@ import {
getProjectConversationStartPath,
getProjectDashboardPath,
getProjectGoalsPath,
+ getProjectHomePath,
getProjectLibraryPath,
+ getProjectSettingsPath,
getProjectTasksPath,
isProjectSectionActive,
+ toProjectPathname,
} from './navigation';
describe('project workspace navigation', () => {
it('builds routes for project agents and libraries', () => {
expect(getProjectAgentPath('agt_1')).toBe('/agent/agt_1');
expect(getProjectLibraryPath('prj_1', 'kb_1')).toBe('/project/prj_1/library/kb_1');
+ expect(getProjectHomePath('prj_1')).toBe('/project/prj_1');
expect(getProjectTasksPath('prj_1')).toBe('/project/prj_1/tasks');
expect(getProjectGoalsPath('prj_1')).toBe('/project/prj_1/goals');
expect(getProjectAcceptancePath('prj_1')).toBe('/project/prj_1/acceptance');
+ expect(getProjectSettingsPath('prj_1', 'members')).toBe('/project/prj_1/settings/members');
});
it('builds the project dashboard list and board routes', () => {
@@ -29,8 +34,8 @@ 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', 'Plan Q3 & ship')).toBe(
- '/project/prj_1/conversation?message=Plan%20Q3%20%26%20ship',
+ expect(getProjectConversationStartPath('prj_1', 'tpc_1', 'Plan Q3 & ship')).toBe(
+ '/project/prj_1/conversation/tpc_1?message=Plan%20Q3%20%26%20ship',
);
});
});
@@ -51,3 +56,11 @@ describe('isProjectSectionActive', () => {
).toBe(false);
});
});
+
+describe('toProjectPathname', () => {
+ it('drops the workspace slug so section paths compare equal', () => {
+ expect(toProjectPathname('/acme/project/prj_1')).toBe('/project/prj_1');
+ expect(toProjectPathname('/acme/project/prj_1/tasks')).toBe('/project/prj_1/tasks');
+ expect(toProjectPathname('/project/prj_1/goals')).toBe('/project/prj_1/goals');
+ });
+});
diff --git a/src/features/Projects/Layout/navigation.ts b/src/features/Projects/Layout/navigation.ts
index 47769001267..bcdb6defb69 100644
--- a/src/features/Projects/Layout/navigation.ts
+++ b/src/features/Projects/Layout/navigation.ts
@@ -1,10 +1,16 @@
export const getProjectAgentPath = (agentId: string) => `/agent/${agentId}`;
+export const getProjectHomePath = (projectId: string) => `/project/${projectId}`;
+
export const getProjectConversationPath = (projectId: string, topicId?: string) =>
topicId ? `/project/${projectId}/conversation/${topicId}` : `/project/${projectId}/conversation`;
-export const getProjectConversationStartPath = (projectId: string, message: string) =>
- `${getProjectConversationPath(projectId)}?message=${encodeURIComponent(message)}`;
+/** 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}`;
@@ -25,6 +31,15 @@ export const getProjectSettingsPath = (projectId: string, section: ProjectSettin
export const getProjectAcceptancePath = (projectId: string) => `/project/${projectId}/acceptance`;
+/**
+ * A workspace-scoped location carries the workspace slug (`/acme/project/…`)
+ * while section paths are built without it. Drop the prefix before comparing.
+ */
+export const toProjectPathname = (pathname: string) => {
+ const index = pathname.indexOf('/project/');
+ return index > 0 ? pathname.slice(index) : pathname;
+};
+
/** A section stays active on its own pages too — a board, an acceptance record. */
export const isProjectSectionActive = (pathname: string, sectionPath: string) =>
pathname === sectionPath || pathname.startsWith(`${sectionPath}/`);
diff --git a/src/features/Projects/Workspace/index.tsx b/src/features/Projects/Workspace/index.tsx
index 04bd47c8f4b..1529603dc43 100644
--- a/src/features/Projects/Workspace/index.tsx
+++ b/src/features/Projects/Workspace/index.tsx
@@ -2,14 +2,14 @@
import {
Button,
- Center,
createStaticStyles,
cssVar,
Flexbox,
- Spin,
+ Segmented,
Tag,
Text,
TextArea,
+ toast,
} from '@lobehub/ui';
import { SendHorizontalIcon, SparklesIcon } from 'lucide-react';
import { memo, useState } from 'react';
@@ -17,14 +17,15 @@ import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router';
import AsyncError from '@/components/AsyncError';
-import { getProjectConversationStartPath } from '@/features/Projects/Layout/navigation';
+import { RouteLoading } from '@/components/Skeleton/RouteSegment';
import ProjectDisabled from '@/features/Projects/ProjectDisabled';
-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import type { ProjectDetail } from '@/store/project';
import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
import { useUserStore } from '@/store/user';
import { labPreferSelectors } from '@/store/user/selectors';
import ProjectDashboard from './ProjectDashboard';
+import { type ProjectComposerMode, useProjectComposer } from './useProjectComposer';
const styles = createStaticStyles(({ css }) => ({
composer: css`
@@ -71,7 +72,12 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorFillQuaternary};
- &:hover {
+ &:disabled {
+ cursor: not-allowed;
+ opacity: 0.5;
+ }
+
+ &:hover:not(:disabled) {
color: ${cssVar.colorText};
background: ${cssVar.colorFillTertiary};
}
@@ -93,35 +99,101 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
+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'));
+ }
+ };
+ const prompts = [
+ t('overview.prompts.summarizeProgress'),
+ t('overview.prompts.planMilestone'),
+ t('overview.prompts.findBlockers'),
+ ];
+
+ return (
+ <Flexbox gap={10}>
+ <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'}
+ >
+ <Flexbox horizontal align={'center'} gap={8}>
+ <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)}
+ />
+ <Tag icon={<SparklesIcon size={12} />}>{project.name}</Tag>
+ <Text fontSize={12} type={'secondary'}>
+ {t(mode === 'task' ? 'overview.taskModeHint' : 'overview.contextEnabled')}
+ </Text>
+ </Flexbox>
+ <Button
+ aria-label={t(mode === 'task' ? 'overview.createTask' : 'overview.startConversation')}
+ disabled={!message.trim()}
+ icon={SendHorizontalIcon}
+ loading={sending}
+ type={'primary'}
+ onClick={submit}
+ />
+ </Flexbox>
+ </Flexbox>
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ {prompts.map((prompt) => (
+ <button
+ className={styles.prompt}
+ disabled={sending}
+ key={prompt}
+ type={'button'}
+ onClick={() => setMessage(prompt)}
+ >
+ {prompt}
+ </button>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ );
+};
+
const ProjectWorkspace = memo(() => {
const { t } = useTranslation('project');
const { projectId } = useParams<{ projectId: string }>();
- const navigate = useWorkspaceAwareNavigate();
const enabled = useUserStore(labPreferSelectors.enableProjects);
const detail = useCurrentProjectDetail(projectId);
- const [message, setMessage] = useState('');
const { error, revalidate } = useProjectStore((s) => s.useFetchProjectDetail)(projectId);
if (!enabled) return <ProjectDisabled />;
if (error && !detail)
return <AsyncError error={error} variant={'page'} onRetry={() => revalidate()} />;
- if (!detail)
- return (
- <Center height={'100%'}>
- <Spin size="small" />
- </Center>
- );
-
- const startConversation = () => {
- const content = message.trim();
- if (!content || !projectId) return;
- navigate(getProjectConversationStartPath(detail.project.slug ?? projectId, content));
- };
- const prompts = [
- t('overview.prompts.summarizeProgress'),
- t('overview.prompts.planMilestone'),
- t('overview.prompts.findBlockers'),
- ];
+ if (!detail) return <RouteLoading />;
return (
<Flexbox className={styles.shell} flex={1}>
@@ -134,53 +206,7 @@ const ProjectWorkspace = memo(() => {
</Text>
<Text type={'secondary'}>{t('overview.description')}</Text>
</Flexbox>
- <Flexbox gap={10}>
- <Flexbox className={styles.composer}>
- <TextArea
- autoFocus
- autoSize={{ maxRows: 7, minRows: 3 }}
- className={styles.textarea}
- placeholder={t('overview.composerPlaceholder')}
- value={message}
- onChange={(event) => setMessage(event.target.value)}
- onKeyDown={(event) => {
- if ((event.metaKey || event.ctrlKey) && event.key === 'Enter')
- startConversation();
- }}
- />
- <Flexbox
- horizontal
- align={'center'}
- className={styles.composerFooter}
- justify={'space-between'}
- >
- <Flexbox horizontal align={'center'} gap={7}>
- <Tag icon={<SparklesIcon size={12} />}>{detail.project.name}</Tag>
- <Text fontSize={12} type={'secondary'}>
- {t('overview.contextEnabled')}
- </Text>
- </Flexbox>
- <Button
- disabled={!message.trim()}
- icon={SendHorizontalIcon}
- type={'primary'}
- onClick={startConversation}
- />
- </Flexbox>
- </Flexbox>
- <Flexbox horizontal gap={8} wrap={'wrap'}>
- {prompts.map((prompt) => (
- <button
- className={styles.prompt}
- key={prompt}
- type={'button'}
- onClick={() => setMessage(prompt)}
- >
- {prompt}
- </button>
- ))}
- </Flexbox>
- </Flexbox>
+ <ProjectComposer key={detail.project.id} project={detail.project} />
</Flexbox>
<ProjectDashboard detail={detail} projectId={detail.project.id} />
</Flexbox>
diff --git a/src/features/Projects/Workspace/useProjectComposer.test.ts b/src/features/Projects/Workspace/useProjectComposer.test.ts
new file mode 100644
index 00000000000..3d7368153df
--- /dev/null
+++ b/src/features/Projects/Workspace/useProjectComposer.test.ts
@@ -0,0 +1,126 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ProjectDetail } from '@/store/project';
+
+import { toConversationTitle, useProjectComposer } from './useProjectComposer';
+
+const mocks = vi.hoisted(() => ({
+ createProjectTopic: vi.fn(),
+ createTask: vi.fn(),
+ navigate: vi.fn(),
+}));
+
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => mocks.navigate,
+}));
+
+vi.mock('@/store/projectWorkingDirectory', () => ({
+ useProjectDirectoryStore: (selector: (state: unknown) => unknown) =>
+ selector({ createProjectTopic: mocks.createProjectTopic }),
+}));
+
+vi.mock('@/store/task', () => ({
+ useTaskStore: (selector: (state: unknown) => unknown) =>
+ selector({ createTask: mocks.createTask }),
+}));
+
+const project = {
+ coordinatorAgentId: 'coordinator',
+ id: 'prj_1',
+ slug: 'apollo',
+} as ProjectDetail['project'];
+
+describe('useProjectComposer', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('opens a coordinator conversation owned by the project and sends the message in it', async () => {
+ mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
+ const { result } = renderHook(() => useProjectComposer(project));
+
+ act(() => result.current.setDraft(' Plan the next milestone\nwith details '));
+ let sent = false;
+ await act(async () => {
+ sent = await result.current.send('chat');
+ });
+
+ 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.createTask).not.toHaveBeenCalled();
+ });
+
+ it('records a project task assigned to the coordinator in task mode', async () => {
+ mocks.createTask.mockResolvedValue({ id: 'task_1', name: 'Ship it' });
+ const { result } = renderHook(() => useProjectComposer(project));
+
+ act(() => result.current.setDraft('Ship it'));
+ await act(async () => {
+ await result.current.send('task');
+ });
+
+ expect(mocks.createTask).toHaveBeenCalledWith({
+ assigneeAgentId: 'coordinator',
+ instruction: 'Ship it',
+ projectId: 'prj_1',
+ });
+ expect(mocks.navigate).toHaveBeenCalledWith('/task/task_1/ship-it');
+ expect(mocks.createProjectTopic).not.toHaveBeenCalled();
+ });
+
+ it('ignores a blank message and keeps a failed send in the composer', async () => {
+ mocks.createProjectTopic.mockRejectedValue(new Error('denied'));
+ const { result } = renderHook(() => useProjectComposer(project));
+
+ act(() => result.current.setDraft(' '));
+ await act(async () => {
+ expect(await result.current.send('chat')).toBe(false);
+ });
+ act(() => result.current.setDraft('Hello'));
+ await act(async () => {
+ await expect(result.current.send('chat')).rejects.toThrow('denied');
+ });
+
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ expect(result.current.draft).toBe('Hello');
+ 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));
+
+ 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;
+ });
+
+ expect(result.current.draft).toBe('Find the current blockers');
+ });
+
+ it('titles a conversation by its first line', () => {
+ expect(toConversationTitle('a'.repeat(60))).toBe(`${'a'.repeat(50)}…`);
+ expect(toConversationTitle('\n Short \nrest')).toBe('Short');
+ });
+});
diff --git a/src/features/Projects/Workspace/useProjectComposer.ts b/src/features/Projects/Workspace/useProjectComposer.ts
new file mode 100644
index 00000000000..27753f7ab46
--- /dev/null
+++ b/src/features/Projects/Workspace/useProjectComposer.ts
@@ -0,0 +1,71 @@
+import { useState } from 'react';
+
+import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
+import { getProjectConversationStartPath } from '@/features/Projects/Layout/navigation';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+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.
+ */
+export type ProjectComposerMode = 'chat' | 'task';
+
+const TITLE_LENGTH = 50;
+
+/** A conversation is titled by its first line until the agent renames it. */
+export const toConversationTitle = (message: string) => {
+ const firstLine = message.trim().split('\n')[0].trim();
+ return firstLine.length > TITLE_LENGTH ? `${firstLine.slice(0, TITLE_LENGTH)}…` : firstLine;
+};
+
+export const useProjectComposer = (project: ProjectDetail['project']) => {
+ const navigate = useWorkspaceAwareNavigate();
+ const createProjectTopic = useProjectDirectoryStore((s) => s.createProjectTopic);
+ const createTask = useTaskStore((s) => s.createTask);
+ const [draft, setDraft] = useState('');
+ 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;
+
+ // 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));
+
+ setSending(true);
+ try {
+ if (mode === 'task') {
+ const task = await createTask({
+ assigneeAgentId: project.coordinatorAgentId,
+ instruction: message,
+ projectId: project.id,
+ });
+ clearSubmitted();
+ if (task) navigate(taskDetailPath(task.id, undefined, task.name));
+ return true;
+ }
+
+ // 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),
+ });
+ clearSubmitted();
+ navigate(getProjectConversationStartPath(project.slug ?? project.id, topic.id, message));
+ return true;
+ } finally {
+ setSending(false);
+ }
+ };
+
+ return { draft, send, sending, setDraft };
+};
diff --git a/src/features/Projects/routeMeta.ts b/src/features/Projects/routeMeta.ts
index d86b7504c43..8ff3540d615 100644
--- a/src/features/Projects/routeMeta.ts
+++ b/src/features/Projects/routeMeta.ts
@@ -23,6 +23,12 @@ export const projectDirectoriesRouteMeta = routeMeta({
titleKey: 'project:settings.title',
});
+export const projectHomeRouteMeta = routeMeta({
+ icon: FolderClosedIcon,
+ Skeleton: createSurfaceSkeleton('detail'),
+ titleKey: 'project:sections.home',
+});
+
export const projectConversationRouteMeta = routeMeta({
DynamicMeta: ProjectConversationDynamicMeta,
icon: FolderClosedIcon,
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index 808552f7fb1..645b557a6b4 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -46,11 +46,7 @@ import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';
import { agentsRouteMeta } from '@/features/AgentViewAll/routeMeta';
import { dashboardRouteMeta, dashboardsRouteMeta } from '@/features/Dashboard/routeMeta';
import { pageRouteMeta } from '@/features/Pages/routeMeta';
-import {
- projectConversationRouteMeta,
- projectDirectoriesRouteMeta,
- projectsRouteMeta,
-} from '@/features/Projects/routeMeta';
+import { projectsRouteMeta } from '@/features/Projects/routeMeta';
import ResourceCategorySkeleton from '@/features/ResourceHome/Skeleton';
import { createSettingsRouteMeta, settingsRouteMeta } from '@/features/Settings/features/routeMeta';
import { workspaceHomeRouteMeta } from '@/features/Workspace/routeMeta';
@@ -82,7 +78,7 @@ import { identitiesListLoader } from '@/spa/router/identitiesListLoader';
import { libraryTreeLoader } from '@/spa/router/libraryTreeLoader';
import { pageListLoader } from '@/spa/router/pageListLoader';
import { preferenceListLoader } from '@/spa/router/preferenceListLoader';
-import { projectAcceptanceRoute } from '@/spa/router/projectAcceptanceRoutes';
+import { projectWorkspaceRoute } from '@/spa/router/projectWorkspaceRoutes';
import { agentAccessLoader, agentGroupAccessLoader } from '@/spa/router/resourceAccessLoader';
import { NoRouteSkeleton, routeMeta } from '@/spa/router/routeMeta';
import { scheduledTaskListLoader } from '@/spa/router/scheduledTaskListLoader';
@@ -1062,87 +1058,8 @@ export const sharedMainAreaChildren: RouteObject[] = [
path: 'dashboard',
},
- // Task workspace routes (cross-agent)
- {
- children: [
- {
- element: redirectElement('conversation'),
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/project/[projectId]/conversation'),
- 'Desktop > Project Conversation',
- { preloadId: 'project-conversation' },
- ),
- handle: { meta: projectConversationRouteMeta },
- path: 'conversation/:topicId?',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/project/[projectId]/tasks'),
- 'Desktop > Project Tasks',
- ),
- handle: { meta: tasksRouteMeta },
- loader: scheduledTaskListLoader,
- path: 'tasks',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/project/[projectId]/settings'),
- 'Desktop > Project Working Directories',
- { preloadId: 'project-settings' },
- ),
- handle: { meta: projectDirectoriesRouteMeta },
- path: 'settings/:section?',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/project/[projectId]/goals'),
- 'Desktop > Project Goals',
- ),
- handle: { meta: goalsRouteMeta },
- path: 'goals',
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/project/[projectId]/dashboard'),
- 'Desktop > Project Dashboards',
- { preloadId: 'dashboard' },
- ),
- handle: { meta: dashboardsRouteMeta },
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/project/[projectId]/dashboard/[dashboardId]'),
- 'Desktop > Project Dashboard Detail',
- { preloadId: 'dashboard' },
- ),
- handle: { meta: dashboardRouteMeta },
- path: ':dashboardId',
- },
- ],
- // Off unless the `dashboard` feature flag is on: the gate leaves for the project.
- element: dynamicLayout(
- () => import('@/routes/(main)/project/[projectId]/dashboard/_layout'),
- 'Desktop > Project Dashboards > Layout',
- { preloadId: 'dashboard' },
- ),
- path: 'dashboard',
- },
- projectAcceptanceRoute,
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/project/_layout'),
- 'Desktop > Project Workspace > Layout',
- { preloadId: 'project' },
- ),
- errorElement: <ErrorBoundary resetPath=".." />,
- path: 'project/:projectId',
- },
+ // Project workspace routes
+ projectWorkspaceRoute,
{
children: taskWorkspaceChildren,
diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index b4070e97359..a4c18196483 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -79,6 +79,7 @@ async function readRouterSources() {
'desktopRouter.shared.tsx',
'desktopRouter.config.tsx',
'desktopRouter.config.desktop.tsx',
+ 'projectWorkspaceRoutes.tsx',
'taskWorkspaceRoutes.tsx',
'workspaceSettingsRoutes.tsx',
].map((filename) => readFile(path.join(process.cwd(), 'src/spa/router', filename), 'utf8')),
@@ -213,16 +214,18 @@ describe('desktop router shared definition', () => {
'dashboard',
'acceptance',
]);
- for (const section of ['general', 'environments', 'directories']) {
+ for (const section of ['general', 'members', 'knowledge', 'environments', 'directories']) {
const matches = matchRoutes(
createMainAreaRoutes(factory),
`/project/project-1/settings/${section}`,
);
expect(matches?.at(-1)?.params.section).toBe(section);
}
+ // The project root is its home page (composer + overview), not a redirect.
expect(
- (projectIndexRoute?.element as ReactElement<{ to: string }> | undefined)?.props.to,
- ).toBe('conversation');
+ (projectIndexRoute?.element as ReactElement<{ to?: string }> | undefined)?.props.to,
+ ).toBeUndefined();
+ expect(projectIndexRoute?.handle?.meta?.titleKey).toBe('project:sections.home');
},
);
diff --git a/src/spa/router/projectWorkspaceRoutes.tsx b/src/spa/router/projectWorkspaceRoutes.tsx
new file mode 100644
index 00000000000..b295eb0b7b0
--- /dev/null
+++ b/src/spa/router/projectWorkspaceRoutes.tsx
@@ -0,0 +1,104 @@
+import type { RouteObject } from 'react-router';
+
+import { goalsRouteMeta } from '@/features/AgentGoals/routeMeta';
+import { tasksRouteMeta } from '@/features/AgentTasks/routeMeta';
+import { dashboardRouteMeta, dashboardsRouteMeta } from '@/features/Dashboard/routeMeta';
+import {
+ projectConversationRouteMeta,
+ projectDirectoriesRouteMeta,
+ projectHomeRouteMeta,
+} from '@/features/Projects/routeMeta';
+import { projectAcceptanceRoute } from '@/spa/router/projectAcceptanceRoutes';
+import { scheduledTaskListLoader } from '@/spa/router/scheduledTaskListLoader';
+import { dynamicElement, dynamicLayout, ErrorBoundary } from '@/utils/router';
+
+/**
+ * One project's workspace under `/project/:projectId`: its home, topics, tasks,
+ * settings, goals, dashboards and acceptance. Mounted under the workspace
+ * layout in `desktopRouter.shared.tsx`.
+ */
+export const projectWorkspaceRoute: RouteObject = {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/project/[projectId]'),
+ 'Desktop > Project Home',
+ { preloadId: 'project-home' },
+ ),
+ handle: { meta: projectHomeRouteMeta },
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/project/[projectId]/conversation'),
+ 'Desktop > Project Conversation',
+ { preloadId: 'project-conversation' },
+ ),
+ handle: { meta: projectConversationRouteMeta },
+ path: 'conversation/:topicId?',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/project/[projectId]/tasks'),
+ 'Desktop > Project Tasks',
+ ),
+ handle: { meta: tasksRouteMeta },
+ loader: scheduledTaskListLoader,
+ path: 'tasks',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/project/[projectId]/settings'),
+ 'Desktop > Project Working Directories',
+ { preloadId: 'project-settings' },
+ ),
+ handle: { meta: projectDirectoriesRouteMeta },
+ path: 'settings/:section?',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/project/[projectId]/goals'),
+ 'Desktop > Project Goals',
+ ),
+ handle: { meta: goalsRouteMeta },
+ path: 'goals',
+ },
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/project/[projectId]/dashboard'),
+ 'Desktop > Project Dashboards',
+ { preloadId: 'dashboard' },
+ ),
+ handle: { meta: dashboardsRouteMeta },
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/project/[projectId]/dashboard/[dashboardId]'),
+ 'Desktop > Project Dashboard Detail',
+ { preloadId: 'dashboard' },
+ ),
+ handle: { meta: dashboardRouteMeta },
+ path: ':dashboardId',
+ },
+ ],
+ // Off unless the `dashboard` feature flag is on: the gate leaves for the project.
+ element: dynamicLayout(
+ () => import('@/routes/(main)/project/[projectId]/dashboard/_layout'),
+ 'Desktop > Project Dashboards > Layout',
+ { preloadId: 'dashboard' },
+ ),
+ path: 'dashboard',
+ },
+ projectAcceptanceRoute,
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/project/_layout'),
+ 'Desktop > Project Workspace > Layout',
+ { preloadId: 'project' },
+ ),
+ errorElement: <ErrorBoundary resetPath=".." />,
+ path: 'project/:projectId',
+};