Skip to content

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

🐛 fix(project): let a project topic switch devices within its project directories (#20753)

Arvin Xu584c48b7adde
diff --git a/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.moveTopic.test.ts b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.moveTopic.test.ts
new file mode 100644
index 00000000000..7a6ea1ef008
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.moveTopic.test.ts
@@ -0,0 +1,86 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ assertCanUseTopicTargets: vi.fn(),
+ moveTopic: 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 { resolve: mocks.resolve };
+ }),
+}));
+
+vi.mock('@/database/repositories/projectDirectory', () => ({
+ ProjectDirectoryRepository: vi.fn(function () {
+ return { moveTopic: mocks.moveTopic };
+ }),
+}));
+
+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 = { directoryId: '00000000-0000-4000-8000-000000000002', topicId: 'topic-1' };
+
+describe('projectWorkingDirectory.moveTopic', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.resolve.mockResolvedValue({ deviceId: 'device-b', path: '/work/repo-b' });
+ mocks.moveTopic.mockResolvedValue({ id: 'topic-1' });
+ });
+
+ it('moves the topic once the destination directory is reachable on its device', async () => {
+ mocks.statPath.mockResolvedValue({ exists: true, isDirectory: true });
+
+ await expect(caller().moveTopic(input)).resolves.toMatchObject({ success: true });
+
+ expect(mocks.statPath).toHaveBeenCalledWith({
+ deviceId: 'device-b',
+ path: '/work/repo-b',
+ userId: 'user-1',
+ workspaceId: undefined,
+ });
+ expect(mocks.moveTopic).toHaveBeenCalledWith('topic-1', input.directoryId);
+ });
+
+ it('keeps the existing binding when the destination is unavailable', async () => {
+ // The device is online but the directory was removed: moving anyway would
+ // drop the session that only holds on the old machine.
+ mocks.statPath.mockResolvedValue({ exists: false, isDirectory: false });
+
+ await expect(caller().moveTopic(input)).rejects.toThrow(
+ 'Device is offline or working directory is unavailable',
+ );
+ expect(mocks.moveTopic).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/projectWorkingDirectory.ts b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
index 1a269c217b9..ec81c7fa6ac 100644
--- a/apps/server/src/routers/lambda/projectWorkingDirectory.ts
+++ b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
@@ -24,6 +24,7 @@ import {
assertCanUseTopicTargets,
assertCanViewTopicTargets,
} from './_helpers/conversationResourceGuard';
+import { assertCreatorTopicTargets } from './_helpers/shareVisitorTargetGuard';
const procedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { serverDB, userId, workspaceId } = opts.ctx;
@@ -176,6 +177,41 @@ export const projectWorkingDirectoryRouter = router({
);
return { data, success: true };
}),
+ /** Switch a project-directory conversation to its project's directory on another device. */
+ moveTopic: procedure
+ .use(withScopedPermission('topic:update'))
+ .input(z.object({ directoryId: z.string().uuid(), topicId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ await assertCanUseTopicTargets(
+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ [input.topicId],
+ );
+ // Same visitor guard as `updateTopicMetadata`: a share-visitor topic is not
+ // the member's conversation to move.
+ await assertCreatorTopicTargets(
+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ [input.topicId],
+ );
+ // Same reachability gate as `startTopic`: the move drops the session that
+ // only holds on the old machine, so a destination the device cannot see
+ // must fail here, while the existing binding and session are still intact.
+ const directory = await ctx.directoryModel.resolve(input.directoryId);
+ const stat = await deviceGateway.statPath({
+ deviceId: directory.deviceId,
+ path: directory.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',
+ });
+ return {
+ data: await ctx.directoryRepo.moveTopic(input.topicId, input.directoryId),
+ success: true,
+ };
+ }),
resolve: procedure.input(idInput).query(async ({ ctx, input }) => ({
data: await ctx.directoryModel.resolve(input.id),
success: true,
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
index 8d4a12a70bd..352782d1d60 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
@@ -711,30 +711,27 @@ describe('AiAgentService.execAgent - device auto-activation', () => {
});
describe('project directory binding', () => {
- it('rejects a project topic whose directory binding was deleted instead of following its pinned device', async () => {
+ it('keeps a project topic without a directory on the device it already ran on', async () => {
mockDeviceProxy.isConfigured = true;
- mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
- // Deleting the directory row nulls the FK but keeps projectId + the pinned device.
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice, onlineDevice2]);
+ // Started outside any directory: the first run stamped its device.
topicMock.findById.mockResolvedValue({
id: 'topic-1',
- metadata: { boundDeviceId: 'device-001', workingDirectory: '/repo' },
+ metadata: { boundDeviceId: 'device-002', workingDirectory: '/repo' },
projectId: 'project-1',
projectWorkingDirectoryId: null,
});
- mockResolveProjectDirectoryForTopic.mockRejectedValueOnce(
- new Error('Project directory binding no longer exists'),
- );
+ // The agent default points elsewhere; the conversation's pin must win.
+ await useAgencyConfig({ boundDeviceId: 'device-001', executionTarget: 'device' });
- await expect(
- service.execAgent({
- agentId: 'agent-1',
- prompt: 'Keep working',
- appContext: { topicId: 'topic-1' },
- }),
- ).rejects.toThrow('Project directory binding no longer exists');
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Keep working',
+ appContext: { topicId: 'topic-1' },
+ });
- expect(mockResolveProjectDirectoryForTopic).toHaveBeenCalledWith('topic-1');
- expect(mockCreateOperation).not.toHaveBeenCalled();
+ expect(mockResolveProjectDirectoryForTopic).not.toHaveBeenCalled();
+ expect(mockCreateOperation.mock.calls[0][0].activeDeviceId).toBe('device-002');
});
it('does not consult the project resolver for plain device-bound topics', async () => {
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index fb144b7a56e..3c1d792ec77 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -604,15 +604,9 @@ export const setupTurn = async (
// (config source of truth), NOT in metadata.
const existingTopic = await deps.topicModel.findById(topicId);
topicEditingGroupId = existingTopic?.metadata?.editingGroupId ?? undefined;
- // Deleting a project directory nulls the FK but leaves `projectId` and the
- // pinned device on the topic; route that signature through the resolver
- // too so it rejects the stale binding instead of falling through to the
- // plain topic-pinned device path below.
- const hasStaleProjectBinding =
- !existingTopic?.projectWorkingDirectoryId &&
- !!existingTopic?.projectId &&
- !!existingTopic?.metadata?.boundDeviceId;
- if (existingTopic?.projectWorkingDirectoryId || hasStaleProjectBinding) {
+ // A project conversation without a directory follows the plain
+ // topic-pinned device path below, like any other conversation.
+ if (existingTopic?.projectWorkingDirectoryId) {
if (shareGate || (botContext && !resolveDeviceAccessPolicy({ botContext }).canUseDevice))
throw new Error('Project directory access denied');
const directory = await new ProjectWorkingDirectoryModel(
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 270dc6001ca..d546b7814e9 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1265,11 +1265,13 @@
"heteroAgent.executionTarget.onlineConnections_one": "Online · {{count}} connection",
"heteroAgent.executionTarget.onlineConnections_other": "Online · {{count}} connections",
"heteroAgent.executionTarget.personalGroup": "Private Devices",
+ "heteroAgent.executionTarget.projectDevicesHint": "Only devices with this project's working directory are listed. Add a directory for another device in the project settings.",
"heteroAgent.executionTarget.reconnect": "Reconnect",
"heteroAgent.executionTarget.reconnectFailed": "Could not reconnect this device. Make sure the desktop app is running, then try again.",
"heteroAgent.executionTarget.sandbox": "Cloud Sandbox",
"heteroAgent.executionTarget.sandboxDesc": "Runs in the cloud, no machine needed",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} currently runs only on a local or connected device",
+ "heteroAgent.executionTarget.switchProjectTopic.content": "This topic will run in the project directory \"{{directory}}\" on {{device}}. Its next turn starts a fresh session there.",
"heteroAgent.executionTarget.switchTopic.content": "This topic has been running on {{name}}, where its working directory and agent session are kept. After switching, its next turn starts a fresh session in the new environment. New topics will use this choice too.",
"heteroAgent.executionTarget.switchTopic.ok": "Switch",
"heteroAgent.executionTarget.switchTopic.title": "Move this topic to another environment?",
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index 05b55db4d3a..9a6ce7aae5f 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -48,6 +48,7 @@
"directories.bindDescription": "Link the folder below to a project so you can continue working from that project. Files stay on the current device.",
"directories.bindFailed": "Could not link directory",
"directories.boundRoot": "This conversation is bound to a project directory. Start a new conversation to use a different directory.",
+ "directories.boundTip": "This directory belongs to the project ({{path}}). Switch devices to use the project's directory on another device.",
"directories.chooseAgent": "Choose Agent",
"directories.conversations": "Conversations",
"directories.coordinator": "Project coordinator",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 0c52731c536..88365502a51 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1265,11 +1265,13 @@
"heteroAgent.executionTarget.onlineConnections_one": "在线 · {{count}} 个连接",
"heteroAgent.executionTarget.onlineConnections_other": "在线 · {{count}} 个连接",
"heteroAgent.executionTarget.personalGroup": "私人设备",
+ "heteroAgent.executionTarget.projectDevicesHint": "仅列出已绑定此项目工作目录的设备。其他设备可在项目设置中添加目录。",
"heteroAgent.executionTarget.reconnect": "重新连接",
"heteroAgent.executionTarget.reconnectFailed": "无法重新连接此设备。请确认桌面端正在运行,然后重试。",
"heteroAgent.executionTarget.sandbox": "云端沙箱",
"heteroAgent.executionTarget.sandboxDesc": "云端运行,不占用机器",
"heteroAgent.executionTarget.sandboxUnsupported": "{{name}} 目前仅支持在本地设备或已连接设备上运行",
+ "heteroAgent.executionTarget.switchProjectTopic.content": "本话题将改到「{{device}}」上的项目目录「{{directory}}」运行,下一轮会在那里开启新会话。",
"heteroAgent.executionTarget.switchTopic.content": "本话题一直在「{{name}}」上运行,工作目录和会话都保存在那里。切换后,下一轮会在新环境中开启新会话;之后的新话题也会使用这个选择。",
"heteroAgent.executionTarget.switchTopic.ok": "切换",
"heteroAgent.executionTarget.switchTopic.title": "将本话题切换到其他执行环境?",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index 1b852615d3e..eb641efcc1e 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -48,6 +48,7 @@
"directories.bindDescription": "将下方文件夹绑定到项目,之后即可从项目中继续工作。文件仍保留在当前设备上。",
"directories.bindFailed": "目录关联失败",
"directories.boundRoot": "此对话已绑定项目工作目录。要使用其他目录,请新建对话。",
+ "directories.boundTip": "该目录属于项目({{path}})。切换设备即可改用该设备上的项目目录。",
"directories.chooseAgent": "选择 Agent",
"directories.conversations": "已有话题",
"directories.coordinator": "项目协调 Agent",
diff --git a/packages/database/src/models/__tests__/projectWorkingDirectory.test.ts b/packages/database/src/models/__tests__/projectWorkingDirectory.test.ts
index 2d3997bacb4..fd9188c894c 100644
--- a/packages/database/src/models/__tests__/projectWorkingDirectory.test.ts
+++ b/packages/database/src/models/__tests__/projectWorkingDirectory.test.ts
@@ -203,7 +203,7 @@ describe('resolveForTopic', () => {
});
});
- it('blocks disabled environments and a removed directory instead of falling back', async () => {
+ it('blocks a disabled environment instead of falling back', async () => {
const directory = await repo.bind(base);
const topic = await createPinnedTopic(directory);
const row = await model.resolve(directory.id);
@@ -212,10 +212,16 @@ describe('resolveForTopic', () => {
.set({ enabled: false })
.where(eq(environments.id, row.environmentId));
await expect(model.resolveForTopic(topic.id)).rejects.toThrow('disabled');
- await db
- .delete(projectWorkingDirectories)
- .where(eq(projectWorkingDirectories.id, directory.id));
- await expect(model.resolveForTopic(topic.id)).rejects.toThrow('no longer exists');
+ });
+
+ it('leaves project conversations without a directory to the device-resolution path', async () => {
+ const topic = await new TopicModel(db, userId).create({
+ agentId: 'directory-agent',
+ metadata: { boundDeviceId: base.deviceId, workingDirectory: base.path },
+ projectId: base.projectId,
+ title: 'Project chat',
+ });
+ expect(await model.resolveForTopic(topic.id)).toBeUndefined();
});
it('returns nothing for conversations without a project pin', async () => {
diff --git a/packages/database/src/models/projectWorkingDirectory.ts b/packages/database/src/models/projectWorkingDirectory.ts
index 181f5b19267..7408d203d54 100644
--- a/packages/database/src/models/projectWorkingDirectory.ts
+++ b/packages/database/src/models/projectWorkingDirectory.ts
@@ -212,14 +212,10 @@ export class ProjectWorkingDirectoryModel {
.select()
.from(topics)
.where(and(eq(topics.id, topicId), buildWorkspaceWhere(this.scope(), topics)));
- if (!topic?.projectWorkingDirectoryId) {
- // The binding row is gone (directory deletion sets the FK null) but the
- // topic still carries its project pin. Plain device-bound topics have no
- // projectId and simply follow the normal device-resolution path.
- if (topic?.projectId && topic?.metadata?.boundDeviceId)
- throw new Error('Project directory binding no longer exists');
- return;
- }
+ // A project conversation without a directory (started outside one, or
+ // associated to the project alone) is device-bound like any other and
+ // follows the normal device-resolution path.
+ if (!topic?.projectWorkingDirectoryId) return;
if (!topic.projectId) throw new Error('Project directory has no owning project');
const directory = await this.resolve(topic.projectWorkingDirectoryId, topic.projectId);
const source = getWorkingDirSourcePath(
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index 4361d369183..aa49366efa5 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -84,6 +84,21 @@ type TopicMetadataPatch = Omit<Partial<ChatTopicMetadata>, 'onboardingSession'>
*/
const LAST_MESSAGE_PREVIEW_LENGTH = 2000;
const TASK_CALLBACK_RESERVATION_TTL_MS = 5 * 60 * 1000;
+
+/**
+ * Whether a turn start currently holds the topic's short start reservation.
+ * A writer that changes where the topic runs must respect it as it would a
+ * `runningOperation`: the reserving turn may already have resolved its target.
+ */
+export const hasLiveTaskCallbackReservation = (
+ metadata: Pick<ChatTopicMetadata, 'taskCallbackReservation'> | null | undefined,
+ now = Date.now(),
+): boolean => {
+ const reservation = metadata?.taskCallbackReservation;
+ if (!reservation) return false;
+ const reservedAt = Date.parse(reservation.reservedAt);
+ return Number.isFinite(reservedAt) && now - reservedAt < TASK_CALLBACK_RESERVATION_TTL_MS;
+};
/**
* How long an operation that still claims `running` / `idle` may hold the topic
* against a background start before it is treated as abandoned.
@@ -2658,11 +2673,7 @@ export class TopicModel {
if (!existing) return null;
const reservation = existing.metadata?.taskCallbackReservation;
- const reservedAt = reservation ? Date.parse(reservation.reservedAt) : 0;
- const hasLiveReservation =
- reservation &&
- Number.isFinite(reservedAt) &&
- Date.now() - reservedAt < TASK_CALLBACK_RESERVATION_TTL_MS;
+ const hasLiveReservation = hasLiveTaskCallbackReservation(existing.metadata);
if (
reservation?.messageId === messageId &&
@@ -2737,11 +2748,7 @@ export class TopicModel {
const current = existing.metadata?.runningOperation;
const reservation = existing.metadata?.taskCallbackReservation;
- const reservedAt = reservation ? Date.parse(reservation.reservedAt) : 0;
- const hasLiveReservation =
- !!reservation &&
- Number.isFinite(reservedAt) &&
- Date.now() - reservedAt < TASK_CALLBACK_RESERVATION_TTL_MS;
+ const hasLiveReservation = hasLiveTaskCallbackReservation(existing.metadata);
const ownsCurrent =
!current ||
current.operationId === params.sourceOperationId ||
diff --git a/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts b/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts
index 1b61127e606..154e0b0cf4c 100644
--- a/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts
+++ b/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts
@@ -5,6 +5,7 @@ import { getTestDB } from '../../../core/getTestDB';
import { EnvironmentModel } from '../../../models/environment';
import { ProjectModel } from '../../../models/project';
import { ProjectWorkingDirectoryModel } from '../../../models/projectWorkingDirectory';
+import { TopicModel } from '../../../models/topic';
import {
agents,
devices,
@@ -15,6 +16,7 @@ import {
projectWorkingDirectories,
topics,
users,
+ workspaces,
} from '../../../schemas';
import { ProjectDirectoryRepository } from '../index';
@@ -300,3 +302,155 @@ describe('ProjectDirectoryRepository.associateTopic', () => {
});
});
});
+
+describe('ProjectDirectoryRepository.moveTopic', () => {
+ const second = { ...base, deviceId: 'second-device', path: '/work/second' };
+ const pinnedTopic = async (directoryId: string) => {
+ await db.insert(topics).values({
+ id: 'to-move',
+ agentId: 'repo-agent',
+ metadata: {
+ boundDeviceId: base.deviceId,
+ heteroSessionId: 'old-session',
+ workingDirectory: base.path,
+ workingDirectoryConfig: { path: base.path },
+ },
+ projectId: base.projectId,
+ projectWorkingDirectoryId: directoryId,
+ userId,
+ });
+ };
+ beforeEach(async () => {
+ await db
+ .insert(devices)
+ .values({ deviceId: second.deviceId, identitySource: 'fallback', platform: 'linux', userId });
+ });
+
+ it("moves a conversation to its project's directory on another device", async () => {
+ const first = await repo.bind(base);
+ const target = await repo.bind(second);
+ await pinnedTopic(first.id);
+ await repo.moveTopic('to-move', target.id);
+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'to-move'));
+ expect(topic.projectWorkingDirectoryId).toBe(target.id);
+ expect(topic.metadata).toMatchObject({
+ boundDeviceId: second.deviceId,
+ workingDirectory: second.path,
+ workingDirectoryConfig: { path: second.path },
+ });
+ // The CLI session lives on the old machine and cannot follow the move.
+ expect(topic.metadata?.heteroSessionId).toBeUndefined();
+ });
+
+ it("refuses another project's directory and running conversations", async () => {
+ const first = await repo.bind(base);
+ await db.insert(agents).values({ id: 'other-coordinator', userId });
+ await db.insert(projects).values({
+ coordinatorAgentId: 'other-coordinator',
+ id: 'other-project',
+ identifier: 'OTH',
+ name: 'Other project',
+ userId,
+ });
+ const foreign = await repo.bind({ ...second, projectId: 'other-project' });
+ await pinnedTopic(first.id);
+ await expect(repo.moveTopic('to-move', foreign.id)).rejects.toThrow();
+ await db.update(topics).set({ status: 'running' }).where(eq(topics.id, 'to-move'));
+ const target = await repo.bind(second);
+ await expect(repo.moveTopic('to-move', target.id)).rejects.toThrow('running');
+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'to-move'));
+ expect(topic.projectWorkingDirectoryId).toBe(first.id);
+ });
+
+ it('refuses to move a topic while a turn holds its start reservation', async () => {
+ const first = await repo.bind(base);
+ const target = await repo.bind(second);
+ await pinnedTopic(first.id);
+ // A start reserved the topic but has not published `runningOperation` yet.
+ await new TopicModel(db, userId).updateMetadata('to-move', {
+ taskCallbackReservation: { messageId: 'msg-1', reservedAt: new Date().toISOString() },
+ });
+ await expect(repo.moveTopic('to-move', target.id)).rejects.toThrow('running');
+
+ // An expired reservation is abandoned and no longer holds the topic.
+ await new TopicModel(db, userId).updateMetadata('to-move', {
+ taskCallbackReservation: {
+ messageId: 'msg-1',
+ reservedAt: new Date(Date.now() - 10 * 60 * 1000).toISOString(),
+ },
+ });
+ await repo.moveTopic('to-move', target.id);
+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'to-move'));
+ expect(topic.projectWorkingDirectoryId).toBe(target.id);
+ });
+
+ it('lets another workspace member move a shared topic they did not create', async () => {
+ const workspaceId = 'move-topic-ws';
+ await db.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Move topic workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ await db.insert(agents).values({ id: 'ws-coordinator', userId, workspaceId });
+ await db.insert(projects).values({
+ coordinatorAgentId: 'ws-coordinator',
+ id: 'ws-project',
+ identifier: 'WSP',
+ name: 'Workspace project',
+ userId,
+ workspaceId,
+ });
+ await db.insert(devices).values([
+ // Workspace devices: the shared pool every member can run on.
+ {
+ deviceId: 'ws-device-a',
+ identitySource: 'fallback',
+ platform: 'linux',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ },
+ {
+ deviceId: 'ws-device-b',
+ identitySource: 'fallback',
+ platform: 'linux',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ },
+ ]);
+ const creatorRepo = new ProjectDirectoryRepository(db, userId, workspaceId);
+ const memberRepo = new ProjectDirectoryRepository(db, otherUserId, workspaceId);
+ const wsBase = { name: 'Repo', projectId: 'ws-project' };
+ const first = await creatorRepo.bind({ ...wsBase, deviceId: 'ws-device-a', path: '/ws/a' });
+ const target = await creatorRepo.bind({ ...wsBase, deviceId: 'ws-device-b', path: '/ws/b' });
+ // Environments start private; a member reaches the project's directories
+ // only once it is shared with the workspace.
+ await db.update(environments).set({ visibility: 'public' });
+ // Started by the creator; `topics.userId` records them, not an owner.
+ await db.insert(topics).values({
+ id: 'ws-topic',
+ metadata: { boundDeviceId: 'ws-device-a', workingDirectory: '/ws/a' },
+ projectId: 'ws-project',
+ projectWorkingDirectoryId: first.id,
+ userId,
+ workspaceId,
+ });
+ await memberRepo.moveTopic('ws-topic', target.id);
+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'ws-topic'));
+ expect(topic).toMatchObject({
+ metadata: { boundDeviceId: 'ws-device-b', workingDirectory: '/ws/b' },
+ projectWorkingDirectoryId: target.id,
+ userId,
+ });
+ });
+
+ it('only moves conversations that run in a project directory', async () => {
+ const target = await repo.bind(second);
+ await db.insert(topics).values({ id: 'plain', agentId: 'repo-agent', userId });
+ await expect(repo.moveTopic('plain', target.id)).rejects.toThrow(
+ 'not bound to a project directory',
+ );
+ });
+});
diff --git a/packages/database/src/repositories/projectDirectory/index.ts b/packages/database/src/repositories/projectDirectory/index.ts
index 7c205c6a763..1e89e625b49 100644
--- a/packages/database/src/repositories/projectDirectory/index.ts
+++ b/packages/database/src/repositories/projectDirectory/index.ts
@@ -8,6 +8,7 @@ import {
normalizeProjectDirectory,
ProjectWorkingDirectoryModel,
} from '../../models/projectWorkingDirectory';
+import { hasLiveTaskCallbackReservation } from '../../models/topic';
import { agents, devices, projectEnvironments, topics } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { buildWorkspaceWhere } from '../../utils/workspace';
@@ -266,4 +267,83 @@ export class ProjectDirectoryRepository {
return updated;
});
}
+ /**
+ * Move a project-directory conversation to its project's directory on another
+ * device. The directory belongs to the project, so switching devices means
+ * switching to that project's directory there — never to an arbitrary path.
+ * The cwd and CLI session only hold on the old machine, so they go with it.
+ */
+ async moveTopic(topicId: string, directoryId: string) {
+ return this.db.transaction(async (tx) => {
+ const db = tx as LobeChatDatabase;
+ const [topic] = await db
+ .select()
+ .from(topics)
+ .where(
+ // Workspace-scoped, not creator-scoped: `topics.userId` only records
+ // who started a shared topic, and any member the router authorized to
+ // use it may move it.
+ and(
+ eq(topics.id, topicId),
+ buildWorkspaceWhere(this.scope(), topics),
+ isNull(topics.deletedAt),
+ ),
+ )
+ .for('update');
+ if (!topic) throw new Error('Topic not found or access denied');
+ if (!topic.projectId || !topic.projectWorkingDirectoryId)
+ throw new Error('Topic is not bound to a project directory');
+ // A start that holds the reservation may already have resolved the old
+ // directory; moving under it would run the turn on the old machine while
+ // the topic is persisted as bound to the new one. The row lock above
+ // serializes with the reservation write.
+ if (
+ topic.status === 'running' ||
+ topic.metadata?.runningOperation ||
+ hasLiveTaskCallbackReservation(topic.metadata)
+ )
+ throw new Error('Wait for the running topic to finish before moving it');
+ // Scoped to the topic's own project: another project's directory is not
+ // a device switch, it is a different conversation context.
+ const directory = await new ProjectWorkingDirectoryModel(
+ db,
+ this.userId,
+ this.workspaceId,
+ ).resolve(directoryId, topic.projectId);
+ if (directory.id === topic.projectWorkingDirectoryId) return topic;
+ if (topic.agentId) {
+ const [agent] = await db
+ .select()
+ .from(agents)
+ .where(and(eq(agents.id, topic.agentId), buildWorkspaceWhere(this.scope(), agents)));
+ if (
+ !agent ||
+ (agent.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
+ agent.agencyConfig.boundDeviceId !== directory.deviceId)
+ )
+ throw new Error('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 },
+ },
+ projectWorkingDirectoryId: directory.id,
+ })
+ .where(eq(topics.id, topicId))
+ .returning();
+ return updated;
+ });
+ }
}
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 3d6765b2332..5a2307240be 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -718,6 +718,10 @@ export default {
'heteroAgent.executionTarget.online': 'Online',
'heteroAgent.executionTarget.onlineConnections_one': 'Online · {{count}} connection',
'heteroAgent.executionTarget.onlineConnections_other': 'Online · {{count}} connections',
+ 'heteroAgent.executionTarget.projectDevicesHint':
+ "Only devices with this project's working directory are listed. Add a directory for another device in the project settings.",
+ 'heteroAgent.executionTarget.switchProjectTopic.content':
+ 'This topic will run in the project directory "{{directory}}" on {{device}}. Its next turn starts a fresh session there.',
'heteroAgent.executionTarget.reconnect': 'Reconnect',
'heteroAgent.executionTarget.reconnectFailed':
'Could not reconnect this device. Make sure the desktop app is running, then try again.',
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index d04af2057d5..1a3c2c5cffe 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -82,6 +82,8 @@ export default {
'directories.environment': 'Environment',
'directories.newEnvironment': 'Create environment',
+ 'directories.boundTip':
+ "This directory belongs to the project ({{path}}). Switch devices to use the project's directory on another device.",
'directories.boundRoot':
'This conversation is bound to a project directory. Start a new conversation to use a different directory.',
'directories.detectRepository': 'Detect GitHub repository',
diff --git a/src/features/ChatInput/ControlBar/DeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/DeviceSwitcher.tsx
new file mode 100644
index 00000000000..6219c6b95da
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/DeviceSwitcher.tsx
@@ -0,0 +1,28 @@
+'use client';
+
+import HeteroDeviceSwitcher from './HeteroDeviceSwitcher';
+import ProjectDeviceSwitcher from './ProjectDeviceSwitcher';
+import { useActiveProjectDirectoryTopicId } from './useProjectTopicDirectory';
+
+interface DeviceSwitcherProps {
+ agentId: string;
+}
+
+/**
+ * The execution-device control for whichever conversation is open. A
+ * project-directory conversation runs in its project's directory, so it only
+ * chooses among the project's devices; everything else gets the general
+ * execution-target picker. Every bar that shows a device control mounts this,
+ * so no surface can fall back to the general picker for a project topic.
+ */
+const DeviceSwitcher = ({ agentId }: DeviceSwitcherProps) => {
+ const projectTopicId = useActiveProjectDirectoryTopicId();
+
+ return projectTopicId ? (
+ <ProjectDeviceSwitcher agentId={agentId} topicId={projectTopicId} />
+ ) : (
+ <HeteroDeviceSwitcher agentId={agentId} />
+ );
+};
+
+export default DeviceSwitcher;
diff --git a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx
index 40d02d16551..eeec09e61ea 100644
--- a/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroControlBar/index.tsx
@@ -14,7 +14,7 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import ChatInputCredits from '@/business/client/features/ChatInputCredits';
-import HeteroDeviceSwitcher from '@/features/ChatInput/ControlBar/HeteroDeviceSwitcher';
+import DeviceSwitcher from '@/features/ChatInput/ControlBar/DeviceSwitcher';
import WorkspaceControls from '@/features/ChatInput/ControlBar/WorkspaceControls';
import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
@@ -184,7 +184,7 @@ const HeteroControlBar = memo(() => {
if (!agentId || isLoading) return null;
return (
<Flexbox horizontal align={'center'} className={styles.bar} justify={'space-between'}>
- <HeteroDeviceSwitcher agentId={agentId} />
+ <DeviceSwitcher agentId={agentId} />
{shouldShowApiCredits && <ChatInputCredits />}
</Flexbox>
);
diff --git a/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx b/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
new file mode 100644
index 00000000000..99d07465b3a
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/ProjectDeviceSwitcher.tsx
@@ -0,0 +1,160 @@
+'use client';
+
+import { Flexbox, Icon, Popover } from '@lobehub/ui';
+import { confirmModal, toast } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ChevronDownIcon } from 'lucide-react';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
+import { useDeviceList } from '@/features/DeviceManager/useDeviceList';
+import { ExecutionTargetDeviceStatus, ExecutionTargetIcon } from '@/features/ExecutionTargetPicker';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+
+import OptionRow from './OptionRow';
+import { listProjectDeviceTargets, projectDirectoryDeviceName } from './projectDeviceTargets';
+import { useProjectTopicDirectory } from './useProjectTopicDirectory';
+import { workingDirectoryChipStyles } from './workingDirectoryChipStyles';
+
+const styles = createStaticStyles(({ css }) => ({
+ desc: css`
+ overflow: hidden;
+ max-width: 200px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ hint: css`
+ padding-block: 6px;
+ padding-inline: 8px;
+ font-size: 11px;
+ color: ${cssVar.colorTextDescription};
+ `,
+ title: css`
+ padding-block: 4px;
+ padding-inline: 8px;
+
+ font-size: 12px;
+ font-weight: 500;
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+interface ProjectDeviceSwitcherProps {
+ agentId: string;
+ topicId: string;
+}
+
+/**
+ * Device switcher for a conversation that runs in a project directory.
+ *
+ * The directory belongs to the project, so the only choice left is which
+ * device to run on — and each device brings the project's own directory there.
+ * Only devices the project has a directory on are offered; picking one moves
+ * the conversation to that directory rather than to an arbitrary path.
+ */
+const ProjectDeviceSwitcher = ({ agentId, topicId }: ProjectDeviceSwitcherProps) => {
+ const { t } = useTranslation('chat');
+ const [open, setOpen] = useState(false);
+ const { canUseResource } = useChatInputResourceAccess();
+ const { directories, directory, directoryId } = useProjectTopicDirectory(topicId);
+ const { data: devices } = useDeviceList();
+ const moveTopic = useProjectDirectoryStore((s) => s.moveTopic);
+ const refreshTopic = useChatStore((s) => s.refreshTopic);
+ // The shared row, not the topic-pinned effective config: a fixed target is
+ // the author's setting, and it is what the server checks the move against.
+ const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
+ const fixedDeviceId =
+ agencyConfig?.executionTargetSelectionPolicy === 'fixed'
+ ? agencyConfig.boundDeviceId
+ : undefined;
+
+ if (!canUseResource) return null;
+
+ const targets = listProjectDeviceTargets(directories, devices, directoryId, fixedDeviceId);
+
+ const handleSelect = ({ active, directory: target, label }: (typeof targets)[number]) => {
+ setOpen(false);
+ if (active) return;
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('heteroAgent.executionTarget.switchProjectTopic.content', {
+ device: label,
+ directory: target.name,
+ }),
+ okText: t('heteroAgent.executionTarget.switchTopic.ok'),
+ onOk: async () => {
+ try {
+ await moveTopic({ directoryId: target.id, topicId });
+ await refreshTopic();
+ } catch (error) {
+ toast.error((error as Error).message);
+ }
+ },
+ title: t('heteroAgent.executionTarget.switchTopic.title'),
+ });
+ };
+
+ const content = (
+ <Flexbox style={{ maxWidth: 320, minWidth: 280 }}>
+ <div className={styles.title}>{t('heteroAgent.executionTarget.title')}</div>
+ {targets.map((target) => {
+ const selectable = target.online && target.allowed;
+ return (
+ <OptionRow
+ active={target.active}
+ disabled={!selectable}
+ key={target.directory.id}
+ label={target.label}
+ tags={target.active ? [t('heteroAgent.executionTarget.topicTag')] : []}
+ desc={
+ target.allowed ? (
+ <>
+ <span className={styles.desc}>{target.directory.path}</span>
+ <ExecutionTargetDeviceStatus
+ offlineLabel={t('heteroAgent.executionTarget.offline')}
+ online={target.online}
+ onlineLabel={t('heteroAgent.executionTarget.online')}
+ />
+ </>
+ ) : (
+ <span className={styles.desc}>{t('heteroAgent.executionTarget.fixedTip')}</span>
+ )
+ }
+ icon={
+ <ExecutionTargetIcon devicePlatform={target.directory.platform} target={'device'} />
+ }
+ onClick={() => (selectable ? handleSelect(target) : undefined)}
+ />
+ );
+ })}
+ <div className={styles.hint}>{t('heteroAgent.executionTarget.projectDevicesHint')}</div>
+ </Flexbox>
+ );
+
+ return (
+ <Popover
+ content={content}
+ open={open}
+ placement="topLeft"
+ styles={{ content: { padding: 4 } }}
+ trigger="click"
+ onOpenChange={setOpen}
+ >
+ <div className={workingDirectoryChipStyles.chip}>
+ <ExecutionTargetIcon devicePlatform={directory?.platform} target={'device'} />
+ <span className={workingDirectoryChipStyles.label}>
+ {directory
+ ? projectDirectoryDeviceName(directory, devices)
+ : t('heteroAgent.executionTarget.unknownDevice')}
+ </span>
+ <Icon icon={ChevronDownIcon} size={12} />
+ </div>
+ </Popover>
+ );
+};
+
+export default ProjectDeviceSwitcher;
diff --git a/src/features/ChatInput/ControlBar/ProjectDirectoryChip.tsx b/src/features/ChatInput/ControlBar/ProjectDirectoryChip.tsx
new file mode 100644
index 00000000000..22fa1100bce
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/ProjectDirectoryChip.tsx
@@ -0,0 +1,36 @@
+'use client';
+
+import { Tooltip } from '@lobehub/ui';
+import { cx } from 'antd-style';
+import { useTranslation } from 'react-i18next';
+
+import DirIcon from './DirIcon';
+import { useProjectTopicDirectory } from './useProjectTopicDirectory';
+import { workingDirectoryChipStyles } from './workingDirectoryChipStyles';
+
+interface ProjectDirectoryChipProps {
+ topicId: string;
+}
+
+/**
+ * The working directory of a project-directory conversation. It belongs to the
+ * project, so it is shown but not picked here — switching devices
+ * (`ProjectDeviceSwitcher`) is what moves the conversation to the project's
+ * directory on another machine.
+ */
+const ProjectDirectoryChip = ({ topicId }: ProjectDirectoryChipProps) => {
+ const { t } = useTranslation('project');
+ const { directory } = useProjectTopicDirectory(topicId);
+ if (!directory) return null;
+
+ return (
+ <Tooltip title={t('directories.boundTip', { path: directory.path })}>
+ <div className={cx(workingDirectoryChipStyles.chip, workingDirectoryChipStyles.readonly)}>
+ <DirIcon />
+ <span className={workingDirectoryChipStyles.label}>{directory.name}</span>
+ </div>
+ </Tooltip>
+ );
+};
+
+export default ProjectDirectoryChip;
diff --git a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
index 0b3f52b345f..490bd81ca25 100644
--- a/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
+++ b/src/features/ChatInput/ControlBar/WorkingDirectorySection.tsx
@@ -16,6 +16,8 @@ import { deviceSelectors, useDeviceStore } from '@/store/device';
import { useElectronStore } from '@/store/electron';
import GitStatus from './GitStatus';
+import ProjectDirectoryChip from './ProjectDirectoryChip';
+import { useActiveProjectDirectoryTopicId } from './useProjectTopicDirectory';
import { useRepoType } from './useRepoType';
import WorkingDirectoryPicker from './WorkingDirectoryPicker';
@@ -59,6 +61,8 @@ const WorkingDirectorySectionInner = memo<WorkingDirectorySectionProps>(({ agent
const topicWorkingDirectoryConfig = useChatStore(
(s) => topicSelectors.currentTopicMetadata(s)?.workingDirectoryConfig,
);
+ // The project owns this conversation's directory; it is shown, not picked.
+ const projectTopicId = useActiveProjectDirectoryTopicId();
// Only trust the persisted config when it actually describes the directory we
// resolved — the topic override wins in `useEffectiveWorkingDirectory`, so this
// holds whenever the config is what produced `effectiveWorkingDirectory`.
@@ -94,7 +98,11 @@ const WorkingDirectorySectionInner = memo<WorkingDirectorySectionProps>(({ agent
return (
<>
- <WorkingDirectoryPicker agentId={agentId} />
+ {projectTopicId ? (
+ <ProjectDirectoryChip topicId={projectTopicId} />
+ ) : (
+ <WorkingDirectoryPicker agentId={agentId} />
+ )}
{effectiveWorkingDirectory && repoType && (
<GitStatus
agentId={agentId}
diff --git a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx b/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
index 08eabc46275..1d5516ac4c1 100644
--- a/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
+++ b/src/features/ChatInput/ControlBar/WorkspaceControls.tsx
@@ -7,7 +7,7 @@ import { useTranslation } from 'react-i18next';
import { useChatInputResourceAccess } from '@/features/ChatInput/hooks/useChatInputResourceAccess';
import CloudRepoSwitcher from './CloudRepoSwitcher';
-import HeteroDeviceSwitcher from './HeteroDeviceSwitcher';
+import DeviceSwitcher from './DeviceSwitcher';
import SandboxStorageSection from './SandboxStorageSection';
import { useWorkspaceSurface, type WorkspaceSurface } from './useWorkspaceSurface';
import WorkingDirectorySection from './WorkingDirectorySection';
@@ -94,7 +94,7 @@ const WorkspaceControls = memo<WorkspaceControlsProps>(
return (
<>
- <HeteroDeviceSwitcher agentId={agentId} />
+ <DeviceSwitcher agentId={agentId} />
{surfaces.map((surface) => (
<Fragment key={surface}>{withAccessGate(surface)}</Fragment>
))}
diff --git a/src/features/ChatInput/ControlBar/__tests__/projectDeviceTargets.test.ts b/src/features/ChatInput/ControlBar/__tests__/projectDeviceTargets.test.ts
new file mode 100644
index 00000000000..1d6c76c6467
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/__tests__/projectDeviceTargets.test.ts
@@ -0,0 +1,86 @@
+import type { DeviceListItem } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import type { ProjectDirectory } from '@/store/projectWorkingDirectory';
+
+import { listProjectDeviceTargets } from '../projectDeviceTargets';
+
+const directory = (id: string, deviceId: string, extra: Partial<ProjectDirectory> = {}) =>
+ ({
+ deviceId,
+ deviceName: null,
+ id,
+ instanceId: `instance-${id}`,
+ name: id,
+ path: `/work/${id}`,
+ permission: 'readWrite',
+ platform: 'darwin',
+ ...extra,
+ }) as ProjectDirectory;
+const device = (deviceId: string, friendlyName: string, online = true) =>
+ ({ channels: [], deviceId, friendlyName, online }) as unknown as DeviceListItem;
+
+describe('listProjectDeviceTargets', () => {
+ const devices = [
+ device('dev-a', 'Device A'),
+ device('dev-b', 'Device B', false),
+ // Online, but the project has no directory there.
+ device('dev-c', 'Device C'),
+ ];
+
+ it('offers one target per project directory, never a device without one', () => {
+ const targets = listProjectDeviceTargets(
+ [directory('dir-a', 'dev-a'), directory('dir-b', 'dev-b')],
+ devices,
+ 'dir-a',
+ );
+ expect(targets.map((t) => [t.label, t.active, t.online])).toEqual([
+ ['Device A', true, true],
+ ['Device B', false, false],
+ ]);
+ });
+
+ it('drops directories that cannot host a run', () => {
+ const targets = listProjectDeviceTargets(
+ [
+ directory('legacy', 'dev-a', { instanceId: null }),
+ directory('read-only', 'dev-c', { permission: 'read' as ProjectDirectory['permission'] }),
+ ],
+ devices,
+ undefined,
+ );
+ expect(targets).toEqual([]);
+ });
+
+ it('only allows the device a fixed agent is pinned to', () => {
+ const targets = listProjectDeviceTargets(
+ [directory('dir-a', 'dev-a'), directory('dir-c', 'dev-c')],
+ devices,
+ 'dir-a',
+ 'dev-a',
+ );
+ // Listed so the user sees where the project lives, but the move would be refused.
+ expect(targets.map((t) => [t.label, t.allowed])).toEqual([
+ ['Device A', true],
+ ['Device C', false],
+ ]);
+ });
+
+ it('allows every project device when the agent is not fixed', () => {
+ const targets = listProjectDeviceTargets(
+ [directory('dir-a', 'dev-a'), directory('dir-c', 'dev-c')],
+ devices,
+ 'dir-a',
+ );
+ expect(targets.every((t) => t.allowed)).toBe(true);
+ });
+
+ it('names a device the list does not know by its directory row', () => {
+ const [target] = listProjectDeviceTargets(
+ [directory('dir-x', 'dev-x', { deviceName: 'Build box' })],
+ devices,
+ undefined,
+ );
+ expect(target).toMatchObject({ label: 'Build box', online: false });
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/__tests__/useActiveProjectDirectoryTopicId.test.ts b/src/features/ChatInput/ControlBar/__tests__/useActiveProjectDirectoryTopicId.test.ts
new file mode 100644
index 00000000000..7df5e9bbdee
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/__tests__/useActiveProjectDirectoryTopicId.test.ts
@@ -0,0 +1,43 @@
+import { renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useActiveProjectDirectoryTopicId } from '../useProjectTopicDirectory';
+
+const state = vi.hoisted(() => ({
+ activeTopicId: undefined as string | undefined,
+ topics: {} as Record<string, { projectWorkingDirectoryId?: string | null }>,
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: unknown) => unknown) => selector(state),
+}));
+
+vi.mock('@/store/chat/selectors', () => ({
+ topicSelectors: {
+ getTopicById: (id: string) => (s: typeof state) => s.topics[id],
+ },
+}));
+
+vi.mock('@/store/projectWorkingDirectory', () => ({
+ useProjectDirectories: () => [],
+ useProjectDirectoryStore: () => () => undefined,
+}));
+
+describe('useActiveProjectDirectoryTopicId', () => {
+ it('names the open conversation when it runs in a project directory', () => {
+ state.activeTopicId = 'project-topic';
+ state.topics = { 'project-topic': { projectWorkingDirectoryId: 'directory-1' } };
+ expect(renderHook(() => useActiveProjectDirectoryTopicId()).result.current).toBe(
+ 'project-topic',
+ );
+ });
+
+ it('leaves ordinary conversations — including directory-less project ones — to the general picker', () => {
+ state.activeTopicId = 'plain-topic';
+ state.topics = { 'plain-topic': { projectWorkingDirectoryId: null } };
+ expect(renderHook(() => useActiveProjectDirectoryTopicId()).result.current).toBeUndefined();
+
+ state.activeTopicId = undefined;
+ expect(renderHook(() => useActiveProjectDirectoryTopicId()).result.current).toBeUndefined();
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/projectDeviceTargets.ts b/src/features/ChatInput/ControlBar/projectDeviceTargets.ts
new file mode 100644
index 00000000000..a79492bc75d
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/projectDeviceTargets.ts
@@ -0,0 +1,44 @@
+import type { DeviceListItem } from '@lobechat/types';
+
+import type { ProjectDirectory } from '@/store/projectWorkingDirectory';
+
+export interface ProjectDeviceTarget {
+ active: boolean;
+ /** False when the agent is fixed to another device — the move would be refused. */
+ allowed: boolean;
+ directory: ProjectDirectory;
+ label: string;
+ online: boolean;
+}
+
+export const projectDirectoryDeviceName = (
+ directory: ProjectDirectory,
+ devices: DeviceListItem[] | undefined,
+) => {
+ const device = devices?.find((item) => item.deviceId === directory.deviceId);
+ return device?.friendlyName || directory.deviceName || device?.hostname || directory.deviceId;
+};
+
+/**
+ * The devices a project-directory conversation may switch to: one per project
+ * directory that can host a run. A device without the project's directory is
+ * not a target — the directory belongs to the project, so there is nothing to
+ * run in there — and a legacy or read-only directory cannot host a run. An
+ * agent fixed to one device in its profile cannot be moved anywhere else, so
+ * every other device is listed but not allowed.
+ */
+export const listProjectDeviceTargets = (
+ directories: ProjectDirectory[],
+ devices: DeviceListItem[] | undefined,
+ currentDirectoryId: string | undefined,
+ fixedDeviceId?: string,
+): ProjectDeviceTarget[] =>
+ directories
+ .filter((d) => d.instanceId && d.permission === 'readWrite')
+ .map((directory) => ({
+ active: directory.id === currentDirectoryId,
+ allowed: !fixedDeviceId || directory.deviceId === fixedDeviceId,
+ directory,
+ label: projectDirectoryDeviceName(directory, devices),
+ online: !!devices?.find((item) => item.deviceId === directory.deviceId)?.online,
+ }));
diff --git a/src/features/ChatInput/ControlBar/useProjectTopicDirectory.ts b/src/features/ChatInput/ControlBar/useProjectTopicDirectory.ts
new file mode 100644
index 00000000000..141eff5d856
--- /dev/null
+++ b/src/features/ChatInput/ControlBar/useProjectTopicDirectory.ts
@@ -0,0 +1,50 @@
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import {
+ type ProjectDirectory,
+ useProjectDirectories,
+ useProjectDirectoryStore,
+} from '@/store/projectWorkingDirectory';
+
+const EMPTY: ProjectDirectory[] = [];
+
+/**
+ * The open conversation's id when it runs in a project directory, otherwise
+ * undefined. Such a conversation only chooses among its project's devices and
+ * shows its directory read-only, so the control bars branch on this.
+ */
+export const useActiveProjectDirectoryTopicId = (): string | undefined =>
+ useChatStore((s) =>
+ s.activeTopicId && topicSelectors.getTopicById(s.activeTopicId)(s)?.projectWorkingDirectoryId
+ ? s.activeTopicId
+ : undefined,
+ );
+
+/**
+ * The project directory a conversation runs in, and the project's other
+ * directories it may move to. Empty for conversations outside a project
+ * directory — those keep the general execution-target and directory pickers.
+ */
+export const useProjectTopicDirectory = (topicId?: string | null) => {
+ const directoryId = useChatStore((s) =>
+ topicId
+ ? (topicSelectors.getTopicById(topicId)(s)?.projectWorkingDirectoryId ?? undefined)
+ : undefined,
+ );
+ const projectId = useChatStore((s) =>
+ topicId && directoryId
+ ? (topicSelectors.getTopicById(topicId)(s)?.projectId ?? undefined)
+ : undefined,
+ );
+ useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId, !!projectId);
+ // Without a project this would read the scope-wide list, so pin it empty.
+ const rows = useProjectDirectories(projectId);
+ const directories = projectId ? rows : EMPTY;
+
+ return {
+ directories,
+ directory: directories.find((d) => d.id === directoryId),
+ directoryId,
+ projectId,
+ };
+};
diff --git a/src/features/ChatInput/ControlBar/workingDirectoryChipStyles.ts b/src/features/ChatInput/ControlBar/workingDirectoryChipStyles.ts
index 5eb96f900d6..0eea827e368 100644
--- a/src/features/ChatInput/ControlBar/workingDirectoryChipStyles.ts
+++ b/src/features/ChatInput/ControlBar/workingDirectoryChipStyles.ts
@@ -29,6 +29,14 @@ export const workingDirectoryChipStyles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorFillTertiary};
}
`,
+ /** Shown, not picked — e.g. a directory owned by the conversation's project. */
+ readonly: css`
+ cursor: default;
+
+ &:hover {
+ background: transparent;
+ }
+ `,
label: css`
overflow: hidden;
max-width: 140px;
diff --git a/src/services/projectWorkingDirectory.ts b/src/services/projectWorkingDirectory.ts
index 1abfb1348a2..ca66844fb05 100644
--- a/src/services/projectWorkingDirectory.ts
+++ b/src/services/projectWorkingDirectory.ts
@@ -29,6 +29,8 @@ class ProjectWorkingDirectoryService {
success: true,
};
};
+ moveTopic = (input: Parameters<Client['moveTopic']['mutate']>[0]) =>
+ lambdaClient.projectWorkingDirectory.moveTopic.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 2e46a730ec4..1f4b8e6e66b 100644
--- a/src/store/projectWorkingDirectory/index.test.ts
+++ b/src/store/projectWorkingDirectory/index.test.ts
@@ -147,5 +147,23 @@ describe('projectWorkingDirectory store', () => {
expect(invalidates('projectTopics', 'project-2')).toBe(false);
expect(invalidates('projectDirectories', 'project-1')).toBe(false);
});
+
+ it('moves a conversation and refreshes both directories it touched', async () => {
+ const moveTopic = vi
+ .spyOn(projectWorkingDirectoryService, 'moveTopic')
+ .mockResolvedValue({ data: { projectId: 'project-1' } } as never);
+
+ await useProjectDirectoryStore
+ .getState()
+ .moveTopic({ directoryId: 'directory-2', topicId: 'topic-1' });
+
+ expect(moveTopic).toHaveBeenCalledWith({ directoryId: 'directory-2', topicId: 'topic-1' });
+ expect(invalidates('projectTopics', 'project-1')).toBe(true);
+ // Left one directory for another: every directory projection is stale.
+ expect(invalidates('directoryTopics', 'directory-1')).toBe(true);
+ expect(invalidates('directoryTopics', 'directory-2')).toBe(true);
+ // The directory rows themselves did not change.
+ expect(invalidates('projectDirectories', 'project-1')).toBe(false);
+ });
});
});
diff --git a/src/store/projectWorkingDirectory/index.ts b/src/store/projectWorkingDirectory/index.ts
index 7ddb0b250c8..40310bbb569 100644
--- a/src/store/projectWorkingDirectory/index.ts
+++ b/src/store/projectWorkingDirectory/index.ts
@@ -99,6 +99,8 @@ interface ProjectDirectoryStore extends ProjectDirectoryStoreState {
createProjectTopic: (
...args: ServiceParams<'createProjectTopic'>
) => Promise<ServiceData<'createProjectTopic'>>;
+ /** Move a directory conversation to its project's directory on another device. */
+ moveTopic: (...args: ServiceParams<'moveTopic'>) => Promise<ServiceData<'moveTopic'>>;
/** Create or rename an environment. */
saveEnvironment: (
...args: ServiceParams<'saveEnvironment'>
@@ -208,6 +210,17 @@ export const useProjectDirectoryStore: UseBoundStoreWithEqualityFn<
]);
return result.data;
},
+ moveTopic: async (input) => {
+ const result = await projectWorkingDirectoryService.moveTopic(input);
+ await Promise.all([
+ result.data.projectId && projectTopics.revalidate(result.data.projectId),
+ // The topic left one directory for another, so both directories'
+ // projections are stale.
+ directoryTopics.revalidate(),
+ environmentTopics.revalidate(),
+ ]);
+ return result.data;
+ },
saveEnvironment: async (input) => {
const result = await projectWorkingDirectoryService.saveEnvironment(input);
// One environment is shared by every project that lists it, and its name