Skip to content

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

🐛 fix(project): run code projects in the sandbox, in the project's repository (#22761)

Arvin Xu85478e484dcb
diff --git a/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.attachRepository.test.ts b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.attachRepository.test.ts
new file mode 100644
index 00000000000..736765dc299
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.attachRepository.test.ts
@@ -0,0 +1,92 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ attachEnvironment: vi.fn(),
+ ensureForRepository: vi.fn(),
+ findManageableById: vi.fn(),
+}));
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return {};
+ }),
+}));
+
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
+ withScopedPermission: vi.fn(function () {
+ return (opts: any) => opts.next({ ctx: opts.ctx });
+ }),
+}));
+
+vi.mock('@/database/models/project', () => ({
+ ProjectModel: vi.fn(function () {
+ return {
+ attachEnvironment: mocks.attachEnvironment,
+ findManageableById: mocks.findManageableById,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/environment', () => ({
+ EnvironmentModel: vi.fn(function () {
+ return { ensureForRepository: mocks.ensureForRepository };
+ }),
+}));
+
+vi.mock('@/server/services/aiAgent/pipeline/precreatedTopic', () => ({
+ createAgentConfigResolver: vi.fn(),
+ resolvePrecreatedTopicSnapshot: vi.fn(),
+}));
+
+const { projectWorkingDirectoryRouter } = await import('../projectWorkingDirectory');
+
+const caller = () =>
+ projectWorkingDirectoryRouter.createCaller({ userId: 'member', workspaceId: 'ws-1' } as never);
+const input = {
+ projectId: 'project-1',
+ repository: { name: 'lobehub/lobe-tts', url: 'https://github.com/lobehub/lobe-tts' },
+};
+
+describe('projectWorkingDirectory.attachRepository', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.ensureForRepository.mockResolvedValue({ id: 'env-repo', name: 'lobehub/lobe-tts' });
+ });
+
+ // The composer's "add a repository" used the generic environment dialog,
+ // which without a GitHub integration made an environment with no repository
+ // at all — linked to the project, and never offered as one.
+ it('links an environment that checks the repository out', async () => {
+ mocks.findManageableById.mockResolvedValue({ id: 'project-1' });
+
+ const result = await caller().attachRepository(input);
+
+ expect(mocks.ensureForRepository).toHaveBeenCalledWith({
+ defaultBranch: undefined,
+ name: 'lobehub/lobe-tts',
+ repositoryUrl: 'https://github.com/lobehub/lobe-tts',
+ visibility: undefined,
+ });
+ expect(mocks.attachEnvironment).toHaveBeenCalledWith('project-1', 'env-repo');
+ expect(result.data).toEqual({ id: 'env-repo', name: 'lobehub/lobe-tts' });
+ });
+
+ it('makes nothing for a project the caller cannot manage', async () => {
+ mocks.findManageableById.mockResolvedValue(null);
+
+ await expect(caller().attachRepository(input)).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(mocks.ensureForRepository).not.toHaveBeenCalled();
+ });
+
+ // A workspace-public agent applies published environments only.
+ it('publishes the environment when asked to', async () => {
+ mocks.findManageableById.mockResolvedValue({ id: 'project-1' });
+
+ await caller().attachRepository({ ...input, visibility: 'public' });
+
+ expect(mocks.ensureForRepository).toHaveBeenCalledWith(
+ expect.objectContaining({ visibility: 'public' }),
+ );
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.createProjectTopic.test.ts b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.createProjectTopic.test.ts
index 93e38c89264..ee99730d9a0 100644
--- a/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.createProjectTopic.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.createProjectTopic.test.ts
@@ -5,6 +5,7 @@ const mocks = vi.hoisted(() => ({
createTopic: vi.fn(),
findById: vi.fn(),
findManageableById: vi.fn(),
+ resolveProjectTopicSandbox: vi.fn(),
}));
vi.mock('@/database/core/db-adaptor', () => ({
@@ -36,6 +37,10 @@ vi.mock('@/server/services/aiAgent/pipeline/precreatedTopic', () => ({
resolvePrecreatedTopicSnapshot: vi.fn(async () => ({ snapshot: { model: 'gpt' } })),
}));
+vi.mock('@/server/services/sandbox/projectPlacement', () => ({
+ resolveProjectTopicSandbox: mocks.resolveProjectTopicSandbox,
+}));
+
vi.mock('../_helpers/conversationResourceGuard', () => ({
assertCanUseConversationTargets: vi.fn(),
assertCanUseTopicTargets: vi.fn(),
@@ -52,6 +57,7 @@ describe('projectWorkingDirectory.createProjectTopic', () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.createTopic.mockImplementation(async (value) => ({ id: 'topic-1', ...value }));
+ mocks.resolveProjectTopicSandbox.mockResolvedValue({});
});
it('lets a workspace member who can read the project start a conversation in it', async () => {
@@ -73,4 +79,34 @@ describe('projectWorkingDirectory.createProjectTopic', () => {
);
expect(mocks.createTopic).not.toHaveBeenCalled();
});
+
+ // The topic is written before any run, so a repository the project has must
+ // be on it from the start — otherwise the first message runs in an empty sandbox.
+ it("starts the conversation in the project's repository", async () => {
+ mocks.findById.mockResolvedValue({ id: 'project-1', userId: 'creator' });
+ mocks.resolveProjectTopicSandbox.mockResolvedValue({
+ sandboxEnvironmentId: 'env-repo',
+ sandboxWorkingDirectory: 'projects/atlas/repo',
+ });
+
+ await caller().createProjectTopic({ ...input, environmentId: 'env-repo' });
+
+ expect(mocks.resolveProjectTopicSandbox).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'coordinator',
+ environmentId: 'env-repo',
+ projectId: 'project-1',
+ workspaceId: 'ws-1',
+ }),
+ );
+ expect(mocks.createTopic).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: {
+ sandboxEnvironmentId: 'env-repo',
+ sandboxWorkingDirectory: 'projects/atlas/repo',
+ },
+ model: 'gpt',
+ }),
+ );
+ });
});
diff --git a/apps/server/src/routers/lambda/projectWorkingDirectory.ts b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
index 28024be0a6c..83298355e13 100644
--- a/apps/server/src/routers/lambda/projectWorkingDirectory.ts
+++ b/apps/server/src/routers/lambda/projectWorkingDirectory.ts
@@ -19,6 +19,7 @@ import {
resolvePrecreatedTopicSnapshot,
} from '@/server/services/aiAgent/pipeline/precreatedTopic';
import { deviceGateway } from '@/server/services/deviceGateway';
+import { resolveProjectTopicSandbox } from '@/server/services/sandbox/projectPlacement';
import {
assertCanUseConversationTargets,
@@ -133,6 +134,8 @@ export const projectWorkingDirectoryRouter = router({
z.object({
projectId: z.string(),
agentId: z.string(),
+ /** The project repository the conversation works in; the first one when left out. */
+ environmentId: z.string().optional(),
title: z.string().trim().min(1).max(255),
}),
)
@@ -145,14 +148,24 @@ export const projectWorkingDirectoryRouter = router({
// project conversation needs read access, not ownership.
if (!(await ctx.projectModel.findById(input.projectId)))
throw new Error('Project not found or access denied');
- const { snapshot } = await resolvePrecreatedTopicSnapshot(
- ctx.precreatedTopicDeps,
- input.agentId,
- );
+ const [{ snapshot }, sandbox] = await Promise.all([
+ resolvePrecreatedTopicSnapshot(ctx.precreatedTopicDeps, input.agentId),
+ // A project with a repository works in it from the first message: the
+ // topic is written before any run, so no later pick would reach it.
+ resolveProjectTopicSandbox({
+ agentId: input.agentId,
+ db: ctx.serverDB,
+ environmentId: input.environmentId,
+ projectId: input.projectId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ }),
+ ]);
return {
data: await ctx.topicModel.create({
...snapshot,
agentId: input.agentId,
+ metadata: { ...snapshot.metadata, ...sandbox },
projectId: input.projectId,
title: input.title,
}),
@@ -175,6 +188,37 @@ export const projectWorkingDirectoryRouter = router({
data: await ctx.projectModel.attachEnvironment(input.projectId, input.environmentId),
success: true,
})),
+ /**
+ * Link a GitHub repository to the project: the caller's environment for it,
+ * made when they have none, attached in the same request — the project
+ * composer's "add a repository" needs nothing else to start on the code.
+ */
+ attachRepository: write
+ .input(
+ z.object({
+ projectId: z.string(),
+ repository: z.object({
+ defaultBranch: z.string().max(255).optional(),
+ name: z.string().trim().min(1).max(255),
+ url: z.string().min(1).max(2048),
+ }),
+ /** `public` for a workspace-public agent, which applies published environments only. */
+ visibility: z.enum(['private', 'public']).optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input: { projectId, repository, visibility } }) => {
+ // Checked before the environment is made, so a refusal leaves nothing behind.
+ if (!(await ctx.projectModel.findManageableById(projectId)))
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found or access denied' });
+ const environment = await ctx.environmentModel.ensureForRepository({
+ defaultBranch: repository.defaultBranch,
+ name: repository.name,
+ repositoryUrl: repository.url,
+ visibility,
+ });
+ await ctx.projectModel.attachEnvironment(projectId, environment.id);
+ return { data: environment, success: true };
+ }),
listEnvironments: procedure
.input(z.object({ projectId: z.string().optional() }))
.query(async ({ ctx, input }) => ({
diff --git a/apps/server/src/services/aiAgent/pipeline/topicProject.test.ts b/apps/server/src/services/aiAgent/pipeline/topicProject.test.ts
index 7827d35c140..b92573c0a64 100644
--- a/apps/server/src/services/aiAgent/pipeline/topicProject.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/topicProject.test.ts
@@ -1,13 +1,18 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { resolveTurnProjectId } from './topicProject';
+import { resolveTurnProjectId, withProjectSandbox } from './topicProject';
const mocks = vi.hoisted(() => ({
findById: vi.fn(),
+ resolveProjectTopicSandbox: vi.fn(),
resolveTask: vi.fn(),
}));
+vi.mock('@/server/services/sandbox/projectPlacement', () => ({
+ resolveProjectTopicSandbox: mocks.resolveProjectTopicSandbox,
+}));
+
vi.mock('@/database/models/project', () => ({
ProjectModel: vi.fn().mockImplementation(function () {
return { findById: mocks.findById };
@@ -90,3 +95,114 @@ describe('resolveTurnProjectId', () => {
).resolves.toBeUndefined();
});
});
+
+describe('withProjectSandbox', () => {
+ const sandbox = {
+ sandboxEnvironmentId: 'env-repo',
+ sandboxWorkingDirectory: 'projects/atlas/repo',
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.resolveProjectTopicSandbox.mockResolvedValue(sandbox);
+ });
+
+ // The sidebar's new topic is created by the run, not by the project home, so
+ // the repository has to be applied here too.
+ it("puts a new project conversation in the project's checkout", async () => {
+ await expect(
+ withProjectSandbox(deps, {
+ agentId: 'agt-1',
+ hasDirectory: false,
+ metadata: { reasoningConfig: { effort: 'high' } } as never,
+ projectId: 'proj-1',
+ }),
+ ).resolves.toEqual({ reasoningConfig: { effort: 'high' }, ...sandbox });
+ expect(mocks.resolveProjectTopicSandbox).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agt-1', projectId: 'proj-1', userId: 'user-1' }),
+ );
+ });
+
+ it('keeps a pick the composer already made', async () => {
+ const metadata = { sandboxWorkingDirectory: 'notes' };
+
+ await expect(
+ withProjectSandbox(deps, { hasDirectory: false, metadata, projectId: 'proj-1' }),
+ ).resolves.toBe(metadata);
+ expect(mocks.resolveProjectTopicSandbox).not.toHaveBeenCalled();
+ });
+
+ // An explicit temporary-sandbox pick used to arrive as no pick at all and
+ // was given the project's persistent checkout.
+ it('keeps an explicit temporary sandbox, and does not store the marker', async () => {
+ await expect(
+ withProjectSandbox(deps, {
+ hasDirectory: false,
+ metadata: { sandboxTemporary: true },
+ projectId: 'proj-1',
+ }),
+ ).resolves.toBeUndefined();
+ await expect(
+ withProjectSandbox(deps, {
+ hasDirectory: false,
+ metadata: { reasoningConfig: { effort: 'high' }, sandboxTemporary: true } as never,
+ projectId: 'proj-1',
+ }),
+ ).resolves.toEqual({ reasoningConfig: { effort: 'high' } });
+ expect(mocks.resolveProjectTopicSandbox).not.toHaveBeenCalled();
+ });
+
+ // A drive-entitled composer seeds the drive root before anyone picks; taking
+ // that as a pick kept project conversations out of the project's repository.
+ it("puts the project's checkout in place of a default nobody picked", async () => {
+ await expect(
+ withProjectSandbox(deps, {
+ hasDirectory: false,
+ metadata: { sandboxDrive: 'personal', sandboxSeeded: true, sandboxWorkingDirectory: '.' },
+ projectId: 'proj-1',
+ }),
+ ).resolves.toEqual(sandbox);
+ });
+
+ it('keeps the default when the project has no repository, without the marker', async () => {
+ mocks.resolveProjectTopicSandbox.mockResolvedValue({});
+
+ await expect(
+ withProjectSandbox(deps, {
+ hasDirectory: false,
+ metadata: { sandboxSeeded: true, sandboxWorkingDirectory: '.' },
+ projectId: 'proj-1',
+ }),
+ ).resolves.toEqual({ sandboxWorkingDirectory: '.' });
+ });
+
+ it('drops the marker outside a project too', async () => {
+ await expect(
+ withProjectSandbox(deps, {
+ hasDirectory: false,
+ metadata: { sandboxTemporary: true },
+ projectId: undefined,
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('leaves a device directory conversation alone', async () => {
+ await expect(
+ withProjectSandbox(deps, { hasDirectory: true, metadata: undefined, projectId: 'proj-1' }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('leaves a conversation outside any project alone', async () => {
+ await expect(
+ withProjectSandbox(deps, { hasDirectory: false, metadata: undefined, projectId: undefined }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('keeps the metadata unchanged when the project has no repository', async () => {
+ mocks.resolveProjectTopicSandbox.mockResolvedValue({});
+
+ await expect(
+ withProjectSandbox(deps, { hasDirectory: false, metadata: undefined, projectId: 'proj-1' }),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/topicProject.ts b/apps/server/src/services/aiAgent/pipeline/topicProject.ts
index cbf9ccb8573..96284ad5dbd 100644
--- a/apps/server/src/services/aiAgent/pipeline/topicProject.ts
+++ b/apps/server/src/services/aiAgent/pipeline/topicProject.ts
@@ -1,8 +1,10 @@
import type { LobeChatDatabase } from '@lobechat/database';
+import type { ChatTopicMetadata } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { ProjectModel } from '@/database/models/project';
import { TaskModel } from '@/database/models/task';
+import { resolveProjectTopicSandbox } from '@/server/services/sandbox/projectPlacement';
import type { AgentShareGate } from '../shareGate';
@@ -52,3 +54,60 @@ export const resolveTurnProjectId = async (
const task = await new TaskModel(deps.db, deps.userId, deps.workspaceId).resolve(input.taskId);
return task?.projectId ?? undefined;
};
+
+/**
+ * A new topic's metadata with the project's repository applied: a project
+ * conversation started anywhere — the sidebar's new topic, a task run — works
+ * in the project's checkout, as one started from the project home does.
+ *
+ * Left alone when there is no project, when the topic lives in a device
+ * directory (it runs there, not in the cloud), or when the conversation already
+ * picked where it keeps its files — a pick in the composer wins, the temporary
+ * sandbox included. The plan's default placement is not a pick: the checkout
+ * takes its place.
+ */
+export const withProjectSandbox = async (
+ deps: TurnProjectDeps,
+ input: {
+ /** The agent the run is for; its visibility decides which repositories it may apply. */
+ agentId?: string;
+ hasDirectory: boolean;
+ metadata: ChatTopicMetadata | undefined;
+ projectId: string | undefined;
+ },
+): Promise<ChatTopicMetadata | undefined> => {
+ const { agentId, hasDirectory, projectId } = input;
+ // Creation-time markers, never stored. `sandboxTemporary`: the composer chose
+ // a temporary sandbox on purpose, so nothing is applied over it.
+ // `sandboxSeeded`: the placement is the plan's default nobody chose, so a
+ // project's checkout takes its place.
+ const { sandboxSeeded, sandboxTemporary, ...rest } = input.metadata ?? {};
+ const metadata =
+ sandboxSeeded === undefined && sandboxTemporary === undefined
+ ? input.metadata
+ : Object.keys(rest).length > 0
+ ? rest
+ : undefined;
+ if (sandboxTemporary || !projectId || hasDirectory) return metadata;
+ if (
+ !sandboxSeeded &&
+ (metadata?.sandboxEnvironmentId ||
+ metadata?.sandboxInstanceId ||
+ metadata?.sandboxWorkingDirectory)
+ )
+ return metadata;
+
+ const sandbox = await resolveProjectTopicSandbox({ ...deps, agentId, projectId });
+ if (Object.keys(sandbox).length === 0) return metadata;
+
+ // The checkout replaces a default placement whole, drive included.
+ const {
+ sandboxDrive: _drive,
+ sandboxEnvironmentId: _environment,
+ sandboxInstanceId: _instance,
+ sandboxWorkingDirectory: _folder,
+ ...others
+ } = metadata ?? {};
+
+ return { ...others, ...sandbox };
+};
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index 573c19b7c9f..cb17abf0349 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -46,7 +46,7 @@ import type { InternalExecAgentParams } from '../types';
import { buildNewTopicMetadata } from './newTopicMetadata';
import { createUserTurnAnchor } from './resolveUserMessageParentId';
import { createStageTracer, openStageMark } from './sendTracing';
-import { resolveTurnProjectId } from './topicProject';
+import { resolveTurnProjectId, withProjectSandbox } from './topicProject';
import { buildUserTurnMetadata } from './userTurnMetadata';
const log = debug('lobe-server:ai-agent-service');
@@ -636,8 +636,12 @@ export const setupTurn = async (
const fallbackTitleSource = markdownToTxt(prompt);
const snapshot = await resolveNewTopicSnapshot(deps, agentConfig);
- const metadataWithSnapshot: ChatTopicMetadata | undefined =
- metadata || snapshot.metadata ? { ...metadata, ...snapshot.metadata } : undefined;
+ const metadataWithSnapshot = await withProjectSandbox(deps, {
+ agentId: resolvedAgentId,
+ hasDirectory: !!projectDirectory,
+ metadata: metadata || snapshot.metadata ? { ...metadata, ...snapshot.metadata } : undefined,
+ projectId: turnProjectId,
+ });
// Second argument: the id the client already rendered this topic under
// (sidebar row, message bucket). Absent → the model mints one as before.
const newTopicParams = {
diff --git a/apps/server/src/services/sandbox/__tests__/driveFolder.test.ts b/apps/server/src/services/sandbox/__tests__/driveFolder.test.ts
index e88ceb2fcad..f911e77b87f 100644
--- a/apps/server/src/services/sandbox/__tests__/driveFolder.test.ts
+++ b/apps/server/src/services/sandbox/__tests__/driveFolder.test.ts
@@ -1,14 +1,20 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { driveFolderCacheSize, driveFolderExists, forgetDriveFolders } from '../driveFolder';
+import {
+ driveFolderCacheSize,
+ driveFolderExists,
+ ensureDriveFolder,
+ forgetDriveFolders,
+} from '../driveFolder';
const listFiles = vi.fn();
+const createDirectory = vi.fn();
vi.mock('@/server/services/market', () => ({
// `function`, not an arrow: the service is constructed with `new`.
MarketService: vi.fn().mockImplementation(function () {
return {
- getSandboxStorageClient: () => ({ listFiles }),
+ getSandboxStorageClient: () => ({ createDirectory, listFiles }),
};
}),
}));
@@ -21,6 +27,7 @@ const check = (path: string, key = claim.key) =>
beforeEach(() => {
vi.useFakeTimers();
listFiles.mockReset().mockResolvedValue({ entries: [] });
+ createDirectory.mockReset().mockResolvedValue({ path: 'projects/a/repo' });
});
afterEach(() => {
@@ -60,3 +67,22 @@ describe('driveFolderExists', () => {
expect(driveFolderCacheSize()).toBe(1000);
});
});
+
+describe('ensureDriveFolder', () => {
+ const ensure = () =>
+ ensureDriveFolder({ claim, path: 'projects/a/repo', topicId: 't1', userId: 'u1' });
+
+ it('creates the folder in the conversation it is for and remembers it', async () => {
+ await expect(ensure()).resolves.toBe(true);
+ expect(createDirectory).toHaveBeenCalledWith({ path: 'projects/a/repo', topicId: 't1' });
+
+ await expect(check('projects/a/repo')).resolves.toBe(true);
+ expect(listFiles).not.toHaveBeenCalled();
+ });
+
+ it('answers false when the drive refuses', async () => {
+ createDirectory.mockRejectedValue(new Error('507'));
+
+ await expect(ensure()).resolves.toBe(false);
+ });
+});
diff --git a/apps/server/src/services/sandbox/__tests__/environmentInit.test.ts b/apps/server/src/services/sandbox/__tests__/environmentInit.test.ts
index bfb8a671c0e..c3d8853a6b4 100644
--- a/apps/server/src/services/sandbox/__tests__/environmentInit.test.ts
+++ b/apps/server/src/services/sandbox/__tests__/environmentInit.test.ts
@@ -206,6 +206,29 @@ describe('buildSandboxEnvironmentInitCommand', () => {
expect(existsSync(join(work, 'setup.txt'))).toBe(false);
});
+ // A project checkout removed while its sandbox lived on is made again empty;
+ // the record of the first clone used to keep it empty for good.
+ it('clones again into a checkout folder that was emptied after it was initialized', () => {
+ const command = buildSandboxEnvironmentInitCommand(init());
+ run(command, work);
+ rmSync(work, { force: true, recursive: true });
+ mkdirSync(work);
+
+ const again = run(command, work);
+
+ expect(environmentInitRan(again.stdout)).toBe(true);
+ expect(readFileSync(join(work, 'README.md'), 'utf8')).toBe('hello');
+ });
+
+ it('does not retry a failed clone just because its folder is still empty', () => {
+ const command = buildSandboxEnvironmentInitCommand(
+ init({ bootstrapCommand: undefined, sources: [{ url: `file://${root}/missing` }] }),
+ );
+
+ expect(environmentInitReport(run(command, work).stdout)).toContain('failed');
+ expect(run(command, work).stdout).toBe('');
+ });
+
it('leaves a folder that already holds files alone, silently', () => {
writeFileSync(join(work, 'mine.txt'), 'work');
diff --git a/apps/server/src/services/sandbox/__tests__/projectPlacement.test.ts b/apps/server/src/services/sandbox/__tests__/projectPlacement.test.ts
new file mode 100644
index 00000000000..1aaa353d7ca
--- /dev/null
+++ b/apps/server/src/services/sandbox/__tests__/projectPlacement.test.ts
@@ -0,0 +1,135 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ findEnvironmentById: vi.fn(),
+ getAgentVisibility: vi.fn(),
+ listEnvironments: vi.fn(),
+}));
+
+vi.mock('@/database/models/project', () => ({
+ ProjectModel: vi.fn(function () {
+ return { listEnvironments: mocks.listEnvironments };
+ }),
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn(function () {
+ return { getAgentVisibility: mocks.getAgentVisibility };
+ }),
+}));
+
+vi.mock('@/database/models/environment', () => ({
+ EnvironmentModel: vi.fn(function () {
+ return { findById: mocks.findEnvironmentById };
+ }),
+}));
+
+const { resolveProjectTopicSandbox } = await import('../projectPlacement');
+
+const db = {} as LobeChatDatabase;
+const gitConfiguration = {
+ kind: 'code',
+ sources: [{ kind: 'git', url: 'https://github.com/lobehub-biz/agent-mail' }],
+};
+const repository = {
+ configuration: gitConfiguration,
+ id: 'env-repo',
+ name: 'lobehub-biz/agent-mail',
+ visibility: 'private',
+};
+
+const resolve = (overrides: Record<string, unknown> = {}) =>
+ resolveProjectTopicSandbox({ db, projectId: 'proj_1', userId: 'user_1', ...overrides });
+
+describe('resolveProjectTopicSandbox', () => {
+ beforeEach(() => {
+ mocks.listEnvironments.mockReset().mockResolvedValue([repository]);
+ mocks.findEnvironmentById.mockReset().mockResolvedValue(repository);
+ mocks.getAgentVisibility.mockReset().mockResolvedValue('private');
+ });
+
+ it("works in the project's repository, checked out in the project's folder", async () => {
+ await expect(resolve()).resolves.toEqual({
+ sandboxEnvironmentId: 'env-repo',
+ sandboxWorkingDirectory: 'projects/proj_1/env-repo',
+ });
+ });
+
+ // The public drive is every member's; a private checkout stays on the member's own.
+ it('puts a private repository on the personal drive in a workspace', async () => {
+ await expect(resolve({ workspaceId: 'ws-1' })).resolves.toMatchObject({
+ sandboxDrive: 'personal',
+ });
+ });
+
+ it('puts a published repository on the public drive', async () => {
+ mocks.findEnvironmentById.mockResolvedValue({ ...repository, visibility: 'public' });
+
+ await expect(resolve({ workspaceId: 'ws-1' })).resolves.toMatchObject({
+ sandboxDrive: 'public',
+ });
+ });
+
+ it('skips linked environments that have no repository', async () => {
+ mocks.listEnvironments.mockResolvedValue([
+ { configuration: {}, id: 'env-empty', name: 'Cloud device (node)' },
+ repository,
+ ]);
+
+ await expect(resolve()).resolves.toMatchObject({ sandboxEnvironmentId: 'env-repo' });
+ expect(mocks.findEnvironmentById).toHaveBeenCalledWith('env-repo');
+ });
+
+ it('uses the repository the composer picked', async () => {
+ const other = { ...repository, id: 'env-other', name: 'lobehub/lobe-tts' };
+ mocks.listEnvironments.mockResolvedValue([repository, other]);
+ mocks.findEnvironmentById.mockResolvedValue(other);
+
+ await expect(resolve({ environmentId: 'env-other' })).resolves.toEqual({
+ sandboxEnvironmentId: 'env-other',
+ sandboxWorkingDirectory: 'projects/proj_1/env-other',
+ });
+ });
+
+ // A workspace-public agent applies published environments only; picking a
+ // private one would show a repository the run then never clones.
+ it('never gives a workspace-public agent a private repository', async () => {
+ mocks.getAgentVisibility.mockResolvedValue('public');
+
+ await expect(resolve({ agentId: 'agt-shared', workspaceId: 'ws-1' })).resolves.toEqual({});
+ await expect(
+ resolve({ agentId: 'agt-shared', environmentId: 'env-repo', workspaceId: 'ws-1' }),
+ ).resolves.toEqual({});
+ expect(mocks.findEnvironmentById).not.toHaveBeenCalled();
+ });
+
+ it('gives a workspace-public agent the published repository', async () => {
+ const published = { ...repository, id: 'env-pub', visibility: 'public' };
+ mocks.getAgentVisibility.mockResolvedValue('public');
+ mocks.listEnvironments.mockResolvedValue([repository, published]);
+ mocks.findEnvironmentById.mockResolvedValue(published);
+
+ await expect(resolve({ agentId: 'agt-shared', workspaceId: 'ws-1' })).resolves.toMatchObject({
+ sandboxDrive: 'public',
+ sandboxEnvironmentId: 'env-pub',
+ });
+ });
+
+ it('ignores a pick that is not linked to the project', async () => {
+ await expect(resolve({ environmentId: 'env-elsewhere' })).resolves.toEqual({});
+ expect(mocks.findEnvironmentById).not.toHaveBeenCalled();
+ });
+
+ it('starts anywhere when the project has no repository', async () => {
+ mocks.listEnvironments.mockResolvedValue([]);
+
+ await expect(resolve()).resolves.toEqual({});
+ });
+
+ it('never throws', async () => {
+ mocks.listEnvironments.mockRejectedValue(new Error('db down'));
+
+ await expect(resolve()).resolves.toEqual({});
+ });
+});
diff --git a/apps/server/src/services/sandbox/__tests__/session.test.ts b/apps/server/src/services/sandbox/__tests__/session.test.ts
index 5f306340bf0..19d353dfd74 100644
--- a/apps/server/src/services/sandbox/__tests__/session.test.ts
+++ b/apps/server/src/services/sandbox/__tests__/session.test.ts
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
driveFolderExists: vi.fn(),
+ ensureDriveFolder: vi.fn(),
findEnvironmentById: vi.fn(),
EnvironmentInstanceModel: vi.fn(),
listStorageDirectories: vi.fn(),
@@ -46,6 +47,7 @@ vi.mock('@/database/models/environmentInstance', () => ({
vi.mock('../driveFolder', () => ({
driveFolderExists: mocks.driveFolderExists,
+ ensureDriveFolder: mocks.ensureDriveFolder,
}));
const { resolveSandboxSessionConfig } = await import('../session');
@@ -93,6 +95,8 @@ describe('resolveSandboxSessionConfig', () => {
});
mocks.driveFolderExists.mockReset();
mocks.driveFolderExists.mockResolvedValue(true);
+ mocks.ensureDriveFolder.mockReset();
+ mocks.ensureDriveFolder.mockResolvedValue(true);
mocks.listStorageDirectories.mockReset();
mocks.listStorageDirectories.mockResolvedValue([]);
resolveSandboxStorageClaim.mockResolvedValue(CLAIM);
@@ -405,6 +409,44 @@ describe('resolveSandboxSessionConfig', () => {
fallback: 'directoryMissing',
mode: 'ephemeral',
});
+ expect(mocks.ensureDriveFolder).not.toHaveBeenCalled();
+ });
+
+ // A repository's checkout is filled by its environment, so bringing the
+ // folder back is a fresh clone — which is how a project conversation's
+ // checkout is made on its first run.
+ it("creates a repository checkout's folder the drive does not have yet", async () => {
+ findById.mockResolvedValue({
+ metadata: {
+ sandboxEnvironmentId: 'env-1',
+ sandboxWorkingDirectory: 'projects/atlas/repo',
+ },
+ });
+ mocks.driveFolderExists.mockResolvedValue(false);
+
+ await expect(resolve()).resolves.toMatchObject({
+ cwd: 'projects/atlas/repo',
+ mode: 'drive',
+ });
+ expect(mocks.ensureDriveFolder).toHaveBeenCalledWith(
+ expect.objectContaining({ claim: CLAIM, path: 'projects/atlas/repo', topicId: 'topic-1' }),
+ );
+ });
+
+ it('falls back when a checkout folder cannot be created', async () => {
+ findById.mockResolvedValue({
+ metadata: {
+ sandboxEnvironmentId: 'env-1',
+ sandboxWorkingDirectory: 'projects/atlas/repo',
+ },
+ });
+ mocks.driveFolderExists.mockResolvedValue(false);
+ mocks.ensureDriveFolder.mockResolvedValue(false);
+
+ await expect(resolve()).resolves.toMatchObject({
+ fallback: 'directoryMissing',
+ mode: 'ephemeral',
+ });
});
// A drive that could not be asked is not a folder that is gone.
diff --git a/apps/server/src/services/sandbox/driveFolder.ts b/apps/server/src/services/sandbox/driveFolder.ts
index e30393d0135..0beabd323e5 100644
--- a/apps/server/src/services/sandbox/driveFolder.ts
+++ b/apps/server/src/services/sandbox/driveFolder.ts
@@ -96,3 +96,35 @@ export const forgetDriveFolders = (storageKey: string) => {
if (key.startsWith(`${storageKey}\0`)) existsCache.delete(key);
}
};
+
+/**
+ * Create a folder a topic works in, parents included, and remember it.
+ *
+ * For a folder that is a repository's checkout rather than a person's pick:
+ * the environment fills an empty folder again, so bringing it back is a fresh
+ * clone, not an empty folder under a name someone chose to remove.
+ *
+ * `true` once the drive has it; `false` when it could not be made, which a
+ * caller treats like a missing folder.
+ */
+export const ensureDriveFolder = async ({
+ claim,
+ path,
+ topicId,
+ userId,
+ workspaceId,
+}: DriveFolderInput & { topicId?: string }): Promise<boolean> => {
+ try {
+ await new MarketService({
+ userInfo: { sandboxStorage: claim, userId, workspaceId: workspaceId ?? undefined },
+ })
+ .getSandboxStorageClient()
+ .createDirectory({ path, topicId });
+ remember(`${claim.key}\0${path}`);
+
+ return true;
+ } catch (error) {
+ log('Could not create drive folder %s on %s: %O', path, claim.key, error);
+ return false;
+ }
+};
diff --git a/apps/server/src/services/sandbox/environmentInit.ts b/apps/server/src/services/sandbox/environmentInit.ts
index 2e2441a53f8..6359dd71f66 100644
--- a/apps/server/src/services/sandbox/environmentInit.ts
+++ b/apps/server/src/services/sandbox/environmentInit.ts
@@ -194,9 +194,18 @@ export const buildSandboxEnvironmentInitCommand = (init: SandboxInitialization):
const record = `"\${HOME:-/tmp}/${SANDBOX_ENVIRONMENT_STATE_DIR}"`;
const key = `"$(printf '%s|%s' "$PWD" ${shellQuote(init.environmentId)} | cksum | cut -d ' ' -f 1)"`;
+ // A successful run that clones always leaves the checkout in the folder, so a
+ // `done` record beside an empty folder is stale: the folder was emptied or
+ // made again — a project checkout recreated after someone removed it — while
+ // the sandbox lived on. That folder is initialized again. A failed run's
+ // record still holds, so a broken clone is not retried on every call, and a
+ // setup with nothing to clone keeps relying on its record alone.
+ const staleWhenEmpty =
+ clones.length > 0 ? ` || [ "$(cat "$__lobe_state" 2>/dev/null)" = done ]` : '';
+
return [
`__lobe_state=${record}/${key}`,
- `if [ ! -e "$__lobe_state" ] && [ -z "$(ls -A . 2>/dev/null)" ]; then`,
+ `if [ -z "$(ls -A . 2>/dev/null)" ] && { [ ! -e "$__lobe_state" ]${staleWhenEmpty}; }; then`,
` echo ${SANDBOX_ENVIRONMENT_RAN_LINE}`,
` mkdir -p ${record}`,
` if ${body}; then`,
diff --git a/apps/server/src/services/sandbox/projectPlacement.ts b/apps/server/src/services/sandbox/projectPlacement.ts
new file mode 100644
index 00000000000..5325911cc80
--- /dev/null
+++ b/apps/server/src/services/sandbox/projectPlacement.ts
@@ -0,0 +1,88 @@
+import { projectCheckoutDirectory, type SandboxDrive } from '@lobechat/builtin-tool-cloud-sandbox';
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { ChatTopicMetadata } from '@lobechat/types';
+import debug from 'debug';
+
+import { AgentModel } from '@/database/models/agent';
+import { EnvironmentModel } from '@/database/models/environment';
+import { ProjectModel } from '@/database/models/project';
+
+const log = debug('lobe-server:sandbox:project-placement');
+
+export type ProjectTopicSandbox = Pick<
+ ChatTopicMetadata,
+ 'sandboxDrive' | 'sandboxEnvironmentId' | 'sandboxWorkingDirectory'
+>;
+
+export interface ProjectTopicSandboxInput {
+ /** The agent the conversation runs; a workspace-public one applies published environments only. */
+ agentId?: string;
+ db: LobeChatDatabase;
+ /** A repository the composer picked; must be one linked to the project. */
+ environmentId?: string;
+ projectId: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+const hasGitSource = (configuration: { sources?: { kind?: string }[] } | null | undefined) =>
+ (configuration?.sources ?? []).some((source) => source.kind === 'git');
+
+/**
+ * The sandbox a new project conversation starts in: the project's repository,
+ * checked out in the project's own folder on the drive.
+ *
+ * The folder is what makes it persistent. The sandbox initializes an empty
+ * folder from the environment and leaves a filled one alone, so the first
+ * conversation clones and every later one picks up the same checkout. Nothing
+ * is created here — the run creates the folder when it first needs it (see
+ * `resolvePlacement`), so starting a conversation never waits on a sandbox.
+ * Without a storage entitlement the run goes to a temporary sandbox, where the
+ * repository still applies.
+ *
+ * A private repository goes on the member's personal drive: the public drive
+ * is every member's, and the checkout can hold its owner's credentials.
+ *
+ * A workspace-public agent runs on its caller's session and applies published
+ * environments only (see `resolveInitialization`), so for one a private
+ * repository is never picked: it would be shown as the conversation's
+ * repository and then never cloned.
+ *
+ * Never throws; a project with no repository starts where any conversation
+ * does.
+ */
+export const resolveProjectTopicSandbox = async ({
+ agentId,
+ db,
+ environmentId,
+ projectId,
+ userId,
+ workspaceId,
+}: ProjectTopicSandboxInput): Promise<ProjectTopicSandbox> => {
+ try {
+ const linked = await new ProjectModel(db, userId, workspaceId).listEnvironments(projectId);
+ const sharedAgent =
+ !!workspaceId &&
+ !!agentId &&
+ (await new AgentModel(db, userId, workspaceId).getAgentVisibility(agentId)) === 'public';
+ const usable = linked.filter(
+ (item) => hasGitSource(item.configuration) && (!sharedAgent || item.visibility === 'public'),
+ );
+ const picked = environmentId ? usable.find((item) => item.id === environmentId) : usable[0];
+ if (!picked) return {};
+
+ const environment = await new EnvironmentModel(db, userId, workspaceId).findById(picked.id);
+ if (!environment) return {};
+
+ const drive: SandboxDrive = environment.visibility === 'public' ? 'public' : 'personal';
+
+ return {
+ ...(workspaceId && { sandboxDrive: drive }),
+ sandboxEnvironmentId: environment.id,
+ sandboxWorkingDirectory: projectCheckoutDirectory(projectId, environment.id),
+ };
+ } catch (error) {
+ log('Failed to resolve the sandbox for a topic in project %s: %O', projectId, error);
+ return {};
+ }
+};
diff --git a/apps/server/src/services/sandbox/session.ts b/apps/server/src/services/sandbox/session.ts
index afee652eb28..48e19679d4c 100644
--- a/apps/server/src/services/sandbox/session.ts
+++ b/apps/server/src/services/sandbox/session.ts
@@ -21,7 +21,7 @@ import { TopicModel } from '@/database/models/topic';
import { resolveScmCloneCredential } from '@/server/services/scm/cloneCredential';
import { sandboxStorageBinding } from './binding';
-import { driveFolderExists } from './driveFolder';
+import { driveFolderExists, ensureDriveFolder } from './driveFolder';
import { resolveSandboxStorageClaim } from './entitlement';
import { type SandboxInitialization, toSandboxInitialization } from './environmentInit';
import type { SandboxSessionSpecification } from './types';
@@ -365,10 +365,20 @@ const resolvePlacement = async ({
// Deleted since it was picked — by this member in another tab, or by a
// colleague on the public drive. Recreating it silently would bring back
- // an empty folder under a name someone chose to remove.
+ // an empty folder under a name someone chose to remove. A repository's
+ // checkout is the exception: the environment fills the folder, so a
+ // project conversation's checkout is made on its first run, and made
+ // again — a fresh clone — after someone removes it.
if ((await driveFolderExists({ claim, path: folder, userId, workspaceId })) === false) {
- log('Folder %o on topic %s is no longer on the drive', folder, topicId);
- return fallBack('directoryMissing');
+ const checkout = !!topic?.metadata?.sandboxEnvironmentId;
+ if (
+ !checkout ||
+ !(await ensureDriveFolder({ claim, path: folder, topicId, userId, workspaceId }))
+ ) {
+ log('Folder %o on topic %s is no longer on the drive', folder, topicId);
+ return fallBack('directoryMissing');
+ }
+ log('Created checkout folder %o for topic %s', folder, topicId);
}
log('Drive for topic %s: cwd=%o drive=%s', topicId, folder, drive);
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index ded22806dcc..d0871f30375 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -223,6 +223,18 @@
"overview.activeTasks": "In progress",
"overview.agentSelect": "Choose an agent",
"overview.composerPlaceholder": "Tell the project what to move forward next…",
+ "overview.context.repository.add": "Add a repository",
+ "overview.context.repository.addAction": "Add",
+ "overview.context.repository.addTitle": "Add a repository to this project",
+ "overview.context.repository.attachFailed": "Couldn't add the repository to this project",
+ "overview.context.repository.publishHint": "This agent is shared with the workspace and only uses published environments, so the repository is added as one that workspace members can see.",
+ "overview.context.repository.tooltip": "New conversations work in this repository, cloned before the first command.",
+ "overview.context.settings": "Repositories and environments",
+ "overview.context.target.device": "A connected device",
+ "overview.context.target.noneTooltip": "This agent has nowhere to run yet. Switch to the cloud sandbox so it can work on the code.",
+ "overview.context.target.sandboxTooltip": "Runs in the cloud sandbox, so none of your devices need to be online.",
+ "overview.context.target.switchFailed": "Couldn't change where this agent runs",
+ "overview.context.target.useSandbox": "Use the cloud sandbox",
"overview.contextTitle": "Project context",
"overview.createTask": "Create task",
"overview.createTaskFailed": "Could not create the task",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index a22429421c2..53bd65e01d8 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -223,6 +223,18 @@
"overview.activeTasks": "正在推进",
"overview.agentSelect": "选择 Agent",
"overview.composerPlaceholder": "告诉项目接下来要推进什么…",
+ "overview.context.repository.add": "添加代码仓库",
+ "overview.context.repository.addAction": "添加",
+ "overview.context.repository.addTitle": "为项目添加代码仓库",
+ "overview.context.repository.attachFailed": "没能把代码仓库加到这个项目里",
+ "overview.context.repository.publishHint": "这个助手已共享给工作区,只能使用已发布的环境,因此仓库会以工作区成员可见的环境添加。",
+ "overview.context.repository.tooltip": "新对话在这个仓库里进行,首条命令前自动克隆。",
+ "overview.context.settings": "仓库与环境设置",
+ "overview.context.target.device": "已连接设备",
+ "overview.context.target.noneTooltip": "这个助手还没有可运行的位置。切换到云端沙箱后,它就能直接处理代码。",
+ "overview.context.target.sandboxTooltip": "在云端沙箱里运行,不需要你的设备在线。",
+ "overview.context.target.switchFailed": "没能切换运行位置",
+ "overview.context.target.useSandbox": "改用云端沙箱",
"overview.contextTitle": "项目上下文",
"overview.createTask": "创建任务",
"overview.createTaskFailed": "创建任务失败",
diff --git a/packages/builtin-tool-cloud-sandbox/src/index.ts b/packages/builtin-tool-cloud-sandbox/src/index.ts
index 2c7fafee514..79adef26f0f 100644
--- a/packages/builtin-tool-cloud-sandbox/src/index.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/index.ts
@@ -1,4 +1,5 @@
export * from './manifest';
+export * from './projectCheckout';
export * from './systemRole';
export * from './types';
export * from './uploadedFiles';
diff --git a/packages/builtin-tool-cloud-sandbox/src/projectCheckout.test.ts b/packages/builtin-tool-cloud-sandbox/src/projectCheckout.test.ts
new file mode 100644
index 00000000000..adf9f42a364
--- /dev/null
+++ b/packages/builtin-tool-cloud-sandbox/src/projectCheckout.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import { projectCheckoutDirectory } from './projectCheckout';
+import { isSafeSandboxCwd } from './workspace';
+
+describe('projectCheckoutDirectory', () => {
+ const ENV_ID = '3f2504e0-4f89-11d3-9a0c-0305e82c3301';
+
+ it('keeps one folder per project and environment', () => {
+ expect(projectCheckoutDirectory('proj_1', ENV_ID)).toBe(`projects/proj_1/${ENV_ID}`);
+ });
+
+ // A filled folder is never initialized again, so a shared folder would run
+ // the second repository against the first one's checkout.
+ it('keeps two repositories apart whatever they are called', () => {
+ expect(projectCheckoutDirectory('proj_1', 'env-a')).not.toBe(
+ projectCheckoutDirectory('proj_1', 'env-b'),
+ );
+ });
+
+ it('turns anything but an id character into a plain one, so no segment escapes', () => {
+ const folder = projectCheckoutDirectory('../proj', '..');
+
+ expect(folder).toBe('projects/___proj/__');
+ expect(isSafeSandboxCwd(folder)).toBe(true);
+ });
+
+ it('stays a usable working directory', () => {
+ expect(isSafeSandboxCwd(projectCheckoutDirectory('proj_1', ENV_ID))).toBe(true);
+ });
+});
diff --git a/packages/builtin-tool-cloud-sandbox/src/projectCheckout.ts b/packages/builtin-tool-cloud-sandbox/src/projectCheckout.ts
new file mode 100644
index 00000000000..637f602eab5
--- /dev/null
+++ b/packages/builtin-tool-cloud-sandbox/src/projectCheckout.ts
@@ -0,0 +1,24 @@
+/** Where every project keeps its repository checkouts on the drive. */
+export const PROJECT_DRIVE_ROOT = 'projects';
+
+/**
+ * One path segment from an id. Ids are already path-safe (`prj_…`, UUIDs); any
+ * other character becomes `_`, which also rules out `.`/`..` segments. One
+ * character class, no anchored repetition, so it runs in linear time on any input.
+ */
+const toSegment = (value: string) => value.replaceAll(/[^\w-]/g, '_');
+
+/**
+ * A project's checkout of one repository on the drive: one folder per project
+ * and environment, shared by every conversation in the project, so work done in
+ * one is there for the next — the way a local clone is.
+ *
+ * Derived from ids alone. A name in the path would move the checkout whenever
+ * the project or the environment is renamed, and the next conversation would
+ * clone afresh beside the work already done; a repository's name alone would
+ * also put `orgA/api` and `orgB/api` in one folder, and a filled folder is never
+ * initialized again. Where the folder is shown, it is shown by the repository's
+ * name, not its path.
+ */
+export const projectCheckoutDirectory = (projectId: string, environmentId: string) =>
+ `${PROJECT_DRIVE_ROOT}/${toSegment(projectId)}/${toSegment(environmentId)}`;
diff --git a/packages/database/src/models/__tests__/environment.test.ts b/packages/database/src/models/__tests__/environment.test.ts
index 84b7368d401..7bdb834ef02 100644
--- a/packages/database/src/models/__tests__/environment.test.ts
+++ b/packages/database/src/models/__tests__/environment.test.ts
@@ -1,7 +1,8 @@
+import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { environments, users } from '../../schemas';
+import { environments, users, workspaces } from '../../schemas';
import { EnvironmentModel, normalizeProjectRepository } from '../environment';
const db = await getTestDB();
@@ -88,6 +89,33 @@ describe('EnvironmentModel', () => {
expect(theirs.id).not.toBe(created.id);
});
+ // A workspace-public agent applies published environments only, so asking
+ // for one must not hand back the caller's private environment for the repo.
+ it('reuses or makes a published environment when one is asked for', async () => {
+ const workspaceId = 'environment-workspace';
+ await db.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Env Workspace',
+ primaryOwnerId: userId,
+ slug: workspaceId,
+ });
+ const scoped = new EnvironmentModel(db, userId, workspaceId);
+ const repo = { name: 'lobehub/lobehub', repositoryUrl: 'https://github.com/lobehub/lobehub' };
+
+ const privateEnv = await scoped.ensureForRepository(repo);
+ const published = await scoped.ensureForRepository({ ...repo, visibility: 'public' });
+
+ expect(privateEnv.visibility).toBe('private');
+ expect(published.id).not.toBe(privateEnv.id);
+ expect(published.visibility).toBe('public');
+ expect((await scoped.ensureForRepository({ ...repo, visibility: 'public' })).id).toBe(
+ published.id,
+ );
+
+ await db.delete(environments);
+ await db.delete(workspaces).where(eq(workspaces.id, workspaceId));
+ });
+
it('suffixes the name when another environment already holds it', async () => {
await model.save({ name: 'lobehub/lobehub' });
await model.save({ name: 'lobehub/lobehub (2)' });
diff --git a/packages/database/src/models/__tests__/project.mainAgent.test.ts b/packages/database/src/models/__tests__/project.mainAgent.test.ts
index f10836a7005..6926da27f9e 100644
--- a/packages/database/src/models/__tests__/project.mainAgent.test.ts
+++ b/packages/database/src/models/__tests__/project.mainAgent.test.ts
@@ -60,6 +60,8 @@ describe('the main agent a project creates', () => {
expect(agent).toEqual(
expect.objectContaining({ avatar: '🚀', title: 'Apollo Project Agent', virtual: false }),
);
+ // A project runs in the cloud sandbox unless someone picks a device.
+ expect(agent.agencyConfig).toEqual({ executionTarget: 'sandbox' });
expect(await labelsOf(agent.id)).toEqual([
expect.objectContaining({ name: PROJECT_AGENT_LABEL, workspaceId: null }),
]);
diff --git a/packages/database/src/models/environment.ts b/packages/database/src/models/environment.ts
index 5cfd5a66ceb..98d5a097e0e 100644
--- a/packages/database/src/models/environment.ts
+++ b/packages/database/src/models/environment.ts
@@ -129,6 +129,7 @@ export class EnvironmentModel {
id: environments.id,
name: environments.name,
configuration: environments.configuration,
+ visibility: environments.visibility,
})
.from(environments)
.where(and(buildWorkspaceWhere(this.scope(), environments), eq(environments.enabled, true)));
@@ -229,11 +230,15 @@ export class EnvironmentModel {
* A new one is named after the repository; when that name is already taken by
* another of the caller's environments, a numeric suffix keeps the
* `(user, scope, name)` unique indexes satisfied.
+ *
+ * Asked for a published one — for a workspace-public agent, which applies
+ * nothing else — only a published environment is reused or made.
*/
async ensureForRepository(input: {
defaultBranch?: string;
name: string;
repositoryUrl: string;
+ visibility?: EnvironmentVisibility;
}): Promise<EnvironmentItem> {
const url = normalizeProjectRepository(input.repositoryUrl);
const [existing] = await this.db
@@ -244,6 +249,7 @@ export class EnvironmentModel {
this.ownership(),
eq(environments.enabled, true),
sql`${environments.configuration} -> 'sources' @> ${JSON.stringify([{ kind: 'git', url }])}::jsonb`,
+ input.visibility === 'public' ? eq(environments.visibility, 'public') : undefined,
),
)
.orderBy(asc(environments.createdAt))
@@ -258,6 +264,7 @@ export class EnvironmentModel {
return this.create({
configuration: { kind: 'code', sources: [{ kind: 'git', url, ...(ref ? { ref } : {}) }] },
name,
+ visibility: input.visibility,
});
}
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.ts
index 7fd0aba0372..b97adb98832 100644
--- a/packages/database/src/models/project.ts
+++ b/packages/database/src/models/project.ts
@@ -1090,6 +1090,7 @@ export class ProjectModel {
id: environments.id,
name: environments.name,
configuration: environments.configuration,
+ visibility: environments.visibility,
})
.from(environments)
.innerJoin(
diff --git a/packages/database/src/models/projectMainAgent.ts b/packages/database/src/models/projectMainAgent.ts
index 73cb2e0476c..f209853ecd0 100644
--- a/packages/database/src/models/projectMainAgent.ts
+++ b/packages/database/src/models/projectMainAgent.ts
@@ -69,6 +69,11 @@ export const createProjectMainAgent = async (
) => {
const agent = await new AgentModel(db, scope.userId, scope.workspaceId).create({
...createProjectCoordinatorAgentConfig({ avatar: input.avatar, name: input.name }),
+ // A project's work outlives a conversation and needs no machine of the
+ // member's to be online: the cloud sandbox keeps the project's checkout on
+ // its drive. Left unset, a web client would resolve the agent to no
+ // execution target at all, and the project would start with nowhere to run.
+ agencyConfig: { executionTarget: 'sandbox' },
visibility: input.visibility,
});
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index d911cabfe4a..b5c6485de92 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -304,6 +304,22 @@ export default {
'rename.title': 'Rename project',
'overview.openTasks': 'Open task workspace',
'overview.composerPlaceholder': 'Tell the project what to move forward next…',
+ 'overview.context.repository.add': 'Add a repository',
+ 'overview.context.repository.addAction': 'Add',
+ 'overview.context.repository.addTitle': 'Add a repository to this project',
+ 'overview.context.repository.attachFailed': "Couldn't add the repository to this project",
+ 'overview.context.repository.publishHint':
+ 'This agent is shared with the workspace and only uses published environments, so the repository is added as one that workspace members can see.',
+ 'overview.context.repository.tooltip':
+ 'New conversations work in this repository, cloned before the first command.',
+ 'overview.context.settings': 'Repositories and environments',
+ 'overview.context.target.device': 'A connected device',
+ 'overview.context.target.noneTooltip':
+ 'This agent has nowhere to run yet. Switch to the cloud sandbox so it can work on the code.',
+ 'overview.context.target.sandboxTooltip':
+ 'Runs in the cloud sandbox, so none of your devices need to be online.',
+ 'overview.context.target.switchFailed': "Couldn't change where this agent runs",
+ 'overview.context.target.useSandbox': 'Use the cloud sandbox',
'overview.sendHint': '⌘ ↵ to send',
'overview.startConversation': 'Start moving',
'overview.tasksEmpty': 'No tasks belong to this project yet.',
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 9e22b688d97..981fc1db841 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -38,6 +38,10 @@ export const initialTopicMetadataSchema = z.object({
/** The environment to initialize the sandbox from; see `ChatTopicMetadata.sandboxEnvironmentId`. */
sandboxEnvironmentId: z.string().max(255).optional(),
sandboxInstanceId: z.string().optional(),
+ /** A default nobody picked; see `ChatTopicMetadata.sandboxSeeded`. */
+ sandboxSeeded: z.boolean().optional(),
+ /** An explicit temporary-sandbox pick; see `ChatTopicMetadata.sandboxTemporary`. */
+ sandboxTemporary: z.boolean().optional(),
sandboxWorkingDirectory: z.string().max(1024).optional(),
workingDirectory: z.string().optional(),
workingDirectoryConfig: workingDirConfigSchema.optional(),
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 07f7a14932b..0b93f6d7e77 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -420,6 +420,20 @@ export interface ChatTopicMetadata {
* directory inside a remote volume.
*/
sandboxInstanceId?: string;
+ /**
+ * Creation-time only, never stored: the placement this topic is created with
+ * is the plan's default, filled in by the composer rather than chosen. A
+ * project conversation is given the project's repository checkout in its
+ * place. The server reads it and drops it.
+ */
+ sandboxSeeded?: boolean;
+ /**
+ * Creation-time only, never stored: the composer explicitly chose a
+ * temporary sandbox before the topic existed. Without it that choice looks
+ * the same as no choice at all, and the server would apply a project's
+ * repository checkout over it. The server reads it and drops it.
+ */
+ sandboxTemporary?: boolean;
/**
* The folder on the user's drive this topic's cloud sandbox works in,
* relative to the drive's root; `'.'` is the root itself. Choosing a folder
diff --git a/src/features/ChatInput/ActionBar/Upload/index.tsx b/src/features/ChatInput/ActionBar/Upload/index.tsx
index f47899366f4..f84ed728adf 100644
--- a/src/features/ChatInput/ActionBar/Upload/index.tsx
+++ b/src/features/ChatInput/ActionBar/Upload/index.tsx
@@ -1,7 +1,7 @@
import { validateVideoFileSize } from '@lobechat/utils/client';
import { Icon, toast, Tooltip, Upload } from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
-import { FileUp, FolderUp, ImageUp, Paperclip } from 'lucide-react';
+import { FileUp, FolderUp, ImageUp, type LucideIcon, Paperclip } from 'lucide-react';
import { memo, Suspense, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -33,10 +33,12 @@ const styles = stylex.create({
});
interface FileUploadProps {
+ /** The trigger's icon; a paperclip unless the host's composer reads better with another. */
+ icon?: LucideIcon;
includeKnowledge?: boolean;
}
-const FileUpload = memo<FileUploadProps>(({ includeKnowledge = true }) => {
+const FileUpload = memo<FileUploadProps>(({ icon = Paperclip, includeKnowledge = true }) => {
const { t } = useTranslation('chat');
const enableKnowledgeBase = useServerConfigStore(
@@ -81,7 +83,7 @@ const FileUpload = memo<FileUploadProps>(({ includeKnowledge = true }) => {
<Tooltip title={reason}>
<ChatInputAction
disabled
- icon={Paperclip}
+ icon={icon}
showTooltip={false}
title={t('upload.action.tooltip')}
/>
@@ -198,7 +200,7 @@ const FileUpload = memo<FileUploadProps>(({ includeKnowledge = true }) => {
const content = (
<ChatInputAction
- icon={Paperclip}
+ icon={icon}
loading={updating}
open={dropdownOpen}
showTooltip={false}
@@ -216,7 +218,7 @@ const FileUpload = memo<FileUploadProps>(({ includeKnowledge = true }) => {
return (
<Suspense
- fallback={<ChatInputAction disabled icon={Paperclip} title={t('upload.action.tooltip')} />}
+ fallback={<ChatInputAction disabled icon={icon} title={t('upload.action.tooltip')} />}
>
{includeKnowledge && showTip ? (
<TipGuide
diff --git a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx
index 11e6aab7fc1..5ba05b03e0e 100644
--- a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx
+++ b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx
@@ -31,7 +31,11 @@ import { agentSelectors } from '@/store/agent/selectors';
import OptionRow from './OptionRow';
import SandboxDriveMenu from './SandboxDriveMenu';
-import { environmentChipState, pickableEnvironments } from './sandboxEnvironmentOptions';
+import {
+ environmentChipState,
+ pickableEnvironments,
+ repositorySelection,
+} from './sandboxEnvironmentOptions';
import SandboxRepositoryMenu, { type SandboxRepositoryOption } from './SandboxRepositoryMenu';
import { isPersistentSelection, type SandboxSelection } from './useSandboxPlacement';
import { workingDirectoryChipStyles } from './workingDirectoryChipStyles';
@@ -81,6 +85,8 @@ interface SandboxDrivePickerProps {
/** Whether this plan includes a drive. Without one the menu offers the way to a plan. */
entitled: boolean;
onChange: (selection: SandboxSelection) => Promise<void>;
+ /** The project the conversation belongs to; its repositories have a checkout there. */
+ projectId?: string;
topicId?: string;
/** Where this conversation works today. */
value: SandboxSelection;
@@ -108,7 +114,7 @@ const folderName = (path: string) => path.split('/').pop() || path;
* replaces it.
*/
const SandboxDrivePicker = memo<SandboxDrivePickerProps>(
- ({ entitled, onChange, topicId, value }) => {
+ ({ entitled, onChange, projectId, topicId, value }) => {
const { t } = useTranslation(['chat', 'device']);
const [open, setOpen] = useState(false);
const workspaceId = useActiveWorkspaceId();
@@ -185,11 +191,16 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(
}
};
- // A repository is only cloned into an empty folder, so it never inherits the
- // folder the conversation was on: it starts in a temporary sandbox.
const pickRepository = async (environment: SandboxRepositoryOption) => {
try {
- await onChange({ environmentId: environment.id });
+ await onChange(
+ repositorySelection(environment, {
+ projectId,
+ published:
+ environments.find((item) => item.id === environment.id)?.visibility === 'public',
+ workspace: !!workspaceId,
+ }),
+ );
void revalidatePlacement();
} catch {
// The topic kept its place; said rather than left looking changed.
diff --git a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx
index 5201153d00b..6f95dc6b742 100644
--- a/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx
+++ b/src/features/ChatInput/ControlBar/SandboxStorageSection.tsx
@@ -31,7 +31,10 @@ interface SandboxStorageSectionProps {
*/
const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }) => {
const { eligible, status } = useSandboxStorageAccess(agentId);
- const { selection, setSelection, topicId } = useSandboxPlacement(agentId, useTopicId());
+ const { projectId, selection, setSelection, topicId } = useSandboxPlacement(
+ agentId,
+ useTopicId(),
+ );
useSeedDefaultSelection(agentId, {
eligible,
entitled: status === 'ready',
@@ -43,6 +46,7 @@ const SandboxStorageSectionInner = memo<SandboxStorageSectionProps>(({ agentId }
return (
<SandboxDrivePicker
entitled={status === 'ready'}
+ projectId={projectId}
topicId={topicId}
value={selection}
onChange={setSelection}
diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts
index fb7e9f24446..c4a5c0af673 100644
--- a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts
+++ b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';
import {
environmentChipState,
pickableEnvironments,
+ repositorySelection,
repositorySlug,
} from './sandboxEnvironmentOptions';
@@ -70,3 +71,33 @@ describe('repositorySlug', () => {
expect(repositorySlug(withUrl('not a url'))).toBeUndefined();
});
});
+
+describe('repositorySelection', () => {
+ const repo = { id: 'env-repo', name: 'lobehub-biz/agent-mail' };
+
+ it('starts a repository outside a project in a temporary sandbox', () => {
+ expect(repositorySelection(repo, { published: false, workspace: true })).toEqual({
+ environmentId: 'env-repo',
+ });
+ });
+
+ // A pick in a project conversation used to drop the project's shared
+ // checkout and start over in a temporary sandbox.
+ it("keeps a project conversation in the project's checkout of the repository", () => {
+ expect(
+ repositorySelection(repo, { projectId: 'proj_1', published: false, workspace: false }),
+ ).toEqual({
+ environmentId: 'env-repo',
+ workingDirectory: 'projects/proj_1/env-repo',
+ });
+ });
+
+ it('puts a private checkout on the personal drive and a published one on the public drive', () => {
+ expect(
+ repositorySelection(repo, { projectId: 'proj_1', published: false, workspace: true }),
+ ).toMatchObject({ drive: 'personal' });
+ expect(
+ repositorySelection(repo, { projectId: 'proj_1', published: true, workspace: true }),
+ ).toMatchObject({ drive: 'public' });
+ });
+});
diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts
index f423b855333..e87f108e1c3 100644
--- a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts
+++ b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts
@@ -1,5 +1,8 @@
+import { projectCheckoutDirectory } from '@lobechat/builtin-tool-cloud-sandbox';
import type { EnvironmentConfiguration } from '@lobechat/types';
+import type { SandboxSelection } from './useSandboxPlacement';
+
/**
* The environments a conversation may start from. A workspace-public agent runs
* on its caller's session, so it applies published environments only — the
@@ -57,3 +60,27 @@ export const environmentChipState = ({
return failed ? { kind: 'loadFailed' } : { kind: 'loading' };
};
+
+/**
+ * Where a conversation works once a repository is picked. A repository is only
+ * cloned into an empty folder, so it never inherits the folder the
+ * conversation was on: it starts in a temporary sandbox — or, in a project, in
+ * the project's own checkout of it, which every conversation there shares (the
+ * run makes the folder when it first needs it). A private checkout stays on the
+ * member's own drive; the public one is every member's.
+ */
+export const repositorySelection = (
+ environment: { id: string; name: string },
+ {
+ projectId,
+ published,
+ workspace,
+ }: { projectId?: string; published: boolean; workspace: boolean },
+): SandboxSelection =>
+ projectId
+ ? {
+ ...(workspace && { drive: published ? 'public' : 'personal' }),
+ environmentId: environment.id,
+ workingDirectory: projectCheckoutDirectory(projectId, environment.id),
+ }
+ : { environmentId: environment.id };
diff --git a/src/features/ChatInput/ControlBar/useSandboxPlacement.test.ts b/src/features/ChatInput/ControlBar/useSandboxPlacement.test.ts
index 818472a0680..a41b9e4ad81 100644
--- a/src/features/ChatInput/ControlBar/useSandboxPlacement.test.ts
+++ b/src/features/ChatInput/ControlBar/useSandboxPlacement.test.ts
@@ -6,15 +6,19 @@ import { getPendingSandboxSelection } from '@/store/chat/pendingSandboxSelection
import { isPersistentSelection, useSandboxPlacement } from './useSandboxPlacement';
interface TopicSandbox {
+ projectId?: string;
sandboxDrive?: 'personal' | 'public';
+ sandboxEnvironmentId?: string;
sandboxInstanceId?: string;
sandboxWorkingDirectory?: string;
}
const state = vi.hoisted(() => ({
activeTopicId: undefined as string | undefined,
+ refreshTopicDetail: vi.fn(),
topics: {} as Record<string, TopicSandbox>,
updateTopicMetadata: vi.fn(),
+ useFetchTopicDetail: vi.fn(),
}));
// Store boundary: the real topic selectors run against this state.
@@ -23,10 +27,15 @@ vi.mock('@/store/chat', () => ({
selector({
activeTopicId: state.activeTopicId,
topicDataMap: {},
+ refreshTopicDetail: state.refreshTopicDetail,
topicDetailMap: Object.fromEntries(
- Object.entries(state.topics).map(([id, metadata]) => [id, { id, metadata }]),
+ Object.entries(state.topics).map(([id, { projectId, ...metadata }]) => [
+ id,
+ { id, metadata, projectId },
+ ]),
),
updateTopicMetadata: state.updateTopicMetadata,
+ useFetchTopicDetail: state.useFetchTopicDetail,
}),
}));
@@ -38,6 +47,8 @@ beforeEach(() => {
'pane-topic': { sandboxDrive: 'personal', sandboxWorkingDirectory: 'reports' },
};
state.updateTopicMetadata.mockReset();
+ state.refreshTopicDetail.mockReset();
+ state.useFetchTopicDetail.mockReset();
});
describe('useSandboxPlacement', () => {
@@ -86,6 +97,47 @@ describe('useSandboxPlacement', () => {
expect(getPendingSandboxSelection('agent-new-topic')).toEqual({ workingDirectory: '.' });
});
+ // ROOT CAUSE:
+ //
+ // A project conversation opened right after the project home created it is in
+ // no loaded topic list. The chip read it as having no metadata (a temporary
+ // sandbox while it worked in a repository), and a repository pick reached the
+ // server but nothing local read it back — the pick looked ignored.
+ //
+ // Before: an unlisted topic was neither fetched nor read back.
+ // After: it is fetched by id, and read back after a write.
+ it('fetches an unlisted topic and reads it back after a pick', async () => {
+ const { result } = renderHook(() => useSandboxPlacement('agent-1', 'fresh-topic'));
+
+ expect(state.useFetchTopicDetail).toHaveBeenLastCalledWith('fresh-topic');
+
+ await act(() => result.current.setSelection({ environmentId: 'env-repo' }));
+
+ expect(state.updateTopicMetadata).toHaveBeenCalledWith(
+ 'fresh-topic',
+ expect.objectContaining({ sandboxEnvironmentId: 'env-repo' }),
+ );
+ expect(state.refreshTopicDetail).toHaveBeenCalledWith('fresh-topic', true);
+ });
+
+ it('leaves a listed topic to the list it is in', async () => {
+ const { result } = renderHook(() => useSandboxPlacement('agent-1', 'pane-topic'));
+
+ expect(state.useFetchTopicDetail).toHaveBeenLastCalledWith(undefined);
+
+ await act(() => result.current.setSelection({ environmentId: 'env-repo' }));
+
+ expect(state.refreshTopicDetail).not.toHaveBeenCalled();
+ });
+
+ it("names the conversation's project", () => {
+ state.topics['project-topic'] = { projectId: 'proj_1' };
+
+ const { result } = renderHook(() => useSandboxPlacement('agent-1', 'project-topic'));
+
+ expect(result.current.projectId).toBe('proj_1');
+ });
+
it('follows the global active topic when no topic is given', () => {
const { result } = renderHook(() => useSandboxPlacement('agent-1'));
diff --git a/src/features/ChatInput/ControlBar/useSandboxPlacement.ts b/src/features/ChatInput/ControlBar/useSandboxPlacement.ts
index 47df6b81039..2ae160237d3 100644
--- a/src/features/ChatInput/ControlBar/useSandboxPlacement.ts
+++ b/src/features/ChatInput/ControlBar/useSandboxPlacement.ts
@@ -53,6 +53,15 @@ export const useSandboxPlacement = (agentId: string, scopeTopicId?: string | nul
const topicMetadata = useChatStore((s) =>
topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata : undefined,
);
+ const projectId = useChatStore((s) =>
+ topicId ? (topicSelectors.getTopicById(topicId)(s)?.projectId ?? undefined) : undefined,
+ );
+ // A conversation no loaded list holds — a project conversation opened right
+ // after the project home created it — is read by id, or the chip would show
+ // a temporary sandbox while the topic works in a repository.
+ const isUnlisted = useChatStore((s) => !!topicId && !topicSelectors.getTopicById(topicId)(s));
+ useChatStore((s) => s.useFetchTopicDetail)(isUnlisted ? topicId : undefined);
+ const refreshTopicDetail = useChatStore((s) => s.refreshTopicDetail);
const topicInstanceId = topicMetadata?.sandboxInstanceId;
const topicWorkingDirectory = topicMetadata?.sandboxWorkingDirectory;
const topicDrive = topicMetadata?.sandboxDrive;
@@ -90,9 +99,12 @@ export const useSandboxPlacement = (agentId: string, scopeTopicId?: string | nul
sandboxInstanceId: next.instanceId,
sandboxWorkingDirectory: next.instanceId ? undefined : next.workingDirectory,
});
+ // Written straight to the server when no list holds the topic; read it
+ // back so the pick shows rather than looking ignored until a reload.
+ if (isUnlisted) await refreshTopicDetail(topicId, true);
},
- [agentId, topicId, updateTopicMetadata],
+ [agentId, isUnlisted, refreshTopicDetail, topicId, updateTopicMetadata],
);
- return { selection, setSelection, topicId: topicId ?? undefined };
+ return { projectId, selection, setSelection, topicId: topicId ?? undefined };
};
diff --git a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts
index f59336fe1d4..4246839b7a7 100644
--- a/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts
+++ b/src/features/ChatInput/ControlBar/useSeedDefaultSelection.ts
@@ -3,7 +3,7 @@ import { useEffect } from 'react';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import {
getPendingSandboxSelection,
- setPendingSandboxSelection,
+ seedPendingSandboxSelection,
setSandboxDefaultSelection,
} from '@/store/chat/pendingSandboxSelection';
@@ -40,6 +40,6 @@ export const useSeedDefaultSelection = (
useEffect(() => {
if (!entitled || hasTopic || getPendingSandboxSelection(agentId)) return;
- setPendingSandboxSelection(agentId, resolveDefaultSandboxSelection(workspaceId));
+ seedPendingSandboxSelection(agentId, resolveDefaultSandboxSelection(workspaceId));
}, [agentId, entitled, hasTopic, workspaceId]);
};
diff --git a/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
index 6c9dfb29a25..bab37e0f8ae 100644
--- a/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
+++ b/src/features/Conversation/WorkingSidebar/__tests__/harness.tsx
@@ -131,6 +131,9 @@ const chatStore = vi.hoisted(() => ({
activeThreadId: undefined as string | undefined,
activeTopicId: undefined as string | undefined,
openTopicComments: vi.fn(),
+ // useSandboxPlacement reads an unlisted topic by id and reads it back after a pick
+ refreshTopicDetail: vi.fn(),
+ useFetchTopicDetail: vi.fn(),
portalStack: [] as Array<{ startMessageId?: string; threadId?: string; type: string }>,
showPortal: false,
threadMaps: {} as Record<string, any[]>,
diff --git a/src/features/Projects/Layout/navigation.ts b/src/features/Projects/Layout/navigation.ts
index 9a4bb06e43e..22724661801 100644
--- a/src/features/Projects/Layout/navigation.ts
+++ b/src/features/Projects/Layout/navigation.ts
@@ -28,7 +28,8 @@ export const getProjectDashboardPath = (projectId: string, dashboardId?: string)
? `/project/${projectId}/dashboard/${dashboardId}`
: `/project/${projectId}/dashboard`;
-export type ProjectSettingsSection = 'directories' | 'general' | 'knowledge' | 'members' | 'sites';
+export type ProjectSettingsSection =
+ 'directories' | 'environments' | 'general' | 'knowledge' | 'members' | 'sites';
export const getProjectSettingsPath = (projectId: string, section: ProjectSettingsSection) =>
`/project/${projectId}/settings/${section}`;
diff --git a/src/features/Projects/Workspace/AddRepositoryModal.tsx b/src/features/Projects/Workspace/AddRepositoryModal.tsx
new file mode 100644
index 00000000000..a76a834f6bd
--- /dev/null
+++ b/src/features/Projects/Workspace/AddRepositoryModal.tsx
@@ -0,0 +1,130 @@
+'use client';
+
+import {
+ Button,
+ createModal,
+ cssVar,
+ Flexbox,
+ Input,
+ ModalFooter,
+ Text,
+ toast,
+ useModalContext,
+} from '@lobehub/ui';
+import { t as translate } from 'i18next';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { GITHUB_RETURN_TO } from '@/features/Integrations/Github/installHref';
+import { parseGithubRepository } from '@/features/Projects/CreateFromGithub/githubRepository';
+import RepositoryList from '@/features/Projects/CreateFromGithub/RepositoryList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+
+interface AddRepositoryContentProps {
+ onAdded: (environmentId: string) => void;
+ projectId: string;
+ /**
+ * Add it as a published environment: the composer's agent is workspace-public
+ * and applies nothing else, so a private one would be linked and never used.
+ */
+ publish?: boolean;
+}
+
+/**
+ * A repository for the project: one the connected GitHub App can read, or a
+ * pasted URL — the same two ways a project is created from GitHub, so the
+ * dialog works whether or not GitHub is connected. The environment that checks
+ * it out is the caller's own, reused when they already have one for it.
+ */
+const AddRepositoryContent = ({ onAdded, projectId, publish }: AddRepositoryContentProps) => {
+ const { t } = useTranslation(['project', 'common']);
+ const { close } = useModalContext();
+ const navigate = useWorkspaceAwareNavigate();
+ const attachRepository = useProjectDirectoryStore((s) => s.attachRepository);
+ const [url, setUrl] = useState('');
+ const [defaultBranch, setDefaultBranch] = useState<string>();
+ const [adding, setAdding] = useState(false);
+
+ const repository = parseGithubRepository(url);
+ const urlInvalid = Boolean(url.trim()) && !repository;
+
+ const add = async () => {
+ if (!repository || adding) return;
+ setAdding(true);
+ try {
+ const environment = await attachRepository({
+ projectId,
+ repository: { defaultBranch, name: repository.fullName, url: repository.url },
+ ...(publish && { visibility: 'public' as const }),
+ });
+ close();
+ onAdded(environment.id);
+ } catch (error) {
+ console.error('Failed to add the repository to the project', error);
+ toast.error(t('overview.context.repository.attachFailed'));
+ } finally {
+ setAdding(false);
+ }
+ };
+
+ return (
+ <>
+ <Flexbox gap={16} padding={16}>
+ <RepositoryList
+ selected={repository?.fullName}
+ onConnect={() => {
+ close();
+ navigate(GITHUB_RETURN_TO);
+ }}
+ onSelect={(picked) => {
+ setUrl(picked.htmlUrl);
+ setDefaultBranch(picked.defaultBranch);
+ }}
+ />
+ <Flexbox gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('createFromGithub.urlLabel')}
+ </Text>
+ <Input
+ aria-invalid={urlInvalid}
+ placeholder={t('createFromGithub.urlPlaceholder')}
+ style={urlInvalid ? { borderColor: cssVar.colorError } : undefined}
+ value={url}
+ onPressEnter={add}
+ onChange={(event) => {
+ setUrl(event.target.value);
+ // A typed URL names no branch; the repository's default applies.
+ setDefaultBranch(undefined);
+ }}
+ />
+ {urlInvalid && (
+ <Text fontSize={12} type={'danger'}>
+ {t('createFromGithub.urlInvalid')}
+ </Text>
+ )}
+ </Flexbox>
+ {publish && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('overview.context.repository.publishHint')}
+ </Text>
+ )}
+ </Flexbox>
+ <ModalFooter>
+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>
+ <Button disabled={!repository} loading={adding} type={'primary'} onClick={add}>
+ {t('overview.context.repository.addAction')}
+ </Button>
+ </ModalFooter>
+ </>
+ );
+};
+
+export const openAddRepositoryModal = (props: AddRepositoryContentProps) =>
+ createModal({
+ content: <AddRepositoryContent {...props} />,
+ footer: null,
+ styles: { content: { padding: 0 } },
+ title: translate('overview.context.repository.addTitle', { ns: 'project' }),
+ width: 520,
+ });
diff --git a/src/features/Projects/Workspace/ProjectAgentSelect.tsx b/src/features/Projects/Workspace/ProjectAgentSelect.tsx
index c2930bc897b..1ed8b21f447 100644
--- a/src/features/Projects/Workspace/ProjectAgentSelect.tsx
+++ b/src/features/Projects/Workspace/ProjectAgentSelect.tsx
@@ -38,8 +38,11 @@ const styles = stylex.create({
flex: '1',
minWidth: 0,
},
+ // Shrinks before anything beside it does: in a narrow composer the agent's
+ // name is the one label that can lose characters and stay recognizable.
trigger: {
- maxWidth: '200px',
+ minWidth: 0,
+ maxWidth: '280px',
paddingInlineStart: '6px',
paddingInlineEnd: '8px',
},
@@ -97,6 +100,8 @@ const AgentRow = memo<{
interface ProjectAgentSelectProps {
agents: ProjectComposerAgent[];
+ /** Avatar only, the name in the button's tooltip — for a narrow composer. */
+ compact?: boolean;
disabled?: boolean;
onChange: (agentId: string) => void;
value: string;
@@ -104,7 +109,7 @@ interface ProjectAgentSelectProps {
/** Picks which project agent the composer sends to; the main agent leads. */
const ProjectAgentSelect = memo<ProjectAgentSelectProps>(
- ({ agents, disabled, onChange, value }) => {
+ ({ agents, compact, disabled, onChange, value }) => {
const { t } = useTranslation('project');
const [open, setOpen] = useState(false);
const selected = agents.find((agent) => agent.id === value) ?? agents[0];
@@ -140,6 +145,7 @@ const ProjectAgentSelect = memo<ProjectAgentSelectProps>(
{...stylex.props(styles.trigger)}
disabled={disabled}
size={'small'}
+ title={meta.name}
type={'text'}
>
<AgentAvatar
@@ -150,9 +156,11 @@ const ProjectAgentSelect = memo<ProjectAgentSelectProps>(
shape={'square'}
size={18}
/>
- <Text ellipsis fontSize={13} style={{ minWidth: 0 }} weight={500}>
- {meta.name}
- </Text>
+ {!compact && (
+ <Text ellipsis fontSize={13} style={{ minWidth: 0 }} weight={500}>
+ {meta.name}
+ </Text>
+ )}
<ChevronDownIcon size={12} {...stylex.props(styles.chevron)} />
</Button>
</Popover>
diff --git a/src/features/Projects/Workspace/ProjectComposer.tsx b/src/features/Projects/Workspace/ProjectComposer.tsx
index be0db2dab10..da1714d98b6 100644
--- a/src/features/Projects/Workspace/ProjectComposer.tsx
+++ b/src/features/Projects/Workspace/ProjectComposer.tsx
@@ -1,9 +1,14 @@
'use client';
-import { cssVar, Flexbox, Segmented, toast } from '@lobehub/ui';
+import { ActionIcon, cssVar as lobeCssVar, Flexbox, toast } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { useSize } from 'ahooks';
+import { PlusIcon, SettingsIcon } from 'lucide-react';
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useUploadFiles } from '@/components/DragUploadZone';
import {
type ActionKeys,
@@ -13,19 +18,26 @@ import {
} from '@/features/ChatInput';
import FileUpload from '@/features/ChatInput/ActionBar/Upload';
import InputDragUpload from '@/features/Home/InputArea/InputDragUpload';
+import ModeSelect from '@/features/Home/InputArea/ModeSelect';
+import { getProjectSettingsPath } from '@/features/Projects/Layout/navigation';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import type { ProjectDetail } from '@/store/project';
+import { useCanManageProject } from '../useCanManageProject';
import ProjectAgentSelect from './ProjectAgentSelect';
import { projectComposerAgents } from './projectComposerAgents';
+import ProjectRepositoryChip from './ProjectRepositoryChip';
+import ProjectRunTargetChip from './ProjectRunTargetChip';
import {
AttachmentsNotReadyError,
getProjectComposerContextKey,
type ProjectComposerMode,
useProjectComposer,
} from './useProjectComposer';
+import { useProjectRepository } from './useProjectRepository';
const leftActions: ActionKeys[] = [];
const rightActions: ActionKeys[] = [];
@@ -39,9 +51,53 @@ const inputContainerProps = {
resize: false,
style: {
borderRadius: CONTAINER_RADIUS,
- boxShadow: cssVar.boxShadowSecondary,
+ boxShadow: lobeCssVar.boxShadowSecondary,
},
};
+
+/** How far the composer reaches up over the context tray behind it. */
+const TRAY_OVERLAP = CONTAINER_RADIUS;
+/**
+ * Below this width the tray drops its labels and keeps the icons, with the
+ * names in tooltips. Shrinking labels one by one could not keep every control
+ * whole in a narrow window; this always fits.
+ */
+const COMPACT_TRAY_WIDTH = 500;
+
+const styles = stylex.create({
+ // The composer sits in front of the tray. The tray is inset by more than the
+ // composer's corner radius on each side, so it only ever meets the
+ // composer's straight top edge and reads as one piece tucked behind it.
+ card: {
+ position: 'relative',
+ zIndex: 1,
+ marginBlockStart: `-${TRAY_OVERLAP}px`,
+ },
+ // The inset is the frame's padding, not the tray's margin: the tray fills its
+ // parent's width, and a margin would push it past the composer's right edge.
+ trayFrame: {
+ paddingInline: '24px',
+ },
+ // The left side gives way in a narrow window (the agent's name truncates);
+ // where the work happens, on the right, always stays whole.
+ trayLeading: {
+ flex: '1',
+ minWidth: 0,
+ },
+ trayTrailing: {
+ flexShrink: 0,
+ },
+ tray: {
+ gap: '8px',
+ paddingBlockStart: '8px',
+ paddingBlockEnd: `${TRAY_OVERLAP + 8}px`,
+ paddingInline: '10px',
+ borderStartStartRadius: '20px',
+ borderStartEndRadius: '20px',
+ backgroundColor: cssVar.colorFillTertiary,
+ },
+});
+
const actionBarStyle = { paddingBlockEnd: ACTION_BAR_INSET, paddingInline: ACTION_BAR_INSET };
export interface ProjectComposerRequest {
@@ -65,6 +121,10 @@ const ProjectComposer = memo<ProjectComposerProps>(({ detail, request }) => {
const containerRef = useRef<HTMLDivElement>(null);
const { t } = useTranslation('project');
const { t: tHome } = useTranslation('home');
+ const navigate = useWorkspaceAwareNavigate();
+ const trayRef = useRef<HTMLDivElement>(null);
+ const traySize = useSize(trayRef);
+ const compact = !!traySize && traySize.width < COMPACT_TRAY_WIDTH;
const [mode, setMode] = useState<ProjectComposerMode>('chat');
const [handledRequest, setHandledRequest] = useState(request);
@@ -84,7 +144,16 @@ const ProjectComposer = memo<ProjectComposerProps>(({ detail, request }) => {
// A pick that left the project (disabled or removed) falls back to the main agent.
const agentId =
agents.find((agent) => agent.id === pickedAgentId)?.id ?? project.coordinatorAgentId;
- const { send, sending } = useProjectComposer(project, mode, agentId);
+ const workspaceId = useActiveWorkspaceId();
+ // A workspace-public agent applies published environments only.
+ const sharedAgent = useAgentStore(
+ (s) => !!workspaceId && s.agentMap[agentId]?.visibility === 'public',
+ );
+ const repositoryState = useProjectRepository(project.id, sharedAgent);
+ const canManageProject = useCanManageProject();
+ // A task is not started in a conversation, so it has no repository to pick.
+ const environmentId = mode === 'chat' ? repositoryState.repository?.id : undefined;
+ const { send, sending } = useProjectComposer(project, mode, agentId, environmentId);
useInitAgentConfig(agentId);
const isAgentConfigLoading = useAgentStore((s) =>
@@ -125,49 +194,83 @@ const ProjectComposer = memo<ProjectComposerProps>(({ detail, request }) => {
return (
<div ref={containerRef}>
- <InputDragUpload radius={CONTAINER_RADIUS} onUploadFiles={handleUploadFiles}>
- <ChatInputProvider
- agentId={agentId}
- allowExpand={false}
- contextSelectionKey={contextSelectionKey}
- leftActions={leftActions}
- rightActions={rightActions}
- sendButtonProps={sendButtonProps}
- slashPlacement="bottom"
- topicId={null}
- onSend={submit}
+ <div ref={trayRef} {...stylex.props(styles.trayFrame)}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.tray).className}
+ justify={'space-between'}
>
- <DesktopChatInput
- actionBarStyle={actionBarStyle}
- dropdownPlacement="bottomLeft"
- inputContainerProps={inputContainerProps}
- showControlBar={false}
- leftContent={
- <Flexbox horizontal align={'center'} gap={4}>
- <Segmented
- size={'small'}
- value={mode}
- options={[
- { label: t('overview.mode.chat'), value: 'chat' },
- { label: t('overview.mode.task'), value: 'task' },
- ]}
- onChange={(value) => setMode(value as ProjectComposerMode)}
- />
- <ProjectAgentSelect
- agents={agents}
- disabled={sending}
- value={agentId}
- onChange={setPickedAgentId}
- />
- <FileUpload includeKnowledge={false} />
- </Flexbox>
- }
- placeholder={t(
- mode === 'task' ? 'overview.taskPlaceholder' : 'overview.composerPlaceholder',
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.trayLeading).className}
+ gap={4}
+ >
+ <ModeSelect value={mode} onChange={setMode} />
+ <ProjectAgentSelect
+ agents={agents}
+ compact={compact}
+ disabled={sending}
+ value={agentId}
+ onChange={setPickedAgentId}
+ />
+ </Flexbox>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={stylex.props(styles.trayTrailing).className}
+ gap={2}
+ >
+ {mode === 'chat' && (
+ <ProjectRepositoryChip
+ canManage={canManageProject}
+ compact={compact}
+ disabled={sending}
+ projectId={project.id}
+ publish={sharedAgent}
+ state={repositoryState}
+ />
)}
- />
- </ChatInputProvider>
- </InputDragUpload>
+ <ProjectRunTargetChip agentId={agentId} compact={compact} disabled={sending} />
+ <ActionIcon
+ aria-label={t('overview.context.settings')}
+ icon={SettingsIcon}
+ size={'small'}
+ title={t('overview.context.settings')}
+ onClick={() =>
+ navigate(getProjectSettingsPath(project.slug ?? project.id, 'environments'))
+ }
+ />
+ </Flexbox>
+ </Flexbox>
+ </div>
+ <div {...stylex.props(styles.card)}>
+ <InputDragUpload radius={CONTAINER_RADIUS} onUploadFiles={handleUploadFiles}>
+ <ChatInputProvider
+ agentId={agentId}
+ allowExpand={false}
+ contextSelectionKey={contextSelectionKey}
+ leftActions={leftActions}
+ rightActions={rightActions}
+ sendButtonProps={sendButtonProps}
+ slashPlacement="bottom"
+ topicId={null}
+ onSend={submit}
+ >
+ <DesktopChatInput
+ actionBarStyle={actionBarStyle}
+ dropdownPlacement="bottomLeft"
+ inputContainerProps={inputContainerProps}
+ leftContent={<FileUpload icon={PlusIcon} includeKnowledge={false} />}
+ showControlBar={false}
+ placeholder={t(
+ mode === 'task' ? 'overview.taskPlaceholder' : 'overview.composerPlaceholder',
+ )}
+ />
+ </ChatInputProvider>
+ </InputDragUpload>
+ </div>
</div>
);
});
diff --git a/src/features/Projects/Workspace/ProjectRepositoryChip.tsx b/src/features/Projects/Workspace/ProjectRepositoryChip.tsx
new file mode 100644
index 00000000000..91b851393e5
--- /dev/null
+++ b/src/features/Projects/Workspace/ProjectRepositoryChip.tsx
@@ -0,0 +1,143 @@
+'use client';
+
+import { Github } from '@lobehub/icons';
+import { type DropdownItem, DropdownMenu, Icon, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { CheckIcon, ChevronDownIcon, PlusIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { repositorySlug } from '@/features/ChatInput/ControlBar/sandboxEnvironmentOptions';
+import { workingDirectoryChipStyles } from '@/features/ChatInput/ControlBar/workingDirectoryChipStyles';
+
+import { openAddRepositoryModal } from './AddRepositoryModal';
+import type { useProjectRepository } from './useProjectRepository';
+
+interface ProjectRepositoryChipProps {
+ /** Whether this member may link a repository to the project. */
+ canManage: boolean;
+ /** Icon only, the repository in the tooltip — for a narrow composer. */
+ compact?: boolean;
+ disabled?: boolean;
+ projectId: string;
+ /** Repositories added here are published: the agent is workspace-public and applies nothing else. */
+ publish?: boolean;
+ state: ReturnType<typeof useProjectRepository>;
+}
+
+/**
+ * Which of the project's repositories a new conversation works in. A project
+ * without one offers to add it here, linked to the project in the same step —
+ * the conversation needs nothing else to start on the code.
+ */
+const ProjectRepositoryChip = ({
+ canManage,
+ compact,
+ disabled,
+ projectId,
+ publish,
+ state,
+}: ProjectRepositoryChipProps) => {
+ const { t } = useTranslation('project');
+ const { loaded, repositories, repository, setPickedId } = state;
+
+ const addRepository = () => openAddRepositoryModal({ onAdded: setPickedId, projectId, publish });
+
+ if (!loaded) return null;
+
+ if (!repository) {
+ if (!canManage) return null;
+ return (
+ <button
+ aria-label={t('overview.context.repository.add')}
+ disabled={disabled}
+ title={compact ? t('overview.context.repository.add') : undefined}
+ type={'button'}
+ {...stylex.props(workingDirectoryChipStyles.chip, styles.button)}
+ onClick={addRepository}
+ >
+ <Icon icon={PlusIcon} size={14} />
+ {!compact && <span>{t('overview.context.repository.add')}</span>}
+ </button>
+ );
+ }
+
+ const slug = repositorySlug(repository) ?? repository.name;
+ const label = (
+ <>
+ <Github size={14} />
+ {!compact && (
+ <span {...stylex.props(workingDirectoryChipStyles.label)}>
+ {slug.split('/').pop() || repository.name}
+ </span>
+ )}
+ </>
+ );
+
+ const items: DropdownItem[] = [
+ ...repositories.map((environment) => ({
+ extra: environment.id === repository.id ? <Icon icon={CheckIcon} size={14} /> : undefined,
+ icon: <Github size={14} />,
+ key: environment.id,
+ label: repositorySlug(environment) ?? environment.name,
+ onClick: () => setPickedId(environment.id),
+ })),
+ ...(canManage
+ ? [
+ { type: 'divider' as const },
+ {
+ icon: <Icon icon={PlusIcon} />,
+ key: 'add',
+ label: t('overview.context.repository.add'),
+ onClick: addRepository,
+ },
+ ]
+ : []),
+ ];
+
+ const chip = (
+ <button
+ aria-label={slug}
+ data-testid={'project-repository-chip'}
+ disabled={disabled}
+ type={'button'}
+ {...stylex.props(workingDirectoryChipStyles.chip, styles.button)}
+ >
+ {label}
+ <Icon icon={ChevronDownIcon} size={12} />
+ </button>
+ );
+
+ return (
+ <Tooltip
+ title={
+ compact
+ ? `${slug} · ${t('overview.context.repository.tooltip')}`
+ : t('overview.context.repository.tooltip')
+ }
+ >
+ <div>
+ {disabled ? (
+ chip
+ ) : (
+ <DropdownMenu items={items} placement={'bottomRight'}>
+ {chip}
+ </DropdownMenu>
+ )}
+ </div>
+ </Tooltip>
+ );
+};
+
+const styles = stylex.create({
+ // Body size and color: the tray says where the work happens, not a footnote.
+ button: {
+ borderWidth: 0,
+ fontFamily: 'inherit',
+ fontSize: '13px',
+ color: cssVar.colorText,
+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillSecondary },
+ },
+});
+
+export default ProjectRepositoryChip;
diff --git a/src/features/Projects/Workspace/ProjectRunTargetChip.test.tsx b/src/features/Projects/Workspace/ProjectRunTargetChip.test.tsx
new file mode 100644
index 00000000000..e65bf735375
--- /dev/null
+++ b/src/features/Projects/Workspace/ProjectRunTargetChip.test.tsx
@@ -0,0 +1,109 @@
+import { fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import ProjectRunTargetChip from './ProjectRunTargetChip';
+
+const mocks = vi.hoisted(() => ({
+ agency: {
+ agencyConfig: undefined as
+ { executionTarget?: string; heterogeneousProvider?: { type: string } } | undefined,
+ canDisplayExecutionTarget: true,
+ canSelectExecutionTarget: true,
+ workspaceScoped: false,
+ },
+ selectExecutionTarget: vi.fn(),
+}));
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+// The real menu opens on hover behind a portal; render its items inline so the
+// cloud-switch action is reachable from the chip itself.
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ DropdownMenu: ({
+ children,
+ items,
+ }: {
+ children: ReactNode;
+ items?: { key: string; label: ReactNode; onClick?: () => void }[];
+ }) => (
+ <div>
+ {children}
+ {items?.map((item) => (
+ <button
+ data-testid={`run-target-menu-${item.key}`}
+ key={item.key}
+ type={'button'}
+ onClick={item.onClick}
+ >
+ {item.label}
+ </button>
+ ))}
+ </div>
+ ),
+}));
+
+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
+ useEffectiveAgencyConfig: () => mocks.agency,
+}));
+
+vi.mock('@/helpers/gatewayMode', () => ({ useIsGatewayModeEnabled: () => false }));
+
+vi.mock('@/features/ChatInput/hooks/useSelectExecutionTarget', () => ({
+ useSelectExecutionTarget: () => mocks.selectExecutionTarget,
+}));
+
+/** A device pick: resolvable everywhere, so the chip is not on the sandbox. */
+const devicePick = (type?: string) => ({
+ boundDeviceId: 'device_1',
+ executionTarget: 'device',
+ ...(type ? { heterogeneousProvider: { type } } : {}),
+});
+
+beforeEach(() => {
+ mocks.agency.agencyConfig = undefined;
+ mocks.selectExecutionTarget.mockReset();
+ mocks.selectExecutionTarget.mockResolvedValue(true);
+});
+
+describe('ProjectRunTargetChip', () => {
+ it('does not offer the cloud switch to a device-only provider', () => {
+ // Amp has no sandbox toolchain: `resolveExecutionTarget` would coerce a
+ // stored sandbox target back to `none`, stripping the working device pick.
+ mocks.agency.agencyConfig = devicePick('amp');
+
+ render(<ProjectRunTargetChip agentId={'agent_1'} />);
+
+ expect(screen.getByTestId('project-run-target-chip')).toBeDisabled();
+ expect(screen.queryByTestId('run-target-menu-sandbox')).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByTestId('project-run-target-chip'));
+
+ expect(mocks.selectExecutionTarget).not.toHaveBeenCalled();
+ });
+
+ it('keeps the cloud switch for a sandbox-capable provider', () => {
+ mocks.agency.agencyConfig = devicePick('claude-code');
+
+ render(<ProjectRunTargetChip agentId={'agent_1'} />);
+
+ expect(screen.getByTestId('project-run-target-chip')).toBeEnabled();
+
+ fireEvent.click(screen.getByTestId('run-target-menu-sandbox'));
+
+ expect(mocks.selectExecutionTarget).toHaveBeenCalledWith('sandbox');
+ });
+
+ it('keeps the cloud switch for an ordinary agent', () => {
+ mocks.agency.agencyConfig = devicePick();
+
+ render(<ProjectRunTargetChip agentId={'agent_1'} />);
+
+ expect(screen.getByTestId('project-run-target-chip')).toBeEnabled();
+
+ fireEvent.click(screen.getByTestId('run-target-menu-sandbox'));
+
+ expect(mocks.selectExecutionTarget).toHaveBeenCalledWith('sandbox');
+ });
+});
diff --git a/src/features/Projects/Workspace/ProjectRunTargetChip.tsx b/src/features/Projects/Workspace/ProjectRunTargetChip.tsx
new file mode 100644
index 00000000000..134024aadc9
--- /dev/null
+++ b/src/features/Projects/Workspace/ProjectRunTargetChip.tsx
@@ -0,0 +1,157 @@
+'use client';
+
+import { isDesktop } from '@lobechat/const';
+import type { DeviceExecutionTarget } from '@lobechat/types';
+import { type DropdownItem, DropdownMenu, Icon, toast, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import {
+ ChevronDownIcon,
+ CloudIcon,
+ LaptopIcon,
+ type LucideIcon,
+ MonitorIcon,
+ MonitorOffIcon,
+ SparklesIcon,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { workingDirectoryChipStyles } from '@/features/ChatInput/ControlBar/workingDirectoryChipStyles';
+import { useSelectExecutionTarget } from '@/features/ChatInput/hooks/useSelectExecutionTarget';
+import {
+ isHeterogeneousSandboxExecutionAvailable,
+ resolveExecutionTarget,
+} from '@/helpers/executionTarget';
+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';
+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
+
+const TARGET_ICONS: Record<DeviceExecutionTarget, LucideIcon> = {
+ auto: SparklesIcon,
+ device: MonitorIcon,
+ local: LaptopIcon,
+ none: MonitorOffIcon,
+ sandbox: CloudIcon,
+};
+
+interface ProjectRunTargetChipProps {
+ agentId: string;
+ /** Icon only, the target in the tooltip — for a narrow composer. */
+ compact?: boolean;
+ disabled?: boolean;
+}
+
+/**
+ * Where the picked agent's new conversation runs, resolved the way the run
+ * resolves it. The cloud sandbox is where a project's repository is checked
+ * out, so an agent that runs anywhere else is offered the switch here; a device
+ * pick stays with the conversation's own device picker.
+ */
+const ProjectRunTargetChip = ({ agentId, compact, disabled }: ProjectRunTargetChipProps) => {
+ const { t } = useTranslation('project');
+ const { t: tChat } = useTranslation('chat');
+ const { agencyConfig, canDisplayExecutionTarget, canSelectExecutionTarget, workspaceScoped } =
+ useEffectiveAgencyConfig(agentId, { topicId: null });
+ const deviceRoutingAvailable = useIsGatewayModeEnabled(agentId);
+ const selectExecutionTarget = useSelectExecutionTarget(agentId);
+
+ if (!canDisplayExecutionTarget) return null;
+
+ const target = resolveExecutionTarget(agencyConfig, {
+ clientExecutionAvailable: isDesktop,
+ deviceRoutingAvailable,
+ isHetero: !!agencyConfig?.heterogeneousProvider?.type,
+ workspaceScoped,
+ });
+ const onSandbox = target === 'sandbox';
+ // A device-only heterogeneous provider (Amp, Cursor, OpenCode, Pi, …) has no
+ // sandbox toolchain: `resolveExecutionTarget` coerces a stored `sandbox`
+ // target back to `none`, so offering the switch would only strip the agent's
+ // runnable device target. Mirrors `HeteroDeviceSwitcher`'s `supportsSandbox`.
+ const sandboxAvailable = isHeterogeneousSandboxExecutionAvailable(
+ agencyConfig?.heterogeneousProvider?.type,
+ );
+ const switchable = !onSandbox && sandboxAvailable && canSelectExecutionTarget && !disabled;
+
+ const switchToSandbox = async () => {
+ if (!(await selectExecutionTarget('sandbox')))
+ toast.error(t('overview.context.target.switchFailed'));
+ };
+
+ const label =
+ target === 'device'
+ ? t('overview.context.target.device')
+ : tChat(`heteroAgent.executionTarget.${target}`);
+
+ const chip = (
+ <button
+ aria-label={label}
+ data-testid={'project-run-target-chip'}
+ disabled={!switchable}
+ type={'button'}
+ {...stylex.props(
+ workingDirectoryChipStyles.chip,
+ styles.button,
+ !switchable && styles.static,
+ target === 'none' && styles.warning,
+ )}
+ >
+ <Icon icon={TARGET_ICONS[target]} size={14} />
+ {!compact && <span {...stylex.props(workingDirectoryChipStyles.label)}>{label}</span>}
+ {switchable && <Icon icon={ChevronDownIcon} size={12} />}
+ </button>
+ );
+
+ const hint = onSandbox
+ ? t('overview.context.target.sandboxTooltip')
+ : target === 'none'
+ ? t('overview.context.target.noneTooltip')
+ : undefined;
+ const tooltip = compact ? [label, hint].filter(Boolean).join(' · ') : hint;
+
+ if (!switchable)
+ return (
+ <Tooltip title={tooltip}>
+ <div>{chip}</div>
+ </Tooltip>
+ );
+
+ const items: DropdownItem[] = [
+ {
+ icon: <Icon icon={CloudIcon} />,
+ key: 'sandbox',
+ label: t('overview.context.target.useSandbox'),
+ onClick: () => void switchToSandbox(),
+ },
+ ];
+
+ return (
+ <Tooltip title={tooltip}>
+ <div>
+ <DropdownMenu items={items} placement={'bottomRight'}>
+ {chip}
+ </DropdownMenu>
+ </div>
+ </Tooltip>
+ );
+};
+
+const styles = stylex.create({
+ // Body size and color: the tray says where the work happens, not a footnote.
+ button: {
+ borderWidth: 0,
+ fontFamily: 'inherit',
+ fontSize: '13px',
+ color: cssVar.colorText,
+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillSecondary },
+ },
+ /** Shown, not picked: no hover, since nothing opens. */
+ static: {
+ cursor: 'default',
+ backgroundColor: { 'default': 'transparent', ':hover': 'transparent' },
+ },
+ warning: {
+ color: cssVar.colorWarning,
+ },
+});
+
+export default ProjectRunTargetChip;
diff --git a/src/features/Projects/Workspace/useProjectComposer.test.ts b/src/features/Projects/Workspace/useProjectComposer.test.ts
index 40f59abbcfb..b1b26de5c56 100644
--- a/src/features/Projects/Workspace/useProjectComposer.test.ts
+++ b/src/features/Projects/Workspace/useProjectComposer.test.ts
@@ -202,6 +202,22 @@ describe('useProjectComposer', () => {
);
});
+ // The topic exists before the send, so the repository has to go with it.
+ it('starts the conversation in the repository picked in the context bar', async () => {
+ mocks.createProjectTopic.mockResolvedValue({ id: 'tpc_1' });
+ const { result } = renderHook(() =>
+ useProjectComposer(project, 'chat', 'coordinator', 'env-repo'),
+ );
+
+ await act(async () => {
+ await result.current.send(composer('Fix the flaky test'));
+ });
+
+ expect(mocks.createProjectTopic).toHaveBeenCalledWith(
+ expect.objectContaining({ environmentId: 'env-repo', projectId: 'prj_1' }),
+ );
+ });
+
it('assigns a task to the picked project agent', async () => {
mocks.createTask.mockResolvedValue({ id: 'task_1', identifier: 'T-1', name: 'Ship it' });
const { result } = renderHook(() => useProjectComposer(project, 'task', 'reviewer'));
diff --git a/src/features/Projects/Workspace/useProjectComposer.ts b/src/features/Projects/Workspace/useProjectComposer.ts
index 6179d749953..ffd8e3e58b3 100644
--- a/src/features/Projects/Workspace/useProjectComposer.ts
+++ b/src/features/Projects/Workspace/useProjectComposer.ts
@@ -109,6 +109,8 @@ export const useProjectComposer = (
mode: ProjectComposerMode,
/** The project agent the message goes to; the main agent unless the user picked another. */
agentId: string,
+ /** The project repository the conversation works in; the server picks the first when unset. */
+ environmentId?: string,
) => {
const { t } = useTranslation('project');
const navigate = useWorkspaceAwareNavigate();
@@ -155,7 +157,7 @@ export const useProjectComposer = (
// Sending here rather than after the page loads keeps the attachments,
// which cannot travel through the URL.
const [topic] = await Promise.all([
- createProjectTopic({ agentId, projectId: project.id, title }),
+ createProjectTopic({ agentId, environmentId, projectId: project.id, title }),
ensureAgentConfigLoaded(agentId),
]);
// Open the conversation right away: the send shows its message there
diff --git a/src/features/Projects/Workspace/useProjectRepository.ts b/src/features/Projects/Workspace/useProjectRepository.ts
new file mode 100644
index 00000000000..e926dd0c795
--- /dev/null
+++ b/src/features/Projects/Workspace/useProjectRepository.ts
@@ -0,0 +1,32 @@
+import { useState } from 'react';
+
+import { useProjectDirectoryStore, useProjectEnvironments } from '@/store/projectWorkingDirectory';
+
+type ProjectEnvironment = ReturnType<typeof useProjectEnvironments>[number];
+
+/** A linked environment a conversation can work in: one that names a repository. */
+export const isRepositoryEnvironment = (environment: ProjectEnvironment) =>
+ (environment.configuration?.sources ?? []).some((source) => source.kind === 'git');
+
+/**
+ * The project's repositories and the one a new conversation starts in: the
+ * person's pick while it is still linked, otherwise the first. The server
+ * applies the same default, so leaving it untouched and picking the first are
+ * the same request.
+ */
+export const useProjectRepository = (
+ projectId: string,
+ /** A workspace-public agent applies published environments only; the server picks the same way. */
+ sharedAgent = false,
+) => {
+ const { hasData } = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);
+ const repositories = useProjectEnvironments(projectId).filter(
+ (environment) =>
+ isRepositoryEnvironment(environment) && (!sharedAgent || environment.visibility === 'public'),
+ );
+ const [pickedId, setPickedId] = useState<string>();
+ const repository =
+ repositories.find((environment) => environment.id === pickedId) ?? repositories[0];
+
+ return { loaded: hasData, repositories, repository, setPickedId };
+};
diff --git a/src/services/projectWorkingDirectory.ts b/src/services/projectWorkingDirectory.ts
index 065a6102240..eaeeb9769b8 100644
--- a/src/services/projectWorkingDirectory.ts
+++ b/src/services/projectWorkingDirectory.ts
@@ -16,6 +16,8 @@ class ProjectWorkingDirectoryService {
lambdaClient.projectWorkingDirectory.saveEnvironment.mutate(input);
attachEnvironment = (projectId: string, environmentId: string) =>
lambdaClient.projectWorkingDirectory.attachEnvironment.mutate({ projectId, environmentId });
+ attachRepository = (input: Parameters<Client['attachRepository']['mutate']>[0]) =>
+ lambdaClient.projectWorkingDirectory.attachRepository.mutate(input);
bind = (input: BindProjectDirectoryInput) =>
lambdaClient.projectWorkingDirectory.bind.mutate(input);
list = (projectId?: string) => lambdaClient.projectWorkingDirectory.list.query({ projectId });
diff --git a/src/store/chat/pendingSandboxSelection.test.ts b/src/store/chat/pendingSandboxSelection.test.ts
index c988a06cc03..9384e914f0b 100644
--- a/src/store/chat/pendingSandboxSelection.test.ts
+++ b/src/store/chat/pendingSandboxSelection.test.ts
@@ -4,6 +4,7 @@ import {
consumePendingSandboxSelection,
getPendingSandboxSelection,
resolvePendingSandboxSelection,
+ seedPendingSandboxSelection,
setPendingSandboxSelection,
setSandboxDefaultSelection,
subscribePendingSandboxSelection,
@@ -68,6 +69,29 @@ describe('pendingSandboxSelection', () => {
expect(toSandboxTopicMetadata(undefined)).toBeUndefined();
});
+ // An explicit temporary-sandbox pick serialized to no fields at all, the same
+ // as no pick, so a project conversation was given the project's checkout.
+ // The server must tell a default the composer filled in from a pick: a
+ // project conversation gives the project's checkout the default's place.
+ it('marks a seeded default, and not a pick of the same place', () => {
+ seedPendingSandboxSelection('agent-seeded', { workingDirectory: '.' });
+
+ expect(toSandboxTopicMetadata(getPendingSandboxSelection('agent-seeded'))).toMatchObject({
+ sandboxSeeded: true,
+ });
+ expect(toSandboxTopicMetadata({ workingDirectory: '.' })).not.toHaveProperty('sandboxSeeded');
+ });
+
+ it('marks an explicit temporary-sandbox pick, and only that', () => {
+ expect(toSandboxTopicMetadata({})).toMatchObject({ sandboxTemporary: true });
+ expect(toSandboxTopicMetadata({ workingDirectory: 'app' })).not.toHaveProperty(
+ 'sandboxTemporary',
+ );
+ expect(toSandboxTopicMetadata({ environmentId: 'env_1' })).not.toHaveProperty(
+ 'sandboxTemporary',
+ );
+ });
+
// The entitlement loads after the composer does. A first message sent while
// it is still in flight used to be born with no folder — the paid default
// silently became a temporary sandbox.
diff --git a/src/store/chat/pendingSandboxSelection.ts b/src/store/chat/pendingSandboxSelection.ts
index 9617914734a..be117cf0501 100644
--- a/src/store/chat/pendingSandboxSelection.ts
+++ b/src/store/chat/pendingSandboxSelection.ts
@@ -57,6 +57,21 @@ export const setPendingSandboxSelection = (agentId: string, selection?: SandboxS
emit();
};
+/**
+ * Selections the composer filled in itself rather than the person choosing
+ * them: the plan's default placement. Kept by identity, so a pick — always a
+ * new object — is never mistaken for one. The server needs the difference: a
+ * project conversation started on the default is given the project's
+ * repository checkout instead, while one the person placed keeps their choice.
+ */
+const seeded = new WeakSet<SandboxSelection>();
+
+/** Fill an agent's empty slot with the default placement, marked as not chosen by anyone. */
+export const seedPendingSandboxSelection = (agentId: string, selection: SandboxSelection): void => {
+ seeded.add(selection);
+ setPendingSandboxSelection(agentId, selection);
+};
+
/**
* The place an agent's next conversation starts when nobody picks one, and
* the plan turns out to include a drive. Registered by the composer as soon as
@@ -69,6 +84,7 @@ const defaults = new Map<string, SandboxSelection>();
/** Register an agent's default placement; `undefined` clears it. */
export const setSandboxDefaultSelection = (agentId: string, selection?: SandboxSelection): void => {
+ if (selection) seeded.add(selection);
if (selection) defaults.set(agentId, selection);
else defaults.delete(agentId);
};
@@ -130,7 +146,13 @@ export const consumePendingSandboxSelection = (agentId: string): SandboxSelectio
return selection;
};
-/** The topic metadata a pending selection becomes when the topic is created with it. */
+/**
+ * The topic metadata a pending selection becomes when the topic is created with
+ * it. An empty selection is the temporary sandbox picked on purpose, and says so:
+ * otherwise it would arrive as nothing picked, and a project conversation would
+ * be given the project's checkout instead. A default nobody picked says that
+ * too, so the project's checkout can take its place.
+ */
export const toSandboxTopicMetadata = (
selection: SandboxSelection | undefined,
): ChatTopicMetadata | undefined =>
@@ -139,4 +161,8 @@ export const toSandboxTopicMetadata = (
sandboxEnvironmentId: selection.environmentId,
sandboxInstanceId: selection.instanceId,
sandboxWorkingDirectory: selection.workingDirectory,
+ ...(seeded.has(selection) && { sandboxSeeded: true }),
+ ...(!selection.environmentId &&
+ !selection.instanceId &&
+ selection.workingDirectory === undefined && { sandboxTemporary: true }),
};
diff --git a/src/store/projectWorkingDirectory/index.ts b/src/store/projectWorkingDirectory/index.ts
index b968b046c38..37fa42cb13c 100644
--- a/src/store/projectWorkingDirectory/index.ts
+++ b/src/store/projectWorkingDirectory/index.ts
@@ -93,6 +93,10 @@ interface ProjectDirectoryStore extends ProjectDirectoryStoreState {
) => Promise<ServiceData<'associateTopic'>>;
/** Link an environment to a project. */
attachEnvironment: (...args: ServiceParams<'attachEnvironment'>) => Promise<void>;
+ /** Link a GitHub repository to a project, making its environment when needed. */
+ attachRepository: (
+ ...args: ServiceParams<'attachRepository'>
+ ) => Promise<ServiceData<'attachRepository'>>;
/** Register a working directory, absorbing the conversations it covers. */
bind: (...args: ServiceParams<'bind'>) => Promise<ServiceData<'bind'>>;
/** Open a project conversation outside any directory binding. */
@@ -277,6 +281,14 @@ export const useProjectDirectoryStore: UseBoundStoreWithEqualityFn<
environments.revalidate(ALL_PROJECTS_KEY),
]);
},
+ attachRepository: async (input) => {
+ const result = await projectWorkingDirectoryService.attachRepository(input);
+ await Promise.all([
+ environments.revalidate(input.projectId),
+ environments.revalidate(ALL_PROJECTS_KEY),
+ ]);
+ return result.data;
+ },
bind: async (input) => {
const result = await projectWorkingDirectoryService.bind(input);
// One bind writes a directory, its environment and the conversations it