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: complete Project, Topic and Environment work flows (#19610)

Arvin Xu9f8e02bd2989
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index d7f404e7cc6..210aa46ae38 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -80,6 +80,7 @@ import { oauthAppRouter } from './oauthApp';
import { oauthDeviceFlowRouter } from './oauthDeviceFlow';
import { pluginRouter } from './plugin';
import { projectRouter } from './project';
+import { projectWorkingDirectoryRouter } from './projectWorkingDirectory';
import { pushTokenRouter } from './pushToken';
import { ragEvalRouter } from './ragEval';
import { recentRouter } from './recent';
@@ -173,6 +174,7 @@ export const lambdaRouter = router({
oauthDeviceFlow: oauthDeviceFlowRouter,
plugin: pluginRouter,
project: projectRouter,
+ projectWorkingDirectory: projectWorkingDirectoryRouter,
pushToken: pushTokenRouter,
ragEval: ragEvalRouter,
recent: recentRouter,
diff --git a/apps/server/src/routers/lambda/projectWorkingDirectory.ts b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
new file mode 100644
index 00000000000..1a269c217b9
--- /dev/null
+++ b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
@@ -0,0 +1,244 @@
+import { TRPCError } from '@trpc/server';
+import { and, eq } from 'drizzle-orm';
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { EnvironmentModel } from '@/database/models/environment';
+import { ProjectModel } from '@/database/models/project';
+import { ProjectWorkingDirectoryModel } from '@/database/models/projectWorkingDirectory';
+import { TopicModel } from '@/database/models/topic';
+import { ProjectDirectoryRepository } from '@/database/repositories/projectDirectory';
+import { agents } from '@/database/schemas';
+import { buildWorkspaceWhere } from '@/database/utils/workspace';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import {
+ createAgentConfigResolver,
+ resolvePrecreatedTopicSnapshot,
+} from '@/server/services/aiAgent/pipeline/precreatedTopic';
+import { deviceGateway } from '@/server/services/deviceGateway';
+
+import {
+ assertCanUseConversationTargets,
+ assertCanUseTopicTargets,
+ assertCanViewTopicTargets,
+} from './_helpers/conversationResourceGuard';
+
+const procedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { serverDB, userId, workspaceId } = opts.ctx;
+ return opts.next({
+ ctx: {
+ directoryModel: new ProjectWorkingDirectoryModel(serverDB, userId, workspaceId ?? undefined),
+ directoryRepo: new ProjectDirectoryRepository(serverDB, userId, workspaceId ?? undefined),
+ environmentModel: new EnvironmentModel(serverDB, userId, workspaceId ?? undefined),
+ projectModel: new ProjectModel(serverDB, userId, workspaceId ?? undefined),
+ topicModel: new TopicModel(serverDB, userId, workspaceId ?? undefined),
+ // Topics written here exist before any run does, so they have to pin their
+ // own model snapshot — see `resolvePrecreatedTopicSnapshot`.
+ precreatedTopicDeps: {
+ db: serverDB,
+ resolveAgentConfigOrThrow: createAgentConfigResolver(
+ serverDB,
+ userId,
+ workspaceId ?? undefined,
+ ),
+ userId,
+ workspaceId: workspaceId ?? undefined,
+ },
+ },
+ });
+});
+const write = procedure.use(withScopedPermission('agent:update'));
+const idInput = z.object({ id: z.string().uuid() });
+
+export const projectWorkingDirectoryRouter = router({
+ associateTopic: write
+ .input(
+ z.object({
+ projectId: z.string(),
+ topicId: z.string(),
+ directoryId: z.string().uuid().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ await assertCanUseTopicTargets(
+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ [input.topicId],
+ );
+ return {
+ data: await ctx.directoryRepo.associateTopic(
+ input.projectId,
+ input.topicId,
+ input.directoryId,
+ ),
+ success: true,
+ };
+ }),
+ createProjectTopic: procedure
+ .use(withScopedPermission('topic:create'))
+ .input(
+ z.object({
+ projectId: z.string(),
+ agentId: z.string(),
+ title: z.string().trim().min(1).max(255),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ await assertCanUseConversationTargets(
+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ [{ agentId: input.agentId }],
+ );
+ if (!(await ctx.projectModel.findManageableById(input.projectId)))
+ throw new Error('Project not found or access denied');
+ const { snapshot } = await resolvePrecreatedTopicSnapshot(
+ ctx.precreatedTopicDeps,
+ input.agentId,
+ );
+ return {
+ data: await ctx.topicModel.create({
+ ...snapshot,
+ agentId: input.agentId,
+ projectId: input.projectId,
+ title: input.title,
+ }),
+ success: true,
+ };
+ }),
+ listProjectTopics: procedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ const data = await ctx.projectModel.listTopics(input.projectId);
+ await assertCanViewTopicTargets(
+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ data.map((topic) => topic.id),
+ );
+ return { data, success: true };
+ }),
+ attachEnvironment: write
+ .input(z.object({ projectId: z.string(), environmentId: z.string().uuid() }))
+ .mutation(async ({ ctx, input }) => ({
+ data: await ctx.projectModel.attachEnvironment(input.projectId, input.environmentId),
+ success: true,
+ })),
+ listEnvironments: procedure
+ .input(z.object({ projectId: z.string().optional() }))
+ .query(async ({ ctx, input }) => ({
+ data: input.projectId
+ ? await ctx.projectModel.listEnvironments(input.projectId)
+ : await ctx.environmentModel.list(),
+ success: true,
+ })),
+ saveEnvironment: write
+ .input(
+ z.object({
+ id: z.string().uuid().optional(),
+ name: z.string().trim().min(1).max(255),
+ repositoryUrl: z.string().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => ({
+ data: await ctx.environmentModel.save(input),
+ success: true,
+ })),
+ bind: write
+ .input(
+ z.object({
+ agentId: z.string().optional(),
+ deviceId: z.string().min(1),
+ environmentId: z.string().uuid().optional(),
+ name: z.string().trim().min(1).max(255),
+ path: z.string().min(1),
+ projectId: z.string().min(1),
+ repositoryUrl: z.string().optional(),
+ topicIds: z.array(z.string()).max(200).optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ if (input.topicIds?.length)
+ await assertCanUseTopicTargets(
+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ input.topicIds,
+ );
+ return { data: await ctx.directoryRepo.bind(input), success: true };
+ }),
+ list: procedure
+ .input(z.object({ projectId: z.string().optional() }))
+ .query(async ({ ctx, input }) => ({
+ data: await ctx.directoryModel.list(input.projectId),
+ success: true,
+ })),
+ listTopics: procedure.input(idInput).query(async ({ ctx, input }) => {
+ const data = await ctx.directoryModel.listTopics(input.id);
+ await assertCanViewTopicTargets(
+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ data.map((topic) => topic.id),
+ );
+ return { data, success: true };
+ }),
+ resolve: procedure.input(idInput).query(async ({ ctx, input }) => ({
+ data: await ctx.directoryModel.resolve(input.id),
+ success: true,
+ })),
+ startTopic: procedure
+ .use(withScopedPermission('topic:create'))
+ .input(idInput.extend({ agentId: z.string(), title: z.string().trim().min(1).max(255) }))
+ .mutation(async ({ ctx, input }) => {
+ await assertCanUseConversationTargets(
+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },
+ [{ agentId: input.agentId }],
+ );
+ const directory = await ctx.directoryModel.resolve(input.id);
+ const [agent] = await ctx.serverDB
+ .select()
+ .from(agents)
+ .where(
+ and(
+ eq(agents.id, input.agentId),
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },
+ agents,
+ ),
+ ),
+ );
+ if (!agent) throw new Error('Agent not found or access denied');
+ if (
+ agent.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
+ agent.agencyConfig.boundDeviceId !== directory.deviceId
+ )
+ throw new Error('This agent is fixed to another execution target');
+ 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',
+ });
+ const { snapshot } = await resolvePrecreatedTopicSnapshot(
+ ctx.precreatedTopicDeps,
+ input.agentId,
+ );
+ return {
+ data: await ctx.topicModel.create({
+ ...snapshot,
+ agentId: input.agentId,
+ // The reasoning snapshot lives in `metadata` too, so merge rather than
+ // replace it with the directory pin.
+ metadata: {
+ ...snapshot.metadata,
+ boundDeviceId: directory.deviceId,
+ workingDirectory: directory.path,
+ workingDirectoryConfig: { path: directory.path },
+ },
+ projectId: directory.projectId,
+ projectWorkingDirectoryId: directory.id,
+ title: input.title,
+ }),
+ 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 a48d367df02..30db522d1d3 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.device.test.ts
@@ -100,6 +100,15 @@ vi.mock('@/database/models/topic', () => ({
}),
}));
+const { mockResolveProjectDirectoryForTopic } = vi.hoisted(() => ({
+ mockResolveProjectDirectoryForTopic: vi.fn().mockResolvedValue(undefined),
+}));
+vi.mock('@/database/models/projectWorkingDirectory', () => ({
+ ProjectWorkingDirectoryModel: vi.fn().mockImplementation(function () {
+ return { resolveForTopic: mockResolveProjectDirectoryForTopic };
+ }),
+}));
+
vi.mock('@/database/models/thread', () => ({
ThreadModel: vi.fn().mockImplementation(function () {
return {
@@ -698,6 +707,52 @@ 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 () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
+ // Deleting the directory row nulls the FK but keeps projectId + the pinned device.
+ topicMock.findById.mockResolvedValue({
+ id: 'topic-1',
+ metadata: { boundDeviceId: 'device-001', workingDirectory: '/repo' },
+ projectId: 'project-1',
+ projectWorkingDirectoryId: null,
+ });
+ mockResolveProjectDirectoryForTopic.mockRejectedValueOnce(
+ new Error('Project directory binding no longer exists'),
+ );
+
+ await expect(
+ service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Keep working',
+ appContext: { topicId: 'topic-1' },
+ }),
+ ).rejects.toThrow('Project directory binding no longer exists');
+
+ expect(mockResolveProjectDirectoryForTopic).toHaveBeenCalledWith('topic-1');
+ expect(mockCreateOperation).not.toHaveBeenCalled();
+ });
+
+ it('does not consult the project resolver for plain device-bound topics', async () => {
+ mockDeviceProxy.isConfigured = true;
+ mockDeviceProxy.queryDeviceList.mockResolvedValue([onlineDevice]);
+ topicMock.findById.mockResolvedValue({
+ id: 'topic-1',
+ metadata: { boundDeviceId: 'device-001' },
+ });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Keep working',
+ appContext: { topicId: 'topic-1' },
+ });
+
+ expect(mockResolveProjectDirectoryForTopic).not.toHaveBeenCalled();
+ expect(mockCreateOperation).toHaveBeenCalled();
+ });
+ });
+
describe('gateway not configured', () => {
it('should never set activeDeviceId when gateway is not configured', async () => {
mockDeviceProxy.isConfigured = false;
diff --git a/apps/server/src/services/aiAgent/__tests__/precreatedTopic.test.ts b/apps/server/src/services/aiAgent/__tests__/precreatedTopic.test.ts
new file mode 100644
index 00000000000..b9f0fbbcd11
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/precreatedTopic.test.ts
@@ -0,0 +1,63 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { resolvePrecreatedTopicSnapshot } from '../pipeline/precreatedTopic';
+
+const { getInfoForAIGeneration, getPreference, isResourceAuthorOrAdmin } = vi.hoisted(() => ({
+ getInfoForAIGeneration: vi.fn(),
+ getPreference: vi.fn(),
+ isResourceAuthorOrAdmin: vi.fn(),
+}));
+
+vi.mock('@/database/models/workspaceUserSettings', () => ({
+ WorkspaceUserSettingsModel: class {
+ getPreference = getPreference;
+ },
+}));
+
+vi.mock('@/database/models/user', () => ({
+ UserModel: { getInfoForAIGeneration },
+}));
+
+vi.mock('@/server/services/resourcePermission', () => ({
+ isResourceAuthorOrAdmin,
+}));
+
+const agentRow = () =>
+ ({
+ agencyConfig: undefined,
+ chatConfig: {},
+ id: 'agent-a',
+ model: 'gpt-4o',
+ plugins: [],
+ provider: 'openai',
+ slug: 'agent-a',
+ systemRole: '',
+ userId: 'user-1',
+ visibility: 'private',
+ }) as never;
+
+const deps = () => ({
+ db: {} as never,
+ resolveAgentConfigOrThrow: async () => agentRow(),
+ userId: 'user-1',
+});
+
+// A topic can be written before `setupTurn` ever runs for it, and `setupTurn`
+// only snapshots the topics it creates itself. Without this snapshot a
+// pre-created row carries neither `model` nor `provider`, so it silently
+// follows every later agent-default change instead of keeping the
+// configuration it was created under.
+describe('resolvePrecreatedTopicSnapshot', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getPreference.mockResolvedValue({});
+ isResourceAuthorOrAdmin.mockResolvedValue(false);
+ getInfoForAIGeneration.mockResolvedValue({ responseLanguage: 'en-US' });
+ });
+
+ it('pins the agent model and provider for the pre-created topic', async () => {
+ const { snapshot } = await resolvePrecreatedTopicSnapshot(deps(), 'agent-a');
+
+ expect(snapshot).toMatchObject({ model: 'gpt-4o', provider: 'openai' });
+ });
+});
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 5555d02f21a..91195361f98 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -76,6 +76,7 @@ import {
import { dispatchHeteroAgent } from './pipeline/heteroDispatch';
import { buildOperationInitRequest, runOperationInit } from './pipeline/operationInit';
import { createHistoryMessagesLoader } from './pipeline/operationPrep';
+import { type PrecreatedTopicDeps, resolvePrecreatedTopicConfig } from './pipeline/precreatedTopic';
import { resolveRunAgentConfig } from './pipeline/resolveRunAgentConfig';
import { traceSendStage } from './pipeline/sendTracing';
import { startOperation } from './pipeline/startOperation';
@@ -439,26 +440,22 @@ export class AiAgentService {
return agentConfig;
}
+ /** Deps shared by every pre-created topic, so its snapshot matches `setupTurn`'s. */
+ private precreatedTopicDeps(): PrecreatedTopicDeps {
+ return {
+ db: this.db,
+ resolveAgentConfigOrThrow: (id) => this.resolveAgentConfigOrThrow(id),
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ };
+ }
+
/** Resolve caller model policy before a pre-created topic permanently pins its model. */
- private async resolvePrecreatedTopicConfig(
+ private resolvePrecreatedTopicConfig(
identifier: string,
overrides?: { model?: string; provider?: string },
) {
- const { agentConfig } = await resolveRunAgentConfig(
- {
- db: this.db,
- resolveAgentConfigOrThrow: (id) => this.resolveAgentConfigOrThrow(id),
- userId: this.userId,
- workspaceId: this.workspaceId,
- },
- {
- identifier,
- modelOverride: overrides?.model,
- providerOverride: overrides?.provider,
- throwIfExecutionAborted: async () => {},
- },
- );
- return agentConfig;
+ return resolvePrecreatedTopicConfig(this.precreatedTopicDeps(), identifier, overrides);
}
/**
diff --git a/apps/server/src/services/aiAgent/pipeline/precreatedTopic.ts b/apps/server/src/services/aiAgent/pipeline/precreatedTopic.ts
new file mode 100644
index 00000000000..31cc1a2509f
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/precreatedTopic.ts
@@ -0,0 +1,75 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { TRPCError } from '@trpc/server';
+
+import type { AgentConfigWithId } from '@/server/services/agent';
+import { AgentService } from '@/server/services/agent';
+
+import { resolveRunAgentConfig } from './resolveRunAgentConfig';
+import { resolveNewTopicSnapshot } from './turnSetup';
+
+/**
+ * A topic can be written before `setupTurn` ever runs for it: a scheduled run,
+ * a group topic, or a project conversation started from a working directory.
+ * `setupTurn` only snapshots the topics it creates itself, so these pre-created
+ * rows must snapshot the agent's effective model / provider / reasoning here —
+ * otherwise they silently follow later agent-default changes instead of keeping
+ * the configuration they were created under.
+ */
+export interface PrecreatedTopicDeps {
+ db: LobeChatDatabase;
+ resolveAgentConfigOrThrow: (identifier: string) => Promise<AgentConfigWithId>;
+ userId: string;
+ workspaceId?: string;
+}
+
+/** Resolve the caller model policy before a pre-created topic permanently pins its model. */
+export const resolvePrecreatedTopicConfig = async (
+ deps: PrecreatedTopicDeps,
+ identifier: string,
+ overrides?: { model?: string; provider?: string },
+): Promise<AgentConfigWithId> => {
+ const { agentConfig } = await resolveRunAgentConfig(deps, {
+ identifier,
+ modelOverride: overrides?.model,
+ providerOverride: overrides?.provider,
+ throwIfExecutionAborted: async () => {},
+ });
+
+ return agentConfig;
+};
+
+/**
+ * The snapshot a pre-created topic must persist. Shared by every pre-creation
+ * path so a topic written ahead of `setupTurn` pins the same
+ * model/provider/reasoning `setupTurn` would have pinned itself.
+ */
+export const resolvePrecreatedTopicSnapshot = async (
+ deps: PrecreatedTopicDeps,
+ identifier: string,
+ overrides?: { model?: string; provider?: string },
+) => {
+ const agentConfig = await resolvePrecreatedTopicConfig(deps, identifier, overrides);
+
+ return {
+ agentConfig,
+ snapshot: await resolveNewTopicSnapshot(deps, agentConfig, overrides),
+ };
+};
+
+/**
+ * Resolver for callers outside the ai-agent service (e.g. a lambda router whose
+ * topic is created before any turn runs). Resolves through the same
+ * {@link AgentService} lookup `AiAgentService` uses, so an agent the caller
+ * cannot see resolves to the same uniform NOT_FOUND.
+ */
+export const createAgentConfigResolver =
+ (db: LobeChatDatabase, userId: string, workspaceId?: string) =>
+ async (identifier: string): Promise<AgentConfigWithId> => {
+ const agentConfig = await new AgentService(db, userId, workspaceId).getAgentConfig(identifier);
+
+ if (!agentConfig) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: `Agent not found: ${identifier}` });
+ }
+
+ return agentConfig;
+ };
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index 9d79b8e4858..a93b01e1cbe 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -22,11 +22,13 @@ import debug from 'debug';
import { AiModelModel } from '@/database/models/aiModel';
import type { MessageModel } from '@/database/models/message';
+import { ProjectWorkingDirectoryModel } from '@/database/models/projectWorkingDirectory';
import type { TopicModel } from '@/database/models/topic';
import { resolveModelExtendParamsForUser } from '@/server/modules/AgentRuntime/adapters/serverCallLlmContextHints';
import type { AgentConfigWithId } from '@/server/services/agent';
import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { shouldSuppressSignal } from '@/server/services/agentSignal/suppressSignal';
+import { deviceGateway } from '@/server/services/deviceGateway';
import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
import { resolveAttachmentsByFileIds } from '@/server/services/file/resolveAttachments';
@@ -602,6 +604,45 @@ 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) {
+ if (shareGate || (botContext && !resolveDeviceAccessPolicy({ botContext }).canUseDevice))
+ throw new Error('Project directory access denied');
+ const directory = await new ProjectWorkingDirectoryModel(
+ deps.db,
+ deps.userId,
+ deps.workspaceId,
+ ).resolveForTopic(topicId);
+ if (!directory) throw new Error('Project directory binding no longer exists');
+ if (
+ agentConfig.agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
+ agentConfig.agencyConfig.boundDeviceId !== directory.deviceId
+ )
+ throw new Error('Agent is fixed to another execution target');
+ const stat = await deviceGateway.statPath({
+ deviceId: directory.deviceId,
+ path: directory.path,
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ });
+ if (!stat?.exists || !stat.isDirectory)
+ throw new Error('Device is offline or working directory is unavailable');
+ resolvedRequestedDeviceId = directory.deviceId;
+ effectiveRequestedDeviceId = directory.deviceId;
+ topicBoundDeviceId = directory.deviceId;
+ agentConfig.agencyConfig = {
+ ...agentConfig.agencyConfig,
+ boundDeviceId: directory.deviceId,
+ executionTarget: 'device',
+ };
+ }
// Fail-closed guard: a non-share run must never operate on a share-visitor
// topic. `findById` is ownership-scoped but deliberately does NOT exclude
@@ -657,8 +698,10 @@ export const setupTurn = async (
const topicPinnedDeviceId = canUseTopicPin
? existingTopic?.metadata?.boundDeviceId
: undefined;
+ // A project-directory topic already routed to its directory's device above.
if (
!requestedDeviceId &&
+ !existingTopic?.projectWorkingDirectoryId &&
topicPinnedDeviceId &&
!isFixedExecutionTargetSelection &&
agentConfig.agencyConfig?.executionTarget !== 'auto'
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 5066fec6844..f70e30e7932 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -1847,7 +1847,10 @@ export class DeviceGateway {
timeout?: number;
userId: string;
workspaceId?: string;
- }): Promise<{ exists: boolean; isDirectory: boolean; repoType?: 'git' | 'github' } | undefined> {
+ }): Promise<
+ | { exists: boolean; isDirectory: boolean; repositoryUrl?: string; repoType?: 'git' | 'github' }
+ | undefined
+ > {
const { userId, deviceId, path, timeout = 8000, workspaceId } = params;
const client = this.getClient();
if (!client) return undefined;
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index 7e0390538fd..60322f6ce96 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -42,6 +42,41 @@
"create.slugLabel": "Slug (optional)",
"create.slugPlaceholder": "my-project",
"create.title": "New project",
+ "directories.add": "Add working directory",
+ "directories.autoFileTopics": "All {{count}} existing topics will be linked to this project.",
+ "directories.bind": "Link to project",
+ "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.chooseAgent": "Choose Agent",
+ "directories.conversations": "Conversations",
+ "directories.coordinator": "Project coordinator",
+ "directories.createProject": "Create a project",
+ "directories.currentFolder": "Current folder",
+ "directories.detectRepository": "Detect GitHub repository",
+ "directories.device": "Select device",
+ "directories.editEnvironment": "Configure environment",
+ "directories.empty": "Link a device directory to start working with an Agent in this project.",
+ "directories.environment": "Environment",
+ "directories.environmentName": "Environment name",
+ "directories.fileTopics": "Also file these {{count}} conversations under this project and device",
+ "directories.keepFiles": "Files stay on {{device}}. Linking only organizes the conversations in this directory.",
+ "directories.name": "Directory name",
+ "directories.newEnvironment": "Create environment",
+ "directories.noConversations": "No conversations in this project yet.",
+ "directories.noEnvironment": "No environment linked",
+ "directories.openProject": "Open project: {{name}}",
+ "directories.path": "Absolute directory path",
+ "directories.project": "Select project",
+ "directories.projectBinding": "Project links",
+ "directories.repository": "GitHub repository URL (optional)",
+ "directories.repositoryHint": "This records the source repository. It does not clone or synchronize files. Do not include credentials.",
+ "directories.sourceSummary": "Existing directory",
+ "directories.start": "Start work here",
+ "directories.startInProject": "Start work in {{name}}",
+ "directories.title": "Working directories",
+ "directories.unavailable": "Device is offline or the directory is unavailable. Reconnect and retry.",
+ "directories.untitled": "Untitled conversation",
"disabled.action": "Enable in Labs",
"disabled.title": "Project workspaces are an Alpha experiment",
"goals.create": "Create goal",
@@ -113,11 +148,64 @@
"sections.home": "Project home",
"sections.knowledgeBases": "Libraries",
"sections.tasks": "Tasks",
+ "settings.addDirectory": "Add folder",
+ "settings.addDirectoryDescription": "Select an environment and a connected device, then enter the full path of an existing folder. Files stay on that device.",
+ "settings.addDirectoryFailed": "Could not add working directory",
+ "settings.addEnvironment": "Add environment",
+ "settings.allEnvironments": "All environments",
+ "settings.configureDirectory": "Add a working directory",
+ "settings.description": "Description",
+ "settings.deviceOffline": "Device disconnected",
+ "settings.deviceOnline": "Device connected",
+ "settings.directoryDescription": "Choose a folder and start a conversation. The Agent will work with files in that folder on the connected device.",
+ "settings.directoryUnavailable": "The device is disconnected or the directory is unavailable. Connect the device and check the path, then retry.",
+ "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",
+ "settings.generalDescription": "Manage the project name, address, and description.",
+ "settings.identifier": "Project identifier",
+ "settings.identifierDescription": "Used in task references. This identifier is set when the project is created.",
+ "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.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.slugDescription": "Used in the project URL. Changing it updates the address; leave blank to use the project ID.",
+ "settings.startDirectoryConversation": "New conversation here",
+ "settings.title": "Project settings",
+ "settings.viewDirectories": "View folders ({{count}})",
+ "settings.workLocations": "Working directories",
"sidebar.agentsEmpty": "No agents are connected yet",
"sidebar.conversationsEmpty": "No project topics yet",
"sidebar.emptyAction": "Create your first project",
"sidebar.librariesEmpty": "No libraries are connected yet",
"sidebar.newConversation": "New conversation",
"sidebar.title": "Projects",
- "sidebar.untitledConversation": "Untitled conversation"
+ "sidebar.untitledConversation": "Untitled conversation",
+ "topics.addLocation": "Add a working directory (optional)",
+ "topics.all": "All topics",
+ "topics.associateFailed": "Could not add conversation to project",
+ "topics.chooseLocation": "Choose a working directory",
+ "topics.chooseTopic": "Choose a topic in the sidebar, or create one to start working",
+ "topics.complete": "Mark completed",
+ "topics.conversationOnly": "Conversation only, without a working directory",
+ "topics.executionContext": "Work location",
+ "topics.gatewayUnavailable": "Enable Agent Gateway before using this project work location.",
+ "topics.group.agent": "By agent",
+ "topics.group.all": "All topics",
+ "topics.group.status": "By status",
+ "topics.groupBy": "Group topics",
+ "topics.notFound": "This topic does not belong to this project, or you do not have access",
+ "topics.resume": "Resume work",
+ "topics.settings": "Settings",
+ "topics.status.active": "Active",
+ "topics.status.archived": "Archived",
+ "topics.status.completed": "Completed",
+ "topics.status.failed": "Failed",
+ "topics.status.running": "Running",
+ "topics.status.scheduled": "Scheduled",
+ "topics.status.unread": "New results",
+ "topics.status.waitingForHuman": "Needs your input",
+ "topics.title": "Topics",
+ "topics.viewProject": "View project"
}
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index 2f68a9e2762..6f1f4c63472 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -42,6 +42,41 @@
"create.slugLabel": "Slug(可选)",
"create.slugPlaceholder": "my-project",
"create.title": "新建项目",
+ "directories.add": "添加工作目录",
+ "directories.autoFileTopics": "此目录已有的 {{count}} 个话题将自动关联到项目。",
+ "directories.bind": "关联项目",
+ "directories.bindDescription": "将下方文件夹绑定到项目,之后即可从项目中继续工作。文件仍保留在当前设备上。",
+ "directories.bindFailed": "目录关联失败",
+ "directories.boundRoot": "此对话已绑定项目工作目录。要使用其他目录,请新建对话。",
+ "directories.chooseAgent": "选择 Agent",
+ "directories.conversations": "已有话题",
+ "directories.coordinator": "项目协调 Agent",
+ "directories.createProject": "创建项目",
+ "directories.currentFolder": "当前文件夹",
+ "directories.detectRepository": "识别 GitHub 仓库",
+ "directories.device": "选择设备",
+ "directories.editEnvironment": "配置环境",
+ "directories.empty": "关联设备目录,即可在此项目下选择 Agent 开始工作。",
+ "directories.environment": "环境",
+ "directories.environmentName": "环境名称",
+ "directories.fileTopics": "同时将这 {{count}} 个话题归入此项目和设备",
+ "directories.keepFiles": "文件保留在 {{device}} 上,关联后将此目录的对话归入项目。",
+ "directories.name": "目录名称",
+ "directories.newEnvironment": "创建环境",
+ "directories.noConversations": "此项目中还没有话题。",
+ "directories.noEnvironment": "未关联环境",
+ "directories.openProject": "前往项目:{{name}}",
+ "directories.path": "目录的绝对路径",
+ "directories.project": "选择项目",
+ "directories.projectBinding": "项目关联",
+ "directories.repository": "GitHub 仓库地址(可选)",
+ "directories.repositoryHint": "此处记录来源仓库,不会克隆或同步文件。请勿填写凭据。",
+ "directories.sourceSummary": "已有目录",
+ "directories.start": "在此开始工作",
+ "directories.startInProject": "在 {{name}} 中开始工作",
+ "directories.title": "工作目录",
+ "directories.unavailable": "设备离线或目录不可用,请重新连接后重试。",
+ "directories.untitled": "未命名话题",
"disabled.action": "前往实验室开启",
"disabled.title": "项目工作空间目前处于 Alpha 阶段",
"goals.create": "新建目标",
@@ -113,11 +148,64 @@
"sections.home": "项目主页",
"sections.knowledgeBases": "资料库",
"sections.tasks": "任务",
+ "settings.addDirectory": "添加文件夹",
+ "settings.addDirectoryDescription": "选择环境和已连接的设备,再填写设备上已有文件夹的完整路径。文件保留在原设备上。",
+ "settings.addDirectoryFailed": "添加工作位置失败",
+ "settings.addEnvironment": "关联环境",
+ "settings.allEnvironments": "全部环境",
+ "settings.configureDirectory": "添加工作目录",
+ "settings.description": "项目说明",
+ "settings.deviceOffline": "设备未连接",
+ "settings.deviceOnline": "设备已连接",
+ "settings.directoryDescription": "选择文件夹,在此新建对话。Agent 将在对应设备上读取和修改该文件夹中的文件。",
+ "settings.directoryUnavailable": "设备未连接或目录不可用。连接设备并检查路径后重试。",
+ "settings.environmentDescription": "用环境管理仓库来源,再添加设备上的文件夹,开始在项目中工作。",
+ "settings.environments": "环境",
+ "settings.general": "基础设置",
+ "settings.generalDescription": "管理项目名称、链接和说明。",
+ "settings.identifier": "项目标识",
+ "settings.identifierDescription": "用于任务编号,创建项目后不可更改。",
+ "settings.noDirectories": "还没有工作目录。添加已连接设备上的文件夹后,即可在此新建对话。",
+ "settings.noEnvironments": "尚未关联环境",
+ "settings.noRepository": "未关联 GitHub 仓库",
+ "settings.reuseEnvironment": "将已有环境添加到本项目",
+ "settings.reuseEnvironmentDescription": "如果之前已创建过环境,可从列表选择,将它的仓库配置关联到本项目,再为本项目添加工作目录。",
+ "settings.slugDescription": "用于项目链接。修改后地址会更新,留空则使用项目 ID。",
+ "settings.startDirectoryConversation": "在此新建对话",
+ "settings.title": "项目设置",
+ "settings.viewDirectories": "查看目录({{count}})",
+ "settings.workLocations": "工作目录",
"sidebar.agentsEmpty": "还没有关联智能体",
"sidebar.conversationsEmpty": "还没有项目话题",
"sidebar.emptyAction": "创建第一个项目",
"sidebar.librariesEmpty": "还没有关联资料库",
"sidebar.newConversation": "新对话",
"sidebar.title": "项目",
- "sidebar.untitledConversation": "未命名对话"
+ "sidebar.untitledConversation": "未命名对话",
+ "topics.addLocation": "添加工作目录(可选)",
+ "topics.all": "全部话题",
+ "topics.associateFailed": "无法将对话归入项目",
+ "topics.chooseLocation": "选择工作目录",
+ "topics.chooseTopic": "从左侧选择话题,或新建话题开始工作",
+ "topics.complete": "标记完成",
+ "topics.conversationOnly": "仅对话,不使用工作目录",
+ "topics.executionContext": "工作位置",
+ "topics.gatewayUnavailable": "此工作位置需要启用 Agent Gateway。请启用后重试。",
+ "topics.group.agent": "按 Agent 分组",
+ "topics.group.all": "全部话题",
+ "topics.group.status": "按状态分组",
+ "topics.groupBy": "话题分组",
+ "topics.notFound": "此话题不属于当前项目,或你没有访问权限",
+ "topics.resume": "恢复工作",
+ "topics.settings": "设置",
+ "topics.status.active": "进行中",
+ "topics.status.archived": "已归档",
+ "topics.status.completed": "已完成",
+ "topics.status.failed": "失败",
+ "topics.status.running": "运行中",
+ "topics.status.scheduled": "已安排",
+ "topics.status.unread": "有新结果",
+ "topics.status.waitingForHuman": "等待你处理",
+ "topics.title": "话题",
+ "topics.viewProject": "查看项目"
}
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index 04cd5ccc34b..79262045758 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -256,6 +256,8 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule
pageShare: rw('chat:read', 'chat:write'),
plugin: rw('agent:read', 'agent:write'),
project: rw('agent:read', 'agent:write'),
+ // project environments and working directories: same agent domain as `project`
+ projectWorkingDirectory: rw('agent:read', 'agent:write'),
pushToken: 'blocked',
ragEval: 'blocked',
recent: rw('chat:read', null),
diff --git a/packages/database/src/models/__tests__/projectWorkingDirectoryBackfill.test.ts b/packages/database/src/models/__tests__/projectWorkingDirectoryBackfill.test.ts
new file mode 100644
index 00000000000..e0b759d42bf
--- /dev/null
+++ b/packages/database/src/models/__tests__/projectWorkingDirectoryBackfill.test.ts
@@ -0,0 +1,172 @@
+// @vitest-environment node
+import { sql } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ type BackfillPool,
+ backfillProjectWorkingDirectoryInstances,
+ SELECT_LEGACY_DIRECTORIES,
+} from '../../../../../scripts/backfillProjectWorkingDirectoryInstancesCore';
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agents,
+ devices,
+ environmentInstances,
+ environments,
+ projectEnvironments,
+ projects,
+ projectWorkingDirectories,
+ users,
+} from '../../schemas';
+import { ProjectWorkingDirectoryModel } from '../projectWorkingDirectory';
+
+const db = await getTestDB();
+const userId = 'backfill-user';
+const projectId = 'backfill-project';
+const model = new ProjectWorkingDirectoryModel(db, userId);
+
+/** The backfill speaks raw SQL; hand it the test database's underlying client. */
+const pool: BackfillPool = {
+ connect: async () => ({
+ query: async (text, params) => (db as any).$client.query(text, params),
+ }),
+};
+
+beforeEach(async () => {
+ await db.insert(users).values({ id: userId });
+ await db.insert(agents).values({ id: 'backfill-coordinator', userId });
+ await db.insert(projects).values({
+ coordinatorAgentId: 'backfill-coordinator',
+ id: projectId,
+ identifier: 'BKF',
+ name: 'Backfill project',
+ userId,
+ });
+});
+afterEach(async () => {
+ await db.delete(projectWorkingDirectories);
+ await db.delete(projectEnvironments);
+ await db.delete(environmentInstances);
+ await db.delete(environments);
+ await db.delete(devices);
+ await db.delete(users);
+});
+
+const insertLegacyDirectory = async (path = '/work/repo') => {
+ const [device] = await db
+ .insert(devices)
+ .values({ deviceId: `device-${path}`, identitySource: 'fallback', platform: 'linux', userId })
+ .returning();
+ const [directory] = await db
+ .insert(projectWorkingDirectories)
+ .values({ addedByUserId: userId, deviceId: device.id, name: 'Repo', path, projectId })
+ .returning();
+ return directory;
+};
+
+describe('backfillProjectWorkingDirectoryInstances', () => {
+ it('upgrades a legacy directory so it resolves through an environment', async () => {
+ const legacy = await insertLegacyDirectory();
+ await expect(model.resolve(legacy.id)).rejects.toThrow();
+
+ const progress = await backfillProjectWorkingDirectoryInstances(pool, {
+ apply: true,
+ batchSize: 10,
+ });
+
+ expect(progress).toMatchObject({ createdInstances: 1, scanned: 1, upgraded: 1 });
+ await expect(model.resolve(legacy.id)).resolves.toMatchObject({ id: legacy.id });
+ });
+
+ it('is a no-op on a second run and leaves a dry run without writes', async () => {
+ await insertLegacyDirectory();
+
+ const dryRun = await backfillProjectWorkingDirectoryInstances(pool, {
+ apply: false,
+ batchSize: 10,
+ });
+ expect(dryRun).toMatchObject({ createdInstances: 1, scanned: 1 });
+ expect(await db.select().from(environmentInstances)).toHaveLength(0);
+
+ await backfillProjectWorkingDirectoryInstances(pool, { apply: true, batchSize: 10 });
+ const rerun = await backfillProjectWorkingDirectoryInstances(pool, {
+ apply: true,
+ batchSize: 10,
+ });
+ expect(rerun.scanned).toBe(0);
+ });
+
+ it('links an existing instance instead of creating another one', async () => {
+ const legacy = await insertLegacyDirectory();
+ const [environment] = await db
+ .insert(environments)
+ .values({ configuration: {}, name: 'Existing', userId })
+ .returning();
+ await db.insert(environmentInstances).values({
+ configurationSnapshot: {},
+ deviceId: legacy.deviceId,
+ environmentId: environment.id,
+ kind: 'device',
+ name: 'Existing',
+ workingDirectory: legacy.path,
+ });
+
+ const progress = await backfillProjectWorkingDirectoryInstances(pool, {
+ apply: true,
+ batchSize: 10,
+ });
+
+ expect(progress).toMatchObject({ createdInstances: 0, upgraded: 1 });
+ expect(await db.select().from(environmentInstances)).toHaveLength(1);
+ await expect(model.resolve(legacy.id)).resolves.toMatchObject({
+ environmentId: environment.id,
+ });
+ });
+
+ // The cursor advances to the last row of each batch, so a scan that drops a
+ // qualifying row from its window strands that row *behind* the cursor: it is
+ // never revisited and the run reports completion anyway. `SKIP LOCKED` used
+ // to do exactly that whenever a row was briefly locked, so the scan must wait
+ // for the lock instead of stepping over it.
+ //
+ // Under the client-db PGlite engine every statement shares one session, so the
+ // lock belongs to the scanning transaction itself and cannot be skipped; the
+ // real assertion needs a node-postgres pool (`TEST_SERVER_DB=1`) where the
+ // holder and the scan run on separate connections.
+ it('keeps a locked row in the cursor window instead of skipping past it', async () => {
+ const a = await insertLegacyDirectory('/work/a');
+ const b = await insertLegacyDirectory('/work/b');
+ const earlier = a.id < b.id ? a : b;
+
+ let markLocked!: () => void;
+ const locked = new Promise<void>((resolve) => {
+ markLocked = resolve;
+ });
+ let releaseLock!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ releaseLock = resolve;
+ });
+
+ const holding = db.transaction(async (tx) => {
+ await tx.execute(
+ sql`SELECT id FROM project_working_directories WHERE id = ${earlier.id} FOR UPDATE`,
+ );
+ markLocked();
+ await gate;
+ });
+
+ await locked;
+
+ const scan = (db as any).$client.query(SELECT_LEGACY_DIRECTORIES, [
+ '00000000-0000-0000-0000-000000000000',
+ 1,
+ ]);
+ // Let the scan reach the locked row before the holder goes away.
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ releaseLock();
+ await holding;
+
+ const { rows } = await scan;
+ expect(rows.map((row: { id: string }) => row.id)).toEqual([earlier.id]);
+ });
+});
diff --git a/packages/device-control/src/types.ts b/packages/device-control/src/types.ts
index c7a485ea644..d17c22fdd4e 100644
--- a/packages/device-control/src/types.ts
+++ b/packages/device-control/src/types.ts
@@ -61,6 +61,7 @@ export interface ListProjectSkillsResult {
export interface StatPathResult {
exists: boolean;
isDirectory: boolean;
+ repositoryUrl?: string;
repoType?: 'git' | 'github';
}
diff --git a/packages/device-control/src/workspace.ts b/packages/device-control/src/workspace.ts
index 80baf8d0130..ac1375e7716 100644
--- a/packages/device-control/src/workspace.ts
+++ b/packages/device-control/src/workspace.ts
@@ -3,7 +3,7 @@ import { access, readdir, readFile, realpath, stat } from 'node:fs/promises';
import * as os from 'node:os';
import path from 'node:path';
-import { detectRepoType } from '@lobechat/local-file-shell/git';
+import { detectGitHubRepository, detectRepoType } from '@lobechat/local-file-shell/git';
import matter from 'gray-matter';
import type {
@@ -267,7 +267,13 @@ export const statPath = async (params: { path: string }): Promise<StatPathResult
const stats = await stat(params.path);
if (!stats.isDirectory()) return { exists: true, isDirectory: false };
const repoType = await detectRepoType(params.path);
- return { exists: true, isDirectory: true, repoType };
+ const repositoryUrl = await detectGitHubRepository(params.path);
+ return {
+ exists: true,
+ isDirectory: true,
+ repoType,
+ ...(repositoryUrl ? { repositoryUrl } : {}),
+ };
} catch {
return { exists: false, isDirectory: false };
}
diff --git a/packages/local-file-shell/src/git/__tests__/repoType.test.ts b/packages/local-file-shell/src/git/__tests__/repoType.test.ts
new file mode 100644
index 00000000000..158b04b184c
--- /dev/null
+++ b/packages/local-file-shell/src/git/__tests__/repoType.test.ts
@@ -0,0 +1,45 @@
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, expect, it } from 'vitest';
+
+import { detectGitHubRepository } from '../repoType';
+
+let root: string;
+beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), 'project-repository-'));
+ await mkdir(path.join(root, '.git'));
+});
+afterEach(async () => {
+ await rm(root, { recursive: true, force: true });
+});
+it.each([
+ '[email protected]:lobehub/lobehub.git',
+ 'https://[email protected]/lobehub/lobehub.git',
+ 'ssh://[email protected]/lobehub/lobehub.git',
+])('returns only repository identity for %s', async (remote) => {
+ await writeFile(path.join(root, '.git/config'), `[remote "origin"]\n url = ${remote}\n`);
+ expect(await detectGitHubRepository(root)).toBe('https://github.com/lobehub/lobehub');
+});
+it('does not use another remote or a look-alike host', async () => {
+ await writeFile(
+ path.join(root, '.git/config'),
+ '[remote "origin"]\n url = https://evilgithub.com/a/b\n[remote "upstream"]\n url = https://github.com/a/b\n',
+ );
+ expect(await detectGitHubRepository(root)).toBeUndefined();
+});
+it('resolves a linked worktree to the common origin', async () => {
+ await writeFile(
+ path.join(root, '.git/config'),
+ '[remote "origin"]\n url = [email protected]:a/b.git\n',
+ );
+ await mkdir(path.join(root, '.git/worktrees/feature'), { recursive: true });
+ await writeFile(path.join(root, '.git/worktrees/feature/commondir'), '../..');
+ await mkdir(path.join(root, 'feature'));
+ await writeFile(
+ path.join(root, 'feature/.git'),
+ `gitdir: ${path.join(root, '.git/worktrees/feature')}`,
+ );
+ expect(await detectGitHubRepository(path.join(root, 'feature'))).toBe('https://github.com/a/b');
+});
diff --git a/packages/local-file-shell/src/git/repoType.ts b/packages/local-file-shell/src/git/repoType.ts
index d32604c7d84..33a7593a3c4 100644
--- a/packages/local-file-shell/src/git/repoType.ts
+++ b/packages/local-file-shell/src/git/repoType.ts
@@ -66,3 +66,33 @@ export const detectRepoType = async (dirPath: string): Promise<'git' | 'github'
return undefined;
}
};
+
+/** Origin's public repository identity. Strip credentials before crossing the device boundary. */
+export const detectGitHubRepository = async (dirPath: string): Promise<string | undefined> => {
+ const commonDir = await resolveCommonGitDir(dirPath);
+ if (!commonDir) return;
+ try {
+ const config = await readFile(path.join(commonDir, 'config'), 'utf8');
+ let inOrigin = false;
+ let raw: string | undefined;
+ for (const entry of config.split('\n')) {
+ const line = entry.trim();
+ if (line.startsWith('[')) inOrigin = line === '[remote "origin"]';
+ if (!inOrigin) continue;
+ const equals = line.indexOf('=');
+ if (equals > 0 && line.slice(0, equals).trim() === 'url') {
+ raw = line.slice(equals + 1).trim();
+ break;
+ }
+ }
+ if (!raw) return;
+ const scp = /^git@github\.com:([\w.-]+\/[\w.-]+)$/.exec(raw);
+ const url = new URL(scp ? `https://github.com/${scp[1]}` : raw);
+ if (url.hostname !== 'github.com' || !['https:', 'ssh:'].includes(url.protocol)) return;
+ const repository = url.pathname.replace(/\/$/, '').replace(/\.git$/, '');
+ if (!/^\/[\w.-]+\/[\w.-]+$/.test(repository)) return;
+ return `https://github.com${repository}`;
+ } catch {
+ return;
+ }
+};
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index 1bd6f68faf8..10df9f8d77d 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -1,4 +1,112 @@
export default {
+ 'directories.currentFolder': 'Current folder',
+ '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 conversation here',
+ 'settings.configureDirectory': 'Add a working directory',
+ 'settings.reuseEnvironment': 'Add an existing environment to this project',
+ 'settings.addDirectoryFailed': 'Could not add working directory',
+ 'settings.identifier': 'Project identifier',
+ 'settings.identifierDescription':
+ 'Used in task references. This identifier is set when the project is created.',
+ 'settings.slugDescription':
+ 'Used in the project URL. Changing it updates the address; leave blank to use the project ID.',
+ 'settings.description': 'Description',
+ 'settings.generalDescription': 'Manage the project name, address, and description.',
+ 'settings.workLocations': 'Working directories',
+ 'settings.directoryDescription':
+ 'Choose a folder and start a conversation. The Agent will work with files in that folder on the connected device.',
+ 'settings.environmentDescription':
+ 'Keep repository sources together in an environment, then add a folder on your device to start working.',
+ 'settings.allEnvironments': 'All environments',
+ 'settings.viewDirectories': 'View folders ({{count}})',
+ 'directories.noEnvironment': 'No environment linked',
+ 'directories.sourceSummary': 'Existing directory',
+ 'directories.keepFiles':
+ 'Files stay on {{device}}. Linking only organizes the conversations in this directory.',
+ 'directories.bindFailed': 'Could not link directory',
+ 'topics.associateFailed': 'Could not add conversation to project',
+ 'topics.chooseLocation': 'Choose a working directory',
+ 'topics.addLocation': 'Add a working directory (optional)',
+
+ 'topics.complete': 'Mark completed',
+ 'topics.resume': 'Resume work',
+ 'topics.gatewayUnavailable': 'Enable Agent Gateway before using this project work location.',
+
+ 'settings.deviceOnline': 'Device connected',
+ 'settings.deviceOffline': 'Device disconnected',
+ 'topics.title': 'Topics',
+ 'topics.groupBy': 'Group topics',
+ 'topics.group.status': 'By status',
+ 'topics.group.all': 'All topics',
+ 'topics.group.agent': 'By agent',
+ 'topics.all': 'All topics',
+ 'topics.executionContext': 'Work location',
+ 'topics.conversationOnly': 'Conversation only, without a working directory',
+ 'topics.chooseTopic': 'Choose a topic in the sidebar, or create one to start working',
+ 'topics.notFound': 'This topic does not belong to this project, or you do not have access',
+ 'topics.viewProject': 'View project',
+ 'topics.settings': 'Settings',
+ 'topics.status.active': 'Active',
+ 'topics.status.running': 'Running',
+ 'topics.status.waitingForHuman': 'Needs your input',
+ 'topics.status.scheduled': 'Scheduled',
+ 'topics.status.failed': 'Failed',
+ 'topics.status.completed': 'Completed',
+ 'topics.status.archived': 'Archived',
+ 'topics.status.unread': 'New results',
+ 'settings.addDirectory': 'Add folder',
+ 'settings.addDirectoryDescription':
+ 'Select an environment and a connected device, then enter the full path of an existing folder. Files stay on that device.',
+ 'settings.directoryUnavailable':
+ '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.',
+ 'settings.general': 'General',
+ 'settings.noRepository': 'No GitHub repository linked',
+ 'settings.noDirectories':
+ 'No folders in this environment yet. Add an existing folder on a connected device to start working.',
+ 'settings.title': 'Project settings',
+ 'settings.environments': 'Environments',
+ 'settings.addEnvironment': 'Add environment',
+ 'settings.noEnvironments': 'No environments associated yet',
+ 'directories.environmentName': 'Environment name',
+ 'directories.editEnvironment': 'Configure environment',
+
+ 'directories.coordinator': 'Project coordinator',
+ 'directories.environment': 'Environment',
+ 'directories.newEnvironment': 'Create environment',
+
+ 'directories.boundRoot':
+ 'This conversation is bound to a project directory. Start a new conversation to use a different directory.',
+ 'directories.detectRepository': 'Detect GitHub repository',
+ 'directories.unavailable':
+ 'Device is offline or the directory is unavailable. Reconnect and retry.',
+
+ 'directories.title': 'Working directories',
+ 'directories.add': 'Add working directory',
+ 'directories.bind': 'Link to project',
+ 'directories.bindDescription':
+ 'Link the folder below to a project so you can continue working from that project. Files stay on the current device.',
+ 'directories.project': 'Select project',
+ 'directories.device': 'Select device',
+ 'directories.path': 'Absolute directory path',
+ 'directories.name': 'Directory name',
+ 'directories.repository': 'GitHub repository URL (optional)',
+ 'directories.repositoryHint':
+ 'This records the source repository. It does not clone or synchronize files. Do not include credentials.',
+ 'directories.fileTopics': 'Also file these {{count}} conversations under this project and device',
+ 'directories.createProject': 'Create a project',
+ 'directories.empty': 'Link a device directory to start working with an Agent in this project.',
+ 'directories.start': 'Start work here',
+ 'directories.chooseAgent': 'Choose Agent',
+ 'directories.conversations': 'Conversations',
+ 'directories.noConversations': 'No conversations in this project yet.',
+ 'directories.untitled': 'Untitled conversation',
+ 'directories.openProject': 'Open project: {{name}}',
+ 'directories.startInProject': 'Start work in {{name}}',
+ 'directories.projectBinding': 'Project links',
+
'acceptance.actions.accept': 'Accept completion',
'acceptance.actions.reject': 'Request changes',
'acceptance.actions.reopen': 'Reopen project',
diff --git a/packages/utils/src/client/topic.test.ts b/packages/utils/src/client/topic.test.ts
index 391d9fe7f92..c38c3ad4d46 100644
--- a/packages/utils/src/client/topic.test.ts
+++ b/packages/utils/src/client/topic.test.ts
@@ -574,3 +574,24 @@ describe('groupTopicsByStatus', () => {
expect(result.map((g) => g.id)).toEqual(['pending']);
});
});
+
+it('keeps project directory bindings and device identities separate', () => {
+ const base = { createdAt: 1, updatedAt: 1, title: 'Work' };
+ const topics: ChatTopic[] = [
+ {
+ ...base,
+ id: 'a',
+ projectWorkingDirectoryId: 'directory-a',
+ metadata: { workingDirectory: '/repo' },
+ },
+ {
+ ...base,
+ id: 'b',
+ projectWorkingDirectoryId: 'directory-b',
+ metadata: { workingDirectory: '/repo' },
+ },
+ { ...base, id: 'c', metadata: { workingDirectory: '/repo', boundDeviceId: 'device-a' } },
+ { ...base, id: 'd', metadata: { workingDirectory: '/repo', boundDeviceId: 'device-b' } },
+ ];
+ expect(groupTopicsByProject(topics, 'updatedAt')).toHaveLength(4);
+});
diff --git a/packages/utils/src/client/topic.ts b/packages/utils/src/client/topic.ts
index 84464ef8d8e..3458741642d 100644
--- a/packages/utils/src/client/topic.ts
+++ b/packages/utils/src/client/topic.ts
@@ -202,7 +202,12 @@ export const groupTopicsByProject = (
for (const topic of topics) {
const normalized = getTopicWorkingDirectorySourcePath(topic) ?? '';
- const id = normalized ? `${PROJECT_GROUP_PREFIX}${normalized}` : NO_PROJECT_GROUP_ID;
+ const deviceId = topic.metadata?.boundDeviceId;
+ const id = topic.projectWorkingDirectoryId
+ ? `project-directory:${topic.projectWorkingDirectoryId}`
+ : normalized
+ ? `${PROJECT_GROUP_PREFIX}${deviceId ? `${deviceId}:` : ''}${normalized}`
+ : NO_PROJECT_GROUP_ID;
const existing = groupsMap.get(id);
if (existing) {
existing.children.push(topic);
diff --git a/scripts/backfillProjectWorkingDirectoryInstances.ts b/scripts/backfillProjectWorkingDirectoryInstances.ts
new file mode 100644
index 00000000000..aff9ed738b2
--- /dev/null
+++ b/scripts/backfillProjectWorkingDirectoryInstances.ts
@@ -0,0 +1,47 @@
+/**
+ * Backfill legacy project_working_directories rows into the environment model,
+ * so they resolve through an environment instance linked to their project.
+ * See backfillProjectWorkingDirectoryInstancesCore.ts for the upgrade rules.
+ *
+ * Dry-run by default; pass --apply to write. Idempotent and resumable.
+ *
+ * bunx tsx scripts/backfillProjectWorkingDirectoryInstances.ts
+ * bunx tsx scripts/backfillProjectWorkingDirectoryInstances.ts --apply --batch-size=100
+ */
+import pg from 'pg';
+
+import { backfillProjectWorkingDirectoryInstances } from './backfillProjectWorkingDirectoryInstancesCore';
+
+const { Pool } = pg;
+
+const DEFAULT_BATCH_SIZE = 100;
+
+const args = new Set(process.argv.slice(2));
+const apply = args.has('--apply');
+const batchSizeArg = process.argv.find((arg) => arg.startsWith('--batch-size='));
+const batchSize = batchSizeArg
+ ? Number.parseInt(batchSizeArg.slice('--batch-size='.length), 10)
+ : DEFAULT_BATCH_SIZE;
+
+if (!Number.isInteger(batchSize) || batchSize < 1 || batchSize > 1000) {
+ throw new Error('--batch-size must be an integer between 1 and 1000');
+}
+
+const connectionString = process.env.DATABASE_URL;
+if (!connectionString) throw new Error('DATABASE_URL is required');
+
+const pool = new Pool({ connectionString });
+
+backfillProjectWorkingDirectoryInstances(pool, {
+ apply,
+ batchSize,
+ onBatch: (progress) => console.log(JSON.stringify({ apply, ...progress })),
+})
+ .then((progress) => console.log(JSON.stringify({ apply, complete: true, ...progress })))
+ .catch((error) => {
+ console.error(error);
+ process.exitCode = 1;
+ })
+ .finally(async () => {
+ await pool.end();
+ });
diff --git a/scripts/backfillProjectWorkingDirectoryInstancesCore.ts b/scripts/backfillProjectWorkingDirectoryInstancesCore.ts
new file mode 100644
index 00000000000..4821de44db3
--- /dev/null
+++ b/scripts/backfillProjectWorkingDirectoryInstancesCore.ts
@@ -0,0 +1,178 @@
+/**
+ * Upgrade legacy project_working_directories rows into the environment model.
+ *
+ * A directory resolves through its natural key: the environment_instances row
+ * for (device_id, path) whose environment is linked to the directory's project
+ * via project_environments. A legacy row is one where that chain is missing.
+ * For each one this:
+ * 1. reuses the instance for (device_id, path), or creates it together with
+ * a minimal parent environment;
+ * 2. links the project to that environment (project_environments).
+ *
+ * Rows whose device is gone (device_id NULL or dangling) can never execute —
+ * ProjectWorkingDirectoryModel.resolve already rejects them — and are deleted.
+ *
+ * Idempotent: an upgraded row satisfies the natural-key chain and is no longer
+ * selected; the id cursor keeps a dry run from revisiting rows.
+ *
+ * The cursor scan deliberately does NOT use `SKIP LOCKED`. Skipping a locked
+ * row would still return later rows, so the cursor would advance past the
+ * skipped one and the row would be stranded behind it — never upgraded, while
+ * the run still reports completion. Waiting for the lock instead keeps the
+ * scanned window gap-free, so the backfill always converges.
+ */
+
+export interface BackfillQueryClient {
+ query: <T = Record<string, unknown>>(text: string, params?: unknown[]) => Promise<{ rows: T[] }>;
+ release?: () => void;
+}
+
+export interface BackfillPool {
+ connect: () => Promise<BackfillQueryClient>;
+}
+
+export interface BackfillOptions {
+ apply: boolean;
+ batchSize: number;
+ onBatch?: (progress: BackfillProgress & { cursor: string }) => void;
+}
+
+export interface BackfillProgress {
+ createdEnvironments: number;
+ createdInstances: number;
+ removedOrphans: number;
+ scanned: number;
+ upgraded: number;
+}
+
+interface LegacyRow {
+ addedByUserId: string | null;
+ deviceId: string | null;
+ id: string;
+ name: string;
+ path: string;
+ projectId: string;
+ projectUserId: string;
+ projectWorkspaceId: string | null;
+ workspaceId: string | null;
+}
+
+export const SELECT_LEGACY_DIRECTORIES = `
+ SELECT pwd.id, pwd.project_id AS "projectId", pwd.device_id AS "deviceId",
+ pwd.path, pwd.name, pwd.workspace_id AS "workspaceId",
+ pwd.added_by_user_id AS "addedByUserId",
+ p.user_id AS "projectUserId", p.workspace_id AS "projectWorkspaceId"
+ FROM project_working_directories pwd
+ INNER JOIN projects p ON p.id = pwd.project_id
+ WHERE pwd.id > $1
+ AND NOT EXISTS (
+ SELECT 1
+ FROM environment_instances ei
+ INNER JOIN project_environments pe
+ ON pe.environment_id = ei.environment_id AND pe.project_id = pwd.project_id
+ WHERE ei.device_id = pwd.device_id AND ei.working_directory = pwd.path
+ )
+ ORDER BY pwd.id
+ LIMIT $2
+ FOR UPDATE OF pwd
+`;
+
+export const backfillProjectWorkingDirectoryInstances = async (
+ pool: BackfillPool,
+ { apply, batchSize, onBatch }: BackfillOptions,
+): Promise<BackfillProgress> => {
+ let cursor = '00000000-0000-0000-0000-000000000000';
+ const progress: BackfillProgress = {
+ createdEnvironments: 0,
+ createdInstances: 0,
+ removedOrphans: 0,
+ scanned: 0,
+ upgraded: 0,
+ };
+
+ while (true) {
+ const client = await pool.connect();
+
+ try {
+ await client.query('BEGIN');
+
+ const { rows } = await client.query<LegacyRow>(SELECT_LEGACY_DIRECTORIES, [
+ cursor,
+ batchSize,
+ ]);
+
+ if (rows.length === 0) {
+ await client.query('COMMIT');
+ break;
+ }
+
+ for (const row of rows) {
+ progress.scanned += 1;
+
+ const device = row.deviceId
+ ? await client.query<{ id: string }>('SELECT id FROM devices WHERE id = $1', [
+ row.deviceId,
+ ])
+ : { rows: [] };
+
+ if (!row.deviceId || device.rows.length === 0) {
+ if (apply)
+ await client.query('DELETE FROM project_working_directories WHERE id = $1', [row.id]);
+ progress.removedOrphans += 1;
+ continue;
+ }
+
+ const existingInstance = await client.query<{ environmentId: string; id: string }>(
+ `SELECT id, environment_id AS "environmentId"
+ FROM environment_instances
+ WHERE device_id = $1 AND working_directory = $2`,
+ [row.deviceId, row.path],
+ );
+
+ let instance = existingInstance.rows[0];
+ if (!instance && apply) {
+ const environment = await client.query<{ id: string }>(
+ `INSERT INTO environments (name, user_id, workspace_id, configuration)
+ VALUES ($1, $2, $3, '{}') RETURNING id`,
+ [row.name, row.projectUserId, row.projectWorkspaceId],
+ );
+ progress.createdEnvironments += 1;
+ const created = await client.query<{ id: string }>(
+ `INSERT INTO environment_instances
+ (environment_id, name, kind, device_id, working_directory, configuration_snapshot)
+ VALUES ($1, $2, 'device', $3, $4, '{}') RETURNING id`,
+ [environment.rows[0].id, row.name, row.deviceId, row.path],
+ );
+ progress.createdInstances += 1;
+ instance = { environmentId: environment.rows[0].id, id: created.rows[0].id };
+ } else if (!instance) {
+ // Dry-run: an instance (and its environment) would be created.
+ progress.createdInstances += 1;
+ progress.createdEnvironments += 1;
+ }
+
+ if (apply && instance) {
+ await client.query(
+ `INSERT INTO project_environments (project_id, environment_id, workspace_id, added_by_user_id)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT DO NOTHING`,
+ [row.projectId, instance.environmentId, row.workspaceId, row.addedByUserId],
+ );
+ }
+ progress.upgraded += 1;
+ }
+
+ await client.query('COMMIT');
+
+ cursor = rows.at(-1)!.id;
+ onBatch?.({ ...progress, cursor });
+ } catch (error) {
+ await client.query('ROLLBACK');
+ throw error;
+ } finally {
+ client.release?.();
+ }
+ }
+
+ return progress;
+};
diff --git a/src/features/AgentSidebar/Topic/List/Item/Actions.tsx b/src/features/AgentSidebar/Topic/List/Item/Actions.tsx
index 67865a13522..e21965e50b3 100644
--- a/src/features/AgentSidebar/Topic/List/Item/Actions.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/Actions.tsx
@@ -7,8 +7,8 @@ import { useOverlayDropdownPortalProps } from '@/features/NavPanel/OverlayContai
import { type TopicItemDropdownMenuProps, useTopicItemDropdownMenu } from './useDropdownMenu';
-const Actions = memo<TopicItemDropdownMenuProps>(({ fav, id, status, title }) => {
- const { dropdownMenu } = useTopicItemDropdownMenu({ fav, id, status, title });
+const Actions = memo<TopicItemDropdownMenuProps>(({ completionLabel, fav, id, status, title }) => {
+ const { dropdownMenu } = useTopicItemDropdownMenu({ completionLabel, fav, id, status, title });
const dropdownPortalProps = useOverlayDropdownPortalProps();
return (
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
index 7c161e98a15..8d7186b3770 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
@@ -5,8 +5,12 @@ import { render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { TopicListScopeContext } from '../../TopicListScope';
import TopicItem from './index';
+const scopedTopicMock = vi.hoisted(() => ({
+ value: undefined as { agentId: string; agentAvatar: string; agentName: string } | undefined,
+}));
const useTopicNavigationMock = vi.hoisted(() => vi.fn());
const prefetchMessagesMock = vi.hoisted(() => vi.fn());
const activeTopicIdMock = vi.hoisted(() => ({ value: undefined as string | undefined }));
@@ -41,6 +45,8 @@ vi.mock('motion/react-m', () => ({
),
}));
+vi.mock('../../useScopedTopics', () => ({ useScopedTopic: () => scopedTopicMock.value }));
+
vi.mock('@/const/version', () => ({ isDesktop: false }));
vi.mock('@/features/NavPanel/components/NavItem', () => ({
default: ({
@@ -81,8 +87,12 @@ vi.mock('@/routes/(main)/agent/channel/const', () => ({
vi.mock('@/store/agent', () => ({
// `agentMap` is read by `agentSelectors.currentAgentVisibility`.
useAgentStore: (
- selector: (state: { activeAgentId: string; agentMap: Record<string, unknown> }) => unknown,
- ) => selector({ activeAgentId: 'agt_test', agentMap: {} }),
+ selector: (state: {
+ activeAgentId: string;
+ agentMap: Record<string, unknown>;
+ builtinAgentIdMap: Record<string, string>;
+ }) => unknown,
+ ) => selector({ activeAgentId: 'agt_test', agentMap: {}, builtinAgentIdMap: {} }),
}));
vi.mock('@/store/chat', () => {
const useChatStore = (
@@ -149,6 +159,7 @@ vi.mock('../../TopicListContent/ThreadList', () => ({
describe('TopicItem active state', () => {
afterEach(() => {
+ scopedTopicMock.value = undefined;
prefetchMessagesMock.mockClear();
activeTopicIdMock.value = undefined;
agentRuntimeRunningMock.value = false;
@@ -158,6 +169,36 @@ describe('TopicItem active state', () => {
vi.useRealTimers();
});
+ it('renders the Project row Agent avatar and keeps its link in the Project', () => {
+ scopedTopicMock.value = {
+ agentId: 'other-agent',
+ agentAvatar: '/avatars/other.png',
+ agentName: 'Other Agent',
+ };
+ useTopicNavigationMock.mockReturnValue({
+ isInAgentSubRoute: false,
+ isInTopicContextRoute: true,
+ routeTopicId: 'project-topic',
+ urlTopicId: 'project-topic',
+ focusTopicPopup: vi.fn(),
+ navigateToTopic: vi.fn(),
+ });
+ render(
+ <TopicListScopeContext value={{ projectId: 'project-1' }}>
+ <TopicItem id="project-topic" title="Project work" />
+ </TopicListScopeContext>,
+ );
+ expect(screen.getByRole('img', { name: 'Other Agent' })).toHaveAttribute(
+ 'src',
+ '/avatars/other.png',
+ );
+ expect(screen.getByTestId('nav-item')).toHaveAttribute(
+ 'data-href',
+ '/team/project/project-1/conversation/project-topic',
+ );
+ expect(screen.getByTestId('nav-item')).toHaveAttribute('data-active', 'true');
+ });
+
it('keeps the current topic highlighted on topic page sub-routes', () => {
useTopicNavigationMock.mockReturnValue({
isInAgentSubRoute: true,
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsx
index 5a7d45f2f09..ddd70c99fef 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx
@@ -1,4 +1,4 @@
-import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
+import { AGENT_CHAT_TOPIC_URL, DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@lobechat/const';
import type { ChatTopicMetadata, ChatTopicStatus } from '@lobechat/types';
import { formatElapsedClockTime } from '@lobechat/utils';
import {
@@ -16,6 +16,7 @@ import { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } fro
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import Avatar from '@/components/Avatar';
import DotsLoading from '@/components/DotsLoading';
import { TOPIC_STATUS_VISUALS } from '@/components/ExecutionStatus';
import RingLoadingIcon from '@/components/RingLoading';
@@ -26,12 +27,13 @@ import DirIcon from '@/features/ChatInput/ControlBar/DirIcon';
import { useHasDraft } from '@/features/ChatInput/draftStorage';
import { startTopicDrag } from '@/features/ChatInput/InputEditor/ReferTopic/topicDragData';
import NavItem from '@/features/NavPanel/components/NavItem';
+import { getProjectConversationPath } from '@/features/Projects/Layout/navigation';
import TopicCreatorAvatar, { useTopicCreator } from '@/features/TopicCreatorAvatar';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { getWorkingDirectoryName } from '@/helpers/workingDirectoryPath';
import { getPlatformIcon } from '@/routes/(main)/agent/channel/const';
import { useAgentStore } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/selectors';
+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
@@ -39,6 +41,8 @@ import { useElectronStore } from '@/store/electron';
import { useTopicNavigation } from '../../hooks/useTopicNavigation';
import ThreadList from '../../TopicListContent/ThreadList';
+import { useTopicListScope } from '../../TopicListScope';
+import { useScopedTopic } from '../../useScopedTopics';
import Actions from './Actions';
import TopicItemContextMenu from './ContextMenu';
import {
@@ -254,15 +258,19 @@ const TopicItemRow = memo<TopicItemRowProps>(
navRef,
showThreadList,
}) => {
+ const scopedTopic = useScopedTopic(id);
+ const scope = useTopicListScope();
+ const inboxId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const { t } = useTranslation('topic');
const { isDarkMode } = useTheme();
// Rows render by the dozen, so agent-level reads share ONE subscription.
// Only workspace-shared (`public`) agents get the creator avatar — a
// workspace-private agent's topics all belong to the viewer.
- const [activeAgentId, isSharedAgent] = useAgentStore((s) => [
+ const [fallbackAgentId, isSharedAgent] = useAgentStore((s) => [
s.activeAgentId,
agentSelectors.currentAgentVisibility(s) === 'public',
]);
+ const activeAgentId = scopedTopic?.agentId ?? fallbackAgentId;
const activeWorkspaceSlug = useActiveWorkspaceSlug();
// Creator of the topic — resolves only inside an active workspace; drives
// the identity-first icon layout below.
@@ -275,8 +283,13 @@ const TopicItemRow = memo<TopicItemRowProps>(
// Construct href for cmd+click support
const href = useMemo(() => {
if (!activeAgentId || !id) return undefined;
- return buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(activeAgentId, id), activeWorkspaceSlug);
- }, [activeAgentId, activeWorkspaceSlug, id]);
+ return buildWorkspaceAwarePath(
+ scope
+ ? getProjectConversationPath(scope.projectId, id)
+ : AGENT_CHAT_TOPIC_URL(activeAgentId, id),
+ activeWorkspaceSlug,
+ );
+ }, [activeAgentId, activeWorkspaceSlug, id, scope]);
const [isLoading, isUnreadCompleted, hasLocalRunningRuntime, isRuntimeVisiblyRunning] =
useChatStore((s) => [
@@ -320,6 +333,11 @@ const TopicItemRow = memo<TopicItemRowProps>(
const handleDoubleClick = useCallback(async () => {
if (!id || !activeAgentId || !isDesktop) return;
cancelPendingSingleClick();
+ if (scope && href) {
+ useElectronStore.getState().addTab(href);
+ void navRef.current.navigateToTopic(id);
+ return;
+ }
if (await navRef.current.focusTopicPopup(id)) {
void navRef.current.navigateToTopic(id, { skipPopupFocus: true });
return;
@@ -330,7 +348,7 @@ const TopicItemRow = memo<TopicItemRowProps>(
buildWorkspaceAwarePath(AGENT_CHAT_TOPIC_URL(activeAgentId, id), activeWorkspaceSlug),
);
void navRef.current.navigateToTopic(id);
- }, [id, activeAgentId, activeWorkspaceSlug, navRef]);
+ }, [id, activeAgentId, activeWorkspaceSlug, navRef, scope, href]);
const isFailed = status === 'failed';
const isRunning = status === 'running';
@@ -535,7 +553,17 @@ const TopicItemRow = memo<TopicItemRowProps>(
// shrinks into a bottom-right corner badge. Personal mode keeps the
// original layout untouched.
const ownIconNode = statusIconNode ?? identityIconNode;
- const leadingIconNode = author ? (
+ const leadingIconNode = scopedTopic ? (
+ <Avatar
+ name={scopedTopic.agentName || scopedTopic.agentTitle || undefined}
+ size={20}
+ title={scopedTopic.agentName || scopedTopic.agentTitle || undefined}
+ avatar={
+ scopedTopic.agentAvatar ||
+ (activeAgentId === inboxId ? DEFAULT_INBOX_AVATAR : DEFAULT_AVATAR)
+ }
+ />
+ ) : author ? (
<TopicCreatorAvatar corner={ownIconNode} userId={userId} />
) : (
(ownIconNode ?? idleIconPlaceholder)
@@ -555,6 +583,7 @@ const TopicItemRow = memo<TopicItemRowProps>(
titleColor={cssVar.colorText}
extra={
<>
+ {scopedTopic && ownIconNode}
<TopicMigrationIndicator agentId={activeAgentId} topicId={id} />
{/* Gated on the SAME boolean that draws the running ring: both say
"this row is visibly running", and a row that stopped spinning
@@ -628,6 +657,7 @@ TopicItemRow.displayName = 'TopicItemRow';
*/
const TopicItem = memo<TopicItemProps>((props) => {
const { id } = props;
+ const scope = useTopicListScope();
const {
focusTopicPopup,
navigateToTopic,
@@ -655,9 +685,9 @@ const TopicItem = memo<TopicItemProps>((props) => {
{...props}
defaultTopicActive={Boolean(active && !isInAgentSubRoute && !isInTopicContextRoute)}
navRef={navRef}
- showThreadList={Boolean(id && id === urlTopicId)}
+ showThreadList={Boolean(!scope && id && id === urlTopicId)}
isTopicActive={Boolean(
- (active || isRouteTopicActive) &&
+ (scope ? isRouteTopicActive : active || isRouteTopicActive) &&
!hasActiveThread &&
(!isInAgentSubRoute || isRouteTopicActive),
)}
diff --git a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.test.tsx b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.test.tsx
index 078f412e325..3a392eda3af 100644
--- a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.test.tsx
@@ -7,6 +7,29 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildTopicPrompt } from './buildTopicPrompt';
import { useTopicItemDropdownMenu } from './useDropdownMenu';
+const locationFixture = vi.hoisted(() => ({ pathname: '/project/project-1/conversation/topic-1' }));
+const removeMock = vi.hoisted(() => vi.fn());
+const confirmDeleteMock = vi.hoisted(() => vi.fn());
+vi.mock('@/features/DeleteTopicConfirm', () => ({ confirmRemoveTopic: confirmDeleteMock }));
+vi.mock('@/hooks/useActiveLocation', () => ({ useActiveLocation: () => locationFixture }));
+
+const scopeFixture = vi.hoisted(() => ({ enabled: false }));
+const refreshProjectMock = vi.hoisted(() => vi.fn());
+const navigateMock = vi.hoisted(() => vi.fn());
+const autoRenameMock = vi.hoisted(() => vi.fn());
+const favoriteMock = vi.hoisted(() => vi.fn());
+const completeMock = vi.hoisted(() => vi.fn());
+const cloneMock = vi.hoisted(() => vi.fn());
+vi.mock('../../useScopedTopics', () => ({
+ useScopedTopic: () =>
+ scopeFixture.enabled ? { id: 'topic-1', agentId: 'agent-other' } : undefined,
+ useScopedTopics: () => ({
+ scope: scopeFixture.enabled ? { projectId: 'project-1' } : null,
+ refresh: refreshProjectMock,
+ }),
+}));
+vi.mock('@/services/topic', () => ({ topicService: { cloneTopic: cloneMock } }));
+
const permissionMock = vi.hoisted(() => ({
create_content: true,
edit_own_content: true,
@@ -53,7 +76,7 @@ vi.mock('@/features/ShareModal', () => ({
}));
vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
- useWorkspaceAwareNavigate: () => vi.fn(),
+ useWorkspaceAwareNavigate: () => navigateMock,
}));
vi.mock('@/hooks/useAppOrigin', () => ({
@@ -75,12 +98,12 @@ vi.mock('@/store/agent', () => ({
vi.mock('@/store/chat', () => ({
useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
selector({
- autoRenameTopicTitle: vi.fn(),
+ autoRenameTopicTitle: autoRenameMock,
duplicateTopic: vi.fn(),
- favoriteTopic: vi.fn(),
- markTopicCompleted: vi.fn(),
- removeTopic: vi.fn(),
- unmarkTopicCompleted: vi.fn(),
+ favoriteTopic: favoriteMock,
+ markTopicCompleted: completeMock,
+ removeTopic: removeMock,
+ unmarkTopicCompleted: completeMock,
updateTopicTitle: vi.fn(),
}),
}));
@@ -102,6 +125,8 @@ const getMenuItem = (
describe('useTopicItemDropdownMenu', () => {
beforeEach(() => {
+ scopeFixture.enabled = false;
+ vi.clearAllMocks();
permissionMock.create_content = true;
permissionMock.edit_own_content = true;
versionMock.isDesktop = false;
@@ -156,6 +181,89 @@ describe('useTopicItemDropdownMenu', () => {
expect(writeText.mock.calls[0][0]).toContain('lh topic view topic-1 -L 500 --workspace ws_1');
});
+ it.each([
+ ['/team/project/project-1/conversation/topic-1', true],
+ ['/project/project-1/conversation/topic-other', false],
+ ['/project/project-1/settings', false],
+ ])(
+ 'after deleting a Project row at %s, navigates home only for the current Topic',
+ async (pathname, shouldNavigate) => {
+ scopeFixture.enabled = true;
+ locationFixture.pathname = pathname;
+ const { result } = renderHook(() =>
+ useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic' }),
+ );
+ const item = getMenuItem(result.current.dropdownMenu(), 'delete');
+ if (!item || !('onClick' in item)) throw new Error('Missing delete');
+ item.onClick?.({} as never);
+ await confirmDeleteMock.mock.calls[0][0].onConfirm(false);
+ expect(removeMock).toHaveBeenCalledWith('topic-1', false);
+ expect(refreshProjectMock).toHaveBeenCalledOnce();
+ if (shouldNavigate) expect(navigateMock).toHaveBeenCalledWith('/project/project-1');
+ else expect(navigateMock).not.toHaveBeenCalled();
+ },
+ );
+
+ it('copies the row Agent link even when another Agent is active', async () => {
+ scopeFixture.enabled = true;
+ const writeText = vi.fn();
+ vi.spyOn(navigator, 'clipboard', 'get').mockReturnValue({ writeText } as unknown as Clipboard);
+ const { result } = renderHook(() =>
+ useTopicItemDropdownMenu({ id: 'topic-1', title: 'Other agent topic' }),
+ );
+ const item = getMenuItem(result.current.dropdownMenu(), 'copyLink');
+ if (!item || !('onClick' in item)) throw new Error('Missing copy link');
+ await item.onClick?.({} as never);
+ expect(writeText).toHaveBeenCalledWith('https://example.com/agent/agent-other/topic-1');
+ });
+
+ it.each(['favorite', 'markCompleted'])(
+ 'refreshes the Project list immediately after %s',
+ async (key) => {
+ scopeFixture.enabled = true;
+ const { result } = renderHook(() =>
+ useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic' }),
+ );
+ const item = getMenuItem(result.current.dropdownMenu(), key);
+ if (!item || !('onClick' in item)) throw new Error('Missing mutation');
+ await item.onClick?.({} as never);
+ expect(refreshProjectMock).toHaveBeenCalledOnce();
+ },
+ );
+
+ it('auto-renames using messages from the row Agent', async () => {
+ scopeFixture.enabled = true;
+ const { result } = renderHook(() =>
+ useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic' }),
+ );
+ const item = getMenuItem(result.current.dropdownMenu(), 'autoRename');
+ if (!item || !('onClick' in item)) throw new Error('Missing auto rename');
+ await item.onClick?.({} as never);
+ expect(autoRenameMock).toHaveBeenCalledWith('topic-1', 'agent-other');
+ expect(refreshProjectMock).toHaveBeenCalledOnce();
+ });
+
+ it('duplicates a Project topic without requiring an Agent sidebar cache', async () => {
+ scopeFixture.enabled = true;
+ cloneMock.mockResolvedValue('topic-copy');
+ const { result } = renderHook(() =>
+ useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic' }),
+ );
+ const item = getMenuItem(result.current.dropdownMenu(), 'duplicate');
+ if (!item || !('onClick' in item)) throw new Error('Missing duplicate');
+ await item.onClick?.({} as never);
+ expect(cloneMock).toHaveBeenCalled();
+ expect(refreshProjectMock).toHaveBeenCalledOnce();
+ expect(navigateMock).toHaveBeenCalledWith('/project/project-1/conversation/topic-copy');
+ });
+
+ it('keeps project association out of the individual topic menu', () => {
+ const { result } = renderHook(() =>
+ useTopicItemDropdownMenu({ id: 'topic-1', title: 'Topic' }),
+ );
+ expect(getMenuItem(result.current.dropdownMenu(), 'associate-project')).toBeUndefined();
+ });
+
it('groups desktop topic actions by intent', () => {
versionMock.isDesktop = true;
diff --git a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
index 72b5fd50021..df6ea763b11 100644
--- a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -32,21 +32,26 @@ import { isDesktop } from '@/const/version';
import { createMoveTopicsModal } from '@/features/AgentTopicManager/MoveTopicsModal';
import { createTopicForwardModal } from '@/features/Conversation/MessageForward/TopicForwardModal';
import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';
+import { getProjectConversationPath } from '@/features/Projects/Layout/navigation';
import { openShareModal } from '@/features/ShareModal';
import { openTopicDoctorModal } from '@/features/TopicDoctorModal';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
+import { useActiveLocation } from '@/hooks/useActiveLocation';
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { usePermission } from '@/hooks/usePermission';
+import { topicService } from '@/services/topic';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
import { useElectronStore } from '@/store/electron';
import { useGlobalStore } from '@/store/global';
import { isForbiddenError } from '@/utils/forbiddenError';
+import { useScopedTopic, useScopedTopics } from '../../useScopedTopics';
import { buildTopicPrompt } from './buildTopicPrompt';
export interface TopicItemDropdownMenuProps {
+ completionLabel?: string;
fav?: boolean;
id?: string;
status?: ChatTopicStatus | null;
@@ -54,6 +59,7 @@ export interface TopicItemDropdownMenuProps {
}
export const useTopicItemDropdownMenu = ({
+ completionLabel,
fav,
id,
status,
@@ -63,13 +69,18 @@ export const useTopicItemDropdownMenu = ({
const navigate = useWorkspaceAwareNavigate();
const activeWorkspaceId = useActiveWorkspaceId();
+ const { pathname } = useActiveLocation();
+ const routeTopicId = pathname.match(/\/project\/[^/]+\/conversation\/([^/]+)\/?$/)?.[1];
const activeWorkspaceSlug = useActiveWorkspaceSlug();
const { allowed: canCreateTopic } = usePermission('create_content');
const { allowed: canEditTopic } = usePermission('edit_own_content');
const openTopicInNewWindow = useGlobalStore((s) => s.openTopicInNewWindow);
const openTopicInPortal = useChatStore((s) => s.openTopicInPortal);
- const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const scopedTopic = useScopedTopic(id);
+ const { scope, refresh } = useScopedTopics();
+ const fallbackAgentId = useAgentStore((s) => s.activeAgentId);
+ const activeAgentId = scopedTopic?.agentId ?? fallbackAgentId;
const addTab = useElectronStore((s) => s.addTab);
const appOrigin = useAppOrigin();
@@ -106,13 +117,13 @@ export const useTopicItemDropdownMenu = ({
disabled: !canEditTopic,
icon: <Icon icon={isCompleted ? ArchiveRestore : Archive} />,
key: 'markCompleted',
- label: isCompleted ? t('actions.unmarkCompleted') : t('actions.markCompleted'),
- onClick: () => {
- if (isCompleted) {
- unmarkTopicCompleted(id);
- } else {
- markTopicCompleted(id);
- }
+ label:
+ completionLabel ??
+ (isCompleted ? t('actions.unmarkCompleted') : t('actions.markCompleted')),
+ onClick: async () => {
+ if (isCompleted) await unmarkTopicCompleted(id);
+ else await markTopicCompleted(id);
+ if (scope) await refresh();
},
sfSymbol: isCompleted ? 'tray.and.arrow.up' : 'archivebox',
},
@@ -121,8 +132,9 @@ export const useTopicItemDropdownMenu = ({
icon: <Icon icon={Star} />,
key: 'favorite',
label: fav ? t('actions.unfavorite') : t('actions.favorite'),
- onClick: () => {
- favoriteTopic(id, !fav);
+ onClick: async () => {
+ await favoriteTopic(id, !fav);
+ if (scope) await refresh();
},
sfSymbol: fav ? 'star.slash' : 'star',
},
@@ -134,8 +146,9 @@ export const useTopicItemDropdownMenu = ({
icon: <Icon icon={Wand2} />,
key: 'autoRename',
label: t('actions.autoRename'),
- onClick: () => {
- autoRenameTopicTitle(id);
+ onClick: async () => {
+ await autoRenameTopicTitle(id, scopedTopic?.agentId ?? undefined);
+ if (scope) await refresh();
},
sfSymbol: 'wand.and.stars',
},
@@ -151,6 +164,7 @@ export const useTopicItemDropdownMenu = ({
onSave: async (newTitle) => {
try {
await updateTopicTitle(id, newTitle);
+ if (scope) await refresh();
} catch (error) {
toast.error(
isForbiddenError(error)
@@ -255,8 +269,20 @@ export const useTopicItemDropdownMenu = ({
icon: <Icon icon={LucideCopy} />,
key: 'duplicate',
label: t('actions.duplicate'),
- onClick: () => {
- duplicateTopic(id);
+ onClick: async () => {
+ if (!scope) return duplicateTopic(id);
+ const loadingToast = toast.loading(t('duplicateLoading', { ns: 'topic' }));
+ try {
+ const newId = await topicService.cloneTopic(
+ id,
+ t('duplicateTitle', { ns: 'chat', title }),
+ );
+ await refresh();
+ navigate(getProjectConversationPath(scope.projectId, newId));
+ toast.success(t('duplicateSuccess', { ns: 'topic' }));
+ } finally {
+ loadingToast.close();
+ }
},
},
{
@@ -303,6 +329,10 @@ export const useTopicItemDropdownMenu = ({
onConfirm: async (removeFiles) => {
try {
await removeTopic(id, removeFiles);
+ if (scope) {
+ if (routeTopicId === id) navigate(`/project/${scope.projectId}`);
+ await refresh();
+ }
} catch (error) {
toast.error(
isForbiddenError(error)
@@ -318,9 +348,14 @@ export const useTopicItemDropdownMenu = ({
},
].filter(Boolean) as MenuProps['items'];
}, [
+ routeTopicId,
+ scope,
+ scopedTopic,
+ refresh,
id,
fav,
isCompleted,
+ completionLabel,
title,
canCreateTopic,
canEditTopic,
diff --git a/src/features/AgentSidebar/Topic/List/index.test.tsx b/src/features/AgentSidebar/Topic/List/index.test.tsx
index 6f7891b5eda..7f2fabb95fd 100644
--- a/src/features/AgentSidebar/Topic/List/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/index.test.tsx
@@ -87,6 +87,7 @@ vi.mock('@/store/chat', () => ({
}));
vi.mock('@/store/chat/selectors', () => ({
+ operationSelectors: { visiblyRunningTopicIds: () => [] },
topicSelectors: {
currentTopicLength: (state: { topicLength: number }) => state.topicLength,
displayTopicsForSidebar: () => (state: typeof chatStoreStateMock) => state.topics,
@@ -114,11 +115,13 @@ vi.mock('@/store/user', () => ({
}));
vi.mock('@/store/user/selectors', () => ({
+ authSelectors: { isLoaded: () => true },
preferenceSelectors: {
topicIncludeCompleted: (state: { topicIncludeCompleted: boolean }) =>
state.topicIncludeCompleted,
topicSortBy: (state: { topicSortBy: string }) => state.topicSortBy,
},
+ userProfileSelectors: { userId: () => 'test-user-id' },
}));
vi.mock('../AllTopicsDrawer', () => ({
diff --git a/src/features/AgentSidebar/Topic/ToggleGroups.tsx b/src/features/AgentSidebar/Topic/ToggleGroups.tsx
index 556e7e14e7f..f6d9ff70e43 100644
--- a/src/features/AgentSidebar/Topic/ToggleGroups.tsx
+++ b/src/features/AgentSidebar/Topic/ToggleGroups.tsx
@@ -13,6 +13,7 @@ import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
import { useAgentTopicGroupMode } from './hooks/useAgentTopicGroupMode';
+import { useScopedSidebarTopics } from './useScopedTopics';
const ToggleGroups = memo(() => {
const { t } = useTranslation('topic');
@@ -31,7 +32,14 @@ const ToggleGroups = memo(() => {
),
[topicPageSize, topicSortBy, topicGroupMode, topicIncludeCompleted],
);
- const groupTopics = useChatStore(groupSelector, isEqual);
+ const agentGroups = useChatStore(groupSelector, isEqual);
+ const scoped = useScopedSidebarTopics(
+ topicPageSize,
+ topicSortBy,
+ topicGroupMode,
+ topicIncludeCompleted,
+ );
+ const groupTopics = scoped.scope ? scoped.groups : agentGroups;
const groupIds = useMemo(() => groupTopics.map((group) => group.id), [groupTopics]);
const { expandedKeys, setExpandedKeys } = useTopicGroupCollapse(topicGroupMode, groupIds);
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
index 68745e38aa4..0b89c781517 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
@@ -5,6 +5,7 @@ import { AccordionRoot } from '@lobehub/ui/base-ui';
import { fireEvent, render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { TopicListScopeContext } from '../../TopicListScope';
import GroupItem from './GroupItem';
const commitAgentDefaultMock = vi.hoisted(() => vi.fn());
@@ -14,6 +15,31 @@ const routeParamsMock = vi.hoisted(() => ({ aid: 'agent-1' as string | undefined
const agentStoreStateMock = vi.hoisted(() => ({ activeAgentId: 'agent-1' as string | undefined }));
const activeWorkspaceSlugMock = vi.hoisted(() => ({ value: 'lobehub' as string | null }));
+const directoryRows = vi.hoisted(
+ () =>
+ [] as Array<{
+ id: string;
+ projectName: string;
+ projectSlug: string;
+ projectId: string;
+ projectAvatar: string;
+ }>,
+);
+vi.mock('@/store/projectWorkingDirectory', () => ({
+ useProjectDirectoryStore: (selector: (state: unknown) => unknown) =>
+ selector({ useFetchDirectories: () => ({ hasData: true }) }),
+ useProjectDirectories: () => directoryRows,
+}));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => routerPushMock,
+}));
+
+vi.mock('@/features/Projects/WorkingDirectories/AgentDirectoryActions', () => ({
+ AgentDirectoryActions: ({ onLegacyStart }: { onLegacyStart: () => Promise<void> }) => (
+ <button aria-label="actions.addNewTopicInProject:project" onClick={onLegacyStart} />
+ ),
+}));
+
vi.mock('react-router', () => ({
useParams: () => routeParamsMock,
}));
@@ -96,6 +122,7 @@ vi.mock('../../List/Item', () => ({
describe('Project topic group item', () => {
beforeEach(() => {
+ directoryRows.length = 0;
commitAgentDefaultMock.mockReset();
switchTopicMock.mockReset();
routerPushMock.mockReset();
@@ -173,3 +200,111 @@ describe('Project topic group item', () => {
expect(commitAgentDefaultMock).toHaveBeenCalledWith('/Users/me/project');
});
});
+
+it('uses the bound project name and lets the user jump directly to that project', () => {
+ directoryRows.push({
+ id: 'binding-1',
+ projectName: 'Shared Project',
+ projectSlug: 'shared-project',
+ projectId: 'prj-1',
+ projectAvatar: '📦',
+ });
+ render(
+ <AccordionRoot defaultValue={['project:/repo']}>
+ <GroupItem
+ expanded
+ group={{
+ id: 'project:/repo',
+ title: 'repo',
+ children: [
+ {
+ id: 'topic-1',
+ title: 'Work',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ projectWorkingDirectoryId: 'binding-1',
+ metadata: { workingDirectory: '/repo' },
+ },
+ ],
+ }}
+ />
+ </AccordionRoot>,
+ );
+ fireEvent.click(screen.getByRole('link', { name: 'Shared Project' }));
+ expect(routerPushMock).toHaveBeenCalledWith('/project/shared-project');
+});
+
+it('keeps the workspace scope in the project link and leaves modified clicks to the browser', () => {
+ activeWorkspaceSlugMock.value = 'lobehub';
+ routerPushMock.mockClear();
+ directoryRows.push({
+ id: 'binding-2',
+ projectName: 'Workspace Project',
+ projectSlug: 'workspace-project',
+ projectId: 'prj-2',
+ projectAvatar: '📦',
+ });
+ render(
+ <AccordionRoot defaultValue={['project:/repo-ws']}>
+ <GroupItem
+ expanded
+ group={{
+ id: 'project:/repo-ws',
+ title: 'repo-ws',
+ children: [
+ {
+ id: 'topic-ws',
+ title: 'Work',
+ createdAt: 1,
+ updatedAt: 1,
+ projectWorkingDirectoryId: 'binding-2',
+ metadata: { workingDirectory: '/repo-ws' },
+ },
+ ],
+ }}
+ />
+ </AccordionRoot>,
+ );
+ const link = screen.getByRole('link', { name: 'Workspace Project' });
+ expect(link).toHaveAttribute('href', '/lobehub/project/workspace-project');
+
+ // fireEvent returns false when the default action was prevented.
+ expect(fireEvent.click(link, { metaKey: true })).toBe(true);
+ expect(fireEvent.click(link, { ctrlKey: true })).toBe(true);
+ expect(routerPushMock).not.toHaveBeenCalled();
+});
+
+it('shows the directory title inside Project scope rather than repeating the project name', () => {
+ directoryRows.push({
+ id: 'binding-scoped',
+ projectName: 'Shared Project',
+ projectSlug: 'shared-project',
+ projectId: 'prj-1',
+ projectAvatar: '📦',
+ });
+ render(
+ <TopicListScopeContext value={{ projectId: 'prj-1' }}>
+ <AccordionRoot defaultValue={['project:/repo-a']}>
+ <GroupItem
+ expanded
+ group={{
+ id: 'project:/repo-a',
+ title: 'repo-a',
+ children: [
+ {
+ id: 'topic-scoped',
+ title: 'Work',
+ createdAt: 1,
+ updatedAt: 1,
+ projectWorkingDirectoryId: 'binding-scoped',
+ metadata: { workingDirectory: '/repo-a' },
+ },
+ ],
+ }}
+ />
+ </AccordionRoot>
+ </TopicListScopeContext>,
+ );
+ expect(screen.getByText('repo-a')).toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'Shared Project' })).not.toBeInTheDocument();
+});
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
index 4254c7ae919..02819818d4f 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx
@@ -6,33 +6,35 @@ import {
AccordionPanel,
accordionStyles,
AccordionTrigger,
- ActionIcon,
Text,
} from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import isEqual from 'fast-deep-equal';
-import { FolderClosedIcon, FolderOpenIcon, type LucideIcon, PlusIcon } from 'lucide-react';
+import { FolderClosedIcon, FolderOpenIcon, type LucideIcon } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import Avatar from '@/components/Avatar';
import { TOPIC_STATUS_VISUALS } from '@/components/ExecutionStatus';
import RingLoadingIcon from '@/components/RingLoading';
import UnreadDot from '@/components/UnreadDot';
-import { isDesktop } from '@/const/version';
import { useCommitWorkingDirectory } from '@/features/ChatInput/ControlBar/useCommitWorkingDirectory';
-import { resolveExecutionTarget } from '@/helpers/executionTarget';
-import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
+import { AgentDirectoryActions } from '@/features/Projects/WorkingDirectories/AgentDirectoryActions';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useActiveLocation } from '@/hooks/useActiveLocation';
import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { useAgentStore } from '@/store/agent';
-import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
+import { useProjectDirectories, useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+import { getTopicWorkingDirectorySourcePath } from '@/utils/client/topic';
import { buildPrefixedAgentRoutePath, parseAgentPathname } from '../../../utils/agentPathname';
import TopicItem from '../../List/Item';
+import { useTopicListScope } from '../../TopicListScope';
import { type GroupItemComponentProps } from '../GroupedAccordion';
import {
getProjectTopicStatusCounts,
@@ -165,12 +167,21 @@ const CollapsedUnreadDot = memo<{ count: number }>(({ count }) => {
CollapsedUnreadDot.displayName = 'CollapsedProjectUnreadDot';
const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
- const { t } = useTranslation('topic');
const { id, title, children } = group;
+ const scope = useTopicListScope();
+ const navigate = useWorkspaceAwareNavigate();
+ useProjectDirectoryStore((s) => s.useFetchDirectories)(
+ undefined,
+ !!children[0]?.projectWorkingDirectoryId,
+ );
+ const directories = useProjectDirectories();
+ const project = directories.find((d) => d.id === children[0]?.projectWorkingDirectoryId);
const workingDirectory = useMemo(
- () => (id.startsWith(PROJECT_GROUP_PREFIX) ? id.slice(PROJECT_GROUP_PREFIX.length) : undefined),
- [id],
+ () =>
+ (children[0] ? getTopicWorkingDirectorySourcePath(children[0]) : undefined) ??
+ (id.startsWith(PROJECT_GROUP_PREFIX) ? id.slice(PROJECT_GROUP_PREFIX.length) : undefined),
+ [id, children],
);
const agentId = useAgentStore((s) => s.activeAgentId);
@@ -181,13 +192,6 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
const currentAgentId = targetAgentId ?? agentId;
const router = useQueryRoute();
const activeWorkspaceSlug = useActiveWorkspaceSlug();
- const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(currentAgentId ?? ''));
- const isHeterogeneous = useAgentStore((s) =>
- currentAgentId ? agentByIdSelectors.isAgentHeterogeneousById(currentAgentId)(s) : false,
- );
- const isWorkspaceAgent = useAgentStore((s) =>
- currentAgentId ? agentByIdSelectors.isWorkspaceAgentById(currentAgentId)(s) : false,
- );
const { commitAgentDefault } = useCommitWorkingDirectory(currentAgentId ?? '');
const handleAddTopic = useCallback(async () => {
@@ -210,17 +214,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
activeWorkspaceSlug,
]);
- // Web can add a topic in a directory too when the agent targets a bound
- // device — the write goes to `workingDirByDevice`, no Electron dependency.
- const deviceRoutingAvailable = useIsGatewayModeEnabled(currentAgentId);
- const effectiveTarget = resolveExecutionTarget(agencyConfig, {
- clientExecutionAvailable: isDesktop,
- deviceRoutingAvailable,
- isHetero: isHeterogeneous,
- workspaceScoped: isWorkspaceAgent,
- });
- const isDeviceMode = effectiveTarget === 'device' && !!agencyConfig?.boundDeviceId;
- const canAddTopic = (isDesktop || isDeviceMode) && !!workingDirectory;
+ const canAddTopic = !scope && !!currentAgentId && !!workingDirectory;
const statusCounts = useChatStore(
(s) => getProjectTopicStatusCounts(children, operationSelectors.visiblyRunningTopicIds(s)),
@@ -239,15 +233,11 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
{hasCollapsedUnread && <CollapsedUnreadDot count={unreadCount} />}
{canAddTopic && (
<span className={hasCollapsedIndicators ? styles.addTopicAction : undefined}>
- <ActionIcon
- icon={PlusIcon}
- size={'small'}
- title={t('actions.addNewTopicInProject', { directory: title })}
- tooltipProps={{ placement: 'right' }}
- onClick={(e) => {
- e.stopPropagation();
- void handleAddTopic();
- }}
+ <AgentDirectoryActions
+ agentId={currentAgentId!}
+ path={workingDirectory!}
+ topics={children}
+ onLegacyStart={handleAddTopic}
/>
</span>
)}
@@ -259,15 +249,54 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {
<AccordionHeader className={'accordion-header'}>
<AccordionTrigger style={{ paddingBlock: 4, paddingInline: 4 }}>
<Flexbox horizontal align="center" gap={8} height={24} style={{ overflow: 'hidden' }}>
- <Center flex={'none'} height={24} width={28}>
- <Icon
- color={cssVar.colorTextTertiary}
- icon={ProjectFolderIcon}
- size={{ size: 15, strokeWidth: 1.5 }}
- />
+ <Center flex="none" height={24} width={28}>
+ {project ? (
+ <Avatar
+ avatar={project.projectAvatar || undefined}
+ name={project.projectName}
+ size={18}
+ />
+ ) : (
+ <Icon
+ color={cssVar.colorTextTertiary}
+ icon={ProjectFolderIcon}
+ size={{ size: 15, strokeWidth: 1.5 }}
+ />
+ )}
</Center>
- <Text ellipsis fontSize={14} style={{ color: cssVar.colorTextSecondary, flex: 1 }}>
- {title}
+ <Text
+ ellipsis
+ fontSize={14}
+ style={{ color: project ? cssVar.colorText : cssVar.colorTextSecondary, flex: 1 }}
+ >
+ {project && !scope ? (
+ <a
+ style={{ color: 'inherit', textDecoration: 'none' }}
+ href={buildWorkspaceAwarePath(
+ `/project/${project.projectSlug ?? project.projectId}`,
+ activeWorkspaceSlug,
+ )}
+ onClick={(event) => {
+ // Keep the accordion closed either way; leave modified clicks
+ // (new tab / window) to the browser's native link handling.
+ event.stopPropagation();
+ if (
+ event.button !== 0 ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
+ event.altKey
+ )
+ return;
+ event.preventDefault();
+ navigate(`/project/${project.projectSlug ?? project.projectId}`);
+ }}
+ >
+ {project.projectName}
+ </a>
+ ) : (
+ title
+ )}
</Text>
</Flexbox>
</AccordionTrigger>
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
index c5e2b8d6989..01056c24c6b 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
@@ -18,6 +18,7 @@ import { preferenceSelectors } from '@/store/user/selectors';
import { useScrollActiveTopicIntoView } from '../../hooks/useScrollActiveTopicIntoView';
import { useNavigateToAgentTopics } from '../../hooks/useTopicNavigation';
import TopicItem from '../../List/Item';
+import { useScopedSidebarTopics } from '../../useScopedTopics';
const FlatMode = memo(() => {
const { t } = useTranslation('chat');
@@ -26,17 +27,20 @@ const FlatMode = memo(() => {
const topicSortBy = useUserStore(preferenceSelectors.topicSortBy);
const topicIncludeCompleted = useUserStore(preferenceSelectors.topicIncludeCompleted);
- const [hasMore, isExpandingPageSize, activeAgentId, activeTopicId] = useChatStore((s) => [
+ const [hasMore, isExpandingPageSize, activeAgentId, agentActiveTopicId] = useChatStore((s) => [
topicSelectors.hasMoreTopicsForSidebar(s),
topicSelectors.isExpandingPageSize(s),
s.activeAgentId,
s.activeTopicId,
]);
- const activeTopicList = useChatStore(
+ const agentTopicList = useChatStore(
topicSelectors.displayTopicsForSidebar(topicPageSize, topicSortBy, topicIncludeCompleted),
isEqual,
);
+ const scoped = useScopedSidebarTopics(topicPageSize, topicSortBy, 'flat', topicIncludeCompleted);
+ const activeTopicList = scoped.scope ? scoped.topics : agentTopicList;
+ const activeTopicId = scoped.scope ? scoped.activeTopicId : agentActiveTopicId;
const renderedTopicIds = useMemo(
() => activeTopicList?.map((topic) => topic.id).join(':') ?? '',
[activeTopicList],
@@ -57,8 +61,11 @@ const FlatMode = memo(() => {
userId={topic.userId}
/>
))}
- {isExpandingPageSize && <SkeletonList rows={3} />}
- {hasMore && !isExpandingPageSize && activeAgentId && (
+ {scoped.scope && scoped.hasMore && (
+ <NavItem icon={MoreHorizontal} title={t('topic.viewAll')} onClick={scoped.loadMore} />
+ )}
+ {!scoped.scope && isExpandingPageSize && <SkeletonList rows={3} />}
+ {!scoped.scope && hasMore && !isExpandingPageSize && activeAgentId && (
<NavItem
icon={MoreHorizontal}
title={t('topic.viewAll')}
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx b/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx
index 8db64706633..358da6f8b6d 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/GroupedAccordion.tsx
@@ -21,6 +21,7 @@ import { type GroupedTopic } from '@/types/topic';
import { useAgentTopicGroupMode } from '../hooks/useAgentTopicGroupMode';
import { useScrollActiveTopicIntoView } from '../hooks/useScrollActiveTopicIntoView';
import { useNavigateToAgentTopics } from '../hooks/useTopicNavigation';
+import { useScopedSidebarTopics } from '../useScopedTopics';
export interface GroupItemComponentProps {
expanded: boolean;
@@ -39,7 +40,7 @@ const GroupedAccordion = memo<GroupedAccordionProps>(({ GroupItem }) => {
const topicIncludeCompleted = useUserStore(preferenceSelectors.topicIncludeCompleted);
const { topicGroupMode } = useAgentTopicGroupMode();
- const [hasMore, isExpandingPageSize, activeAgentId, activeTopicId] = useChatStore((s) => [
+ const [hasMore, isExpandingPageSize, activeAgentId, agentActiveTopicId] = useChatStore((s) => [
topicSelectors.hasMoreTopicsForSidebar(s),
topicSelectors.isExpandingPageSize(s),
s.activeAgentId,
@@ -56,8 +57,16 @@ const GroupedAccordion = memo<GroupedAccordionProps>(({ GroupItem }) => {
),
[topicPageSize, topicSortBy, topicGroupMode, topicIncludeCompleted],
);
- const groupTopics = useChatStore(groupSelector, isEqual);
+ const agentGroups = useChatStore(groupSelector, isEqual);
+ const scoped = useScopedSidebarTopics(
+ topicPageSize,
+ topicSortBy,
+ topicGroupMode,
+ topicIncludeCompleted,
+ );
+ const groupTopics = scoped.scope ? scoped.groups : agentGroups;
+ const activeTopicId = scoped.scope ? scoped.activeTopicId : agentActiveTopicId;
const groupIds = useMemo(() => groupTopics.map((group) => group.id), [groupTopics]);
const { expandedKeys, setExpandedKeys } = useTopicGroupCollapse(topicGroupMode, groupIds);
const activeGroupId = useMemo(
@@ -100,8 +109,11 @@ const GroupedAccordion = memo<GroupedAccordionProps>(({ GroupItem }) => {
<GroupItem expanded={expandedKeys.includes(group.id)} group={group} key={group.id} />
))}
</AccordionRoot>
- {isExpandingPageSize && <SkeletonList rows={3} />}
- {hasMore && !isExpandingPageSize && activeAgentId && (
+ {scoped.scope && scoped.hasMore && (
+ <NavItem icon={MoreHorizontal} title={t('topic.viewAll')} onClick={scoped.loadMore} />
+ )}
+ {!scoped.scope && isExpandingPageSize && <SkeletonList rows={3} />}
+ {!scoped.scope && hasMore && !isExpandingPageSize && activeAgentId && (
<NavItem
icon={MoreHorizontal}
title={t('topic.viewAll')}
diff --git a/src/features/AgentSidebar/Topic/TopicListScope.tsx b/src/features/AgentSidebar/Topic/TopicListScope.tsx
new file mode 100644
index 00000000000..b07bb2a77d2
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListScope.tsx
@@ -0,0 +1,5 @@
+import { createContext, use } from 'react';
+
+/** Host identity keeps the shared list inside its Project route and data scope. */
+export const TopicListScopeContext = createContext<{ projectId: string } | null>(null);
+export const useTopicListScope = () => use(TopicListScopeContext);
diff --git a/src/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode.ts b/src/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode.ts
index 95a1028f9d8..076f640580f 100644
--- a/src/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode.ts
+++ b/src/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode.ts
@@ -6,9 +6,12 @@ import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
import type { TopicGroupMode } from '@/types/topic';
+import { useTopicListScope } from '../TopicListScope';
import { resolveAgentTopicGroupMode } from '../utils/topicGroupMode';
export const useAgentTopicGroupMode = () => {
+ const scope = useTopicListScope();
+ const updatePreference = useUserStore((s) => s.updatePreference);
const agentType = useAgentStore(agentSelectors.currentAgentHeterogeneousProviderType);
const agentTopicGroupMode = useAgentStore(
(s) => agentSelectors.currentAgentConfig(s)?.chatConfig?.topicGroupMode,
@@ -16,17 +19,20 @@ export const useAgentTopicGroupMode = () => {
const updateAgentChatConfig = useAgentStore((s) => s.updateAgentChatConfig);
const globalMode = useUserStore(preferenceSelectors.topicGroupMode);
- const topicGroupMode = resolveAgentTopicGroupMode({
- agentTopicGroupMode,
- agentType,
- globalMode,
- });
+ const topicGroupMode = scope
+ ? globalMode
+ : resolveAgentTopicGroupMode({
+ agentTopicGroupMode,
+ agentType,
+ globalMode,
+ });
const updateTopicGroupMode = useCallback(
async (mode: TopicGroupMode) => {
- await updateAgentChatConfig({ topicGroupMode: mode });
+ if (scope) await updatePreference({ topicGroupMode: mode });
+ else await updateAgentChatConfig({ topicGroupMode: mode });
},
- [updateAgentChatConfig],
+ [scope, updateAgentChatConfig, updatePreference],
);
return useMemo(
diff --git a/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.test.tsx b/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.test.tsx
index ace1f215a6b..0e5efaba515 100644
--- a/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.test.tsx
+++ b/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.test.tsx
@@ -4,6 +4,7 @@
import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { TopicListScopeContext } from '../TopicListScope';
import { useNavigateToAgentTopics, useTopicNavigation } from './useTopicNavigation';
const switchTopicMock = vi.hoisted(() => vi.fn());
@@ -67,6 +68,20 @@ describe('useTopicNavigation', () => {
workspaceStoreStateMock.activeWorkspaceId = null;
});
+ it('keeps project topics in their project route instead of switching the active Agent', async () => {
+ pathnameMock.mockReturnValue('/project/project-1/settings');
+ workspaceStoreStateMock.activeWorkspaceId = 'workspace-1';
+ const { result } = renderHook(() => useTopicNavigation(), {
+ wrapper: ({ children }) => (
+ <TopicListScopeContext value={{ projectId: 'project-1' }}>{children}</TopicListScopeContext>
+ ),
+ });
+ await act(async () => result.current.navigateToTopic('topic-other-agent'));
+ expect(pushMock).toHaveBeenCalledWith('/team/project/project-1/conversation/topic-other-agent');
+ expect(switchTopicMock).not.toHaveBeenCalled();
+ expect(focusTopicPopupMock).not.toHaveBeenCalled();
+ });
+
it('focuses the popup and still navigates back to the chat route when the topic is detached', async () => {
pathnameMock.mockReturnValue('/agent/agent-1/profile');
focusTopicPopupMock.mockResolvedValue(true);
diff --git a/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.ts b/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.ts
index 5794fbb49a5..6e1073f2470 100644
--- a/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.ts
+++ b/src/features/AgentSidebar/Topic/hooks/useTopicNavigation.ts
@@ -3,7 +3,9 @@ import { useCallback, useMemo } from 'react';
import urlJoin from 'url-join';
import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { getProjectConversationPath } from '@/features/Projects/Layout/navigation';
import { useFocusTopicPopup } from '@/features/TopicPopupGuard/useTopicPopupsRegistry';
+import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';
import { useActiveLocation } from '@/hooks/useActiveLocation';
import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
import { useQueryRoute } from '@/hooks/useQueryRoute';
@@ -11,6 +13,7 @@ import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
import { buildPrefixedAgentRoutePath, parseAgentPathname } from '../../utils/agentPathname';
+import { useTopicListScope } from '../TopicListScope';
/**
* Hook to handle topic navigation with automatic route detection
@@ -21,6 +24,7 @@ interface NavigateToTopicOptions {
}
export const useTopicNavigation = () => {
+ const scope = useTopicListScope();
const { pathname } = useActiveLocation();
const agentRoute = useMemo(() => parseAgentPathname(pathname), [pathname]);
const params = useActiveRouteParams<{ aid?: string; topicId?: string }>();
@@ -59,6 +63,16 @@ export const useTopicNavigation = () => {
const navigateToTopic = useCallback(
async (topicId?: string, options?: NavigateToTopicOptions) => {
+ if (scope && topicId) {
+ router.push(
+ buildWorkspaceAwarePath(
+ getProjectConversationPath(scope.projectId, topicId),
+ activeWorkspaceSlug,
+ ),
+ );
+ toggleConfig(false);
+ return;
+ }
if (!options?.skipPopupFocus) {
await focusTopicPopup(topicId);
}
@@ -80,6 +94,7 @@ export const useTopicNavigation = () => {
toggleConfig(false);
},
[
+ scope,
activeWorkspaceSlug,
agentRoute,
focusTopicPopup,
@@ -94,7 +109,7 @@ export const useTopicNavigation = () => {
return {
focusTopicPopup,
isInAgentSubRoute: isInAgentSubRoute(),
- isInTopicContextRoute: isInTopicContextRoute(),
+ isInTopicContextRoute: !!scope || isInTopicContextRoute(),
navigateToTopic,
routeTopicId,
urlTopicId,
diff --git a/src/features/AgentSidebar/Topic/useScopedTopics.test.ts b/src/features/AgentSidebar/Topic/useScopedTopics.test.ts
new file mode 100644
index 00000000000..4f527396ab5
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/useScopedTopics.test.ts
@@ -0,0 +1,109 @@
+/** @vitest-environment happy-dom */
+import { renderHook } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TopicListScopeContext } from './TopicListScope';
+import { useScopedSidebarTopics } from './useScopedTopics';
+
+const fixture = vi.hoisted(() => ({ topicId: undefined as string | undefined }));
+const rows = [
+ {
+ id: 'old',
+ title: 'Old',
+ agentId: 'agent-a',
+ createdAt: 10,
+ updatedAt: 40,
+ status: 'active',
+ favorite: false,
+ },
+ {
+ id: 'new',
+ title: 'New',
+ agentId: 'agent-b',
+ createdAt: 30,
+ updatedAt: 30,
+ status: 'failed',
+ favorite: false,
+ },
+ {
+ id: 'star',
+ title: 'Favorite',
+ agentId: 'agent-a',
+ createdAt: 5,
+ updatedAt: 5,
+ status: 'active',
+ favorite: true,
+ },
+ {
+ id: 'done',
+ title: 'Completed',
+ agentId: 'agent-b',
+ createdAt: 50,
+ updatedAt: 50,
+ status: 'completed',
+ favorite: false,
+ },
+];
+vi.mock('@/store/projectWorkingDirectory', () => ({
+ useProjectDirectoryStore: (selector: (s: unknown) => unknown) =>
+ selector({ useFetchProjectTopics: () => ({ hasData: true, revalidate: async () => {} }) }),
+ useProjectTopics: () => rows,
+}));
+vi.mock('@/hooks/useActiveRouteParams', () => ({ useActiveRouteParams: () => fixture }));
+vi.mock('@/store/chat', () => ({ useChatStore: () => new Set<string>() }));
+vi.mock('@/store/global', () => ({ useGlobalStore: () => vi.fn() }));
+vi.mock('i18next', () => ({ t: (key: string) => key }));
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(TopicListScopeContext, { value: { projectId: 'project-a' } }, children);
+
+describe('Project topics use the canonical Agent sidebar rules', () => {
+ beforeEach(() => {
+ fixture.topicId = undefined;
+ });
+ it('pins favorites and orders the rest by the selected timestamp across Agents', () => {
+ const { result, rerender } = renderHook(
+ ({ sort }: { sort: 'createdAt' | 'updatedAt' }) =>
+ useScopedSidebarTopics(20, sort, 'flat', false),
+ { wrapper, initialProps: { sort: 'updatedAt' } },
+ );
+ expect(result.current.topics.map((topic) => topic.id)).toEqual(['star', 'old', 'new']);
+ rerender({ sort: 'createdAt' });
+ expect(result.current.topics.map((topic) => topic.id)).toEqual(['star', 'new', 'old']);
+ });
+ it('uses the needs-attention status bucket and keeps favorites separate', () => {
+ const { result } = renderHook(
+ () => useScopedSidebarTopics(20, 'updatedAt', 'byStatus', false),
+ { wrapper },
+ );
+ expect(result.current.groups.map((group) => group.id)).toEqual([
+ 'favorite',
+ 'pending',
+ 'active',
+ ]);
+ expect(
+ result.current.groups
+ .find((group) => group.id === 'pending')
+ ?.children.map((topic) => topic.id),
+ ).toEqual(['new']);
+ });
+ it('reveals completed topics on request, and preserves the active completed topic when filtered', () => {
+ const { result, rerender } = renderHook(
+ ({ include }: { include: boolean }) =>
+ useScopedSidebarTopics(20, 'updatedAt', 'flat', include),
+ { wrapper, initialProps: { include: true } },
+ );
+ expect(result.current.topics.map((topic) => topic.id)).toContain('done');
+ fixture.topicId = 'done';
+ rerender({ include: false });
+ expect(result.current.topics.map((topic) => topic.id)).toEqual(['star', 'old', 'new', 'done']);
+ });
+ it('does not silently lose topics beyond the page limit', () => {
+ const { result } = renderHook(() => useScopedSidebarTopics(1, 'updatedAt', 'flat', false), {
+ wrapper,
+ });
+ expect(result.current.topics.map((topic) => topic.id)).toEqual(['star']);
+ expect(result.current.hasMore).toBe(true);
+ });
+});
diff --git a/src/features/AgentSidebar/Topic/useScopedTopics.ts b/src/features/AgentSidebar/Topic/useScopedTopics.ts
new file mode 100644
index 00000000000..c3cc8640d0d
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/useScopedTopics.ts
@@ -0,0 +1,76 @@
+import { useMemo } from 'react';
+
+import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';
+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
+import { useChatStore } from '@/store/chat';
+import { operationSelectors } from '@/store/chat/selectors';
+import { groupSidebarTopics, selectSidebarTopics } from '@/store/chat/slices/topic/selectors';
+import { useGlobalStore } from '@/store/global';
+import { useProjectDirectoryStore, useProjectTopics } from '@/store/projectWorkingDirectory';
+import type { ChatTopic, TopicGroupMode, TopicSortBy } from '@/types/topic';
+
+import { useTopicListScope } from './TopicListScope';
+
+export const useScopedTopics = () => {
+ const scope = useTopicListScope();
+ const request = useProjectDirectoryStore((s) => s.useFetchProjectTopics)(scope?.projectId);
+ const rows = useProjectTopics(scope?.projectId);
+ const topics = useMemo(
+ () =>
+ rows.map((topic) => ({
+ ...topic,
+ createdAt: new Date(topic.createdAt).getTime(),
+ updatedAt: new Date(topic.updatedAt).getTime(),
+ favorite: topic.favorite ?? false,
+ metadata: topic.metadata ?? undefined,
+ title: topic.title ?? '',
+ })),
+ [rows],
+ );
+ return { scope, topics, refresh: request.revalidate };
+};
+
+export const useScopedTopic = (id?: string) =>
+ useScopedTopics().topics?.find((topic) => topic.id === id);
+
+export const useScopedSidebarTopics = (
+ pageSize: number,
+ sortBy: TopicSortBy,
+ groupMode: TopicGroupMode,
+ includeCompleted: boolean,
+) => {
+ const { scope, topics } = useScopedTopics();
+ const { topicId } = useActiveRouteParams<{ topicId?: string }>();
+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
+ const running = useChatStore(operationSelectors.visiblyRunningTopicIds);
+ const visible = useMemo(() => {
+ const list: ChatTopic[] = (topics ?? []).filter(
+ (topic) => !topic.trigger || !MAIN_SIDEBAR_EXCLUDE_TRIGGERS.includes(topic.trigger),
+ );
+ return selectSidebarTopics(
+ list,
+ pageSize,
+ sortBy,
+ includeCompleted,
+ list.find((topic) => topic.id === topicId),
+ );
+ }, [topics, topicId, pageSize, sortBy, includeCompleted]);
+ const groups = useMemo(
+ () => groupSidebarTopics(visible, groupMode, sortBy, running),
+ [visible, groupMode, sortBy, running],
+ );
+ const hasMore =
+ (topics ?? []).filter(
+ (topic) =>
+ (!topic.trigger || !MAIN_SIDEBAR_EXCLUDE_TRIGGERS.includes(topic.trigger)) &&
+ (includeCompleted || topic.status !== 'completed'),
+ ).length > pageSize;
+ return {
+ scope,
+ topics: visible,
+ groups,
+ activeTopicId: topicId,
+ hasMore,
+ loadMore: () => updateSystemStatus({ topicPageSize: pageSize + 20 }),
+ };
+};
diff --git a/src/features/AgentTopicManager/BulkActionBar.tsx b/src/features/AgentTopicManager/BulkActionBar.tsx
index 1db67cf5916..24c32cf0bf6 100644
--- a/src/features/AgentTopicManager/BulkActionBar.tsx
+++ b/src/features/AgentTopicManager/BulkActionBar.tsx
@@ -3,11 +3,13 @@
import { Flexbox } from '@lobehub/ui';
import { ActionIcon, Text } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import { Archive, Star, Trash2, X } from 'lucide-react';
+import { Archive, FolderInput, Star, Trash2, X } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';
+import { openAssociateTopicModal } from '@/features/Projects/WorkingDirectories/AssociateTopicModal';
+import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
import MoveToAgentButton from './MoveToAgentButton';
@@ -47,6 +49,8 @@ const styles = createStaticStyles(({ css }) => ({
const BulkActionBar = memo(() => {
const { t } = useTranslation('topic');
+ const { allowed: canEditTopic } = usePermission('edit_own_content');
+ const activeAgentId = useChatStore((s) => s.activeAgentId);
const selectedIds = useTopicsViewStore((s) => s.selectedIds);
const exitSelectMode = useTopicsViewStore((s) => s.exitSelectMode);
@@ -106,6 +110,15 @@ const BulkActionBar = memo(() => {
onClick={handleBatchArchive}
/>
<MoveToAgentButton />
+ {selectedIds.length === 1 && canEditTopic && (
+ <ActionIcon
+ aria-label={t('directories.bind', { ns: 'project' })}
+ icon={FolderInput}
+ size="small"
+ title={t('directories.bind', { ns: 'project' })}
+ onClick={() => openAssociateTopicModal(selectedIds[0], activeAgentId)}
+ />
+ )}
<ActionIcon
icon={Trash2}
size={'small'}
diff --git a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
index d16d295c0eb..9af00602608 100644
--- a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
@@ -1,3 +1,4 @@
+import type { ChatTopic } from '@lobechat/types';
import { renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -13,7 +14,7 @@ const testState = vi.hoisted(() => ({
},
chat: {
activeTopicId: undefined as string | undefined,
- topic: undefined as { metadata?: Record<string, unknown> } | undefined,
+ topic: undefined as ChatTopic | undefined,
updateTopicMetadata: vi.fn(),
},
currentDeviceId: 'this-machine' as string | undefined,
@@ -61,6 +62,7 @@ vi.mock('@/helpers/heteroSessionByWorkingDirectory', () => ({
describe('useCommitWorkingDirectory — localTarget', () => {
beforeEach(() => {
vi.clearAllMocks();
+ testState.chat.topic = undefined;
testState.agent.agencyConfig = undefined;
testState.agent.agentMap = {};
testState.agent.localAgentWorkingDirectoryMap = {};
@@ -77,6 +79,21 @@ describe('useCommitWorkingDirectory — localTarget', () => {
};
});
+ it('keeps a project-bound source directory while allowing worktree selection', async () => {
+ testState.chat.activeTopicId = 'topic';
+ testState.chat.topic = {
+ id: 'topic',
+ projectWorkingDirectoryId: 'directory',
+ metadata: { workingDirectory: '/repo', workingDirectoryConfig: { path: '/repo' } },
+ } as ChatTopic;
+ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
+ await expect(result.current.commit({ path: '/elsewhere' })).rejects.toThrow();
+ await expect(result.current.clear()).rejects.toThrow();
+ expect(testState.chat.updateTopicMetadata).not.toHaveBeenCalled();
+ await result.current.commit({ path: '/repo', git: { activeWorktree: '/repo-worktree' } });
+ expect(testState.chat.updateTopicMetadata).toHaveBeenCalled();
+ });
+
it('files a workspace member’s first sandbox pick against their own machine', async () => {
// The caller selects `local` as part of the same action, so the config here
// still describes the previous (workspace-shared) target — and selecting
@@ -147,7 +164,7 @@ describe('useCommitWorkingDirectory — topic device provenance', () => {
// A conversation first pinned on device A, now running on device B.
testState.chat.topic = {
metadata: { boundDeviceId: 'device-a', workingDirectory: '/Users/me/repo-a' },
- };
+ } as ChatTopic;
testState.chat.updateTopicMetadata = vi.fn();
testState.currentDeviceId = 'this-machine';
testState.effective = {
diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
index 5d27def9011..f5018cf40a7 100644
--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts
@@ -93,7 +93,7 @@ const toAgentWorkingDirConfig = (entry: WorkingDirEntry): WorkingDirConfig => ({
* the same metadata write — same as the legacy pickers.
*/
export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string | null) => {
- const { t } = useTranslation(['plugin', 'chat']);
+ const { t } = useTranslation(['plugin', 'chat', 'project']);
// The RAW shared config — every write below spreads it back into
// `agents.agencyConfig`, so it must never contain this member's per-user
@@ -256,6 +256,8 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
// Clear whichever precedence level currently supplies the cwd, so the picker
// falls back to the next level (agent default → device default → "not set").
const clearCwd = useCallback(async () => {
+ if (activeTopic?.projectWorkingDirectoryId)
+ throw new Error(t('directories.boundRoot', { ns: 'project' }));
// A topic override (when present) is the effective source — drop it first so
// we fall back to the agent default rather than nuking everything.
if (activeTopicId && activeTopic?.metadata?.workingDirectory) {
@@ -299,6 +301,7 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
updateAgentConfigById,
updateAgentRuntimeEnvConfigById,
updateTopicMetadata,
+ t,
]);
/** Pick a directory (with the CC-session-reset guard). */
@@ -308,6 +311,13 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string
const effectivePath = getWorkingDirEffectivePath(normalizedEntry);
if (!normalizedEntry || !effectivePath) return;
+ if (activeTopic?.projectWorkingDirectoryId) {
+ const source = getWorkingDirSourcePath(
+ activeTopic.metadata?.workingDirectoryConfig ?? activeTopic.metadata?.workingDirectory,
+ );
+ if (getWorkingDirSourcePath(normalizedEntry) !== source)
+ throw new Error(t('directories.boundRoot', { ns: 'project' }));
+ }
const run = () => writeCwd(normalizedEntry, options);
// Warn about losing the CLI session only when the SESSION cwd changes.
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index af9802da31d..a61034d5b91 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -4,7 +4,7 @@ import { type VoiceMessageRecording } from '@lobechat/types';
import { type SlashOptions } from '@lobehub/editor';
import { type ChatInputActionsProps } from '@lobehub/editor/react';
import { Flexbox, type MenuProps } from '@lobehub/ui';
-import { Alert } from '@lobehub/ui/base-ui';
+import { Alert, toast } from '@lobehub/ui/base-ui';
import { type ReactNode } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -19,10 +19,11 @@ import {
type SendButtonHandler,
type SendButtonProps,
} from '@/features/ChatInput/store/initialState';
+import { checkProjectExecution } from '@/features/Projects/WorkingDirectories/checkExecution';
import { useAgentStore } from '@/store/agent';
import { chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
-import { operationSelectors } from '@/store/chat/selectors';
+import { operationSelectors, topicSelectors } from '@/store/chat/selectors';
import { selectCurrentTurnTodosFromMessages } from '@/store/chat/slices/message/selectors/dbMessage';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { fileChatSelectors, useFileStore } from '@/store/file';
@@ -377,6 +378,21 @@ const ChatInput = memo<ChatInputProps>(
if (!message.trim() && currentFileList.length === 0 && currentContextList.length === 0)
return;
+ // A rejected directory preflight has no persisted message to recover from.
+ // Keep the composer and attachments intact until the target is usable.
+ const chatState = useChatStore.getState();
+ const sendContext = storeApi.getState().context;
+ const topic = sendContext.topicId
+ ? topicSelectors.getTopicById(sendContext.topicId)(chatState)
+ : undefined;
+ try {
+ await checkProjectExecution(topic, chatState.isGatewayModeEnabled(sendContext.agentId));
+ } catch (error) {
+ console.error('Project execution preflight failed', error);
+ toast.error(error instanceof Error ? error.message : String(error));
+ return;
+ }
+
// Capture editor JSON state before clearing for rich text rendering
const editorData = getEditorData();
diff --git a/src/features/Conversation/Messages/Assistant/components/ThreadExecutionSummary.tsx b/src/features/Conversation/Messages/Assistant/components/ThreadExecutionSummary.tsx
index 7e1570d3a93..23c4b37e6df 100644
--- a/src/features/Conversation/Messages/Assistant/components/ThreadExecutionSummary.tsx
+++ b/src/features/Conversation/Messages/Assistant/components/ThreadExecutionSummary.tsx
@@ -39,6 +39,9 @@ const ThreadExecutionSummary = memo<ThreadExecutionSummaryProps>(({ messageId })
return (
<Accordion
indicatorPlacement="inline"
+ styles={{ trigger: { paddingBlock: 4, paddingInline: 4 } }}
+ value={[]}
+ variant={'borderless'}
items={[
{
key: 'execution-record',
@@ -49,9 +52,6 @@ const ThreadExecutionSummary = memo<ThreadExecutionSummaryProps>(({ messageId })
),
},
]}
- styles={{ trigger: { paddingBlock: 4, paddingInline: 4 } }}
- value={[]}
- variant={'borderless'}
onValueChange={handleValueChange}
/>
);
diff --git a/src/features/Conversation/Workspace/index.tsx b/src/features/Conversation/Workspace/index.tsx
new file mode 100644
index 00000000000..c1d5f7ff0a6
--- /dev/null
+++ b/src/features/Conversation/Workspace/index.tsx
@@ -0,0 +1,76 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { useSize } from 'ahooks';
+import { createStaticStyles } from 'antd-style';
+import { type ReactNode, useRef } from 'react';
+
+import ChatTerminalPanel from '@/features/ChatTerminal';
+import AgentWorkingSidebar from '@/features/Conversation/WorkingSidebar';
+import OverviewSlot from '@/features/Conversation/WorkingSidebar/OverviewSlot';
+import HeaderSlot from '@/routes/(main)/agent/(chat)/_layout/HeaderSlot';
+import Portal from '@/routes/(main)/agent/features/Portal';
+
+const styles = createStaticStyles(({ css }) => ({
+ // Named container queried by ChatHeader and the list top spacer: when this
+ // column is wide enough, the header floats above the full-bleed message
+ // stream instead of sitting in flow as a solid bar.
+ conversationColumn: css`
+ position: relative;
+ container-name: agent-chat-layout;
+ container-type: inline-size;
+ `,
+}));
+
+const ConversationWorkspace = ({
+ children,
+ header,
+}: {
+ children: ReactNode;
+ header: ReactNode;
+}) => {
+ // The working sidebar needs the row width to know whether it still fits next
+ // to an open portal — a wide portal otherwise squeezes the conversation out.
+ const rowRef = useRef<HTMLDivElement>(null);
+ const rowSize = useSize(rowRef);
+
+ return (
+ <HeaderSlot.Provider>
+ <OverviewSlot.Provider>
+ <Flexbox
+ flex={1}
+ height={'100%'}
+ style={{ minHeight: 0, overflow: 'hidden' }}
+ width={'100%'}
+ >
+ <Flexbox
+ horizontal
+ flex={1}
+ ref={rowRef}
+ style={{ minHeight: 0, overflow: 'hidden', position: 'relative' }}
+ width={'100%'}
+ >
+ <Flexbox
+ className={styles.conversationColumn}
+ flex={1}
+ style={{ minHeight: 0, minWidth: 0 }}
+ >
+ {header}
+ <Flexbox horizontal flex={1} style={{ minHeight: 0, minWidth: 0 }}>
+ <Flexbox flex={1} style={{ minHeight: 0, minWidth: 0 }}>
+ {children}
+ </Flexbox>
+ <OverviewSlot.Outlet />
+ </Flexbox>
+ </Flexbox>
+ <Portal />
+ <AgentWorkingSidebar availableWidth={rowSize?.width} />
+ </Flexbox>
+ <ChatTerminalPanel />
+ </Flexbox>
+ </OverviewSlot.Provider>
+ </HeaderSlot.Provider>
+ );
+};
+
+export default ConversationWorkspace;
diff --git a/src/features/Projects/Conversation/index.tsx b/src/features/Projects/Conversation/index.tsx
index df029cfa5c0..d31e13e7e2b 100644
--- a/src/features/Projects/Conversation/index.tsx
+++ b/src/features/Projects/Conversation/index.tsx
@@ -7,14 +7,19 @@ import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router';
import AsyncError from '@/components/AsyncError';
+import TopicActions from '@/features/AgentSidebar/Topic/List/Item/Actions';
+import ConversationWorkspace from '@/features/Conversation/Workspace';
import NavHeader from '@/features/NavHeader';
import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
import ChatConversation from '@/routes/(main)/agent/features/Conversation';
import ChatHydration from '@/routes/(main)/agent/features/Conversation/ChatHydration';
+import TerminalPanelToggle from '@/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle';
+import WorkingPanelToggle from '@/routes/(main)/agent/features/Conversation/Header/WorkingPanelToggle';
import { useAgentStore } from '@/store/agent';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
+import { useProjectDirectoryStore, useProjectTopics } from '@/store/projectWorkingDirectory';
import { getProjectConversationPath } from '../Layout/navigation';
@@ -23,28 +28,38 @@ const ProjectConversation = memo(() => {
const { projectId, topicId } = useParams<{ projectId: string; topicId?: string }>();
const detail = useCurrentProjectDetail(projectId);
const detailSWR = useProjectStore((s) => s.useFetchProjectDetail)(projectId);
- const coordinatorAgentId = detail?.project.coordinatorAgentId;
+ const topicsRequest = useProjectDirectoryStore((s) => s.useFetchProjectTopics)(
+ detail?.project.id,
+ );
+ const topics = useProjectTopics(detail?.project.id);
+ const selectedTopic = topics.find((topic) => topic.id === topicId);
+ const conversationAgentId = topicId
+ ? (selectedTopic?.agentId ?? undefined)
+ : detail?.project.coordinatorAgentId;
const projectSlug = detail?.project.slug ?? projectId;
- const topicTitle = useChatStore((s) =>
- topicId ? topicSelectors.getTopicById(topicId)(s)?.title : undefined,
+ const storedTopic = useChatStore((s) =>
+ topicId ? topicSelectors.getTopicById(topicId)(s) : undefined,
);
+ const topicTitle = storedTopic?.title;
- useInitAgentConfig(coordinatorAgentId);
+ const agent = useInitAgentConfig(conversationAgentId);
+ const topicDetail = useChatStore((s) => s.useFetchTopicDetail)(selectedTopic?.id);
+ const activeAgentId = useChatStore((s) => s.activeAgentId);
useLayoutEffect(() => {
- if (!coordinatorAgentId) return;
+ if (!conversationAgentId) return;
useAgentStore.setState(
- { activeAgentId: coordinatorAgentId },
+ { activeAgentId: conversationAgentId },
false,
'ProjectConversation/syncAgentId',
);
useChatStore.setState(
- { activeAgentId: coordinatorAgentId },
+ { activeAgentId: conversationAgentId },
false,
'ProjectConversation/syncAgentId',
);
- }, [coordinatorAgentId]);
+ }, [conversationAgentId]);
const getConversationPath = useCallback(
() => getProjectConversationPath(projectSlug!),
@@ -55,10 +70,35 @@ const ProjectConversation = memo(() => {
[projectSlug],
);
+ if (topicDetail.error)
+ return <AsyncError error={topicDetail.error} variant="page" onRetry={topicDetail.revalidate} />;
+ if (agent.error) return <AsyncError error={agent.error} variant="page" onRetry={agent.mutate} />;
+ if (topicsRequest.error)
+ return (
+ <AsyncError error={topicsRequest.error} variant="page" onRetry={topicsRequest.revalidate} />
+ );
+ if (!topicId)
+ return (
+ <Center height="100%">
+ <Text>{t('topics.chooseTopic')}</Text>
+ </Center>
+ );
+ if (topicsRequest.hasData && !selectedTopic)
+ return (
+ <Center height="100%">
+ <Text>{t('topics.notFound')}</Text>
+ </Center>
+ );
if (detailSWR.error && !detail) {
return <AsyncError error={detailSWR.error} variant="page" onRetry={detailSWR.revalidate} />;
}
- if (!detail || !coordinatorAgentId) {
+ if (
+ !detail ||
+ !conversationAgentId ||
+ agent.isLoading ||
+ (!storedTopic && topicDetail.isValidating) ||
+ activeAgentId !== conversationAgentId
+ ) {
return (
<Center height="100%" width="100%">
<Spin size="small" />
@@ -67,17 +107,34 @@ const ProjectConversation = memo(() => {
}
return (
- <Flexbox flex={1} height="100%" style={{ minHeight: 0, minWidth: 0 }}>
- <NavHeader
- left={
- <Text ellipsis weight={600}>
- {topicTitle || t('sidebar.newConversation')}
- </Text>
- }
- />
+ <ConversationWorkspace
+ header={
+ <NavHeader
+ left={
+ <Text ellipsis weight={600}>
+ {topicTitle || selectedTopic?.title || t('sidebar.newConversation')}
+ </Text>
+ }
+ right={
+ <Flexbox horizontal align="center" gap={4}>
+ <TerminalPanelToggle />
+ <WorkingPanelToggle />
+ <TopicActions
+ id={topicId}
+ status={selectedTopic?.status}
+ title={topicTitle || selectedTopic?.title || t('directories.untitled')}
+ completionLabel={t(
+ selectedTopic?.status === 'completed' ? 'topics.resume' : 'topics.complete',
+ )}
+ />
+ </Flexbox>
+ }
+ />
+ }
+ >
<ChatHydration getConversationPath={getConversationPath} getTopicPath={getTopicPath} />
<ChatConversation />
- </Flexbox>
+ </ConversationWorkspace>
);
});
diff --git a/src/features/Projects/Layout/ProjectHeader.tsx b/src/features/Projects/Layout/ProjectHeader.tsx
index ed9936f8453..d05874b5060 100644
--- a/src/features/Projects/Layout/ProjectHeader.tsx
+++ b/src/features/Projects/Layout/ProjectHeader.tsx
@@ -1,5 +1,7 @@
'use client';
+import { ActionIcon } from '@lobehub/ui/base-ui';
+import { SettingsIcon } from 'lucide-react';
import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -31,7 +33,7 @@ const ProjectHeader = memo<ProjectHeaderProps>(({ project }) => {
const items = useMemo<SwitcherItem[]>(
() =>
projects.map((item) => ({
- avatar: item.avatar || item.name,
+ avatar: item.avatar || undefined,
id: item.slug ?? item.id,
private: item.visibility === 'private',
title: item.name,
@@ -63,12 +65,21 @@ const ProjectHeader = memo<ProjectHeaderProps>(({ project }) => {
}
>
<SidebarHeaderSelectTrigger
- avatar={project?.avatar || project?.name || t('sidebar.title')}
+ avatar={project?.avatar || undefined}
name={project?.name || t('sidebar.title')}
title={project?.name || t('sidebar.title')}
/>
</SidebarHeaderSelectPopover>
}
+ right={
+ <ActionIcon
+ aria-label={t('settings.title')}
+ icon={SettingsIcon}
+ size="small"
+ title={t('settings.title')}
+ onClick={() => navigate(`/project/${project?.slug ?? project?.id}/settings`)}
+ />
+ }
/>
);
});
diff --git a/src/features/Projects/Layout/Sidebar.tsx b/src/features/Projects/Layout/Sidebar.tsx
index 7a503891b8c..02d9038ce99 100644
--- a/src/features/Projects/Layout/Sidebar.tsx
+++ b/src/features/Projects/Layout/Sidebar.tsx
@@ -1,7 +1,7 @@
'use client';
import { Flexbox } from '@lobehub/ui';
-import { ClipboardCheckIcon, ListTodoIcon, TargetIcon } from 'lucide-react';
+import { ClipboardCheckIcon, ListTodoIcon, SettingsIcon, TargetIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router';
@@ -14,6 +14,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwar
import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
+import { ProjectDirectoryTopics } from '../WorkingDirectories/SidebarTopics';
import { getProjectAcceptancePath, getProjectGoalsPath, getProjectTasksPath } from './navigation';
import ProjectHeader from './ProjectHeader';
@@ -63,6 +64,18 @@ const ProjectSidebarContent = memo(() => {
title={t('sections.acceptance')}
onClick={() => navigate(projectAcceptancePath)}
/>
+ <NavItem
+ active={pathname.includes(`/project/${projectId}/settings`)}
+ icon={SettingsIcon}
+ title={t('topics.settings')}
+ onClick={() => navigate(`/project/${projectId}/settings/general`)}
+ />
+ {detail?.project && (
+ <ProjectDirectoryTopics
+ coordinatorAgentId={detail.project.coordinatorAgentId}
+ projectId={detail.project.id}
+ />
+ )}
</Flexbox>
}
/>
diff --git a/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsx b/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsx
new file mode 100644
index 00000000000..0a9aa2db4a1
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/AddDirectoryModal.tsx
@@ -0,0 +1,134 @@
+import { Flexbox } from '@lobehub/ui';
+import {
+ Alert,
+ Button,
+ createModal,
+ Input,
+ Select,
+ Text,
+ useModalContext,
+} from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { deviceService } from '@/services/device';
+import { useDeviceStore } from '@/store/device';
+import { useProjectDirectoryStore, useProjectEnvironments } from '@/store/projectWorkingDirectory';
+
+function AddDirectoryContent({
+ projectId,
+ environmentId: initialEnvironmentId,
+}: {
+ projectId: string;
+ environmentId?: string;
+}) {
+ const { t } = useTranslation('project');
+ const deviceRequest = useDeviceStore((s) => s.useFetchDevices)(true);
+ const devices = useDeviceStore((s) => s.devices);
+ const environmentsRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);
+ const environments = useProjectEnvironments(projectId);
+ const [environmentId, setEnvironment] = useState(initialEnvironmentId ?? '');
+ const [deviceId, setDevice] = useState('');
+ const [path, setPath] = useState('');
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState<unknown>();
+ const bind = useProjectDirectoryStore((s) => s.bind);
+ const { close } = useModalContext();
+ const save = async () => {
+ setPending(true);
+ setError(undefined);
+ try {
+ const stat = await deviceService.statPath(deviceId, path);
+ if (!stat?.exists || !stat.isDirectory) throw new Error(t('settings.directoryUnavailable'));
+ await bind({
+ projectId,
+ environmentId,
+ deviceId,
+ path,
+ name: path.split(/[\\/]/).findLast(Boolean) || path,
+ });
+ close();
+ } catch (error) {
+ console.error('Failed to add work location', error);
+ setError(error);
+ } finally {
+ setPending(false);
+ }
+ };
+ return (
+ <Flexbox gap={16}>
+ <Text type="secondary">{t('settings.addDirectoryDescription')}</Text>
+ <Text>{t('directories.environment')}</Text>
+ <Select
+ aria-label={t('directories.environment')}
+ disabled={pending}
+ options={environments.map((env) => ({ value: env.id, label: env.name }))}
+ placeholder={t('directories.environment')}
+ value={environmentId}
+ onChange={(id) => {
+ setEnvironment(id ?? '');
+ setError(undefined);
+ }}
+ />
+ <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={error instanceof Error ? error.message : undefined}
+ title={t('settings.addDirectoryFailed')}
+ type="error"
+ />
+ ) : null}
+ {deviceRequest.error || environmentsRequest.error ? (
+ <AsyncError
+ error={deviceRequest.error || environmentsRequest.error}
+ onRetry={() => Promise.all([deviceRequest.mutate(), environmentsRequest.revalidate()])}
+ />
+ ) : null}
+ <Flexbox horizontal gap={8} justify="flex-end">
+ <Button disabled={pending} onClick={close}>
+ {t('cancel', { ns: 'common' })}
+ </Button>
+ <Button
+ disabled={!environmentId || !deviceId || !path.trim()}
+ loading={pending}
+ type="primary"
+ onClick={save}
+ >
+ {t('settings.addDirectory')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+}
+export const openAddDirectoryModal = (projectId: string, environmentId?: string) =>
+ createModal({
+ title: t('settings.addDirectory', { ns: 'project' }),
+ content: <AddDirectoryContent environmentId={environmentId} projectId={projectId} />,
+ footer: null,
+ width: 520,
+ });
diff --git a/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx b/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx
new file mode 100644
index 00000000000..669693a93fd
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/AgentDirectoryActions.tsx
@@ -0,0 +1,126 @@
+import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
+import type { ChatTopic } from '@lobechat/types';
+import { ActionIcon, DropdownMenu, toast } from '@lobehub/ui/base-ui';
+import { MoreHorizontalIcon, PlusIcon } from 'lucide-react';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
+import { useElectronStore } from '@/store/electron';
+import { useProjectDirectories, useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+
+import { openBindDirectoryModal } from './BindDirectoryModal';
+
+export function AgentDirectoryActions({
+ agentId,
+ path,
+ topics,
+ onLegacyStart,
+}: {
+ agentId: string;
+ path: string;
+ topics: ChatTopic[];
+ onLegacyStart: () => Promise<void>;
+}) {
+ const { t } = useTranslation('project');
+ const navigate = useWorkspaceAwareNavigate();
+ const { agencyConfig, workspaceScoped } = useEffectiveAgencyConfig(agentId, {
+ topicId: null,
+ });
+ const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
+ const pinnedDevice = topics[0]?.metadata?.boundDeviceId;
+ const deviceId =
+ pinnedDevice ?? resolveTargetDeviceId(agencyConfig, currentDeviceId, { workspaceScoped });
+ const request = useProjectDirectoryStore((s) => s.useFetchDirectories)();
+ const directories = useProjectDirectories();
+ const bindingId = topics[0]?.projectWorkingDirectoryId;
+ const bindings = directories.filter((directory) =>
+ bindingId
+ ? directory.id === bindingId
+ : directory.deviceId === deviceId &&
+ directory.path.replace(/[\\/]+$/, '') === path.replace(/[\\/]+$/, ''),
+ );
+ const [pending, setPending] = useState(false);
+ const startTopic = useProjectDirectoryStore((s) => s.startTopic);
+ const start = async (id?: string) => {
+ setPending(true);
+ try {
+ if (id) {
+ const topic = await startTopic(id, agentId, t('directories.untitled'));
+ navigate(AGENT_CHAT_TOPIC_URL(agentId, topic.id));
+ } else await onLegacyStart();
+ } catch (error) {
+ console.error('Failed to start directory conversation', error);
+ toast.error(error instanceof Error ? error.message : t('operationFailed', { ns: 'common' }));
+ } finally {
+ setPending(false);
+ }
+ };
+ const repositoryUrl = topics
+ .map((topic) => topic.metadata?.repos?.[0])
+ .find((url) => url?.startsWith('https://github.com/'));
+ return (
+ <>
+ <DropdownMenu
+ items={[
+ ...bindings.map((directory) => ({
+ key: `open-${directory.id}`,
+ label: t('topics.viewProject'),
+ onClick: () => navigate(`/project/${directory.projectSlug ?? directory.projectId}`),
+ })),
+ ...(bindings.length ? [{ type: 'divider' as const }] : []),
+ ...bindings.map((directory) => ({
+ key: `settings-${directory.id}`,
+ label: t('topics.settings'),
+ onClick: () =>
+ navigate(`/project/${directory.projectSlug ?? directory.projectId}/settings`),
+ })),
+ ...(bindings.length
+ ? []
+ : [
+ {
+ key: 'bind',
+ label: t('directories.bind'),
+ disabled: !deviceId,
+ onClick: () =>
+ deviceId &&
+ openBindDirectoryModal({
+ agentId,
+ deviceId,
+ path,
+ repositoryUrl,
+ topicIds: topics.map((topic) => topic.id),
+ }),
+ },
+ ]),
+ ]}
+ >
+ <ActionIcon
+ disabled={pending}
+ icon={MoreHorizontalIcon}
+ size="small"
+ title={t('directories.projectBinding')}
+ onClick={(e) => e.stopPropagation()}
+ />
+ </DropdownMenu>
+ <ActionIcon
+ icon={PlusIcon}
+ size="small"
+ title={t('directories.start')}
+ disabled={
+ pending ||
+ !request.hasData ||
+ !!request.error ||
+ bindings.length > 1 ||
+ (!!bindingId && !bindings.length)
+ }
+ onClick={(e) => {
+ e.stopPropagation();
+ void start(bindings[0]?.id);
+ }}
+ />
+ </>
+ );
+}
diff --git a/src/features/Projects/WorkingDirectories/AssociateTopicModal.tsx b/src/features/Projects/WorkingDirectories/AssociateTopicModal.tsx
new file mode 100644
index 00000000000..f908402d02f
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/AssociateTopicModal.tsx
@@ -0,0 +1,205 @@
+import { getWorkingDirSourcePath } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
+import {
+ Alert,
+ Avatar,
+ Button,
+ createModal,
+ Select,
+ Switch,
+ Text,
+ useModalContext,
+} from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useChatStore } from '@/store/chat';
+import { useCurrentProjectList, useProjectStore } from '@/store/project';
+import { useProjectDirectories, useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+
+import { openCreateProjectModal } from '../CreateProjectModal';
+import { getProjectConversationPath } from '../Layout/navigation';
+import { openBindDirectoryModal } from './BindDirectoryModal';
+
+function AssociateTopicContent({ topicId, agentId }: { topicId: string; agentId?: string }) {
+ const { t } = useTranslation('project');
+ const { close } = useModalContext();
+ const navigate = useWorkspaceAwareNavigate();
+ const topicSync = useChatStore((s) => s.useFetchTopicDetail)(topicId);
+ const topic = useChatStore((s) => s.topicDetailMap?.[topicId]);
+ const projectSync = useProjectStore((s) => s.useFetchProjectList)();
+ const projects = useCurrentProjectList();
+ const [selectedProject, setProject] = useState('');
+ const projectId = topic?.projectId || selectedProject;
+ const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(
+ projectId,
+ !!projectId,
+ );
+ const directories = useProjectDirectories(projectId);
+ const [directoryId, setDirectory] = useState('');
+ const [includeDirectory, setIncludeDirectory] = useState(false);
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState<unknown>();
+ const associate = useProjectDirectoryStore((s) => s.associateTopic);
+ const source = getWorkingDirSourcePath(
+ topic?.metadata?.workingDirectoryConfig ?? topic?.metadata?.workingDirectory,
+ );
+ const deviceId = topic?.metadata?.boundDeviceId;
+ const options = directories.filter(
+ (d) =>
+ !source ||
+ (d.path.replace(/[\\/]+$/, '') === source.replace(/[\\/]+$/, '') &&
+ (!deviceId || d.deviceId === deviceId)),
+ );
+ const selectedDirectory =
+ topic?.projectWorkingDirectoryId ||
+ directoryId ||
+ (source && deviceId && options.length === 1 ? options[0].id : undefined);
+ const save = async () => {
+ setPending(true);
+ setError(undefined);
+ try {
+ await associate({
+ topicId,
+ projectId,
+ directoryId:
+ source || topic?.projectWorkingDirectoryId || includeDirectory
+ ? selectedDirectory || undefined
+ : undefined,
+ });
+ await useChatStore.getState().refreshTopic();
+ close();
+ navigate(getProjectConversationPath(projectId, topicId));
+ } catch (error) {
+ console.error('Failed to associate topic', error);
+ setError(error);
+ } finally {
+ setPending(false);
+ }
+ };
+ return (
+ <Flexbox gap={16}>
+ <Text>{topic?.title}</Text>
+ {topic?.projectId && (
+ <Button
+ onClick={() => {
+ close();
+ navigate(getProjectConversationPath(projectId, topicId));
+ }}
+ >
+ {t('topics.viewProject')}
+ </Button>
+ )}
+ {source && (
+ <Text type="secondary">
+ {deviceId} · {source}
+ </Text>
+ )}
+ <Select
+ aria-label={t('directories.project')}
+ disabled={pending || !!topic?.projectId}
+ placeholder={t('directories.project')}
+ value={projectId}
+ options={[
+ ...projects.map((p) => ({
+ value: p.id,
+ label: (
+ <Flexbox horizontal align="center" gap={8}>
+ <Avatar avatar={p.avatar || '📁'} size={20} />
+ {p.name}
+ </Flexbox>
+ ),
+ })),
+ { value: '__create__', label: t('directories.createProject') },
+ ]}
+ onChange={(value) =>
+ value === '__create__'
+ ? openCreateProjectModal({ onCreated: (p) => setProject(p.id) })
+ : (setProject(value ?? ''), setDirectory(''))
+ }
+ />
+ {!source && !topic?.projectWorkingDirectoryId && (
+ <Flexbox horizontal align="center" justify="space-between">
+ <label htmlFor="associate-topic-directory">{t('topics.addLocation')}</label>
+ <Switch
+ checked={includeDirectory}
+ disabled={pending || !projectId}
+ id="associate-topic-directory"
+ onChange={setIncludeDirectory}
+ />
+ </Flexbox>
+ )}
+ {(source || topic?.projectWorkingDirectoryId || includeDirectory) && (
+ <Select
+ aria-label={t('topics.executionContext')}
+ disabled={pending || !projectId || !!topic?.projectWorkingDirectoryId}
+ placeholder={t('topics.chooseLocation')}
+ value={selectedDirectory}
+ options={options.map((d) => ({
+ value: d.id,
+ label: `${d.environmentName || d.name} · ${d.deviceName || d.deviceId} · ${d.path}`,
+ }))}
+ onChange={(value) => setDirectory(value ?? '')}
+ />
+ )}
+ {source && deviceId && !options.length && projectId && (
+ <Button
+ onClick={() =>
+ openBindDirectoryModal({
+ projectId,
+ agentId,
+ deviceId,
+ path: source,
+ topicIds: [topicId],
+ })
+ }
+ >
+ {t('directories.bind')}
+ </Button>
+ )}
+ {error ? (
+ <Alert
+ showIcon
+ description={error instanceof Error ? error.message : undefined}
+ title={t('topics.associateFailed')}
+ type="error"
+ />
+ ) : null}
+ {topicSync.error || projectSync.error || directoriesRequest.error ? (
+ <AsyncError
+ error={topicSync.error || projectSync.error || directoriesRequest.error}
+ onRetry={() =>
+ Promise.all([
+ topicSync.revalidate(),
+ projectSync.revalidate(),
+ directoriesRequest.revalidate(),
+ ])
+ }
+ />
+ ) : null}
+ <Flexbox horizontal gap={8} justify="flex-end">
+ <Button disabled={pending} onClick={close}>
+ {t('cancel', { ns: 'common' })}
+ </Button>
+ <Button
+ disabled={!projectId || !topic || ((!!source || includeDirectory) && !selectedDirectory)}
+ loading={pending}
+ type="primary"
+ onClick={save}
+ >
+ {t('directories.bind')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+}
+export const openAssociateTopicModal = (topicId: string, agentId?: string) =>
+ createModal({
+ title: t('directories.bind', { ns: 'project' }),
+ content: <AssociateTopicContent agentId={agentId} topicId={topicId} />,
+ footer: null,
+ width: 520,
+ });
diff --git a/src/features/Projects/WorkingDirectories/BindDirectoryModal.tsx b/src/features/Projects/WorkingDirectories/BindDirectoryModal.tsx
new file mode 100644
index 00000000000..c8732fe6a85
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/BindDirectoryModal.tsx
@@ -0,0 +1,198 @@
+import { Flexbox, Icon } from '@lobehub/ui';
+import {
+ Alert,
+ Avatar,
+ Button,
+ createModal,
+ ModalFooter,
+ Select,
+ Text,
+ useModalContext,
+} from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+import { FolderIcon, PlusIcon } from 'lucide-react';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';
+import { useDeviceStore } from '@/store/device';
+import { useCurrentProjectList, useProjectStore } from '@/store/project';
+import { useProjectDirectoryStore, useProjectEnvironments } from '@/store/projectWorkingDirectory';
+
+import { openCreateProjectModal } from '../CreateProjectModal';
+import { openEnvironmentModal } from './EnvironmentModal';
+import { useBindDirectory } from './useBindDirectory';
+
+export interface BindDirectoryOptions {
+ agentId?: string;
+ deviceId: string;
+ environmentId?: string;
+ path: string;
+ projectId?: string;
+ repositoryUrl?: string;
+ topicIds?: string[];
+}
+const CREATE = '__create__';
+function BindDirectoryContent(options: BindDirectoryOptions) {
+ const { t } = useTranslation('project');
+ const { close } = useModalContext();
+ const [environmentId, setEnvironmentId] = useState(options.environmentId ?? '');
+ const [projectId, setProjectId] = useState(options.projectId ?? '');
+ const name = options.path.split(/[\\/]/).findLast(Boolean) ?? '';
+ const { pending, error, save: bindDirectory } = useBindDirectory(options, close);
+ const projectSync = useProjectStore((s) => s.useFetchProjectList)();
+ const projects = useCurrentProjectList();
+ useDeviceStore((s) => s.useFetchDevices)(true);
+ const devices = useDeviceStore((s) => s.devices);
+ const device = devices.find((d) => d.deviceId === options.deviceId);
+ const deviceName = device?.friendlyName ?? options.deviceId;
+ const environmentsRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)();
+ const environments = useProjectEnvironments();
+ const save = () => bindDirectory(projectId, environmentId);
+ return (
+ <>
+ <Flexbox
+ gap={12}
+ padding={16}
+ style={{ maxHeight: 'calc(100dvh - 200px)', overflowY: 'auto' }}
+ >
+ <Text type="secondary">{t('directories.bindDescription')}</Text>
+ <Flexbox gap={6}>
+ <Text weight={500}>{t('directories.currentFolder')}</Text>
+ <Flexbox horizontal align="center" gap={8}>
+ {getDeviceIcon(device?.platform, 16)}
+ <Text fontSize={13}>{deviceName}</Text>
+ </Flexbox>
+ <Flexbox horizontal align="start" gap={8}>
+ <Icon icon={FolderIcon} size={16} style={{ flexShrink: 0, marginTop: 2 }} />
+ <Text fontSize={13} style={{ overflowWrap: 'anywhere' }} type="secondary">
+ {options.path}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ <Text>{t('directories.project')}</Text>
+ {projectSync.error ? (
+ <AsyncError error={projectSync.error} onRetry={projectSync.revalidate} />
+ ) : (
+ <Select
+ aria-label={t('directories.project')}
+ disabled={pending || !!options.projectId}
+ placeholder={t('directories.project')}
+ value={projectId}
+ options={[
+ ...projects.map((project) => ({
+ label: (
+ <Flexbox horizontal align="center" gap={8}>
+ <Avatar avatar={project.avatar || '📁'} size={20} />
+ {project.name}
+ </Flexbox>
+ ),
+ value: project.id,
+ })),
+ {
+ label: (
+ <Flexbox horizontal align="center" gap={8}>
+ <Icon icon={PlusIcon} size={16} />
+ {t('directories.createProject')}
+ </Flexbox>
+ ),
+ value: CREATE,
+ },
+ ]}
+ onChange={(value) =>
+ value === CREATE
+ ? openCreateProjectModal({ onCreated: (project) => setProjectId(project.id) })
+ : setProjectId(value ?? '')
+ }
+ />
+ )}
+ <Text>{t('directories.environment')}</Text>
+ {environmentsRequest.error ? (
+ <AsyncError error={environmentsRequest.error} onRetry={environmentsRequest.revalidate} />
+ ) : (
+ <Select
+ aria-label={t('directories.environment')}
+ disabled={pending}
+ placeholder={t('directories.environment')}
+ value={environmentId}
+ optionRender={(option) => {
+ const env = environments.find((env) => env.id === option.value);
+ const source = env?.configuration.sources?.find((source) => source.kind === 'git');
+ return (
+ <Flexbox horizontal align="center" gap={8}>
+ <Text>{option.label}</Text>
+ {source && (
+ <Text fontSize={12} type="secondary">
+ {source.url.replace('https://github.com/', 'GitHub · ')}
+ </Text>
+ )}
+ </Flexbox>
+ );
+ }}
+ options={[
+ ...environments.map((env) => ({
+ label: env.name,
+ value: env.id,
+ })),
+ {
+ label: (
+ <Flexbox horizontal align="center" gap={8}>
+ <Icon icon={PlusIcon} size={16} />
+ {t('directories.newEnvironment')}
+ </Flexbox>
+ ),
+ value: CREATE,
+ },
+ ]}
+ onChange={(value) =>
+ value === CREATE
+ ? openEnvironmentModal({
+ name,
+ repositoryUrl: options.repositoryUrl,
+ deviceId: options.deviceId,
+ path: options.path,
+ onSaved: (env) => setEnvironmentId(env.id),
+ })
+ : setEnvironmentId(value ?? '')
+ }
+ />
+ )}
+ {!!options.topicIds?.length && (
+ <Text fontSize={12} type="secondary">
+ {t('directories.autoFileTopics', { count: options.topicIds.length })}
+ </Text>
+ )}
+ {error ? (
+ <Alert
+ showIcon
+ description={error instanceof Error ? error.message : undefined}
+ title={t('directories.bindFailed')}
+ type="error"
+ />
+ ) : null}
+ </Flexbox>
+ <ModalFooter>
+ <Button disabled={pending} onClick={close}>
+ {t('cancel', { ns: 'common' })}
+ </Button>
+ <Button
+ disabled={!projectId || !environmentId || !name.trim()}
+ loading={pending}
+ type="primary"
+ onClick={save}
+ >
+ {t('directories.bind')}
+ </Button>
+ </ModalFooter>
+ </>
+ );
+}
+export const openBindDirectoryModal = (options: BindDirectoryOptions) =>
+ createModal({
+ title: t('directories.bind', { ns: 'project' }),
+ content: <BindDirectoryContent {...options} />,
+ footer: null,
+ styles: { content: { padding: 0 } },
+ width: 480,
+ });
diff --git a/src/features/Projects/WorkingDirectories/EnvironmentModal.tsx b/src/features/Projects/WorkingDirectories/EnvironmentModal.tsx
new file mode 100644
index 00000000000..fd81e6f4061
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/EnvironmentModal.tsx
@@ -0,0 +1,116 @@
+import { Flexbox } from '@lobehub/ui';
+import {
+ Button,
+ createModal,
+ Input,
+ ModalFooter,
+ Text,
+ useModalContext,
+} from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { deviceService } from '@/services/device';
+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+
+interface EnvironmentOptions {
+ deviceId?: string;
+ id?: string;
+ name?: string;
+ onSaved: (environment: { id: string; name: string }) => void | Promise<void>;
+ path?: string;
+ repositoryUrl?: string;
+}
+function EnvironmentContent(options: EnvironmentOptions) {
+ const { t } = useTranslation('project');
+ const { close } = useModalContext();
+ const [name, setName] = useState(options.name ?? '');
+ const [repositoryUrl, setRepositoryUrl] = useState(options.repositoryUrl ?? '');
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState<unknown>();
+ const [failedAction, setFailedAction] = useState<'save' | 'detect'>('save');
+ const saveEnvironment = useProjectDirectoryStore((s) => s.saveEnvironment);
+ const save = async () => {
+ setFailedAction('save');
+ setPending(true);
+ setError(undefined);
+ try {
+ const environment = await saveEnvironment({ id: options.id, name, repositoryUrl });
+ await options.onSaved(environment);
+ close();
+ } catch (error) {
+ console.error('Failed to save environment', error);
+ setError(error);
+ } finally {
+ setPending(false);
+ }
+ };
+ const detect = async () => {
+ setFailedAction('detect');
+ setPending(true);
+ setError(undefined);
+ try {
+ const result = await deviceService.statPath(options.deviceId!, options.path!);
+ if (!result?.isDirectory) throw new Error(t('directories.unavailable'));
+ setRepositoryUrl(result.repositoryUrl ?? '');
+ } catch (error) {
+ console.error('Failed to detect repository', error);
+ setError(error);
+ } finally {
+ setPending(false);
+ }
+ };
+ return (
+ <>
+ <Flexbox gap={12} padding={16}>
+ <Text>{t('directories.environmentName')}</Text>
+ <Input
+ aria-label={t('directories.environmentName')}
+ disabled={pending}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <Text>{t('directories.repository')}</Text>
+ <Input
+ aria-label={t('directories.repository')}
+ disabled={pending}
+ value={repositoryUrl}
+ onChange={(e) => setRepositoryUrl(e.target.value)}
+ />
+ {options.deviceId && options.path && (
+ <Button disabled={pending} onClick={detect}>
+ {t('directories.detectRepository')}
+ </Button>
+ )}
+ <Text type="secondary">{t('directories.repositoryHint')}</Text>
+ {error ? (
+ <AsyncError
+ description={error instanceof Error ? error.message : undefined}
+ error={error}
+ onRetry={failedAction === 'detect' ? detect : save}
+ />
+ ) : null}
+ </Flexbox>
+ <ModalFooter>
+ <Button disabled={pending} onClick={close}>
+ {t('cancel', { ns: 'common' })}
+ </Button>
+ <Button disabled={!name.trim()} loading={pending} type="primary" onClick={save}>
+ {t('save', { ns: 'common' })}
+ </Button>
+ </ModalFooter>
+ </>
+ );
+}
+export const openEnvironmentModal = (options: EnvironmentOptions) =>
+ createModal({
+ title: t(options.id ? 'directories.editEnvironment' : 'directories.newEnvironment', {
+ ns: 'project',
+ }),
+ content: <EnvironmentContent {...options} />,
+ footer: null,
+ styles: { content: { padding: 0 } },
+ width: 480,
+ });
diff --git a/src/features/Projects/WorkingDirectories/GeneralSettings.tsx b/src/features/Projects/WorkingDirectories/GeneralSettings.tsx
new file mode 100644
index 00000000000..36385d0c49b
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/GeneralSettings.tsx
@@ -0,0 +1,173 @@
+import { Flexbox, Form } from '@lobehub/ui';
+import { Button, confirmModal, Input, TextArea, toast } from '@lobehub/ui/base-ui';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { FORM_STYLE } from '@/const/layoutTokens';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import type { ProjectDetail } from '@/store/project';
+import { useProjectStore } from '@/store/project';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import { isProjectSlugValid } from '../createProjectForm';
+
+export function GeneralSettings({ project }: { project: ProjectDetail['project'] }) {
+ const { t } = useTranslation('project');
+ const [name, setName] = useState(project.name);
+ const [slug, setSlug] = useState(project.slug ?? '');
+ const [description, setDescription] = useState(project.description ?? '');
+ const navigate = useWorkspaceAwareNavigate();
+ const deleteProject = useProjectStore((s) => s.deleteProject);
+ const currentUserId = useUserStore(userProfileSelectors.userId);
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState<unknown>();
+ const updateProject = useProjectStore((s) => s.updateProject);
+ const save = async () => {
+ setPending(true);
+ setError(undefined);
+ try {
+ const saved = await updateProject(project.id, {
+ name: name.trim(),
+ slug: slug.trim() || null,
+ description: description.trim() || null,
+ });
+ navigate(`/project/${saved.slug ?? saved.id}/settings/general`, { replace: true });
+ toast.success(t('rename.success'));
+ } catch (error) {
+ console.error('Failed to update project', error);
+ setError(error);
+ } finally {
+ setPending(false);
+ }
+ };
+ const saveDisabled =
+ pending ||
+ !name.trim() ||
+ !isProjectSlugValid(slug) ||
+ (name.trim() === project.name &&
+ slug.trim() === (project.slug ?? '') &&
+ description.trim() === (project.description ?? ''));
+
+ return (
+ <Flexbox gap={24}>
+ <Form
+ {...FORM_STYLE}
+ collapsible={false}
+ itemMinWidth="100%"
+ itemsType="group"
+ layout="vertical"
+ variant="filled"
+ footer={
+ <Flexbox gap={16}>
+ {error ? <AsyncError error={error} onRetry={save} /> : null}
+ <Flexbox horizontal justify="flex-end">
+ <Button disabled={saveDisabled} loading={pending} type="primary" onClick={save}>
+ {t('save', { ns: 'common' })}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ }
+ items={[
+ {
+ title: t('settings.general'),
+ children: [
+ {
+ label: t('create.nameLabel'),
+ children: (
+ <Input
+ aria-label={t('create.nameLabel')}
+ disabled={pending}
+ maxLength={255}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ ),
+ },
+ {
+ label: t('settings.identifier'),
+ desc: t('settings.identifierDescription'),
+ children: (
+ <Input
+ readOnly
+ aria-label={t('settings.identifier')}
+ value={project.identifier}
+ />
+ ),
+ },
+ {
+ label: t('create.slugLabel'),
+ desc: t('settings.slugDescription'),
+ help: isProjectSlugValid(slug) ? undefined : t('create.slugInvalid'),
+ validateStatus: isProjectSlugValid(slug) ? undefined : 'error',
+ children: (
+ <Input
+ aria-label={t('create.slugLabel')}
+ disabled={pending}
+ maxLength={100}
+ value={slug}
+ onChange={(e) => setSlug(e.target.value.toLowerCase())}
+ />
+ ),
+ },
+ {
+ label: t('settings.description'),
+ children: (
+ <TextArea
+ aria-label={t('settings.description')}
+ autoSize={{ minRows: 3, maxRows: 8 }}
+ disabled={pending}
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ />
+ ),
+ },
+ ],
+ },
+ ]}
+ />
+ {currentUserId === project.userId && (
+ <Form
+ {...FORM_STYLE}
+ itemsType="flat"
+ variant="filled"
+ items={[
+ {
+ label: t('list.deleteAction'),
+ desc: t('list.deleteConfirmDescription', { name: project.name }),
+ minWidth: undefined,
+ children: (
+ <Button
+ danger
+ disabled={pending}
+ onClick={() =>
+ confirmModal({
+ title: t('list.deleteConfirmTitle'),
+ content: t('list.deleteConfirmDescription', { name: project.name }),
+ okText: t('delete', { ns: 'common' }),
+ cancelText: t('cancel', { ns: 'common' }),
+ okButtonProps: { danger: true },
+ onOk: async () => {
+ try {
+ await deleteProject(project.id);
+ navigate('/projects', { replace: true });
+ } catch (error) {
+ console.error('Failed to delete project', error);
+ toast.error(t('list.deleteError'));
+ throw error;
+ }
+ },
+ })
+ }
+ >
+ {t('list.deleteAction')}
+ </Button>
+ ),
+ },
+ ]}
+ />
+ )}
+ </Flexbox>
+ );
+}
diff --git a/src/features/Projects/WorkingDirectories/Page.tsx b/src/features/Projects/WorkingDirectories/Page.tsx
new file mode 100644
index 00000000000..22482971b8f
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/Page.tsx
@@ -0,0 +1,51 @@
+import { Flexbox } from '@lobehub/ui';
+import { Tabs, Text } from '@lobehub/ui/base-ui';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import AsyncError from '@/components/AsyncError';
+import { RouteLoading } from '@/components/Skeleton/RouteSegment';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
+import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
+
+import { GeneralSettings } from './GeneralSettings';
+import { ProjectWorkingDirectories } from './index';
+import { WorkingDirectorySettings } from './WorkingDirectorySettings';
+
+export function ProjectDirectoriesPage() {
+ const { t } = useTranslation('project');
+ const { section = 'general' } = useParams<{ section?: string }>();
+ const navigate = useWorkspaceAwareNavigate();
+ const { projectId } = useActiveRouteParams<{ projectId: string }>();
+ const { error, revalidate } = useProjectStore((s) => s.useFetchProjectDetail)(projectId);
+ const detail = useCurrentProjectDetail(projectId);
+ if (error && !detail) return <AsyncError error={error} variant="page" onRetry={revalidate} />;
+ if (!detail) return <RouteLoading />;
+ return (
+ <Flexbox flex={1} padding={32} style={{ overflow: 'auto' }}>
+ <Flexbox gap={28} style={{ width: '100%', maxWidth: 800, marginInline: 'auto' }}>
+ <Text fontSize={24} weight={600}>
+ {t('settings.title')}
+ </Text>
+ <Tabs
+ activeKey={section}
+ variant="square"
+ items={[
+ { label: t('settings.general'), key: 'general' },
+ { label: t('settings.environments'), key: 'environments' },
+ { label: t('settings.workLocations'), key: 'directories' },
+ ]}
+ onChange={(key) => navigate(`/project/${projectId}/settings/${key}`)}
+ />
+ {section === 'general' ? (
+ <GeneralSettings key={detail.project.id} project={detail.project} />
+ ) : section === 'directories' ? (
+ <WorkingDirectorySettings projectId={detail.project.id} />
+ ) : (
+ <ProjectWorkingDirectories projectId={detail.project.id} />
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+}
diff --git a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx b/src/features/Projects/WorkingDirectories/SidebarTopics.tsx
new file mode 100644
index 00000000000..7b2bdd00b84
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/SidebarTopics.tsx
@@ -0,0 +1,232 @@
+import { Flexbox } from '@lobehub/ui';
+import {
+ ActionIcon,
+ Button,
+ createModal,
+ ModalFooter,
+ Select,
+ Text,
+ useModalContext,
+} from '@lobehub/ui/base-ui';
+import { PlusIcon } from 'lucide-react';
+import { useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import Filter from '@/features/AgentSidebar/Topic/Filter';
+import { useAgentTopicGroupMode } from '@/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode';
+import ToggleGroups from '@/features/AgentSidebar/Topic/ToggleGroups';
+import ByProjectMode from '@/features/AgentSidebar/Topic/TopicListContent/ByProjectMode';
+import ByStatusMode from '@/features/AgentSidebar/Topic/TopicListContent/ByStatusMode';
+import ByTimeMode from '@/features/AgentSidebar/Topic/TopicListContent/ByTimeMode';
+import FlatMode from '@/features/AgentSidebar/Topic/TopicListContent/FlatMode';
+import { TopicListScopeContext } from '@/features/AgentSidebar/Topic/TopicListScope';
+import AssigneeAgentSelector from '@/features/AgentTasks/features/AssigneeAgentSelector';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import type { ProjectDirectory } from '@/store/projectWorkingDirectory';
+import {
+ useProjectDirectories,
+ useProjectDirectoryStore,
+ useProjectTopics,
+} from '@/store/projectWorkingDirectory';
+
+import { getProjectConversationPath } from '../Layout/navigation';
+import { openAddDirectoryModal } from './AddDirectoryModal';
+import { openEnvironmentModal } from './EnvironmentModal';
+import { useDirectoryAgent } from './useDirectoryAgent';
+
+function StartDirectoryContent({
+ directories,
+ coordinatorAgentId,
+ projectId,
+ initialDirectoryId,
+}: {
+ directories: ProjectDirectory[];
+ coordinatorAgentId: string;
+ projectId: string;
+ initialDirectoryId?: string;
+}) {
+ const [directoryId, setDirectoryId] = useState(
+ initialDirectoryId ?? (directories.length === 1 ? directories[0].id : ''),
+ );
+ useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);
+ const liveDirectories = useProjectDirectories(projectId);
+ const locations = liveDirectories.length ? liveDirectories : directories;
+ const directory = locations.find((d) => d.id === directoryId);
+ const attachEnvironment = useProjectDirectoryStore((s) => s.attachEnvironment);
+ const { t } = useTranslation('project');
+ const { close } = useModalContext();
+ const navigate = useWorkspaceAwareNavigate();
+ const { agentId, agentName, setAgentId } = useDirectoryAgent(coordinatorAgentId);
+ const startTopic = useProjectDirectoryStore((s) => s.startTopic);
+ const createTopic = useProjectDirectoryStore((s) => s.createProjectTopic);
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState<unknown>();
+ const start = async () => {
+ setPending(true);
+ setError(undefined);
+ try {
+ const topic = directory
+ ? await startTopic(directory.id, agentId, t('directories.untitled'))
+ : await createTopic({ projectId, agentId, title: t('directories.untitled') });
+ close();
+ navigate(getProjectConversationPath(projectId, topic.id));
+ } catch (error) {
+ console.error('Failed to start directory work', error);
+ setError(error);
+ } finally {
+ setPending(false);
+ }
+ };
+ return (
+ <>
+ <Flexbox gap={16} padding={16}>
+ <Text>{t('topics.executionContext')}</Text>
+ <Select
+ aria-label={t('topics.executionContext')}
+ disabled={pending}
+ value={directoryId || '__none__'}
+ options={[
+ { value: '__none__', label: t('topics.conversationOnly') },
+ ...locations
+ .filter((d) => d.instanceId)
+ .map((d) => ({
+ value: d.id,
+ label: `${d.environmentName || d.name} · ${d.deviceName || d.deviceId} · ${d.path}`,
+ })),
+ ]}
+ onChange={(id) => setDirectoryId(id === '__none__' ? '' : (id ?? ''))}
+ />
+ {!locations.length && (
+ <Button
+ onClick={() =>
+ openEnvironmentModal({
+ onSaved: async (env) => {
+ await attachEnvironment(projectId, env.id);
+ openAddDirectoryModal(projectId, env.id);
+ },
+ })
+ }
+ >
+ {t('settings.addDirectory')}
+ </Button>
+ )}
+ <AssigneeAgentSelector
+ currentAgentId={agentId}
+ disabled={pending}
+ onChange={(id) => id && setAgentId(id)}
+ >
+ <span>{agentName || t('directories.coordinator')}</span>
+ </AssigneeAgentSelector>
+ {error ? (
+ <AsyncError
+ description={error instanceof Error ? error.message : undefined}
+ error={error}
+ onRetry={start}
+ />
+ ) : null}
+ </Flexbox>
+ <ModalFooter>
+ <Button disabled={pending} onClick={close}>
+ {t('cancel', { ns: 'common' })}
+ </Button>
+ <Button loading={pending} type="primary" onClick={start}>
+ {t('directories.start')}
+ </Button>
+ </ModalFooter>
+ </>
+ );
+}
+export function ProjectDirectoryTopics(props: { projectId: string; coordinatorAgentId: string }) {
+ const scope = useMemo(() => ({ projectId: props.projectId }), [props.projectId]);
+ return (
+ <TopicListScopeContext value={scope}>
+ <ProjectTopicList {...props} />
+ </TopicListScopeContext>
+ );
+}
+
+function ProjectTopicList({
+ projectId,
+ coordinatorAgentId,
+}: {
+ projectId: string;
+ coordinatorAgentId: string;
+}) {
+ const { t } = useTranslation('project');
+ const { topicGroupMode } = useAgentTopicGroupMode();
+ const request = useProjectDirectoryStore((s) => s.useFetchProjectTopics)(projectId);
+ const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);
+ const topics = useProjectTopics(projectId);
+ const directories = useProjectDirectories(projectId);
+ return (
+ <Flexbox gap={1} paddingBlock={12}>
+ <Flexbox horizontal align="center" justify="space-between" paddingInline={8}>
+ <Text fontSize={12} type="secondary" weight={500}>
+ {t('topics.title')}
+ </Text>
+ <Flexbox horizontal align="center" gap={2}>
+ <ToggleGroups />
+ <Filter />
+ <ActionIcon
+ aria-label={t('sidebar.newConversation')}
+ disabled={!directoriesRequest.hasData || !!directoriesRequest.error}
+ icon={PlusIcon}
+ size="small"
+ title={t('sidebar.newConversation')}
+ onClick={() =>
+ createModal({
+ title: t('sidebar.newConversation'),
+ content: (
+ <StartDirectoryContent
+ coordinatorAgentId={coordinatorAgentId}
+ directories={directories}
+ projectId={projectId}
+ />
+ ),
+ footer: null,
+ width: 520,
+ })
+ }
+ />
+ </Flexbox>
+ </Flexbox>
+ {request.error || directoriesRequest.error ? (
+ <AsyncError
+ error={request.error || directoriesRequest.error}
+ onRetry={() => Promise.all([request.revalidate(), directoriesRequest.revalidate()])}
+ />
+ ) : null}
+ {!request.hasData ? (
+ <SkeletonList />
+ ) : !topics.length && !request.error ? (
+ <Text type="secondary">{t('directories.noConversations')}</Text>
+ ) : null}
+ {topicGroupMode === 'flat' ? (
+ <FlatMode />
+ ) : topicGroupMode === 'byStatus' ? (
+ <ByStatusMode />
+ ) : topicGroupMode === 'byProject' ? (
+ <ByProjectMode />
+ ) : (
+ <ByTimeMode />
+ )}
+ </Flexbox>
+ );
+}
+
+export function openProjectTopicModal(options: {
+ projectId: string;
+ coordinatorAgentId: string;
+ directories: ProjectDirectory[];
+ initialDirectoryId?: string;
+ title: string;
+}) {
+ return createModal({
+ title: options.title,
+ content: <StartDirectoryContent {...options} />,
+ footer: null,
+ width: 520,
+ });
+}
diff --git a/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx b/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx
new file mode 100644
index 00000000000..a3ac04ca507
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/WorkingDirectorySettings.tsx
@@ -0,0 +1,163 @@
+import { Block, Flexbox, Icon } from '@lobehub/ui';
+import { Button, Select, Text } from '@lobehub/ui/base-ui';
+import { cssVar } from 'antd-style';
+import { FolderIcon, MessageSquarePlusIcon, PlusIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { useSearchParams } from 'react-router';
+
+import AsyncError from '@/components/AsyncError';
+import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useDeviceStore } from '@/store/device';
+import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
+import {
+ useProjectDirectories,
+ useProjectDirectoryStore,
+ useProjectEnvironments,
+} from '@/store/projectWorkingDirectory';
+
+import { openAddDirectoryModal } from './AddDirectoryModal';
+import { openBindDirectoryModal } from './BindDirectoryModal';
+import { openProjectTopicModal } from './SidebarTopics';
+
+export function WorkingDirectorySettings({ projectId }: { projectId: string }) {
+ const { t } = useTranslation('project');
+ const navigate = useWorkspaceAwareNavigate();
+ const [params, setParams] = useSearchParams();
+ const environmentId = params.get('environment') ?? '';
+ useProjectStore((s) => s.useFetchProjectDetail)(projectId);
+ const project = useCurrentProjectDetail(projectId);
+ const environmentsRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);
+ const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);
+ const environments = useProjectEnvironments(projectId);
+ const directories = useProjectDirectories(projectId);
+ const deviceRequest = useDeviceStore((s) => s.useFetchDevices)(true);
+ const devices = useDeviceStore((s) => s.devices);
+ const items = directories.filter((d) => !environmentId || d.environmentId === environmentId);
+ const error = environmentsRequest.error || directoriesRequest.error || deviceRequest.error;
+ return (
+ <Flexbox gap={20}>
+ <Flexbox gap={6}>
+ <Text fontSize={16} weight={600}>
+ {t('settings.workLocations')}
+ </Text>
+ <Text type="secondary">{t('settings.directoryDescription')}</Text>
+ </Flexbox>
+ <Flexbox horizontal gap={12} justify="space-between">
+ <Select
+ aria-label={t('directories.environment')}
+ value={environmentId || '__all__'}
+ options={[
+ { label: t('settings.allEnvironments'), value: '__all__' },
+ ...environments.map((env) => ({ label: env.name, value: env.id })),
+ ]}
+ onChange={(id) => setParams(id && id !== '__all__' ? { environment: id } : {})}
+ />
+ <Button
+ icon={PlusIcon}
+ type="primary"
+ onClick={() =>
+ environments.length
+ ? openAddDirectoryModal(projectId, environmentId || undefined)
+ : navigate(`/project/${projectId}/settings/environments`)
+ }
+ >
+ {t('settings.addDirectory')}
+ </Button>
+ </Flexbox>
+ {error ? (
+ <AsyncError
+ error={error}
+ onRetry={() =>
+ Promise.all([
+ environmentsRequest.revalidate(),
+ directoriesRequest.revalidate(),
+ deviceRequest.mutate(),
+ ])
+ }
+ />
+ ) : null}
+ {error ? null : !directoriesRequest.hasData ||
+ !environmentsRequest.hasData ||
+ deviceRequest.isLoading ? (
+ <Text>{t('loading', { ns: 'common' })}</Text>
+ ) : !items.length ? (
+ <Flexbox gap={12} paddingBlock={24}>
+ <Text type="secondary">{t('settings.noDirectories')}</Text>
+ {!environments.length && (
+ <Button onClick={() => navigate(`/project/${projectId}/settings/environments`)}>
+ {t('settings.addEnvironment')}
+ </Button>
+ )}
+ </Flexbox>
+ ) : (
+ <Block padding={0} variant="outlined">
+ {items.map((directory, index) => (
+ <Flexbox
+ key={directory.id}
+ padding={16}
+ 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>
+ </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,
+ 14,
+ )}
+ <Text fontSize={12}>{directory.deviceName || directory.deviceId}</Text>
+ <Text fontSize={12} type="secondary">
+ {t(
+ devices.find((d) => d.deviceId === directory.deviceId)?.online
+ ? 'settings.deviceOnline'
+ : 'settings.deviceOffline',
+ )}
+ </Text>
+ <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({
+ projectId,
+ deviceId: directory.deviceId,
+ path: directory.path,
+ })
+ : openProjectTopicModal({
+ projectId,
+ coordinatorAgentId: project!.project.coordinatorAgentId,
+ directories,
+ initialDirectoryId: directory.id,
+ title: t('directories.start'),
+ })
+ }
+ >
+ {t(
+ directory.instanceId
+ ? 'settings.startDirectoryConversation'
+ : 'directories.bind',
+ )}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ ))}
+ </Block>
+ )}
+ </Flexbox>
+ );
+}
diff --git a/src/features/Projects/WorkingDirectories/checkExecution.test.ts b/src/features/Projects/WorkingDirectories/checkExecution.test.ts
new file mode 100644
index 00000000000..8406dcf2d7f
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/checkExecution.test.ts
@@ -0,0 +1,33 @@
+import type { ChatTopic } from '@lobechat/types';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { deviceService } from '@/services/device';
+import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
+
+import { checkProjectExecution } from './checkExecution';
+
+afterEach(() => vi.restoreAllMocks());
+const topic = { id: 'topic', projectWorkingDirectoryId: 'directory' } as ChatTopic;
+describe('project send preflight', () => {
+ it('allows a plain conversation without a gateway', async () => {
+ await expect(checkProjectExecution(undefined, false)).resolves.toBeUndefined();
+ });
+ it('rejects an unavailable gateway before resolving a device', async () => {
+ const resolve = vi.spyOn(projectWorkingDirectoryService, 'resolve');
+ await expect(checkProjectExecution(topic, false)).rejects.toThrow();
+ expect(resolve).not.toHaveBeenCalled();
+ });
+ it('rejects offline devices and recovers only when the actual directory exists', async () => {
+ vi.spyOn(projectWorkingDirectoryService, 'resolve').mockResolvedValue({
+ data: { deviceId: 'pinned-device', path: '/project' },
+ success: true,
+ } as Awaited<ReturnType<typeof projectWorkingDirectoryService.resolve>>);
+ const stat = vi
+ .spyOn(deviceService, 'statPath')
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce({ exists: true, isDirectory: true });
+ await expect(checkProjectExecution(topic, true)).rejects.toThrow();
+ await expect(checkProjectExecution(topic, true)).resolves.toBeUndefined();
+ expect(stat).toHaveBeenLastCalledWith('pinned-device', '/project');
+ });
+});
diff --git a/src/features/Projects/WorkingDirectories/checkExecution.ts b/src/features/Projects/WorkingDirectories/checkExecution.ts
new file mode 100644
index 00000000000..0e2507d17c4
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/checkExecution.ts
@@ -0,0 +1,17 @@
+import type { ChatTopic } from '@lobechat/types';
+import { t } from 'i18next';
+
+import { deviceService } from '@/services/device';
+import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
+
+/** UI preflight only; the runtime revalidates the binding before every execution. */
+export async function checkProjectExecution(topic: ChatTopic | undefined, gatewayEnabled: boolean) {
+ if (!topic?.projectWorkingDirectoryId) return;
+ if (!gatewayEnabled) throw new Error(t('topics.gatewayUnavailable', { ns: 'project' }));
+ const { data: directory } = await projectWorkingDirectoryService.resolve(
+ topic.projectWorkingDirectoryId,
+ );
+ const stat = await deviceService.statPath(directory.deviceId, directory.path);
+ if (!stat?.exists || !stat.isDirectory)
+ throw new Error(t('settings.directoryUnavailable', { ns: 'project' }));
+}
diff --git a/src/features/Projects/WorkingDirectories/index.tsx b/src/features/Projects/WorkingDirectories/index.tsx
new file mode 100644
index 00000000000..126b816de94
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/index.tsx
@@ -0,0 +1,178 @@
+import { Block, Flexbox, Icon } from '@lobehub/ui';
+import { ActionIcon, Button, DropdownMenu, Text } from '@lobehub/ui/base-ui';
+import { GithubIcon } from '@lobehub/ui/icons';
+import { cssVar } from 'antd-style';
+import { ChevronDownIcon, FolderIcon, PencilIcon, PlusIcon } from 'lucide-react';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import {
+ useProjectDirectories,
+ useProjectDirectoryStore,
+ useProjectEnvironments,
+} from '@/store/projectWorkingDirectory';
+
+import { openEnvironmentModal } from './EnvironmentModal';
+
+export function ProjectWorkingDirectories({ projectId }: { projectId: string }) {
+ const { t } = useTranslation('project');
+ const navigate = useWorkspaceAwareNavigate();
+ const linkedRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);
+ const availableRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)();
+ const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);
+ const linked = useProjectEnvironments(projectId);
+ const available = useProjectEnvironments();
+ const directories = useProjectDirectories(projectId);
+ const attach = useProjectDirectoryStore((s) => s.attachEnvironment);
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState<unknown>();
+ const [failedEnvironmentId, setFailedEnvironmentId] = useState<string>();
+ const link = async (id: string) => {
+ setFailedEnvironmentId(id);
+ setPending(true);
+ setError(undefined);
+ try {
+ await attach(projectId, id);
+ setFailedEnvironmentId(undefined);
+ } catch (error) {
+ console.error('Failed to associate environment', error);
+ setError(error);
+ } finally {
+ setPending(false);
+ }
+ };
+ const unlinked = available.filter((env) => !linked.some((item) => item.id === env.id));
+ const requestError =
+ error || linkedRequest.error || availableRequest.error || directoriesRequest.error;
+ return (
+ <Flexbox gap={20}>
+ <Flexbox gap={12}>
+ <Flexbox horizontal align="center" gap={12} justify="space-between">
+ <Text fontSize={16} weight={600}>
+ {t('settings.environments')}
+ </Text>
+ <Flexbox horizontal gap={8}>
+ {!!unlinked.length && (
+ <DropdownMenu
+ items={unlinked.map((env) => ({
+ key: env.id,
+ label: env.name,
+ onClick: () => void link(env.id),
+ }))}
+ >
+ <Button disabled={pending} icon={ChevronDownIcon}>
+ {t('settings.reuseEnvironment')}
+ </Button>
+ </DropdownMenu>
+ )}
+ <Button
+ disabled={pending}
+ icon={PlusIcon}
+ type="primary"
+ onClick={() => openEnvironmentModal({ onSaved: (env) => link(env.id) })}
+ >
+ {t('directories.newEnvironment')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ <Text type="secondary">{t('settings.environmentDescription')}</Text>
+ {!!unlinked.length && (
+ <Text fontSize={13} type="secondary">
+ {t('settings.reuseEnvironmentDescription')}
+ </Text>
+ )}
+ </Flexbox>
+ {requestError ? (
+ <AsyncError
+ error={requestError}
+ onRetry={() =>
+ failedEnvironmentId
+ ? link(failedEnvironmentId)
+ : Promise.all([
+ linkedRequest.revalidate(),
+ availableRequest.revalidate(),
+ directoriesRequest.revalidate(),
+ ])
+ }
+ />
+ ) : !linkedRequest.hasData || !directoriesRequest.hasData ? (
+ <Text>{t('loading', { ns: 'common' })}</Text>
+ ) : !linked.length ? (
+ <Text type="secondary">{t('settings.noEnvironments')}</Text>
+ ) : (
+ <Block padding={0} variant="outlined">
+ {linked.map((env, index) => {
+ const source = env.configuration.sources?.find((source) => source.kind === 'git');
+ const count = directories.filter((d) => d.environmentId === env.id).length;
+ return (
+ <Flexbox
+ horizontal
+ align="center"
+ gap={16}
+ justify="space-between"
+ key={env.id}
+ padding={16}
+ style={
+ index ? { borderTop: `1px solid ${cssVar.colorBorderSecondary}` } : undefined
+ }
+ >
+ <Flexbox flex={1} gap={6} style={{ minWidth: 0 }}>
+ <Text weight={500}>{env.name}</Text>
+ <Flexbox horizontal align="center" gap={6}>
+ <Icon icon={source ? GithubIcon : FolderIcon} size={14} />
+ {source ? (
+ <a
+ href={source.url}
+ rel="noreferrer"
+ target="_blank"
+ style={{
+ color: cssVar.colorTextSecondary,
+ overflowWrap: 'anywhere',
+ fontSize: 13,
+ }}
+ >
+ {source.url.replace('https://github.com/', '')}
+ </a>
+ ) : (
+ <Text fontSize={13} type="secondary">
+ {t('settings.noRepository')}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ <Flexbox horizontal align="center" flex="none" gap={12}>
+ <Button
+ size="small"
+ onClick={() =>
+ navigate(`/project/${projectId}/settings/directories?environment=${env.id}`)
+ }
+ >
+ {t(count ? 'settings.viewDirectories' : 'settings.configureDirectory', {
+ count,
+ })}
+ </Button>
+ <ActionIcon
+ aria-label={t('directories.editEnvironment')}
+ icon={PencilIcon}
+ size="small"
+ title={t('directories.editEnvironment')}
+ onClick={() =>
+ openEnvironmentModal({
+ id: env.id,
+ name: env.name,
+ repositoryUrl: source?.url,
+ onSaved: () => {},
+ })
+ }
+ />
+ </Flexbox>
+ </Flexbox>
+ );
+ })}
+ </Block>
+ )}
+ </Flexbox>
+ );
+}
diff --git a/src/features/Projects/WorkingDirectories/useBindDirectory.test.ts b/src/features/Projects/WorkingDirectories/useBindDirectory.test.ts
new file mode 100644
index 00000000000..c03909022ea
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/useBindDirectory.test.ts
@@ -0,0 +1,52 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useBindDirectory } from './useBindDirectory';
+
+const { bind, refreshTopic } = vi.hoisted(() => ({ bind: vi.fn(), refreshTopic: vi.fn() }));
+vi.mock('@/store/projectWorkingDirectory', () => ({
+ useProjectDirectoryStore: (selector: (s: { bind: typeof bind }) => unknown) => selector({ bind }),
+}));
+vi.mock('@/store/chat', () => ({ useChatStore: { getState: () => ({ refreshTopic }) } }));
+const options = {
+ agentId: 'writer',
+ deviceId: 'laptop',
+ path: '/work/docs',
+ topicIds: ['old-1', 'old-2'],
+};
+describe('binding an Agent directory', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ bind.mockResolvedValue({ id: 'binding' });
+ });
+ it('files every supplied existing topic automatically and refreshes before closing', async () => {
+ const saved = vi.fn();
+ const { result } = renderHook(() => useBindDirectory(options, saved));
+ await act(async () => result.current.save('project', 'environment'));
+ expect(bind).toHaveBeenCalledWith(
+ expect.objectContaining({
+ topicIds: ['old-1', 'old-2'],
+ deviceId: 'laptop',
+ path: '/work/docs',
+ projectId: 'project',
+ }),
+ );
+ expect(refreshTopic).toHaveBeenCalled();
+ expect(saved).toHaveBeenCalled();
+ expect(result.current.pending).toBe(false);
+ });
+ it('keeps the form open and supports retry when association fails', async () => {
+ const error = new Error('Wait for conversation to finish');
+ bind.mockRejectedValueOnce(error);
+ const saved = vi.fn();
+ const { result } = renderHook(() => useBindDirectory(options, saved));
+ await act(async () => result.current.save('project', 'environment'));
+ expect(result.current.error).toBe(error);
+ expect(result.current.pending).toBe(false);
+ expect(saved).not.toHaveBeenCalled();
+ expect(refreshTopic).not.toHaveBeenCalled();
+ await act(async () => result.current.save('project', 'environment'));
+ expect(result.current.error).toBeUndefined();
+ expect(saved).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/features/Projects/WorkingDirectories/useBindDirectory.ts b/src/features/Projects/WorkingDirectories/useBindDirectory.ts
new file mode 100644
index 00000000000..91c3bc9a5ca
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/useBindDirectory.ts
@@ -0,0 +1,35 @@
+import { useState } from 'react';
+
+import { useChatStore } from '@/store/chat';
+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+
+import type { BindDirectoryOptions } from './BindDirectoryModal';
+
+export function useBindDirectory(options: BindDirectoryOptions, onSaved: () => void) {
+ const bind = useProjectDirectoryStore((s) => s.bind);
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState<unknown>();
+ const save = async (projectId: string, environmentId: string) => {
+ setPending(true);
+ setError(undefined);
+ try {
+ await bind({
+ agentId: options.agentId,
+ deviceId: options.deviceId,
+ environmentId,
+ name: options.path.split(/[\\/]/).findLast(Boolean) || options.path,
+ path: options.path,
+ projectId,
+ topicIds: options.topicIds,
+ });
+ await useChatStore.getState().refreshTopic();
+ onSaved();
+ } catch (error) {
+ console.error('Failed to bind project directory', error);
+ setError(error);
+ } finally {
+ setPending(false);
+ }
+ };
+ return { error, pending, save };
+}
diff --git a/src/features/Projects/WorkingDirectories/useDirectoryAgent.test.ts b/src/features/Projects/WorkingDirectories/useDirectoryAgent.test.ts
new file mode 100644
index 00000000000..3fbd5688cc6
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/useDirectoryAgent.test.ts
@@ -0,0 +1,42 @@
+import { act, renderHook } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { directoryAgentName, useDirectoryAgent } from './useDirectoryAgent';
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: () => 'Lobe AI' }) }));
+vi.mock('@/store/agent/selectors', () => ({
+ builtinAgentSelectors: { inboxAgentId: () => 'inbox-agent' },
+}));
+
+vi.mock('@/store/home', () => ({
+ useHomeStore: (selector: (state: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/home/selectors', () => ({
+ homeAgentListSelectors: {
+ getAgentById: (id: string) => () =>
+ id === 'selected-agent' ? { title: 'Selected Agent' } : undefined,
+ },
+}));
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: unknown) => unknown) => selector({ agentMap: {} }),
+}));
+
+describe('useDirectoryAgent', () => {
+ it('uses list metadata for the selected agent before its detail has been loaded', () => {
+ const { result } = renderHook(() => useDirectoryAgent('coordinator'));
+ expect(result.current.agentId).toBe('coordinator');
+ act(() => result.current.setAgentId('selected-agent'));
+ expect(result.current.agentId).toBe('selected-agent');
+ expect(result.current.agentName).toBe('Selected Agent');
+ });
+});
+
+it('labels the built-in agent without a stored title and honors custom display names', () => {
+ expect(directoryAgentName({ title: null }, true, 'Lobe AI')).toBe('Lobe AI');
+ expect(directoryAgentName({ name: 'Designer', title: 'Old title' }, false, 'Lobe AI')).toBe(
+ 'Designer',
+ );
+ const { result } = renderHook(() => useDirectoryAgent('coordinator'));
+ act(() => result.current.setAgentId('inbox-agent'));
+ expect(result.current.agentName).toBe('Lobe AI');
+});
diff --git a/src/features/Projects/WorkingDirectories/useDirectoryAgent.ts b/src/features/Projects/WorkingDirectories/useDirectoryAgent.ts
new file mode 100644
index 00000000000..8da54030356
--- /dev/null
+++ b/src/features/Projects/WorkingDirectories/useDirectoryAgent.ts
@@ -0,0 +1,26 @@
+import { agentDisplayName } from '@lobechat/types';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
+
+export const directoryAgentName = (
+ agent: { name?: string | null; title?: string | null } | undefined,
+ isInbox: boolean,
+ inboxName: string,
+) => agentDisplayName(agent) ?? (isInbox ? inboxName : undefined);
+
+export const useDirectoryAgent = (coordinatorAgentId: string) => {
+ const [agentId, setAgentId] = useState(coordinatorAgentId);
+ const { t } = useTranslation('chat');
+ const inboxId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const listName = useHomeStore((s) =>
+ agentDisplayName(homeAgentListSelectors.getAgentById(agentId)(s)),
+ );
+ const agentName = listName ?? (agentId === inboxId ? t('inbox.title') : undefined);
+
+ return { agentId, agentName, setAgentId };
+};
diff --git a/src/features/Projects/routeMeta.ts b/src/features/Projects/routeMeta.ts
index e53fa3138e3..f5ddaa2a7d7 100644
--- a/src/features/Projects/routeMeta.ts
+++ b/src/features/Projects/routeMeta.ts
@@ -1,5 +1,6 @@
import { FolderClosedIcon } from 'lucide-react';
+import ConversationSegmentSkeleton from '@/components/Skeleton/Conversation/Segment';
import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';
import { routeMeta } from '@/spa/router/routeMeta';
@@ -8,3 +9,15 @@ export const projectsRouteMeta = routeMeta({
Skeleton: createSurfaceSkeleton('grid'),
titleKey: 'navigation.projects',
});
+
+export const projectDirectoriesRouteMeta = routeMeta({
+ icon: FolderClosedIcon,
+ Skeleton: createSurfaceSkeleton('list'),
+ titleKey: 'project:settings.title',
+});
+
+export const projectConversationRouteMeta = routeMeta({
+ icon: FolderClosedIcon,
+ Skeleton: ConversationSegmentSkeleton,
+ titleKey: 'project:topics.title',
+});
diff --git a/src/hooks/useEffectiveAgencyConfig.test.ts b/src/hooks/useEffectiveAgencyConfig.test.ts
index d0f91751bff..9f13b6e866c 100644
--- a/src/hooks/useEffectiveAgencyConfig.test.ts
+++ b/src/hooks/useEffectiveAgencyConfig.test.ts
@@ -15,6 +15,26 @@ vi.mock('@/features/ResourcePermission/useAgentManagementAccess', () => ({
useAgentManagementAccess: () => managementAccess,
}));
+const topicState = vi.hoisted(() => ({
+ activeTopicId: 'topic-1',
+ topic: undefined as
+ | {
+ agentId?: string;
+ metadata?: { boundDeviceId?: string };
+ projectWorkingDirectoryId?: string;
+ }
+ | undefined,
+}));
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: typeof topicState) => unknown) => selector(topicState),
+}));
+vi.mock('@/store/chat/selectors', () => ({
+ topicSelectors: {
+ getTopicById: (id: string) => (s: typeof topicState) =>
+ id === s.activeTopicId ? s.topic : undefined,
+ },
+}));
+
vi.mock('@/store/agent', () => ({ useAgentStore: vi.fn() }));
vi.mock('@/store/agent/selectors', () => ({
agentByIdSelectors: {
@@ -72,6 +92,7 @@ const setupStores = ({
describe('useEffectiveAgencyConfig', () => {
beforeEach(() => {
vi.clearAllMocks();
+ topicState.topic = undefined;
managementAccess.canManageAgent = false;
managementAccess.isAccessLoading = false;
});
@@ -244,6 +265,21 @@ describe('useEffectiveAgencyConfig', () => {
expect(result.current.agencyConfig).toEqual(sharedConfig);
});
+ it('pins the conversation device without changing the agent default', () => {
+ setupStores();
+ topicState.topic = {
+ agentId: 'agent-1',
+ metadata: { boundDeviceId: 'project-device' },
+ projectWorkingDirectoryId: 'directory-1',
+ };
+ const { result } = renderHook(() => useEffectiveAgencyConfig('agent-1'));
+ expect(result.current.agencyConfig?.boundDeviceId).toBe('project-device');
+ expect(result.current.canSelectExecutionTarget).toBe(false);
+ const defaults = renderHook(() => useEffectiveAgencyConfig('agent-1', { topicId: null }));
+ expect(defaults.result.current.agencyConfig).toEqual(sharedConfig);
+ expect(sharedConfig.boundDeviceId).toBe('creator-device');
+ });
+
it('returns undefined config when agentId is missing', () => {
setupStores({ override: { boundDeviceId: 'my-device' }, workspaceId: 'ws-1' });
diff --git a/src/hooks/useEffectiveAgencyConfig.ts b/src/hooks/useEffectiveAgencyConfig.ts
index 9cb75e7931b..569246a71ec 100644
--- a/src/hooks/useEffectiveAgencyConfig.ts
+++ b/src/hooks/useEffectiveAgencyConfig.ts
@@ -111,6 +111,13 @@ export const useEffectiveAgencyConfig = (
agentId,
),
);
+ // A project-directory topic runs in its bound directory, so its execution
+ // target is owned by the binding rather than the picker.
+ const isProjectDirectoryTopic = useChatStore(
+ (s) =>
+ !!bindingTopicId &&
+ !!topicSelectors.getTopicById(bindingTopicId)(s)?.projectWorkingDirectoryId,
+ );
const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
const { agencyConfig, workspaceScoped } = applyTopicDeviceBinding(
{
@@ -129,7 +136,10 @@ export const useEffectiveAgencyConfig = (
agencyConfig,
canDisplayExecutionTarget: !!agentId && !isPreferenceLoading,
canSelectExecutionTarget:
- !!agentId && !isPreferenceLoading && agencyConfig?.executionTargetSelectionPolicy !== 'fixed',
+ !!agentId &&
+ !isProjectDirectoryTopic &&
+ !isPreferenceLoading &&
+ agencyConfig?.executionTargetSelectionPolicy !== 'fixed',
isPreferenceLoading,
workspaceScoped,
};
diff --git a/src/libs/next/proxy/define-config.test.ts b/src/libs/next/proxy/define-config.test.ts
index 9bedabe371e..a4ead8efff7 100644
--- a/src/libs/next/proxy/define-config.test.ts
+++ b/src/libs/next/proxy/define-config.test.ts
@@ -6,6 +6,9 @@ import { readFile } from 'node:fs/promises';
import { NextRequest } from 'next/server';
import { describe, expect, it, vi } from 'vitest';
+import { config as proxyConfig } from '@/proxy';
+
+import { createRouteMatcher } from './createRouteMatcher';
import { defineConfig } from './define-config';
vi.mock('@/auth', () => ({
@@ -159,3 +162,16 @@ describe('OIDC protocol endpoints', () => {
expect(getSession).toHaveBeenCalled();
});
});
+
+describe('project deep links', () => {
+ it.each(['/projects', '/project/environment-demo', '/project/environment-demo/tasks'])(
+ 'routes %s into the SPA on a direct request',
+ async (path) => {
+ expect(
+ createRouteMatcher(proxyConfig.matcher)(new NextRequest(`http://localhost:3010${path}`)),
+ ).toBe(true);
+ const rewrite = await run(`http://localhost:3010${path}`);
+ expect(new URL(rewrite!).pathname).toMatch(new RegExp(`/spa/[^/]+${path}$`));
+ },
+ );
+});
diff --git a/src/proxy.ts b/src/proxy.ts
index 027e71fb212..59860b6e3a2 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -38,6 +38,9 @@ export const config = {
'/resource',
'/resource(.*)',
'/profile(.*)',
+ '/projects',
+ '/project',
+ '/project/(.*)',
'/page',
'/page(.*)',
'/tasks',
diff --git a/src/routes/(main)/agent/(chat)/_layout/index.tsx b/src/routes/(main)/agent/(chat)/_layout/index.tsx
index 5a2028c57fc..c48c3692383 100644
--- a/src/routes/(main)/agent/(chat)/_layout/index.tsx
+++ b/src/routes/(main)/agent/(chat)/_layout/index.tsx
@@ -1,75 +1,14 @@
'use client';
-import { Flexbox } from '@lobehub/ui';
-import { useSize } from 'ahooks';
-import { createStaticStyles } from 'antd-style';
-import { memo, useRef } from 'react';
import { Outlet } from 'react-router';
-import ChatTerminalPanel from '@/features/ChatTerminal';
-import AgentWorkingSidebar from '@/features/Conversation/WorkingSidebar';
-import OverviewSlot from '@/features/Conversation/WorkingSidebar/OverviewSlot';
+import ConversationWorkspace from '@/features/Conversation/Workspace';
import ChatHeader from '@/routes/(main)/agent/features/Conversation/Header';
-import Portal from '@/routes/(main)/agent/features/Portal';
-import HeaderSlot from './HeaderSlot';
-
-const styles = createStaticStyles(({ css }) => ({
- // Named container queried by ChatHeader and the list top spacer: when this
- // column is wide enough, the header floats above the full-bleed message
- // stream instead of sitting in flow as a solid bar.
- conversationColumn: css`
- position: relative;
- container-name: agent-chat-layout;
- container-type: inline-size;
- `,
-}));
-
-const ChatLayout = memo(() => {
- // The working sidebar needs the row width to know whether it still fits next
- // to an open portal — a wide portal otherwise squeezes the conversation out.
- const rowRef = useRef<HTMLDivElement>(null);
- const rowSize = useSize(rowRef);
-
- return (
- <HeaderSlot.Provider>
- <OverviewSlot.Provider>
- <Flexbox
- flex={1}
- height={'100%'}
- style={{ minHeight: 0, overflow: 'hidden' }}
- width={'100%'}
- >
- <Flexbox
- horizontal
- flex={1}
- ref={rowRef}
- style={{ minHeight: 0, overflow: 'hidden', position: 'relative' }}
- width={'100%'}
- >
- <Flexbox
- className={styles.conversationColumn}
- flex={1}
- style={{ minHeight: 0, minWidth: 0 }}
- >
- <ChatHeader />
- <Flexbox horizontal flex={1} style={{ minHeight: 0, minWidth: 0 }}>
- <Flexbox flex={1} style={{ minHeight: 0, minWidth: 0 }}>
- <Outlet />
- </Flexbox>
- <OverviewSlot.Outlet />
- </Flexbox>
- </Flexbox>
- <Portal />
- <AgentWorkingSidebar availableWidth={rowSize?.width} />
- </Flexbox>
- <ChatTerminalPanel />
- </Flexbox>
- </OverviewSlot.Provider>
- </HeaderSlot.Provider>
- );
-});
-
-ChatLayout.displayName = 'ChatLayout';
+const ChatLayout = () => (
+ <ConversationWorkspace header={<ChatHeader />}>
+ <Outlet />
+ </ConversationWorkspace>
+);
export default ChatLayout;
diff --git a/src/routes/(main)/project/[projectId]/settings/index.tsx b/src/routes/(main)/project/[projectId]/settings/index.tsx
new file mode 100644
index 00000000000..845ce3e901e
--- /dev/null
+++ b/src/routes/(main)/project/[projectId]/settings/index.tsx
@@ -0,0 +1 @@
+export { ProjectDirectoriesPage as default } from '@/features/Projects/WorkingDirectories/Page';
diff --git a/src/services/__tests__/projectWorkingDirectory.test.ts b/src/services/__tests__/projectWorkingDirectory.test.ts
new file mode 100644
index 00000000000..f2e0fda0f2c
--- /dev/null
+++ b/src/services/__tests__/projectWorkingDirectory.test.ts
@@ -0,0 +1,43 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { lambdaClient } from '@/libs/trpc/client';
+import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ projectWorkingDirectory: {
+ listTopics: { query: vi.fn() },
+ },
+ },
+}));
+
+describe('environment topics', () => {
+ beforeEach(() => vi.clearAllMocks());
+ it('merges all directory conversations across agents in newest-first order', async () => {
+ vi.mocked(lambdaClient.projectWorkingDirectory.listTopics.query)
+ .mockResolvedValueOnce({
+ success: true,
+ data: [{ id: 'a', agentId: 'writer', title: 'Draft', updatedAt: new Date('2026-09-01') }],
+ } as Awaited<ReturnType<typeof lambdaClient.projectWorkingDirectory.listTopics.query>>)
+ .mockResolvedValueOnce({
+ success: true,
+ data: [
+ { id: 'b', agentId: 'reviewer', title: 'Review', updatedAt: new Date('2026-09-02') },
+ ],
+ } as Awaited<ReturnType<typeof lambdaClient.projectWorkingDirectory.listTopics.query>>);
+ const result = await projectWorkingDirectoryService.listEnvironmentTopics([
+ 'directory-a',
+ 'directory-b',
+ ]);
+ expect(result.data.map((topic) => topic.id)).toEqual(['b', 'a']);
+ expect(result.data.map((topic) => topic.agentId)).toEqual(['reviewer', 'writer']);
+ });
+ it('does not present a partial list as complete when a directory fails', async () => {
+ vi.mocked(lambdaClient.projectWorkingDirectory.listTopics.query)
+ .mockResolvedValueOnce({ success: true, data: [] })
+ .mockRejectedValueOnce(new Error('Access denied'));
+ await expect(projectWorkingDirectoryService.listEnvironmentTopics(['a', 'b'])).rejects.toThrow(
+ 'Access denied',
+ );
+ });
+});
diff --git a/src/services/project.ts b/src/services/project.ts
index cdceb5f4997..a8c375b8d67 100644
--- a/src/services/project.ts
+++ b/src/services/project.ts
@@ -52,8 +52,10 @@ class ProjectService {
requestCompletion = async (id: string) => lambdaClient.project.requestCompletion.mutate({ id });
- update = async (id: string, input: { name?: string }) =>
- lambdaClient.project.update.mutate({ id, ...input });
+ update = async (
+ id: string,
+ input: { description?: string | null; name?: string; slug?: string | null },
+ ) => lambdaClient.project.update.mutate({ id, ...input });
updateStatus = async (id: string, status: 'active' | 'archived' | 'backlog' | 'paused') =>
lambdaClient.project.updateStatus.mutate({ id, status });
diff --git a/src/services/projectWorkingDirectory.ts b/src/services/projectWorkingDirectory.ts
new file mode 100644
index 00000000000..1abfb1348a2
--- /dev/null
+++ b/src/services/projectWorkingDirectory.ts
@@ -0,0 +1,36 @@
+import { lambdaClient } from '@/libs/trpc/client';
+
+type Client = typeof lambdaClient.projectWorkingDirectory;
+export type BindProjectDirectoryInput = Parameters<Client['bind']['mutate']>[0];
+
+class ProjectWorkingDirectoryService {
+ listProjectTopics = (projectId: string) =>
+ lambdaClient.projectWorkingDirectory.listProjectTopics.query({ projectId });
+ createProjectTopic = (input: Parameters<Client['createProjectTopic']['mutate']>[0]) =>
+ lambdaClient.projectWorkingDirectory.createProjectTopic.mutate(input);
+ associateTopic = (input: Parameters<Client['associateTopic']['mutate']>[0]) =>
+ lambdaClient.projectWorkingDirectory.associateTopic.mutate(input);
+ listEnvironments = (projectId?: string) =>
+ lambdaClient.projectWorkingDirectory.listEnvironments.query({ projectId });
+ saveEnvironment = (input: Parameters<Client['saveEnvironment']['mutate']>[0]) =>
+ lambdaClient.projectWorkingDirectory.saveEnvironment.mutate(input);
+ attachEnvironment = (projectId: string, environmentId: string) =>
+ lambdaClient.projectWorkingDirectory.attachEnvironment.mutate({ projectId, environmentId });
+ bind = (input: BindProjectDirectoryInput) =>
+ lambdaClient.projectWorkingDirectory.bind.mutate(input);
+ list = (projectId?: string) => lambdaClient.projectWorkingDirectory.list.query({ projectId });
+ listTopics = (id: string) => lambdaClient.projectWorkingDirectory.listTopics.query({ id });
+ listEnvironmentTopics = async (directoryIds: string[]) => {
+ const responses = await Promise.all(directoryIds.map((id) => this.listTopics(id)));
+ return {
+ data: responses
+ .flatMap((response) => response.data)
+ .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()),
+ success: true,
+ };
+ };
+ resolve = (id: string) => lambdaClient.projectWorkingDirectory.resolve.query({ id });
+ startTopic = (input: Parameters<Client['startTopic']['mutate']>[0]) =>
+ lambdaClient.projectWorkingDirectory.startTopic.mutate(input);
+}
+export const projectWorkingDirectoryService = new ProjectWorkingDirectoryService();
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index 312096a3ed0..ecb3c9ae682 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -50,7 +50,11 @@ import { goalDetailRouteMeta, goalsRouteMeta } from '@/features/AgentGoals/route
import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';
import { agentsRouteMeta } from '@/features/AgentViewAll/routeMeta';
import { pageRouteMeta } from '@/features/Pages/routeMeta';
-import { projectsRouteMeta } from '@/features/Projects/routeMeta';
+import {
+ projectConversationRouteMeta,
+ projectDirectoriesRouteMeta,
+ projectsRouteMeta,
+} from '@/features/Projects/routeMeta';
import { settingsRouteMeta } from '@/features/Settings/features/routeMeta';
import { workspaceHomeRouteMeta } from '@/features/Workspace/routeMeta';
import WorkspaceProviderRedirect from '@/features/WorkspaceSetting/ProviderRedirect';
@@ -1000,9 +1004,18 @@ export const sharedMainAreaChildren: RouteObject[] = [
{
children: [
{
- element: redirectElement('tasks'),
+ element: redirectElement('conversation'),
index: true,
},
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/project/[projectId]/conversation'),
+ 'Desktop > Project Conversation',
+ { preloadId: 'project-conversation' },
+ ),
+ handle: { meta: projectConversationRouteMeta },
+ path: 'conversation/:topicId?',
+ },
{
element: dynamicElement(
() => import('@/routes/(main)/project/[projectId]/tasks'),
@@ -1011,6 +1024,15 @@ export const sharedMainAreaChildren: RouteObject[] = [
handle: { meta: tasksRouteMeta },
path: 'tasks',
},
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/project/[projectId]/settings'),
+ 'Desktop > Project Working Directories',
+ { preloadId: 'project-settings' },
+ ),
+ handle: { meta: projectDirectoriesRouteMeta },
+ path: 'settings/:section?',
+ },
{
element: dynamicElement(
() => import('@/routes/(main)/project/[projectId]/goals'),
diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index 80c8b46f8ea..c621ce574a8 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -196,10 +196,23 @@ describe('desktop router shared definition', () => {
?.map((route) => route.path)
.filter((routePath): routePath is string => Boolean(routePath));
- expect(projectPaths).toEqual(['tasks', 'goals', 'acceptance']);
+ expect(projectPaths).toEqual([
+ 'conversation/:topicId?',
+ 'tasks',
+ 'settings/:section?',
+ 'goals',
+ 'acceptance',
+ ]);
+ for (const section of ['general', 'environments', 'directories']) {
+ const matches = matchRoutes(
+ createMainAreaRoutes(factory),
+ `/project/project-1/settings/${section}`,
+ );
+ expect(matches?.at(-1)?.params.section).toBe(section);
+ }
expect(
(projectIndexRoute?.element as ReactElement<{ to: string }> | undefined)?.props.to,
- ).toBe('tasks');
+ ).toBe('conversation');
},
);
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
index ce3cdb5376f..5db8d8561e2 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
@@ -29,6 +29,7 @@ vi.mock('@/libs/trpc/client', () => ({
success: false,
}),
},
+ stopPendingApproval: { mutate: vi.fn().mockResolvedValue({ success: true }) },
submitHeteroIntervention: { mutate: vi.fn().mockResolvedValue({ success: true }) },
},
shareChat: {
@@ -1795,6 +1796,7 @@ describe('ConversationControl actions', () => {
it('retires the paused operation only when Stop wins the durable claim', async () => {
const { result } = renderHook(() => useChatStore());
const pausedOperationId = seedDurableTerminalCard(result);
+ vi.spyOn(result.current, 'refreshMessages').mockResolvedValue(undefined);
const executeGatewayAgentSpy = vi
.spyOn(result.current, 'executeGatewayAgent')
.mockResolvedValue({} as any);
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 5ccb7ac2dab..afcd1d498ed 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -53,6 +53,7 @@ import { chatService } from '@/services/chat';
import { resolveSelectedSkillsWithContent } from '@/services/chat/mecha/skillPreload';
import { resolveSelectedToolsWithContent } from '@/services/chat/mecha/toolPreload';
import { messageService } from '@/services/message';
+import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
import { topicService } from '@/services/topic';
import { getAgentStoreState } from '@/store/agent';
import {
@@ -473,7 +474,7 @@ export class ConversationLifecycleActionImpl {
// switcher. A workspace-local pick is intentionally private to this member
// and is therefore safe to execute in-process on their desktop. An existing
// conversation then stays on the machine it already ran on.
- const { agencyConfig, workspaceScoped } = applyTopicDeviceBinding(
+ const topicBinding = applyTopicDeviceBinding(
{
agencyConfig: resolveAgentAgencyConfig(agentConfig?.agencyConfig, deviceOverride, {
canManage,
@@ -488,7 +489,30 @@ export class ConversationLifecycleActionImpl {
),
getElectronStoreState().gatewayDeviceInfo?.deviceId,
);
+ const { workspaceScoped } = topicBinding;
+ let { agencyConfig } = topicBinding;
const isGatewayMode = this.#get().isGatewayModeEnabled(agentId);
+ const boundTopic = context.topicId
+ ? topicSelectors.getTopicById(context.topicId)(this.#get())
+ : undefined;
+ if (boundTopic?.projectWorkingDirectoryId) {
+ const { data: directory } = await projectWorkingDirectoryService.resolve(
+ boundTopic.projectWorkingDirectoryId,
+ );
+ if (!isGatewayMode)
+ throw new Error('Enable Gateway Mode to run in a project working directory');
+ if (
+ agencyConfig?.executionTargetSelectionPolicy === 'fixed' &&
+ agencyConfig.boundDeviceId !== directory.deviceId
+ )
+ throw new Error('Agent is fixed to another execution target');
+ agencyConfig = {
+ ...agencyConfig,
+ boundDeviceId: directory.deviceId,
+ executionTarget: 'device',
+ };
+ }
+
// Legacy agents may only carry `model: '<cli-type>'`. Keep gateway routing
// unchanged when it is available. Recover the provider when gateway mode is
// off so desktop can still spawn locally and non-desktop (Android/web) still
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index 07d2a6ac82e..3795b1ddff6 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -3391,6 +3391,38 @@ describe('topic action', () => {
});
});
describe('summaryTopicTitle', () => {
+ it('summarizes an uncached Project topic using its own Agent messages', async () => {
+ const topicId = 'project-uncached-topic';
+ const messages = [
+ { id: 'project-message', content: 'Work in my project', role: 'user' },
+ ] as UIChatMessage[];
+ useChatStore.setState({
+ activeAgentId: 'unrelated-agent',
+ topicDataMap: {},
+ topicDetailMap: {},
+ });
+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue({
+ id: topicId,
+ title: 'Old title',
+ createdAt: 1,
+ updatedAt: 1,
+ });
+ vi.spyOn(messageService, 'getMessages').mockResolvedValue(messages);
+ vi.spyOn(aiChatService, 'generateJSON').mockResolvedValue({
+ data: { title: 'Project summary' },
+ } as never);
+ const update = vi
+ .spyOn(useChatStore.getState(), 'internal_updateTopic')
+ .mockResolvedValue(undefined);
+ await useChatStore.getState().autoRenameTopicTitle(topicId, 'project-agent');
+ expect(messageService.getMessages).toHaveBeenCalledWith({
+ agentId: 'project-agent',
+ topicId,
+ });
+ expect(update).toHaveBeenCalledWith(topicId, { title: 'Project summary' });
+ expect(useChatStore.getState().activeAgentId).toBe('unrelated-agent');
+ });
+
it('should wait for assistant text before summarizing an audio-only conversation', async () => {
const topicId = 'topic-1';
const messages = [
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index aa9bdb0020f..57fb596d31f 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -434,7 +434,9 @@ export class ChatTopicActionImpl {
summaryTopicTitle = async (topicId: string, messages: UIChatMessage[]): Promise<void> => {
const { internal_updateTopicTitleInSummary } = this.#get();
- const topic = topicSelectors.getTopicById(topicId)(this.#get());
+ const topic =
+ topicSelectors.getTopicById(topicId)(this.#get()) ??
+ (await topicService.getTopicDetail(topicId));
if (!topic) return;
const messagesForTitle = normalizeTopicTitleMessages(messages);
@@ -1278,8 +1280,9 @@ export class ChatTopicActionImpl {
);
};
- autoRenameTopicTitle = async (id: string): Promise<void> => {
- const { activeAgentId: agentId, summaryTopicTitle } = this.#get();
+ autoRenameTopicTitle = async (id: string, topicAgentId?: string): Promise<void> => {
+ const { activeAgentId, summaryTopicTitle } = this.#get();
+ const agentId = topicAgentId ?? activeAgentId;
const messages = await messageService.getMessages({ agentId, topicId: id });
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index 67395180ea4..0d8d228a977 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -307,41 +307,50 @@ const displayTopicsForSidebar =
const topics = currentTopicsWithoutSystemTriggers(s);
if (!topics) return undefined;
- const visibleTopics = includeCompleted
- ? topics
- : topics.filter((topic) => topic.status !== 'completed');
-
- // Favorites first, then sorted by the chosen timestamp, then page-sliced
- const favTopics = visibleTopics.filter((t) => t.favorite);
- const rest = visibleTopics.filter((t) => !t.favorite);
- const pagedTopics = [...sortTopics(favTopics, sortBy), ...sortTopics(rest, sortBy)].slice(
- 0,
- pageSize,
- );
- const activeTopic = currentActiveTopic(s);
-
- // A search result or direct URL can open a topic outside the sidebar's
- // first page (or an archived topic excluded by the completed filter). Keep
- // the configured page intact and add that one active row so selection never
- // disappears merely because the route target was filtered out. An injected
- // favorite stays in the favorite prefix instead of falling below regular rows.
- if (
- activeTopic &&
- activeTopic.trigger !== 'cron' &&
- !pagedTopics.some((topic) => topic.id === activeTopic.id)
- ) {
- if (activeTopic.favorite) {
- const pagedFavorites = pagedTopics.filter((topic) => topic.favorite);
- const pagedRest = pagedTopics.filter((topic) => !topic.favorite);
-
- return [...sortTopics([...pagedFavorites, activeTopic], sortBy), ...pagedRest];
- }
-
- return [...pagedTopics, activeTopic];
+ return selectSidebarTopics(topics, pageSize, sortBy, includeCompleted, currentActiveTopic(s));
+ };
+
+export const selectSidebarTopics = (
+ topics: ChatTopic[],
+ pageSize: number,
+ sortBy: TopicSortBy = 'updatedAt',
+ includeCompleted = true,
+ activeTopic?: ChatTopic,
+): ChatTopic[] => {
+ const visibleTopics = includeCompleted
+ ? topics
+ : topics.filter((topic) => topic.status !== 'completed');
+
+ // Favorites first, then sorted by the chosen timestamp, then page-sliced
+ const favTopics = visibleTopics.filter((t) => t.favorite);
+ const rest = visibleTopics.filter((t) => !t.favorite);
+ const pagedTopics = [...sortTopics(favTopics, sortBy), ...sortTopics(rest, sortBy)].slice(
+ 0,
+ pageSize,
+ );
+
+ // A search result or direct URL can open a topic outside the sidebar's
+ // first page (or an archived topic excluded by the completed filter). Keep
+ // the configured page intact and add that one active row so selection never
+ // disappears merely because the route target was filtered out. An injected
+ // favorite stays in the favorite prefix instead of falling below regular rows.
+ if (
+ activeTopic &&
+ activeTopic.trigger !== 'cron' &&
+ !pagedTopics.some((topic) => topic.id === activeTopic.id)
+ ) {
+ if (activeTopic.favorite) {
+ const pagedFavorites = pagedTopics.filter((topic) => topic.favorite);
+ const pagedRest = pagedTopics.filter((topic) => !topic.favorite);
+
+ return [...sortTopics([...pagedFavorites, activeTopic], sortBy), ...pagedRest];
}
- return pagedTopics;
- };
+ return [...pagedTopics, activeTopic];
+ }
+
+ return pagedTopics;
+};
const getGroupFn = (
groupMode: TopicGroupMode,
@@ -392,6 +401,13 @@ const buildGroupedTopics = (
: groupFn(topics);
};
+export const groupSidebarTopics = (
+ topics: ChatTopic[],
+ groupMode: TopicGroupMode,
+ sortBy: TopicSortBy,
+ loadingTopicIds?: ReadonlySet<string>,
+) => buildGroupedTopics(topics, getGroupFn(groupMode, sortBy, loadingTopicIds));
+
const groupedTopicsSelector =
(groupFn: typeof groupTopicsByTime = groupTopicsByTime) =>
(s: ChatStoreState): GroupedTopic[] => {
@@ -416,7 +432,7 @@ const groupedTopicsForSidebar =
// buckets straight from `topic.status`.
const loadingTopicIds =
groupMode === 'byStatus' ? operationSelectors.visiblyRunningTopicIds(s) : undefined;
- return buildGroupedTopics(limitedTopics, getGroupFn(groupMode, sortBy, loadingTopicIds));
+ return groupSidebarTopics(limitedTopics, groupMode, sortBy, loadingTopicIds);
};
const hasMoreTopics = (s: ChatStoreState): boolean => {
diff --git a/src/store/project/store.ts b/src/store/project/store.ts
index cc602e6a028..7e68ffb598c 100644
--- a/src/store/project/store.ts
+++ b/src/store/project/store.ts
@@ -45,7 +45,10 @@ interface ProjectStore extends ProjectStoreState {
}) => Promise<ProjectListItem>;
deleteProject: (id: string) => Promise<void>;
refreshProjectList: () => Promise<void>;
- updateProject: (id: string, input: { name: string }) => Promise<ProjectListItem>;
+ updateProject: (
+ id: string,
+ input: Parameters<typeof projectService.update>[1],
+ ) => Promise<ProjectListItem>;
/** Fetch orchestration only; read the value with `useCurrentProjectDetail`. */
useFetchProjectDetail: (idOrSlug?: string) => ReplicaSyncResult;
/** Fetch orchestration only; read the rows with `useCurrentProjectList`. */
diff --git a/src/store/projectWorkingDirectory/index.test.ts b/src/store/projectWorkingDirectory/index.test.ts
new file mode 100644
index 00000000000..2e46a730ec4
--- /dev/null
+++ b/src/store/projectWorkingDirectory/index.test.ts
@@ -0,0 +1,151 @@
+import { renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { mutate, useClientDataSWR } from '@/libs/swr';
+import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
+
+import { PROJECT_TOPICS_POLL_INTERVAL, useProjectDirectoryStore } from './index';
+
+vi.mock('@/libs/swr', () => ({ mutate: vi.fn(), useClientDataSWR: vi.fn() }));
+
+vi.mock('@/libs/swr/useCacheScope', () => ({
+ getCacheScope: () => 'scope',
+ isScopeTrusted: () => true,
+ useCacheScope: () => 'scope',
+}));
+
+/** The replica sync call for the project-topics entry. */
+const syncCall = () =>
+ vi
+ .mocked(useClientDataSWR)
+ .mock.calls.find(
+ ([key]) => Array.isArray(key) && key[0] === 'replica:sync' && key[1] === 'projectTopics',
+ );
+
+const renderTopicList = (projectId = 'project-1') => {
+ vi.mocked(useClientDataSWR).mockReturnValue({ isValidating: false, mutate: vi.fn() } as any);
+ return renderHook(() => useProjectDirectoryStore.getState().useFetchProjectTopics(projectId));
+};
+
+/**
+ * Whether the recorded revalidations can match this entry. A scope-wide
+ * invalidation matches every key, so only a negative assertion proves a write
+ * stayed inside its own entry.
+ */
+const invalidates = (name: string, entryKey: string) =>
+ vi
+ .mocked(mutate)
+ .mock.calls.some(([match]) =>
+ (match as (key: unknown) => boolean)(['replica:sync', name, 1, 'scope', entryKey, undefined]),
+ );
+
+describe('projectWorkingDirectory store', () => {
+ describe('useFetchProjectTopics polling', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ useProjectDirectoryStore.setState({ projectTopicsMap: {} });
+ });
+
+ it('polls while a project conversation is in flight and stops once it settles', () => {
+ useProjectDirectoryStore.setState({
+ projectTopicsMap: { 'project-1': [{ status: 'running' } as any] },
+ });
+ const { rerender } = renderTopicList();
+
+ expect(syncCall()?.[2]).toMatchObject({ refreshInterval: PROJECT_TOPICS_POLL_INTERVAL });
+
+ // A settled project never re-reads its whole history on a timer.
+ vi.mocked(useClientDataSWR).mockClear();
+ useProjectDirectoryStore.setState({
+ projectTopicsMap: {
+ 'project-1': [
+ { status: 'active' },
+ { status: 'completed' },
+ { status: 'unread' },
+ { status: null },
+ ] as any,
+ },
+ });
+ rerender();
+
+ expect(syncCall()?.[2]).toMatchObject({ refreshInterval: 0 });
+ });
+
+ it('treats a conversation waiting for human input as in flight', () => {
+ useProjectDirectoryStore.setState({
+ projectTopicsMap: { 'project-1': [{ status: 'waitingForHuman' } as any] },
+ });
+ renderTopicList();
+
+ expect(syncCall()?.[2]).toMatchObject({ refreshInterval: PROJECT_TOPICS_POLL_INTERVAL });
+ });
+
+ it('does not poll before anything is loaded', () => {
+ renderTopicList();
+
+ expect(syncCall()?.[2]).toMatchObject({ refreshInterval: 0 });
+ });
+ });
+
+ describe('fetch result', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ useProjectDirectoryStore.setState({ projectTopicsMap: {} });
+ });
+
+ it('reports rows only once they have materialized', () => {
+ // `isValidating` on its own cannot separate a re-fetch from a first load,
+ // so surfaces gating on "nothing to show yet" read `hasData`.
+ const { rerender, result } = renderTopicList();
+ expect(result.current.hasData).toBe(false);
+
+ // A project with no conversations is loaded, not loading.
+ useProjectDirectoryStore.setState({ projectTopicsMap: { 'project-1': [] } });
+ rerender();
+
+ expect(result.current.hasData).toBe(true);
+ });
+ });
+
+ describe('write actions', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('refreshes the projections a bind lands in, and only those entries', async () => {
+ vi.spyOn(projectWorkingDirectoryService, 'bind').mockResolvedValue({ data: {} } as never);
+
+ await useProjectDirectoryStore.getState().bind({
+ deviceId: 'device-1',
+ name: 'repo',
+ path: '/repo',
+ projectId: 'project-1',
+ } as never);
+
+ // The directory, its environment and the conversations it absorbs.
+ expect(invalidates('projectDirectories', 'all')).toBe(true);
+ expect(invalidates('projectDirectories', 'project-1')).toBe(true);
+ expect(invalidates('projectTopics', 'project-1')).toBe(true);
+ // One environment is shared across projects, so both scopes converge.
+ expect(invalidates('projectEnvironments', 'project-1')).toBe(true);
+ expect(invalidates('projectEnvironments', 'all')).toBe(true);
+ expect(invalidates('environmentTopics', 'directory-1')).toBe(true);
+ });
+
+ it('keeps a project-scoped write inside its own project', async () => {
+ vi.spyOn(projectWorkingDirectoryService, 'createProjectTopic').mockResolvedValue({
+ data: {},
+ } as never);
+
+ await useProjectDirectoryStore.getState().createProjectTopic({
+ agentId: 'agent-1',
+ projectId: 'project-1',
+ title: 'Untitled',
+ } as never);
+
+ expect(invalidates('projectTopics', 'project-1')).toBe(true);
+ expect(invalidates('projectTopics', 'project-2')).toBe(false);
+ expect(invalidates('projectDirectories', 'project-1')).toBe(false);
+ });
+ });
+});
diff --git a/src/store/projectWorkingDirectory/index.ts b/src/store/projectWorkingDirectory/index.ts
new file mode 100644
index 00000000000..7ddb0b250c8
--- /dev/null
+++ b/src/store/projectWorkingDirectory/index.ts
@@ -0,0 +1,334 @@
+import type { StoreApi } from 'zustand';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn, type UseBoundStoreWithEqualityFn } from 'zustand/traditional';
+
+import {
+ createReplicaSlice,
+ createReplicaState,
+ recordLens,
+ type ReplicaState,
+ type ReplicaSyncResult,
+} from '@/libs/replica';
+import { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
+
+import {
+ ALL_PROJECTS_KEY,
+ directoryIdsFromKey,
+ directoryIdsKey,
+ type DirectoryTopic,
+ directoryTopicsResource,
+ environmentTopicsResource,
+ projectDirectoriesResource,
+ type ProjectDirectory,
+ type ProjectEnvironment,
+ projectEnvironmentsResource,
+ type ProjectTopic,
+ projectTopicsResource,
+} from './projection';
+
+export type {
+ DirectoryTopic,
+ ProjectDirectory,
+ ProjectEnvironment,
+ ProjectTopic,
+} from './projection';
+
+/** Poll cadence for the project topic list while a conversation is in flight. */
+export const PROJECT_TOPICS_POLL_INTERVAL = 5000;
+
+/** Statuses the server can still move on its own. */
+const IN_FLIGHT_STATUSES = new Set(['running', 'waitingForHuman']);
+
+/** Whether a project still has a conversation the server may still be updating. */
+const hasInFlightTopic = (topics: ProjectTopic[] | undefined) =>
+ !!topics?.some((topic) => IN_FLIGHT_STATUSES.has(topic.status ?? ''));
+
+/**
+ * What a `useFetch*` hook reports. It never carries rows — read them with the
+ * matching `use*` selector, which is the only place the data lives.
+ */
+export interface ProjectListSyncResult extends ReplicaSyncResult {
+ /**
+ * The rows have materialized (persisted replica or network). `isValidating`
+ * cannot tell a re-fetch from a first load, but surfaces that gate on "there
+ * is nothing to show yet" must not flash their empty state on every
+ * revalidation — nor before the first fetch has even been scheduled.
+ */
+ hasData: boolean;
+}
+
+export interface ProjectDirectoryStoreState {
+ /** Directory rows by project (`all` = every project of the scope). */
+ directoriesMap: Record<string, ProjectDirectory[]>;
+ /** Replica bookkeeping for `directoriesMap`. */
+ directoriesReplica: ReplicaState<ProjectDirectory[]>;
+ /** Conversations bound to one directory, by directory id. */
+ directoryTopicsMap: Record<string, DirectoryTopic[]>;
+ /** Replica bookkeeping for `directoryTopicsMap`. */
+ directoryTopicsReplica: ReplicaState<DirectoryTopic[]>;
+ /** Environments by project (`all` = every environment of the scope). */
+ environmentsMap: Record<string, ProjectEnvironment[]>;
+ /** Replica bookkeeping for `environmentsMap`. */
+ environmentsReplica: ReplicaState<ProjectEnvironment[]>;
+ /** The union of several directories' conversations, by directory-id set. */
+ environmentTopicsMap: Record<string, DirectoryTopic[]>;
+ /** Replica bookkeeping for `environmentTopicsMap`. */
+ environmentTopicsReplica: ReplicaState<DirectoryTopic[]>;
+ /** Conversations of one project, by project id. */
+ projectTopicsMap: Record<string, ProjectTopic[]>;
+ /** Replica bookkeeping for `projectTopicsMap`. */
+ projectTopicsReplica: ReplicaState<ProjectTopic[]>;
+}
+
+type Service = typeof projectWorkingDirectoryService;
+type ServiceParams<Name extends keyof Service> = Parameters<Service[Name]>;
+/** A service call's `data`, so a store action never widens its result to `unknown`. */
+type ServiceData<Name extends keyof Service> =
+ Awaited<ReturnType<Service[Name]>> extends { data: infer TData } ? TData : never;
+
+interface ProjectDirectoryStore extends ProjectDirectoryStoreState {
+ /** Bind a conversation to a directory of a project. */
+ associateTopic: (
+ ...args: ServiceParams<'associateTopic'>
+ ) => Promise<ServiceData<'associateTopic'>>;
+ /** Link an environment to a project. */
+ attachEnvironment: (...args: ServiceParams<'attachEnvironment'>) => Promise<void>;
+ /** Register a working directory, absorbing the conversations it covers. */
+ bind: (...args: ServiceParams<'bind'>) => Promise<ServiceData<'bind'>>;
+ /** Open a project conversation outside any directory binding. */
+ createProjectTopic: (
+ ...args: ServiceParams<'createProjectTopic'>
+ ) => Promise<ServiceData<'createProjectTopic'>>;
+ /** Create or rename an environment. */
+ saveEnvironment: (
+ ...args: ServiceParams<'saveEnvironment'>
+ ) => Promise<ServiceData<'saveEnvironment'>>;
+ /** Start a conversation inside one directory. */
+ startTopic: (id: string, agentId: string, title: string) => Promise<ServiceData<'startTopic'>>;
+ /** Fetch orchestration only; read the rows with `useProjectDirectories`. */
+ useFetchDirectories: (projectId?: string, enabled?: boolean) => ProjectListSyncResult;
+ /** Fetch orchestration only; read the rows with `useDirectoryTopics`. */
+ useFetchDirectoryTopics: (id?: string) => ProjectListSyncResult;
+ /** Fetch orchestration only; read the rows with `useProjectEnvironments`. */
+ useFetchEnvironments: (projectId?: string) => ProjectListSyncResult;
+ /** Fetch orchestration only; read the rows with `useEnvironmentTopics`. */
+ useFetchEnvironmentTopics: (directoryIds: string[]) => ProjectListSyncResult;
+ /** Fetch orchestration only; read the rows with `useProjectTopics`. */
+ useFetchProjectTopics: (projectId?: string) => ProjectListSyncResult;
+}
+
+export const initialProjectDirectoryState: ProjectDirectoryStoreState = {
+ directoriesMap: {},
+ directoriesReplica: createReplicaState(),
+ directoryTopicsMap: {},
+ directoryTopicsReplica: createReplicaState(),
+ environmentTopicsMap: {},
+ environmentTopicsReplica: createReplicaState(),
+ environmentsMap: {},
+ environmentsReplica: createReplicaState(),
+ projectTopicsMap: {},
+ projectTopicsReplica: createReplicaState(),
+};
+
+/**
+ * The `useFetch*` actions read their own store to decide what to report, so the
+ * bound hook is referenced before its initializer finishes. Annotate the
+ * variable: without it the equality-fn overload has to infer its store-mutator
+ * list *from* that initializer and becomes circular (`TS7022`), which would
+ * quietly degrade every selector in this module to `any`.
+ */
+export const useProjectDirectoryStore: UseBoundStoreWithEqualityFn<
+ StoreApi<ProjectDirectoryStore>
+> = createWithEqualityFn<ProjectDirectoryStore>()((set, get) => {
+ const directories = createReplicaSlice(projectDirectoriesResource, {
+ actionPrefix: 'projectWorkingDirectory/directories',
+ fetcher: (key) =>
+ projectWorkingDirectoryService.list(key === ALL_PROJECTS_KEY ? undefined : key),
+ get,
+ merge: (response) => response.data,
+ set,
+ stateKey: 'directoriesReplica',
+ view: recordLens<ProjectDirectoryStore, ProjectDirectory[]>('directoriesMap'),
+ });
+ const environments = createReplicaSlice(projectEnvironmentsResource, {
+ actionPrefix: 'projectWorkingDirectory/environments',
+ fetcher: (key) =>
+ projectWorkingDirectoryService.listEnvironments(key === ALL_PROJECTS_KEY ? undefined : key),
+ get,
+ merge: (response) => response.data,
+ set,
+ stateKey: 'environmentsReplica',
+ view: recordLens<ProjectDirectoryStore, ProjectEnvironment[]>('environmentsMap'),
+ });
+ const projectTopics = createReplicaSlice(projectTopicsResource, {
+ actionPrefix: 'projectWorkingDirectory/projectTopics',
+ fetcher: (projectId) => projectWorkingDirectoryService.listProjectTopics(projectId),
+ get,
+ merge: (response) => response.data,
+ set,
+ stateKey: 'projectTopicsReplica',
+ view: recordLens<ProjectDirectoryStore, ProjectTopic[]>('projectTopicsMap'),
+ });
+ const directoryTopics = createReplicaSlice(directoryTopicsResource, {
+ actionPrefix: 'projectWorkingDirectory/directoryTopics',
+ fetcher: (directoryId) => projectWorkingDirectoryService.listTopics(directoryId),
+ get,
+ merge: (response) => response.data,
+ set,
+ stateKey: 'directoryTopicsReplica',
+ view: recordLens<ProjectDirectoryStore, DirectoryTopic[]>('directoryTopicsMap'),
+ });
+ const environmentTopics = createReplicaSlice(environmentTopicsResource, {
+ actionPrefix: 'projectWorkingDirectory/environmentTopics',
+ fetcher: (idsKey) =>
+ projectWorkingDirectoryService.listEnvironmentTopics(directoryIdsFromKey(idsKey)),
+ get,
+ merge: (response) => response.data,
+ set,
+ stateKey: 'environmentTopicsReplica',
+ view: recordLens<ProjectDirectoryStore, DirectoryTopic[]>('environmentTopicsMap'),
+ });
+
+ return {
+ ...initialProjectDirectoryState,
+
+ createProjectTopic: async (input) => {
+ const result = await projectWorkingDirectoryService.createProjectTopic(input);
+ await projectTopics.revalidate(input.projectId);
+ return result.data;
+ },
+ associateTopic: async (input) => {
+ const result = await projectWorkingDirectoryService.associateTopic(input);
+ await Promise.all([
+ projectTopics.revalidate(input.projectId),
+ // The topic now points at a directory, so every projection that lists
+ // it (one directory's, or a set of directories') is stale too.
+ 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
+ // is denormalized into the directory rows — so both resources converge
+ // on the new value, for every loaded project.
+ await Promise.all([environments.revalidate(), directories.revalidate()]);
+ return result.data;
+ },
+ attachEnvironment: async (projectId, environmentId) => {
+ await projectWorkingDirectoryService.attachEnvironment(projectId, environmentId);
+ await Promise.all([
+ environments.revalidate(projectId),
+ // The scope-wide list gained the environment instanced by the attach.
+ environments.revalidate(ALL_PROJECTS_KEY),
+ ]);
+ },
+ bind: async (input) => {
+ const result = await projectWorkingDirectoryService.bind(input);
+ // One bind writes a directory, its environment and the conversations it
+ // absorbs — the replica resources are the only place that knows which
+ // projections those land in.
+ await Promise.all([
+ projectTopics.revalidate(input.projectId),
+ directories.revalidate(ALL_PROJECTS_KEY),
+ directories.revalidate(input.projectId),
+ environmentTopics.revalidate(),
+ environments.revalidate(),
+ environments.revalidate(input.projectId),
+ ]);
+ return result.data;
+ },
+ startTopic: async (id, agentId, title) => {
+ const result = await projectWorkingDirectoryService.startTopic({ agentId, id, title });
+ await Promise.all([
+ projectTopics.revalidate(),
+ directoryTopics.revalidate(id),
+ environmentTopics.revalidate(),
+ ]);
+ return result.data;
+ },
+
+ useFetchProjectTopics: (projectId) => {
+ // Poll from a reactive boolean derived from the folded rows: SWR's
+ // function-form `refreshInterval` is only re-evaluated after a timer
+ // fires, so a first call that returns 0 never schedules one at all.
+ const shouldPoll = useProjectDirectoryStore((state) =>
+ projectId ? hasInFlightTopic(state.projectTopicsMap[projectId]) : false,
+ );
+ const sync = projectTopics.useSync(projectId, {
+ refreshInterval: shouldPoll ? PROJECT_TOPICS_POLL_INTERVAL : 0,
+ });
+ const hasData = useProjectDirectoryStore((state) =>
+ projectId ? state.projectTopicsMap[projectId] !== undefined : false,
+ );
+ return { ...sync, hasData };
+ },
+ useFetchDirectories: (projectId, enabled = true) => {
+ const key = projectId ?? ALL_PROJECTS_KEY;
+ const sync = directories.useSync(key, { enabled });
+ const hasData = useProjectDirectoryStore((state) => state.directoriesMap[key] !== undefined);
+ return { ...sync, hasData };
+ },
+ useFetchEnvironments: (projectId) => {
+ const key = projectId ?? ALL_PROJECTS_KEY;
+ const sync = environments.useSync(key);
+ const hasData = useProjectDirectoryStore((state) => state.environmentsMap[key] !== undefined);
+ return { ...sync, hasData };
+ },
+ useFetchDirectoryTopics: (id) => {
+ const sync = directoryTopics.useSync(id);
+ const hasData = useProjectDirectoryStore((state) =>
+ id ? state.directoryTopicsMap[id] !== undefined : false,
+ );
+ return { ...sync, hasData };
+ },
+ useFetchEnvironmentTopics: (directoryIds) => {
+ const key = directoryIdsKey(directoryIds);
+ const sync = environmentTopics.useSync(key, { enabled: directoryIds.length > 0 });
+ const hasData = useProjectDirectoryStore(
+ (state) => state.environmentTopicsMap[key] !== undefined,
+ );
+ return { ...sync, hasData };
+ },
+ };
+}, shallow);
+
+const EMPTY_DIRECTORY_TOPICS: DirectoryTopic[] = [];
+const EMPTY_DIRECTORIES: ProjectDirectory[] = [];
+const EMPTY_ENVIRONMENTS: ProjectEnvironment[] = [];
+const EMPTY_PROJECT_TOPICS: ProjectTopic[] = [];
+
+/** Stable-identity empty lists: an absent entry and an empty one read the same. */
+const rowsOf = <T>(map: Record<string, T[]>, key: string | undefined, empty: T[]): T[] =>
+ (key ? map[key] : undefined) ?? empty;
+
+/** Conversations of one project. */
+export const useProjectTopics = (projectId?: string) =>
+ useProjectDirectoryStore((state) =>
+ rowsOf(state.projectTopicsMap, projectId, EMPTY_PROJECT_TOPICS),
+ );
+
+/** Directories of one project, or every directory of the scope. */
+export const useProjectDirectories = (projectId?: string) =>
+ useProjectDirectoryStore((state) =>
+ rowsOf(state.directoriesMap, projectId ?? ALL_PROJECTS_KEY, EMPTY_DIRECTORIES),
+ );
+
+/** Environments of one project, or every environment of the scope. */
+export const useProjectEnvironments = (projectId?: string) =>
+ useProjectDirectoryStore((state) =>
+ rowsOf(state.environmentsMap, projectId ?? ALL_PROJECTS_KEY, EMPTY_ENVIRONMENTS),
+ );
+
+/** Conversations bound to one directory. */
+export const useDirectoryTopics = (directoryId?: string) =>
+ useProjectDirectoryStore((state) =>
+ rowsOf(state.directoryTopicsMap, directoryId, EMPTY_DIRECTORY_TOPICS),
+ );
+
+/** Conversations bound to any of these directories. */
+export const useEnvironmentTopics = (directoryIds: string[]) =>
+ useProjectDirectoryStore((state) =>
+ rowsOf(state.environmentTopicsMap, directoryIdsKey(directoryIds), EMPTY_DIRECTORY_TOPICS),
+ );
diff --git a/src/store/projectWorkingDirectory/projection.ts b/src/store/projectWorkingDirectory/projection.ts
new file mode 100644
index 00000000000..3dc606238c5
--- /dev/null
+++ b/src/store/projectWorkingDirectory/projection.ts
@@ -0,0 +1,101 @@
+import { defineReplica } from '@/libs/replica';
+import type { projectWorkingDirectoryService } from '@/services/projectWorkingDirectory';
+
+/**
+ * Replica resources for the project-env surfaces (directories, their
+ * conversations, and the environments they resolve through).
+ *
+ * Every entry key is a primitive so a mount that asks for the same thing twice
+ * produces the same SWR key: the sync key carries `params` verbatim, and a
+ * freshly built object/array would refetch on each render.
+ */
+
+/** One entry covers every project of the scope when no project is named. */
+export const ALL_PROJECTS_KEY = 'all';
+
+type ProjectTopicsResponse = Awaited<
+ ReturnType<typeof projectWorkingDirectoryService.listProjectTopics>
+>;
+export type ProjectTopic = ProjectTopicsResponse['data'][number];
+
+type DirectoriesResponse = Awaited<ReturnType<typeof projectWorkingDirectoryService.list>>;
+export type ProjectDirectory = DirectoriesResponse['data'][number];
+
+type EnvironmentsResponse = Awaited<
+ ReturnType<typeof projectWorkingDirectoryService.listEnvironments>
+>;
+export type ProjectEnvironment = EnvironmentsResponse['data'][number];
+
+type DirectoryTopicsResponse = Awaited<
+ ReturnType<typeof projectWorkingDirectoryService.listTopics>
+>;
+export type DirectoryTopic = DirectoryTopicsResponse['data'][number];
+
+/** Conversations of one project (`projectTopicsMap[projectId]`). */
+export const projectTopicsResource = defineReplica<string, ProjectTopic[], ProjectTopicsResponse>({
+ key: (projectId) => projectId,
+ name: 'projectTopics',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Directories of one project, or of every project (`directoriesMap[projectId | 'all']`). */
+export const projectDirectoriesResource = defineReplica<
+ string,
+ ProjectDirectory[],
+ DirectoriesResponse
+>({
+ key: (projectId) => projectId,
+ name: 'projectDirectories',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Environments of one project, or of every project (`environmentsMap[projectId | 'all']`). */
+export const projectEnvironmentsResource = defineReplica<
+ string,
+ ProjectEnvironment[],
+ EnvironmentsResponse
+>({
+ key: (projectId) => projectId,
+ name: 'projectEnvironments',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Conversations bound to one directory (`directoryTopicsMap[directoryId]`). */
+export const directoryTopicsResource = defineReplica<
+ string,
+ DirectoryTopic[],
+ DirectoryTopicsResponse
+>({
+ key: (directoryId) => directoryId,
+ name: 'directoryTopics',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * The union of several directories' conversations, keyed by the sorted id set
+ * so two mounts that name the same directories share one entry and one fetch.
+ */
+export const environmentTopicsResource = defineReplica<
+ string,
+ DirectoryTopic[],
+ DirectoryTopicsResponse
+>({
+ key: (directoryIdsKey) => directoryIdsKey,
+ name: 'environmentTopics',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+const DIRECTORY_IDS_SEPARATOR = '|';
+
+/** Stable key for a set of directory ids, independent of the caller's order. */
+export const directoryIdsKey = (directoryIds: string[]) =>
+ [...directoryIds].sort().join(DIRECTORY_IDS_SEPARATOR);
+
+/** The ids a {@link directoryIdsKey} entry was built from (fetcher side). */
+export const directoryIdsFromKey = (directoryIdsKey: string) =>
+ directoryIdsKey ? directoryIdsKey.split(DIRECTORY_IDS_SEPARATOR) : [];