π€― 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
π fix(chat): continue forwarded topics in the source working directory (#22238)
Mocha458f99cadd30
diff --git a/src/features/MessageList/ChannelConversation.tsx b/src/features/MessageList/ChannelConversation.tsxindex 4580d00351f..6658a1177f4 100644--- a/src/features/MessageList/ChannelConversation.tsx+++ b/src/features/MessageList/ChannelConversation.tsx@@ -1,12 +1,12 @@'use client';+import { CHANNEL_URL } from '@lobechat/const';import type { ChannelListItem } from '@lobechat/types';import { Avatar, Icon } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import { HashIcon } from 'lucide-react';import { memo } from 'react';-import { channelPath } from '@/features/Channels/paths';import { useChannelMenu } from '@/features/Channels/useChannelMenu';import ConversationRow from './ConversationRow';@@ -31,7 +31,7 @@ const ChannelConversation = memo<ChannelConversationProps>(({ active, activeAt,preview={channelPreview(channel)}title={channel.title}unread={channel.unreadCount}- url={channelPath(channel.id)}+ url={CHANNEL_URL(channel.id)}avatar={<Avataravatar={<Icon color={cssVar.colorTextSecondary} icon={HashIcon} size={16} />}diff --git a/src/features/MessageList/Header.tsx b/src/features/MessageList/Header.tsxindex 9815daa98ce..7624e91c882 100644--- a/src/features/MessageList/Header.tsx+++ b/src/features/MessageList/Header.tsx@@ -1,5 +1,6 @@'use client';+import { CHANNEL_URL } from '@lobechat/const';import { ActionIcon, DropdownMenu, Flexbox, Icon, SearchBar, Text } from '@lobehub/ui';import { HashIcon, PlusIcon } from 'lucide-react';import { memo, type ReactNode, useMemo } from 'react';@@ -7,7 +8,6 @@ import { useTranslation } from 'react-i18next';import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';import { openCreateChannel } from '@/features/Channels/CreateChannel';-import { channelPath } from '@/features/Channels/paths';import { useChannelsEnabled } from '@/features/Channels/useChannelsEnabled';import { useCreateMenuItems } from '@/features/HomeSidebar/hooks';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';@@ -58,7 +58,7 @@ const Header = memo(() => {icon: <Icon icon={HashIcon} />,key: 'newChannel',label: t('create', { ns: 'channel' }),- onClick: () => openCreateChannel((id) => navigate(channelPath(id))),+ onClick: () => openCreateChannel((id) => navigate(CHANNEL_URL(id))),},...rest,];diff --git a/src/features/MessageList/useAgentConversationLink.ts b/src/features/MessageList/useAgentConversationLink.tsindex 41ca7fec618..4341556e3cd 100644--- a/src/features/MessageList/useAgentConversationLink.ts+++ b/src/features/MessageList/useAgentConversationLink.ts@@ -1,7 +1,7 @@+import { CHANNEL_URL } from '@lobechat/const';import { type MouseEvent, useCallback, useEffect, useRef } from 'react';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';-import { channelPath } from '@/features/Channels/paths';import { useChannelsEnabled } from '@/features/Channels/useChannelsEnabled';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useActiveLocation } from '@/hooks/useActiveLocation';@@ -49,7 +49,7 @@ export const useAgentConversationLink = (agentId: string, agentUrl: string) => {};void channelActions.openDirect(agentId)- .then((channelId) => go(channelId ? channelPath(channelId) : agentUrl))+ .then((channelId) => go(channelId ? CHANNEL_URL(channelId) : agentUrl)).catch((error) => {console.error('[channel] Failed to open the direct Channel', error);go(agentUrl);@@ -61,6 +61,6 @@ export const useAgentConversationLink = (agentId: string, agentUrl: string) => {[agentId, agentUrl, navigate],);- if (directChannelId) return { url: channelPath(directChannelId) };+ if (directChannelId) return { url: CHANNEL_URL(directChannelId) };return { onClick: enabled ? onClick : undefined, url: agentUrl };};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 2d0a470dfaf..590cf788f05 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@@ -4,7 +4,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { agentService } from '@/services/agent';import { aiChatService } from '@/services/aiChat';+import { deviceService } from '@/services/device';+import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';import { getPendingTopicRepos, setPendingTopicRepos } from '@/store/chat/pendingTopicRepos';+import { useElectronStore } from '@/store/electron';import { type ProjectDirectory, useProjectDirectoryStore } from '@/store/projectWorkingDirectory';import { getSessionStoreState } from '@/store/session';import { useUserStore } from '@/store/user';@@ -340,3 +343,231 @@ describe('sendMessage in a project without a directory', () => {expect(result.current.pendingNewTopicDirectory).toEqual({ agentId, projectId: 'prj-1' });});});++describe('sendMessage continuing a source topic', () => {+ const OTHER_DEVICE_ID = 'device-other';+ const SOURCE_PATH = '/repo/source';+ const forwardContext = (agentId: string) => ({+ agentId,+ isNew: true,+ isolatedTopic: true,+ scope: 'main' as const,+ });+ const statPath = (exists: boolean | null) =>+ vi+ .spyOn(deviceService, 'statPath')+ .mockResolvedValue(exists === null ? null : ({ exists, isDirectory: exists } as any));+ beforeEach(() => {+ statPath(true);+ });+ const sendForward = async (sourceTopic: any) => {+ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({ topicId: 'tpc_new' });+ const agentId = TEST_IDS.SESSION_ID;+ act(() => {+ useChatStore.setState({+ executeGatewayAgent: executeGatewayAgentSpy,+ isGatewayModeEnabled: () => true,+ });+ });+ const { result } = renderHook(() => useChatStore());+ await act(async () => {+ await result.current.sendMessage({+ context: forwardContext(agentId),+ message: 'Continue the handoff',+ sourceTopic,+ });+ });+ return executeGatewayAgentSpy.mock.calls[0][0];+ };++ // Regression (user report): a forwarded task started in the receiving+ // agent's default directory instead of the one the source topic ran in.+ it('starts a forwarded topic in the source project directory', async () => {+ mockConstEnv.isDesktop = true;+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ boundDeviceId: DEVICE_ID,+ executionTarget: 'device',+ workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },+ },+ },+ });++ const params = await sendForward({+ metadata: { boundDeviceId: DEVICE_ID, workingDirectory: PROJECT_PATH },+ projectId: 'prj-1',+ projectWorkingDirectoryId: 'dir-85',+ });++ expect(params.projectWorkingDirectoryId).toBe('dir-85');+ expect(params.newTopicMetadata).toEqual(+ expect.objectContaining({ workingDirectory: PROJECT_PATH }),+ );+ });++ it('carries the source bare directory to the server on the same machine', async () => {+ mockConstEnv.isDesktop = true;+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ boundDeviceId: DEVICE_ID,+ executionTarget: 'device',+ workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },+ },+ },+ });++ const params = await sendForward({+ metadata: {+ boundDeviceId: DEVICE_ID,+ heteroSessionId: 'source-cli-session',+ workingDirectory: SOURCE_PATH,+ workingDirectoryConfig: { path: SOURCE_PATH },+ },+ });++ expect(params.projectWorkingDirectoryId).toBeUndefined();+ expect(params.newTopicMetadata).toEqual({+ boundDeviceId: DEVICE_ID,+ workingDirectory: SOURCE_PATH,+ workingDirectoryConfig: { path: SOURCE_PATH },+ });+ });++ // The path only exists on the machine it was recorded on.+ // A legacy topic never recorded its machine: the same absolute path on the+ // receiving machine may be an unrelated checkout, so it is not inherited.+ it.each([+ ['on another machine', { boundDeviceId: OTHER_DEVICE_ID, workingDirectory: SOURCE_PATH }],+ ['on an unknown machine', { workingDirectory: SOURCE_PATH }],+ ])('keeps the agent default when the source directory is %s', async (_, metadata) => {+ mockConstEnv.isDesktop = true;+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ boundDeviceId: DEVICE_ID,+ executionTarget: 'device',+ workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },+ },+ },+ });++ const params = await sendForward({ metadata });++ expect(params.newTopicMetadata).toEqual(+ expect.objectContaining({ workingDirectory: AGENT_DEFAULT_PATH }),+ );+ });++ // `auto` resolves this desktop client-side, but the server may route the run+ // to another online device; a machine-specific path cannot be inherited until+ // the run's machine is actually known.+ it('keeps the agent default for an auto-routed agent', async () => {+ mockConstEnv.isDesktop = true;+ vi.spyOn(useElectronStore.getState(), 'resolveGatewayDeviceId').mockResolvedValue(DEVICE_ID);+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ executionTarget: 'auto',+ workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },+ },+ },+ });++ const params = await sendForward({+ metadata: { boundDeviceId: DEVICE_ID, workingDirectory: SOURCE_PATH },+ });++ expect(params.newTopicMetadata?.workingDirectory).not.toBe(SOURCE_PATH);+ });++ // A source directory the receiving agent cannot resolve (deleted, gateway+ // off) must not fail the handoff: it continues in the source's bare cwd.+ it('falls back to the source cwd when its project directory cannot be resolved', async () => {+ mockConstEnv.isDesktop = true;+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ boundDeviceId: DEVICE_ID,+ executionTarget: 'device',+ workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },+ },+ },+ });+ useProjectDirectoryStore.setState({ directoriesMap: {} });+ vi.spyOn(projectWorkingDirectoryService, 'resolve').mockRejectedValue(+ new Error('Directory not found'),+ );++ const params = await sendForward({+ metadata: { boundDeviceId: DEVICE_ID, workingDirectory: PROJECT_PATH },+ projectWorkingDirectoryId: 'dir-gone',+ });++ expect(params.projectWorkingDirectoryId).toBeUndefined();+ expect(params.newTopicMetadata).toEqual(+ expect.objectContaining({ workingDirectory: PROJECT_PATH }),+ );+ });+ // The source directory may have been deleted since it ran; the receiving+ // agent then takes the handoff in its own default instead of a run that can+ // only fail with "working directory not found".+ const deviceAgent = () =>+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ boundDeviceId: DEVICE_ID,+ executionTarget: 'device',+ workingDirByDevice: { [DEVICE_ID]: AGENT_DEFAULT_PATH },+ },+ },+ });++ it('falls back to the agent default when the source cwd no longer exists', async () => {+ mockConstEnv.isDesktop = true;+ deviceAgent();+ statPath(false);++ const params = await sendForward({+ metadata: { boundDeviceId: DEVICE_ID, workingDirectory: SOURCE_PATH },+ });++ expect(deviceService.statPath).toHaveBeenCalledWith(DEVICE_ID, SOURCE_PATH);+ expect(params.newTopicMetadata).toEqual(+ expect.objectContaining({ workingDirectory: AGENT_DEFAULT_PATH }),+ );+ });++ it('falls back to the agent default when the source project directory no longer exists', async () => {+ mockConstEnv.isDesktop = true;+ deviceAgent();+ statPath(false);++ const params = await sendForward({+ metadata: { boundDeviceId: DEVICE_ID, workingDirectory: PROJECT_PATH },+ projectWorkingDirectoryId: 'dir-85',+ });++ expect(params.projectWorkingDirectoryId).toBeUndefined();+ expect(params.newTopicMetadata).toEqual(+ expect.objectContaining({ workingDirectory: AGENT_DEFAULT_PATH }),+ );+ });++ // An unreachable device cannot say the directory is gone; the spawn-time+ // check stays the authority rather than silently moving the task elsewhere.+ it('keeps the source cwd when its existence cannot be verified', async () => {+ mockConstEnv.isDesktop = true;+ deviceAgent();+ statPath(null);++ const params = await sendForward({+ metadata: { boundDeviceId: DEVICE_ID, workingDirectory: SOURCE_PATH },+ });++ expect(params.newTopicMetadata).toEqual(+ expect.objectContaining({ workingDirectory: SOURCE_PATH }),+ );+ });+});diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.tsindex 6cc1c77b84c..24201bc5ed8 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts@@ -140,8 +140,8 @@ import {import { pageConversationNeedsGateway, preparePageConversation } from '../pageConversation';import { mergePartialPersistedMessages, resolveSendResponseMessages } from '../persistedMessages';import { resolveExistingTopicForRun } from '../resolveExistingTopic';-import { resolveProjectDirectoryRun } from '../resolveProjectDirectoryRun';import { type ContextCompressionOptions, executeContextCompression } from './compression';+import { resolveRunCwd, resolveSendProjectRun, type SourceTopicDirectory } from './runCwd';import { showSendErrorInContext } from './sendErrorNotice';/**@@ -171,6 +171,8 @@ export interface SendMessageWithContextParams extends SendMessageParams {* own `switchTopic` handles the transition on the global chat store.*/onTopicCreated?: (topicId: string) => void | Promise<void>;+ /** Topic a new topic continues (a handoff): only its cwd carries over, never its CLI session. */+ sourceTopic?: SourceTopicDirectory;}/**@@ -284,6 +286,7 @@ export class ConversationLifecycleActionImpl {onTopicCreated,preserveComposer,signal,+ sourceTopic,}: SendMessageWithContextParams): Promise<SendMessageResult | undefined> => {throwIfSendAborted(signal);@@ -440,21 +443,16 @@ export class ConversationLifecycleActionImpl {const boundTopic = context.topicId? topicSelectors.getTopicById(context.topicId)(this.#get()): undefined;- // A blank conversation opened from a project "+" runs in the directory (or- // just the project) it staged; the new topic is born bound to it.const pendingDirectory = this.#get().pendingNewTopicDirectory;- const projectRun = await resolveProjectDirectoryRun({+ const { inheritedTopic, ...projectRun } = await resolveSendProjectRun({agencyConfig,boundDirectoryId: boundTopic?.projectWorkingDirectoryId,+ context,+ directMentionRoute: !!directMentionRoute,isGatewayMode,- staged:- !context.topicId &&- !context.isolatedTopic &&- !context.groupId &&- !directMentionRoute &&- pendingDirectory?.agentId === ownerAgentId- ? pendingDirectory- : undefined,+ ownerAgentId,+ pendingDirectory,+ sourceTopic,});({ agencyConfig } = projectRun);const { newTopicProject, stagedDirectory, stagedProjectId } = projectRun;@@ -1205,23 +1203,14 @@ export class ConversationLifecycleActionImpl {const resolveWorkingDirPath = isLocalCliHetero? getWorkingDirSourcePath: getWorkingDirEffectivePath;- // A topic's cwd is a bare path that only holds on the machine it was pinned- // on β never hand another machine's path to this run (mirrors the server's- // `topicPinFitsDevice`).- const topicDeviceId = existingTopic?.metadata?.boundDeviceId;- const topicCwdMetadata =- topicDeviceId && runCwdDeviceId && topicDeviceId !== runCwdDeviceId- ? undefined- : existingTopic?.metadata;- const workingDirectory =- resolveWorkingDirPath(topicCwdMetadata?.workingDirectoryConfig) ??- topicCwdMetadata?.workingDirectory ??- agentWorkingDirectory;- const workingDirectoryConfig =- topicCwdMetadata?.workingDirectoryConfig ??- (topicCwdMetadata?.workingDirectory- ? { path: topicCwdMetadata.workingDirectory }- : agentWorkingDirectoryConfig);+ const { workingDirectory, workingDirectoryConfig } = await resolveRunCwd({+ agentWorkingDirectory,+ agentWorkingDirectoryConfig,+ existingTopic,+ inheritedTopic: !stagedDirectory && resolvesRunCwd ? inheritedTopic : undefined,+ resolvePath: resolveWorkingDirPath,+ runMachine: { deviceId: runCwdDeviceId, target: runEffectiveTarget },+ });// Record which machine a new conversation runs on, so its next turn β and// the device picker β stay on it after the agent default changes. `auto`// has not picked a machine yet; the server stamps the one it routes to.@@ -1794,6 +1783,8 @@ export class ConversationLifecycleActionImpl {clientOperations,replacesOperationId: replaceableGatewayOperationId,optimisticTopic,+ // An isolated handoff topic has no optimistic row to carry its cwd.+ newTopicMetadata: sourceTopic && !optimisticTopic ? workingDirectoryMetadata : undefined,...newTopicProject,// Forward @-mentioned tool ids so the server runtime enables them for// this run β the gateway/server path otherwise never sees the mentiondiff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.tsnew file mode 100644index 00000000000..8528399ddaf--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/runCwd.ts@@ -0,0 +1,152 @@+import { isDesktop } from '@lobechat/const';+import type { ChatTopic, ConversationContext, WorkingDirConfig } from '@lobechat/types';++import { deviceService } from '@/services/device';+import type { PendingNewTopicDirectory } from '@/store/chat/slices/topic/initialState';+import { ensureElectronIpc } from '@/utils/electron/ipc';++import { resolveProjectDirectoryRun } from '../resolveProjectDirectoryRun';++/** The part of a handoff's source topic a new topic continues in. */+export type SourceTopicDirectory = Pick<+ ChatTopic,+ 'metadata' | 'projectId' | 'projectWorkingDirectoryId'+>;++/** The machine a run's cwd lives on, and the execution target that picked it. */+export interface RunMachine {+ deviceId?: string;+ target?: string;+}++/** `local`/`device` fix the run's machine client-side; `auto` is routed by the server. */+const isMachineFixed = (machine: RunMachine) =>+ machine.target === 'local' || machine.target === 'device';++/**+ * Whether a handoff source's directory is KNOWN to be gone on the run's machine+ * β deleted or moved since the source ran. `false` when it cannot be verified+ * (device unreachable, no machine resolved yet): the spawn-time check then still+ * reports `working_directory_not_found` instead of the task silently moving.+ */+const isKnownMissingDirectory = async (path: string, machine: RunMachine): Promise<boolean> => {+ try {+ const stat =+ isDesktop && machine.target === 'local'+ ? await ensureElectronIpc().workspace.statPath({ path })+ : machine.deviceId+ ? await deviceService.statPath(machine.deviceId, path)+ : null;+ return !!stat && (!stat.exists || !stat.isDirectory);+ } catch (error) {+ console.warn('[sendMessage] Could not verify the source working directory:', error);+ return false;+ }+};++/**+ * Route a send into the project directory it runs in (`resolveProjectDirectoryRun`).+ *+ * A blank conversation opened from a project "+" runs in the directory (or just+ * the project) it staged; the new topic is born bound to it. A handoff's new+ * topic continues in its source topic's directory (or project) instead. The+ * receiving agent may be unable to run there (gateway off, fixed to another+ * device, directory unresolvable); it still takes the handoff, falling back to+ * the source's bare cwd (see {@link resolveRunCwd}) or β when the directory is+ * gone from its device β its own default.+ */+export const resolveSendProjectRun = async <T extends { boundDeviceId?: string }>(params: {+ agencyConfig: T | undefined;+ boundDirectoryId: string | null | undefined;+ context: ConversationContext;+ directMentionRoute: boolean;+ isGatewayMode: boolean;+ ownerAgentId: string;+ pendingDirectory: PendingNewTopicDirectory | undefined;+ sourceTopic: SourceTopicDirectory | undefined;+}) => {+ const { context, directMentionRoute, ownerAgentId, pendingDirectory, sourceTopic } = params;+ const createsTopic = !context.topicId && !context.groupId && !directMentionRoute;+ const inheritedTopic = createsTopic ? sourceTopic : undefined;+ const runParams = {+ agencyConfig: params.agencyConfig,+ boundDirectoryId: params.boundDirectoryId,+ isGatewayMode: params.isGatewayMode,+ staged:+ createsTopic && !context.isolatedTopic && pendingDirectory?.agentId === ownerAgentId+ ? pendingDirectory+ : undefined,+ };+ const inherited: PendingNewTopicDirectory | undefined = inheritedTopic?.projectWorkingDirectoryId+ ? { agentId: ownerAgentId, projectWorkingDirectoryId: inheritedTopic.projectWorkingDirectoryId }+ : inheritedTopic?.projectId+ ? { agentId: ownerAgentId, projectId: inheritedTopic.projectId }+ : undefined;+ if (!inherited) return { ...(await resolveProjectDirectoryRun(runParams)), inheritedTopic };++ try {+ const run = await resolveProjectDirectoryRun({ ...runParams, staged: inherited });+ const directory = run.stagedDirectory;+ // The server only checks the device is online on send; the source's bare cwd+ // is this same path, so a gone directory drops the inheritance entirely.+ // Project directories run through the gateway on their device, even this one.+ const machine = { deviceId: directory?.deviceId ?? undefined, target: 'device' };+ if (directory && (await isKnownMissingDirectory(directory.path, machine))) {+ return { ...(await resolveProjectDirectoryRun(runParams)), inheritedTopic: undefined };+ }+ return { ...run, inheritedTopic };+ } catch (error) {+ console.warn('[sendMessage] Source project directory unavailable:', error);+ return { ...(await resolveProjectDirectoryRun(runParams)), inheritedTopic };+ }+};++/**+ * The cwd a run uses: its topic's pinned cwd, else the agent default.+ *+ * A topic's cwd is a bare path that only holds on the machine it was pinned on+ * β never hand another machine's path to this run (mirrors the server's+ * `topicPinFitsDevice`). A new topic may inherit a handoff source's cwd; that+ * has no binding on the new topic yet, so the source must have recorded the+ * machine this run resolves a cwd for β not merely not contradict it.+ */+export const resolveRunCwd = async (params: {+ agentWorkingDirectory: string | undefined;+ agentWorkingDirectoryConfig: WorkingDirConfig | undefined;+ existingTopic: Pick<ChatTopic, 'metadata'> | undefined;+ /** Source topic whose cwd a new topic may inherit; omit when it cannot. */+ inheritedTopic: SourceTopicDirectory | undefined;+ /** Source repo for local CLIs, effective (worktree) path otherwise. */+ resolvePath: (config: WorkingDirConfig | undefined) => string | undefined;+ runMachine: RunMachine;+}): Promise<{ workingDirectory?: string; workingDirectoryConfig?: WorkingDirConfig }> => {+ const { existingTopic, inheritedTopic, resolvePath, runMachine } = params;+ const runCwdDeviceId = runMachine.deviceId;+ const pinnedDeviceId = (existingTopic ?? inheritedTopic)?.metadata?.boundDeviceId;+ // An inherited path needs a known, matching machine: an unpinned legacy source+ // could name an unrelated checkout that merely shares the path here.+ const fits = existingTopic+ ? !pinnedDeviceId || !runCwdDeviceId || pinnedDeviceId === runCwdDeviceId+ : isMachineFixed(runMachine) && !!pinnedDeviceId && pinnedDeviceId === runCwdDeviceId;+ let metadata = fits ? (existingTopic ?? inheritedTopic)?.metadata : undefined;+ // An existing topic's cwd is its own (the spawn guide offers a way back); an+ // inherited one is dropped when it is known to be gone.+ const inheritedPath =+ !existingTopic && metadata+ ? (resolvePath(metadata.workingDirectoryConfig) ?? metadata.workingDirectory)+ : undefined;+ if (inheritedPath && (await isKnownMissingDirectory(inheritedPath, runMachine)))+ metadata = undefined;++ return {+ workingDirectory:+ resolvePath(metadata?.workingDirectoryConfig) ??+ metadata?.workingDirectory ??+ params.agentWorkingDirectory,+ workingDirectoryConfig:+ metadata?.workingDirectoryConfig ??+ (metadata?.workingDirectory+ ? { path: metadata.workingDirectory }+ : params.agentWorkingDirectoryConfig),+ };+};diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 9db7aaa93f4..51b1748fb4f 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -39,12 +39,8 @@ import { shareChatService } from '@/services/shareChat';import { topicService } from '@/services/topic';import { getAgentStoreState } from '@/store/agent';import { chatConfigByIdSelectors } from '@/store/agent/selectors';-import {- consumePendingSandboxSelection,- getPendingSandboxSelection,- toSandboxTopicMetadata,-} from '@/store/chat/pendingSandboxSelection';-import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';+import { consumePendingSandboxSelection } from '@/store/chat/pendingSandboxSelection';+import { consumePendingTopicRepos } from '@/store/chat/pendingTopicRepos';import { topicSelectors } from '@/store/chat/selectors';import { leaveBlankConversationBucket } from '@/store/chat/slices/agentRun/actions/clearBlankBucket';import { operationSelectors } from '@/store/chat/slices/operation/selectors';@@ -78,6 +74,7 @@ import { createGatewayEventHandler } from './gatewayEventHandler';import { createGatewayEventRouter } from './gatewayEventRouter';import { createGatewayMemberStreamHandler, mergeGroupSnapshot } from './gatewayMemberStreamHandler';import { awaitStartRequest, interruptGatewayTaskOrThrow } from './gatewayStartRequest';+import { resolveInitialTopicMetadata } from './initialTopicMetadata';import {type GatewayMuxIdentity,getGatewayMux,@@ -947,6 +944,8 @@ export class GatewayActionImpl {onTopicCreated?: (topicId: string) => void | Promise<void>;/** Called when the gateway session completes (agent finished running) */onComplete?: () => void;+ /** New-topic cwd for a send without an optimistic row (an isolated handoff topic). */+ newTopicMetadata?: ChatTopicMetadata;/** Temporary sidebar topic inserted by sendMessage before the server creates the real topic. */optimisticTopic?: { id: string; metadata?: ChatTopicMetadata; title: string };/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */@@ -1036,6 +1035,7 @@ export class GatewayActionImpl {metadata,onComplete,onMessageAccepted,+ newTopicMetadata,onTopicCreated,optimisticTopic,parentMessageId,@@ -1069,46 +1069,12 @@ export class GatewayActionImpl {// the turn persists onto the topic's main spine and the subtopic collapses// back into the main chat.- // If this is a new topic, read any repos the user pre-selected before- // sending the first message. We read without consuming yet β if execAgentTask- // fails or is aborted, the selection is preserved so a retry can still pick- // it up. We clear only after the server confirms the topic was created.- const pendingRepos =- isCreateNewTopic && messageContext.agentId- ? getPendingTopicRepos(messageContext.agentId)- : [];- // Pending repo selection wins; otherwise carry the caller-resolved topic- // metadata (e.g. the hetero cwd `conversationLifecycle` resolved from the- // effective device + per-user legacy slot) so the SERVER topic is born with- // it β the server can't read client-local state, and without this a- // workspace hetero run's first send would fall back to the device default- // cwd instead of the member's pick.- // The instance the composer bound before any topic existed. Merged rather- // than folded into the branches below: it is orthogonal to the cwd, and a- // conversation can start with one, the other, or both.- const pendingSandboxSelection =- isCreateNewTopic && executionContext.agentId- ? getPendingSandboxSelection(executionContext.agentId)- : undefined;- const sandboxTopicMetadata = toSandboxTopicMetadata(pendingSandboxSelection);- const cwdTopicMetadata =- pendingRepos.length > 0- ? {- repos: pendingRepos,- workingDirectory: pendingRepos[0],- workingDirectoryConfig: { path: pendingRepos[0], repoType: 'github' as const },- }- : isCreateNewTopic && optimisticTopic?.metadata?.workingDirectory- ? {- repos: optimisticTopic.metadata.repos,- workingDirectory: optimisticTopic.metadata.workingDirectory,- workingDirectoryConfig: optimisticTopic.metadata.workingDirectoryConfig,- }- : undefined;- const initialTopicMetadata =- cwdTopicMetadata || sandboxTopicMetadata- ? { ...cwdTopicMetadata, ...sandboxTopicMetadata }- : undefined;+ const initialTopicMetadata = resolveInitialTopicMetadata({+ callerTopicMetadata: optimisticTopic?.metadata ?? newTopicMetadata,+ isCreateNewTopic,+ repoAgentId: messageContext.agentId,+ sandboxAgentId: executionContext.agentId,+ });// Honour user-initiated cancel during phase-1 init: while we await the// execAgentTask round-trip the caller's loading state is still running, sodiff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/initialTopicMetadata.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/initialTopicMetadata.tsnew file mode 100644index 00000000000..12ad1f11055--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/initialTopicMetadata.ts@@ -0,0 +1,60 @@+import type { ChatTopicMetadata } from '@lobechat/types';++import {+ getPendingSandboxSelection,+ toSandboxTopicMetadata,+} from '@/store/chat/pendingSandboxSelection';+import { getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';++/**+ * The metadata a NEW server topic is born with; `undefined` for an existing topic.+ *+ * Repos the user pre-selected before the first message are read without+ * consuming them β if execAgentTask fails or is aborted, the selection is+ * preserved so a retry can still pick it up; the caller clears it only after+ * the server confirms the topic was created.+ *+ * Pending repo selection wins; otherwise carry the caller-resolved topic+ * metadata (e.g. the hetero cwd `conversationLifecycle` resolved from the+ * effective device + per-user legacy slot) so the SERVER topic is born with it+ * β the server can't read client-local state, and without this a workspace+ * hetero run's first send would fall back to the device default cwd instead of+ * the member's pick.+ *+ * The sandbox instance the composer bound before any topic existed is merged+ * rather than folded into the cwd branches: it is orthogonal to the cwd, and a+ * conversation can start with one, the other, or both.+ */+export const resolveInitialTopicMetadata = (params: {+ /** Optimistic row metadata, else an isolated handoff topic's cwd. */+ callerTopicMetadata: ChatTopicMetadata | undefined;+ isCreateNewTopic: boolean;+ repoAgentId: string | undefined;+ sandboxAgentId: string | undefined;+}): ChatTopicMetadata | undefined => {+ const { callerTopicMetadata, isCreateNewTopic, repoAgentId, sandboxAgentId } = params;+ if (!isCreateNewTopic) return;++ const pendingRepos = repoAgentId ? getPendingTopicRepos(repoAgentId) : [];+ const sandboxTopicMetadata = toSandboxTopicMetadata(+ sandboxAgentId ? getPendingSandboxSelection(sandboxAgentId) : undefined,+ );+ const cwdTopicMetadata =+ pendingRepos.length > 0+ ? {+ repos: pendingRepos,+ workingDirectory: pendingRepos[0],+ workingDirectoryConfig: { path: pendingRepos[0], repoType: 'github' as const },+ }+ : callerTopicMetadata?.workingDirectory+ ? {+ repos: callerTopicMetadata.repos,+ workingDirectory: callerTopicMetadata.workingDirectory,+ workingDirectoryConfig: callerTopicMetadata.workingDirectoryConfig,+ }+ : undefined;++ return cwdTopicMetadata || sandboxTopicMetadata+ ? { ...cwdTopicMetadata, ...sandboxTopicMetadata }+ : undefined;+};diff --git a/src/store/chat/slices/forward/action.test.ts b/src/store/chat/slices/forward/action.test.tsindex a9c1faecfd9..2c64b4ecc92 100644--- a/src/store/chat/slices/forward/action.test.ts+++ b/src/store/chat/slices/forward/action.test.ts@@ -18,6 +18,7 @@ describe('ChatForwardAction', () => {async (id) => ({ id }) as never,);vi.spyOn(messageService, 'getMessages').mockResolvedValue([]);+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(null);});afterEach(() => {@@ -27,7 +28,10 @@ describe('ChatForwardAction', () => {it('does not start a target when the dispatcher already owns the source', async () => {vi.spyOn(topicService, 'cancelRateLimitContinuation').mockRejectedValue(new Error('claimed'));const sendMessage = vi.fn();- const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);+ const action = new ChatForwardActionImpl(+ vi.fn() as never,+ () => ({ sendMessage, topicDataMap: {} }) as never,+ );await expect(action.forwardTopic({@@ -60,6 +64,7 @@ describe('ChatForwardAction', () => {({internal_dispatchTopic: vi.fn(),sendMessage,+ topicDataMap: {},}) as never,);@@ -81,7 +86,10 @@ describe('ChatForwardAction', () => {vi.mocked(messageService.getMessages).mockRejectedValue(new Error('history unavailable'));const cancel = vi.spyOn(topicService, 'cancelRateLimitContinuation');const sendMessage = vi.fn();- const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);+ const action = new ChatForwardActionImpl(+ vi.fn() as never,+ () => ({ sendMessage, topicDataMap: {} }) as never,+ );const result = await action.forwardTopic({cancelSourceContinuation: true,header: 'Forwarded',@@ -104,7 +112,10 @@ describe('ChatForwardAction', () => {return { createdTopicId: 'topic-a' };}).mockRejectedValueOnce(new Error('failed'));- const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);+ const action = new ChatForwardActionImpl(+ vi.fn() as never,+ () => ({ sendMessage, topicDataMap: {} }) as never,+ );const result = await action.forwardMessages({header: 'Forwarded',@@ -132,7 +143,10 @@ describe('ChatForwardAction', () => {it('treats a send without a created topic as a failure', async () => {const sendMessage = vi.fn().mockResolvedValue(undefined);- const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);+ const action = new ChatForwardActionImpl(+ vi.fn() as never,+ () => ({ sendMessage, topicDataMap: {} }) as never,+ );const result = await action.forwardMessages({header: 'Forwarded',@@ -148,7 +162,10 @@ describe('ChatForwardAction', () => {it('treats a missing target agent as a failure without sending', async () => {vi.mocked(agentService.getAgentConfigById).mockResolvedValueOnce(null);const sendMessage = vi.fn();- const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);+ const action = new ChatForwardActionImpl(+ vi.fn() as never,+ () => ({ sendMessage, topicDataMap: {} }) as never,+ );const result = await action.forwardMessages({header: 'Forwarded',@@ -178,7 +195,10 @@ describe('ChatForwardAction', () => {notify('new-topic');return { createdTopicId: 'new-topic' };});- const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);+ const action = new ChatForwardActionImpl(+ vi.fn() as never,+ () => ({ sendMessage, topicDataMap: {} }) as never,+ );const result = await action.forwardTopic({header: 'Forwarded topic',@@ -205,6 +225,34 @@ describe('ChatForwardAction', () => {expect(sendMessage.mock.calls[0][0].message).not.toContain('private tool output');});+ it('hands the source topic to the target so it continues in the same directory', async () => {+ const sourceTopic = {+ id: 'source-topic',+ metadata: { workingDirectory: '/repo/source' },+ projectWorkingDirectoryId: 'dir-1',+ };+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(sourceTopic as never);+ const sendMessage = vi.fn().mockResolvedValue({ createdTopicId: 'new-topic' });+ const action = new ChatForwardActionImpl(+ vi.fn() as never,+ () => ({ sendMessage, topicDataMap: {} }) as never,+ );++ await action.forwardTopic({+ header: 'Forwarded topic',+ roleLabel: (role) => role,+ sourceAgentId: 'source-agent',+ targets: [{ id: 'agent-a' }, { id: 'agent-b' }],+ topicId: 'source-topic',+ });++ expect(topicService.getTopicDetail).toHaveBeenCalledTimes(1);+ expect(sendMessage.mock.calls.map(([params]) => params.sourceTopic)).toEqual([+ sourceTopic,+ sourceTopic,+ ]);+ });+it('keeps transcript context when the target agent cannot use the LobeHub CLI', async () => {vi.mocked(messageService.getMessages).mockResolvedValueOnce([message('user', 'question'),@@ -214,7 +262,10 @@ describe('ChatForwardAction', () => {notify('new-topic');return { createdTopicId: 'new-topic' };});- const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);+ const action = new ChatForwardActionImpl(+ vi.fn() as never,+ () => ({ sendMessage, topicDataMap: {} }) as never,+ );await action.forwardTopic({header: 'Forwarded topic',diff --git a/src/store/chat/slices/forward/action.ts b/src/store/chat/slices/forward/action.tsindex b6049d3e82f..b3d60dd4657 100644--- a/src/store/chat/slices/forward/action.ts+++ b/src/store/chat/slices/forward/action.ts@@ -1,10 +1,11 @@-import type { UIChatMessage } from '@lobechat/types';+import type { ChatTopic, UIChatMessage } from '@lobechat/types';import { agentService } from '@/services/agent';import { messageService } from '@/services/message';import { topicService } from '@/services/topic';import { getAgentStoreState } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';+import { topicSelectors } from '@/store/chat/slices/topic/selectors';import type { ChatStore } from '@/store/chat/store';import type { StoreSetter } from '@/store/types';@@ -131,6 +132,15 @@ export class ChatForwardActionImpl {});return transcriptPromise;};+ // The targets continue in the source topic's working directory. The list+ // store is paginated, so an older source topic may only exist on the server.+ let sourceTopicPromise: Promise<ChatTopic | null | undefined> | undefined;+ const getSourceTopic = () => {+ sourceTopicPromise ??= Promise.resolve(+ topicSelectors.getTopicById(topicId)(this.#get()) ?? topicService.getTopicDetail(topicId),+ );+ return sourceTopicPromise;+ };// Resolve configuration and context before touching the source schedule.const prepared = await Promise.allSettled(targets.map(async (target) => {@@ -146,7 +156,7 @@ export class ChatForwardActionImpl {? `${cliInstruction}\n\n${await getTranscript()}`: await getTranscript();- return { content, target };+ return { content, sourceTopic: (await getSourceTopic()) ?? undefined, target };}),);const hasReadyTarget = prepared.some((item) => item.status === 'fulfilled');@@ -168,11 +178,12 @@ export class ChatForwardActionImpl {const settled = await Promise.allSettled(prepared.map(async (item) => {if (item.status === 'rejected') throw item.reason;- const { content, target } = item.value;+ const { content, sourceTopic, target } = item.value;const result = await this.#get().sendMessage({context: { agentId: target.id, isNew: true, isolatedTopic: true, scope: 'main' },message: content,messages: [],+ sourceTopic,onTopicCreated: async (createdTopicId) => {accepted = true;createdTopicIds.set(target.id, createdTopicId);