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(topic): stop the project group "+" from creating an untitled topic (#20629)

Arvin Xu1c5acb80eb17
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.ts
index 0acad5fc22a..ad792313d44 100644
--- a/apps/server/src/routers/lambda/topic.ts
+++ b/apps/server/src/routers/lambda/topic.ts
@@ -22,6 +22,7 @@ import { AgentOperationModel } from '@/database/models/agentOperation';
import { ChatGroupModel } from '@/database/models/chatGroup';
import { FileModel } from '@/database/models/file';
import { MessageModel } from '@/database/models/message';
+import { ProjectWorkingDirectoryModel } from '@/database/models/projectWorkingDirectory';
import { RbacModel } from '@/database/models/rbac';
import { TopicModel } from '@/database/models/topic';
import { TopicShareModel } from '@/database/models/topicShare';
@@ -490,6 +491,9 @@ export const topicRouter = 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 working directory. Resolved and
+ // pinned below, mirroring `projectWorkingDirectory.startTopic`.
+ projectWorkingDirectoryId: z.string().optional(),
provider: z.string().optional(),
title: z.string(),
trigger: z.string().optional(),
@@ -497,7 +501,7 @@ export const topicRouter = router({
.extend(basicContextSchema.shape),
)
.mutation(async ({ input, ctx }) => {
- const { agentId, ...rest } = input;
+ const { agentId, projectWorkingDirectoryId, ...rest } = input;
const resolved = await resolveContextWithAgentId(
{ agentId, groupId: rest.groupId, sessionId: rest.sessionId },
ctx.serverDB,
@@ -510,10 +514,44 @@ export const topicRouter = router({
// See batchCreateTopics β€” reparenting a visitor message would leak it.
await assertCreatorMessageTargets(guardCtx(ctx), rest.messages ?? []);
+ // A topic started from a project group's "+" defers its row to the first
+ // message. Pin the directory here so the row is born inside the project β€”
+ // list, sidebar group and execution routing β€” instead of dropping into a
+ // path-only conversation. A directory that can no longer be resolved
+ // (deleted, unlinked from its environment, or another user's) is logged
+ // and skipped: losing the binding must not fail the user's first send.
+ const directory = projectWorkingDirectoryId
+ ? await new ProjectWorkingDirectoryModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ )
+ .resolve(projectWorkingDirectoryId)
+ .catch((error) => {
+ console.error(
+ '[topic.createTopic] Failed to resolve the project directory binding:',
+ error,
+ );
+ return undefined;
+ })
+ : undefined;
+
const data = await ctx.topicModel.create({
...rest,
agentId: resolved.agentId,
sessionId: resolved.sessionId,
+ ...(directory
+ ? {
+ metadata: {
+ ...rest.metadata,
+ boundDeviceId: directory.deviceId,
+ workingDirectory: directory.path,
+ workingDirectoryConfig: { path: directory.path },
+ },
+ projectId: directory.projectId,
+ projectWorkingDirectoryId: directory.id,
+ }
+ : {}),
});
return data.id;
diff --git a/packages/database/src/models/__tests__/documentHistory.test.ts b/packages/database/src/models/__tests__/documentHistory.test.ts
index 173dacda008..99b512a23ad 100644
--- a/packages/database/src/models/__tests__/documentHistory.test.ts
+++ b/packages/database/src/models/__tests__/documentHistory.test.ts
@@ -352,16 +352,22 @@ describe('DocumentHistoryModel.list cursor', () => {
savedAt,
});
- const [lowerId, higherId] = [first.id, second.id].sort();
+ // The tie-break is a *database* comparison (`saved_at = ? AND id < ?`)
+ // under the column collation, which is not JavaScript's code-unit order β€”
+ // with `en_US.utf8`, 'a' < 'B' but 'Z' > 'a'. Ordering the ids with
+ // `Array.sort()` therefore disagrees with the query roughly half the time
+ // and the cursor page comes back empty, so anchor on the row the database
+ // itself reports as newest and expect the other one back.
+ const [newest, older] = await historyModel.list({ documentId });
+ expect(new Set([newest.id, older.id])).toEqual(new Set([first.id, second.id]));
const rows = await historyModel.list({
- beforeId: higherId,
- beforeSavedAt: savedAt,
+ beforeId: newest.id,
+ beforeSavedAt: new Date(newest.savedAt),
documentId,
});
- expect(rows).toHaveLength(1);
- expect(rows[0]?.id).toBe(lowerId);
+ expect(rows.map((row) => row.id)).toEqual([older.id]);
});
it('should ignore beforeId when there is no savedAt anchor', async () => {
diff --git a/packages/database/src/models/__tests__/session.test.ts b/packages/database/src/models/__tests__/session.test.ts
index 024accb963e..4b3368c4332 100644
--- a/packages/database/src/models/__tests__/session.test.ts
+++ b/packages/database/src/models/__tests__/session.test.ts
@@ -366,6 +366,36 @@ describe('SessionModel', () => {
});
});
+ describe('findSessionsByKeywords BM25 limit', () => {
+ it('clamps the page size to the ParadeDB BM25 ceiling', async () => {
+ // ParadeDB rejects `LIMIT > 8192` for BM25 (`@@@`) ordering with
+ // `error: min > max. min = 9999, max = 8192`, and the error is swallowed
+ // one frame below β€” so an over-limit "no pagination" page size returned
+ // *no* matches at all instead of the top hits.
+ const findMany = vi.fn().mockResolvedValue([]);
+ const model = new SessionModel(
+ { query: { agents: { findMany } } } as unknown as LobeChatDatabase,
+ userId,
+ );
+
+ await model.findSessionsByKeywords({ keyword: 'hello' });
+
+ expect(findMany).toHaveBeenCalledWith(expect.objectContaining({ limit: 8192 }));
+ });
+
+ it('keeps an explicit page size below the ceiling', async () => {
+ const findMany = vi.fn().mockResolvedValue([]);
+ const model = new SessionModel(
+ { query: { agents: { findMany } } } as unknown as LobeChatDatabase,
+ userId,
+ );
+
+ await model.findSessionsByKeywords({ keyword: 'hello', pageSize: 20 });
+
+ expect(findMany).toHaveBeenCalledWith(expect.objectContaining({ limit: 20 }));
+ });
+ });
+
describe('queryByKeyword with external candidates', () => {
it('hydrates only current-scope sessions and surfaces candidate failures', async () => {
await serverDB.insert(users).values({ id: 'candidate-other-user' });
diff --git a/packages/database/src/models/session.ts b/packages/database/src/models/session.ts
index 3e1d795a923..a12d8a05572 100644
--- a/packages/database/src/models/session.ts
+++ b/packages/database/src/models/session.ts
@@ -21,6 +21,17 @@ import { inJsonStringArray } from '../utils/inJsonStringArray';
import { isTrashed, notTrashed } from '../utils/softDelete';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
+/**
+ * ParadeDB's BM25 (`@@@`) ordering rejects a `LIMIT` above 8192 with
+ * `error: min > max. min = 9999, max = 8192`.
+ *
+ * A page size used as "no pagination" therefore has to be clamped instead of
+ * passed through: `findSessionsByKeywords` swallows database errors, so an
+ * over-limit page size does not degrade gracefully β€” it silently returns *no*
+ * matches at all.
+ */
+const BM25_MAX_LIMIT = 8192;
+
/**
* @deprecated Sessions are the legacy shell of an agent β€” see the `sessions`
* schema note. Reads here still exist for the mobile session list and legacy
@@ -745,7 +756,9 @@ export class SessionModel {
keyword: string;
pageSize?: number;
}) => {
- const { keyword, pageSize = 9999, current = 0 } = params;
+ const { keyword, current = 0 } = params;
+ // "No pagination" must stay under ParadeDB's BM25 ceiling β€” see BM25_MAX_LIMIT.
+ const pageSize = Math.min(params.pageSize ?? BM25_MAX_LIMIT, BM25_MAX_LIMIT);
const offset = current * pageSize;
if (this.ftsSearchCandidateSource?.ftsSearchCandidateEnabled) {
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 0236c1d56dd..1c541f1a52e 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -765,6 +765,14 @@ export interface CreateTopicParams {
metadata?: ChatTopicMetadata;
/** Pinned model snapshot for the new topic (see `ChatTopic.model`). */
model?: 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
+ * binding `projectWorkingDirectory.startTopic` writes. Carried by the first
+ * message of a conversation started from a project group's "+", so deferring
+ * the topic creation does not drop the project membership.
+ */
+ projectWorkingDirectoryId?: string;
provider?: string;
sessionId?: string | null;
title: string;
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
index fe5a63425f6..ff49d96c8f2 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
@@ -15,6 +15,8 @@ const routeParamsMock = vi.hoisted(() => ({ aid: 'agent-1' as string | undefined
const agentStoreStateMock = vi.hoisted(() => ({ activeAgentId: 'agent-1' as string | undefined }));
const activeWorkspaceSlugMock = vi.hoisted(() => ({ value: 'lobehub' as string | null }));
+const startTopicMock = vi.hoisted(() => vi.fn());
+const setPendingNewTopicDirectoryMock = vi.hoisted(() => vi.fn());
const directoryRows = vi.hoisted(
() =>
[] as Array<{
@@ -23,21 +25,40 @@ const directoryRows = vi.hoisted(
projectSlug: string;
projectId: string;
projectAvatar: string;
+ deviceId?: string;
+ path?: string;
}>,
);
vi.mock('@/store/projectWorkingDirectory', () => ({
useProjectDirectoryStore: (selector: (state: unknown) => unknown) =>
- selector({ useFetchDirectories: () => ({ hasData: true }) }),
+ selector({
+ startTopic: startTopicMock,
+ useFetchDirectories: () => ({ error: undefined, hasData: true }),
+ }),
useProjectDirectories: () => directoryRows,
}));
vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
useWorkspaceAwareNavigate: () => routerPushMock,
}));
-vi.mock('@/features/Projects/WorkingDirectories/AgentDirectoryActions', () => ({
- AgentDirectoryActions: ({ onLegacyStart }: { onLegacyStart: () => Promise<void> }) => (
- <button aria-label="actions.addNewTopicInProject:project" onClick={onLegacyStart} />
- ),
+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
+ useEffectiveAgencyConfig: () => ({
+ agencyConfig: { boundDeviceId: 'device-1' },
+ workspaceScoped: false,
+ }),
+}));
+
+vi.mock('@/store/electron', () => ({
+ useElectronStore: (selector: (state: unknown) => unknown) =>
+ selector({ gatewayDeviceInfo: { deviceId: 'device-1' } }),
+}));
+
+vi.mock('@/helpers/agentWorkingDirectory', () => ({
+ resolveTargetDeviceId: () => 'device-1',
+}));
+
+vi.mock('@/features/Projects/WorkingDirectories/BindDirectoryModal', () => ({
+ openBindDirectoryModal: vi.fn(),
}));
const openProjectTopicModalMock = vi.hoisted(() => vi.fn());
@@ -110,7 +131,10 @@ vi.mock('@/store/agent/selectors', () => ({
vi.mock('@/store/chat', () => {
const useChatStore = (selector: (state: object) => unknown) => selector({});
- useChatStore.getState = () => ({ switchTopic: switchTopicMock });
+ useChatStore.getState = () => ({
+ setPendingNewTopicDirectory: setPendingNewTopicDirectoryMock,
+ switchTopic: switchTopicMock,
+ });
return { useChatStore };
});
@@ -129,6 +153,8 @@ describe('Project topic group item', () => {
beforeEach(() => {
directoryRows.length = 0;
commitAgentDefaultMock.mockReset();
+ startTopicMock.mockReset();
+ setPendingNewTopicDirectoryMock.mockReset();
switchTopicMock.mockReset();
routerPushMock.mockReset();
routeParamsMock.aid = 'agent-1';
@@ -136,7 +162,19 @@ describe('Project topic group item', () => {
activeWorkspaceSlugMock.value = 'lobehub';
});
- it('navigates to a new chat topic after committing the project directory', async () => {
+ it('opens the new-topic composer for the project directory without creating a topic', async () => {
+ // The group "+" must not persist anything: it opens the composer, and the
+ // topic is created once the user sends the first message. Regression for
+ // the straight-to-server start that dropped an empty "untitled" topic into
+ // the project on the click itself.
+ directoryRows.push({
+ deviceId: 'device-1',
+ id: 'binding-1',
+ path: '/Users/me/project',
+ projectId: 'prj-1',
+ projectName: 'LobeHub',
+ projectSlug: 'lobehub',
+ });
commitAgentDefaultMock.mockResolvedValue(undefined);
render(
@@ -152,12 +190,19 @@ describe('Project topic group item', () => {
</AccordionRoot>,
);
- fireEvent.click(screen.getByRole('button', { name: 'actions.addNewTopicInProject:project' }));
+ fireEvent.click(screen.getByRole('button', { name: 'directories.start' }));
expect(commitAgentDefaultMock).toHaveBeenCalledWith('/Users/me/project');
await expect.poll(() => routerPushMock.mock.calls.length).toBe(1);
expect(switchTopicMock).toHaveBeenCalledWith(null, { skipRefreshMessage: true });
expect(routerPushMock).toHaveBeenCalledWith('/agent/agent-1');
+ expect(startTopicMock).not.toHaveBeenCalled();
+ // The deferred row must still be born inside the project: the staged
+ // directory rides along to the first-message creation.
+ expect(setPendingNewTopicDirectoryMock).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ projectWorkingDirectoryId: 'binding-1',
+ });
});
it('preserves the detected route prefix when adding a project topic without an active workspace slug', async () => {
@@ -177,7 +222,7 @@ describe('Project topic group item', () => {
</AccordionRoot>,
);
- fireEvent.click(screen.getByRole('button', { name: 'actions.addNewTopicInProject:project' }));
+ fireEvent.click(screen.getByRole('button', { name: 'directories.start' }));
await expect.poll(() => routerPushMock.mock.calls.length).toBe(1);
expect(routerPushMock).toHaveBeenCalledWith('/lobehub/agent/agent-1');
@@ -200,7 +245,7 @@ describe('Project topic group item', () => {
</AccordionRoot>,
);
- fireEvent.click(screen.getByRole('button', { name: 'actions.addNewTopicInProject:project' }));
+ fireEvent.click(screen.getByRole('button', { name: 'directories.start' }));
expect(commitAgentDefaultMock).toHaveBeenCalledWith('/Users/me/project');
});
@@ -376,6 +421,7 @@ it('opens the plain new-topic composer when a merged project group spans multipl
openProjectTopicModalMock.mockClear();
commitAgentDefaultMock.mockClear();
switchTopicMock.mockClear();
+ setPendingNewTopicDirectoryMock.mockClear();
routerPushMock.mockClear();
directoryRows.push(
{
@@ -429,11 +475,18 @@ it('opens the plain new-topic composer when a merged project group spans multipl
expect(commitAgentDefaultMock).not.toHaveBeenCalled();
expect(switchTopicMock).toHaveBeenCalledWith(null, { skipRefreshMessage: true });
expect(routerPushMock).toHaveBeenCalledWith('/agent/agent-1');
+ // A multi-directory group has no single directory to stage β€” the user picks
+ // the machine in the composer.
+ expect(setPendingNewTopicDirectoryMock).not.toHaveBeenCalled();
});
-it('keeps the direct start action when a merged project group has a single directory', () => {
+it('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();
+ routerPushMock.mockClear();
directoryRows.push({
id: 'binding-single',
projectName: 'Single Project',
@@ -463,6 +516,14 @@ it('keeps the direct start action when a merged project group has a single direc
/>
</AccordionRoot>,
);
- expect(screen.queryByRole('button', { name: 'directories.start' })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'directories.start' }));
+
+ await 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/TopicListContent/ByProjectMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
index ccffb2f08f7..745470691b3 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
@@ -208,25 +208,39 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
const activeWorkspaceSlug = useActiveWorkspaceSlug();
const { commitAgentDefault } = useCommitWorkingDirectory(currentAgentId ?? '');
- const handleAddTopic = useCallback(async () => {
- if (!workingDirectory || !currentAgentId || !targetAgentId) return;
- // Write the agent's per-device default so the new topic inherits this
- // directory at creation time β€” the same high-precedence slot the picker
- // uses, not the legacy per-agent fallback that gets shadowed by it.
- await commitAgentDefault(workingDirectory);
- useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });
- router.push(
- buildPrefixedAgentRoutePath(AGENT_CHAT_URL(targetAgentId), agentRoute, activeWorkspaceSlug),
- );
- }, [
- workingDirectory,
- currentAgentId,
- targetAgentId,
- commitAgentDefault,
- router,
- agentRoute,
- activeWorkspaceSlug,
- ]);
+ const handleAddTopic = useCallback(
+ async (projectWorkingDirectoryId?: string) => {
+ if (!workingDirectory || !currentAgentId || !targetAgentId) return;
+ // Write the agent's per-device default so the new topic inherits this
+ // directory at creation time β€” the same high-precedence slot the picker
+ // uses, not the legacy per-agent fallback that gets shadowed by it.
+ await commitAgentDefault(workingDirectory);
+ useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });
+ // No topic row is created here β€” the first message creates it. Stage the
+ // project directory so that creation binds the deferred row to the
+ // project (list, sidebar grouping and execution routing), instead of
+ // dropping it into a path-only conversation.
+ useChatStore
+ .getState()
+ .setPendingNewTopicDirectory(
+ projectWorkingDirectoryId
+ ? { agentId: targetAgentId, projectWorkingDirectoryId }
+ : undefined,
+ );
+ router.push(
+ buildPrefixedAgentRoutePath(AGENT_CHAT_URL(targetAgentId), agentRoute, activeWorkspaceSlug),
+ );
+ },
+ [
+ workingDirectory,
+ currentAgentId,
+ targetAgentId,
+ commitAgentDefault,
+ router,
+ agentRoute,
+ activeWorkspaceSlug,
+ ],
+ );
// A merged project group may span several machines. It opens the plain new
// topic composer β€” no directory is pre-committed and no chooser modal pops;
diff --git a/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx b/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx
index aee5d7646b8..d4bdf0e84d2 100644
--- a/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx
+++ b/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx
@@ -1,4 +1,3 @@
-import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
import type { ChatTopic } from '@lobechat/types';
import { ActionIcon, DropdownMenu, toast } from '@lobehub/ui/base-ui';
import { MoreHorizontalIcon, PlusIcon } from 'lucide-react';
@@ -23,7 +22,7 @@ export function AgentDirectoryActions({
agentId: string;
path: string;
topics: ChatTopic[];
- onLegacyStart: () => Promise<void>;
+ onLegacyStart: (projectWorkingDirectoryId?: string) => Promise<void>;
/** Render only the binding/menu affordance; the caller provides its own start action. */
hideStartAction?: boolean;
}) {
@@ -36,7 +35,8 @@ export function AgentDirectoryActions({
const pinnedDevice = topics[0]?.metadata?.boundDeviceId;
const deviceId =
pinnedDevice ?? resolveTargetDeviceId(agencyConfig, currentDeviceId, { workspaceScoped });
- const request = useProjectDirectoryStore((s) => s.useFetchDirectories)();
+ // Keep the directories query warm for the binding menu below.
+ useProjectDirectoryStore((s) => s.useFetchDirectories)();
const directories = useProjectDirectories();
const bindingId = topics[0]?.projectWorkingDirectoryId;
const bindings = directories.filter((directory) =>
@@ -46,14 +46,14 @@ export function AgentDirectoryActions({
directory.path.replace(/[\\/]+$/, '') === path.replace(/[\\/]+$/, ''),
);
const [pending, setPending] = useState(false);
- const startTopic = useProjectDirectoryStore((s) => s.startTopic);
- const start = async (id?: string) => {
+ // "+" opens the new-topic composer for this group; it must never create a
+ // topic. The row is persisted on the first message, which is also when the
+ // directory is applied β€” the caller stages it so the deferred topic is still
+ // born inside the project instead of dropping into a path-only conversation.
+ const start = async (projectWorkingDirectoryId?: string) => {
setPending(true);
try {
- if (id) {
- const topic = await startTopic(id, agentId, t('directories.untitled'));
- navigate(AGENT_CHAT_TOPIC_URL(agentId, topic.id));
- } else await onLegacyStart();
+ await onLegacyStart(projectWorkingDirectoryId);
} catch (error) {
console.error('Failed to start directory conversation', error);
toast.error(error instanceof Error ? error.message : t('operationFailed', { ns: 'common' }));
@@ -110,16 +110,10 @@ export function AgentDirectoryActions({
</DropdownMenu>
{!hideStartAction && (
<ActionIcon
+ disabled={pending}
icon={PlusIcon}
size="small"
title={t('directories.start')}
- disabled={
- pending ||
- !request.hasData ||
- !!request.error ||
- bindings.length > 1 ||
- (!!bindingId && !bindings.length)
- }
onClick={(e) => {
e.stopPropagation();
void start(bindings[0]?.id);
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index 3795b1ddff6..2b11855a429 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -258,6 +258,67 @@ describe('topic action', () => {
await summaryPromise;
});
});
+
+ it('binds a deferred new topic to the staged project directory', async () => {
+ // ROOT CAUSE: "+" on a project group defers the row to the first message.
+ // Creating it with only the working-directory path left the topic outside
+ // its project β€” missing from the project list, mis-grouped in the sidebar
+ // and skipping the project-directory execution routing. The staged
+ // directory must ride along on the create call.
+ const { result } = renderHook(() => useChatStore());
+ const messages = [{ id: 'message1' }] as UIChatMessage[];
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: 'session-id',
+ messagesMap: {
+ [messageMapKey({ agentId: 'session-id' })]: messages,
+ },
+ pendingNewTopicDirectory: {
+ agentId: 'session-id',
+ projectWorkingDirectoryId: 'binding-1',
+ },
+ });
+ });
+
+ const createTopicSpy = vi
+ .spyOn(topicService, 'createTopic')
+ .mockResolvedValue('new-topic-id');
+
+ await result.current.saveToTopic();
+
+ expect(createTopicSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ projectWorkingDirectoryId: 'binding-1' }),
+ );
+ // Consumed, so it cannot leak onto a later, unrelated topic.
+ expect(useChatStore.getState().pendingNewTopicDirectory).toBeUndefined();
+ });
+
+ it('does not apply a staged directory that belongs to another agent', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const messages = [{ id: 'message1' }] as UIChatMessage[];
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: 'session-id',
+ messagesMap: {
+ [messageMapKey({ agentId: 'session-id' })]: messages,
+ },
+ pendingNewTopicDirectory: {
+ agentId: 'another-agent',
+ projectWorkingDirectoryId: 'binding-1',
+ },
+ });
+ });
+
+ const createTopicSpy = vi
+ .spyOn(topicService, 'createTopic')
+ .mockResolvedValue('new-topic-id');
+
+ await result.current.saveToTopic();
+
+ expect(createTopicSpy).toHaveBeenCalledWith(
+ expect.not.objectContaining({ projectWorkingDirectoryId: expect.anything() }),
+ );
+ });
});
describe('refreshTopic', () => {
afterEach(() => {
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 57fb596d31f..e36726b8d5f 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -316,8 +316,28 @@ export class ChatTopicActionImpl {
this.#set({ allTopicsDrawerOpen: true }, false, n('openAllTopicsDrawer'));
};
+ /**
+ * Stage (or clear) the project working directory the next topic creation
+ * binds to.
+ *
+ * `+` on a project group opens a blank conversation *without* creating a row;
+ * this records which directory that blank conversation belongs to, and
+ * `internal_createTopic` applies it when the first message creates the topic.
+ * 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 => {
+ this.#set({ pendingNewTopicDirectory: value }, false, n('setPendingNewTopicDirectory'));
+ };
+
openNewTopicOrSaveTopic = async (): Promise<void> => {
const { switchTopic, saveToTopic, refreshMessages, activeTopicId } = this.#get();
+ // An explicit new topic supersedes whatever a group "+" staged β€” the user
+ // asked for a plain conversation, not one inside that project directory.
+ this.#get().setPendingNewTopicDirectory();
const hasTopic = !!activeTopicId;
if (hasTopic) switchTopic(null);
@@ -1557,6 +1577,12 @@ export class ChatTopicActionImpl {
return;
const epoch = ++this.#switchTopicEpoch;
+ // A staged project directory only describes the blank conversation it was
+ // opened from; moving to a real topic ends that window. Cleared here (after
+ // the guards) so a switch the guards dropped does not discard it.
+ if (id) {
+ this.#set({ pendingNewTopicDirectory: undefined }, false, n('clearPendingNewTopicDirectory'));
+ }
this.#set(
{ activeTopicId: id || (null as any), activeThreadId: undefined },
@@ -1827,13 +1853,28 @@ export class ChatTopicActionImpl {
};
internal_createTopic = async (params: CreateTopicParams): Promise<string> => {
+ // A blank conversation opened from a project group's "+" carries the
+ // directory it belongs to β€” fold it into the create call so the row is born
+ // inside that project. Only for the agent it was staged on: a pending
+ // 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 }
+ : params;
+
const tmpId = Date.now().toString();
this.#get().internal_dispatchTopic(
- { type: 'addTopic', value: { ...params, id: tmpId } },
+ { type: 'addTopic', value: { ...createParams, id: tmpId } },
'internal_createTopic',
);
- const topicId = await topicService.createTopic(params);
+ const topicId = await topicService.createTopic(createParams);
+ if (pendingDirectoryId) 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 8aa54ab6eec..c77d865e9ee 100644
--- a/src/store/chat/slices/topic/initialState.ts
+++ b/src/store/chat/slices/topic/initialState.ts
@@ -69,6 +69,18 @@ export interface ChatTopicState {
creatingTopicIds: string[];
inSearchingMode?: boolean;
isSearchingTopic: boolean;
+ /**
+ * Project working directory the *next* topic creation should bind to.
+ *
+ * Set when a project group's "+" opens a blank conversation and cleared by
+ * any later switch to a real topic (or by the creation itself), so it can
+ * only ever describe that one pending new topic. `internal_createTopic` folds
+ * 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.
+ */
+ pendingNewTopicDirectory?: { agentId: string; projectWorkingDirectoryId: string };
searchTopics: ChatTopic[];
/**
* Unified topic data map for each agent