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): start a topic from a device subgroup in that device's directory (#20852)

Arvin Xuf567efd8f74e
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 028a15e23aa..48eb61f0b21 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -1236,6 +1236,8 @@ const ExecAgentSchema = z
* identity survives the gateway step_start snapshot / refetch.
*/
orchestrationRole: z.enum(['supervisor', 'member']).optional(),
+ /** Bind a NEW topic to this project working directory (ignored with topicId). */
+ projectWorkingDirectoryId: z.string().optional(),
scope: z.string().nullish(),
sessionId: z.string().optional(),
taskId: z.string().nullish(),
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
index 352782d1d60..037ddc99f77 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
@@ -103,12 +103,16 @@ vi.mock('@/database/models/topic', () => ({
}),
}));
-const { mockResolveProjectDirectoryForTopic } = vi.hoisted(() => ({
+const { mockResolveProjectDirectory, mockResolveProjectDirectoryForTopic } = vi.hoisted(() => ({
+ mockResolveProjectDirectory: vi.fn(),
mockResolveProjectDirectoryForTopic: vi.fn().mockResolvedValue(undefined),
}));
vi.mock('@/database/models/projectWorkingDirectory', () => ({
ProjectWorkingDirectoryModel: vi.fn().mockImplementation(function () {
- return { resolveForTopic: mockResolveProjectDirectoryForTopic };
+ return {
+ resolve: mockResolveProjectDirectory,
+ resolveForTopic: mockResolveProjectDirectoryForTopic,
+ };
}),
}));
@@ -826,6 +830,58 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
});
});
+ describe('new topic in a staged project directory', () => {
+ const stagedDirectory = {
+ deviceId: 'device-001',
+ id: 'dir-1',
+ path: '/repo',
+ permission: 'readWrite',
+ platform: 'darwin',
+ projectId: 'project-1',
+ };
+
+ // Regression: a blank conversation opened from a project group's "+" was
+ // created without its directory β€” the first send dropped the staged
+ // binding, so the topic left the project and ran on the agent default.
+ it('binds the created topic to the directory and runs on its device', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice, onlineDevice2]);
+ mockResolveProjectDirectory.mockResolvedValueOnce(stagedDirectory);
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: { projectWorkingDirectoryId: 'dir-1' },
+ prompt: 'Start here',
+ });
+
+ expect(mockResolveProjectDirectory).toHaveBeenCalledWith('dir-1');
+ const createArgs = topicMock.create.mock.calls.at(-1)![0];
+ expect(createArgs.projectId).toBe('project-1');
+ expect(createArgs.projectWorkingDirectoryId).toBe('dir-1');
+ expect(createArgs.metadata?.boundDeviceId).toBe('device-001');
+ expect(createArgs.metadata?.workingDirectory).toBe('/repo');
+ expect(mockCreateOperation.mock.calls.at(-1)![0].activeDeviceId).toBe('device-001');
+ });
+
+ it('rejects an offline directory device before creating the topic', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice2]);
+ mockResolveProjectDirectory.mockResolvedValueOnce(stagedDirectory);
+ topicMock.create.mockClear();
+ mockCreateOperation.mockClear();
+
+ await expect(
+ service.execAgent({
+ agentId: 'agent-1',
+ appContext: { projectWorkingDirectoryId: 'dir-1' },
+ prompt: 'Start here',
+ }),
+ ).rejects.toThrow('Device is offline or working directory is unavailable');
+ expect(topicMock.create).not.toHaveBeenCalled();
+ expect(mockCreateOperation).not.toHaveBeenCalled();
+ });
+ });
+
describe('gateway not configured', () => {
it('should never set activeDeviceId when gateway is not configured', async () => {
mockDeviceProxy.isConfigured = false;
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index ec2bcbbfb4b..c238004784e 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -486,6 +486,41 @@ export const setupTurn = async (
});
}
+ const assertProjectDirectoryAccess = () => {
+ if (shareGate || (botContext && !resolveDeviceAccessPolicy({ botContext }).canUseDevice))
+ throw new Error('Project directory access denied');
+ };
+ /** Pin the run to the device a project directory lives on β€” only it can honour the run. */
+ const routeToProjectDirectory = async (directory: { deviceId: string | null }) => {
+ if (
+ agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
+ agentConfig.agencyConfig.boundDeviceId !== directory.deviceId
+ )
+ throw new Error('Agent is fixed to another execution target');
+ // Reject an unavailable device *here*, before the user/assistant rows are
+ // persisted: the client treats a rejected send as never accepted, keeps the
+ // draft and rolls back its optimistic pair, so a later rejection would leave
+ // a failed turn durable server-side that the client disagrees with.
+ // Liveness comes from the gateway's device listing β€” not a device round
+ // trip β€” so the send path keeps the latency fix, and the dispatch remains
+ // the authority on whether the directory still exists on the device.
+ const { canUseDevice: canUseProjectDevice } = resolveDeviceAccessPolicy({ botContext });
+ const projectDevices = canUseProjectDevice
+ ? await getScopedOnlineDevices(deps.db, deps.userId, deps.workspaceId)
+ : [];
+ if (!projectDevices.some((device) => device.deviceId === directory.deviceId && device.online))
+ throw new Error('Device is offline or working directory is unavailable');
+ const deviceId = directory.deviceId ?? undefined;
+ resolvedRequestedDeviceId = deviceId;
+ effectiveRequestedDeviceId = deviceId;
+ topicBoundDeviceId = deviceId;
+ agentConfig.agencyConfig = {
+ ...agentConfig.agencyConfig,
+ boundDeviceId: deviceId,
+ executionTarget: 'device',
+ };
+ };
+
// Topic resolution assigns the turn's narrowed bindings (topic id, pinned
// model, device targets), so it is a marked block rather than a callback:
// every exit, including a throw, records the error and closes the span.
@@ -496,9 +531,29 @@ export const setupTurn = async (
throw new Error('Resume mode requires the parent message to belong to a topic');
}
+ // A blank conversation opened from a project group's "+" is born inside
+ // that directory: bound to it, and run on the device it lives on.
+ let projectDirectory:
+ Awaited<ReturnType<ProjectWorkingDirectoryModel['resolve']>> | undefined;
+ if (appContext?.projectWorkingDirectoryId) {
+ assertProjectDirectoryAccess();
+ projectDirectory = await new ProjectWorkingDirectoryModel(
+ deps.db,
+ deps.userId,
+ deps.workspaceId,
+ ).resolve(appContext.projectWorkingDirectoryId);
+ await routeToProjectDirectory(projectDirectory);
+ }
+
// Prepare metadata with cronJobId, taskId, botContext, bound device, and any
// client-supplied initial metadata (e.g. repos selected before first message).
- const initialTopicMeta = appContext?.initialTopicMetadata;
+ const initialTopicMeta = projectDirectory
+ ? {
+ ...appContext?.initialTopicMetadata,
+ workingDirectory: projectDirectory.path,
+ workingDirectoryConfig: { path: projectDirectory.path },
+ }
+ : appContext?.initialTopicMetadata;
// Builder conversations are owned by a builtin builder agent and get no
// `groupId` / `sessionId` (those columns mark the target's own chat), so
// without this the row keeps no trace of what it was configuring. The
@@ -552,6 +607,10 @@ export const setupTurn = async (
// must carry the groupId through too (group topic sidebar + ownership fix).
groupId: appContext?.groupId,
metadata: metadataWithSnapshot,
+ ...(projectDirectory && {
+ projectId: projectDirectory.projectId,
+ projectWorkingDirectoryId: projectDirectory.id,
+ }),
// Snapshot the effective model as the topic's pinned model (config).
model: snapshot.model,
provider: snapshot.provider,
@@ -607,44 +666,14 @@ export const setupTurn = async (
// A project conversation without a directory follows the plain
// topic-pinned device path below, like any other conversation.
if (existingTopic?.projectWorkingDirectoryId) {
- if (shareGate || (botContext && !resolveDeviceAccessPolicy({ botContext }).canUseDevice))
- throw new Error('Project directory access denied');
+ assertProjectDirectoryAccess();
const directory = await new ProjectWorkingDirectoryModel(
deps.db,
deps.userId,
deps.workspaceId,
).resolveForTopic(topicId);
if (!directory) throw new Error('Project directory binding no longer exists');
- if (
- agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
- agentConfig.agencyConfig.boundDeviceId !== directory.deviceId
- )
- throw new Error('Agent is fixed to another execution target');
- // The directory lives on one device, so only that device can honour the
- // run. Reject an unavailable device *here*, before the user/assistant
- // rows are persisted: the client treats a rejected send as never
- // accepted, keeps the draft and rolls back its optimistic pair, so a
- // later rejection would leave a failed turn durable server-side that the
- // client disagrees with. Liveness comes from the gateway's device
- // listing β€” not a device round trip β€” so the send path keeps the latency
- // fix, and the dispatch remains the authority on whether the directory
- // still exists on the device.
- const { canUseDevice: canUseProjectDevice } = resolveDeviceAccessPolicy({ botContext });
- const projectDevices = canUseProjectDevice
- ? await getScopedOnlineDevices(deps.db, deps.userId, deps.workspaceId)
- : [];
- if (
- !projectDevices.some((device) => device.deviceId === directory.deviceId && device.online)
- )
- throw new Error('Device is offline or working directory is unavailable');
- resolvedRequestedDeviceId = directory.deviceId;
- effectiveRequestedDeviceId = directory.deviceId;
- topicBoundDeviceId = directory.deviceId;
- agentConfig.agencyConfig = {
- ...agentConfig.agencyConfig,
- boundDeviceId: directory.deviceId,
- executionTarget: 'device',
- };
+ await routeToProjectDirectory(directory);
}
// Fail-closed guard: a non-share run must never operate on a share-visitor
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index bdeef4d3e2e..609ba64a105 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -173,6 +173,12 @@ export interface ExecAgentAppContext {
* `metadata.orchestrationRole` so the role snapshot persists for rendering.
*/
orchestrationRole?: 'supervisor' | 'member';
+ /**
+ * Project working directory a NEW topic is born in β€” the blank conversation a
+ * project group's "+" opened. The topic is bound to it and the run routes to
+ * the directory's device. Ignored when a topicId is already provided.
+ */
+ projectWorkingDirectoryId?: string;
/** Scope identifier */
scope?: string | null;
/** Session ID */
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
index 24fad3dc6ec..8bbb12c56fa 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
@@ -2,7 +2,7 @@
* @vitest-environment happy-dom
*/
import { AccordionRoot } from '@lobehub/ui/base-ui';
-import { fireEvent, render, screen } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { TopicListScopeContext } from '../../TopicListScope';
@@ -35,7 +35,12 @@ const updateSystemStatusMock = vi.hoisted(() => vi.fn());
vi.mock('@/store/global', () => ({
useGlobalStore: (selector: (state: object) => unknown) =>
selector({
- status: { projectTopicSubGroupModeByGroup: { 'project-id:prj-1': subGroupModeMock.value } },
+ status: {
+ projectTopicSubGroupModeByGroup: {
+ 'project-id:prj-1': subGroupModeMock.value,
+ 'project:/tmp/x': subGroupModeMock.value,
+ },
+ },
updateSystemStatus: updateSystemStatusMock,
}),
}));
@@ -149,9 +154,25 @@ vi.mock('@/store/agent/selectors', () => ({
},
}));
+const updateTopicStatusMock = vi.hoisted(() => vi.fn());
+const refreshTopicMock = vi.hoisted(() => vi.fn());
+vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
+ useActiveWorkspaceId: () => undefined,
+}));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (state: object) => unknown) => selector({}),
+}));
+vi.mock('@/store/user/selectors', () => ({
+ preferenceSelectors: { topicSortBy: () => 'updatedAt' },
+ userProfileSelectors: { userId: () => 'user-1' },
+}));
+
vi.mock('@/store/chat', () => {
const useChatStore = (selector: (state: object) => unknown) => selector({});
useChatStore.getState = () => ({
+ refreshTopic: refreshTopicMock,
+ updateTopicStatus: updateTopicStatusMock,
setPendingNewTopicDirectory: setPendingNewTopicDirectoryMock,
switchTopic: switchTopicMock,
});
@@ -181,6 +202,8 @@ describe('Project topic group item', () => {
agentStoreStateMock.activeAgentId = 'agent-1';
activeWorkspaceSlugMock.value = 'lobehub';
subGroupModeMock.value = 'none';
+ updateTopicStatusMock.mockReset();
+ refreshTopicMock.mockReset();
});
it('keeps the sub-group menu when the newest project topic has no working directory', () => {
@@ -278,6 +301,159 @@ describe('Project topic group item', () => {
expect(text.indexOf('Mac topic')).toBeLessThan(text.indexOf('groupTitle.byDevice.unknown'));
});
+ it('offers no device grouping for a plain folder group and ignores a stale byDevice choice', async () => {
+ subGroupModeMock.value = 'byDevice';
+ render(
+ <AccordionRoot defaultValue={['project:/tmp/x']}>
+ <GroupItem
+ expanded
+ group={{
+ // A path-only group: no project id, no bound directory.
+ children: [
+ { id: 't1', metadata: { workingDirectory: '/tmp/x' }, title: 'Folder topic' },
+ ] as any,
+ id: 'project:/tmp/x',
+ title: '/tmp/x',
+ }}
+ />
+ </AccordionRoot>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'topics.subGroup.title' }));
+ expect(await screen.findByText('topics.subGroup.byTime')).toBeTruthy();
+ expect(screen.queryByText('topics.subGroup.byDevice')).toBeNull();
+ expect(document.body.textContent).not.toContain('groupTitle.byDevice.unknown');
+ });
+
+ it('archives only this group\'s merged-PR topics from the group "more" menu', async () => {
+ const merged = { github: { pullRequest: { mergedAt: '2026-10-01', state: 'closed' } } };
+ render(
+ <AccordionRoot>
+ <GroupItem
+ expanded
+ group={{
+ children: [
+ {
+ id: 't-merged',
+ metadata: { workingDirectory: '/tmp/x', workingDirectoryConfig: { git: merged } },
+ title: 'Merged',
+ },
+ {
+ id: 't-done',
+ metadata: { workingDirectory: '/tmp/x', workingDirectoryConfig: { git: merged } },
+ status: 'completed',
+ title: 'Already done',
+ },
+ { id: 't-open', metadata: { workingDirectory: '/tmp/x' }, title: 'Open' },
+ ] as any,
+ id: 'project:/tmp/x',
+ title: '/tmp/x',
+ }}
+ />
+ </AccordionRoot>,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: 'directories.projectBinding' }));
+ fireEvent.click(await screen.findByText('actions.archiveMergedPullRequests'));
+
+ await waitFor(() => expect(refreshTopicMock).toHaveBeenCalled());
+ expect(updateTopicStatusMock).toHaveBeenCalledTimes(1);
+ expect(updateTopicStatusMock).toHaveBeenCalledWith({
+ status: 'completed',
+ topicId: 't-merged',
+ });
+ });
+
+ it('folds a device section from its header without touching the others', async () => {
+ subGroupModeMock.value = 'byDevice';
+ directoryRows.push({
+ deviceId: 'device-2',
+ id: 'binding-linux',
+ path: '/home/me/project',
+ projectAvatar: '',
+ projectId: 'prj-1',
+ projectName: 'LobeHub',
+ projectSlug: 'lobehub',
+ });
+
+ render(
+ <AccordionRoot defaultValue={['project-id:prj-1']}>
+ <GroupItem
+ expanded
+ group={{
+ children: [
+ { id: 't1', projectWorkingDirectoryId: 'binding-linux', title: 'Linux topic' },
+ { id: 't2', title: 'Loose topic' },
+ ] as any,
+ id: 'project-id:prj-1',
+ title: 'LobeHub',
+ }}
+ />
+ </AccordionRoot>,
+ );
+
+ expect(screen.getByText('Linux topic')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Studio Linux' }));
+
+ await waitFor(() => expect(screen.queryByText('Linux topic')).toBeNull());
+ expect(screen.getByText('Loose topic')).toBeTruthy();
+ });
+
+ it('starts a new topic in the project directory of a device section from its "+"', () => {
+ subGroupModeMock.value = 'byDevice';
+ directoryRows.push(
+ {
+ deviceId: 'device-1',
+ deviceName: 'MacBook',
+ id: 'binding-mac',
+ path: '/Users/me/project',
+ projectAvatar: '',
+ projectId: 'prj-1',
+ projectName: 'LobeHub',
+ projectSlug: 'lobehub',
+ },
+ {
+ deviceId: 'device-2',
+ id: 'binding-linux',
+ path: '/home/me/project',
+ projectAvatar: '',
+ projectId: 'prj-1',
+ projectName: 'LobeHub',
+ projectSlug: 'lobehub',
+ },
+ );
+
+ render(
+ <AccordionRoot defaultValue={['project-id:prj-1']}>
+ <GroupItem
+ expanded
+ group={{
+ children: [
+ { id: 't1', projectWorkingDirectoryId: 'binding-linux', title: 'Linux topic' },
+ { id: 't2', title: 'Loose topic' },
+ ] as any,
+ id: 'project-id:prj-1',
+ title: 'LobeHub',
+ }}
+ />
+ </AccordionRoot>,
+ );
+
+ // Only the Linux section gets a "+" β€” the unknown section has no directory
+ // to start in (and the group header has no path, so it renders none).
+ const starts = screen.getAllByRole('button', { name: 'directories.start' });
+ expect(starts).toHaveLength(1);
+ fireEvent.click(starts[0]);
+
+ expect(commitAgentDefaultMock).not.toHaveBeenCalled();
+ expect(switchTopicMock).toHaveBeenCalledWith(null, { skipRefreshMessage: true });
+ expect(setPendingNewTopicDirectoryMock).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ projectWorkingDirectoryId: 'binding-linux',
+ });
+ expect(routerPushMock).toHaveBeenCalled();
+ });
+
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
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
index c1370f57059..c41cfa68e71 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
@@ -10,13 +10,15 @@ import {
type DropdownItem,
DropdownMenu,
Text,
+ toast,
} from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import isEqual from 'fast-deep-equal';
import {
+ Archive,
FolderClosedIcon,
FolderOpenIcon,
- ListTreeIcon,
+ ListFilter,
LucideCheck,
type LucideIcon,
PlusIcon,
@@ -24,6 +26,7 @@ import {
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import Avatar from '@/components/Avatar';
import { TOPIC_STATUS_VISUALS } from '@/components/ExecutionStatus';
@@ -35,6 +38,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwar
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useActiveLocation } from '@/hooks/useActiveLocation';
import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
+import { usePermission } from '@/hooks/usePermission';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
@@ -43,10 +47,13 @@ import { useGlobalStore } from '@/store/global';
import { type ProjectTopicSubGroupMode } from '@/store/global/initialState';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useProjectDirectories, useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
import { getTopicWorkingDirectorySourcePath } from '@/utils/client/topic';
import { buildPrefixedAgentRoutePath, parseAgentPathname } from '../../../utils/agentPathname';
import { useTopicListScope } from '../../TopicListScope';
+import { getMergedPullRequestTopics } from '../../utils/mergedPullRequestTopics';
import { type GroupItemComponentProps } from '../GroupedAccordion';
import ProjectTopicList from './ProjectTopicList';
import {
@@ -58,6 +65,8 @@ import {
const PROJECT_GROUP_PREFIX = 'project:';
const PROJECT_ID_GROUP_PREFIX = 'project-id:';
const SUB_GROUP_MODES: ProjectTopicSubGroupMode[] = ['none', 'byDevice', 'byTime', 'byStatus'];
+// A plain folder lives on one machine, so sectioning it by device says nothing.
+const FOLDER_SUB_GROUP_MODES = SUB_GROUP_MODES.filter((mode) => mode !== 'byDevice');
const styles = createStaticStyles(({ css }) => ({
statusBadge: css`
@@ -271,16 +280,35 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
);
}, [currentAgentId, targetAgentId, router, agentRoute, activeWorkspaceSlug]);
+ // Start on one specific project directory β€” the device sub-group "+". The
+ // directory pins the device, so nothing is committed to the agent default.
+ const handleStartInDirectory = useCallback(
+ (projectWorkingDirectoryId: string) => {
+ if (!targetAgentId) return;
+ useChatStore.getState().switchTopic(null, { skipRefreshMessage: true });
+ useChatStore
+ .getState()
+ .setPendingNewTopicDirectory({ agentId: targetAgentId, projectWorkingDirectoryId });
+ router.push(
+ buildPrefixedAgentRoutePath(AGENT_CHAT_URL(targetAgentId), agentRoute, activeWorkspaceSlug),
+ );
+ },
+ [targetAgentId, router, agentRoute, activeWorkspaceSlug],
+ );
+
const canAddTopic = !scope && !!currentAgentId && !!workingDirectory;
const needsPlainStart = !!projectId && projectDirectories.length > 1;
const { t: tProject } = useTranslation('project');
- const subGroupMode = useGlobalStore(systemStatusSelectors.projectTopicSubGroupMode(id));
+ const isProjectGroup = !!projectId || !!children[0]?.projectWorkingDirectoryId;
+ const subGroupModes = isProjectGroup ? SUB_GROUP_MODES : FOLDER_SUB_GROUP_MODES;
+ const storedSubGroupMode = useGlobalStore(systemStatusSelectors.projectTopicSubGroupMode(id));
+ const subGroupMode = subGroupModes.includes(storedSubGroupMode) ? storedSubGroupMode : 'none';
const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
const subGroupMenuItems = useMemo<DropdownItem[]>(
() => [
{
- children: SUB_GROUP_MODES.map((mode) => ({
+ children: subGroupModes.map((mode) => ({
icon: subGroupMode === mode ? <Icon icon={LucideCheck} /> : <div />,
key: `sub-group-${mode}`,
label: tProject(`topics.subGroup.${mode}`),
@@ -291,7 +319,45 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
type: 'group',
},
],
- [id, subGroupMode, tProject, updateSystemStatus],
+ [id, subGroupModes, subGroupMode, tProject, updateSystemStatus],
+ );
+
+ // "Archive merged PR topics", scoped to this group β€” a workspace member only
+ // archives their own topics, same as the sidebar-wide action.
+ const { t } = useTranslation('topic');
+ const activeWorkspaceId = useActiveWorkspaceId();
+ const currentUserId = useUserStore(userProfileSelectors.userId);
+ const { allowed: canEditTopic } = usePermission('edit_own_content');
+ const archiveMenuItems = useMemo<DropdownItem[]>(
+ () => [
+ {
+ disabled: !canEditTopic,
+ icon: <Icon icon={Archive} />,
+ key: 'archiveMergedPullRequests',
+ label: t(
+ activeWorkspaceId
+ ? 'actions.archiveMergedPullRequestsOwn'
+ : 'actions.archiveMergedPullRequests',
+ ),
+ onClick: async () => {
+ const merged = getMergedPullRequestTopics(
+ children,
+ activeWorkspaceId ? (currentUserId ?? null) : undefined,
+ );
+ if (merged.length === 0) {
+ toast.info(t('actions.archiveMergedPullRequestsNone'));
+ return;
+ }
+ const { refreshTopic, updateTopicStatus } = useChatStore.getState();
+ await Promise.all(
+ merged.map(({ id }) => updateTopicStatus({ status: 'completed', topicId: id })),
+ );
+ await refreshTopic();
+ toast.success(t('actions.archiveMergedPullRequestsSuccess', { count: merged.length }));
+ },
+ },
+ ],
+ [activeWorkspaceId, canEditTopic, children, currentUserId, t],
);
const statusCounts = useChatStore(
@@ -313,8 +379,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
<span className={hasCollapsedIndicators ? styles.addTopicAction : undefined}>
<DropdownMenu items={subGroupMenuItems}>
<ActionIcon
- active={subGroupMode !== 'none'}
- icon={ListTreeIcon}
+ icon={ListFilter}
size={'small'}
title={tProject('topics.subGroup.title')}
onClick={(e) => e.stopPropagation()}
@@ -325,6 +390,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
<AgentDirectoryActions
hideStartAction
agentId={currentAgentId!}
+ extraMenuItems={archiveMenuItems}
path={workingDirectory!}
topics={children}
onLegacyStart={handleAddTopic}
@@ -342,6 +408,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
) : (
<AgentDirectoryActions
agentId={currentAgentId!}
+ extraMenuItems={archiveMenuItems}
path={workingDirectory!}
topics={children}
onLegacyStart={handleAddTopic}
@@ -419,7 +486,12 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
</div>
</AccordionHeader>
<AccordionPanel contentStyle={{ padding: 0 }}>
- <ProjectTopicList groupId={id} topics={children} />
+ <ProjectTopicList
+ mode={subGroupMode}
+ startDirectories={projectId ? projectDirectories : project ? [project] : undefined}
+ topics={children}
+ onStartInDirectory={!scope && targetAgentId ? handleStartInDirectory : undefined}
+ />
</AccordionPanel>
</AccordionItem>
);
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx
index 266eb6876e5..a8cb6231e86 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx
@@ -1,9 +1,18 @@
import { Center, Flexbox, Icon } from '@lobehub/ui';
-import { Text } from '@lobehub/ui/base-ui';
-import { cssVar } from 'antd-style';
+import {
+ AccordionHeader,
+ AccordionItem,
+ AccordionPanel,
+ AccordionRoot,
+ accordionStyles,
+ AccordionTrigger,
+ ActionIcon,
+ Text,
+} from '@lobehub/ui/base-ui';
+import { cssVar, cx } from 'antd-style';
import isEqual from 'fast-deep-equal';
-import { LaptopIcon } from 'lucide-react';
-import { memo, useCallback, useMemo } from 'react';
+import { LaptopIcon, PlusIcon } from 'lucide-react';
+import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -15,9 +24,8 @@ import { projectDirectoryDeviceName } from '@/features/ChatInput/ControlBar/proj
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { deviceSelectors, useDeviceStore } from '@/store/device';
-import { useGlobalStore } from '@/store/global';
-import { systemStatusSelectors } from '@/store/global/selectors';
-import { useProjectDirectories } from '@/store/projectWorkingDirectory';
+import { type ProjectTopicSubGroupMode } from '@/store/global/initialState';
+import { type ProjectDirectory, useProjectDirectories } from '@/store/projectWorkingDirectory';
import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
import { type ChatTopic, type GroupedTopic } from '@/types/topic';
@@ -49,8 +57,12 @@ const renderTopic = (topic: ChatTopic) => (
);
interface ProjectTopicListProps {
- /** The byProject group id β€” the sub-group mode is remembered per group. */
- groupId: string;
+ /** The group's effective sub-group mode (folders never get `byDevice`). */
+ mode: ProjectTopicSubGroupMode;
+ /** Opens the new-topic composer staged on one project directory. */
+ onStartInDirectory?: (projectWorkingDirectoryId: string) => void;
+ /** The group's project directories a device section's "+" may start in. */
+ startDirectories?: ProjectDirectory[];
topics: ChatTopic[];
}
@@ -58,9 +70,10 @@ interface ProjectTopicListProps {
* Topics of one byProject sidebar group, optionally sectioned by device, time
* or status (picked from the group's "more" menu).
*/
-const ProjectTopicList = memo<ProjectTopicListProps>(({ groupId, topics }) => {
+const ProjectTopicList = memo<ProjectTopicListProps>((props) => {
+ const { mode, onStartInDirectory, startDirectories, topics } = props;
const { t } = useTranslation('topic');
- const mode = useGlobalStore(systemStatusSelectors.projectTopicSubGroupMode(groupId));
+ const { t: tProject } = useTranslation('project');
const topicSortBy = useUserStore(preferenceSelectors.topicSortBy);
const field = topicSortBy === 'createdAt' ? 'createdAt' : 'updatedAt';
@@ -114,6 +127,34 @@ const ProjectTopicList = memo<ProjectTopicListProps>(({ groupId, topics }) => {
[mode, t, directories, devices],
);
+ // The directory a device section's "+" starts in: the one its newest topic
+ // runs in, else any of the group's directories on that device.
+ const getStartDirectoryId = (group: GroupedTopic) => {
+ if (mode !== 'byDevice' || !onStartInDirectory || !startDirectories?.length) return;
+ if (!group.id.startsWith(DEVICE_SUB_GROUP_PREFIX)) return;
+ const deviceId = group.id.slice(DEVICE_SUB_GROUP_PREFIX.length);
+ const candidates = startDirectories.filter((item) => item.deviceId === deviceId);
+ const used = group.children.find((topic) =>
+ candidates.some((item) => item.id === topic.projectWorkingDirectoryId),
+ )?.projectWorkingDirectoryId;
+ return used ?? candidates[0]?.id;
+ };
+
+ // Sections start expanded; only the ones the user folds are remembered.
+ const [collapsedIds, setCollapsedIds] = useState<string[]>([]);
+ const expandedIds = useMemo(
+ () => groups?.filter((group) => !collapsedIds.includes(group.id)).map((group) => group.id),
+ [groups, collapsedIds],
+ );
+ const handleExpandedChange = useCallback(
+ (next: unknown[]) =>
+ setCollapsedIds((prev) => [
+ ...prev.filter((id) => !groups?.some((group) => group.id === id)),
+ ...(groups ?? []).filter((group) => !next.includes(group.id)).map((group) => group.id),
+ ]),
+ [groups],
+ );
+
if (!groups) {
return (
<Flexbox gap={1} paddingBlock={1}>
@@ -123,7 +164,12 @@ const ProjectTopicList = memo<ProjectTopicListProps>(({ groupId, topics }) => {
}
return (
- <Flexbox gap={4} paddingBlock={1}>
+ <AccordionRoot
+ indicatorPlacement="inline"
+ style={{ gap: 1, paddingBlock: 1 }}
+ value={expandedIds}
+ onValueChange={handleExpandedChange}
+ >
{groups.map((group) => {
const icon =
mode === 'byStatus'
@@ -131,30 +177,57 @@ const ProjectTopicList = memo<ProjectTopicListProps>(({ groupId, topics }) => {
: mode === 'byDevice'
? { color: cssVar.colorTextTertiary, icon: LaptopIcon }
: undefined;
+ const startDirectoryId = getStartDirectoryId(group);
return (
- <Flexbox gap={1} key={group.id}>
- <Flexbox
- horizontal
- align="center"
- gap={6}
- height={24}
- paddingInline={'12px 8px'}
- style={{ overflow: 'hidden' }}
- >
- {icon && (
- <Center flex={'none'} height={16} width={16}>
- <Icon color={icon.color} icon={icon.icon} size={{ size: 12 }} />
- </Center>
+ <AccordionItem key={group.id} value={group.id}>
+ <AccordionHeader className={'accordion-header'}>
+ {/* Same icon column and gap as the project row, so the section
+ title lines up with the project name and the topics below. */}
+ <AccordionTrigger style={{ paddingBlock: 2, paddingInline: 4 }}>
+ <Flexbox
+ horizontal
+ align="center"
+ gap={8}
+ height={24}
+ style={{ overflow: 'hidden' }}
+ >
+ <Center flex={'none'} height={24} width={28}>
+ {icon && <Icon color={icon.color} icon={icon.icon} size={{ size: 12 }} />}
+ </Center>
+ <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
+ {getTitle(group)}
+ </Text>
+ </Flexbox>
+ </AccordionTrigger>
+ {startDirectoryId && (
+ <div
+ className={cx(
+ 'accordion-action',
+ accordionStyles.action,
+ accordionStyles.actionBorderless,
+ )}
+ >
+ <ActionIcon
+ icon={PlusIcon}
+ size={'small'}
+ title={tProject('directories.start')}
+ onClick={(e) => {
+ e.stopPropagation();
+ onStartInDirectory?.(startDirectoryId);
+ }}
+ />
+ </div>
)}
- <Text ellipsis fontSize={12} type={'secondary'} weight={500}>
- {getTitle(group)}
- </Text>
- </Flexbox>
- {group.children.map(renderTopic)}
- </Flexbox>
+ </AccordionHeader>
+ <AccordionPanel contentStyle={{ padding: 0 }}>
+ <Flexbox gap={1} paddingBlock={1}>
+ {group.children.map(renderTopic)}
+ </Flexbox>
+ </AccordionPanel>
+ </AccordionItem>
);
})}
- </Flexbox>
+ </AccordionRoot>
);
}, isEqual);
diff --git a/src/features/AgentSidebar/Topic/useDropdownMenu.tsx b/src/features/AgentSidebar/Topic/useDropdownMenu.tsx
index 55b9803d6bb..3cd0958c8f9 100644
--- a/src/features/AgentSidebar/Topic/useDropdownMenu.tsx
+++ b/src/features/AgentSidebar/Topic/useDropdownMenu.tsx
@@ -19,6 +19,8 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectors';
+import { getMergedPullRequestTopics } from './utils/mergedPullRequestTopics';
+
const hotArea = css`
&::before {
content: '';
@@ -64,25 +66,10 @@ export const useTopicActionsDropdownMenu = (
const handleArchiveMergedPullRequests = useCallback(
async (scope: TopicMaintenanceScope = 'own') => {
- const mergedTopics = (topics ?? []).filter((topic) => {
- if (
- activeWorkspaceId &&
- scope === 'own' &&
- (!currentUserId || topic.userId !== currentUserId)
- ) {
- return false;
- }
-
- const pullRequest = topic.metadata?.workingDirectoryConfig?.git?.github?.pullRequest;
- const isMerged = !!pullRequest?.mergedAt || pullRequest?.state?.toLowerCase() === 'merged';
-
- return (
- isMerged &&
- topic.status !== 'completed' &&
- topic.status !== 'archived' &&
- topic.status !== 'unread'
- );
- });
+ const mergedTopics = getMergedPullRequestTopics(
+ topics ?? [],
+ activeWorkspaceId && scope === 'own' ? (currentUserId ?? null) : undefined,
+ );
if (mergedTopics.length === 0) {
toast.info(t('actions.archiveMergedPullRequestsNone'));
diff --git a/src/features/AgentSidebar/Topic/utils/mergedPullRequestTopics.ts b/src/features/AgentSidebar/Topic/utils/mergedPullRequestTopics.ts
new file mode 100644
index 00000000000..238679716f8
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/utils/mergedPullRequestTopics.ts
@@ -0,0 +1,24 @@
+import { type ChatTopic } from '@/types/topic';
+
+/**
+ * Topics whose linked PR has merged and that are still open β€” the ones the
+ * "archive merged PR topics" actions mark as completed. Pass `ownerId` to keep
+ * only that user's topics (a workspace member's own scope).
+ */
+export const getMergedPullRequestTopics = (
+ topics: ChatTopic[],
+ ownerId?: string | null,
+): ChatTopic[] =>
+ topics.filter((topic) => {
+ if (ownerId !== undefined && (!ownerId || topic.userId !== ownerId)) return false;
+
+ const pullRequest = topic.metadata?.workingDirectoryConfig?.git?.github?.pullRequest;
+ const isMerged = !!pullRequest?.mergedAt || pullRequest?.state?.toLowerCase() === 'merged';
+
+ return (
+ isMerged &&
+ topic.status !== 'completed' &&
+ topic.status !== 'archived' &&
+ topic.status !== 'unread'
+ );
+ });
diff --git a/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx b/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx
index d4bdf0e84d2..6fc4e7a5d1a 100644
--- a/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx
+++ b/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx
@@ -1,6 +1,13 @@
import type { ChatTopic } from '@lobechat/types';
-import { ActionIcon, DropdownMenu, toast } from '@lobehub/ui/base-ui';
-import { MoreHorizontalIcon, PlusIcon } from 'lucide-react';
+import { Icon } from '@lobehub/ui';
+import { ActionIcon, type DropdownItem, DropdownMenu, toast } from '@lobehub/ui/base-ui';
+import {
+ ArrowUpRightIcon,
+ LinkIcon,
+ MoreHorizontalIcon,
+ PlusIcon,
+ SettingsIcon,
+} from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -18,6 +25,7 @@ export function AgentDirectoryActions({
topics,
onLegacyStart,
hideStartAction = false,
+ extraMenuItems,
}: {
agentId: string;
path: string;
@@ -25,6 +33,8 @@ export function AgentDirectoryActions({
onLegacyStart: (projectWorkingDirectoryId?: string) => Promise<void>;
/** Render only the binding/menu affordance; the caller provides its own start action. */
hideStartAction?: boolean;
+ /** Group-level actions appended to the "more" menu after a divider. */
+ extraMenuItems?: DropdownItem[];
}) {
const { t } = useTranslation('project');
const navigate = useWorkspaceAwareNavigate();
@@ -69,12 +79,14 @@ export function AgentDirectoryActions({
<DropdownMenu
items={[
...bindings.map((directory) => ({
+ icon: <Icon icon={ArrowUpRightIcon} />,
key: `open-${directory.id}`,
label: t('topics.viewProject'),
onClick: () => navigate(`/project/${directory.projectSlug ?? directory.projectId}`),
})),
...(bindings.length ? [{ type: 'divider' as const }] : []),
...bindings.map((directory) => ({
+ icon: <Icon icon={SettingsIcon} />,
key: `settings-${directory.id}`,
label: t('topics.settings'),
onClick: () =>
@@ -84,6 +96,7 @@ export function AgentDirectoryActions({
? []
: [
{
+ icon: <Icon icon={LinkIcon} />,
key: 'bind',
label: t('directories.bind'),
disabled: !deviceId,
@@ -98,6 +111,7 @@ export function AgentDirectoryActions({
}),
},
]),
+ ...(extraMenuItems?.length ? [{ type: 'divider' as const }, ...extraMenuItems] : []),
]}
>
<ActionIcon
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index 3a459166dd1..a4c95dbbaa3 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -445,6 +445,43 @@ describe('ConversationLifecycle actions', () => {
expect(setDocument).not.toHaveBeenCalled();
});
+ // Regression: the send adopts its minted topic (clearing the staged
+ // directory) before the gateway transport runs, so the directory a
+ // project group "+" staged never reached the server and the topic was
+ // born outside the project.
+ it('carries the staged project directory into the gateway send of a new topic', async () => {
+ const { projectWorkingDirectoryService } =
+ await import('@/services/projectWorkingDirectory');
+ vi.spyOn(projectWorkingDirectoryService, 'resolve').mockResolvedValue({
+ data: { deviceId: 'device-85', id: 'dir-85', projectId: 'prj-1' },
+ } as any);
+ const { result } = renderHook(() => useChatStore());
+ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({ topicId: 'tpc_new' });
+
+ act(() => {
+ useChatStore.setState({
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ pendingNewTopicDirectory: {
+ agentId: TEST_IDS.SESSION_ID,
+ projectWorkingDirectoryId: 'dir-85',
+ },
+ });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ context: createTestContext(),
+ message: 'Start in the directory',
+ });
+ });
+
+ expect(projectWorkingDirectoryService.resolve).toHaveBeenCalledWith('dir-85');
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ projectWorkingDirectoryId: 'dir-85' }),
+ );
+ });
+
it('should restore the pre-send editor snapshot when a gateway send fails', async () => {
// Regression: the composer is cleared the instant Enter is pressed, and
// only the client-runtime branch put the text back. The gateway branch
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index 2b3de128163..3ab24c74653 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -2021,6 +2021,65 @@ describe('GatewayActionImpl', () => {
);
});
+ // Regression: the directory a project group "+" staged never reached the
+ // server, so the first send created the topic outside the project.
+ it('forwards the staged project directory when creating a topic', async () => {
+ const { action } = createExecuteTestAction();
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({
+ agentId: 'agent-1',
+ assistantMessageId: 'ast-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'ok',
+ operationId: 'server-op-1',
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: 'test-token',
+ topicId: 'topic-new',
+ userMessageId: 'usr-1',
+ });
+
+ await action.executeGatewayAgent({
+ context: { agentId: 'agent-1', scope: 'main' },
+ message: 'Start in the directory',
+ projectWorkingDirectoryId: 'dir-1',
+ });
+
+ expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ appContext: expect.objectContaining({ projectWorkingDirectoryId: 'dir-1' }),
+ }),
+ );
+ });
+
+ it('does not forward a project directory for a send into an existing topic', async () => {
+ const { action } = createExecuteTestAction();
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({
+ agentId: 'agent-1',
+ assistantMessageId: 'ast-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'ok',
+ operationId: 'server-op-1',
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: 'test-token',
+ topicId: 'topic-1',
+ userMessageId: 'usr-1',
+ });
+
+ await action.executeGatewayAgent({
+ context: { agentId: 'agent-1', scope: 'main', topicId: 'topic-1' },
+ message: 'Keep going',
+ projectWorkingDirectoryId: 'dir-1',
+ });
+
+ const appContext = vi.mocked(aiAgentService.execAgentTask).mock.calls.at(-1)![0].appContext;
+ expect(appContext).not.toHaveProperty('projectWorkingDirectoryId');
+ });
+
it('should forward empty prompt for continue generation', async () => {
const { action } = createExecuteTestAction();
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 910f53d50bd..5e6ed8e5f23 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -495,10 +495,22 @@ export class ConversationLifecycleActionImpl {
const boundTopic = context.topicId
? topicSelectors.getTopicById(context.topicId)(this.#get())
: undefined;
- if (boundTopic?.projectWorkingDirectoryId) {
- const { data: directory } = await projectWorkingDirectoryService.resolve(
- boundTopic.projectWorkingDirectoryId,
- );
+ // A blank conversation opened from a project group's "+" runs in the
+ // directory it staged; the gateway transport has the server bind the topic.
+ const pendingDirectory = this.#get().pendingNewTopicDirectory;
+ const stagedDirectoryId =
+ !context.topicId &&
+ !context.isolatedTopic &&
+ !context.groupId &&
+ !directMentionRoute &&
+ pendingDirectory?.agentId === ownerAgentId
+ ? pendingDirectory.projectWorkingDirectoryId
+ : undefined;
+ const projectDirectoryId = boundTopic?.projectWorkingDirectoryId ?? stagedDirectoryId;
+ let stagedDirectory: { id: string; projectId: string } | undefined;
+ if (projectDirectoryId) {
+ const { data: directory } = await projectWorkingDirectoryService.resolve(projectDirectoryId);
+ if (stagedDirectoryId) stagedDirectory = directory;
if (!isGatewayMode)
throw new Error('Enable Gateway Mode to run in a project working directory');
if (
@@ -1168,6 +1180,11 @@ export class ConversationLifecycleActionImpl {
value: {
id: mintedTopicId,
...newTopicModelSnapshot,
+ // Shown under its project group from the first frame.
+ ...(stagedDirectory && {
+ projectId: stagedDirectory.projectId,
+ projectWorkingDirectoryId: stagedDirectory.id,
+ }),
...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),
title: newTopicTitle,
},
@@ -1886,6 +1903,7 @@ export class ConversationLifecycleActionImpl {
clientOperations,
replacesOperationId: replaceableGatewayOperationId,
optimisticTopic,
+ projectWorkingDirectoryId: stagedDirectory?.id,
// 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.
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 4200cbbb394..3a8be3c6389 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -1066,6 +1066,12 @@ 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.
+ */
+ projectWorkingDirectoryId?: string;
/** Server operation whose visible output ended before this fresh turn. */
replacesOperationId?: string;
/** Diagnostic snapshot of the conversation's server runs, see `ExecAgentTaskParams`. */
@@ -1139,6 +1145,7 @@ export class GatewayActionImpl {
parentMessageId,
parentOperationId,
precreatedResult,
+ projectWorkingDirectoryId,
replacesOperationId,
resumeApproval,
resumeApprovals,
@@ -1316,6 +1323,7 @@ export class GatewayActionImpl {
// supervisor turn loses its role on the step_start snapshot / refetch
// and renders as a generic assistant.
orchestrationRole: executionContext.orchestrationRole,
+ ...(isCreateNewTopic && projectWorkingDirectoryId && { projectWorkingDirectoryId }),
scope: executionContext.scope,
taskId,
threadId: executionContext.threadId,