π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(project): open a blank composer from the project sidebar "+" (#21471)
Arvin Xu5e3260e92e2c
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsxindex b85588c4b78..4313c430ce2 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx@@ -2,7 +2,7 @@* @vitest-environment happy-dom*/import { AccordionRoot } from '@lobehub/ui';-import { render, screen } from '@testing-library/react';+import { fireEvent, render, screen } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';import { TopicListScopeContext } from '../../TopicListScope';@@ -10,12 +10,19 @@ import GroupItem from './GroupItem';const subGroupModes: Record<string, string> = {};let registeredMeta: { avatar?: string; name?: string; title?: string } = {};+const agencyConfigById: Record<+ string,+ { boundDeviceId?: string; executionTargetSelectionPolicy?: string }+> = {};vi.mock('@/store/agent', () => ({useAgentStore: (selector: (state: unknown) => unknown) => selector({ activeAgentId: 'agent-1' }),}));vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: {+ getAgencyConfigById: (id: string) => () => agencyConfigById[id],+ },agentSelectors: {currentAgentMeta: () => ({ title: 'ιͺζΆεεΉΆ-Alpha', avatar: 'π °οΈ' }),getAgentMetaById: () => () => registeredMeta,@@ -33,14 +40,41 @@ vi.mock('@/store/global/selectors', () => ({},}));-const directories: { deviceId: string; id: string; instanceId?: string }[] = [];+const directories: {+ deviceId: string;+ environmentId?: string;+ id: string;+ instanceId?: string;+ permission?: string;+}[] = [];+const runnable = (instanceId: string) => ({+ environmentId: 'env-1',+ instanceId,+ permission: 'readWrite',+});vi.mock('@/store/projectWorkingDirectory', () => ({useProjectDirectories: () => directories,}));-vi.mock('@/features/Projects/WorkingDirectories/StartDirectoryModal', () => ({+const { navigate, openProjectTopicModal, startProjectTopicDraft } = vi.hoisted(() => ({+ navigate: vi.fn(),openProjectTopicModal: vi.fn(),+ startProjectTopicDraft: vi.fn(),+}));++vi.mock('@/features/Projects/WorkingDirectories/StartDirectoryModal', () => ({+ openProjectTopicModal,+}));+vi.mock(+ '@/features/Projects/WorkingDirectories/startProjectTopicDraft',+ async (importOriginal) => ({+ ...(await importOriginal<object>()),+ startProjectTopicDraft,+ }),+);+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => navigate,}));vi.mock('@/store/device', () => ({@@ -135,8 +169,10 @@ const renderGroup = () =>describe('TopicByAgentGroupItem', () => {beforeEach(() => {+ vi.clearAllMocks();for (const key of Object.keys(subGroupModes)) delete subGroupModes[key];registeredMeta = {};+ for (const key of Object.keys(agencyConfigById)) delete agencyConfigById[key];directories.splice(0,directories.length,@@ -179,10 +215,108 @@ describe('TopicByAgentGroupItem', () => {// device, but the new-topic modal only lists instance-bound directories,// so a legacy directory opened with an unselectable raw id.subGroupModes[GROUP_ID] = 'byDevice';- directories[0] = { ...directories[0], instanceId: 'ins-mac' };+ directories[0] = { ...directories[0], ...runnable('ins-mac') };+ renderGroup();++ expect(screen.getAllByRole('button', { name: 'directories.start' })).toHaveLength(1);+ });++ /** @example User report: the device "+" popped a "new topic" modal instead of opening the composer. */+ it('starts a blank conversation on the device directory from the section "+" without a modal', () => {+ // ROOT CAUSE: the project sidebar "+" always opened the work-location+ // modal and created the topic row up front, unlike an agent's "+", which+ // only opens the composer and lets the first message create the topic.+ subGroupModes[GROUP_ID] = 'byDevice';+ directories[1] = { ...directories[1], ...runnable('ins-linux') };+ renderGroup();++ fireEvent.click(screen.getByRole('button', { name: 'directories.start' }));++ expect(startProjectTopicDraft).toHaveBeenCalledWith({+ agentId: 'agt_acc_merge_alpha',+ directoryId: 'binding-linux',+ navigate,+ projectId: 'project-1',+ });+ expect(openProjectTopicModal).not.toHaveBeenCalled();+ });++ /** @example Review: the agent "+" staged a read-only directory, so the first send was refused. */+ it('skips a directory that cannot run when the agent "+" picks the default', () => {+ directories[0] = { ...directories[0], ...runnable('ins-mac'), permission: 'read' };+ directories[1] = { ...directories[1], ...runnable('ins-linux') };+ renderGroup();++ fireEvent.click(screen.getByRole('button', { name: 'sidebar.newConversation' }));++ expect(startProjectTopicDraft).toHaveBeenCalledWith(+ expect.objectContaining({ directoryId: 'binding-linux' }),+ );+ });++ /** @example Review: an agent fixed to one device staged a directory on another, so the first send was refused. */+ it('picks a directory on the device a fixed agent is bound to', () => {+ // ROOT CAUSE: the agent "+" took the first runnable directory whatever the+ // agent's fixed execution target was, and `resolveProjectDirectoryRun`+ // throws "Agent is fixed to another execution target" on the first send.+ directories[0] = { ...directories[0], ...runnable('ins-mac') };+ directories[1] = { ...directories[1], ...runnable('ins-linux') };+ agencyConfigById.agt_acc_merge_alpha = {+ boundDeviceId: 'device-2',+ executionTargetSelectionPolicy: 'fixed',+ };+ renderGroup();++ fireEvent.click(screen.getByRole('button', { name: 'sidebar.newConversation' }));++ expect(startProjectTopicDraft).toHaveBeenCalledWith(+ expect.objectContaining({ directoryId: 'binding-linux' }),+ );+ });++ /** @example Review: a fixed agent's "+" staged another device's directory, so the first send threw. */+ it('offers a device section "+" only on the device a fixed agent is bound to', () => {+ subGroupModes[GROUP_ID] = 'byDevice';+ agencyConfigById.agt_acc_merge_alpha = {+ boundDeviceId: 'device-2',+ executionTargetSelectionPolicy: 'fixed',+ };+ directories[0] = { ...directories[0], ...runnable('ins-mac') };+ directories[1] = { ...directories[1], ...runnable('ins-linux') };renderGroup();+ // Only the fixed device's section offers a "+".expect(screen.getAllByRole('button', { name: 'directories.start' })).toHaveLength(1);++ fireEvent.click(screen.getByRole('button', { name: 'sidebar.newConversation' }));++ expect(startProjectTopicDraft).toHaveBeenCalledWith(+ expect.objectContaining({ directoryId: 'binding-linux' }),+ );+ });++ it('opens the modal instead of a 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') };+ agencyConfigById.agt_acc_merge_alpha = { executionTargetSelectionPolicy: 'fixed' };+ renderGroup();++ expect(screen.queryAllByRole('button', { name: 'directories.start' })).toHaveLength(0);++ fireEvent.click(screen.getByRole('button', { name: 'sidebar.newConversation' }));++ expect(startProjectTopicDraft).not.toHaveBeenCalled();+ expect(openProjectTopicModal).toHaveBeenCalledTimes(1);+ });++ it('keeps the modal for a project with no runnable directory, so one can be added', () => {+ renderGroup();++ fireEvent.click(screen.getByRole('button', { name: 'sidebar.newConversation' }));++ expect(startProjectTopicDraft).not.toHaveBeenCalled();+ expect(openProjectTopicModal).toHaveBeenCalledTimes(1);});const renderInProject = (agentId: string) =>diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsxindex 6c03862c50a..d30e4c67115 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx@@ -26,6 +26,12 @@ import { useTranslation } from 'react-i18next';import Avatar from '@/components/Avatar';import { openProjectTopicModal } from '@/features/Projects/WorkingDirectories/StartDirectoryModal';+import {+ canStageDraftOn,+ startProjectTopicDraft,+} from '@/features/Projects/WorkingDirectories/startProjectTopicDraft';+import { useAgentFixedDeviceId } from '@/features/Projects/WorkingDirectories/useAgentFixedDeviceId';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { useGlobalStore } from '@/store/global';@@ -95,16 +101,26 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {// Only an attributed bucket in a project-scoped list can start a topic with// its agent preselected; the `no-agent` bucket has no agent to preselect.const canAddTopic = !!scope && !!agentId;- // The new-topic modal's picker only lists instance-bound directories; a- // device section offering any other directory would open with an unselectable- // work location, so its "+" only considers instance-bound ones.+ // A directory that can't run work β or one on another device than the agent+ // is fixed to β would stage a draft whose first send is refused, so both the+ // default and the device sections' "+" only consider ones the agent can use.+ const fixedDeviceId = useAgentFixedDeviceId(agentId);const startDirectories = useMemo(- () => (canAddTopic ? directories.filter((directory) => directory.instanceId) : undefined),- [canAddTopic, directories],+ () => (canAddTopic ? directories.filter((d) => canStageDraftOn(d, fixedDeviceId)) : undefined),+ [canAddTopic, directories, fixedDeviceId],);+ const navigate = useWorkspaceAwareNavigate();+ // Same habit as an agent's "+": open a blank conversation on a directory and+ // let the first message create the topic. The modal is only the fallback for+ // a project with no runnable directory yet β it offers to add one.const handleAddTopic = (initialDirectoryId?: string) => {if (!scope || !agentId) return;+ const directoryId = initialDirectoryId ?? startDirectories?.[0]?.id;+ if (directoryId) {+ startProjectTopicDraft({ agentId, directoryId, navigate, projectId: scope.projectId });+ return;+ }openProjectTopicModal({coordinatorAgentId: scope.coordinatorAgentId ?? agentId,directories,diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsxindex a872be5bcb1..c7a19b1cbdd 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx@@ -20,7 +20,9 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';-import { openProjectTopicModal } from '@/features/Projects/WorkingDirectories/StartDirectoryModal';+import { startProjectTopicDraft } from '@/features/Projects/WorkingDirectories/startProjectTopicDraft';+import { useAgentFixedDeviceId } from '@/features/Projects/WorkingDirectories/useAgentFixedDeviceId';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useAgentStore } from '@/store/agent';import { useDeviceStore } from '@/store/device';import { deviceSelectors } from '@/store/device/selectors';@@ -61,20 +63,22 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {unknownLabel: t('groupTitle.byDevice.unknown'),});- // Preselect a directory on this device so the new topic starts where the- // group points; the modal's picker only lists instance-bound directories, so- // without one on this device the + would silently start work on another.+ // Stage a directory on this device so the blank conversation runs where the+ // group points; only a runnable directory can take the run, so without+ // one on this device the + would silently start work on another. An agent+ // fixed to another device could never run here, so it gets no "+".+ const navigate = useWorkspaceAwareNavigate();const fallbackAgentId = scope?.coordinatorAgentId ?? activeAgentId;- const targetDirectory = findDeviceTopicDirectory(directories, deviceId);+ const fixedDeviceId = useAgentFixedDeviceId(fallbackAgentId);+ const targetDirectory = findDeviceTopicDirectory(directories, deviceId, fixedDeviceId);const canAddTopic = !!scope && !!deviceId && !!fallbackAgentId && !!targetDirectory;const handleAddTopic = () => {if (!scope || !deviceId || !fallbackAgentId || !targetDirectory) return;- openProjectTopicModal({- coordinatorAgentId: fallbackAgentId,- directories,- initialDirectoryId: targetDirectory.id,+ startProjectTopicDraft({+ agentId: fallbackAgentId,+ directoryId: targetDirectory.id,+ navigate,projectId: scope.projectId,- title: tProject('sidebar.newConversation'),});};diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.test.ts b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.test.tsindex 2a9266ceccc..2efa19ceddf 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.test.ts+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.test.ts@@ -4,8 +4,20 @@ import { findDeviceTopicDirectory, resolveDeviceGroupName } from './resolveDevicconst directories = [{ deviceId: 'dev-a', id: 'dir-a-plain' },- { deviceId: 'dev-a', id: 'dir-a-instance', instanceId: 'ins-1' },- { deviceId: 'dev-b', id: 'dir-b-instance', instanceId: 'ins-2' },+ {+ deviceId: 'dev-a',+ id: 'dir-a-instance',+ environmentId: 'env-1',+ instanceId: 'ins-1',+ permission: 'readWrite',+ },+ {+ deviceId: 'dev-b',+ id: 'dir-b-instance',+ environmentId: 'env-1',+ instanceId: 'ins-2',+ permission: 'readWrite',+ },];describe('findDeviceTopicDirectory', () => {@@ -20,6 +32,23 @@ describe('findDeviceTopicDirectory', () => {);});+ /** @example Review: a read-only or unlinked directory was staged, so the first send was refused. */+ it('skips a directory that cannot run β read-only or without a linked environment', () => {+ const runnable = { deviceId: 'dev-d', environmentId: 'env-1', permission: 'readWrite' };+ const rows = [+ { ...runnable, id: 'dir-d-readonly', instanceId: 'ins-3', permission: 'read' },+ { ...runnable, environmentId: null, id: 'dir-d-unlinked', instanceId: 'ins-4' },+ { ...runnable, id: 'dir-d-ok', instanceId: 'ins-5' },+ ];++ expect(findDeviceTopicDirectory(rows, 'dev-d')?.id).toBe('dir-d-ok');+ });++ it('offers nothing on a device other than the one the agent is fixed to', () => {+ expect(findDeviceTopicDirectory(directories, 'dev-a', 'dev-b')).toBeUndefined();+ expect(findDeviceTopicDirectory(directories, 'dev-b', 'dev-b')?.id).toBe('dir-b-instance');+ });+it('returns undefined for groups without a device (favorites, unknown bucket)', () => {expect(findDeviceTopicDirectory(directories, undefined)).toBeUndefined();expect(findDeviceTopicDirectory(directories)).toBeUndefined();diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.ts b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.tsindex 7a17d247a46..d40ee8ca78d 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.ts+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.ts@@ -1,20 +1,27 @@+import { canStageDraftOn } from '@/features/Projects/WorkingDirectories/startProjectTopicDraft';+interface DeviceDirectoryLike {deviceId?: string | null;+ environmentId?: string | null;id: string;instanceId?: string | null;+ permission?: string | null;}/**- * The add-topic affordance on a device group is only safe when the modal can- * preselect an instance-bound directory on THIS device β its picker lists- * instance-bound directories only, so without one it silently falls back to- * another device's directory and the topic would start on the wrong device.+ * The add-topic affordance on a device group is only safe with a runnable+ * directory on THIS device that the draft's agent may run on β otherwise the+ * blank conversation would be staged somewhere the first send is refused, or+ * on another device altogether.*/export const findDeviceTopicDirectory = <T extends DeviceDirectoryLike>(directories: T[],deviceId?: string,+ fixedDeviceId?: string | null,): T | undefined =>- deviceId ? directories.find((d) => d.deviceId === deviceId && d.instanceId) : undefined;+ deviceId+ ? directories.find((d) => d.deviceId === deviceId && canStageDraftOn(d, fixedDeviceId))+ : undefined;/*** A synthetic bucket (e.g. favorites) carries its own title and wins over anydiff --git a/src/features/Conversation/useAgentConversationCoordinate.desktop.test.ts b/src/features/Conversation/useAgentConversationCoordinate.desktop.test.tsindex 3377b67e4ff..31f44d125ec 100644--- a/src/features/Conversation/useAgentConversationCoordinate.desktop.test.ts+++ b/src/features/Conversation/useAgentConversationCoordinate.desktop.test.ts@@ -71,6 +71,16 @@ describe('useAgentConversationCoordinate (desktop)', () => {expect(result.current).toEqual(['agent-of-topic', 'tpc_1', null]);});+ /** @example Review: on desktop the sidebar "+" draft had no agent, so its first send was a no-op. */+ it('takes the agent of a blank project draft from its route', () => {+ route.params = { projectId: 'prj_1' };+ route.search = new URLSearchParams('agent=agent-of-draft&dir=pwd_1');++ const { result } = renderHook(() => useAgentConversationCoordinate());++ expect(result.current).toEqual(['agent-of-draft', null, null]);+ });+it('keeps agent undefined for an unknown project topic instead of falling back to the global pointer', () => {route.params = { projectId: 'prj_1', topicId: 'tpc_unknown' };route.search = new URLSearchParams();diff --git a/src/features/Conversation/useAgentConversationCoordinate.desktop.ts b/src/features/Conversation/useAgentConversationCoordinate.desktop.tsindex 906fd57c89d..7ba4adc8863 100644--- a/src/features/Conversation/useAgentConversationCoordinate.desktop.ts+++ b/src/features/Conversation/useAgentConversationCoordinate.desktop.ts@@ -11,8 +11,13 @@ export const useAgentConversationCoordinate = () => {// owning agent resolves from the project topic β still route-derived per tab,// never the global pointer (another tab may own it).const projectTopics = useProjectTopics(params.aid ? undefined : params.projectId);+ // A blank draft a sidebar "+" opened has no topic yet; its owner rides in the+ // route (`?agent=`) and stays there through the first send's topic switch,+ // until the project list has the new topic.const projectTopicAgentId = params.projectId- ? projectTopics.find((topic) => topic.id === params.topicId)?.agentId+ ? (projectTopics.find((topic) => topic.id === params.topicId)?.agentId ??+ searchParams.get('agent') ??+ undefined): undefined;return [diff --git a/src/features/Projects/Conversation/freshProjectTopicAgentId.test.ts b/src/features/Projects/Conversation/freshProjectTopicAgentId.test.tsnew file mode 100644index 00000000000..f71c4a1d06b--- /dev/null+++ b/src/features/Projects/Conversation/freshProjectTopicAgentId.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';++import { freshProjectTopicAgentId } from './freshProjectTopicAgentId';++const fresh = {+ listed: false,+ projectId: 'prj_a',+ storedTopic: { projectId: 'prj_a', sessionId: 'agt_owner' },+ topicId: 'tpc_new',+};++describe('freshProjectTopicAgentId', () => {+ it('returns the owner of a just-created topic of this project before the list has it', () => {+ expect(freshProjectTopicAgentId(fresh)).toBe('agt_owner');+ });++ /** @example Review: project A's cached topic rendered inside project B's conversation URL. */+ it("does not treat another project's cached topic as fresh", () => {+ expect(freshProjectTopicAgentId({ ...fresh, projectId: 'prj_b' })).toBeUndefined();+ expect(+ freshProjectTopicAgentId({+ ...fresh,+ storedTopic: { projectId: null, sessionId: 'agt_owner' },+ }),+ ).toBeUndefined();+ });++ /** @example Review: another pane changed the focused agent, and the fresh topic was rebound to it. */+ it('takes the owner from the topic row, so a topic without one is not adopted', () => {+ expect(+ freshProjectTopicAgentId({ ...fresh, storedTopic: { projectId: 'prj_a' } }),+ ).toBeUndefined();+ });++ it('keeps the remembered owner once a refreshed row no longer carries one', () => {+ const refreshed = { ...fresh, storedTopic: { projectId: 'prj_a' } };++ expect(+ freshProjectTopicAgentId({+ ...refreshed,+ rememberedOwner: { agentId: 'agt_owner', topicId: 'tpc_new' },+ }),+ ).toBe('agt_owner');+ expect(+ freshProjectTopicAgentId({+ ...refreshed,+ rememberedOwner: { agentId: 'agt_owner', topicId: 'tpc_other' },+ }),+ ).toBeUndefined();+ });++ it('is undefined once the project list has the topic', () => {+ expect(freshProjectTopicAgentId({ ...fresh, listed: true })).toBeUndefined();+ });+});diff --git a/src/features/Projects/Conversation/freshProjectTopicAgentId.ts b/src/features/Projects/Conversation/freshProjectTopicAgentId.tsnew file mode 100644index 00000000000..7f18dd6b721--- /dev/null+++ b/src/features/Projects/Conversation/freshProjectTopicAgentId.ts@@ -0,0 +1,28 @@+/**+ * The owning agent of a topic the route points at that the project list doesn't+ * have yet, but the chat store does: the first send of a blank project+ * conversation moves the route before the list catches up. Undefined for+ * anything else β another project's cached topic must still read as not found.+ *+ * The owner comes from the topic row (`sessionId`), never the globally focused+ * agent: another pane may change that while this one waits for the list, and+ * this pane would then load β and write back β the wrong agent. Only the+ * optimistic row carries `sessionId` (server list rows strip it), so once a+ * refresh replaces that row the caller passes back the owner it remembered.+ */+export const freshProjectTopicAgentId = (params: {+ listed: boolean;+ projectId: string | undefined;+ rememberedOwner?: { agentId: string; topicId: string };+ storedTopic: { projectId?: string | null; sessionId?: string | null } | undefined;+ topicId: string | undefined;+}): string | undefined => {+ const { listed, projectId, rememberedOwner, storedTopic, topicId } = params;+ if (!topicId || listed || !storedTopic?.projectId || storedTopic.projectId !== projectId)+ return undefined;++ return (+ storedTopic.sessionId ??+ (rememberedOwner?.topicId === topicId ? rememberedOwner.agentId : undefined)+ );+};diff --git a/src/features/Projects/Conversation/index.tsx b/src/features/Projects/Conversation/index.tsxindex 28a85e04273..ee53e652668 100644--- a/src/features/Projects/Conversation/index.tsx+++ b/src/features/Projects/Conversation/index.tsx@@ -1,9 +1,9 @@'use client';import { Center, Flexbox, Spin, Text } from '@lobehub/ui';-import { memo, useCallback, useLayoutEffect } from 'react';+import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';-import { Navigate, useParams } from 'react-router';+import { Navigate, useParams, useSearchParams } from 'react-router';import AsyncError from '@/components/AsyncError';import TopicActions from '@/features/AgentSidebar/Topic/List/Item/Actions';@@ -18,9 +18,16 @@ import { useAgentStore } from '@/store/agent';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';import { useCurrentProjectDetail, useProjectStore } from '@/store/project';-import { useProjectDirectoryStore, useProjectTopics } from '@/store/projectWorkingDirectory';+import {+ useProjectDirectories,+ useProjectDirectoryStore,+ useProjectTopics,+} from '@/store/projectWorkingDirectory';import { getProjectConversationPath } from '../Layout/navigation';+import { freshProjectTopicAgentId } from './freshProjectTopicAgentId';+import { useProjectDraftStaging } from './useProjectDraftStaging';+import { useRevalidateWhileUnlisted } from './useRevalidateWhileUnlisted';const ProjectConversation = memo(() => {const { t } = useTranslation('project');@@ -32,18 +39,54 @@ const ProjectConversation = memo(() => {);const topics = useProjectTopics(detail?.project.id);const selectedTopic = topics.find((topic) => topic.id === topicId);- const conversationAgentId = topicId- ? (selectedTopic?.agentId ?? undefined)- : detail?.project.coordinatorAgentId;const projectSlug = detail?.project.slug ?? projectId;const storedTopic = useChatStore((s) =>topicId ? topicSelectors.getTopicById(topicId)(s) : undefined,);+ // A sidebar "+" opens a blank draft instead of creating a row (see+ // `startProjectTopicDraft`). The draft rides in this pane's route, so split+ // panes keep their own; the first message creates the topic.+ const [searchParams] = useSearchParams();+ const draftAgentParam = topicId ? null : searchParams.get('agent');+ const draftDirectoryParam = topicId ? null : searchParams.get('dir');+ const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(+ detail?.project.id,+ );+ const directories = useProjectDirectories(detail?.project.id);+ const directoryIds = useMemo(() => new Set(directories.map((d) => d.id)), [directories]);+ const draft = useMemo(+ () =>+ draftAgentParam && draftDirectoryParam && directoryIds.has(draftDirectoryParam)+ ? { agentId: draftAgentParam, projectWorkingDirectoryId: draftDirectoryParam }+ : undefined,+ [draftAgentParam, draftDirectoryParam, directoryIds],+ );+ const draftAgentId = draft?.agentId;+ const restageDraft = useProjectDraftStaging(draft, directoryIds);+ const chatAgentId = useChatStore((s) => s.activeAgentId);+ // Keep the conversation on its agent instead of flashing "not found" while+ // the project list catches up with a topic the first send just created.+ const freshOwnerRef = useRef<{ agentId: string; topicId: string }>(undefined);+ const freshTopicAgentId = freshProjectTopicAgentId({+ listed: !!selectedTopic,+ projectId: detail?.project.id,+ rememberedOwner: freshOwnerRef.current,+ storedTopic,+ topicId,+ });+ useEffect(() => {+ if (freshTopicAgentId && topicId)+ freshOwnerRef.current = { agentId: freshTopicAgentId, topicId };+ }, [freshTopicAgentId, topicId]);+ const isFreshTopic = !!freshTopicAgentId;+ const conversationAgentId = topicId+ ? (selectedTopic?.agentId ?? freshTopicAgentId)+ : draftAgentId;+ useRevalidateWhileUnlisted(isFreshTopic, topicId, topicsRequest.revalidate);const topicTitle = storedTopic?.title;const agent = useInitAgentConfig(conversationAgentId);const topicDetail = useChatStore((s) => s.useFetchTopicDetail)(selectedTopic?.id);- const activeAgentId = useChatStore((s) => s.activeAgentId);useLayoutEffect(() => {if (!conversationAgentId) return;@@ -76,9 +119,19 @@ const ProjectConversation = memo(() => {return (<AsyncError error={topicsRequest.error} variant="page" onRetry={topicsRequest.revalidate} />);- // New project conversations start from the project home composer.- if (!topicId) return <Navigate replace relative="path" to=".." />;- if (topicsRequest.hasData && !selectedTopic)+ if (!topicId && !draftAgentId) {+ // A draft's directory list may still be loading; wait for it rather than+ // sending the draft away.+ if (draftAgentParam && !directoriesRequest.hasData)+ return (+ <Center height="100%" width="100%">+ <Spin size="small" />+ </Center>+ );+ // Other new project conversations start from the project home composer.+ return <Navigate replace relative="path" to=".." />;+ }+ if (topicId && topicsRequest.hasData && !selectedTopic && !isFreshTopic)return (<Center height="100%"><Text>{t('topics.notFound')}</Text>@@ -92,7 +145,7 @@ const ProjectConversation = memo(() => {!conversationAgentId ||agent.isLoading ||(!storedTopic && topicDetail.isValidating) ||- activeAgentId !== conversationAgentId+ chatAgentId !== conversationAgentId) {return (<Center height="100%" width="100%">@@ -114,21 +167,30 @@ const ProjectConversation = memo(() => {<Flexbox horizontal align="center" gap={4}><TerminalPanelToggle /><WorkingPanelToggle />- <TopicActions- id={topicId}- status={selectedTopic?.status}- title={topicTitle || selectedTopic?.title || t('directories.untitled')}- completionLabel={t(- selectedTopic?.status === 'completed' ? 'topics.resume' : 'topics.complete',- )}- />+ {topicId && (+ <TopicActions+ id={topicId}+ status={selectedTopic?.status}+ title={topicTitle || selectedTopic?.title || t('directories.untitled')}+ completionLabel={t(+ selectedTopic?.status === 'completed' ? 'topics.resume' : 'topics.complete',+ )}+ />+ )}</Flexbox>}/>}><ChatHydration getConversationPath={getConversationPath} getTopicPath={getTopicPath} />- <ChatConversation />+ <Flexbox+ flex={1}+ style={{ minHeight: 0, minWidth: 0 }}+ onFocusCapture={restageDraft}+ onPointerDownCapture={restageDraft}+ >+ <ChatConversation />+ </Flexbox></ConversationWorkspace>);});diff --git a/src/features/Projects/Conversation/useProjectDraftStaging.test.ts b/src/features/Projects/Conversation/useProjectDraftStaging.test.tsnew file mode 100644index 00000000000..ee3e1c4f466--- /dev/null+++ b/src/features/Projects/Conversation/useProjectDraftStaging.test.ts@@ -0,0 +1,52 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it } from 'vitest';++import { useChatStore } from '@/store/chat';++import { useProjectDraftStaging } from './useProjectDraftStaging';++const ids = new Set(['pwd_mac', 'pwd_linux']);+const paneA = { agentId: 'agt_a', projectWorkingDirectoryId: 'pwd_mac' };+const paneB = { agentId: 'agt_b', projectWorkingDirectoryId: 'pwd_linux' };++const pending = () => useChatStore.getState().pendingNewTopicDirectory;++describe('useProjectDraftStaging', () => {+ beforeEach(() => {+ act(() => useChatStore.getState().setPendingNewTopicDirectory());+ });++ it("stages the pane's draft when it mounts", () => {+ renderHook(() => useProjectDraftStaging(paneA, ids));++ expect(pending()).toEqual(paneA);+ });++ /** @example Review: a draft opened in a second split pane overwrote the first pane's staging. */+ it('restages its own draft when the user returns to the pane', () => {+ const a = renderHook(() => useProjectDraftStaging(paneA, ids));+ renderHook(() => useProjectDraftStaging(paneB, ids));+ expect(pending()).toEqual(paneB);++ act(() => a.result.current());++ expect(pending()).toEqual(paneA);+ });++ it('follows a device switch in its own composer instead of reverting it', () => {+ const a = renderHook(() => useProjectDraftStaging(paneA, ids));+ const switched = { agentId: 'agt_a', projectWorkingDirectoryId: 'pwd_linux' };++ act(() => useChatStore.getState().setPendingNewTopicDirectory(switched));+ act(() => a.result.current());++ expect(pending()).toEqual(switched);+ });++ it('stages nothing without a draft', () => {+ const { result } = renderHook(() => useProjectDraftStaging(undefined, ids));+ act(() => result.current());++ expect(pending()).toBeUndefined();+ });+});diff --git a/src/features/Projects/Conversation/useProjectDraftStaging.ts b/src/features/Projects/Conversation/useProjectDraftStaging.tsnew file mode 100644index 00000000000..5b3eff54fae--- /dev/null+++ b/src/features/Projects/Conversation/useProjectDraftStaging.ts@@ -0,0 +1,62 @@+import { useCallback, useEffect, useRef } from 'react';++import { useChatStore } from '@/store/chat';++interface Draft {+ agentId: string;+ projectWorkingDirectoryId: string;+}++const sameDraft = (a: Draft | undefined, b: Draft | undefined) =>+ a?.agentId === b?.agentId && a?.projectWorkingDirectoryId === b?.projectWorkingDirectoryId;++/**+ * Keep this pane's blank draft staged for the send.+ *+ * The send reads one global `pendingNewTopicDirectory`, but desktop split view+ * mounts a router per pane. Each pane therefore owns its draft (from its route)+ * and re-stages it whenever it mounts or the user interacts with it, so a draft+ * opened in another pane can't make this one send to the wrong agent/device.+ * A device switch in this pane's composer restages the global value; the pane+ * follows it while it stays on the same agent and project.+ */+export const useProjectDraftStaging = (+ draft: Draft | undefined,+ projectDirectoryIds: ReadonlySet<string>,+) => {+ const ownRef = useRef(draft);+ const directoryIdsRef = useRef(projectDirectoryIds);+ directoryIdsRef.current = projectDirectoryIds;++ const restage = useCallback(() => {+ const own = ownRef.current;+ if (!own) return;+ const { pendingNewTopicDirectory, setPendingNewTopicDirectory } = useChatStore.getState();+ if (!sameDraft(pendingNewTopicDirectory, own)) setPendingNewTopicDirectory(own);+ }, []);++ useEffect(() => {+ ownRef.current = draft;+ restage();+ }, [draft?.agentId, draft?.projectWorkingDirectoryId, restage]);++ useEffect(+ () =>+ useChatStore.subscribe(+ (s) => s.pendingNewTopicDirectory,+ (pending) => {+ const own = ownRef.current;+ if (+ own &&+ pending &&+ pending.agentId === own.agentId &&+ directoryIdsRef.current.has(pending.projectWorkingDirectoryId)+ )+ ownRef.current = pending;+ },+ ),+ [],+ );++ return restage;+};diff --git a/src/features/Projects/Conversation/useRevalidateWhileUnlisted.test.ts b/src/features/Projects/Conversation/useRevalidateWhileUnlisted.test.tsnew file mode 100644index 00000000000..df89b172ff2--- /dev/null+++ b/src/features/Projects/Conversation/useRevalidateWhileUnlisted.test.ts@@ -0,0 +1,42 @@+import { renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useRevalidateWhileUnlisted } from './useRevalidateWhileUnlisted';++describe('useRevalidateWhileUnlisted', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ /** @example Review: the only refetch ran before the send persisted the topic, so the sidebar never showed it. */+ it('keeps refetching while the fresh topic is unlisted, and stops once it is listed', () => {+ const revalidate = vi.fn();+ const { rerender } = renderHook(+ ({ unlisted }) => useRevalidateWhileUnlisted(unlisted, 'tpc_new', revalidate),+ { initialProps: { unlisted: true } },+ );++ expect(revalidate).toHaveBeenCalledTimes(1);+ vi.advanceTimersByTime(4000);+ expect(revalidate).toHaveBeenCalledTimes(3);++ rerender({ unlisted: false });+ vi.advanceTimersByTime(10_000);+ expect(revalidate).toHaveBeenCalledTimes(3);+ });++ it('gives up after a bounded number of retries', () => {+ const revalidate = vi.fn();+ renderHook(() => useRevalidateWhileUnlisted(true, 'tpc_new', revalidate));++ vi.advanceTimersByTime(120_000);+ expect(revalidate).toHaveBeenCalledTimes(16);+ });++ it('does nothing for a listed topic', () => {+ const revalidate = vi.fn();+ renderHook(() => useRevalidateWhileUnlisted(false, 'tpc_old', revalidate));++ vi.advanceTimersByTime(10_000);+ expect(revalidate).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Projects/Conversation/useRevalidateWhileUnlisted.ts b/src/features/Projects/Conversation/useRevalidateWhileUnlisted.tsnew file mode 100644index 00000000000..cc8e127c4f8--- /dev/null+++ b/src/features/Projects/Conversation/useRevalidateWhileUnlisted.ts@@ -0,0 +1,35 @@+import { useEffect, useRef } from 'react';++const RETRY_INTERVAL_MS = 2000;+const MAX_RETRIES = 15;++/**+ * Refetch the project topic list until a just-created topic shows up in it.+ *+ * The route moves to the new topic as soon as the send adopts its optimistic+ * row, before the server has persisted it, so the first refetch can come back+ * without it β and the list only polls for in-flight rows it already holds.+ * Retrying while the topic is unlisted closes that gap; a send that fails drops+ * the optimistic row, which ends the loop as well. Bounded so a topic that never+ * lands in this project cannot refetch forever.+ */+export const useRevalidateWhileUnlisted = (+ unlisted: boolean,+ topicId: string | undefined,+ revalidate: () => unknown,+) => {+ const revalidateRef = useRef(revalidate);+ revalidateRef.current = revalidate;++ useEffect(() => {+ if (!unlisted) return;+ void revalidateRef.current();+ let retries = 0;+ const timer = setInterval(() => {+ retries += 1;+ if (retries > MAX_RETRIES) return clearInterval(timer);+ void revalidateRef.current();+ }, RETRY_INTERVAL_MS);+ return () => clearInterval(timer);+ }, [unlisted, topicId]);+};diff --git a/src/features/Projects/Layout/navigation.ts b/src/features/Projects/Layout/navigation.tsindex bcdb6defb69..e5f3c19c63a 100644--- a/src/features/Projects/Layout/navigation.ts+++ b/src/features/Projects/Layout/navigation.ts@@ -5,6 +5,14 @@ export const getProjectHomePath = (projectId: string) => `/project/${projectId}`export const getProjectConversationPath = (projectId: string, topicId?: string) =>topicId ? `/project/${projectId}/conversation/${topicId}` : `/project/${projectId}/conversation`;+/**+ * 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.+ */+export const getProjectDraftPath = (projectId: string, agentId: string, directoryId: string) =>+ `${getProjectConversationPath(projectId)}?${new URLSearchParams({ agent: agentId, dir: directoryId })}`;+/** Open a project conversation and send `message` in it once it has loaded. */export const getProjectConversationStartPath = (projectId: string,diff --git a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx b/src/features/Projects/WorkingDirectories/SidebarTopics.tsxindex f81c2c37fa1..190cd717790 100644--- a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx+++ b/src/features/Projects/WorkingDirectories/SidebarTopics.tsx@@ -20,6 +20,7 @@ import {} from '@/features/AgentSidebar/Topic/TopicListScope';import { useOnlyMineTopics, useScopedTopics } from '@/features/AgentSidebar/Topic/useScopedTopics';import SkeletonList from '@/features/NavPanel/components/SkeletonList';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useWorkspacePreferenceReady } from '@/hooks/useWorkspacePreferenceReady';import {useProjectDirectories,@@ -29,6 +30,8 @@ import {import { filterTopics, type TopicListFilter } from '@/utils/client/topic';import { openProjectTopicModal } from './StartDirectoryModal';+import { canStageDraftOn, startProjectTopicDraft } from './startProjectTopicDraft';+import { useAgentFixedDeviceId } from './useAgentFixedDeviceId';import { useProjectTopicReveal } from './useProjectTopicReveal';export function ProjectDirectoryTopics(props: { projectId: string; coordinatorAgentId: string }) {@@ -79,6 +82,8 @@ function ProjectTopicList({// nothing else on a project route syncs that preference. Hold the list until// it is known so the unfiltered rows never paint.const isPreferenceLoading = !useWorkspacePreferenceReady();+ const navigate = useWorkspaceAwareNavigate();+ const fixedDeviceId = useAgentFixedDeviceId(coordinatorAgentId);return (<Flexbox gap={1} paddingBlock={12}><Flexbox horizontal align="center" justify="space-between" paddingInline={8}>@@ -94,14 +99,27 @@ function ProjectTopicList({icon={PlusIcon}size="small"title={t('sidebar.newConversation')}- onClick={() =>+ onClick={() => {+ // Same habit as an agent's "+": a blank conversation on the first+ // directory the coordinator can run in, switchable in the composer before the first+ // send. The modal only remains for a project with none yet.+ const directory = directories.find((d) => canStageDraftOn(d, fixedDeviceId));+ if (directory) {+ startProjectTopicDraft({+ agentId: coordinatorAgentId,+ directoryId: directory.id,+ navigate,+ projectId,+ });+ return;+ }openProjectTopicModal({title: t('sidebar.newConversation'),coordinatorAgentId,directories,projectId,- })- }+ });+ }}/></Flexbox></Flexbox>diff --git a/src/features/Projects/WorkingDirectories/startProjectTopicDraft.test.ts b/src/features/Projects/WorkingDirectories/startProjectTopicDraft.test.tsnew file mode 100644index 00000000000..3b52c08919a--- /dev/null+++ b/src/features/Projects/WorkingDirectories/startProjectTopicDraft.test.ts@@ -0,0 +1,83 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ canStageDraftOn,+ isRunnableProjectDirectory,+ startProjectTopicDraft,+} from './startProjectTopicDraft';++const { chat } = vi.hoisted(() => ({+ chat: { setPendingNewTopicDirectory: vi.fn(), switchTopic: vi.fn() },+}));++vi.mock('@/store/chat', () => ({+ useChatStore: { getState: () => chat },+}));++describe('isRunnableProjectDirectory', () => {+ it('requires a linked environment instance and write access', () => {+ const runnable = { environmentId: 'env', instanceId: 'ins', permission: 'readWrite' };++ expect(isRunnableProjectDirectory(runnable)).toBe(true);+ expect(isRunnableProjectDirectory({ ...runnable, permission: 'read' })).toBe(false);+ expect(isRunnableProjectDirectory({ ...runnable, environmentId: null })).toBe(false);+ expect(isRunnableProjectDirectory({ ...runnable, instanceId: undefined })).toBe(false);+ });+});++describe('canStageDraftOn', () => {+ it('keeps a fixed agent on its device', () => {+ const directory = {+ deviceId: 'dev-a',+ environmentId: 'env',+ instanceId: 'ins',+ permission: 'readWrite',+ };++ expect(canStageDraftOn(directory)).toBe(true);+ expect(canStageDraftOn(directory, 'dev-a')).toBe(true);+ expect(canStageDraftOn(directory, 'dev-b')).toBe(false);+ expect(canStageDraftOn({ ...directory, permission: 'read' }, 'dev-a')).toBe(false);+ });++ /** @example Review: an agent fixed to a sandbox was treated as unrestricted, so its draft's first send was refused. */+ it('stages nothing for an agent fixed to a target that is not a device', () => {+ const directory = {+ deviceId: 'dev-a',+ environmentId: 'env',+ instanceId: 'ins',+ permission: 'readWrite',+ };++ expect(canStageDraftOn(directory, null)).toBe(false);+ expect(canStageDraftOn({ ...directory, deviceId: null }, null)).toBe(false);+ });+});++describe('startProjectTopicDraft', () => {+ beforeEach(() => vi.clearAllMocks());++ it('stages the directory on a blank conversation and opens the project composer', () => {+ const navigate = vi.fn();++ startProjectTopicDraft({+ agentId: 'agt_1',+ directoryId: 'pwd_1',+ navigate,+ projectId: 'prj_1',+ });++ // The draft belongs to the target agent, so its blank bucket is the one+ // cleaned β not whichever conversation the "+" was clicked from.+ expect(chat.switchTopic).toHaveBeenCalledWith(null, {+ clearNewKeyContext: { agentId: 'agt_1', groupId: null },+ skipRefreshMessage: true,+ });+ expect(chat.setPendingNewTopicDirectory).toHaveBeenCalledWith({+ agentId: 'agt_1',+ projectWorkingDirectoryId: 'pwd_1',+ });+ // The draft rides in the route so it stays with the pane that opened it.+ expect(navigate).toHaveBeenCalledWith('/project/prj_1/conversation?agent=agt_1&dir=pwd_1');+ });+});diff --git a/src/features/Projects/WorkingDirectories/startProjectTopicDraft.ts b/src/features/Projects/WorkingDirectories/startProjectTopicDraft.tsnew file mode 100644index 00000000000..568cddbc9fd--- /dev/null+++ b/src/features/Projects/WorkingDirectories/startProjectTopicDraft.ts@@ -0,0 +1,59 @@+import { useChatStore } from '@/store/chat';++import { getProjectDraftPath } from '../Layout/navigation';++interface RunnableDirectoryLike {+ environmentId?: string | null;+ instanceId?: string | null;+ permission?: string | null;+}++/**+ * Whether a blank conversation may be staged on this directory: it needs a+ * linked environment instance and write access β the same rule the send+ * preflight and the composer's device switcher apply. A blank draft has no+ * topic for that preflight to check, so a "+" must only pick such a directory.+ */+export const isRunnableProjectDirectory = (directory: RunnableDirectoryLike) =>+ !!directory.instanceId && !!directory.environmentId && directory.permission === 'readWrite';++/**+ * A runnable directory the draft's agent may also run in: an agent fixed to+ * one device is refused anywhere else, so its draft must stay on that device β+ * and one fixed to a non-device target (e.g. a sandbox) can't use any.+ */+export const canStageDraftOn = (+ directory: RunnableDirectoryLike & { deviceId?: string | null },+ /** Undefined: not fixed. Null: fixed to a target that is not a device. */+ fixedDeviceId?: string | null,+) =>+ isRunnableProjectDirectory(directory) &&+ (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`).+ */+export const startProjectTopicDraft = ({+ agentId,+ directoryId,+ navigate,+ projectId,+}: {+ agentId: string;+ directoryId: string;+ navigate: (path: string) => void;+ projectId: string;+}) => {+ const chat = useChatStore.getState();+ // Clean the target agent's blank bucket, not the view the "+" was clicked+ // from β the draft is that agent's conversation.+ chat.switchTopic(null, {+ clearNewKeyContext: { agentId, groupId: null },+ skipRefreshMessage: true,+ });+ chat.setPendingNewTopicDirectory({ agentId, projectWorkingDirectoryId: directoryId });+ navigate(getProjectDraftPath(projectId, agentId, directoryId));+};diff --git a/src/features/Projects/WorkingDirectories/useAgentFixedDeviceId.ts b/src/features/Projects/WorkingDirectories/useAgentFixedDeviceId.tsnew file mode 100644index 00000000000..9025e0d8867--- /dev/null+++ b/src/features/Projects/WorkingDirectories/useAgentFixedDeviceId.ts@@ -0,0 +1,18 @@+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';++/**+ * The device an agent's author fixed it to. Read from the shared row, as the+ * composer's device switcher does: it is what the server checks a run in a+ * project directory against. `null` for an agent fixed to a target that is not+ * a device (no `boundDeviceId` to match), `undefined` when it is not fixed or+ * not loaded.+ */+export const useAgentFixedDeviceId = (agentId: string | undefined) =>+ useAgentStore((s) => {+ if (!agentId) return undefined;+ const agencyConfig = agentByIdSelectors.getAgencyConfigById(agentId)(s);+ return agencyConfig?.executionTargetSelectionPolicy === 'fixed'+ ? (agencyConfig.boundDeviceId ?? null)+ : 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.tsindex 9d25aff9763..411131be12c 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@@ -165,6 +165,44 @@ describe('sendMessage in a project directory', () => {expect(pendingAtDispatch).toEqual([]);});+ // Regression (acceptance): a first send the server refused (device offline)+ // rolled the optimistic topic back but left the staging consumed, so the+ // blank project conversation lost its directory β on a project page the+ // composer vanished and the restored draft had nowhere to be sent.+ it('restages the project directory when a refused first send rolls back', async () => {+ mockConstEnv.isDesktop = true;+ setupMockSelectors({+ agentConfig: { agencyConfig: { boundDeviceId: DEVICE_ID, executionTarget: 'device' } },+ });+ const agentId = TEST_IDS.SESSION_ID;+ const staged = { agentId, projectWorkingDirectoryId: 'dir-85' };+ const executeGatewayAgentSpy = vi+ .fn()+ .mockRejectedValue(new Error('Device is offline or working directory is unavailable'));++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: undefined,+ executeGatewayAgent: executeGatewayAgentSpy,+ isGatewayModeEnabled: () => true,+ pendingNewTopicDirectory: staged,+ });+ });++ const { result } = renderHook(() => useChatStore());+ await act(async () => {+ await result.current.sendMessage({+ context: { agentId, threadId: null, topicId: null },+ message: 'Start on an offline device',+ });+ });++ expect(executeGatewayAgentSpy).toHaveBeenCalled();+ expect(result.current.activeTopicId).toBeFalsy();+ expect(result.current.pendingNewTopicDirectory).toEqual(staged);+ });+// `/newTopic` from a project topic creates a topic outside the project, so it// must not inherit the directory it was sent from.it('keeps a /newTopic sent from a project topic on the agent default', async () => {diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 6646b3ba670..1fc807c2ac8 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -57,7 +57,6 @@ import { chatService } from '@/services/chat';import { resolveSelectedSkillsWithContent } from '@/services/chat/mecha/skillPreload';import { resolveSelectedToolsWithContent } from '@/services/chat/mecha/toolPreload';import { messageService } from '@/services/message';-import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';import { topicService } from '@/services/topic';import { getAgentStoreState } from '@/store/agent';import {@@ -121,7 +120,6 @@ import { getElectronStoreState } from '@/store/electron';import { getFileStoreState } from '@/store/file/store';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';-import { findProjectDirectory } from '@/store/projectWorkingDirectory';import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';import { type StoreSetter } from '@/store/types';import { getUserStoreState } from '@/store/user';@@ -145,6 +143,7 @@ import {} from './commandBus';import { mergePartialPersistedMessages, resolveSendResponseMessages } from './persistedMessages';import { resolveExistingTopicForRun } from './resolveExistingTopic';+import { resolveProjectDirectoryRun } from './resolveProjectDirectoryRun';/*** Extended params for sendMessage with context@@ -462,31 +461,15 @@ export class ConversationLifecycleActionImpl {pendingDirectory?.agentId === ownerAgentId? pendingDirectory.projectWorkingDirectoryId: undefined;- const projectDirectoryId = boundTopic?.projectWorkingDirectoryId ?? stagedDirectoryId;- let stagedDirectory: { id: string; path: string; projectId: string } | undefined;- if (projectDirectoryId) {- // 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- // server re-validates the directory (environment link, enabled state,- // permission) when it starts the run. Only a cold replica pays for resolve.- const directory =- findProjectDirectory(projectDirectoryId) ??- (await projectWorkingDirectoryService.resolve(projectDirectoryId)).data;- if (stagedDirectoryId) stagedDirectory = directory;- if (stagedDirectory) consumePendingTopicRepos(ownerAgentId); // a cloud repo pick conflicts- if (!isGatewayMode)- throw new Error('Enable Gateway Mode to run in a project working directory');- if (- agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&- agencyConfig.boundDeviceId !== directory.deviceId- )- throw new Error('Agent is fixed to another execution target');- agencyConfig = {- ...agencyConfig,- boundDeviceId: directory.deviceId,- executionTarget: 'device',- };- }+ const projectRun = await resolveProjectDirectoryRun({+ agencyConfig,+ boundDirectoryId: boundTopic?.projectWorkingDirectoryId,+ isGatewayMode,+ stagedDirectoryId,+ });+ ({ agencyConfig } = projectRun);+ const { stagedDirectory } = projectRun;+ if (stagedDirectory) consumePendingTopicRepos(ownerAgentId); // a cloud repo pick conflicts// Legacy agents may only carry `model: '<cli-type>'`. Keep gateway routing// unchanged when it is available. Recover the provider when gateway mode is@@ -1421,6 +1404,9 @@ 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);}this.#get().internal_dispatchTopic({ ...optimisticTopicScope, type: 'deleteTopic', id: optimisticTopic.id },diff --git a/src/store/chat/slices/agentRun/actions/entries/resolveProjectDirectoryRun.ts b/src/store/chat/slices/agentRun/actions/entries/resolveProjectDirectoryRun.tsnew file mode 100644index 00000000000..56eb6ea4849--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/entries/resolveProjectDirectoryRun.ts@@ -0,0 +1,51 @@+import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';+import { findProjectDirectory } from '@/store/projectWorkingDirectory';++interface DeviceRouting {+ boundDeviceId?: string;+ executionTarget?: string;+ executionTargetSelectionPolicy?: string;+}++/**+ * Route a send into the project directory it runs in: the bound topic's, or β+ * for a blank conversation a project group's "+" opened β the staged one. The+ * directory pins the run to its device, so the agent's own device choice is+ * overridden; an agent fixed to another device cannot run there.+ *+ * `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.+ */+export const resolveProjectDirectoryRun = async <T extends DeviceRouting>(params: {+ agencyConfig: T | undefined;+ boundDirectoryId: string | null | undefined;+ isGatewayMode: boolean;+ stagedDirectoryId: string | undefined;+}) => {+ const { agencyConfig, boundDirectoryId, isGatewayMode, stagedDirectoryId } = params;+ const directoryId = boundDirectoryId ?? stagedDirectoryId;+ if (!directoryId) return { agencyConfig, stagedDirectory: undefined };++ // 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+ // server re-validates the directory (environment link, enabled state,+ // permission) when it starts the run. Only a cold replica pays for resolve.+ const directory =+ findProjectDirectory(directoryId) ??+ (await projectWorkingDirectoryService.resolve(directoryId)).data;+ if (!isGatewayMode) throw new Error('Enable Gateway Mode to run in a project working directory');+ if (+ agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&+ agencyConfig.boundDeviceId !== directory.deviceId+ )+ throw new Error('Agent is fixed to another execution target');++ return {+ agencyConfig: {+ ...agencyConfig,+ boundDeviceId: directory.deviceId,+ executionTarget: 'device',+ } as T,+ stagedDirectory: stagedDirectoryId ? directory : undefined,+ };+};