🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(project): group channels inside projects and fold project sidebar sections (#21752)
Arvin Xu1f4ac0289291
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.tsindex 147eca38181..9d591a5a507 100644--- a/apps/server/src/routers/lambda/channel.ts+++ b/apps/server/src/routers/lambda/channel.ts@@ -94,6 +94,7 @@ export const channelRouter = router({.input(z.object({agents: z.array(agentSelection).min(1).max(20),+ projectId: z.string().min(1).optional(),title: z.string().trim().min(1).max(CHANNEL_LIMITS.titleLength),}),)diff --git a/apps/server/src/services/channel/ChannelService.project.test.ts b/apps/server/src/services/channel/ChannelService.project.test.tsnew file mode 100644index 00000000000..6d57ecea31e--- /dev/null+++ b/apps/server/src/services/channel/ChannelService.project.test.ts@@ -0,0 +1,65 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ChannelService } from './ChannelService';++const { create, findProject, getAgent } = vi.hoisted(() => ({+ create: vi.fn(),+ findProject: vi.fn(),+ getAgent: vi.fn(),+}));+vi.mock('@/database/repositories/channel', async (original) => ({+ ...(await original<object>()),+ ChannelRepository: class {+ create = create;+ },+}));+vi.mock('@/database/models/project', () => ({+ ProjectModel: class {+ findById = findProject;+ },+}));+vi.mock('@/database/models/device', () => ({ DeviceModel: class {} }));+vi.mock('@/server/services/agent', () => ({+ AgentService: class {+ getAgentConfigById = getAgent;+ },+}));+vi.mock('@/server/services/file', () => ({ FileService: class {} }));+vi.mock('./ChannelCoordinator', () => ({ ChannelCoordinator: class {} }));+vi.mock('./notify', () => ({ notifyChannel: vi.fn() }));+vi.mock('./queue', () => ({ wakeChannel: vi.fn() }));++describe('creating a Channel inside a project', () => {+ beforeEach(() => {+ vi.resetAllMocks();+ create.mockResolvedValue({ channel: { id: 'chn_1' } });+ getAgent.mockResolvedValue({ model: 'gpt-5' });+ });+ const service = () => new ChannelService({} as never, 'owner', 'workspace');+ const agents = [{ agentId: 'agt_1' }];++ it('groups the Channel under a project the caller can read', async () => {+ findProject.mockResolvedValue({ id: 'pro_1' });+ await service().create({ agents, projectId: 'pro_1', title: 'Launch' });+ expect(findProject).toHaveBeenCalledWith('pro_1');+ expect(create).toHaveBeenCalledWith(+ expect.objectContaining({ projectId: 'pro_1', title: 'Launch' }),+ );+ });++ it('rejects a project outside the caller’s scope before creating anything', async () => {+ findProject.mockResolvedValue(undefined);+ await expect(+ service().create({ agents, projectId: 'pro_other', title: 'Launch' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(getAgent).not.toHaveBeenCalled();+ expect(create).not.toHaveBeenCalled();+ });++ it('keeps a Channel without a project standalone', async () => {+ await service().create({ agents, title: 'Launch' });+ expect(findProject).not.toHaveBeenCalled();+ expect(create).toHaveBeenCalledWith(expect.objectContaining({ projectId: undefined }));+ });+});diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.tsindex 98aab21f63e..e2c55709d7e 100644--- a/apps/server/src/services/channel/ChannelService.ts+++ b/apps/server/src/services/channel/ChannelService.ts@@ -4,6 +4,7 @@ import { isChannelRuntime } from '@lobechat/types';import pMap from 'p-map';import { DeviceModel } from '@/database/models/device';+import { ProjectModel } from '@/database/models/project';import type {ChannelAddAgentInput,ChannelSendInput,@@ -32,6 +33,7 @@ export class ChannelService {readonly repository: ChannelRepository;private readonly agentService: AgentService;private readonly deviceModel: DeviceModel;+ private readonly projectModel: ProjectModel;constructor(private readonly db: LobeChatDatabase,@@ -41,6 +43,7 @@ export class ChannelService {this.repository = new ChannelRepository(db, userId, workspaceId);this.agentService = new AgentService(db, userId, workspaceId);this.deviceModel = new DeviceModel(db, userId, workspaceId);+ this.projectModel = new ProjectModel(db, userId, workspaceId);}private async resolveAgent(input: ChannelAgentSelection): Promise<ChannelAddAgentInput> {@@ -89,12 +92,19 @@ export class ChannelService {return { agentId: input.agentId, config, description: input.description, name: input.name };}- create = async (input: { agents: ChannelAgentSelection[]; title: string }) => {+ create = async (input: {+ agents: ChannelAgentSelection[];+ projectId?: string;+ title: string;+ }) => {+ // The project must be readable in this scope, the same visibility as the project list.+ if (input.projectId && !(await this.projectModel.findById(input.projectId)))+ throw new ChannelError('NOT_FOUND', 'Project not found');// Resolving probes devices, so cap the work one request can start.const agents = await pMap(input.agents, (agent) => this.resolveAgent(agent), {concurrency: 5,});- return this.repository.create({ agents, title: input.title });+ return this.repository.create({ agents, projectId: input.projectId, title: input.title });};addAgent = async (channelId: string, input: ChannelAgentSelection) => {diff --git a/locales/ar/project.json b/locales/ar/project.jsonindex e49dd8e51dc..ef5c60411c0 100644--- a/locales/ar/project.json+++ b/locales/ar/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "اختر دليل عمل","topics.chooseTopic": "اختر موضوعًا في الشريط الجانبي، أو أنشئ واحدًا لبدء العمل","topics.complete": "وضع علامة مكتمل",- "topics.conversationOnly": "المحادثة فقط، بدون دليل عمل","topics.executionContext": "موقع العمل","topics.gatewayUnavailable": "قم بتمكين بوابة الوكيل قبل استخدام موقع العمل لهذا المشروع.","topics.group.agent": "حسب الوكيل",diff --git a/locales/bg-BG/project.json b/locales/bg-BG/project.jsonindex a8f2f6c0329..d0735aae638 100644--- a/locales/bg-BG/project.json+++ b/locales/bg-BG/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "Изберете работна директория","topics.chooseTopic": "Изберете тема в страничната лента или създайте нова, за да започнете работа","topics.complete": "Отбележи като завършено",- "topics.conversationOnly": "Само разговор, без работна директория","topics.executionContext": "Местоположение на работа","topics.gatewayUnavailable": "Активирайте Agent Gateway, преди да използвате това местоположение за работа по проекта.","topics.group.agent": "По агент",diff --git a/locales/de-DE/project.json b/locales/de-DE/project.jsonindex 90602201dd9..88a3877b89f 100644--- a/locales/de-DE/project.json+++ b/locales/de-DE/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "Ein Arbeitsverzeichnis auswählen","topics.chooseTopic": "Wählen Sie ein Thema in der Seitenleiste aus oder erstellen Sie eines, um mit der Arbeit zu beginnen","topics.complete": "Als abgeschlossen markieren",- "topics.conversationOnly": "Nur Gespräch, ohne Arbeitsverzeichnis","topics.executionContext": "Arbeitsort","topics.gatewayUnavailable": "Aktivieren Sie das Agent Gateway, bevor Sie diesen Projektarbeitsort verwenden.","topics.group.agent": "Nach Agent",diff --git a/locales/en-US/project.json b/locales/en-US/project.jsonindex 19547c76c82..ed301b61ab8 100644--- a/locales/en-US/project.json+++ b/locales/en-US/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "Choose a working directory","topics.chooseTopic": "Choose a topic in the sidebar, or create one to start working","topics.complete": "Mark completed",- "topics.conversationOnly": "Conversation only, without a working directory","topics.executionContext": "Work location","topics.gatewayUnavailable": "Enable Agent Gateway before using this project work location.","topics.group.agent": "By agent",diff --git a/locales/es-ES/project.json b/locales/es-ES/project.jsonindex f1b91f8e129..d74f54b163b 100644--- a/locales/es-ES/project.json+++ b/locales/es-ES/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "Elegir un directorio de trabajo","topics.chooseTopic": "Elige un tema en la barra lateral o crea uno para comenzar a trabajar","topics.complete": "Marcar como completado",- "topics.conversationOnly": "Solo conversación, sin un directorio de trabajo","topics.executionContext": "Ubicación de trabajo","topics.gatewayUnavailable": "Habilita el Gateway del Agente antes de usar esta ubicación de trabajo del proyecto.","topics.group.agent": "Por agente",diff --git a/locales/fa-IR/project.json b/locales/fa-IR/project.jsonindex 7f245b709a4..a73acb1de74 100644--- a/locales/fa-IR/project.json+++ b/locales/fa-IR/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "انتخاب یک دایرکتوری کاری","topics.chooseTopic": "یک موضوع را در نوار کناری انتخاب کنید، یا یکی ایجاد کنید تا کار را شروع کنید","topics.complete": "علامتگذاری بهعنوان تکمیلشده",- "topics.conversationOnly": "فقط مکالمه، بدون دایرکتوری کاری","topics.executionContext": "محل کار","topics.gatewayUnavailable": "ایجنت Gateway را قبل از استفاده از این محل کار پروژه فعال کنید.","topics.group.agent": "بر اساس ایجنت",diff --git a/locales/fr-FR/project.json b/locales/fr-FR/project.jsonindex 1005840fae4..a231f594896 100644--- a/locales/fr-FR/project.json+++ b/locales/fr-FR/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "Choisir un répertoire de travail","topics.chooseTopic": "Choisissez un sujet dans la barre latérale ou créez-en un pour commencer à travailler","topics.complete": "Marquer comme terminé",- "topics.conversationOnly": "Conversation uniquement, sans répertoire de travail","topics.executionContext": "Lieu de travail","topics.gatewayUnavailable": "Activez la passerelle Agent avant d'utiliser ce lieu de travail du projet.","topics.group.agent": "Par agent",diff --git a/locales/it-IT/project.json b/locales/it-IT/project.jsonindex 1bf6e26707d..2d76289c016 100644--- a/locales/it-IT/project.json+++ b/locales/it-IT/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "Scegli una directory di lavoro","topics.chooseTopic": "Scegli un argomento nella barra laterale o creane uno per iniziare a lavorare","topics.complete": "Segna come completato",- "topics.conversationOnly": "Solo conversazione, senza una directory di lavoro","topics.executionContext": "Luogo di lavoro","topics.gatewayUnavailable": "Abilita Agent Gateway prima di utilizzare questa posizione di lavoro del progetto.","topics.group.agent": "Per ajan",diff --git a/locales/ja-JP/project.json b/locales/ja-JP/project.jsonindex 4d8d600e24d..bb472dcf8bc 100644--- a/locales/ja-JP/project.json+++ b/locales/ja-JP/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "作業ディレクトリを選択","topics.chooseTopic": "サイドバーでトピックを選択するか、新しいトピックを作成して作業を開始してください","topics.complete": "完了としてマーク",- "topics.conversationOnly": "作業ディレクトリなしの会話のみ","topics.executionContext": "作業場所","topics.gatewayUnavailable": "このプロジェクトの作業場所を使用する前にエージェントゲートウェイを有効にしてください。","topics.group.agent": "エージェント別",diff --git a/locales/ko-KR/project.json b/locales/ko-KR/project.jsonindex 746c9ac0480..0a82056f7f0 100644--- a/locales/ko-KR/project.json+++ b/locales/ko-KR/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "작업 디렉토리 선택","topics.chooseTopic": "사이드바에서 주제를 선택하거나 새로 만들어 작업을 시작하세요.","topics.complete": "완료로 표시",- "topics.conversationOnly": "작업 디렉토리 없이 대화만","topics.executionContext": "작업 위치","topics.gatewayUnavailable": "이 프로젝트 작업 위치를 사용하려면 에이전트 게이트웨이를 활성화하세요.","topics.group.agent": "에이전트별",diff --git a/locales/nl-NL/project.json b/locales/nl-NL/project.jsonindex 208e1ddedbb..18170e56ee4 100644--- a/locales/nl-NL/project.json+++ b/locales/nl-NL/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "Kies een werkmap","topics.chooseTopic": "Kies een onderwerp in de zijbalk, of maak er een aan om te beginnen met werken","topics.complete": "Markeer als voltooid",- "topics.conversationOnly": "Alleen gesprek, zonder werkmap","topics.executionContext": "Werklocatie","topics.gatewayUnavailable": "Schakel Agent Gateway in voordat je deze projectwerkplek gebruikt.","topics.group.agent": "Per Agent",diff --git a/locales/pl-PL/project.json b/locales/pl-PL/project.jsonindex ae851300cf0..b8d44850877 100644--- a/locales/pl-PL/project.json+++ b/locales/pl-PL/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "Wybierz katalog roboczy","topics.chooseTopic": "Wybierz temat w pasku bocznym lub utwórz nowy, aby rozpocząć pracę","topics.complete": "Oznacz jako ukończone",- "topics.conversationOnly": "Tylko rozmowa, bez katalogu roboczego","topics.executionContext": "Miejsce pracy","topics.gatewayUnavailable": "Włącz Agent Gateway przed użyciem tego miejsca pracy w projekcie.","topics.group.agent": "Według agenta",diff --git a/locales/pt-BR/project.json b/locales/pt-BR/project.jsonindex 1c68bb4d85a..29b055ff4af 100644--- a/locales/pt-BR/project.json+++ b/locales/pt-BR/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "Escolher um diretório de trabalho","topics.chooseTopic": "Escolha um tópico na barra lateral ou crie um para começar a trabalhar","topics.complete": "Marcar como concluído",- "topics.conversationOnly": "Apenas conversa, sem um diretório de trabalho","topics.executionContext": "Local de trabalho","topics.gatewayUnavailable": "Habilite o Gateway do Agente antes de usar este local de trabalho do projeto.","topics.group.agent": "Por agente",diff --git a/locales/ru-RU/project.json b/locales/ru-RU/project.jsonindex 3fcf044c32f..3cb8875fa85 100644--- a/locales/ru-RU/project.json+++ b/locales/ru-RU/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "Выбрать рабочую директорию","topics.chooseTopic": "Выберите тему в боковой панели или создайте новую, чтобы начать работу","topics.complete": "Отметить завершенным",- "topics.conversationOnly": "Только разговор, без рабочей директории","topics.executionContext": "Место работы","topics.gatewayUnavailable": "Включите Agent Gateway перед использованием рабочего места проекта.","topics.group.agent": "По агенту",diff --git a/locales/tr-TR/project.json b/locales/tr-TR/project.jsonindex 2e5238b96c4..31d3d0b63ab 100644--- a/locales/tr-TR/project.json+++ b/locales/tr-TR/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "Bir çalışma dizini seç","topics.chooseTopic": "Kenardaki bir konuyu seçin veya çalışmaya başlamak için bir tane oluşturun","topics.complete": "Tamamlandı olarak işaretle",- "topics.conversationOnly": "Sadece konuşma, çalışma dizini olmadan","topics.executionContext": "Çalışma konumu","topics.gatewayUnavailable": "Bu proje çalışma konumunu kullanmadan önce Ajan Geçidi'ni etkinleştirin.","topics.group.agent": "Ajana göre",diff --git a/locales/vi-VN/project.json b/locales/vi-VN/project.jsonindex b284ab62fbe..b823b2c3049 100644--- a/locales/vi-VN/project.json+++ b/locales/vi-VN/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "Chọn một thư mục làm việc","topics.chooseTopic": "Chọn một chủ đề trong thanh bên, hoặc tạo một chủ đề để bắt đầu làm việc","topics.complete": "Đánh dấu hoàn thành",- "topics.conversationOnly": "Chỉ cuộc trò chuyện, không có thư mục làm việc","topics.executionContext": "Vị trí làm việc","topics.gatewayUnavailable": "Kích hoạt Agent Gateway trước khi sử dụng vị trí làm việc của dự án này.","topics.group.agent": "Theo ajan",diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.jsonindex 0f1c98a8eff..9eb30ce6d9b 100644--- a/locales/zh-CN/project.json+++ b/locales/zh-CN/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "选择工作目录","topics.chooseTopic": "从左侧选择话题,或新建话题开始工作","topics.complete": "标记完成",- "topics.conversationOnly": "仅对话,不使用工作目录","topics.executionContext": "工作位置","topics.gatewayUnavailable": "此工作位置需要启用 Agent Gateway。请启用后重试。","topics.group.agent": "按 Agent 分组",diff --git a/locales/zh-TW/project.json b/locales/zh-TW/project.jsonindex b87daca87be..3c8a1f00189 100644--- a/locales/zh-TW/project.json+++ b/locales/zh-TW/project.json@@ -306,7 +306,6 @@"topics.chooseLocation": "選擇工作目錄","topics.chooseTopic": "在側邊欄選擇一個主題,或建立一個以開始工作","topics.complete": "標記為完成",- "topics.conversationOnly": "僅對話,無工作目錄","topics.executionContext": "工作位置","topics.gatewayUnavailable": "啟用 Agent Gateway 後才能使用此專案工作位置。","topics.group.agent": "按 Agent",diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 642571a316f..5ca143050a6 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -78,6 +78,8 @@ export class ChannelRepository {create = async (params: {agentId?: string;agents?: ChannelAddAgentInput[];+ /** Callers check that the project is readable in this scope. */+ projectId?: string;title: string;visibility?: ChannelVisibility;}) =>@@ -98,6 +100,7 @@ export class ChannelRepository {}const insert = tx.insert(channels).values({agentId,+ projectId: params.projectId,userId: this.userId,title: params.title,visibility: params.visibility,diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.tsindex 180c1ee9f03..a3f82f938c9 100644--- a/packages/locales/src/default/project.ts+++ b/packages/locales/src/default/project.ts@@ -42,7 +42,6 @@ export default {'topics.group.agent': 'By agent','topics.all': 'All topics','topics.executionContext': 'Work location',- 'topics.conversationOnly': 'Conversation only, without a working directory','topics.chooseTopic': 'Choose a topic in the sidebar, or create one to start working','topics.notFound': 'This topic does not belong to this project, or you do not have access','topics.viewProject': 'View project',diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex 9e79884b8d8..f72cdf93799 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -216,6 +216,8 @@ export interface ChannelListItem {canDelete: boolean;createdAt: Date;id: string;+ /** The project the channel is grouped under; null for a standalone channel. */+ projectId: string | null;sequence: number;status: ChannelStatus;title: string;diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsxindex 13bb3cd6f5b..5274bb76770 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx@@ -57,17 +57,15 @@ const runnable = (instanceId: string) => ({vi.mock('@/store/projectWorkingDirectory', () => ({useProjectDirectories: () => directories,+ useProjectDirectoryStore: (selector: (state: object) => unknown) =>+ selector({ createProjectTopic, startTopic: vi.fn() }),}));-const { navigate, openProjectTopicModal, startProjectTopicDraft } = vi.hoisted(() => ({+const { createProjectTopic, navigate, startProjectTopicDraft } = vi.hoisted(() => ({+ createProjectTopic: vi.fn(async () => ({ id: 'tpc_new' })),navigate: vi.fn(),- openProjectTopicModal: vi.fn(),startProjectTopicDraft: vi.fn(),}));--vi.mock('@/features/Projects/WorkingDirectories/StartDirectoryModal', () => ({- openProjectTopicModal,-}));vi.mock('@/features/Projects/WorkingDirectories/startProjectTopicDraft',async (importOriginal) => ({@@ -242,7 +240,7 @@ describe('TopicByAgentGroupItem', () => {navigate,projectId: 'project-1',});- expect(openProjectTopicModal).not.toHaveBeenCalled();+ expect(createProjectTopic).not.toHaveBeenCalled();});/** @example Review: the agent "+" staged a read-only directory, so the first send was refused. */@@ -299,7 +297,7 @@ describe('TopicByAgentGroupItem', () => {);});- it('opens the modal instead of a draft for an agent fixed to a non-device target', () => {+ it('goes straight into a conversation-only topic for an agent fixed to a non-device target', async () => {subGroupModes[GROUP_ID] = 'byDevice';directories[0] = { ...directories[0], ...runnable('ins-mac') };directories[1] = { ...directories[1], ...runnable('ins-linux') };@@ -311,16 +309,26 @@ describe('TopicByAgentGroupItem', () => {fireEvent.click(screen.getByRole('button', { name: 'sidebar.newConversation' }));expect(startProjectTopicDraft).not.toHaveBeenCalled();- expect(openProjectTopicModal).toHaveBeenCalledTimes(1);+ await expect+ .poll(() => navigate.mock.calls.at(-1)?.[0])+ .toBe('/project/project-1/topic/tpc_new');});- it('keeps the modal for a project with no runnable directory, so one can be added', () => {+ /** @example Review feedback: "new topic" must go straight into the agent, never through the work-location modal. */+ it('opens a conversation-only topic of this agent when the project has no runnable directory', async () => {renderGroup();fireEvent.click(screen.getByRole('button', { name: 'sidebar.newConversation' }));expect(startProjectTopicDraft).not.toHaveBeenCalled();- expect(openProjectTopicModal).toHaveBeenCalledTimes(1);+ expect(createProjectTopic).toHaveBeenCalledWith({+ agentId: 'agt_acc_merge_alpha',+ projectId: 'project-1',+ title: 'directories.untitled',+ });+ await expect+ .poll(() => navigate.mock.calls.at(-1)?.[0])+ .toBe('/project/project-1/topic/tpc_new');});/** @example User report: the project sidebar hid devices that had no topics yet. */@@ -506,6 +514,48 @@ describe('TopicByAgentGroupItem', () => {expect(screen.queryByText('公共CC(美国 100刀)')).toBeNull();});+ /** @example Review feedback: a project with no topic should show the main agent group with "new topic". */+ it('offers a new topic inside the main agent group before the project has any topic', () => {+ directories[0] = { ...directories[0], ...runnable('ins-mac') };+ render(+ <TopicListScopeContext+ value={{+ coordinatorAgent: { avatar: '🚀', title: '官网改版 Coordinator' },+ coordinatorAgentId: 'agt_lead',+ projectId: 'prj_1',+ }}+ >+ <AccordionRoot defaultValue={['agent:agt_lead']}>+ <GroupItem+ expanded+ group={{ children: [], id: 'agent:agt_lead', title: '官网改版 Coordinator' }}+ />+ </AccordionRoot>+ </TopicListScopeContext>,+ );++ expect(screen.getAllByText('官网改版 Coordinator').length).toBeGreaterThan(0);+ // The header "+" shares the label; the extra match is the row inside the empty group.+ const entries = screen.getAllByText('sidebar.newConversation');+ expect(entries).toHaveLength(2);+ fireEvent.click(entries[1]);++ expect(startProjectTopicDraft).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agt_lead',+ directoryId: 'binding-mac',+ projectId: 'prj_1',+ }),+ );+ });++ it('adds no extra "new topic" row to a group that already has topics', () => {+ renderInProject('agt_lead');++ // Only the header "+" carries the label.+ expect(screen.getAllByText('sidebar.newConversation')).toHaveLength(1);+ });+it("tags the project's main agent as its lead", () => {renderInProject('agt_lead');diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsxindex 020b7000f9d..0f39feb14f4 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx@@ -25,13 +25,10 @@ import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import Avatar from '@/components/Avatar';-import { openProjectTopicModal } from '@/features/Projects/WorkingDirectories/StartDirectoryModal';-import {- canStageDraftOn,- startProjectTopicDraft,-} from '@/features/Projects/WorkingDirectories/startProjectTopicDraft';+import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';+import { canStageDraftOn } from '@/features/Projects/WorkingDirectories/startProjectTopicDraft';import { useAgentFixedDeviceId } from '@/features/Projects/WorkingDirectories/useAgentFixedDeviceId';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useStartProjectTopic } from '@/features/Projects/WorkingDirectories/useStartProjectTopic';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { useGlobalStore } from '@/store/global';@@ -90,16 +87,21 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {// from its own rows or the agent registry to avoid mislabeling.const isOwnBucket = !agentId || agentId === activeAgentId;+ const isCoordinator = !!agentId && agentId === scope?.coordinatorAgentId;+ // An empty main-agent group has no row to read; the project knows its main agent.+ const coordinatorMeta = isCoordinator ? scope?.coordinatorAgent : undefined;+const avatar =- row?.agentAvatar || registeredMeta?.avatar || (isOwnBucket ? activeMeta.avatar : undefined);+ row?.agentAvatar ||+ registeredMeta?.avatar ||+ coordinatorMeta?.avatar ||+ (isOwnBucket ? activeMeta.avatar : undefined);const name =title ??agentDisplayName(registeredMeta) ??(isOwnBucket ? agentDisplayName(activeMeta) : undefined) ??t('groupTitle.byAgent.unknown');- const isCoordinator = !!agentId && agentId === scope?.coordinatorAgentId;-// Only an attributed bucket in a project-scoped list can start a topic with// its agent preselected; the `no-agent` bucket has no agent to preselect.const canAddTopic = !!scope && !!agentId;@@ -112,25 +114,12 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {[canAddTopic, directories, fixedDeviceId],);- const navigate = useWorkspaceAwareNavigate();- // Same habit as an agent's "+": open a blank conversation on a directory and- // let the first message create the topic. The modal is only the fallback for- // a project with no runnable directory yet — it offers to add one.+ const startTopic = useStartProjectTopic(scope?.projectId);+ // Same habit as an agent's "+": straight into this agent's conversation, on+ // the first directory it can run in when there is one.const handleAddTopic = (initialDirectoryId?: string) => {if (!scope || !agentId) return;- const directoryId = initialDirectoryId ?? startDirectories?.[0]?.id;- if (directoryId) {- startProjectTopicDraft({ agentId, directoryId, navigate, projectId: scope.projectId });- return;- }- openProjectTopicModal({- coordinatorAgentId: scope.coordinatorAgentId ?? agentId,- directories,- initialAgentId: agentId,- initialDirectoryId,- projectId: scope.projectId,- title: tProject('sidebar.newConversation'),- });+ void startTopic({ agentId, directoryId: initialDirectoryId ?? startDirectories?.[0]?.id });};// The agent bucket already sits inside one project, so its rows skip the@@ -206,6 +195,12 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {</div></AccordionHeader><AccordionPanel contentStyle={{ padding: 0 }}>+ {!children.length && canAddTopic && (+ <EmptyNavItem+ title={tProject('sidebar.newConversation')}+ onClick={() => handleAddTopic()}+ />+ )}<ProjectTopicList// The group header already names the owning agent — the row must not// repeat the avatar at its leading position.diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsxindex a8eb09e59cf..744a07e317a 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx@@ -90,11 +90,6 @@ vi.mock('@/features/Projects/WorkingDirectories/BindDirectoryModal', () => ({openBindDirectoryModal: openBindDirectoryModalMock,}));-const openProjectTopicModalMock = vi.hoisted(() => vi.fn());-vi.mock('@/features/Projects/WorkingDirectories/StartDirectoryModal', () => ({- openProjectTopicModal: openProjectTopicModalMock,-}));-vi.mock('react-router', () => ({useParams: () => routeParamsMock,}));@@ -777,7 +772,6 @@ it('opens the plain new-topic composer when a merged project group spans multipl// composer control bar, so no modal may pop and no directory default may be// committed to the agent for a multi-machine merged group.directoryRows.length = 0;- openProjectTopicModalMock.mockClear();commitAgentDefaultMock.mockClear();switchTopicMock.mockClear();setPendingNewTopicDirectoryMock.mockClear();@@ -838,7 +832,6 @@ it('opens the plain new-topic composer when a merged project group spans multipl</AccordionRoot>,);fireEvent.click(screen.getByRole('button', { name: 'directories.start' }));- expect(openProjectTopicModalMock).not.toHaveBeenCalled();expect(commitAgentDefaultMock).not.toHaveBeenCalled();expect(switchTopicMock).toHaveBeenCalledWith(null, { skipRefreshMessage: true });expect(routerPushMock).toHaveBeenCalledWith('/agent/agent-1');@@ -853,7 +846,6 @@ it('opens the plain new-topic composer when a merged project group spans multiplit('keeps the legacy directory start when a project group has a single directory', async () => {directoryRows.length = 0;- openProjectTopicModalMock.mockClear();commitAgentDefaultMock.mockClear();commitAgentDefaultMock.mockResolvedValue(undefined);startTopicMock.mockClear();@@ -892,7 +884,6 @@ it('keeps the legacy directory start when a project group has a single directoryawait expect.poll(() => commitAgentDefaultMock.mock.calls.length).toBe(1);expect(commitAgentDefaultMock).toHaveBeenCalledWith('/repo');expect(startTopicMock).not.toHaveBeenCalled();- expect(openProjectTopicModalMock).not.toHaveBeenCalled();expect(setPendingNewTopicDirectoryMock).toHaveBeenCalledWith({agentId: 'agent-1',projectWorkingDirectoryId: 'binding-single',diff --git a/src/features/AgentSidebar/Topic/TopicListScope.tsx b/src/features/AgentSidebar/Topic/TopicListScope.tsxindex a566741ac3e..60b31ca86b0 100644--- a/src/features/AgentSidebar/Topic/TopicListScope.tsx+++ b/src/features/AgentSidebar/Topic/TopicListScope.tsx@@ -2,8 +2,16 @@ import { createContext, use } from 'react';import type { TopicListFilter } from '@/utils/client/topic';+export interface TopicListScopeAgent {+ avatar?: string | null;+ name?: string | null;+ title?: string | null;+}+/** Host identity keeps the shared list inside its Project route and data scope. */export const TopicListScopeContext = createContext<{+ /** The main agent's display meta, for its group before it has any topic. */+ coordinatorAgent?: TopicListScopeAgent;coordinatorAgentId?: string;projectId: string;} | null>(null);diff --git a/src/features/AgentSidebar/Topic/useScopedTopics.test.ts b/src/features/AgentSidebar/Topic/useScopedTopics.test.tsindex d7d0b33cc95..d3a73e4e9f4 100644--- a/src/features/AgentSidebar/Topic/useScopedTopics.test.ts+++ b/src/features/AgentSidebar/Topic/useScopedTopics.test.ts@@ -8,7 +8,12 @@ import {TopicListRevealContext,TopicListScopeContext,} from './TopicListScope';-import { pinCoordinatorGroup, useOnlyMineTopics, useScopedSidebarTopics } from './useScopedTopics';+import {+ pinCoordinatorGroup,+ useOnlyMineTopics,+ useScopedSidebarTopics,+ withCoordinatorGroup,+} from './useScopedTopics';const fixture = vi.hoisted(() => ({ topicId: undefined as string | undefined }));const userFixture = vi.hoisted(() => ({ topicOnlyMine: false, userId: 'me' }));@@ -267,6 +272,25 @@ describe('pinCoordinatorGroup', () => {});});+describe('withCoordinatorGroup', () => {+ /** @example Review feedback: an empty project showed text, not the main agent's group with "new topic". */+ it('shows the main agent as an empty group named from the project when there is no topic', () => {+ expect(+ withCoordinatorGroup([], {+ coordinatorAgent: { name: null, title: '官网改版 Coordinator' },+ coordinatorAgentId: 'agt_lead',+ }),+ ).toEqual([{ children: [], id: 'agent:agt_lead', title: '官网改版 Coordinator' }]);+ });++ it('leaves existing groups and scopes without a main agent alone', () => {+ const groups = [{ children: [], id: 'agent:a', title: 'a' }];+ expect(withCoordinatorGroup(groups, { coordinatorAgentId: 'agt_lead' })).toBe(groups);+ expect(withCoordinatorGroup([], { coordinatorAgentId: undefined })).toEqual([]);+ expect(withCoordinatorGroup([], null)).toEqual([]);+ });+});+describe('useOnlyMineTopics', () => {beforeEach(() => {userFixture.topicOnlyMine = false;diff --git a/src/features/AgentSidebar/Topic/useScopedTopics.ts b/src/features/AgentSidebar/Topic/useScopedTopics.tsindex 1289ad47c63..35cb3648cb1 100644--- a/src/features/AgentSidebar/Topic/useScopedTopics.ts+++ b/src/features/AgentSidebar/Topic/useScopedTopics.ts@@ -1,3 +1,4 @@+import { agentDisplayName } from '@lobechat/types';import { useMemo } from 'react';import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';@@ -16,7 +17,12 @@ import { userProfileSelectors } from '@/store/user/selectors';import type { ChatTopic, GroupedTopic, TopicGroupMode, TopicSortBy } from '@/types/topic';import { filterTopics } from '@/utils/client/topic';-import { useTopicListFilter, useTopicListReveal, useTopicListScope } from './TopicListScope';+import {+ type TopicListScopeAgent,+ useTopicListFilter,+ useTopicListReveal,+ useTopicListScope,+} from './TopicListScope';export const useScopedTopics = () => {const scope = useTopicListScope();@@ -49,6 +55,25 @@ export const pinCoordinatorGroup = (groups: GroupedTopic[], coordinatorAgentId?:return [...rest.slice(0, leadIndex), groups[index], ...rest.slice(leadIndex)];};+/**+ * A project with no topic yet still shows its main agent's group, so starting+ * the first topic reads the same as adding one later. Only when nothing is+ * filtered: a filter that matches nothing keeps its own empty state.+ */+export const withCoordinatorGroup = (+ groups: GroupedTopic[],+ scope: { coordinatorAgent?: TopicListScopeAgent; coordinatorAgentId?: string } | null,+): GroupedTopic[] =>+ groups.length || !scope?.coordinatorAgentId+ ? groups+ : [+ {+ children: [],+ id: `agent:${scope.coordinatorAgentId}`,+ title: agentDisplayName(scope.coordinatorAgent),+ },+ ];+export const useScopedTopic = (id?: string) =>useScopedTopics().topics?.find((topic) => topic.id === id);@@ -117,8 +142,10 @@ export const useScopedSidebarTopics = (const coordinatorAgentId = scope?.coordinatorAgentId;const groups = useMemo(() => {const grouped = groupSidebarTopics(visible, groupMode, sortBy, running, directories);- return groupMode === 'byAgent' ? pinCoordinatorGroup(grouped, coordinatorAgentId) : grouped;- }, [visible, groupMode, sortBy, running, directories, coordinatorAgentId]);+ if (groupMode !== 'byAgent') return grouped;+ const pinned = pinCoordinatorGroup(grouped, coordinatorAgentId);+ return filtering ? pinned : withCoordinatorGroup(pinned, scope);+ }, [visible, groupMode, sortBy, running, directories, coordinatorAgentId, filtering, scope]);const hasMore =candidates.filtered.filter((topic) => includeCompleted || topic.status !== 'completed').length >visibleLimit;diff --git a/src/features/Channels/ChannelList.tsx b/src/features/Channels/ChannelList.tsxindex 4eedac37fd3..d41d931f07c 100644--- a/src/features/Channels/ChannelList.tsx+++ b/src/features/Channels/ChannelList.tsx@@ -26,7 +26,7 @@ import {Plus,Trash,} from 'lucide-react';-import { useState } from 'react';+import { useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';@@ -42,6 +42,7 @@ import { channelActions, channelSelectors, useChannelStore } from '@/store/channimport { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';import { isTrpcErrorCode } from '@/utils/trpcError';+import { channelsInScope } from './channelScope';import { openCreateChannel } from './CreateChannel';import { channelPath, matchChannel } from './paths';import { threadTitle } from './threadTitle';@@ -52,9 +53,11 @@ import { useThreadMenu } from './useThreadMenu';const ChannelThreads = ({channelId,+ projectId,threadId,}: {channelId: string;+ projectId: string | null;threadId: string | null;}) => {const { t } = useTranslation('channel');@@ -68,7 +71,7 @@ const ChannelThreads = ({return (<Flexbox aria-label={t('thread')} gap={1} paddingBlock={1} style={{ paddingInlineStart: 20 }}>{detail.threads.map((thread, index) => {- const path = channelPath(channelId, thread.id);+ const path = channelPath(channelId, thread.id, projectId);const active = thread.id === threadId;// Archived threads stay reachable from their root message, out of the sidebar.if (thread.status === 'archived' && !active) return null;@@ -107,21 +110,36 @@ const ChannelThreads = ({);};-/** Channels beside Agents in the home sidebar, with the open Channel's threads nested under it. */-const EnabledChannelList = () => {+interface ChannelSectionProps {+ /** The accordion item value; the parent `AccordionRoot` owns the expanded state. */+ itemKey?: string;+ /**+ * Lists only this project's Channels, and new ones join it. Without it the list holds the+ * Channels outside any project.+ */+ projectId?: string;+}++/**+ * Channels beside Agents in the home sidebar or above a project's topics, with the open+ * Channel's threads nested under it.+ */+const EnabledChannelSection = ({ itemKey = 'channels', projectId }: ChannelSectionProps) => {const { t } = useTranslation('channel');const { pathname, search } = useActiveLocation();const navigate = useWorkspaceAwareNavigate();const slug = useActiveWorkspaceSlug();const sync = channelActions.useFetchList();- const channels = useChannelStore(channelSelectors.list);+ const allChannels = useChannelStore(channelSelectors.list);+ const channels = useMemo(() => channelsInScope(allChannels, projectId), [allChannels, projectId]);useChannelEvents();const remove = useRemoveChannel();const { archive, unarchive } = useChannelArchive();const [showArchived, setShowArchived] = useState(false);const activeChannelId = matchChannel(pathname);- const create = () => openCreateChannel((id) => navigate(channelPath(id)));+ const create = () =>+ openCreateChannel((id) => navigate(channelPath(id, null, projectId)), projectId);const activeThreadId = new URLSearchParams(search).get('thread');const rename = (channel: ChannelListItem) =>openRenameModal({@@ -184,7 +202,7 @@ const EnabledChannelList = () => {];const renderChannel = (channel: ChannelListItem) => {- const path = channelPath(channel.id);+ const path = channelPath(channel.id, null, channel.projectId);const open = activeChannelId === channel.id;return (<Flexbox key={channel.id}>@@ -203,7 +221,13 @@ const EnabledChannelList = () => {)}onClick={() => navigate(path)}/>- {open && <ChannelThreads channelId={channel.id} threadId={activeThreadId} />}+ {open && (+ <ChannelThreads+ channelId={channel.id}+ projectId={channel.projectId}+ threadId={activeThreadId}+ />+ )}</Flexbox>);};@@ -215,76 +239,82 @@ const EnabledChannelList = () => {: archived.filter((channel) => channel.id === activeChannelId);return (- <AccordionRoot defaultValue={['channels']} indicatorPlacement="inline">- <AccordionItem value="channels">- <AccordionHeader>- <AccordionTrigger style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>- <Text ellipsis fontSize={12} type="secondary" weight={500}>- {t('title')}- </Text>- </AccordionTrigger>- <Flexbox- horizontal- align="center"- gap={2}- className={cx(- 'accordion-action',- accordionStyles.action,- accordionStyles.actionBorderless,- )}- >- <ActionIcon- aria-label={t('create')}- icon={Plus}- size="small"- title={t('create')}- onClick={(event) => {- event.stopPropagation();- create();- }}+ <AccordionItem value={itemKey}>+ <AccordionHeader>+ <AccordionTrigger style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>+ <Text ellipsis fontSize={12} type="secondary" weight={500}>+ {t('title')}+ </Text>+ </AccordionTrigger>+ <Flexbox+ horizontal+ align="center"+ gap={2}+ className={cx(+ 'accordion-action',+ accordionStyles.action,+ accordionStyles.actionBorderless,+ )}+ >+ <ActionIcon+ aria-label={t('create')}+ icon={Plus}+ size="small"+ title={t('create')}+ onClick={(event) => {+ event.stopPropagation();+ create();+ }}+ />+ </Flexbox>+ </AccordionHeader>+ <AccordionPanel contentStyle={{ padding: 0 }}>+ <Flexbox gap={1} paddingBlock={1}>+ {!channels && !sync.error && <SkeletonList rows={3} />}+ {!!sync.error && (+ <AsyncError+ error={sync.error}+ variant="inline"+ onRetry={() => void channelActions.refreshList()}/>- </Flexbox>- </AccordionHeader>- <AccordionPanel contentStyle={{ padding: 0 }}>- <Flexbox gap={1} paddingBlock={1}>- {!channels && !sync.error && <SkeletonList rows={3} />}- {!!sync.error && (- <AsyncError- error={sync.error}- variant="inline"- onRetry={() => void channelActions.refreshList()}+ )}+ {channels && !active.length && <EmptyNavItem title={t('create')} onClick={create} />}+ {active.map(renderChannel)}+ {archived.length > 0 && (+ <>+ <NavItem+ aria-expanded={showArchived}+ icon={Archive}+ title={t('archivedGroup', { count: archived.length })}+ onClick={() => setShowArchived(!showArchived)}/>- )}- {channels && !active.length && <EmptyNavItem title={t('create')} onClick={create} />}- {active.map(renderChannel)}- {archived.length > 0 && (- <>- <NavItem- aria-expanded={showArchived}- icon={Archive}- title={t('archivedGroup', { count: archived.length })}- onClick={() => setShowArchived(!showArchived)}- />- {shownArchived.length > 0 && (- <Flexbox gap={1} style={{ paddingInlineStart: 12 }}>- {shownArchived.map(renderChannel)}- </Flexbox>- )}- </>- )}- </Flexbox>- </AccordionPanel>- </AccordionItem>- </AccordionRoot>+ {shownArchived.length > 0 && (+ <Flexbox gap={1} style={{ paddingInlineStart: 12 }}>+ {shownArchived.map(renderChannel)}+ </Flexbox>+ )}+ </>+ )}+ </Flexbox>+ </AccordionPanel>+ </AccordionItem>);};-const ChannelList = () => {- // Before the per-user flags load the store holds defaults; wait instead of guessing.- const enabled = useServerConfigStore(- (s) => s.serverConfigInit && serverConfigSelectors.enableChannels(s),- );- return enabled ? <EnabledChannelList /> : null;-};+// Before the per-user flags load the store holds defaults; wait instead of guessing.+const useChannelsEnabled = () =>+ useServerConfigStore((s) => s.serverConfigInit && serverConfigSelectors.enableChannels(s));++/** One accordion item; place it inside an `AccordionRoot`. */+export const ChannelSection = (props: ChannelSectionProps) =>+ useChannelsEnabled() ? <EnabledChannelSection {...props} /> : null;++/** The home sidebar's standalone Channels, outside any project. */+const ChannelList = () =>+ useChannelsEnabled() ? (+ <AccordionRoot defaultValue={['channels']} indicatorPlacement="inline">+ <EnabledChannelSection />+ </AccordionRoot>+ ) : null;export default ChannelList;diff --git a/src/features/Channels/CreateChannel/index.tsx b/src/features/Channels/CreateChannel/index.tsxindex a15d0d91a9b..f967e0252dc 100644--- a/src/features/Channels/CreateChannel/index.tsx+++ b/src/features/Channels/CreateChannel/index.tsx@@ -28,6 +28,8 @@ interface CreateChannelProps {/** Set when inviting members into a Channel that already exists. */existing?: ExistingChannel;onCreated?: (id: string) => void;+ /** A new Channel created from a project's sidebar is grouped under that project. */+ projectId?: string;}const openMemberDialog = (props: CreateChannelProps) =>@@ -38,8 +40,8 @@ const openMemberDialog = (props: CreateChannelProps) =>width: 'min(90vw, 800px)',});-export const openCreateChannel = (onCreated?: (id: string) => void) =>- openMemberDialog({ onCreated });+export const openCreateChannel = (onCreated?: (id: string) => void, projectId?: string) =>+ openMemberDialog({ onCreated, projectId });/** The single entry for adding people and Agents to an existing Channel. */export const openInviteMembers = (existing: ExistingChannel) => openMemberDialog({ existing });@@ -49,7 +51,7 @@ export const openInviteMembers = (existing: ExistingChannel) => openMemberDialog* members' names; the sidebar renames it later. Inviting into an existing Channel uses the* same picker without a name, and also lists workspace members in workspace Channels.*/-function CreateChannel({ existing, onCreated }: CreateChannelProps) {+function CreateChannel({ existing, onCreated, projectId }: CreateChannelProps) {const { t } = useTranslation('channel');const { close, setCanDismissByClickOutside } = useModalContext();const [title, setTitle] = useState('');@@ -95,6 +97,7 @@ function CreateChannel({ existing, onCreated }: CreateChannelProps) {} else {const id = await channelActions.create({agents: selections,+ projectId,title: title.trim() || autoTitle,});close();@@ -111,7 +114,6 @@ function CreateChannel({ existing, onCreated }: CreateChannelProps) {return (<Flexbox gap={16}><Flexbox gap={8} inert={busy}>- {!existing && <Text weight={500}>{t('agents')}</Text>}<MemberSelectionexclude={existing?.agentIds}options={options}diff --git a/src/features/Channels/channelScope.test.ts b/src/features/Channels/channelScope.test.tsnew file mode 100644index 00000000000..f16bf3f4d1e--- /dev/null+++ b/src/features/Channels/channelScope.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from 'vitest';++import { channelsInScope } from './channelScope';++const channels = [+ { id: 'standalone', projectId: null },+ { id: 'launch', projectId: 'pro_1' },+ { id: 'other', projectId: 'pro_2' },+ // Cached before the list carried a project.+ { id: 'legacy', projectId: undefined as unknown as null },+];++describe('channelsInScope', () => {+ it('lists only the project’s own Channels inside a project', () => {+ expect(channelsInScope(channels, 'pro_1')?.map((c) => c.id)).toEqual(['launch']);+ });++ it('keeps project Channels out of the home list', () => {+ expect(channelsInScope(channels)?.map((c) => c.id)).toEqual(['standalone', 'legacy']);+ });++ it('waits for the list to load', () => {+ expect(channelsInScope(undefined, 'pro_1')).toBeUndefined();+ });+});diff --git a/src/features/Channels/channelScope.ts b/src/features/Channels/channelScope.tsnew file mode 100644index 00000000000..25dce4a6a1d--- /dev/null+++ b/src/features/Channels/channelScope.ts@@ -0,0 +1,11 @@+import type { ChannelListItem } from '@lobechat/types';++/**+ * The Channels one sidebar lists: a project's own, or (without a project) those outside every+ * project, so each Channel appears in exactly one place.+ */+export const channelsInScope = <T extends Pick<ChannelListItem, 'projectId'>>(+ channels: T[] | undefined,+ projectId?: string,+): T[] | undefined =>+ channels?.filter((channel) => (projectId ? channel.projectId === projectId : !channel.projectId));diff --git a/src/features/Channels/paths.test.ts b/src/features/Channels/paths.test.tsindex 618f789500f..38249d4f0be 100644--- a/src/features/Channels/paths.test.ts+++ b/src/features/Channels/paths.test.ts@@ -7,6 +7,13 @@ describe('channelPath', () => {expect(channelPath('chn_1')).toBe('/channels/chn_1');expect(channelPath('chn_1', 'cht_1')).toBe('/channels/chn_1?thread=cht_1');});++ it('opens a project Channel inside its project', () => {+ expect(channelPath('chn_1', null, 'pro_1')).toBe('/project/pro_1/channels/chn_1');+ expect(channelPath('chn_1', 'cht_1', 'pro_1')).toBe(+ '/project/pro_1/channels/chn_1?thread=cht_1',+ );+ });});describe('matchChannel', () => {@@ -14,14 +21,19 @@ describe('matchChannel', () => {['/channels/chn_1', 'chn_1'],['/channels/chn_1/', 'chn_1'],['/acme/channels/chn_1', 'chn_1'],+ ['/project/pro_1/channels/chn_1', 'chn_1'],+ ['/acme/project/pro_1/channels/chn_1/', 'chn_1'],])('reads %s as an open Channel', (pathname, expected) => {expect(matchChannel(pathname)).toBe(expected);});- it.each(['/', '/channels', '/group/grp_1', '/agent/agt_1/channels/telegram'])(- 'finds no Channel in %s',- (pathname) => {- expect(matchChannel(pathname)).toBeUndefined();- },- );+ it.each([+ '/',+ '/channels',+ '/group/grp_1',+ '/agent/agt_1/channels/telegram',+ '/project/pro_1/channels',+ ])('finds no Channel in %s', (pathname) => {+ expect(matchChannel(pathname)).toBeUndefined();+ });});diff --git a/src/features/Channels/paths.ts b/src/features/Channels/paths.tsindex 3a11921c042..1b300d53daf 100644--- a/src/features/Channels/paths.ts+++ b/src/features/Channels/paths.ts@@ -1,12 +1,19 @@-/** A Channel page; a thread opens beside its Channel. */-export const channelPath = (channelId: string, threadId?: string | null) => {- const path = `/channels/${channelId}`;+/**+ * A Channel page; a thread opens beside its Channel. A project's Channel opens inside the+ * project so its sidebar stays in place.+ */+export const channelPath = (+ channelId: string,+ threadId?: string | null,+ projectId?: string | null,+) => {+ const path = projectId ? `/project/${projectId}/channels/${channelId}` : `/channels/${channelId}`;return threadId ? `${path}?thread=${encodeURIComponent(threadId)}` : path;};-// An optional leading segment is the workspace slug.-const CHANNEL_PATH = /^(?:\/[^/]+)?\/channels\/([^/]+)\/?$/;+// An optional leading segment is the workspace slug, then an optional project scope.+const CHANNEL_PATH = /^(?:\/[^/]+)?(?:\/project\/[^/]+)?\/channels\/([^/]+)\/?$/;-/** Which Channel a (possibly workspace-prefixed) pathname opens, if any. */+/** Which Channel a (possibly workspace-prefixed or project-scoped) pathname opens, if any. */export const matchChannel = (pathname: string): string | undefined =>CHANNEL_PATH.exec(pathname)?.[1];diff --git a/src/features/Channels/useRemoveChannel.test.ts b/src/features/Channels/useRemoveChannel.test.tsindex 556b12cf30f..88b729d9954 100644--- a/src/features/Channels/useRemoveChannel.test.ts+++ b/src/features/Channels/useRemoveChannel.test.ts@@ -33,6 +33,7 @@ const channel: ChannelListItem = {canDelete: true,createdAt: new Date(),id: 'chn_abcdefghijkl',+ projectId: null,sequence: 0,status: 'active',title: 'Important channel',@@ -75,6 +76,16 @@ describe('Channel deletion confirmation', () => {expect(success).toHaveBeenCalledWith('moveToTrashSuccess');});+ it('returns to the project after deleting the open project Channel', async () => {+ location.pathname = `/project/pro_1/channels/${channel.id}`;+ const hook = renderHook(useRemoveChannel);+ act(() => {+ hook.result.current({ ...channel, projectId: 'pro_1' });+ });+ await (confirm.mock.calls[0][0].onOk as () => Promise<void>)();+ expect(navigate).toHaveBeenCalledWith('/project/pro_1', { replace: true });+ });+it('does not redirect if the user navigated elsewhere while confirmation was open', async () => {const { onOk, rerender } = open();location.pathname = '/channels/chn_otherchannel';diff --git a/src/features/Channels/useRemoveChannel.ts b/src/features/Channels/useRemoveChannel.tsindex c6ffc4d7831..09039c03ddf 100644--- a/src/features/Channels/useRemoveChannel.ts+++ b/src/features/Channels/useRemoveChannel.ts@@ -37,8 +37,11 @@ export const useRemoveChannel = () => {throw error; // Keep the confirmation open so the user can retry or cancel.}if (cacheScope.get() !== scope) return;+ // A project's Channel returns to its project, where the list lives.if (matchChannel(latest.current.location.pathname) === channel.id)- latest.current.navigate('/', { replace: true });+ latest.current.navigate(channel.projectId ? `/project/${channel.projectId}` : '/', {+ replace: true,+ });toast.success(t('moveToTrashSuccess'));},});diff --git a/src/features/Projects/Layout/Sidebar.tsx b/src/features/Projects/Layout/Sidebar.tsxindex 422af635666..9abe129bf3c 100644--- a/src/features/Projects/Layout/Sidebar.tsx+++ b/src/features/Projects/Layout/Sidebar.tsx@@ -9,7 +9,7 @@ import {SettingsIcon,TargetIcon,} from 'lucide-react';-import { memo } from 'react';+import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { useLocation } from 'react-router';@@ -22,7 +22,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import { useCurrentProjectDetail, useProjectStore } from '@/store/project';-import { ProjectDirectoryTopics } from '../WorkingDirectories/SidebarTopics';+import { projectComposerAgents } from '../Workspace/projectComposerAgents';import {getProjectAcceptancePath,getProjectDashboardPath,@@ -33,6 +33,7 @@ import {toProjectPathname,} from './navigation';import ProjectHeader from './ProjectHeader';+import SidebarSections from './SidebarSections';const ProjectSidebarContent = memo(() => {const { t } = useTranslation('project');@@ -48,6 +49,12 @@ const ProjectSidebarContent = memo(() => {const projectAcceptancePath = getProjectAcceptancePath(projectId!);const projectDashboardPath = getProjectDashboardPath(projectId!);+ // The main agent leads the composer list; its meta names its topic group before any topic.+ const coordinatorAgent = useMemo(+ () => (detail?.project ? projectComposerAgents(detail)[0] : undefined),+ [detail],+ );+const header = <ProjectHeader project={detail?.project} />;if (detailSWR.error && !detail)@@ -104,7 +111,8 @@ const ProjectSidebarContent = memo(() => {onClick={() => navigate(`/project/${projectId}/settings/general`)}/>{detail?.project && (- <ProjectDirectoryTopics+ <SidebarSections+ coordinatorAgent={coordinatorAgent}coordinatorAgentId={detail.project.coordinatorAgentId}projectId={detail.project.id}/>diff --git a/src/features/Projects/Layout/SidebarSections.tsx b/src/features/Projects/Layout/SidebarSections.tsxnew file mode 100644index 00000000000..ec4af391227--- /dev/null+++ b/src/features/Projects/Layout/SidebarSections.tsx@@ -0,0 +1,68 @@+import { AccordionRoot } from '@lobehub/ui';+import { memo, useMemo } from 'react';++import { type TopicListScopeAgent } from '@/features/AgentSidebar/Topic/TopicListScope';+import { ChannelSection } from '@/features/Channels/ChannelList';+import { useGlobalStore } from '@/store/global';+import { systemStatusSelectors } from '@/store/global/selectors';++import { ProjectDirectoryTopics } from '../WorkingDirectories/SidebarTopics';++export enum ProjectSidebarKey {+ Channels = 'channels',+ Topics = 'topics',+}++const DEFAULT_EXPANDED: Record<string, boolean> = {+ [ProjectSidebarKey.Channels]: true,+ [ProjectSidebarKey.Topics]: true,+};++interface SidebarSectionsProps {+ coordinatorAgent?: TopicListScopeAgent;+ coordinatorAgentId: string;+ projectId: string;+}++/** The project's Channels above its topics, each collapsible and remembered per project. */+const SidebarSections = memo<SidebarSectionsProps>(+ ({ coordinatorAgent, coordinatorAgentId, projectId }) => {+ const sections = useGlobalStore(systemStatusSelectors.projectSidebarSections(projectId));+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);++ const expandedKeys = useMemo(() => {+ const resolved = { ...DEFAULT_EXPANDED, ...sections };+ return Object.keys(resolved).filter((key) => resolved[key]);+ }, [sections]);++ return (+ <AccordionRoot+ indicatorPlacement="inline"+ style={{ gap: 8, paddingBlock: 12 }}+ value={expandedKeys}+ onValueChange={(next) => {+ const keys = next as string[];+ updateSystemStatus({+ expandProjectSidebarSectionsByProject: {+ [projectId]: Object.fromEntries(+ Object.values(ProjectSidebarKey).map((key) => [key, keys.includes(key)]),+ ),+ },+ });+ }}+ >+ <ChannelSection itemKey={ProjectSidebarKey.Channels} projectId={projectId} />+ <ProjectDirectoryTopics+ coordinatorAgent={coordinatorAgent}+ coordinatorAgentId={coordinatorAgentId}+ itemKey={ProjectSidebarKey.Topics}+ projectId={projectId}+ />+ </AccordionRoot>+ );+ },+);++SidebarSections.displayName = 'ProjectSidebarSections';++export default SidebarSections;diff --git a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx b/src/features/Projects/WorkingDirectories/SidebarTopics.tsxindex 312b4065587..35e22c2af8d 100644--- a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx+++ b/src/features/Projects/WorkingDirectories/SidebarTopics.tsx@@ -1,4 +1,15 @@-import { ActionIcon, Button, Flexbox, Text } from '@lobehub/ui';+import {+ AccordionHeader,+ AccordionItem,+ AccordionPanel,+ accordionStyles,+ AccordionTrigger,+ ActionIcon,+ Button,+ cx,+ Flexbox,+ Text,+} from '@lobehub/ui';import { PlusIcon } from 'lucide-react';import { useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -15,12 +26,12 @@ import FlatMode from '@/features/AgentSidebar/Topic/TopicListContent/FlatMode';import {TopicListFilterContext,TopicListRevealContext,+ type TopicListScopeAgent,TopicListScopeContext,useTopicListFilter,} from '@/features/AgentSidebar/Topic/TopicListScope';import { useOnlyMineTopics, useScopedTopics } from '@/features/AgentSidebar/Topic/useScopedTopics';import SkeletonList from '@/features/NavPanel/components/SkeletonList';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useWorkspacePreferenceReady } from '@/hooks/useWorkspacePreferenceReady';import {useProjectDirectories,@@ -29,15 +40,28 @@ import {} from '@/store/projectWorkingDirectory';import { filterTopics, type TopicListFilter } from '@/utils/client/topic';-import { openProjectTopicModal } from './StartDirectoryModal';-import { canStageDraftOn, startProjectTopicDraft } from './startProjectTopicDraft';+import { canStageDraftOn } from './startProjectTopicDraft';import { useAgentFixedDeviceId } from './useAgentFixedDeviceId';import { useProjectTopicReveal } from './useProjectTopicReveal';+import { useStartProjectTopic } from './useStartProjectTopic';-export function ProjectDirectoryTopics(props: { projectId: string; coordinatorAgentId: string }) {+interface ProjectDirectoryTopicsProps {+ /** The main agent's display meta, for its group before the project has any topic. */+ coordinatorAgent?: TopicListScopeAgent;+ coordinatorAgentId: string;+ /** The accordion item value; the parent `AccordionRoot` owns the expanded state. */+ itemKey: string;+ projectId: string;+}++export function ProjectDirectoryTopics(props: ProjectDirectoryTopicsProps) {const scope = useMemo(- () => ({ coordinatorAgentId: props.coordinatorAgentId, projectId: props.projectId }),- [props.projectId, props.coordinatorAgentId],+ () => ({+ coordinatorAgent: props.coordinatorAgent,+ coordinatorAgentId: props.coordinatorAgentId,+ projectId: props.projectId,+ }),+ [props.projectId, props.coordinatorAgentId, props.coordinatorAgent],);const reveal = useProjectTopicReveal(props.projectId);const [filter, setFilter] = useState<TopicListFilter>({});@@ -53,13 +77,7 @@ export function ProjectDirectoryTopics(props: { projectId: string; coordinatorAg);}-function ProjectTopicList({- projectId,- coordinatorAgentId,-}: {- projectId: string;- coordinatorAgentId: string;-}) {+function ProjectTopicList({ projectId, coordinatorAgentId, itemKey }: ProjectDirectoryTopicsProps) {const { t } = useTranslation('project');const { t: tTopic } = useTranslation('topic');const { topicGroupMode } = useAgentTopicGroupMode();@@ -82,15 +100,26 @@ function ProjectTopicList({// nothing else on a project route syncs that preference. Hold the list until// it is known so the unfiltered rows never paint.const isPreferenceLoading = !useWorkspacePreferenceReady();- const navigate = useWorkspaceAwareNavigate();+ const startTopic = useStartProjectTopic(projectId);const fixedDeviceId = useAgentFixedDeviceId(coordinatorAgentId);return (- <Flexbox gap={1} paddingBlock={12}>- <Flexbox horizontal align="center" justify="space-between" paddingInline={8}>- <Text fontSize={12} type="secondary" weight={500}>- {t('topics.title')}- </Text>- <Flexbox horizontal align="center" gap={2}>+ <AccordionItem value={itemKey}>+ <AccordionHeader>+ <AccordionTrigger style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>+ <Text ellipsis fontSize={12} type="secondary" weight={500}>+ {t('topics.title')}+ </Text>+ </AccordionTrigger>+ <Flexbox+ horizontal+ align="center"+ gap={2}+ className={cx(+ 'accordion-action',+ accordionStyles.action,+ accordionStyles.actionBorderless,+ )}+ ><ToggleGroups /><Filter /><ActionIcon@@ -99,61 +128,53 @@ function ProjectTopicList({icon={PlusIcon}size="small"title={t('sidebar.newConversation')}- onClick={() => {- // Same habit as an agent's "+": a blank conversation on the first- // directory the coordinator can run in, switchable in the composer before the first- // send. The modal only remains for a project with none yet.- const directory = directories.find((d) => canStageDraftOn(d, fixedDeviceId));- if (directory) {- startProjectTopicDraft({- agentId: coordinatorAgentId,- directoryId: directory.id,- navigate,- projectId,- });- return;- }- openProjectTopicModal({- title: t('sidebar.newConversation'),- coordinatorAgentId,- directories,- projectId,- });- }}+ onClick={() =>+ // Same habit as an agent's "+": straight into the coordinator's+ // conversation, on the first directory it can run in when there is one.+ void startTopic({+ agentId: coordinatorAgentId,+ directoryId: directories.find((d) => canStageDraftOn(d, fixedDeviceId))?.id,+ })+ }/></Flexbox>- </Flexbox>- {request.error || directoriesRequest.error ? (- <AsyncError- error={request.error || directoriesRequest.error}- onRetry={() => Promise.all([request.revalidate(), directoriesRequest.revalidate()])}- />- ) : null}- {!request.hasData || isPreferenceLoading ? (- <SkeletonList />- ) : !topics.length && !request.error ? (- <Text fontSize={12} style={{ paddingInline: 8 }} type="secondary">- {t('directories.noConversations')}- </Text>- ) : filteredEmpty ? (- <Flexbox align="flex-start" gap={4} paddingInline={8}>- <Text type="secondary">{tTopic('filter.emptyFiltered')}</Text>- <Button size="small" type="text" onClick={() => filterState?.setFilter({})}>- {tTopic('filter.clear')}- </Button>+ </AccordionHeader>+ <AccordionPanel contentStyle={{ padding: 0 }}>+ <Flexbox gap={1} paddingBlock={1}>+ {request.error || directoriesRequest.error ? (+ <AsyncError+ error={request.error || directoriesRequest.error}+ onRetry={() => Promise.all([request.revalidate(), directoriesRequest.revalidate()])}+ />+ ) : null}+ {!request.hasData || isPreferenceLoading ? (+ <SkeletonList />+ ) : !topics.length && !request.error && topicGroupMode !== 'byAgent' ? (+ // By agent, the main agent's empty group offers the first topic instead.+ <Text fontSize={12} style={{ paddingInline: 8 }} type="secondary">+ {t('directories.noConversations')}+ </Text>+ ) : filteredEmpty ? (+ <Flexbox align="flex-start" gap={4} paddingInline={8}>+ <Text type="secondary">{tTopic('filter.emptyFiltered')}</Text>+ <Button size="small" type="text" onClick={() => filterState?.setFilter({})}>+ {tTopic('filter.clear')}+ </Button>+ </Flexbox>+ ) : null}+ {isPreferenceLoading ? null : topicGroupMode === 'flat' ? (+ <FlatMode />+ ) : topicGroupMode === 'byStatus' ? (+ <ByStatusMode />+ ) : topicGroupMode === 'byAgent' ? (+ <ByAgentMode />+ ) : topicGroupMode === 'byDevice' ? (+ <ByDeviceMode />+ ) : (+ <ByTimeMode />+ )}</Flexbox>- ) : null}- {isPreferenceLoading ? null : topicGroupMode === 'flat' ? (- <FlatMode />- ) : topicGroupMode === 'byStatus' ? (- <ByStatusMode />- ) : topicGroupMode === 'byAgent' ? (- <ByAgentMode />- ) : topicGroupMode === 'byDevice' ? (- <ByDeviceMode />- ) : (- <ByTimeMode />- )}- </Flexbox>+ </AccordionPanel>+ </AccordionItem>);}diff --git a/src/features/Projects/WorkingDirectories/StartDirectoryModal.tsx b/src/features/Projects/WorkingDirectories/StartDirectoryModal.tsxdeleted file mode 100644index da801227e28..00000000000--- a/src/features/Projects/WorkingDirectories/StartDirectoryModal.tsx+++ /dev/null@@ -1,148 +0,0 @@-'use client';--import {- Button,- createModal,- Flexbox,- ModalFooter,- Select,- Text,- useModalContext,-} from '@lobehub/ui';-import { useState } from 'react';-import { useTranslation } from 'react-i18next';--import AsyncError from '@/components/AsyncError';-import AssigneeAgentSelector from '@/features/AgentTasks/features/AssigneeAgentSelector';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import {- type ProjectDirectory,- useProjectDirectories,- useProjectDirectoryStore,-} from '@/store/projectWorkingDirectory';--import { getProjectTopicPath } from '../Layout/navigation';-import { openAddDirectoryModal } from './AddDirectoryModal';-import { openEnvironmentModal } from './EnvironmentModal';-import { useDirectoryAgent } from './useDirectoryAgent';--export function StartDirectoryContent({- directories,- coordinatorAgentId,- projectId,- initialAgentId,- initialDirectoryId,-}: {- directories: ProjectDirectory[];- coordinatorAgentId: string;- projectId: string;- initialAgentId?: string;- initialDirectoryId?: string;-}) {- const [directoryId, setDirectoryId] = useState(- initialDirectoryId ?? (directories.length === 1 ? directories[0].id : ''),- );- useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);- const liveDirectories = useProjectDirectories(projectId);- const locations = liveDirectories.length ? liveDirectories : directories;- const directory = locations.find((d) => d.id === directoryId);- const attachEnvironment = useProjectDirectoryStore((s) => s.attachEnvironment);- const { t } = useTranslation('project');- const { close } = useModalContext();- const navigate = useWorkspaceAwareNavigate();- const { agentId, agentName, setAgentId } = useDirectoryAgent(coordinatorAgentId, initialAgentId);- const startTopic = useProjectDirectoryStore((s) => s.startTopic);- const createTopic = useProjectDirectoryStore((s) => s.createProjectTopic);- const [pending, setPending] = useState(false);- const [error, setError] = useState<unknown>();- const start = async () => {- setPending(true);- setError(undefined);- try {- const topic = directory- ? await startTopic(directory.id, agentId, t('directories.untitled'))- : await createTopic({ projectId, agentId, title: t('directories.untitled') });- close();- navigate(getProjectTopicPath(projectId, topic.id));- } catch (error) {- console.error('Failed to start directory work', error);- setError(error);- } finally {- setPending(false);- }- };- return (- <>- <Flexbox gap={16} padding={16}>- <Text>{t('topics.executionContext')}</Text>- <Select- aria-label={t('topics.executionContext')}- disabled={pending}- value={directoryId || '__none__'}- options={[- { value: '__none__', label: t('topics.conversationOnly') },- ...locations- .filter((d) => d.instanceId)- .map((d) => ({- value: d.id,- label: `${d.environmentName || d.name} · ${d.deviceName || d.deviceId} · ${d.path}`,- })),- ]}- onChange={(id) => setDirectoryId(id === '__none__' ? '' : (id ?? ''))}- />- {!locations.length && (- <Button- onClick={() =>- openEnvironmentModal({- onSaved: async (env) => {- await attachEnvironment(projectId, env.id);- openAddDirectoryModal(projectId, env.id);- },- })- }- >- {t('settings.addDirectory')}- </Button>- )}- <AssigneeAgentSelector- currentAgentId={agentId}- disabled={pending}- onChange={(id) => id && setAgentId(id)}- >- <span>{agentName || t('directories.coordinator')}</span>- </AssigneeAgentSelector>- {error ? (- <AsyncError- description={error instanceof Error ? error.message : undefined}- error={error}- onRetry={start}- />- ) : null}- </Flexbox>- <ModalFooter>- <Button disabled={pending} onClick={close}>- {t('cancel', { ns: 'common' })}- </Button>- <Button loading={pending} type="primary" onClick={start}>- {t('directories.start')}- </Button>- </ModalFooter>- </>- );-}--export function openProjectTopicModal(options: {- projectId: string;- coordinatorAgentId: string;- directories: ProjectDirectory[];- initialAgentId?: string;- initialDirectoryId?: string;- title: string;-}) {- return createModal({- title: options.title,- content: <StartDirectoryContent {...options} />,- footer: null,- width: 520,- });-}diff --git a/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx b/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsxindex 32d19696955..a5117104f96 100644--- a/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx+++ b/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx@@ -17,7 +17,9 @@ import {import { openAddDirectoryModal } from './AddDirectoryModal';import { openBindDirectoryModal } from './BindDirectoryModal';-import { openProjectTopicModal } from './StartDirectoryModal';+import { canStageDraftOn } from './startProjectTopicDraft';+import { useAgentFixedDeviceId } from './useAgentFixedDeviceId';+import { useStartProjectTopic } from './useStartProjectTopic';/*** A device row restored from the persisted list (`onlineUnknown`) has not been@@ -40,6 +42,8 @@ export function WorkingDirectorySettings({ projectId }: { projectId: string }) {const environmentId = params.get('environment') ?? '';useProjectStore((s) => s.useFetchProjectDetail)(projectId);const project = useCurrentProjectDetail(projectId);+ const startTopic = useStartProjectTopic(projectId);+ const fixedDeviceId = useAgentFixedDeviceId(project?.project.coordinatorAgentId);const environmentsRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);const environments = useProjectEnvironments(projectId);@@ -148,12 +152,11 @@ export function WorkingDirectorySettings({ projectId }: { projectId: string }) {deviceId: directory.deviceId,path: directory.path,})- : openProjectTopicModal({- projectId,- coordinatorAgentId: project!.project.coordinatorAgentId,- directories,- initialDirectoryId: directory.id,- title: t('directories.start'),+ : void startTopic({+ agentId: project!.project.coordinatorAgentId,+ ...(canStageDraftOn(directory, fixedDeviceId)+ ? { directoryId: directory.id }+ : { bindDirectoryId: directory.id }),})}>diff --git a/src/features/Projects/WorkingDirectories/useStartProjectTopic.ts b/src/features/Projects/WorkingDirectories/useStartProjectTopic.tsnew file mode 100644index 00000000000..9a9f59eb176--- /dev/null+++ b/src/features/Projects/WorkingDirectories/useStartProjectTopic.ts@@ -0,0 +1,48 @@+import { toast } from '@lobehub/ui';+import { useTranslation } from 'react-i18next';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';++import { getProjectTopicPath } from '../Layout/navigation';+import { startProjectTopicDraft } from './startProjectTopicDraft';++/**+ * Every project "new topic" goes straight into the agent's conversation, never+ * through a picker. On a directory the agent can run in it opens a blank draft+ * that the first message turns into a topic. Otherwise it creates the topic+ * up front — bound to `bindDirectoryId` when the caller names a directory the+ * draft can't stage on, else conversation-only — since a draft needs both.+ */+export const useStartProjectTopic = (projectId: string | undefined) => {+ const { t } = useTranslation('project');+ const navigate = useWorkspaceAwareNavigate();+ const createProjectTopic = useProjectDirectoryStore((s) => s.createProjectTopic);+ const startDirectoryTopic = useProjectDirectoryStore((s) => s.startTopic);++ return async ({+ agentId,+ bindDirectoryId,+ directoryId,+ }: {+ agentId: string;+ bindDirectoryId?: string;+ directoryId?: string;+ }) => {+ if (!projectId) return;+ if (directoryId) {+ startProjectTopicDraft({ agentId, directoryId, navigate, projectId });+ return;+ }+ try {+ const title = t('directories.untitled');+ const topic = bindDirectoryId+ ? await startDirectoryTopic(bindDirectoryId, agentId, title)+ : await createProjectTopic({ agentId, projectId, title });+ navigate(getProjectTopicPath(projectId, topic.id));+ } catch (error) {+ console.error('Failed to start a project topic', error);+ toast.error(t('overview.sendFailed'));+ }+ };+};diff --git a/src/routes/(main)/project/[projectId]/channels/[channelId]/index.tsx b/src/routes/(main)/project/[projectId]/channels/[channelId]/index.tsxnew file mode 100644index 00000000000..8217871cf31--- /dev/null+++ b/src/routes/(main)/project/[projectId]/channels/[channelId]/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/Channels';diff --git a/src/services/channel.ts b/src/services/channel.tsindex f52ca8ec1a8..461cf38ec3b 100644--- a/src/services/channel.ts+++ b/src/services/channel.ts@@ -38,7 +38,7 @@ class ChannelService {(await lambdaClient.channel.userCandidates.query({ channelId, search })).data;addAgent = (channelId: string, agent: ChannelAgentSelection) =>lambdaClient.channel.addAgent.mutate({ agent, channelId });- create = (input: { agents: ChannelAgentSelection[]; title: string }) =>+ create = (input: { agents: ChannelAgentSelection[]; projectId?: string; title: string }) =>lambdaClient.channel.create.mutate(input);detail = async (params: ChannelViewParams): Promise<ChannelDetail> =>(await lambdaClient.channel.detail.query(params)).data;diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsxindex 08eef77c800..e21d24f62f4 100644--- a/src/spa/router/desktopRouter.sync.test.tsx+++ b/src/spa/router/desktopRouter.sync.test.tsx@@ -203,7 +203,7 @@ describe('desktop router shared definition', () => {});it.each(mainAreaVariants)(- '%s exposes project task, goal, dashboard, and acceptance workspaces',+ '%s exposes project channel, task, goal, dashboard, and acceptance workspaces',(_, factory) => {const projectRoute = factory().find((route) => route.path === 'project/:projectId');const projectIndexRoute = projectRoute?.children?.find((route) => route.index);@@ -214,6 +214,7 @@ describe('desktop router shared definition', () => {expect(projectPaths).toEqual(['topic/:topicId?','conversation/:topicId?',+ 'channels/:channelId','tasks','settings/:section?','goals',@@ -227,6 +228,12 @@ describe('desktop router shared definition', () => {);expect(matches?.at(-1)?.params.section).toBe(section);}+ // A project's Channel opens inside the project, beside its sidebar.+ const channelMatches = matchRoutes(+ createMainAreaRoutes(factory),+ '/project/project-1/channels/chn_1',+ );+ expect(channelMatches?.at(-1)?.params.channelId).toBe('chn_1');// The project root is its home page (composer + overview), not a redirect.expect((projectIndexRoute?.element as ReactElement<{ to?: string }> | undefined)?.props.to,diff --git a/src/spa/router/mobileWorkspaceRoutes.tsx b/src/spa/router/mobileWorkspaceRoutes.tsxindex 32587408ec5..f1aee433016 100644--- a/src/spa/router/mobileWorkspaceRoutes.tsx+++ b/src/spa/router/mobileWorkspaceRoutes.tsx@@ -82,6 +82,12 @@ const projectRoutes: RouteObject[] = [{...projectWorkspaceRoute,children: overlayRoutes(projectWorkspaceRoute.children ?? [], {+ // Like `/channels/*` below: Channels have no mobile layout yet.+ 'channels/:channelId': (route) => ({+ ...route,+ element: redirectElement('..'),+ handle: undefined,+ }),'index': withHandle({mobileShellHeader: true,mobileShellTitle: ProjectMobileShellTitle,diff --git a/src/spa/router/projectWorkspaceRoutes.tsx b/src/spa/router/projectWorkspaceRoutes.tsxindex 1240db08c09..1ba6ed2578a 100644--- a/src/spa/router/projectWorkspaceRoutes.tsx+++ b/src/spa/router/projectWorkspaceRoutes.tsx@@ -2,6 +2,7 @@ import { Navigate, type RouteObject, useLocation, useParams } from 'react-routerimport { goalsRouteMeta } from '@/features/AgentGoals/routeMeta';import { tasksRouteMeta } from '@/features/AgentTasks/routeMeta';+import { channelRouteMeta } from '@/features/Channels/routeMeta';import { dashboardRouteMeta, dashboardsRouteMeta } from '@/features/Dashboard/routeMeta';import {projectConversationRouteMeta,@@ -22,7 +23,7 @@ const LegacyProjectConversationRedirect = () => {};/**- * One project's workspace under `/project/:projectId`: its home, topics, tasks,+ * One project's workspace under `/project/:projectId`: its home, channels, topics, tasks,* settings, goals, dashboards and acceptance. Mounted under the workspace* layout in `desktopRouter.shared.tsx`.*/@@ -47,6 +48,15 @@ export const projectWorkspaceRoute: RouteObject = {path: 'topic/:topicId?',},{ element: <LegacyProjectConversationRedirect />, path: 'conversation/:topicId?' },+ {+ element: dynamicElement(+ () => import('@/routes/(main)/project/[projectId]/channels/[channelId]'),+ 'Desktop > Project Channel',+ { preloadId: 'channels' },+ ),+ handle: { meta: channelRouteMeta },+ path: 'channels/:channelId',+ },{element: dynamicElement(() => import('@/routes/(main)/project/[projectId]/tasks'),diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex fc1e6d2f52b..858685ba95c 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -260,6 +260,11 @@ export interface SystemStatus {*/expandAgentSidebarSectionsByAgent?: Record<string, Record<string, boolean>>;expandInputActionbar?: boolean;+ /**+ * Per-project expanded state of the project sidebar's sections (Channels / Topics), keyed by+ * projectId. Nested booleans for the same `merge` reason as the agent sections above.+ */+ expandProjectSidebarSectionsByProject?: Record<string, Record<string, boolean>>;// which sessionGroup should expandexpandSessionGroupKeys: string[];fileManagerViewMode?: 'list' | 'masonry';diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.tsindex 92d89b148b4..5c43f01876e 100644--- a/src/store/global/selectors/systemStatus.ts+++ b/src/store/global/selectors/systemStatus.ts@@ -115,6 +115,11 @@ const agentSidebarSections =(s: GlobalState): Record<string, boolean> | undefined =>agentId ? s.status.expandAgentSidebarSectionsByAgent?.[agentId] : undefined;+const projectSidebarSections =+ (projectId: string | undefined) =>+ (s: GlobalState): Record<string, boolean> | undefined =>+ projectId ? s.status.expandProjectSidebarSectionsByProject?.[projectId] : undefined;+/** Upper bound of `topic.getTopics`'s `pageSize` input on the server. */export const MAX_TOPIC_PAGE_SIZE = 100;@@ -558,6 +563,7 @@ export const systemStatusSelectors = {taskListViewOptions,sidebarExpandedKeys,agentSidebarSections,+ projectSidebarSections,sidebarItems,sessionGroupKeys,showAgentBuilderPanel,