🤯 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(device): 修复工作目录选项持久化 (#22261)
Mochaba180ea8cc0f
diff --git a/apps/share/app/stubs/trpcClient.ts b/apps/share/app/stubs/trpcClient.tsindex 51d23435965..a2b30a951c6 100644--- a/apps/share/app/stubs/trpcClient.ts+++ b/apps/share/app/stubs/trpcClient.ts@@ -1,6 +1,7 @@import { reject } from './reject';export const lambdaClient = reject('lambdaClient');+export const createWorkspaceLambdaClient = reject('createWorkspaceLambdaClient');export const asyncClient = reject('asyncClient');export const toolsClient = reject('toolsClient');export const lambdaQuery = reject('lambdaQuery');diff --git a/apps/workbench/app/stubs/surface.test.ts b/apps/workbench/app/stubs/surface.test.tsindex 3a395be9407..33ab3a96f63 100644--- a/apps/workbench/app/stubs/surface.test.ts+++ b/apps/workbench/app/stubs/surface.test.ts@@ -13,6 +13,24 @@ import {const stubDir = import.meta.dirname;describe('workbench stub surface', () => {+ it.each(['trpcClient.ts', 'trpcClient.client.ts', '../../../share/app/stubs/trpcClient.ts'])(+ 'covers the device service imports in %s',+ (stubFile) => {+ const source = readFileSync(+ path.resolve(stubDir, '../../../../src/services/device.ts'),+ 'utf8',+ );+ const stub = readFileSync(path.resolve(stubDir, stubFile), 'utf8');++ expect(+ reportStubSurfaceGaps(+ [{ rel: 'src/services/device.ts', source }],+ [{ source: stub, specifier: '@/libs/trpc/client' }],+ ),+ ).toEqual([]);+ },+ );+it('treats reject() and createTRPCClient() as open members', () => {const surface = parseStubSurface(readFileSync(path.join(stubDir, 'trpcClient.client.ts'), 'utf8'),@@ -20,6 +38,7 @@ describe('workbench stub surface', () => {expect([...surface.exports].sort()).toEqual(['asyncClient',+ 'createWorkspaceLambdaClient','lambdaClient','lambdaQuery','toolsClient',@@ -31,13 +50,13 @@ describe('workbench stub surface', () => {stubUsageGaps(surface,collectStubUsage(- `import { lambdaClient, createWorkspaceLambdaClient } from '@/libs/trpc/client';+ `import { lambdaClient, unavailableWorkspaceClient } from '@/libs/trpc/client';void lambdaClient.verify.getBundle.query();- void createWorkspaceLambdaClient('ws');`,+ void unavailableWorkspaceClient('ws');`,'@/libs/trpc/client',)!,),- ).toEqual(['createWorkspaceLambdaClient']);+ ).toEqual(['unavailableWorkspaceClient']);});it('reports a store method the simplified stub does not implement', () => {diff --git a/apps/workbench/app/stubs/trpcClient.client.ts b/apps/workbench/app/stubs/trpcClient.client.tsindex 5425c7fe454..29a6efa73a3 100644--- a/apps/workbench/app/stubs/trpcClient.client.ts+++ b/apps/workbench/app/stubs/trpcClient.client.ts@@ -15,6 +15,7 @@ export const lambdaClient = createTRPCClient<LambdaRouter>({],});+export const createWorkspaceLambdaClient = reject('createWorkspaceLambdaClient');export const asyncClient = reject('asyncClient');export const toolsClient = reject('toolsClient');export const lambdaQuery = reject('lambdaQuery');diff --git a/apps/workbench/app/stubs/trpcClient.ts b/apps/workbench/app/stubs/trpcClient.tsindex e524ab561ff..101c4527ee7 100644--- a/apps/workbench/app/stubs/trpcClient.ts+++ b/apps/workbench/app/stubs/trpcClient.ts@@ -1,6 +1,7 @@import { reject } from './reject';export const lambdaClient = reject('lambdaClient');+export const createWorkspaceLambdaClient = reject('createWorkspaceLambdaClient');export const asyncClient = reject('asyncClient');export const toolsClient = reject('toolsClient');export const lambdaQuery = reject('lambdaQuery');diff --git a/locales/en-US/device.json b/locales/en-US/device.jsonindex e7a373fbb35..d21471e70bf 100644--- a/locales/en-US/device.json+++ b/locales/en-US/device.json@@ -127,6 +127,7 @@"workingDirectory.refreshFolders": "Refresh folders","workingDirectory.refreshGitStatus": "Refresh branch & PR status","workingDirectory.removeRecent": "Remove from recent",+ "workingDirectory.removeRecentFailed": "Could not remove this folder. Please try again.","workingDirectory.removeWorktreeAction": "Delete worktree","workingDirectory.removeWorktreeConfirm": "Delete worktree “{{name}}”? This removes the worktree directory but keeps its branch. Git will refuse if it has uncommitted changes.","workingDirectory.removeWorktreeFailed": "Delete worktree failed",diff --git a/locales/zh-CN/device.json b/locales/zh-CN/device.jsonindex 4dd83dab903..b99dc1b60f5 100644--- a/locales/zh-CN/device.json+++ b/locales/zh-CN/device.json@@ -127,6 +127,7 @@"workingDirectory.refreshFolders": "刷新文件夹列表","workingDirectory.refreshGitStatus": "刷新分支与 PR 状态","workingDirectory.removeRecent": "从最近目录中移除",+ "workingDirectory.removeRecentFailed": "无法移除此文件夹,请重试。","workingDirectory.removeWorktreeAction": "删除 Worktree","workingDirectory.removeWorktreeConfirm": "删除 Worktree“{{name}}”?这会移除该 worktree 目录,但保留其分支;如果仍有未提交更改,Git 会拒绝删除。","workingDirectory.removeWorktreeFailed": "删除 Worktree 失败",diff --git a/packages/locales/src/default/device.ts b/packages/locales/src/default/device.tsindex 0ca0de5e0d6..47e91e1d098 100644--- a/packages/locales/src/default/device.ts+++ b/packages/locales/src/default/device.ts@@ -100,6 +100,7 @@ export default {'workingDirectory.recent': 'Working directory','workingDirectory.refreshGitStatus': 'Refresh branch & PR status','workingDirectory.removeRecent': 'Remove from recent',+ 'workingDirectory.removeRecentFailed': 'Could not remove this folder. Please try again.','workingDirectory.removed': 'Removed “{{name}}”','workingDirectory.renameBranchAction': 'Rename branch','workingDirectory.renameBranchTitle': 'Rename branch',diff --git a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsxindex 3088672431a..4aa38d6071f 100644--- a/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx+++ b/src/features/ChatInput/ControlBar/WorkingDirectoryPicker.tsx@@ -137,30 +137,35 @@ const isValidWorkingDirEntry = (entry: WorkingDirEntry): boolean =>type FolderEntry = { environmentId?: string; path: string; repoType?: 'git' | 'github' };/** This machine: browse the filesystem via the native Electron folder dialog. */-const ChooseLocalFolderRow = memo<{ defaultPath?: string; onPick: (entry: FolderEntry) => void }>(- ({ defaultPath, onPick }) => {- const { t } = useTranslation('device');- const handleClick = async () => {+const ChooseLocalFolderRow = memo<{+ defaultPath?: string;+ onPick: (entry: FolderEntry) => void | Promise<void>;+}>(({ defaultPath, onPick }) => {+ const { t } = useTranslation('device');+ const handleClick = async () => {+ try {const result = await electronSystemService.selectFolder({defaultPath: defaultPath || undefined,title: t('workingDirectory.selectFolder'),});- if (result) onPick({ path: result.path, repoType: result.repoType });- };- return (- <Flexbox- horizontal- align={'center'}- className={stylex.props(styles.chooseFolderItem).className}- gap={8}- onClick={handleClick}- >- <Icon icon={FolderOpenIcon} size={14} />- <span>{t('workingDirectory.chooseDifferentFolder')}</span>- </Flexbox>- );- },-);+ if (result) await onPick({ path: result.path, repoType: result.repoType });+ } catch {+ toast.error(t('workingDirectory.addFolderFailed'));+ }+ };+ return (+ <Flexbox+ horizontal+ align={'center'}+ className={stylex.props(styles.chooseFolderItem).className}+ gap={8}+ onClick={handleClick}+ >+ <Icon icon={FolderOpenIcon} size={14} />+ <span>{t('workingDirectory.chooseDifferentFolder')}</span>+ </Flexbox>+ );+});ChooseLocalFolderRow.displayName = 'ChooseLocalFolderRow';/** Browse the target device through its directory RPC. */@@ -320,27 +325,32 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =setOpen(false);};- const handleRemoveRecent = (e: React.MouseEvent, entry: WorkingDirEntry) => {+ const handleRemoveRecent = async (e: React.MouseEvent, entry: WorkingDirEntry) => {e.stopPropagation();if (!targetDeviceId) return;- // Both remove and the undo re-add persist the *whole* `workingDirs` array, so- // an undo fired before the remove settles would race it — a late-finishing- // remove would clobber the re-added entry and the undo would silently fail.- // Chain the undo behind the remove promise so the re-add always writes last.- const removed = removeDeviceWorkingDir(targetDeviceId, entry.path);- toast.success({- actions: [- {- label: t('workingDirectory.undo'),- onClick: () =>- void removed.then(() => updateDeviceCwd(targetDeviceId, entry, { setDefault: false })),- variant: 'text',- },- ],- title: t('workingDirectory.removed', {- name: getWorkingDirectoryName(entry.path) ?? entry.path,- }),- });+ try {+ await removeDeviceWorkingDir(targetDeviceId, entry.path);+ toast.success({+ actions: [+ {+ label: t('workingDirectory.undo'),+ onClick: async () => {+ try {+ await updateDeviceCwd(targetDeviceId, entry, { setDefault: false });+ } catch {+ toast.error(t('workingDirectory.addFolderFailed'));+ }+ },+ variant: 'text',+ },+ ],+ title: t('workingDirectory.removed', {+ name: getWorkingDirectoryName(entry.path) ?? entry.path,+ }),+ });+ } catch {+ toast.error(t('workingDirectory.removeRecentFailed'));+ }};const handleToggleDefault = async (@@ -377,7 +387,9 @@ const WorkingDirectoryPicker = memo<WorkingDirectoryPickerProps>(({ agentId }) =stylex.props(stylex.defaultMarker(), styles.dirItem, isActive && styles.dirItemActive).className}- onClick={() => void pick(entry)}+ onClick={() =>+ void pick(entry).catch(() => toast.error(t('workingDirectory.addFolderFailed')))+ }><DirIcon repoType={entry.repoType} /><Flexbox flex={1} style={{ minWidth: 0 }}>diff --git a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsxindex 7ba22a30f82..48e6d808d86 100644--- a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx@@ -18,6 +18,7 @@ const testState = vi.hoisted(() => ({updateTopicMetadata: vi.fn(),},currentDeviceId: 'this-machine' as string | undefined,+ updateDeviceCwd: vi.fn(),resolveGatewayDeviceId: vi.fn(async (): Promise<string | undefined> => undefined),effective: {agencyConfig: undefined as Record<string, unknown> | undefined,@@ -48,7 +49,7 @@ vi.mock('@/store/chat/selectors', () => ({vi.mock('@/store/device', () => ({useDeviceStore: (selector: (s: { updateDeviceCwd: unknown }) => unknown) =>- selector({ updateDeviceCwd: vi.fn() }),+ selector({ updateDeviceCwd: testState.updateDeviceCwd }),}));vi.mock('@/store/electron', () => ({@@ -135,6 +136,52 @@ describe('useCommitWorkingDirectory — localTarget', () => {);});+ it('records a local pick on this machine instead of the previous remote target', async () => {+ testState.effective.agencyConfig = {+ boundDeviceId: 'other-device',+ executionTarget: 'device',+ };+ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));++ await result.current.commit({ path: '/local/repo' }, { localTarget: true });++ expect(testState.updateDeviceCwd).toHaveBeenCalledWith(+ 'this-machine',+ { path: '/local/repo' },+ { setDefault: false },+ );+ });++ it('records the picked folder on the same newly resolved device as the topic', async () => {+ testState.currentDeviceId = undefined;+ testState.chat.activeTopicId = 'topic';+ testState.resolveGatewayDeviceId.mockResolvedValueOnce('resolved-device');+ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));++ await result.current.commit({ path: '/repo' });++ expect(testState.chat.updateTopicMetadata).toHaveBeenCalledWith(+ 'topic',+ expect.objectContaining({ boundDeviceId: 'resolved-device', workingDirectory: '/repo' }),+ );+ expect(testState.updateDeviceCwd).toHaveBeenCalledWith(+ 'resolved-device',+ { path: '/repo' },+ { setDefault: false },+ );+ });++ it('keeps the selection unchanged when saving the reusable directory fails', async () => {+ testState.chat.activeTopicId = 'topic';+ testState.updateDeviceCwd.mockRejectedValueOnce(new Error('save failed'));+ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));++ await expect(result.current.commit({ path: '/repo' })).rejects.toThrow('save failed');++ expect(testState.chat.updateTopicMetadata).not.toHaveBeenCalled();+ expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();+ });+it('leaves ordinary writes routed by the resolved config', async () => {// No override: a `device` target still files against its bound device, so// the new option cannot change how the directory picker behaves.diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.tsindex cd85db28fc0..3ece5ad1e80 100644--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts@@ -154,7 +154,13 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string// lets it state the destination it is creating, so the cwd lands in the// same slot the pending `local` pick will read from.const localTarget = options?.localTarget === true;- const writeDeviceId = localTarget ? currentDeviceId : targetDeviceId;+ const writeDeviceId = localTarget+ ? currentDeviceId+ : (targetDeviceId ??+ activeTopic?.metadata?.boundDeviceId ??+ (entry && activeTopicId+ ? await getElectronStoreState().resolveGatewayDeviceId()+ : undefined));// A `local` pick on a workspace agent always means this member's own// machine, which routes to the per-user slot rather than the shared row.const writePersonalSlot = localTarget@@ -164,6 +170,11 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string// The session cwd anchors to the source repo for hetero (stable across// worktree switches) and to the effective/worktree path otherwise.const sessionCwd = isHetero ? getWorkingDirSourcePath(entry) : effectivePath;+ // Save the reusable device entry before changing the selection. A failed+ // recent-directory write must not leave a chip that looks successfully saved.+ if (entry && effectivePath && writeDeviceId) {+ await updateDeviceCwd(writeDeviceId, entry, { setDefault: false });+ }// Topic override wins once a conversation exists; otherwise persist the// agent's per-device choice so a new topic inherits it.if (activeTopicId) {@@ -187,11 +198,7 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string// moved to another device keeps the directory just chosen there. An// unresolved target keeps the topic's own pin (or this desktop's id)// rather than leaving the new path with no machine at all.- boundDeviceId: entry- ? (writeDeviceId ??- activeTopic?.metadata?.boundDeviceId ??- (await getElectronStoreState().resolveGatewayDeviceId()))- : undefined,+ boundDeviceId: entry ? writeDeviceId : undefined,...(shouldUpdateHeteroSession ? { heteroSessionId: scopedHeteroSessionId } : {}),workingDirectory: sessionCwd,workingDirectoryConfig: entry ? toAgentWorkingDirConfig(entry) : undefined,@@ -234,11 +241,6 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: stringawait updateAgentRuntimeEnvConfigById(agentId, { workingDirectory: undefined });}}- // Record on the target device's recent list (not the device-wide default —- // a per-agent pick shouldn't repoint other agents on the same device).- if (entry && effectivePath && targetDeviceId) {- await updateDeviceCwd(targetDeviceId, entry, { setDefault: false });- }},[agentId,diff --git a/src/services/__tests__/deviceWorkingDirectory.scope.test.ts b/src/services/__tests__/deviceWorkingDirectory.scope.test.tsnew file mode 100644index 00000000000..7ef75befb65--- /dev/null+++ b/src/services/__tests__/deviceWorkingDirectory.scope.test.ts@@ -0,0 +1,103 @@+// @vitest-environment node+import type { WorkingDirEntry } from '@lobechat/types';+import { fetchRequestHandler } from '@trpc/server/adapters/fetch';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { authedProcedure, router } from '@/libs/trpc/lambda';+import { registryRouter } from '@/server/routers/lambda/device/registry';+import { workspaceDeviceWorkingDirProcedures } from '@/server/routers/lambda/deviceWorkspaceWorkingDirs';++import { deviceService } from '../device';++const database = vi.hoisted(() => ({+ personalDirs: [] as WorkingDirEntry[],+ workspaceDirs: [] as WorkingDirEntry[],+}));++vi.mock('@/const/version', () => ({ isDesktop: false }));+vi.mock('@/services/_auth', () => ({ createHeaderWithAuth: async () => ({}) }));+vi.mock('@/business/client/trpc-headers', () => ({+ getBusinessTrpcHeaders: async () => ({ 'X-Workspace-Id': 'workspace' }),+}));+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/device', () => ({+ DeviceModel: class {+ findByDeviceId = async () => ({ workingDirs: database.personalDirs });+ findWorkspaceDeviceById = async (deviceId: string) =>+ deviceId === 'workspace-device' ? { userId: 'member', visibility: 'public' } : undefined;+ update = async (_deviceId: string, value: { workingDirs?: WorkingDirEntry[] }) => {+ if (value.workingDirs) database.personalDirs = value.workingDirs;+ };+ mutateWorkspaceDeviceWorkingDirs = async (+ _deviceId: string,+ apply: (dirs: WorkingDirEntry[]) => WorkingDirEntry[],+ ) => {+ database.workspaceDirs = apply(database.workspaceDirs);+ };+ },+}));++// Exercise the real client headers, authorization middleware and write handlers.+// Only the database and device-list read are fixtures; no gateway is needed.+const testRouter = router({+ device: router({+ addWorkspaceDeviceWorkingDir: workspaceDeviceWorkingDirProcedures.addWorkspaceDeviceWorkingDir,+ listDevices: authedProcedure.query(() => [+ { deviceId: 'personal-device', workingDirs: database.personalDirs },+ { deviceId: 'workspace-device', workingDirs: database.workspaceDirs },+ ]),+ updateDevice: registryRouter._def.procedures.updateDevice,+ }),+});++describe('device working-directory persistence while a workspace is active', () => {+ beforeEach(() => {+ database.personalDirs = [{ path: '/existing' }];+ database.workspaceDirs = [{ path: '/shared' }];+ vi.stubGlobal('location', new URL('http://localhost/'));+ vi.stubGlobal('fetch', (input: RequestInfo | URL, init?: RequestInit) => {+ const req = new Request(new URL(String(input), 'http://localhost'), init);+ return fetchRequestHandler({+ createContext: () =>+ ({+ userId: 'member',+ workspaceId: req.headers.get('X-Workspace-Id') ?? undefined,+ workspaceRole: 'member',+ }) as never,+ endpoint: '/trpc/lambda',+ req,+ router: testRouter,+ });+ });+ });++ afterEach(() => vi.unstubAllGlobals());++ it('keeps an added personal directory when the device list is fetched again', async () => {+ await deviceService.updateDevice({+ deviceId: 'personal-device',+ workingDirs: [{ path: '/new' }, ...database.personalDirs],+ });++ const devices = await deviceService.listDevices();+ expect(devices[0].workingDirs).toEqual([{ path: '/new' }, { path: '/existing' }]);+ expect(devices[1].workingDirs).toEqual([{ path: '/shared' }]);+ });++ it('keeps a removed personal directory out of subsequent device lists', async () => {+ await deviceService.updateDevice({ deviceId: 'personal-device', workingDirs: [] });++ expect((await deviceService.listDevices())[0].workingDirs).toEqual([]);+ });++ it('continues saving workspace directories through the workspace scope', async () => {+ await deviceService.addWorkspaceDeviceWorkingDir({+ deviceId: 'workspace-device',+ entry: { path: '/new-shared' },+ });++ const devices = await deviceService.listDevices();+ expect(devices[1].workingDirs).toEqual([{ path: '/new-shared' }, { path: '/shared' }]);+ expect(devices[0].workingDirs).toEqual([{ path: '/existing' }]);+ });+});diff --git a/src/services/device.ts b/src/services/device.tsindex 01ba65a337b..4df7fdbfd7b 100644--- a/src/services/device.ts+++ b/src/services/device.ts@@ -5,7 +5,7 @@ import type {DeviceScope,} from '@lobechat/types';-import { lambdaClient } from '@/libs/trpc/client';+import { createWorkspaceLambdaClient, lambdaClient } from '@/libs/trpc/client';import { type TopicListItem } from '@/services/topic';type DeviceClient = typeof lambdaClient.device;@@ -27,7 +27,8 @@ class DeviceService {/** Update user-editable device fields (defaultCwd / friendlyName / workingDirs). */updateDevice(input: Parameters<DeviceClient['updateDevice']['mutate']>[0]) {- return lambdaClient.device.updateDevice.mutate(input);+ // Personal devices remain editable while the UI has an active workspace.+ return createWorkspaceLambdaClient(null).device.updateDevice.mutate(input);}/** Update user-editable fields of a workspace-enrolled device (workspace-scoped write). */