Skip to content

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

πŸ› fix(project): open a blank draft from every project "+" instead of creating an untitled topic (#21989)

Arvin Xua6e4675e8044
diff --git a/apps/server/src/routers/lambda/__tests__/aiChat.projectTopic.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.projectTopic.test.ts
new file mode 100644
index 00000000000..56ddf11265e
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/aiChat.projectTopic.test.ts
@@ -0,0 +1,82 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MessageModel } from '@/database/models/message';
+import { ProjectModel } from '@/database/models/project';
+import { TopicRepository } from '@/database/repositories/topic';
+import { AiChatService } from '@/server/services/aiChat';
+
+import { aiChatRouter } from '../aiChat';
+
+vi.mock('@/server/routers/lambda/_helpers/resolveContext', () => ({
+ resolveContext: vi.fn(async (input) => ({
+ ...input,
+ agentId: input.agentId ?? null,
+ sessionId: input.sessionId ?? null,
+ })),
+}));
+vi.mock('@/database/models/agent');
+vi.mock('@/database/models/message');
+vi.mock('@/database/models/project');
+vi.mock('@/database/models/thread');
+vi.mock('@/database/repositories/topic');
+vi.mock('@/server/services/aiChat');
+vi.mock('@/server/services/file', () => ({ FileService: vi.fn() }));
+vi.mock('@/server/modules/ModelRuntime', () => ({ initModelRuntimeFromDB: vi.fn() }));
+
+const createTopic = vi.fn();
+const findProject = vi.fn();
+
+const send = () =>
+ aiChatRouter.createCaller({ userId: 'u1' } as any).sendMessageInServer({
+ newAssistantMessage: { model: 'gpt-4o', provider: 'openai' },
+ newTopic: { projectId: 'prj_1', title: 'T' },
+ newUserMessage: { content: 'hi' },
+ sessionId: 's1',
+ } as any);
+
+describe('aiChatRouter.sendMessageInServer in a project', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ createTopic.mockResolvedValue({ id: 't1' });
+ vi.mocked(TopicRepository).mockImplementation(function () {
+ return { create: createTopic } as any;
+ });
+ vi.mocked(ProjectModel).mockImplementation(function () {
+ return { findById: findProject } as any;
+ });
+ vi.mocked(MessageModel).mockImplementation(function () {
+ return {
+ createUserAndAssistantMessages: vi.fn(async () => ({
+ assistantMessage: { id: 'm-assistant' },
+ userMessage: { id: 'm-user' },
+ })),
+ } as any;
+ });
+ vi.mocked(AiChatService).mockImplementation(function () {
+ return {
+ getMessagesAndTopics: vi.fn().mockResolvedValue({ messages: [], topics: undefined }),
+ } as any;
+ });
+ });
+
+ /** @example User report: a project "+" with no runnable directory left an untitled topic behind. */
+ it('creates the first-send topic inside the project the blank draft was staged in', async () => {
+ findProject.mockResolvedValue({ id: 'prj_1' });
+
+ await send();
+
+ expect(findProject).toHaveBeenCalledWith('prj_1');
+ expect(createTopic).toHaveBeenCalledWith(
+ expect.objectContaining({ projectId: 'prj_1', title: 'T' }),
+ undefined,
+ );
+ });
+
+ it('refuses a project the user cannot read', async () => {
+ findProject.mockResolvedValue(undefined);
+
+ await expect(send()).rejects.toThrow('Project not found');
+ expect(createTopic).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.ts
index 762fd0bd722..f22180fb569 100644
--- a/apps/server/src/routers/lambda/aiChat.ts
+++ b/apps/server/src/routers/lambda/aiChat.ts
@@ -22,6 +22,7 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceA
import { LOADING_FLAT } from '@/const/message';
import { AgentModel } from '@/database/models/agent';
import { MessageModel } from '@/database/models/message';
+import { ProjectModel } from '@/database/models/project';
import { ThreadModel } from '@/database/models/thread';
import { TopicRepository } from '@/database/repositories/topic';
import { router } from '@/libs/trpc/lambda';
@@ -308,6 +309,14 @@ export const aiChatRouter = router({
// create topic if there should be a new topic
if (input.newTopic) {
log('creating new topic with title: %s', input.newTopic.title);
+ const { projectId } = input.newTopic;
+ if (
+ projectId &&
+ !(await new ProjectModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined).findById(
+ projectId,
+ ))
+ )
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });
const topicItem = await runTimedStage(
timingContext,
'lambda.aiChat.topic.create',
@@ -318,6 +327,7 @@ export const aiChatRouter = router({
messages: input.newTopic!.topicMessageIds,
metadata: input.newTopic!.metadata,
model: input.newTopic!.model,
+ projectId,
provider: input.newTopic!.provider,
sessionId,
title: input.newTopic!.title,
diff --git a/apps/server/src/routers/lambda/topic/create.test.ts b/apps/server/src/routers/lambda/topic/create.test.ts
index 62bb31a61ad..e8b3d3cad30 100644
--- a/apps/server/src/routers/lambda/topic/create.test.ts
+++ b/apps/server/src/routers/lambda/topic/create.test.ts
@@ -8,12 +8,29 @@ vi.mock('@/database/core/db-adaptor', () => ({
}));
const mockTopicBatchCreate = vi.fn();
+const mockTopicCreate = vi.fn();
vi.mock('@/database/repositories/topic', () => ({
TopicRepository: vi.fn(function () {
- return { batchCreate: mockTopicBatchCreate };
+ return { batchCreate: mockTopicBatchCreate, create: mockTopicCreate };
}),
}));
+const mockProjectFindById = vi.fn();
+vi.mock('@/database/models/project', () => ({
+ ProjectModel: vi.fn(function () {
+ return { findById: mockProjectFindById };
+ }),
+}));
+
+vi.mock('../_helpers/conversationResourceGuard', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ assertCanUseConversationTargets: vi.fn(),
+}));
+vi.mock('../_helpers/shareVisitorTargetGuard', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ assertCreatorMessageTargets: vi.fn(),
+}));
+
let inFlight = 0;
let maxInFlight = 0;
vi.mock('../_helpers/resolveContext', async (importOriginal) => ({
@@ -57,3 +74,31 @@ describe('topic.batchCreateTopics', () => {
expect(maxInFlight).toBeLessThanOrEqual(5);
});
});
+
+describe('topic.createTopic', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockTopicCreate.mockResolvedValue({ id: 'tpc_new' });
+ });
+
+ /** @example User report: a project "+" with no runnable directory left an untitled topic behind. */
+ it('creates a conversation-only topic inside a project the user can read', async () => {
+ mockProjectFindById.mockResolvedValue({ id: 'prj_1' });
+
+ await caller().createTopic({ agentId: 'agent-1', projectId: 'prj_1', title: 'Hi' });
+
+ expect(mockProjectFindById).toHaveBeenCalledWith('prj_1');
+ expect(mockTopicCreate).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agent-1', projectId: 'prj_1', title: 'Hi' }),
+ );
+ });
+
+ it('refuses a project the user cannot read', async () => {
+ mockProjectFindById.mockResolvedValue(undefined);
+
+ await expect(
+ caller().createTopic({ agentId: 'agent-1', projectId: 'prj_other', title: 'Hi' }),
+ ).rejects.toThrow('Project not found');
+ expect(mockTopicCreate).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/topic/create.ts b/apps/server/src/routers/lambda/topic/create.ts
index c86bb438986..33e69f339fb 100644
--- a/apps/server/src/routers/lambda/topic/create.ts
+++ b/apps/server/src/routers/lambda/topic/create.ts
@@ -8,6 +8,7 @@ import pMap from 'p-map';
import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { ProjectModel } from '@/database/models/project';
import { ProjectWorkingDirectoryModel } from '@/database/models/projectWorkingDirectory';
import { router } from '@/libs/trpc/lambda';
import { type BatchTaskResult } from '@/types/service';
@@ -155,6 +156,9 @@ export const createRouter = router({
// The topic's pinned model snapshot, persisted to the top-level
// `topics.model`/`provider` columns (config source of truth).
model: z.string().optional(),
+ // Bind the new row to a project, conversation-only β€” a project "+"
+ // with no directory the agent can run in. A directory wins.
+ projectId: z.string().optional(),
// Bind the new row to a project working directory. Resolved and
// pinned below, mirroring `projectWorkingDirectory.startTopic`.
projectWorkingDirectoryId: z.string().optional(),
@@ -165,7 +169,7 @@ export const createRouter = router({
.extend(basicContextSchema.shape),
)
.mutation(async ({ input, ctx }) => {
- const { agentId, projectWorkingDirectoryId, ...rest } = input;
+ const { agentId, projectId, projectWorkingDirectoryId, ...rest } = input;
const resolved = await resolveContextWithAgentId(
{ agentId, groupId: rest.groupId, sessionId: rest.sessionId },
ctx.serverDB,
@@ -200,8 +204,19 @@ export const createRouter = router({
})
: undefined;
+ // Read access is enough: everyone who can read a project collaborates in it.
+ if (
+ !directory &&
+ projectId &&
+ !(await new ProjectModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined).findById(
+ projectId,
+ ))
+ )
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });
+
const data = await ctx.topicRepo.create({
...rest,
+ ...(!directory && projectId && { projectId }),
agentId: resolved.agentId,
sessionId: resolved.sessionId,
...(directory
diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.ts
index b6a5e783cf4..a9a73dfc1e3 100644
--- a/packages/types/src/aiChat.ts
+++ b/packages/types/src/aiChat.ts
@@ -104,6 +104,8 @@ export interface SendMessageServerParams {
metadata?: ChatTopicMetadata;
/** Pinned model snapshot for the new topic (top-level `topics.model` column). */
model?: string;
+ /** Project the topic is born in, conversation-only (a project "+" with no directory). */
+ projectId?: string;
provider?: string;
title?: string;
topicMessageIds?: string[];
@@ -190,6 +192,7 @@ export const AiSendMessageServerSchema = z.object({
id: clientEntityId('topics'),
metadata: z.custom<ChatTopicMetadata>().optional(),
model: z.string().optional(),
+ projectId: z.string().optional(),
provider: z.string().optional(),
title: z.string().optional(),
topicMessageIds: z.array(z.string()).optional(),
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index abca0e423d2..4fc2e439254 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -823,6 +823,12 @@ export interface CreateTopicParams {
metadata?: ChatTopicMetadata;
/** Pinned model snapshot for the new topic (see `ChatTopic.model`). */
model?: string;
+ /**
+ * Bind the new topic to a project without a directory (conversation-only).
+ * Ignored when `projectWorkingDirectoryId` resolves β€” the directory carries
+ * its own project.
+ */
+ projectId?: string;
/**
* Bind the new topic to a project working directory. The server resolves the
* directory and pins its project, device and paths onto the topic β€” the same
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx
index 5274bb76770..6abef8193cc 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx
@@ -297,7 +297,7 @@ describe('TopicByAgentGroupItem', () => {
);
});
- it('goes straight into a conversation-only topic for an agent fixed to a non-device target', async () => {
+ it('opens a conversation-only draft for an agent fixed to a non-device target', () => {
subGroupModes[GROUP_ID] = 'byDevice';
directories[0] = { ...directories[0], ...runnable('ins-mac') };
directories[1] = { ...directories[1], ...runnable('ins-linux') };
@@ -308,27 +308,30 @@ describe('TopicByAgentGroupItem', () => {
fireEvent.click(screen.getByRole('button', { name: 'sidebar.newConversation' }));
- expect(startProjectTopicDraft).not.toHaveBeenCalled();
- await expect
- .poll(() => navigate.mock.calls.at(-1)?.[0])
- .toBe('/project/project-1/topic/tpc_new');
+ expect(startProjectTopicDraft).toHaveBeenCalledWith({
+ agentId: 'agt_acc_merge_alpha',
+ directoryId: undefined,
+ navigate,
+ projectId: 'project-1',
+ });
+ expect(createProjectTopic).not.toHaveBeenCalled();
});
- /** @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 () => {
+ /** @example User report: the project "+" left an empty "ζœͺε‘½εθ―ι’˜" row behind before anything was sent. */
+ it('opens a blank conversation-only draft when the project has no runnable directory', () => {
+ // ROOT CAUSE: the draft could only be staged on a directory, so a project
+ // without a runnable one fell back to creating an untitled topic up front.
renderGroup();
fireEvent.click(screen.getByRole('button', { name: 'sidebar.newConversation' }));
- expect(startProjectTopicDraft).not.toHaveBeenCalled();
- expect(createProjectTopic).toHaveBeenCalledWith({
+ expect(startProjectTopicDraft).toHaveBeenCalledWith({
agentId: 'agt_acc_merge_alpha',
+ directoryId: undefined,
+ navigate,
projectId: 'project-1',
- title: 'directories.untitled',
});
- await expect
- .poll(() => navigate.mock.calls.at(-1)?.[0])
- .toBe('/project/project-1/topic/tpc_new');
+ expect(createProjectTopic).not.toHaveBeenCalled();
});
/** @example User report: the project sidebar hid devices that had no topics yet. */
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx
index 486cef292b5..017373940ec 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx
@@ -119,7 +119,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {
// the first directory it can run in when there is one.
const handleAddTopic = (initialDirectoryId?: string) => {
if (!scope || !agentId) return;
- void startTopic({ agentId, directoryId: initialDirectoryId ?? startDirectories?.[0]?.id });
+ startTopic({ agentId, directoryId: initialDirectoryId ?? startDirectories?.[0]?.id });
};
// The agent bucket already sits inside one project, so its rows skip the
diff --git a/src/features/Projects/Conversation/useProjectConversation.test.ts b/src/features/Projects/Conversation/useProjectConversation.test.ts
index f5127959c22..f18bad12f6b 100644
--- a/src/features/Projects/Conversation/useProjectConversation.test.ts
+++ b/src/features/Projects/Conversation/useProjectConversation.test.ts
@@ -3,6 +3,7 @@ import { createElement, Fragment, type ReactNode } from 'react';
import { MemoryRouter, Route, Routes } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { useChatStore } from '@/store/chat';
import { useProjectStore } from '@/store/project';
import { type ProjectListItem } from '@/store/project';
@@ -135,4 +136,17 @@ describe('useProjectConversation', () => {
expect(screen.queryByText('Project not found or access denied')).toBeNull();
expect(container.querySelector('[aria-busy]')).not.toBeNull();
});
+
+ /** @example User report: a project "+" with no runnable directory created an untitled topic up front. */
+ it('opens and stages a conversation-only draft that carries no directory', () => {
+ const { result } = renderHook(() => useProjectConversation(), {
+ wrapper: wrapper('/project/launch/topic?agent=agt_coord'),
+ });
+
+ expect(result.current.fallback).toBeUndefined();
+ expect(useChatStore.getState().pendingNewTopicDirectory).toEqual({
+ agentId: 'agt_coord',
+ projectId: 'prj_launch',
+ });
+ });
});
diff --git a/src/features/Projects/Conversation/useProjectConversation.tsx b/src/features/Projects/Conversation/useProjectConversation.tsx
index c5e8693911b..63d5636bc83 100644
--- a/src/features/Projects/Conversation/useProjectConversation.tsx
+++ b/src/features/Projects/Conversation/useProjectConversation.tsx
@@ -11,6 +11,7 @@ import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
+import { type PendingNewTopicDirectory } from '@/store/chat/slices/topic/initialState';
import { useCurrentProjectDetail, useProjectIdByRef, useProjectStore } from '@/store/project';
import {
useProjectDirectories,
@@ -60,13 +61,17 @@ export const useProjectConversation = () => {
const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectRefId);
const directories = useProjectDirectories(projectRefId);
const directoryIds = useMemo(() => new Set(directories.map((d) => d.id)), [directories]);
- const draft = useMemo(
- () =>
- draftAgentParam && draftDirectoryParam && directoryIds.has(draftDirectoryParam)
+ // A draft without a directory is conversation-only in the project; it needs
+ // the real project id (the param may be a slug) before it can be staged.
+ const draftProjectId = projectConfirmed ? projectRefId : undefined;
+ const draft = useMemo<PendingNewTopicDirectory | undefined>(() => {
+ if (!draftAgentParam) return;
+ if (draftDirectoryParam)
+ return directoryIds.has(draftDirectoryParam)
? { agentId: draftAgentParam, projectWorkingDirectoryId: draftDirectoryParam }
- : undefined,
- [draftAgentParam, draftDirectoryParam, directoryIds],
- );
+ : undefined;
+ return draftProjectId ? { agentId: draftAgentParam, projectId: draftProjectId } : undefined;
+ }, [draftAgentParam, draftDirectoryParam, directoryIds, draftProjectId]);
const draftAgentId = draft?.agentId;
const restageDraft = useProjectDraftStaging(draft, directoryIds);
const chatAgentId = useChatStore((s) => s.activeAgentId);
@@ -136,11 +141,12 @@ export const useProjectConversation = () => {
<AsyncError error={topicsRequest.error} variant="page" onRetry={topicsRequest.revalidate} />
);
else if (!topicId && !draftAgentId) {
- // A draft's directory list may still be loading; wait for it rather than
- // sending the draft away. Other new project conversations start from the
- // project home composer.
+ // A draft's directory list (or, without a directory, its project) may still
+ // be loading; wait for it rather than sending the draft away. Other new
+ // project conversations start from the project home composer.
fallback =
- draftAgentParam && !directoriesRequest.hasData ? (
+ draftAgentParam &&
+ (draftDirectoryParam ? !directoriesRequest.hasData : !draftProjectId && !detailSWR.error) ? (
loading
) : (
<Navigate replace relative="path" to=".." />
diff --git a/src/features/Projects/Conversation/useProjectDraftStaging.ts b/src/features/Projects/Conversation/useProjectDraftStaging.ts
index 5b3eff54fae..5eacf6f4037 100644
--- a/src/features/Projects/Conversation/useProjectDraftStaging.ts
+++ b/src/features/Projects/Conversation/useProjectDraftStaging.ts
@@ -1,14 +1,12 @@
import { useCallback, useEffect, useRef } from 'react';
import { useChatStore } from '@/store/chat';
-
-interface Draft {
- agentId: string;
- projectWorkingDirectoryId: string;
-}
+import { type PendingNewTopicDirectory as Draft } from '@/store/chat/slices/topic/initialState';
const sameDraft = (a: Draft | undefined, b: Draft | undefined) =>
- a?.agentId === b?.agentId && a?.projectWorkingDirectoryId === b?.projectWorkingDirectoryId;
+ a?.agentId === b?.agentId &&
+ a?.projectWorkingDirectoryId === b?.projectWorkingDirectoryId &&
+ a?.projectId === b?.projectId;
/**
* Keep this pane's blank draft staged for the send.
@@ -38,7 +36,7 @@ export const useProjectDraftStaging = (
useEffect(() => {
ownRef.current = draft;
restage();
- }, [draft?.agentId, draft?.projectWorkingDirectoryId, restage]);
+ }, [draft?.agentId, draft?.projectWorkingDirectoryId, draft?.projectId, restage]);
useEffect(
() =>
@@ -50,6 +48,7 @@ export const useProjectDraftStaging = (
own &&
pending &&
pending.agentId === own.agentId &&
+ !!pending.projectWorkingDirectoryId &&
directoryIdsRef.current.has(pending.projectWorkingDirectoryId)
)
ownRef.current = pending;
diff --git a/src/features/Projects/Layout/navigation.ts b/src/features/Projects/Layout/navigation.ts
index 07bbfc52d16..ef1642a7d4f 100644
--- a/src/features/Projects/Layout/navigation.ts
+++ b/src/features/Projects/Layout/navigation.ts
@@ -6,12 +6,15 @@ export const getProjectTopicPath = (projectId: string, topicId?: string) =>
topicId ? `/project/${projectId}/topic/${topicId}` : `/project/${projectId}/topic`;
/**
- * A blank project conversation a sidebar "+" opened for one agent on one
- * directory. The draft lives in the route so it stays with its own pane (and
- * survives a reload); nothing is created until its first message.
+ * A blank project conversation a sidebar "+" opened for one agent, on one
+ * directory when the agent can run in one (else conversation-only). The draft
+ * lives in the route so it stays with its own pane (and survives a reload);
+ * nothing is created until its first message.
*/
-export const getProjectDraftPath = (projectId: string, agentId: string, directoryId: string) =>
- `${getProjectTopicPath(projectId)}?${new URLSearchParams({ agent: agentId, dir: directoryId })}`;
+export const getProjectDraftPath = (projectId: string, agentId: string, directoryId?: string) =>
+ `${getProjectTopicPath(projectId)}?${new URLSearchParams(
+ directoryId ? { agent: agentId, dir: directoryId } : { agent: agentId },
+ )}`;
export const getProjectLibraryPath = (projectId: string, libraryId: string) =>
`/project/${projectId}/library/${libraryId}`;
diff --git a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx b/src/features/Projects/WorkingDirectories/SidebarTopics.tsx
index eea5ed483af..1e6165626a9 100644
--- a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx
+++ b/src/features/Projects/WorkingDirectories/SidebarTopics.tsx
@@ -126,7 +126,7 @@ function ProjectTopicList({ projectId, coordinatorAgentId, itemKey }: ProjectDir
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({
+ startTopic({
agentId: coordinatorAgentId,
directoryId: directories.find((d) => canStageDraftOn(d, fixedDeviceId))?.id,
})
diff --git a/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx b/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx
index a5117104f96..5dd28317e22 100644
--- a/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx
+++ b/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx
@@ -17,9 +17,7 @@ import {
import { openAddDirectoryModal } from './AddDirectoryModal';
import { openBindDirectoryModal } from './BindDirectoryModal';
-import { canStageDraftOn } from './startProjectTopicDraft';
-import { useAgentFixedDeviceId } from './useAgentFixedDeviceId';
-import { useStartProjectTopic } from './useStartProjectTopic';
+import { useStartDirectoryConversation } from './useStartProjectTopic';
/**
* A device row restored from the persisted list (`onlineUnknown`) has not been
@@ -42,8 +40,10 @@ 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 startConversation = useStartDirectoryConversation(
+ projectId,
+ project?.project.coordinatorAgentId,
+ );
const environmentsRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);
const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);
const environments = useProjectEnvironments(projectId);
@@ -152,12 +152,7 @@ export function WorkingDirectorySettings({ projectId }: { projectId: string }) {
deviceId: directory.deviceId,
path: directory.path,
})
- : void startTopic({
- agentId: project!.project.coordinatorAgentId,
- ...(canStageDraftOn(directory, fixedDeviceId)
- ? { directoryId: directory.id }
- : { bindDirectoryId: directory.id }),
- })
+ : startConversation(directory)
}
>
{t(
diff --git a/src/features/Projects/WorkingDirectories/startProjectTopicDraft.test.ts b/src/features/Projects/WorkingDirectories/startProjectTopicDraft.test.ts
index a284113137d..634b8298900 100644
--- a/src/features/Projects/WorkingDirectories/startProjectTopicDraft.test.ts
+++ b/src/features/Projects/WorkingDirectories/startProjectTopicDraft.test.ts
@@ -80,4 +80,16 @@ describe('startProjectTopicDraft', () => {
// The draft rides in the route so it stays with the pane that opened it.
expect(navigate).toHaveBeenCalledWith('/project/prj_1/topic?agent=agt_1&dir=pwd_1');
});
+
+ it('stages the project alone for a conversation-only draft', () => {
+ const navigate = vi.fn();
+
+ startProjectTopicDraft({ agentId: 'agt_1', navigate, projectId: 'prj_1' });
+
+ expect(chat.setPendingNewTopicDirectory).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ projectId: 'prj_1',
+ });
+ expect(navigate).toHaveBeenCalledWith('/project/prj_1/topic?agent=agt_1');
+ });
});
diff --git a/src/features/Projects/WorkingDirectories/startProjectTopicDraft.ts b/src/features/Projects/WorkingDirectories/startProjectTopicDraft.ts
index 568cddbc9fd..e1e62906982 100644
--- a/src/features/Projects/WorkingDirectories/startProjectTopicDraft.ts
+++ b/src/features/Projects/WorkingDirectories/startProjectTopicDraft.ts
@@ -31,10 +31,10 @@ export const canStageDraftOn = (
(fixedDeviceId === undefined || (!!fixedDeviceId && directory.deviceId === fixedDeviceId));
/**
- * Open a blank project conversation on one directory, the same habit as an
- * agent's "+": no topic row is created here. The staged directory pins the
- * agent and device for the composer, and the first message creates the topic
- * inside it (see `pendingNewTopicDirectory`).
+ * Open a blank project conversation, the same habit as an agent's "+": no
+ * topic row is created here. A staged directory pins the agent and device for
+ * the composer; without one the project alone is staged. Either way the first
+ * message creates the topic inside it (see `pendingNewTopicDirectory`).
*/
export const startProjectTopicDraft = ({
agentId,
@@ -43,7 +43,8 @@ export const startProjectTopicDraft = ({
projectId,
}: {
agentId: string;
- directoryId: string;
+ /** Omitted when the agent has no directory it can run in: conversation-only. */
+ directoryId?: string;
navigate: (path: string) => void;
projectId: string;
}) => {
@@ -54,6 +55,8 @@ export const startProjectTopicDraft = ({
clearNewKeyContext: { agentId, groupId: null },
skipRefreshMessage: true,
});
- chat.setPendingNewTopicDirectory({ agentId, projectWorkingDirectoryId: directoryId });
+ chat.setPendingNewTopicDirectory(
+ directoryId ? { agentId, projectWorkingDirectoryId: directoryId } : { agentId, projectId },
+ );
navigate(getProjectDraftPath(projectId, agentId, directoryId));
};
diff --git a/src/features/Projects/WorkingDirectories/useStartProjectTopic.test.ts b/src/features/Projects/WorkingDirectories/useStartProjectTopic.test.ts
new file mode 100644
index 00000000000..9168ff87405
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/useStartProjectTopic.test.ts
@@ -0,0 +1,68 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useStartDirectoryConversation } from './useStartProjectTopic';
+
+const { navigate, startProjectTopicDraft } = vi.hoisted(() => ({
+ navigate: vi.fn(),
+ startProjectTopicDraft: vi.fn(),
+}));
+
+let fixedDeviceId: string | null | undefined;
+
+vi.mock('./startProjectTopicDraft', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ startProjectTopicDraft,
+}));
+vi.mock('./useAgentFixedDeviceId', () => ({ useAgentFixedDeviceId: () => fixedDeviceId }));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => navigate,
+}));
+
+const directory = {
+ deviceId: 'device-1',
+ environmentId: 'env-1',
+ id: 'pwd_1',
+ instanceId: 'ins-1',
+ permission: 'readWrite',
+};
+
+const start = (dir: typeof directory) =>
+ renderHook(() => useStartDirectoryConversation('prj_1', 'agt_lead')).result.current(dir);
+
+describe('useStartDirectoryConversation', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ fixedDeviceId = undefined;
+ });
+
+ it('opens a blank draft on a directory the agent can run in', () => {
+ start(directory);
+
+ expect(startProjectTopicDraft).toHaveBeenCalledWith({
+ agentId: 'agt_lead',
+ directoryId: 'pwd_1',
+ navigate,
+ projectId: 'prj_1',
+ });
+ });
+
+ /** @example User report: the settings "start conversation" left an empty untitled topic behind. */
+ it('opens a conversation-only draft instead of creating a topic on a directory the agent cannot use', () => {
+ // ROOT CAUSE: a directory a draft can't stage on (read-only, or on another
+ // device than the agent is fixed to) fell back to creating a bound topic
+ // up front.
+ fixedDeviceId = 'device-2';
+ start(directory);
+ start({ ...directory, permission: 'read' });
+
+ expect(startProjectTopicDraft).toHaveBeenCalledTimes(2);
+ for (const [params] of startProjectTopicDraft.mock.calls)
+ expect(params).toEqual({
+ agentId: 'agt_lead',
+ directoryId: undefined,
+ navigate,
+ projectId: 'prj_1',
+ });
+ });
+});
diff --git a/src/features/Projects/WorkingDirectories/useStartProjectTopic.ts b/src/features/Projects/WorkingDirectories/useStartProjectTopic.ts
index 9a9f59eb176..045a633c987 100644
--- a/src/features/Projects/WorkingDirectories/useStartProjectTopic.ts
+++ b/src/features/Projects/WorkingDirectories/useStartProjectTopic.ts
@@ -1,48 +1,39 @@
-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';
+import { canStageDraftOn, startProjectTopicDraft } from './startProjectTopicDraft';
+import { useAgentFixedDeviceId } from './useAgentFixedDeviceId';
/**
* 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.
+ * through a picker, and never creates a row up front. It opens a blank draft β€”
+ * on `directoryId` when the agent can run there, else conversation-only in the
+ * project β€” that the first message turns into a topic.
*/
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;
- }) => {
+ return ({ agentId, directoryId }: { agentId: 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'));
- }
+ startProjectTopicDraft({ agentId, directoryId, navigate, projectId });
+ };
+};
+
+/**
+ * "Start a conversation" on one project directory: a blank draft on it when
+ * `agentId` can run there, else a conversation-only draft in the project.
+ */
+export const useStartDirectoryConversation = (
+ projectId: string | undefined,
+ agentId: string | undefined,
+) => {
+ const startTopic = useStartProjectTopic(projectId);
+ const fixedDeviceId = useAgentFixedDeviceId(agentId);
+
+ return (directory: Parameters<typeof canStageDraftOn>[0] & { id: string }) => {
+ if (!agentId) return;
+ startTopic({
+ agentId,
+ directoryId: canStageDraftOn(directory, fixedDeviceId) ? directory.id : undefined,
+ });
};
};
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts
index 411131be12c..2d0a470dfaf 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.projectCwd.test.ts
@@ -3,6 +3,7 @@ import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { agentService } from '@/services/agent';
+import { aiChatService } from '@/services/aiChat';
import { getPendingTopicRepos, setPendingTopicRepos } from '@/store/chat/pendingTopicRepos';
import { type ProjectDirectory, useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
import { getSessionStoreState } from '@/store/session';
@@ -269,3 +270,73 @@ describe('sendMessage in a project directory', () => {
);
});
});
+
+describe('sendMessage in a project without a directory', () => {
+ // Regression (user report): a project "+" with no runnable directory created
+ // an empty "untitled" topic up front. The blank draft now stages the project
+ // alone, and the first send creates the topic conversation-only inside it.
+ it('binds the new gateway topic to the staged project without routing to a device', async () => {
+ setupMockSelectors({ agentConfig: { agencyConfig: { executionTarget: 'cloud' } } });
+ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({ topicId: 'tpc_new' });
+ const agentId = TEST_IDS.SESSION_ID;
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: undefined,
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ pendingNewTopicDirectory: { agentId, projectId: 'prj-1' },
+ });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ await act(async () => {
+ await result.current.sendMessage({
+ context: { agentId, threadId: null, topicId: null },
+ message: 'Start in the project',
+ });
+ });
+
+ const params = executeGatewayAgentSpy.mock.calls[0][0];
+ expect(params.projectId).toBe('prj-1');
+ expect(params.projectWorkingDirectoryId).toBeUndefined();
+ const optimisticRow = Object.values(result.current.topicDataMap)
+ .flatMap((data) => data.items)
+ .find((topic) => topic.id === params.optimisticTopic.id);
+ expect(optimisticRow?.projectId).toBe('prj-1');
+ expect(optimisticRow?.projectWorkingDirectoryId).toBeUndefined();
+ });
+
+ it('creates the client-runtime topic inside the staged project', async () => {
+ setupMockSelectors({ agentConfig: {} });
+ const agentId = TEST_IDS.SESSION_ID;
+ const sendMessageInServerSpy = vi
+ .spyOn(aiChatService, 'sendMessageInServer')
+ .mockRejectedValue(new Error('stop after the request is built'));
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: undefined,
+ isGatewayModeEnabled: () => false,
+ pendingNewTopicDirectory: { agentId, projectId: 'prj-1' },
+ });
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ await act(async () => {
+ await result.current.sendMessage({
+ context: { agentId, threadId: null, topicId: null },
+ message: 'Start in the project',
+ });
+ });
+
+ expect(sendMessageInServerSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ newTopic: expect.objectContaining({ projectId: 'prj-1' }) }),
+ expect.any(AbortController),
+ );
+ // The refused first send hands the project back to the blank draft.
+ expect(result.current.pendingNewTopicDirectory).toEqual({ agentId, projectId: 'prj-1' });
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
index e0aa2e7b7fd..31e7022808e 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
@@ -435,25 +435,24 @@ export class ConversationLifecycleActionImpl {
const boundTopic = context.topicId
? topicSelectors.getTopicById(context.topicId)(this.#get())
: undefined;
- // A blank conversation opened from a project group's "+" runs in the
- // directory it staged; the gateway transport has the server bind the topic.
+ // A blank conversation opened from a project "+" runs in the directory (or
+ // just the project) it staged; the new topic is born bound to it.
const pendingDirectory = this.#get().pendingNewTopicDirectory;
- const stagedDirectoryId =
- !context.topicId &&
- !context.isolatedTopic &&
- !context.groupId &&
- !directMentionRoute &&
- pendingDirectory?.agentId === ownerAgentId
- ? pendingDirectory.projectWorkingDirectoryId
- : undefined;
const projectRun = await resolveProjectDirectoryRun({
agencyConfig,
boundDirectoryId: boundTopic?.projectWorkingDirectoryId,
isGatewayMode,
- stagedDirectoryId,
+ staged:
+ !context.topicId &&
+ !context.isolatedTopic &&
+ !context.groupId &&
+ !directMentionRoute &&
+ pendingDirectory?.agentId === ownerAgentId
+ ? pendingDirectory
+ : undefined,
});
({ agencyConfig } = projectRun);
- const { stagedDirectory } = projectRun;
+ const { newTopicProject, stagedDirectory, stagedProjectId } = projectRun;
if (stagedDirectory) consumePendingTopicRepos(ownerAgentId); // a cloud repo pick conflicts
// Legacy agents may only carry `model: '<cli-type>'`. Keep gateway routing
@@ -1087,10 +1086,7 @@ export class ConversationLifecycleActionImpl {
id: mintedTopicId,
...newTopicModelSnapshot,
// Shown under its project group from the first frame.
- ...(stagedDirectory && {
- projectId: stagedDirectory.projectId,
- projectWorkingDirectoryId: stagedDirectory.id,
- }),
+ ...newTopicProject,
...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),
title: newTopicTitle,
},
@@ -1376,7 +1372,7 @@ export class ConversationLifecycleActionImpl {
void this.#get().switchTopic(null, { skipRefreshMessage: true });
// Adopting the minted topic consumed the staging; the topic never came
// to be, so the blank conversation still belongs to that directory.
- if (stagedDirectory) this.#get().setPendingNewTopicDirectory(pendingDirectory);
+ if (newTopicProject) this.#get().setPendingNewTopicDirectory(pendingDirectory);
}
this.#get().internal_dispatchTopic(
{ ...optimisticTopicScope, type: 'deleteTopic', id: optimisticTopic.id },
@@ -1449,6 +1445,7 @@ export class ConversationLifecycleActionImpl {
id: optimisticTopic?.id,
metadata: optimisticTopicMetadata,
...newTopicModelSnapshot,
+ projectId: stagedProjectId,
title: newTopicTitle,
topicMessageIds: messages.map((m) => m.id),
}
@@ -1809,7 +1806,7 @@ export class ConversationLifecycleActionImpl {
clientOperations,
replacesOperationId: replaceableGatewayOperationId,
optimisticTopic,
- projectWorkingDirectoryId: stagedDirectory?.id,
+ ...newTopicProject,
// Forward @-mentioned tool ids so the server runtime enables them for
// this run β€” the gateway/server path otherwise never sees the mention
// selection (only the client runtime did). Omit when empty.
@@ -1998,6 +1995,7 @@ export class ConversationLifecycleActionImpl {
// ever write the cwd back (the server-side binding only exists
// on the gateway path).
metadata: optimisticTopicMetadata,
+ projectId: stagedProjectId,
topicMessageIds: forceNewTopicFromExisting ? [] : messages.map((m) => m.id),
title: newTopicTitle,
}
diff --git a/src/store/chat/slices/agentRun/actions/entries/resolveProjectDirectoryRun.ts b/src/store/chat/slices/agentRun/actions/entries/resolveProjectDirectoryRun.ts
index 56eb6ea4849..36fee82de70 100644
--- a/src/store/chat/slices/agentRun/actions/entries/resolveProjectDirectoryRun.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/resolveProjectDirectoryRun.ts
@@ -1,4 +1,5 @@
import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
+import { type PendingNewTopicDirectory } from '@/store/chat/slices/topic/initialState';
import { findProjectDirectory } from '@/store/projectWorkingDirectory';
interface DeviceRouting {
@@ -15,16 +16,29 @@ interface DeviceRouting {
*
* `stagedDirectory` is set only for the staged case: the caller binds the new
* topic to it, and hands it back to the blank view if that topic never lands.
+ * A draft staged on a project without a directory only yields
+ * `stagedProjectId`: the topic is born conversation-only in that project and
+ * runs wherever the agent itself routes. `newTopicProject` is what the new
+ * topic is bound to in either staged case.
*/
export const resolveProjectDirectoryRun = async <T extends DeviceRouting>(params: {
agencyConfig: T | undefined;
boundDirectoryId: string | null | undefined;
isGatewayMode: boolean;
- stagedDirectoryId: string | undefined;
+ staged: PendingNewTopicDirectory | undefined;
}) => {
- const { agencyConfig, boundDirectoryId, isGatewayMode, stagedDirectoryId } = params;
+ const { agencyConfig, boundDirectoryId, isGatewayMode, staged } = params;
+ const stagedDirectoryId = staged?.projectWorkingDirectoryId;
const directoryId = boundDirectoryId ?? stagedDirectoryId;
- if (!directoryId) return { agencyConfig, stagedDirectory: undefined };
+ if (!directoryId) {
+ const stagedProjectId = staged?.projectId;
+ return {
+ agencyConfig,
+ newTopicProject: stagedProjectId ? { projectId: stagedProjectId } : undefined,
+ stagedDirectory: undefined,
+ stagedProjectId,
+ };
+ }
// The sidebar's directory replica already holds the row; read it locally
// so the optimistic pair is not held behind a network round trip. The
@@ -46,6 +60,10 @@ export const resolveProjectDirectoryRun = async <T extends DeviceRouting>(params
boundDeviceId: directory.deviceId,
executionTarget: 'device',
} as T,
+ newTopicProject: stagedDirectoryId
+ ? { projectId: directory.projectId, projectWorkingDirectoryId: directory.id }
+ : undefined,
stagedDirectory: stagedDirectoryId ? directory : undefined,
+ stagedProjectId: undefined,
};
};
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/execRequest.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/execRequest.ts
index c74cbb9c6a6..f0145838d21 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/execRequest.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/execRequest.ts
@@ -150,14 +150,14 @@ export const buildExecAppContext = (
executionContext,
initialTopicMetadata,
messageContext = executionContext,
- projectWorkingDirectoryId,
+ newTopicProject: { projectId, projectWorkingDirectoryId } = {},
}: {
executionContext: ConversationContext;
/** Seed metadata for the topic this run creates. */
initialTopicMetadata?: Partial<ChatTopicMetadata>;
messageContext?: ConversationContext;
- /** The project directory the topic this run creates is bound to. */
- projectWorkingDirectoryId?: string;
+ /** The project directory β€” or, without one, the project β€” the topic this run creates is bound to. */
+ newTopicProject?: { projectId?: string; projectWorkingDirectoryId?: string };
},
): ExecAgentAppContext => {
const newThread = resolveNewThreadIntent(executionContext);
@@ -198,7 +198,7 @@ export const buildExecAppContext = (
// supervisor turn loses its role on the step_start snapshot / refetch
// and renders as a generic assistant.
orchestrationRole: executionContext.orchestrationRole,
- ...(projectWorkingDirectoryId && { projectWorkingDirectoryId }),
+ ...(projectWorkingDirectoryId ? { projectWorkingDirectoryId } : projectId && { projectId }),
scope: executionContext.scope,
taskId:
executionContext.viewedTask?.type === 'detail'
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index 683b0ab2670..2830db88ede 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -961,11 +961,8 @@ export class GatewayActionImpl {
* without issuing a second legacy resume request.
*/
precreatedResult?: ExecAgentResult;
- /**
- * Project working directory the NEW topic is born in β€” the blank
- * conversation a project group's "+" staged. The caller reads it before the
- * send adopts its minted topic, since that switch clears the staging.
- */
+ /** Directory, else project, a project "+" staged the NEW topic in (read before adopt clears it). */
+ projectId?: string;
projectWorkingDirectoryId?: string;
/** Server operation whose visible output ended before this fresh turn. */
replacesOperationId?: string;
@@ -1048,6 +1045,7 @@ export class GatewayActionImpl {
parentMessageId,
parentOperationId,
precreatedResult,
+ projectId,
projectWorkingDirectoryId,
replacesOperationId,
resumeApproval,
@@ -1183,7 +1181,7 @@ export class GatewayActionImpl {
executionContext,
initialTopicMetadata,
messageContext,
- projectWorkingDirectoryId: isCreateNewTopic ? projectWorkingDirectoryId : undefined,
+ newTopicProject: isCreateNewTopic ? { projectId, projectWorkingDirectoryId } : {},
}),
...desktopDeviceHints,
clientOperations,
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 6eb592acb67..155c6d6fae7 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -69,7 +69,7 @@ import { type ChatTopic, type ChatTopicStatus, type CreateTopicParams } from '@/
import { setNamespace } from '@/utils/storeDebug';
import { displayMessageSelectors } from '../message/selectors';
-import { type TopicData } from './initialState';
+import { type PendingNewTopicDirectory, type TopicData } from './initialState';
import { type PendingTopicStatusSource, PendingTopicStatusWrites } from './pendingStatusWrites';
import {
applyTopicDispatchToBucket,
@@ -315,10 +315,7 @@ export class ChatTopicActionImpl {
* Without it the deferred row would be born with only a path β€” outside the
* project list, the sidebar's project grouping and its execution routing.
*/
- setPendingNewTopicDirectory = (value?: {
- agentId: string;
- projectWorkingDirectoryId: string;
- }): void => {
+ setPendingNewTopicDirectory = (value?: PendingNewTopicDirectory): void => {
this.#set({ pendingNewTopicDirectory: value }, false, n('setPendingNewTopicDirectory'));
};
@@ -1833,12 +1830,14 @@ export class ChatTopicActionImpl {
// directory must never land on another agent's topic.
const pending = this.#get().pendingNewTopicDirectory;
const targetSessionId = params.sessionId ?? this.#get().activeAgentId;
- const pendingDirectoryId =
- pending && pending.agentId === targetSessionId
- ? pending.projectWorkingDirectoryId
- : undefined;
- const createParams: CreateTopicParams = pendingDirectoryId
- ? { ...params, projectWorkingDirectoryId: pendingDirectoryId }
+ const staged = pending?.agentId === targetSessionId ? pending : undefined;
+ const createParams: CreateTopicParams = staged
+ ? {
+ ...params,
+ ...(staged.projectWorkingDirectoryId
+ ? { projectWorkingDirectoryId: staged.projectWorkingDirectoryId }
+ : { projectId: staged.projectId }),
+ }
: params;
const tmpId = Date.now().toString();
@@ -1848,7 +1847,7 @@ export class ChatTopicActionImpl {
);
const topicId = await topicService.createTopic(createParams);
- if (pendingDirectoryId) this.#get().setPendingNewTopicDirectory();
+ if (staged) this.#get().setPendingNewTopicDirectory();
await this.#get().refreshTopic();
return topicId;
diff --git a/src/store/chat/slices/topic/initialState.ts b/src/store/chat/slices/topic/initialState.ts
index 457306af5bb..be117bfcaf1 100644
--- a/src/store/chat/slices/topic/initialState.ts
+++ b/src/store/chat/slices/topic/initialState.ts
@@ -1,6 +1,11 @@
import { createReplicaState, type ReplicaPagedData, type ReplicaState } from '@/libs/replica';
import { type ChatTopic, type TopicQuerySortBy } from '@/types/topic';
+/** The project (and directory, when there is one) a blank conversation was opened in. */
+export type PendingNewTopicDirectory =
+ | { agentId: string; projectId?: undefined; projectWorkingDirectoryId: string }
+ | { agentId: string; projectId: string; projectWorkingDirectoryId?: undefined };
+
/**
* Unified topic data structure for each agent: the generic local-first paged
* view plus topic query descriptors.
@@ -88,9 +93,11 @@ export interface ChatTopicState {
* it into the create call, which is what keeps the deferred row inside the
* project instead of dropping it into a path-only conversation. The agent id
* is part of the value: switching agents must not let one agent's pending
- * directory land on another agent's topic.
+ * directory land on another agent's topic. A project without a directory the
+ * agent can run in stages the project alone: the topic is born
+ * conversation-only inside it.
*/
- pendingNewTopicDirectory?: { agentId: string; projectWorkingDirectoryId: string };
+ pendingNewTopicDirectory?: PendingNewTopicDirectory;
searchTopics: ChatTopic[];
/**
* Unified topic data map for each agent