Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(project): edit and remove project working directories (#22725)

Arvin Xu6aabdb753d95
diff --git a/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.relocate.test.ts b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.relocate.test.ts
new file mode 100644
index 00000000000..5bc8bc1d7f8
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.relocate.test.ts
@@ -0,0 +1,105 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ assertCanUseTopicTargets: vi.fn(),
+ listTopics: vi.fn(),
+ relocate: vi.fn(),
+ resolve: vi.fn(),
+ statPath: vi.fn(),
+}));
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn(function () {
+ return (opts: any) => opts.next({ ctx: opts.ctx });
+ }),
+}));
+
+vi.mock('@/database/models/projectWorkingDirectory', () => ({
+ ProjectWorkingDirectoryModel: vi.fn(function () {
+ return { listTopics: mocks.listTopics, resolve: mocks.resolve };
+ }),
+}));
+
+vi.mock('@/database/repositories/projectDirectory', () => ({
+ ProjectDirectoryRepository: vi.fn(function () {
+ return { relocate: mocks.relocate };
+ }),
+}));
+
+vi.mock('../_helpers/shareVisitorTargetGuard', () => ({
+ assertCreatorTopicTargets: vi.fn(),
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: { statPath: mocks.statPath },
+}));
+
+vi.mock('../_helpers/conversationResourceGuard', () => ({
+ assertCanUseConversationTargets: vi.fn(),
+ assertCanUseTopicTargets: mocks.assertCanUseTopicTargets,
+ assertCanViewTopicTargets: vi.fn(),
+}));
+
+const { projectWorkingDirectoryRouter } = await import('../projectWorkingDirectory');
+
+const caller = () =>
+ projectWorkingDirectoryRouter.createCaller({ userId: 'user-1', workspaceId: null } as never);
+const input = {
+ deviceId: 'device-b',
+ id: '00000000-0000-4000-8000-000000000002',
+ path: '/work/repo-b',
+ projectId: 'project-1',
+};
+
+describe('projectWorkingDirectory.relocate', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.relocate.mockResolvedValue({ id: 'directory-2' });
+ mocks.listTopics.mockResolvedValue([{ id: 'topic-1' }, { id: 'topic-2' }]);
+ });
+
+ it('relocates once the new path exists on the chosen device', async () => {
+ mocks.statPath.mockResolvedValue({ exists: true, isDirectory: true });
+
+ await expect(caller().relocate(input)).resolves.toMatchObject({ success: true });
+
+ expect(mocks.statPath).toHaveBeenCalledWith({
+ deviceId: 'device-b',
+ path: '/work/repo-b',
+ userId: 'user-1',
+ workspaceId: undefined,
+ });
+ expect(mocks.assertCanUseTopicTargets).toHaveBeenCalledWith(expect.anything(), [
+ 'topic-1',
+ 'topic-2',
+ ]);
+ expect(mocks.relocate).toHaveBeenCalledWith({
+ ...input,
+ authorizedTopicIds: ['topic-1', 'topic-2'],
+ });
+ });
+
+ it('keeps the directory where it is when the new path is not on the device', async () => {
+ mocks.statPath.mockResolvedValue({ exists: false, isDirectory: false });
+
+ await expect(caller().relocate(input)).rejects.toThrow(
+ 'Device is offline or working directory is unavailable',
+ );
+ expect(mocks.relocate).not.toHaveBeenCalled();
+ });
+
+ it('keeps the directory where it is when the caller cannot use one of its topics', async () => {
+ mocks.statPath.mockResolvedValue({ exists: true, isDirectory: true });
+ mocks.assertCanUseTopicTargets.mockRejectedValue(new Error('Forbidden topic'));
+
+ await expect(caller().relocate(input)).rejects.toThrow('Forbidden topic');
+ expect(mocks.relocate).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/projectWorkingDirectory.ts b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
index 908413a94a6..28024be0a6c 100644
--- a/apps/server/src/routers/lambda/projectWorkingDirectory.ts
+++ b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
@@ -281,6 +281,48 @@ export const projectWorkingDirectoryRouter = router({
success: true,
};
}),
+ /** Repoint a directory bound with the wrong device or path; its topics follow it. */
+ relocate: write
+ .input(
+ idInput.extend({
+ deviceId: z.string().min(1),
+ path: z.string().min(1),
+ projectId: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ // The same gate as `moveTopic`: the conversations move with the directory,
+ // so a destination the device cannot see must fail before anything moves.
+ const stat = await deviceGateway.statPath({
+ deviceId: input.deviceId,
+ path: input.path,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ });
+ if (!stat?.exists || !stat.isDirectory)
+ throw new TRPCError({
+ code: 'PRECONDITION_FAILED',
+ message: 'Device is offline or working directory is unavailable',
+ });
+ // Relocating rewrites each topic's execution target and drops its CLI
+ // session, which is a write to every one of them: the caller needs `use`
+ // access to each, as `moveTopic` requires for one.
+ const topicIds = (await ctx.directoryModel.listTopics(input.id)).map((topic) => topic.id);
+ await assertCanUseTopicTargets(
+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ topicIds,
+ );
+ return {
+ data: await ctx.directoryRepo.relocate({ ...input, authorizedTopicIds: topicIds }),
+ success: true,
+ };
+ }),
+ remove: write
+ .input(idInput.extend({ projectId: z.string() }))
+ .mutation(async ({ ctx, input }) => ({
+ data: await ctx.directoryRepo.remove(input.projectId, input.id),
+ success: true,
+ })),
resolve: procedure.input(idInput).query(async ({ ctx, input }) => ({
data: await ctx.directoryModel.resolve(input.id),
success: true,
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index f8c1d98a59a..ded22806dcc 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -338,8 +338,13 @@
"settings.description": "Description",
"settings.deviceOffline": "Device disconnected",
"settings.deviceOnline": "Device connected",
- "settings.directoryDescription": "Choose a folder and start a topic. The Agent will work with files in that folder on the connected device.",
+ "settings.directoryListDescription": "Device folders this project works in. Agents read and change files in them on that device.",
"settings.directoryUnavailable": "The device is disconnected or the directory is unavailable. Connect the device and check the path, then retry.",
+ "settings.editDirectory": "Edit folder",
+ "settings.editDirectoryBusy": "A topic is running in this folder. Wait for it to finish and try again.",
+ "settings.editDirectoryDescription": "Choose the device and folder this working directory points to. Its topics move to the new folder and start new sessions there.",
+ "settings.editDirectoryFailed": "Could not update the folder",
+ "settings.editDirectoryOtherEnvironment": "This folder already belongs to another environment. Choose a different folder or device.",
"settings.environmentDescription": "Keep repository sources together in an environment, then add a folder on your device to start working.",
"settings.environments": "Environments",
"settings.general": "General",
@@ -358,6 +363,10 @@
"settings.noDirectories": "No folders in this environment yet. Add an existing folder on a connected device to start working.",
"settings.noEnvironments": "No environments associated yet",
"settings.noRepository": "No GitHub repository linked",
+ "settings.removeDirectory": "Remove folder",
+ "settings.removeDirectoryConfirmDescription": "{{path}} on {{device}} will no longer be a working directory of this project. Files on the device are not changed. Its topics stay in the project but are no longer linked to this folder.",
+ "settings.removeDirectoryConfirmTitle": "Remove {{name}} from this project?",
+ "settings.removeDirectoryFailed": "Could not remove the folder. If a topic is running here, wait for it to finish and try again.",
"settings.reuseEnvironment": "Add an existing environment to this project",
"settings.reuseEnvironmentDescription": "Already created an environment? Select it to link its repository configuration to this project, then add a working directory for this project.",
"settings.saveFailed": "Could not save the change",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index 58b67d99fb7..a22429421c2 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -338,8 +338,13 @@
"settings.description": "项目说明",
"settings.deviceOffline": "设备未连接",
"settings.deviceOnline": "设备已连接",
- "settings.directoryDescription": "选择文件夹,在此新建话题。Agent 将在对应设备上读取和修改该文件夹中的文件。",
+ "settings.directoryListDescription": "本项目在这些设备文件夹中工作,Agent 会在对应设备上读取和修改其中的文件。",
"settings.directoryUnavailable": "设备未连接或目录不可用。连接设备并检查路径后重试。",
+ "settings.editDirectory": "修改文件夹",
+ "settings.editDirectoryBusy": "有话题正在此文件夹运行,请等待结束后重试。",
+ "settings.editDirectoryDescription": "选择这个工作目录对应的设备和文件夹。相关话题会一起迁移到新文件夹,并在那里开始新的会话。",
+ "settings.editDirectoryFailed": "无法修改文件夹",
+ "settings.editDirectoryOtherEnvironment": "这个文件夹已属于其他环境,请选择别的文件夹或设备。",
"settings.environmentDescription": "用环境管理仓库来源,再添加设备上的文件夹,开始在项目中工作。",
"settings.environments": "环境",
"settings.general": "基础设置",
@@ -358,6 +363,10 @@
"settings.noDirectories": "还没有工作目录。添加已连接设备上的文件夹后,即可在此新建对话。",
"settings.noEnvironments": "尚未关联环境",
"settings.noRepository": "未关联 GitHub 仓库",
+ "settings.removeDirectory": "移除文件夹",
+ "settings.removeDirectoryConfirmDescription": "{{device}} 上的 {{path}} 将不再是本项目的工作目录。设备上的文件不会改动,相关话题仍保留在项目中,但不再关联此文件夹。",
+ "settings.removeDirectoryConfirmTitle": "从项目中移除「{{name}}」?",
+ "settings.removeDirectoryFailed": "无法移除文件夹。如果有话题正在此处运行,请等待结束后重试。",
"settings.reuseEnvironment": "将已有环境添加到本项目",
"settings.reuseEnvironmentDescription": "如果之前已创建过环境,可从列表选择,将它的仓库配置关联到本项目,再为本项目添加工作目录。",
"settings.saveFailed": "保存失败",
diff --git a/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts b/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts
index 38c4720c1bc..e629eb9feea 100644
--- a/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts
+++ b/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts
@@ -603,3 +603,201 @@ describe('ProjectDirectoryRepository.moveTopic', () => {
);
});
});
+
+describe('ProjectDirectoryRepository.remove', () => {
+ const seedTopic = async (directoryId: string, patch: Partial<typeof topics.$inferInsert> = {}) =>
+ db.insert(topics).values({
+ id: 'remove-topic',
+ projectId: base.projectId,
+ projectWorkingDirectoryId: directoryId,
+ title: 'Topic',
+ userId,
+ ...patch,
+ });
+
+ it('drops only the project link, keeping its instance and conversations', async () => {
+ const directory = await repo.bind(base);
+ await seedTopic(directory.id);
+
+ await expect(repo.remove(base.projectId, directory.id)).resolves.toMatchObject({
+ id: directory.id,
+ });
+
+ expect(await directoryModel.list(base.projectId)).toEqual([]);
+ expect(await db.select().from(environmentInstances)).toHaveLength(1);
+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'remove-topic'));
+ expect(topic).toMatchObject({ projectId: base.projectId, projectWorkingDirectoryId: null });
+ });
+
+ it('lets the same location be bound again after removal', async () => {
+ const directory = await repo.bind(base);
+ await repo.remove(base.projectId, directory.id);
+
+ const rebound = await repo.bind(base);
+
+ expect(rebound.id).not.toBe(directory.id);
+ expect(await directoryModel.list(base.projectId)).toHaveLength(1);
+ });
+
+ it('refuses while a conversation is running in the directory', async () => {
+ const directory = await repo.bind(base);
+ await seedTopic(directory.id, { status: 'running' });
+
+ await expect(repo.remove(base.projectId, directory.id)).rejects.toThrow(
+ 'Wait for the running topics',
+ );
+
+ expect(await directoryModel.list(base.projectId)).toHaveLength(1);
+ });
+
+ it('refuses a caller who cannot manage the project', async () => {
+ const directory = await repo.bind(base);
+
+ await expect(otherRepo.remove(base.projectId, directory.id)).rejects.toThrow(
+ 'Project not found or access denied',
+ );
+
+ expect(await directoryModel.list(base.projectId)).toHaveLength(1);
+ });
+
+ it('does not remove a directory through another project', async () => {
+ const directory = await repo.bind(base);
+ await db.insert(projects).values({
+ coordinatorAgentId: 'repo-coordinator',
+ id: 'remove-other-project',
+ identifier: 'OTH',
+ name: 'Other project',
+ userId,
+ });
+
+ await expect(repo.remove('remove-other-project', directory.id)).rejects.toThrow(
+ 'Project directory not found',
+ );
+
+ expect(await directoryModel.list(base.projectId)).toHaveLength(1);
+ });
+});
+
+describe('ProjectDirectoryRepository.relocate', () => {
+ const otherDevice = 'repo-device-2';
+ const seedTopic = async (directoryId: string, patch: Partial<typeof topics.$inferInsert> = {}) =>
+ db.insert(topics).values({
+ agentId: 'repo-agent',
+ id: 'relocate-topic',
+ metadata: {
+ boundDeviceId: base.deviceId,
+ heteroSessionId: 'stale-session',
+ workingDirectory: base.path,
+ },
+ projectId: base.projectId,
+ projectWorkingDirectoryId: directoryId,
+ title: 'Topic',
+ userId,
+ ...patch,
+ });
+
+ beforeEach(async () => {
+ await db
+ .insert(devices)
+ .values({ deviceId: otherDevice, identitySource: 'fallback', platform: 'linux', userId });
+ });
+
+ it('moves the directory and its topics to the new location', async () => {
+ const directory = await repo.bind(base);
+ await seedTopic(directory.id);
+
+ const moved = await repo.relocate({
+ deviceId: otherDevice,
+ id: directory.id,
+ path: '/work/fixed/',
+ projectId: base.projectId,
+ });
+
+ const rows = await directoryModel.list(base.projectId);
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({
+ deviceId: otherDevice,
+ environmentId: (await directoryModel.list())[0].environmentId,
+ id: moved.id,
+ path: '/work/fixed',
+ });
+ expect(moved.id).not.toBe(directory.id);
+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'relocate-topic'));
+ expect(topic.projectWorkingDirectoryId).toBe(moved.id);
+ expect(topic.metadata).toEqual({
+ boundDeviceId: otherDevice,
+ workingDirectory: '/work/fixed',
+ workingDirectoryConfig: { path: '/work/fixed' },
+ });
+ });
+
+ it('keeps everything in place when a topic is running there', async () => {
+ const directory = await repo.bind(base);
+ await seedTopic(directory.id, { status: 'running' });
+
+ await expect(
+ repo.relocate({
+ deviceId: otherDevice,
+ id: directory.id,
+ path: '/work/fixed',
+ projectId: base.projectId,
+ }),
+ ).rejects.toThrow('Wait for the running topics');
+
+ expect(await directoryModel.list(base.projectId)).toMatchObject([
+ { id: directory.id, path: base.path },
+ ]);
+ });
+
+ it('refuses a topic bound after the caller was authorized', async () => {
+ const directory = await repo.bind(base);
+ await seedTopic(directory.id);
+
+ await expect(
+ repo.relocate({
+ authorizedTopicIds: [],
+ deviceId: otherDevice,
+ id: directory.id,
+ path: '/work/fixed',
+ projectId: base.projectId,
+ }),
+ ).rejects.toThrow('The topics in this directory changed');
+
+ expect(await directoryModel.list(base.projectId)).toMatchObject([{ id: directory.id }]);
+ });
+
+ it('refuses a move away from the device a topic agent is fixed to', async () => {
+ const directory = await repo.bind(base);
+ await db
+ .update(agents)
+ .set({
+ agencyConfig: { boundDeviceId: base.deviceId, executionTargetSelectionPolicy: 'fixed' },
+ })
+ .where(eq(agents.id, 'repo-agent'));
+ await seedTopic(directory.id);
+
+ await expect(
+ repo.relocate({
+ deviceId: otherDevice,
+ id: directory.id,
+ path: '/work/fixed',
+ projectId: base.projectId,
+ }),
+ ).rejects.toThrow('Agent cannot use this execution target');
+
+ expect(await directoryModel.list(base.projectId)).toMatchObject([{ id: directory.id }]);
+ });
+
+ it('refuses a caller who cannot manage the project', async () => {
+ const directory = await repo.bind(base);
+
+ await expect(
+ otherRepo.relocate({
+ deviceId: otherDevice,
+ id: directory.id,
+ path: '/work/fixed',
+ projectId: base.projectId,
+ }),
+ ).rejects.toThrow('Project not found or access denied');
+ });
+});
diff --git a/packages/database/src/repositories/projectDirectory/index.ts b/packages/database/src/repositories/projectDirectory/index.ts
index 9f88a77625e..8573e5eb8d7 100644
--- a/packages/database/src/repositories/projectDirectory/index.ts
+++ b/packages/database/src/repositories/projectDirectory/index.ts
@@ -1,3 +1,4 @@
+import type { ChatTopicMetadata } from '@lobechat/types';
import { getWorkingDirSourcePath } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { and, eq, inArray, isNull } from 'drizzle-orm';
@@ -10,7 +11,13 @@ import {
ProjectWorkingDirectoryModel,
} from '../../models/projectWorkingDirectory';
import { hasLiveTaskCallbackReservation } from '../../models/topic';
-import { agents, devices, projectEnvironments, topics } from '../../schemas';
+import {
+ agents,
+ devices,
+ projectEnvironments,
+ projectWorkingDirectories,
+ topics,
+} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { joinTopicAgentsToProjects } from '../../utils/projectTopicAgents';
import { buildWorkspaceWhere } from '../../utils/workspace';
@@ -35,6 +42,48 @@ export interface SkippedProjectTopic {
reason: SkippedProjectTopicReason;
}
+/**
+ * Point a conversation at another device directory. The cwd and CLI session
+ * only hold on the old machine, so they are dropped rather than carried over.
+ */
+const pinTopicToDirectory = (
+ metadata: ChatTopicMetadata | null | undefined,
+ deviceId: string,
+ path: string,
+): ChatTopicMetadata => {
+ const {
+ heteroSessionBindingKey: _bindingKey,
+ heteroSessionBindingKeyByWorkingDirectory: _bindingKeys,
+ heteroSessionId: _sessionId,
+ heteroSessionIdByWorkingDirectory: _sessionIds,
+ ...rest
+ } = metadata ?? {};
+ return {
+ ...rest,
+ boundDeviceId: deviceId,
+ workingDirectory: path,
+ workingDirectoryConfig: { path },
+ };
+};
+
+const isTopicInFlight = (topic: { metadata?: ChatTopicMetadata | null; status?: string | null }) =>
+ topic.status === 'running' ||
+ !!topic.metadata?.runningOperation ||
+ hasLiveTaskCallbackReservation(topic.metadata);
+
+export interface RelocateProjectDirectoryInput {
+ /**
+ * The topics the caller was authorized to move. A topic bound to the
+ * directory after that check fails the relocation instead of moving
+ * unchecked.
+ */
+ authorizedTopicIds?: string[];
+ deviceId: string;
+ id: string;
+ path: string;
+ projectId: string;
+}
+
export interface BindProjectDirectoryInput {
agentId?: string;
deviceId: string;
@@ -334,6 +383,127 @@ export class ProjectDirectoryRepository {
return updated;
});
}
+
+ /**
+ * Remove a directory from its project. Only the project's link goes: the
+ * environment instance is keyed by (device, path) and may serve other
+ * projects, and the conversations stay in the project with the foreign key
+ * clearing their directory binding.
+ */
+ async remove(projectId: string, directoryId: string) {
+ await this.assertManageableProject(projectId);
+ return this.db.transaction(async (tx) => {
+ const db = tx as LobeChatDatabase;
+ const bound = await db
+ .select()
+ .from(topics)
+ .where(
+ and(
+ eq(topics.projectId, projectId),
+ eq(topics.projectWorkingDirectoryId, directoryId),
+ isNull(topics.deletedAt),
+ ),
+ )
+ .for('update');
+ // A run that already resolved this directory would finish against a
+ // binding that no longer exists. The row locks serialize with its
+ // reservation write, as in `moveTopic`.
+ if (bound.some(isTopicInFlight))
+ throw new ProjectDirectoryError(
+ 'CONFLICT',
+ 'Wait for the running topics to finish before removing this directory',
+ );
+ const [removed] = await db
+ .delete(projectWorkingDirectories)
+ .where(
+ and(
+ eq(projectWorkingDirectories.id, directoryId),
+ eq(projectWorkingDirectories.projectId, projectId),
+ ),
+ )
+ .returning();
+ if (!removed) throw new ProjectDirectoryError('NOT_FOUND', 'Project directory not found');
+ return removed;
+ });
+ }
+
+ /**
+ * Point a directory at another device location, for a binding made with the
+ * wrong path. The new location is bound like any other (same environment),
+ * the directory's conversations follow it as in `moveTopic`, and the old row
+ * goes — so no conversation is left pinned to a path its directory no longer
+ * names. The caller has already confirmed the new path exists on the device.
+ */
+ async relocate(input: RelocateProjectDirectoryInput) {
+ await this.assertManageableProject(input.projectId);
+ return this.db.transaction(async (tx) => {
+ const db = tx as LobeChatDatabase;
+ const current = (
+ await new ProjectWorkingDirectoryModel(db, this.userId, this.workspaceId).list(
+ input.projectId,
+ )
+ ).find((row) => row.id === input.id);
+ if (!current) throw new ProjectDirectoryError('NOT_FOUND', 'Project directory not found');
+ const bound = await db
+ .select()
+ .from(topics)
+ .where(
+ and(
+ eq(topics.projectId, input.projectId),
+ eq(topics.projectWorkingDirectoryId, input.id),
+ isNull(topics.deletedAt),
+ ),
+ )
+ .for('update');
+ if (bound.some(isTopicInFlight))
+ throw new ProjectDirectoryError(
+ 'CONFLICT',
+ 'Wait for the running topics to finish before changing this directory',
+ );
+ const authorized = input.authorizedTopicIds && new Set(input.authorizedTopicIds);
+ if (authorized && bound.some((topic) => !authorized.has(topic.id)))
+ throw new ProjectDirectoryError(
+ 'CONFLICT',
+ 'The topics in this directory changed; try again',
+ );
+ const next = await new ProjectDirectoryRepository(db, this.userId, this.workspaceId).bind({
+ deviceId: input.deviceId,
+ environmentId: current.environmentId ?? undefined,
+ name: input.path.split(/[\\/]/).findLast(Boolean) || input.path,
+ path: input.path,
+ projectId: input.projectId,
+ });
+ if (next.id === input.id) return next;
+ const agentIds = [
+ ...new Set(bound.flatMap((topic) => (topic.agentId ? [topic.agentId] : []))),
+ ];
+ const boundAgents = agentIds.length
+ ? await db
+ .select()
+ .from(agents)
+ .where(and(inArray(agents.id, agentIds), buildWorkspaceWhere(this.scope(), agents)))
+ : [];
+ if (
+ boundAgents.some(
+ (agent) =>
+ agent.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
+ agent.agencyConfig.boundDeviceId !== input.deviceId,
+ )
+ )
+ throw new ProjectDirectoryError('FORBIDDEN', 'Agent cannot use this execution target');
+ for (const topic of bound)
+ await db
+ .update(topics)
+ .set({
+ metadata: pinTopicToDirectory(topic.metadata, input.deviceId, next.path),
+ projectWorkingDirectoryId: next.id,
+ })
+ .where(eq(topics.id, topic.id));
+ await db.delete(projectWorkingDirectories).where(eq(projectWorkingDirectories.id, input.id));
+ return next;
+ });
+ }
+
/**
* Move a project-directory conversation to its project's directory on another
* device. The directory belongs to the project, so switching devices means
@@ -393,22 +563,10 @@ export class ProjectDirectoryRepository {
)
throw new ProjectDirectoryError('FORBIDDEN', 'Agent cannot use this execution target');
}
- const {
- heteroSessionBindingKey: _bindingKey,
- heteroSessionBindingKeyByWorkingDirectory: _bindingKeys,
- heteroSessionId: _sessionId,
- heteroSessionIdByWorkingDirectory: _sessionIds,
- ...metadata
- } = topic.metadata ?? {};
const [updated] = await db
.update(topics)
.set({
- metadata: {
- ...metadata,
- boundDeviceId: directory.deviceId,
- workingDirectory: directory.path,
- workingDirectoryConfig: { path: directory.path },
- },
+ metadata: pinTopicToDirectory(topic.metadata, directory.deviceId, directory.path),
projectWorkingDirectoryId: directory.id,
})
.where(eq(topics.id, topicId))
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index 3fe1c285d83..d911cabfe4a 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -3,6 +3,20 @@ export default {
'settings.reuseEnvironmentDescription':
'Already created an environment? Select it to link its repository configuration to this project, then add a working directory for this project.',
'settings.startDirectoryConversation': 'New topic here',
+ 'settings.editDirectory': 'Edit folder',
+ 'settings.editDirectoryBusy':
+ 'A topic is running in this folder. Wait for it to finish and try again.',
+ 'settings.editDirectoryOtherEnvironment':
+ 'This folder already belongs to another environment. Choose a different folder or device.',
+ 'settings.editDirectoryDescription':
+ 'Choose the device and folder this working directory points to. Its topics move to the new folder and start new sessions there.',
+ 'settings.editDirectoryFailed': 'Could not update the folder',
+ 'settings.removeDirectory': 'Remove folder',
+ 'settings.removeDirectoryConfirmDescription':
+ '{{path}} on {{device}} will no longer be a working directory of this project. Files on the device are not changed. Its topics stay in the project but are no longer linked to this folder.',
+ 'settings.removeDirectoryConfirmTitle': 'Remove {{name}} from this project?',
+ 'settings.removeDirectoryFailed':
+ 'Could not remove the folder. If a topic is running here, wait for it to finish and try again.',
'settings.configureDirectory': 'Add a working directory',
'settings.reuseEnvironment': 'Add an existing environment to this project',
'settings.addDirectoryFailed': 'Could not add working directory',
@@ -14,8 +28,8 @@ export default {
'settings.description': 'Description',
'settings.generalDescription': 'Manage the project name, address, and description.',
'settings.workLocations': 'Working directories',
- 'settings.directoryDescription':
- 'Choose a folder and start a topic. The Agent will work with files in that folder on the connected device.',
+ 'settings.directoryListDescription':
+ 'Device folders this project works in. Agents read and change files in them on that device.',
'settings.environmentDescription':
'Keep repository sources together in an environment, then add a folder on your device to start working.',
'settings.allEnvironments': 'All environments',
diff --git a/src/features/Projects/WorkingDirectories/EditDirectoryModal.test.ts b/src/features/Projects/WorkingDirectories/EditDirectoryModal.test.ts
new file mode 100644
index 00000000000..193da0613e4
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/EditDirectoryModal.test.ts
@@ -0,0 +1,34 @@
+import { TRPCClientError } from '@trpc/client';
+import { describe, expect, it, vi } from 'vitest';
+
+import { describeEditDirectoryError } from './EditDirectoryModal';
+
+vi.mock('i18next', () => ({ t: (key: string) => key }));
+
+const conflict = (message: string) =>
+ new TRPCClientError(message, { result: { error: { data: { code: 'CONFLICT' } } } } as never);
+
+describe('describeEditDirectoryError', () => {
+ it('asks the user to wait only when a topic is running', () => {
+ const error = conflict('Wait for the running topics to finish before changing this directory');
+ Object.assign(error, { data: { code: 'CONFLICT' } });
+
+ expect(describeEditDirectoryError(error)).toBe('settings.editDirectoryBusy');
+ });
+
+ it('explains a destination owned by another environment instead of asking to wait', () => {
+ const error = conflict('This directory belongs to another environment');
+ Object.assign(error, { data: { code: 'CONFLICT' } });
+
+ expect(describeEditDirectoryError(error)).toBe('settings.editDirectoryOtherEnvironment');
+ });
+
+ it('keeps the message of any other conflict', () => {
+ const error = conflict('The topics in this directory changed; try again');
+ Object.assign(error, { data: { code: 'CONFLICT' } });
+
+ expect(describeEditDirectoryError(error)).toBe(
+ 'The topics in this directory changed; try again',
+ );
+ });
+});
diff --git a/src/features/Projects/WorkingDirectories/EditDirectoryModal.tsx b/src/features/Projects/WorkingDirectories/EditDirectoryModal.tsx
new file mode 100644
index 00000000000..6a3c97f5106
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/EditDirectoryModal.tsx
@@ -0,0 +1,132 @@
+import {
+ Alert,
+ Button,
+ createModal,
+ Flexbox,
+ Input,
+ Select,
+ Text,
+ useModalContext,
+} from '@lobehub/ui';
+import { TRPCClientError } from '@trpc/client';
+import { t } from 'i18next';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { deviceService } from '@/services/device';
+import { deviceSelectors, useDeviceStore } from '@/store/device';
+import type { ProjectDirectory } from '@/store/projectWorkingDirectory';
+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+
+/**
+ * The refusals a user can act on, in their language. `CONFLICT` covers both a
+ * running topic and a destination owned by another environment; only the
+ * first is resolved by waiting, so each keeps its own advice.
+ */
+const CONFLICT_MESSAGES = [
+ ['running topics', 'settings.editDirectoryBusy'],
+ ['another environment', 'settings.editDirectoryOtherEnvironment'],
+] as const;
+
+export const describeEditDirectoryError = (error: unknown) => {
+ if (error instanceof TRPCClientError && error.data?.code === 'CONFLICT') {
+ const key = CONFLICT_MESSAGES.find(([match]) => error.message.includes(match))?.[1];
+ if (key) return t(key, { ns: 'project' });
+ }
+ return error instanceof Error ? error.message : undefined;
+};
+
+function EditDirectoryContent({
+ directory,
+ projectId,
+}: {
+ directory: ProjectDirectory;
+ projectId: string;
+}) {
+ const { t } = useTranslation('project');
+ const deviceRequest = useDeviceStore((s) => s.useFetchDevices)(true);
+ const devices = useDeviceStore(deviceSelectors.deviceList);
+ const [deviceId, setDevice] = useState(directory.deviceId);
+ const [path, setPath] = useState(directory.path);
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState<unknown>();
+ const relocate = useProjectDirectoryStore((s) => s.relocateDirectory);
+ const { close } = useModalContext();
+ const unchanged = deviceId === directory.deviceId && path.trim() === directory.path;
+ const save = async () => {
+ setPending(true);
+ setError(undefined);
+ try {
+ const stat = await deviceService.statPath(deviceId, path.trim());
+ if (!stat?.exists || !stat.isDirectory) throw new Error(t('settings.directoryUnavailable'));
+ await relocate({ deviceId, id: directory.id, path: path.trim(), projectId });
+ close();
+ } catch (error) {
+ console.error('Failed to update project directory', error);
+ setError(error);
+ } finally {
+ setPending(false);
+ }
+ };
+ return (
+ <Flexbox gap={16}>
+ <Text type="secondary">{t('settings.editDirectoryDescription')}</Text>
+ <Text>{t('directories.device')}</Text>
+ <Select
+ aria-label={t('directories.device')}
+ disabled={pending}
+ options={devices.map((d) => ({ value: d.deviceId, label: d.friendlyName || d.deviceId }))}
+ placeholder={t('directories.device')}
+ value={deviceId}
+ onChange={(id) => {
+ setDevice(id ?? '');
+ setError(undefined);
+ }}
+ />
+ <Text>{t('directories.path')}</Text>
+ <Input
+ aria-label={t('directories.path')}
+ disabled={pending}
+ placeholder={t('directories.path')}
+ value={path}
+ onChange={(e) => {
+ setPath(e.target.value);
+ setError(undefined);
+ }}
+ />
+ {error ? (
+ <Alert
+ showIcon
+ description={describeEditDirectoryError(error)}
+ title={t('settings.editDirectoryFailed')}
+ type="error"
+ />
+ ) : null}
+ {deviceRequest.error ? (
+ <AsyncError error={deviceRequest.error} onRetry={() => deviceRequest.revalidate()} />
+ ) : null}
+ <Flexbox horizontal gap={8} justify="flex-end">
+ <Button disabled={pending} onClick={close}>
+ {t('cancel', { ns: 'common' })}
+ </Button>
+ <Button
+ disabled={!deviceId || !path.trim() || unchanged}
+ loading={pending}
+ type="primary"
+ onClick={save}
+ >
+ {t('save', { ns: 'common' })}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+}
+
+export const openEditDirectoryModal = (projectId: string, directory: ProjectDirectory) =>
+ createModal({
+ title: t('settings.editDirectory', { ns: 'project' }),
+ content: <EditDirectoryContent directory={directory} projectId={projectId} />,
+ footer: null,
+ width: 520,
+ });
diff --git a/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx b/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx
index 5dd28317e22..df71748d78f 100644
--- a/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx
+++ b/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx
@@ -1,6 +1,16 @@
import type { DeviceListItem } from '@lobechat/types';
-import { Block, Button, cssVar, Flexbox, Icon, Select, Text } from '@lobehub/ui';
-import { FolderIcon, MessageSquarePlusIcon, PlusIcon } from 'lucide-react';
+import {
+ ActionIcon,
+ Button,
+ confirmModal,
+ cssVar,
+ Flexbox,
+ Icon,
+ Select,
+ Text,
+ toast,
+} from '@lobehub/ui';
+import { FolderIcon, LinkIcon, PencilIcon, PlusIcon, Trash2Icon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router';
@@ -9,6 +19,7 @@ import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { deviceSelectors, useDeviceStore } from '@/store/device';
import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
+import type { ProjectDirectory } from '@/store/projectWorkingDirectory';
import {
useProjectDirectories,
useProjectDirectoryStore,
@@ -17,7 +28,7 @@ import {
import { openAddDirectoryModal } from './AddDirectoryModal';
import { openBindDirectoryModal } from './BindDirectoryModal';
-import { useStartDirectoryConversation } from './useStartProjectTopic';
+import { openEditDirectoryModal } from './EditDirectoryModal';
/**
* A device row restored from the persisted list (`onlineUnknown`) has not been
@@ -40,10 +51,6 @@ export function WorkingDirectorySettings({ projectId }: { projectId: string }) {
const environmentId = params.get('environment') ?? '';
useProjectStore((s) => s.useFetchProjectDetail)(projectId);
const project = useCurrentProjectDetail(projectId);
- const startConversation = useStartDirectoryConversation(
- projectId,
- project?.project.coordinatorAgentId,
- );
const environmentsRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);
const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);
const environments = useProjectEnvironments(projectId);
@@ -53,13 +60,34 @@ export function WorkingDirectorySettings({ projectId }: { projectId: string }) {
const isDeviceListLoaded = useDeviceStore(deviceSelectors.isDeviceListLoaded);
const items = directories.filter((d) => !environmentId || d.environmentId === environmentId);
const error = environmentsRequest.error || directoriesRequest.error || deviceRequest.error;
+ const removeDirectory = useProjectDirectoryStore((s) => s.removeDirectory);
+ const canManage = project?.permissions?.canManage ?? false;
+ const remove = (directory: ProjectDirectory) =>
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('settings.removeDirectoryConfirmDescription', {
+ device: directory.deviceName || directory.deviceId,
+ path: directory.path,
+ }),
+ okButtonProps: { danger: true },
+ okText: t('settings.removeDirectory'),
+ onOk: async () => {
+ try {
+ await removeDirectory(projectId, directory.id);
+ } catch (error) {
+ console.error('Failed to remove project directory', error);
+ toast.error(t('settings.removeDirectoryFailed'));
+ }
+ },
+ title: t('settings.removeDirectoryConfirmTitle', { name: directory.name }),
+ });
return (
<Flexbox gap={20}>
<Flexbox gap={6}>
<Text fontSize={16} weight={600}>
{t('settings.workLocations')}
</Text>
- <Text type="secondary">{t('settings.directoryDescription')}</Text>
+ <Text type="secondary">{t('settings.directoryListDescription')}</Text>
</Flexbox>
<Flexbox horizontal gap={12} justify="space-between">
<Select
@@ -109,24 +137,21 @@ export function WorkingDirectorySettings({ projectId }: { projectId: string }) {
)}
</Flexbox>
) : (
- <Block padding={0} variant="outlined">
+ <Flexbox>
{items.map((directory, index) => (
<Flexbox
key={directory.id}
- padding={16}
+ paddingBlock={12}
style={index ? { borderTop: `1px solid ${cssVar.colorBorderSecondary}` } : undefined}
>
<Flexbox horizontal align="center" gap={16} justify="space-between">
<Flexbox flex={1} gap={6} style={{ minWidth: 0 }}>
<Flexbox horizontal align="center" gap={8}>
<Icon icon={FolderIcon} size={18} />
- <Text weight={500}>
- {directory.path.split(/[\\/]/).findLast(Boolean) || directory.name}
+ <Text style={{ overflowWrap: 'anywhere' }} weight={500}>
+ {directory.path}
</Text>
</Flexbox>
- <Text fontSize={12} style={{ overflowWrap: 'anywhere' }} type="secondary">
- {directory.path}
- </Text>
<Flexbox horizontal align="center" gap={8} wrap="wrap">
{getDeviceIcon(
devices.find((d) => d.deviceId === directory.deviceId)?.platform,
@@ -136,35 +161,46 @@ export function WorkingDirectorySettings({ projectId }: { projectId: string }) {
<DevicePresence
device={devices.find((d) => d.deviceId === directory.deviceId)}
/>
- <Text fontSize={12} type="secondary">
- · {directory.environmentName || t('directories.noEnvironment')}
- </Text>
</Flexbox>
</Flexbox>
- <Button
- disabled={Boolean(directory.instanceId) && !project?.project.coordinatorAgentId}
- icon={MessageSquarePlusIcon}
- size="small"
- onClick={() =>
- !directory.instanceId
- ? openBindDirectoryModal({
+ <Flexbox horizontal align="center" gap={8}>
+ {/* A legacy row has no environment yet, so linking it is still its next step. */}
+ {!directory.instanceId && (
+ <Button
+ icon={LinkIcon}
+ size="small"
+ onClick={() =>
+ openBindDirectoryModal({
projectId,
deviceId: directory.deviceId,
path: directory.path,
})
- : startConversation(directory)
- }
- >
- {t(
- directory.instanceId
- ? 'settings.startDirectoryConversation'
- : 'directories.bind',
+ }
+ >
+ {t('directories.bind')}
+ </Button>
+ )}
+ {canManage && (
+ <ActionIcon
+ icon={PencilIcon}
+ size="small"
+ title={t('settings.editDirectory')}
+ onClick={() => openEditDirectoryModal(projectId, directory)}
+ />
)}
- </Button>
+ {canManage && (
+ <ActionIcon
+ icon={Trash2Icon}
+ size="small"
+ title={t('settings.removeDirectory')}
+ onClick={() => remove(directory)}
+ />
+ )}
+ </Flexbox>
</Flexbox>
</Flexbox>
))}
- </Block>
+ </Flexbox>
)}
</Flexbox>
);
diff --git a/src/services/projectWorkingDirectory.ts b/src/services/projectWorkingDirectory.ts
index ca66844fb05..065a6102240 100644
--- a/src/services/projectWorkingDirectory.ts
+++ b/src/services/projectWorkingDirectory.ts
@@ -31,6 +31,10 @@ class ProjectWorkingDirectoryService {
};
moveTopic = (input: Parameters<Client['moveTopic']['mutate']>[0]) =>
lambdaClient.projectWorkingDirectory.moveTopic.mutate(input);
+ relocate = (input: Parameters<Client['relocate']['mutate']>[0]) =>
+ lambdaClient.projectWorkingDirectory.relocate.mutate(input);
+ remove = (input: Parameters<Client['remove']['mutate']>[0]) =>
+ lambdaClient.projectWorkingDirectory.remove.mutate(input);
resolve = (id: string) => lambdaClient.projectWorkingDirectory.resolve.query({ id });
startTopic = (input: Parameters<Client['startTopic']['mutate']>[0]) =>
lambdaClient.projectWorkingDirectory.startTopic.mutate(input);
diff --git a/src/store/projectWorkingDirectory/index.test.ts b/src/store/projectWorkingDirectory/index.test.ts
index a2de619e2fa..8f64eef94c0 100644
--- a/src/store/projectWorkingDirectory/index.test.ts
+++ b/src/store/projectWorkingDirectory/index.test.ts
@@ -45,6 +45,45 @@ const invalidates = (name: string, entryKey: string) =>
);
describe('projectWorkingDirectory store', () => {
+ describe('relocateDirectory', () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it('relocates through the service and refreshes the project listings', async () => {
+ const relocate = vi
+ .spyOn(projectWorkingDirectoryService, 'relocate')
+ .mockResolvedValue({ data: { id: 'directory-2' }, success: true } as never);
+ const input = { deviceId: 'device-2', id: 'directory-1', path: '/work', projectId: 'p-1' };
+
+ await useProjectDirectoryStore.getState().relocateDirectory(input);
+
+ expect(relocate).toHaveBeenCalledWith(input);
+ expect(invalidates('projectTopics', 'p-1')).toBe(true);
+ });
+ });
+
+ describe('removeDirectory', () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it('removes through the service and refreshes the project listings', async () => {
+ const remove = vi
+ .spyOn(projectWorkingDirectoryService, 'remove')
+ .mockResolvedValue({ data: {}, success: true } as never);
+
+ await useProjectDirectoryStore.getState().removeDirectory('project-1', 'directory-1');
+
+ expect(remove).toHaveBeenCalledWith({ id: 'directory-1', projectId: 'project-1' });
+ expect(invalidates('projectTopics', 'project-1')).toBe(true);
+ });
+
+ it('rejects so the caller can report a refused removal', async () => {
+ vi.spyOn(projectWorkingDirectoryService, 'remove').mockRejectedValue(new Error('conflict'));
+
+ await expect(
+ useProjectDirectoryStore.getState().removeDirectory('project-1', 'directory-1'),
+ ).rejects.toThrow('conflict');
+ });
+ });
+
describe('useFetchProjectTopics polling', () => {
afterEach(() => {
vi.restoreAllMocks();
diff --git a/src/store/projectWorkingDirectory/index.ts b/src/store/projectWorkingDirectory/index.ts
index 51223d0dc34..b968b046c38 100644
--- a/src/store/projectWorkingDirectory/index.ts
+++ b/src/store/projectWorkingDirectory/index.ts
@@ -103,6 +103,10 @@ interface ProjectDirectoryStore extends ProjectDirectoryStoreState {
moveTopic: (...args: ServiceParams<'moveTopic'>) => Promise<ServiceData<'moveTopic'>>;
/** Refetch a project's conversations after a change made elsewhere, e.g. a new main agent. */
refreshProjectTopics: (projectId: string) => Promise<void>;
+ /** Repoint a directory at another device location; its conversations follow it. */
+ relocateDirectory: (...args: ServiceParams<'relocate'>) => Promise<ServiceData<'relocate'>>;
+ /** Remove a directory from a project; its conversations stay in the project. */
+ removeDirectory: (projectId: string, id: string) => Promise<void>;
/** Create or rename an environment. */
saveEnvironment: (
...args: ServiceParams<'saveEnvironment'>
@@ -232,6 +236,31 @@ export const useProjectDirectoryStore: UseBoundStoreWithEqualityFn<
environmentTopics.revalidate(),
]);
},
+ relocateDirectory: async (input) => {
+ const result = await projectWorkingDirectoryService.relocate(input);
+ await Promise.all([
+ directories.revalidate(ALL_PROJECTS_KEY),
+ directories.revalidate(input.projectId),
+ // The directory's conversations now point at the new location.
+ projectTopics.revalidate(input.projectId),
+ directoryTopics.revalidate(),
+ environmentTopics.revalidate(),
+ environments.revalidate(),
+ environments.revalidate(input.projectId),
+ ]);
+ return result.data;
+ },
+ removeDirectory: async (projectId, id) => {
+ await projectWorkingDirectoryService.remove({ id, projectId });
+ await Promise.all([
+ directories.revalidate(ALL_PROJECTS_KEY),
+ directories.revalidate(projectId),
+ // The removal cleared the directory binding on its conversations.
+ projectTopics.revalidate(projectId),
+ directoryTopics.revalidate(id),
+ environmentTopics.revalidate(),
+ ]);
+ },
saveEnvironment: async (input) => {
const result = await projectWorkingDirectoryService.saveEnvironment(input);
// One environment is shared by every project that lists it, and its name