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 workspace members file shared conversations into a project (#21418)

Arvin Xu4fcc03ce0dd2
diff --git a/apps/server/src/routers/lambda/projectWorkingDirectory.ts b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
index c65aff2b50a..7f82f3a5bda 100644
--- a/apps/server/src/routers/lambda/projectWorkingDirectory.ts
+++ b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
@@ -63,10 +63,11 @@ export const projectWorkingDirectoryRouter = router({
}),
)
.mutation(async ({ ctx, input }) => {
- await assertCanUseTopicTargets(
- { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
- [input.topicId],
- );
+ const guardCtx = { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId };
+ await assertCanUseTopicTargets(guardCtx, [input.topicId]);
+ // Same visitor guard as `moveTopic`: a share-visitor topic is not the
+ // member's conversation to file into a project.
+ await assertCreatorTopicTargets(guardCtx, [input.topicId]);
return {
data: await ctx.directoryRepo.associateTopic(
input.projectId,
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index 1e7b4303836..1eefd903384 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -77,6 +77,7 @@
"directories.start": "Start work here",
"directories.startInProject": "Start work in {{name}}",
"directories.title": "Working directories",
+ "directories.topicsSkipped": "Directory linked. {{count}} topics were left out because they run in another directory or on another device, belong to another project, are still running, or no longer exist.",
"directories.unavailable": "Device is offline or the directory is unavailable. Reconnect and retry.",
"directories.untitled": "Untitled topic",
"disabled.action": "Enable in Labs",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index df689e24177..cb251fe2c65 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -77,6 +77,7 @@
"directories.start": "在此开始工作",
"directories.startInProject": "在 {{name}} 中开始工作",
"directories.title": "工作目录",
+ "directories.topicsSkipped": "目录已关联。有 {{count}} 个话题未归入项目:它们在其他目录或设备上运行、已属于其他项目、仍在运行,或已不存在。",
"directories.unavailable": "设备离线或目录不可用,请重新连接后重试。",
"directories.untitled": "未命名话题",
"disabled.action": "前往实验室开启",
diff --git a/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts b/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts
index 154e0b0cf4c..38c4720c1bc 100644
--- a/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts
+++ b/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts
@@ -201,27 +201,118 @@ describe('ProjectDirectoryRepository.bind', () => {
expect(topic.projectId).toBeNull();
});
- it('files explicit conversations and rolls back mismatched selections', async () => {
+ it('files matching conversations and reports the ones it skips', async () => {
+ await db.insert(projects).values({
+ coordinatorAgentId: 'repo-coordinator',
+ id: 'another-project',
+ identifier: 'ANO',
+ name: 'Another project',
+ userId,
+ });
await db.insert(topics).values([
+ { id: 'matching', agentId: 'repo-agent', userId, metadata: { workingDirectory: base.path } },
+ { id: 'other-path', agentId: 'repo-agent', userId, metadata: { workingDirectory: '/other' } },
{
- id: 'matching',
+ id: 'filed-elsewhere',
agentId: 'repo-agent',
+ projectId: 'another-project',
userId,
metadata: { workingDirectory: base.path },
},
{
- id: 'other-path',
+ id: 'busy',
agentId: 'repo-agent',
+ status: 'running',
userId,
- metadata: { workingDirectory: '/other' },
+ metadata: { workingDirectory: base.path },
},
]);
- await expect(
- repo.bind({ ...base, agentId: 'repo-agent', topicIds: ['matching', 'other-path'] }),
- ).rejects.toThrow('different directory');
- expect(await directoryModel.list()).toEqual([]);
- const directory = await repo.bind({ ...base, agentId: 'repo-agent', topicIds: ['matching'] });
- expect(await directoryModel.listTopics(directory.id)).toHaveLength(1);
+ const directory = await repo.bind({
+ ...base,
+ agentId: 'repo-agent',
+ topicIds: ['matching', 'other-path', 'filed-elsewhere', 'busy', 'missing'],
+ });
+ expect(directory.skippedTopics).toEqual(
+ expect.arrayContaining([
+ { id: 'other-path', reason: 'differentLocation' },
+ { id: 'filed-elsewhere', reason: 'otherProject' },
+ { id: 'busy', reason: 'running' },
+ { id: 'missing', reason: 'notFound' },
+ ]),
+ );
+ expect(directory.skippedTopics).toHaveLength(4);
+ expect((await directoryModel.listTopics(directory.id)).map((t) => t.id)).toEqual(['matching']);
+ });
+
+ it('files every workspace member’s conversations in a shared agent’s directory', async () => {
+ const workspaceId = 'bind-topic-ws';
+ await db.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Bind topic workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ await db.insert(agents).values([
+ { id: 'ws-bind-coordinator', userId, workspaceId },
+ { id: 'ws-shared-agent', userId, workspaceId },
+ ]);
+ await db.insert(projects).values({
+ coordinatorAgentId: 'ws-bind-coordinator',
+ id: 'ws-bind-project',
+ identifier: 'WSB',
+ name: 'Workspace bind project',
+ userId: otherUserId,
+ workspaceId,
+ });
+ await db.insert(devices).values({
+ deviceId: 'ws-bind-device',
+ identitySource: 'fallback',
+ platform: 'linux',
+ userId,
+ visibility: 'public',
+ workspaceId,
+ });
+ // One conversation per member in the same directory of a shared agent.
+ await db.insert(topics).values([
+ {
+ id: 'creator-topic',
+ agentId: 'ws-shared-agent',
+ metadata: { boundDeviceId: 'ws-bind-device', workingDirectory: '/ws/repo' },
+ userId,
+ workspaceId,
+ },
+ {
+ id: 'member-topic',
+ agentId: 'ws-shared-agent',
+ metadata: { workingDirectory: '/ws/repo' },
+ userId: otherUserId,
+ workspaceId,
+ },
+ // A share visitor's conversation is hidden from members and must not be filed.
+ {
+ id: 'visitor-topic',
+ agentId: 'ws-shared-agent',
+ metadata: { workingDirectory: '/ws/repo' },
+ senderId: userId,
+ userId,
+ workspaceId,
+ },
+ ]);
+ const memberRepo = new ProjectDirectoryRepository(db, otherUserId, workspaceId);
+ const directory = await memberRepo.bind({
+ agentId: 'ws-shared-agent',
+ deviceId: 'ws-bind-device',
+ name: 'Repo',
+ path: '/ws/repo',
+ projectId: 'ws-bind-project',
+ topicIds: ['creator-topic', 'member-topic', 'visitor-topic'],
+ });
+ expect(directory.skippedTopics).toEqual([{ id: 'visitor-topic', reason: 'notFound' }]);
+ const filed = await db.select().from(topics).where(eq(topics.projectId, 'ws-bind-project'));
+ expect(filed.map((t) => [t.id, t.userId]).sort()).toEqual([
+ ['creator-topic', userId],
+ ['member-topic', otherUserId],
+ ]);
});
});
@@ -303,6 +394,64 @@ describe('ProjectDirectoryRepository.associateTopic', () => {
});
});
+describe('ProjectDirectoryRepository.associateTopic in a workspace', () => {
+ it('lets a member file a shared topic they did not create', async () => {
+ const workspaceId = 'associate-topic-ws';
+ await db.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Associate topic workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ await db.insert(agents).values({ id: 'ws-assoc-coordinator', userId, workspaceId });
+ await db.insert(projects).values({
+ coordinatorAgentId: 'ws-assoc-coordinator',
+ id: 'ws-assoc-project',
+ identifier: 'WSA',
+ name: 'Workspace associate project',
+ userId: otherUserId,
+ workspaceId,
+ });
+ await db.insert(topics).values({ id: 'ws-assoc-topic', userId, workspaceId });
+ await new ProjectDirectoryRepository(db, otherUserId, workspaceId).associateTopic(
+ 'ws-assoc-project',
+ 'ws-assoc-topic',
+ );
+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'ws-assoc-topic'));
+ expect(topic).toMatchObject({ projectId: 'ws-assoc-project', userId });
+ });
+
+ it('does not file a share visitor’s topic', async () => {
+ const workspaceId = 'associate-visitor-ws';
+ await db.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Associate visitor workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ await db.insert(agents).values({ id: 'ws-visitor-coordinator', userId, workspaceId });
+ await db.insert(projects).values({
+ coordinatorAgentId: 'ws-visitor-coordinator',
+ id: 'ws-visitor-project',
+ identifier: 'WSV',
+ name: 'Workspace visitor project',
+ userId: otherUserId,
+ workspaceId,
+ });
+ await db
+ .insert(topics)
+ .values({ id: 'ws-visitor-topic', senderId: userId, userId, workspaceId });
+ await expect(
+ new ProjectDirectoryRepository(db, otherUserId, workspaceId).associateTopic(
+ 'ws-visitor-project',
+ 'ws-visitor-topic',
+ ),
+ ).rejects.toThrow('not found');
+ const [topic] = await db.select().from(topics).where(eq(topics.id, 'ws-visitor-topic'));
+ expect(topic.projectId).toBeNull();
+ });
+});
+
describe('ProjectDirectoryRepository.moveTopic', () => {
const second = { ...base, deviceId: 'second-device', path: '/work/second' };
const pinnedTopic = async (directoryId: string) => {
diff --git a/packages/database/src/repositories/projectDirectory/index.ts b/packages/database/src/repositories/projectDirectory/index.ts
index 1e89e625b49..a5afc35f2af 100644
--- a/packages/database/src/repositories/projectDirectory/index.ts
+++ b/packages/database/src/repositories/projectDirectory/index.ts
@@ -1,4 +1,5 @@
import { getWorkingDirSourcePath } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
import { and, eq, inArray, isNull } from 'drizzle-orm';
import { EnvironmentModel, normalizeProjectRepository } from '../../models/environment';
@@ -13,6 +14,26 @@ import { agents, devices, projectEnvironments, topics } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { buildWorkspaceWhere } from '../../utils/workspace';
+/**
+ * A refused directory write. It carries its tRPC code, so a permission or
+ * state problem reaches the client as a 4xx with this message instead of
+ * being wrapped as an internal server error.
+ */
+export class ProjectDirectoryError extends TRPCError {
+ constructor(code: 'BAD_REQUEST' | 'CONFLICT' | 'FORBIDDEN' | 'NOT_FOUND', message: string) {
+ super({ code, message });
+ this.name = 'ProjectDirectoryError';
+ }
+}
+
+export type SkippedProjectTopicReason =
+ 'differentLocation' | 'notFound' | 'otherProject' | 'running';
+
+export interface SkippedProjectTopic {
+ id: string;
+ reason: SkippedProjectTopicReason;
+}
+
export interface BindProjectDirectoryInput {
agentId?: string;
deviceId: string;
@@ -48,7 +69,8 @@ export class ProjectDirectoryRepository {
this.userId,
this.workspaceId,
).findManageableById(projectId);
- if (!project) throw new Error('Project not found or access denied');
+ if (!project)
+ throw new ProjectDirectoryError('NOT_FOUND', 'Project not found or access denied');
return project;
}
@@ -68,7 +90,8 @@ export class ProjectDirectoryRepository {
and(eq(devices.deviceId, input.deviceId), buildWorkspaceWhere(this.scope(), devices)),
)
.for('update');
- if (!device) throw new Error('Device not found or access denied');
+ if (!device)
+ throw new ProjectDirectoryError('NOT_FOUND', 'Device not found or access denied');
const path = normalizeProjectDirectory(input.path, device.platform);
const repositoryUrl = input.repositoryUrl
? normalizeProjectRepository(input.repositoryUrl)
@@ -90,16 +113,23 @@ export class ProjectDirectoryRepository {
// The name lookup deliberately sees disabled rows, because the unique
// indexes do: a disabled environment of this name still owns the name,
// so minting a replacement would only hit the constraint.
- if (!environment && named) throw new Error('Environment is disabled');
+ if (!environment && named)
+ throw new ProjectDirectoryError('BAD_REQUEST', 'Environment is disabled');
if (!environment || (input.environmentId && input.environmentId !== environment.id))
- throw new Error('This directory belongs to another environment');
+ throw new ProjectDirectoryError(
+ 'CONFLICT',
+ 'This directory belongs to another environment',
+ );
if (
repositoryUrl &&
!environment.configuration.sources?.some(
(source) => source.kind === 'git' && source.url === repositoryUrl,
)
)
- throw new Error('Repository differs from the existing environment');
+ throw new ProjectDirectoryError(
+ 'CONFLICT',
+ 'Repository differs from the existing environment',
+ );
} else {
environment = await environmentModel.save({
name: input.name,
@@ -115,7 +145,8 @@ export class ProjectDirectoryRepository {
workingDirectory: path,
});
}
- if (!instance.enabled) throw new Error('Environment instance is disabled');
+ if (!instance.enabled)
+ throw new ProjectDirectoryError('BAD_REQUEST', 'Environment instance is disabled');
await projectModel.attachEnvironment(input.projectId, environment.id);
const [link] = await db
.select()
@@ -126,7 +157,8 @@ export class ProjectDirectoryRepository {
eq(projectEnvironments.environmentId, environment.id),
),
);
- if (!link.enabled) throw new Error('Environment is disabled in this project');
+ if (!link.enabled)
+ throw new ProjectDirectoryError('BAD_REQUEST', 'Environment is disabled in this project');
const prior = await directoryModel.findByLocation(input.projectId, device.id, path);
const directory =
prior ??
@@ -138,8 +170,13 @@ export class ProjectDirectoryRepository {
projectId: input.projectId,
workspaceId: this.workspaceId,
}));
+ const skippedTopics: SkippedProjectTopic[] = [];
if (input.topicIds?.length) {
- if (!input.agentId) throw new Error('Agent is required when filing conversations');
+ if (!input.agentId)
+ throw new ProjectDirectoryError(
+ 'BAD_REQUEST',
+ 'Agent is required when filing conversations',
+ );
const [filingAgent] = await db
.select()
.from(agents)
@@ -149,37 +186,53 @@ export class ProjectDirectoryRepository {
(filingAgent.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
filingAgent.agencyConfig.boundDeviceId !== device.deviceId)
)
- throw new Error('Agent cannot use this execution target');
+ throw new ProjectDirectoryError('FORBIDDEN', 'Agent cannot use this execution target');
+ const topicIds = [...new Set(input.topicIds)];
const selected = await db
.select()
.from(topics)
.where(
+ // Workspace-scoped, not creator-scoped: a shared agent's directory
+ // holds every member's conversations, and `topics.userId` only
+ // records who started one. The router already authorized the
+ // caller to use them. Share-visitor topics (`senderId`) stay out:
+ // they are hidden from members, and filing one into a project
+ // would list it there.
and(
- inArray(topics.id, input.topicIds),
+ inArray(topics.id, topicIds),
eq(topics.agentId, input.agentId),
- eq(topics.userId, this.userId),
buildWorkspaceWhere(this.scope(), topics),
+ isNull(topics.deletedAt),
+ isNull(topics.senderId),
),
)
.for('update');
- if (selected.length !== new Set(input.topicIds).size)
- throw new Error('Conversation not found or access denied');
+ const found = new Set(selected.map((topic) => topic.id));
+ for (const id of topicIds)
+ if (!found.has(id)) skippedTopics.push({ id, reason: 'notFound' });
+ // Filing is a convenience on top of the binding: one conversation that
+ // cannot move must not cost the directory or the others, so it is
+ // skipped and reported instead of failing the whole bind.
for (const topic of selected) {
const metadata = topic.metadata ?? {};
const source = getWorkingDirSourcePath(
metadata.workingDirectoryConfig ?? metadata.workingDirectory,
);
const pinnedDevice = metadata.boundDeviceId ?? metadata.runningOperation?.deviceId;
- if (
+ const reason: SkippedProjectTopicReason | undefined =
!source ||
normalizeProjectDirectory(source, device.platform) !== path ||
(pinnedDevice && pinnedDevice !== device.deviceId)
- )
- throw new Error('Conversation uses a different directory or device');
- if (topic.projectId && topic.projectId !== input.projectId)
- throw new Error('Conversation already belongs to another project');
- if (metadata.runningOperation || topic.status === 'running')
- throw new Error('Wait for the conversation to finish before binding it');
+ ? 'differentLocation'
+ : topic.projectId && topic.projectId !== input.projectId
+ ? 'otherProject'
+ : metadata.runningOperation || topic.status === 'running'
+ ? 'running'
+ : undefined;
+ if (reason) {
+ skippedTopics.push({ id: topic.id, reason });
+ continue;
+ }
await db
.update(topics)
.set({
@@ -190,7 +243,7 @@ export class ProjectDirectoryRepository {
.where(eq(topics.id, topic.id));
}
}
- return directory;
+ return { ...directory, skippedTopics };
});
}
@@ -208,32 +261,41 @@ export class ProjectDirectoryRepository {
.select()
.from(topics)
.where(
+ // Workspace-scoped, not creator-scoped, without share-visitor
+ // topics — see `bind`.
and(
eq(topics.id, topicId),
- eq(topics.userId, this.userId),
buildWorkspaceWhere(this.scope(), topics),
isNull(topics.deletedAt),
+ isNull(topics.senderId),
),
)
.for('update');
- if (!topic) throw new Error('Topic not found or access denied');
+ if (!topic) throw new ProjectDirectoryError('NOT_FOUND', 'Topic not found or access denied');
if (topic.projectId && topic.projectId !== projectId)
- throw new Error('Topic already belongs to another project');
+ throw new ProjectDirectoryError('CONFLICT', 'Topic already belongs to another project');
if (topic.status === 'running' || topic.metadata?.runningOperation)
- throw new Error('Wait for the running topic to finish before associating it');
+ throw new ProjectDirectoryError(
+ 'CONFLICT',
+ 'Wait for the running topic to finish before associating it',
+ );
const source = getWorkingDirSourcePath(
topic.metadata?.workingDirectoryConfig ?? topic.metadata?.workingDirectory,
);
- if (source && !directory) throw new Error('Select the existing working directory');
+ if (source && !directory)
+ throw new ProjectDirectoryError('BAD_REQUEST', 'Select the existing working directory');
const pinned = topic.metadata?.boundDeviceId;
if (
directory &&
((source && normalizeProjectDirectory(source, directory.platform) !== directory.path) ||
(pinned && pinned !== directory.deviceId))
)
- throw new Error('Keep the existing device and working directory');
+ throw new ProjectDirectoryError(
+ 'BAD_REQUEST',
+ 'Keep the existing device and working directory',
+ );
if (topic.projectWorkingDirectoryId && topic.projectWorkingDirectoryId !== directoryId)
- throw new Error('Keep the existing project directory binding');
+ throw new ProjectDirectoryError('CONFLICT', 'Keep the existing project directory binding');
if (directory && topic.agentId) {
const [agent] = await db
.select()
@@ -244,7 +306,7 @@ export class ProjectDirectoryRepository {
(agent.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
agent.agencyConfig.boundDeviceId !== directory.deviceId)
)
- throw new Error('Agent cannot use this execution target');
+ throw new ProjectDirectoryError('FORBIDDEN', 'Agent cannot use this execution target');
}
const [updated] = await db
.update(topics)
@@ -290,9 +352,9 @@ export class ProjectDirectoryRepository {
),
)
.for('update');
- if (!topic) throw new Error('Topic not found or access denied');
+ if (!topic) throw new ProjectDirectoryError('NOT_FOUND', 'Topic not found or access denied');
if (!topic.projectId || !topic.projectWorkingDirectoryId)
- throw new Error('Topic is not bound to a project directory');
+ throw new ProjectDirectoryError('BAD_REQUEST', '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
@@ -302,7 +364,10 @@ export class ProjectDirectoryRepository {
topic.metadata?.runningOperation ||
hasLiveTaskCallbackReservation(topic.metadata)
)
- throw new Error('Wait for the running topic to finish before moving it');
+ throw new ProjectDirectoryError(
+ 'CONFLICT',
+ '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(
@@ -321,7 +386,7 @@ export class ProjectDirectoryRepository {
(agent.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
agent.agencyConfig.boundDeviceId !== directory.deviceId)
)
- throw new Error('Agent cannot use this execution target');
+ throw new ProjectDirectoryError('FORBIDDEN', 'Agent cannot use this execution target');
}
const {
heteroSessionBindingKey: _bindingKey,
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index 14ed139cc03..1047fa26338 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -67,6 +67,8 @@ export default {
'The device is disconnected or the directory is unavailable. Connect the device and check the path, then retry.',
'directories.autoFileTopics': 'All {{count}} existing topics will be linked to this project.',
+ 'directories.topicsSkipped':
+ 'Directory linked. {{count}} topics were left out because they run in another directory or on another device, belong to another project, are still running, or no longer exist.',
'settings.general': 'General',
'settings.logo': 'Logo',
'settings.logoDescription': 'Shown in the project header, sidebar and switcher.',
diff --git a/src/features/Projects/WorkingDirectories/useBindDirectory.test.ts b/src/features/Projects/WorkingDirectories/useBindDirectory.test.ts
index c03909022ea..06aba732010 100644
--- a/src/features/Projects/WorkingDirectories/useBindDirectory.test.ts
+++ b/src/features/Projects/WorkingDirectories/useBindDirectory.test.ts
@@ -3,7 +3,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useBindDirectory } from './useBindDirectory';
-const { bind, refreshTopic } = vi.hoisted(() => ({ bind: vi.fn(), refreshTopic: vi.fn() }));
+const { bind, refreshTopic, warning } = vi.hoisted(() => ({
+ bind: vi.fn(),
+ refreshTopic: vi.fn(),
+ warning: vi.fn(),
+}));
+vi.mock('@lobehub/ui', () => ({ toast: { warning } }));
vi.mock('@/store/projectWorkingDirectory', () => ({
useProjectDirectoryStore: (selector: (s: { bind: typeof bind }) => unknown) => selector({ bind }),
}));
@@ -17,7 +22,7 @@ const options = {
describe('binding an Agent directory', () => {
beforeEach(() => {
vi.clearAllMocks();
- bind.mockResolvedValue({ id: 'binding' });
+ bind.mockResolvedValue({ id: 'binding', skippedTopics: [] });
});
it('files every supplied existing topic automatically and refreshes before closing', async () => {
const saved = vi.fn();
@@ -34,6 +39,19 @@ describe('binding an Agent directory', () => {
expect(refreshTopic).toHaveBeenCalled();
expect(saved).toHaveBeenCalled();
expect(result.current.pending).toBe(false);
+ expect(warning).not.toHaveBeenCalled();
+ });
+ it('links the directory and warns about the topics it could not file', async () => {
+ bind.mockResolvedValueOnce({
+ id: 'binding',
+ skippedTopics: [{ id: 'old-2', reason: 'running' }],
+ });
+ const saved = vi.fn();
+ const { result } = renderHook(() => useBindDirectory(options, saved));
+ await act(async () => result.current.save('project', 'environment'));
+ expect(saved).toHaveBeenCalled();
+ expect(result.current.error).toBeUndefined();
+ expect(warning).toHaveBeenCalledOnce();
});
it('keeps the form open and supports retry when association fails', async () => {
const error = new Error('Wait for conversation to finish');
diff --git a/src/features/Projects/WorkingDirectories/useBindDirectory.ts b/src/features/Projects/WorkingDirectories/useBindDirectory.ts
index 91c3bc9a5ca..5ec4e02e685 100644
--- a/src/features/Projects/WorkingDirectories/useBindDirectory.ts
+++ b/src/features/Projects/WorkingDirectories/useBindDirectory.ts
@@ -1,3 +1,5 @@
+import { toast } from '@lobehub/ui';
+import { t } from 'i18next';
import { useState } from 'react';
import { useChatStore } from '@/store/chat';
@@ -13,7 +15,7 @@ export function useBindDirectory(options: BindDirectoryOptions, onSaved: () => v
setPending(true);
setError(undefined);
try {
- await bind({
+ const directory = await bind({
agentId: options.agentId,
deviceId: options.deviceId,
environmentId,
@@ -24,6 +26,11 @@ export function useBindDirectory(options: BindDirectoryOptions, onSaved: () => v
});
await useChatStore.getState().refreshTopic();
onSaved();
+ // The directory is linked even when some topics stay where they are.
+ if (directory.skippedTopics.length)
+ toast.warning(
+ t('directories.topicsSkipped', { count: directory.skippedTopics.length, ns: 'project' }),
+ );
} catch (error) {
console.error('Failed to bind project directory', error);
setError(error);