🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(project): one environment per project, with any number of repositories (#23402)
Rdmclin2e998173235dc
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.tsindex 955f400dec4..01a8c880df8 100644--- a/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts+++ b/apps/server/src/modules/Mecha/ContextEngineering/providers/index.ts@@ -487,7 +487,7 @@ export const createServerContextFactProviders = ({// the runtime is: that is the workspace the trust token carries, and the// entitlement has to agree with the token that presents it.resolveSandboxPersistence: async () => {- const { mode, cwd, claim, workingDir } = await resolveSandboxSessionConfig({+ const { mode, cwd, claim, initialization, workingDir } = await resolveSandboxSessionConfig({isShareVisitorRun: Boolean(ctx.agentShareVisitor),serverDB: db,topicId: ctx.topicId ?? state.origin?.topicId,@@ -500,7 +500,19 @@ export const createServerContextFactProviders = ({workspaceId,});- return claim ? { cwd, mode, workingDir } : undefined;+ // What the topic's environment checks out, for the model to be told where+ // each repository is — on any sandbox, persistent or not.+ const repositories = (initialization?.sources ?? []).map((source) => ({+ ...(source.path && source.path !== '.' && { folder: source.path }),+ ...(source.ref && { ref: source.ref }),+ repository: source.url+ .replace(/^https:\/\/(www\.)?github\.com\//, '')+ .replace(/\.git$/, '')+ .replace(/\/$/, ''),+ }));++ if (claim) return { cwd, mode, workingDir, ...(repositories.length && { repositories }) };+ return repositories.length ? { mode: 'ephemeral' as const, repositories } : undefined;},listTopicMessages: async (topic) => {diff --git a/apps/server/src/routers/lambda/__tests__/integration/setup.ts b/apps/server/src/routers/lambda/__tests__/integration/setup.tsindex 7c956a14a05..e0c25f6cbc7 100644--- a/apps/server/src/routers/lambda/__tests__/integration/setup.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/setup.ts@@ -63,6 +63,11 @@ export const cleanupTestUser = async (serverDB: LobeChatDatabase, userId: stringconst { users } = await import('@/database/schemas');const { eq } = await import('drizzle-orm');- // Due to foreign key cascade deletion, only the user needs to be deleted+ const { releaseProjectEnvironments } =+ await import('@/database/models/utils/projectEnvironmentCleanup');++ // Everything else cascades from the user; each project's environment is+ // released the way account deletion releases it.+ await releaseProjectEnvironments(serverDB, { userId });await serverDB.delete(users).where(eq(users.id, userId));};diff --git a/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.attachRepository.test.ts b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.attachRepository.test.tsdeleted file mode 100644index 736765dc299..00000000000--- a/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.attachRepository.test.ts+++ /dev/null@@ -1,92 +0,0 @@-// @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.compat.test.ts b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.compat.test.tsnew file mode 100644index 00000000000..26b35b951d9--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.compat.test.ts@@ -0,0 +1,96 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ addRepositories: vi.fn(),+ findById: vi.fn(),+ get: 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/repositories/projectEnvironment', () => ({+ ProjectEnvironmentRepository: vi.fn(function () {+ return { addRepositories: mocks.addRepositories, get: mocks.get };+ }),+}));++vi.mock('@/database/models/environment', () => ({+ EnvironmentModel: vi.fn(function () {+ return { findById: mocks.findById };+ }),+}));++const { projectWorkingDirectoryRouter } = await import('../projectWorkingDirectory');++const caller = () =>+ projectWorkingDirectoryRouter.createCaller({ userId: 'user-1', workspaceId: null } as never);++/**+ * Clients built before a project had one environment still call these; each+ * maps onto the single environment instead of failing as an unknown procedure.+ */+describe('projectWorkingDirectory compatibility procedures', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.addRepositories.mockResolvedValue({ id: 'env-1' });+ mocks.get.mockResolvedValue({ id: 'env-1' });+ });++ it('attachRepository adds the repository to the project environment', async () => {+ await expect(+ caller().attachRepository({+ projectId: 'project-1',+ repository: {+ defaultBranch: 'main',+ name: 'a/one',+ url: 'https://github.com/a/one',+ },+ }),+ ).resolves.toEqual({ data: { id: 'env-1' }, success: true });+ expect(mocks.addRepositories).toHaveBeenCalledWith('project-1', [+ { sources: [{ kind: 'git', ref: 'main', url: 'https://github.com/a/one' }] },+ ]);+ });++ it('attachRepository refuses a URL the environment cannot clone', async () => {+ await expect(+ caller().attachRepository({+ projectId: 'project-1',+ repository: { name: 'x', url: 'http://example.com/x' },+ }),+ ).rejects.toThrow('Unsupported repository URL');+ expect(mocks.addRepositories).not.toHaveBeenCalled();+ });++ it("attachEnvironment adds the environment's repositories", async () => {+ const configuration = { sources: [{ kind: 'git', url: 'https://github.com/a/two' }] };+ mocks.findById.mockResolvedValue({ configuration, id: 'standalone' });++ await caller().attachEnvironment({+ environmentId: '6f1c1b2e-6c8a-4b8e-9a52-6e7b8f1d2c3a',+ projectId: 'project-1',+ });+ expect(mocks.addRepositories).toHaveBeenCalledWith('project-1', [configuration]);+ });++ it('detachEnvironment changes nothing and returns the environment', async () => {+ await expect(+ caller().detachEnvironment({+ environmentId: '6f1c1b2e-6c8a-4b8e-9a52-6e7b8f1d2c3a',+ projectId: 'project-1',+ }),+ ).resolves.toEqual({ data: { id: 'env-1' }, success: true });+ expect(mocks.addRepositories).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.createProjectTopic.test.ts b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.createProjectTopic.test.tsindex ee99730d9a0..36975245ed9 100644--- a/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.createProjectTopic.test.ts+++ b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.createProjectTopic.test.ts@@ -94,7 +94,6 @@ describe('projectWorkingDirectory.createProjectTopic', () => {expect(mocks.resolveProjectTopicSandbox).toHaveBeenCalledWith(expect.objectContaining({agentId: 'coordinator',- environmentId: 'env-repo',projectId: 'project-1',workspaceId: 'ws-1',}),@@ -109,4 +108,18 @@ describe('projectWorkingDirectory.createProjectTopic', () => {}),);});++ it("starts in an empty working directory when asked to go without the project's environment", async () => {+ mocks.findById.mockResolvedValue({ id: 'project-1', userId: 'creator' });+ mocks.resolveProjectTopicSandbox.mockResolvedValue({ sandboxEnvironmentId: 'env-repo' });++ await caller().createProjectTopic({ ...input, withoutEnvironment: true });++ expect(mocks.resolveProjectTopicSandbox).not.toHaveBeenCalled();+ expect(mocks.createTopic).toHaveBeenCalledWith(+ expect.not.objectContaining({+ metadata: expect.objectContaining({ sandboxEnvironmentId: expect.anything() }),+ }),+ );+ });});diff --git a/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.ts b/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.tsindex c3df81cf49b..4d4d6d07383 100644--- a/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.ts+++ b/apps/server/src/routers/lambda/__tests__/sandboxStorage.test.ts@@ -137,6 +137,11 @@ const mockResolveCloneCredential = vi.hoisted(() => vi.fn());vi.mock('@/server/services/scm/cloneCredential', () => ({resolveScmCloneCredential: mockResolveCloneCredential,+ // One repository: the single host-wide credential, as a list.+ resolveScmCloneCredentials: async (params: unknown) => {+ const credential = await mockResolveCloneCredential(params);+ return credential ? [credential] : [];+ },}));const { sandboxStorageRouter } = await import('../sandboxStorage');diff --git a/apps/server/src/routers/lambda/__tests__/trash.projectFilter.test.ts b/apps/server/src/routers/lambda/__tests__/trash.projectFilter.test.tsindex 9bfd94adbf2..7c447e7d0a9 100644--- a/apps/server/src/routers/lambda/__tests__/trash.projectFilter.test.ts+++ b/apps/server/src/routers/lambda/__tests__/trash.projectFilter.test.ts@@ -9,7 +9,15 @@ import { AgentModel } from '@/database/models/agent';import { ProjectModel } from '@/database/models/project';import { TopicModel } from '@/database/models/topic';import { ProjectRepository } from '@/database/repositories/project';-import { agents, topics, trashItems, users, workspaces } from '@/database/schemas';+import {+ agents,+ environments,+ projectEnvironments,+ topics,+ trashItems,+ users,+ workspaces,+} from '@/database/schemas';import { TrashService } from '@/server/services/trash';let testDB: LobeChatDatabase;@@ -91,6 +99,8 @@ const caller = (ctx: any) => trashRouter.createCaller(ctx);beforeEach(async () => {testDB = await getTestDB();+ await testDB.delete(projectEnvironments);+ await testDB.delete(environments);await testDB.delete(users);await testDB.insert(users).values([{ id: ownerId }, { id: memberId }, { id: strangerId }]);await testDB.insert(workspaces).values([@@ -101,6 +111,9 @@ beforeEach(async () => {afterEach(async () => {vi.clearAllMocks();+ // Every project made here has an environment, which holds its user back.+ await testDB.delete(projectEnvironments);+ await testDB.delete(environments);await testDB.delete(users);});diff --git a/apps/server/src/routers/lambda/_schema/__tests__/environment.test.ts b/apps/server/src/routers/lambda/_schema/__tests__/environment.test.tsnew file mode 100644index 00000000000..8dfb8ebd1f5--- /dev/null+++ b/apps/server/src/routers/lambda/_schema/__tests__/environment.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';++import { configurationSchema } from '../environment';++describe('configurationSchema sources', () => {+ const git = (url: string, path?: string) => ({+ kind: 'git' as const,+ url,+ ...(path && { path }),+ });++ it('accepts repositories in folders of their own, or left to the layout', () => {+ expect(+ configurationSchema.safeParse({+ sources: [git('https://github.com/a/one'), git('https://github.com/a/two', 'two')],+ }).success,+ ).toBe(true);+ });++ it('refuses two repositories checked out into the same folder', () => {+ const result = configurationSchema.safeParse({+ sources: [git('https://github.com/a/one', 'app'), git('https://github.com/a/two', './app/')],+ });+ expect(result.success).toBe(false);+ });++ it('takes a setup command for a single repository', () => {+ expect(+ configurationSchema.safeParse({+ sources: [{ ...git('https://github.com/a/one'), setupCommand: 'pnpm i' }],+ }).success,+ ).toBe(true);+ });+});diff --git a/apps/server/src/routers/lambda/_schema/environment.ts b/apps/server/src/routers/lambda/_schema/environment.tsindex d61a029f258..f627878087e 100644--- a/apps/server/src/routers/lambda/_schema/environment.ts+++ b/apps/server/src/routers/lambda/_schema/environment.ts@@ -30,6 +30,8 @@ const environmentSourceSchema = z.object({/** Where the checkout lands, relative to the instance's own directory. */path: relativePathSchema.optional(),ref: z.string().trim().min(1).max(255).optional(),+ /** Run inside this repository's folder before the environment's own setup. */+ setupCommand: z.string().max(8000).optional(),url: z.string().url()@@ -75,11 +77,31 @@ export const configurationSchema = z.object({// it would leave those environments impossible to change.kind: z.enum(['code', 'files']).optional(),maintenanceCommand: z.string().max(8000).optional(),- // One repository per environment. The wire format stays a list because the- // execution plane checks out an array of sources, but an environment that- // builds from two repositories has no single working directory to hand a- // conversation — and the picker that fills this offers exactly one.- sources: z.array(environmentSourceSchema).max(1).optional(),+ // Any number of repositories, or none. The working directory a conversation+ // gets is still one folder: the first repository is checked out at its top+ // and each one after it into a folder of its own (`path`, which the form+ // fills with the repository's name), the layout Codex environments use.+ sources: z+ .array(environmentSourceSchema)+ .max(10)+ // Two checkouts into one folder would merge their files and leave one+ // repository's `.git` over the other's. Folders left blank are given+ // distinct ones by `layoutRepositorySources`; one set by hand is kept as+ // it is, so it is checked here.+ .refine(+ (sources) => {+ const folders = sources.flatMap((source) => {+ const folder = source.path+ ?.trim()+ .replace(/^\.?\/+/, '')+ .replace(/\/+$/, '');+ return folder && folder !== '.' ? [folder] : [];+ });+ return new Set(folders).size === folders.length;+ },+ { message: 'Two repositories cannot be checked out into the same folder' },+ )+ .optional(),});/**diff --git a/apps/server/src/routers/lambda/project.ts b/apps/server/src/routers/lambda/project.tsindex 6976656999a..5bfd8d089d0 100644--- a/apps/server/src/routers/lambda/project.ts+++ b/apps/server/src/routers/lambda/project.ts@@ -14,6 +14,7 @@ import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAimport { ProjectIdentifierTakenError, ProjectModel } from '@/database/models/project';import { ProjectRepository } from '@/database/repositories/project';import { ProjectCoordinatorRepository } from '@/database/repositories/projectCoordinator';+import { ProjectEnvironmentRepository } from '@/database/repositories/projectEnvironment';import { ProjectOverviewRepository } from '@/database/repositories/projectOverview';import type { LobeChatDatabase } from '@/database/type';import { router } from '@/libs/trpc/lambda';@@ -192,6 +193,20 @@ export const projectRouter = router({id: z.string().regex(PROJECT_ID_REGEX).optional(),identifier: projectIdentifierInput.optional(),name: z.string().min(1).max(255),+ /**+ * More GitHub repositories the project's environment checks out beside+ * `repository` — the create dialog's advanced options. Laid out side+ * by side, each in a folder named after it.+ */+ additionalRepositories: z+ .array(+ z.object({+ defaultBranch: z.string().max(255).optional(),+ url: z.string().min(1).max(2048),+ }),+ )+ .max(9)+ .optional(),repository: z.object({defaultBranch: z.string().max(255).optional(),@@ -480,6 +495,10 @@ export const projectRouter = router({previousVisibility = project.visibility;}const updated = requireResult(await ctx.projectModel.update(id, input));+ // The environment is named after the project and not editable on its+ // own, so a rename carries over at once rather than on its next read.+ if (input.name !== undefined)+ await ProjectEnvironmentRepository.ensure(ctx.serverDB, updated);// Members can no longer see the project, so they must not keep opening its goals.if (input.visibility === 'private' && previousVisibility === 'public')await new GoalService(diff --git a/apps/server/src/routers/lambda/projectWorkingDirectory.ts b/apps/server/src/routers/lambda/projectWorkingDirectory.tsindex 957ee5e1903..51bd9722a62 100644--- a/apps/server/src/routers/lambda/projectWorkingDirectory.ts+++ b/apps/server/src/routers/lambda/projectWorkingDirectory.ts@@ -10,6 +10,7 @@ import { ProjectModel } from '@/database/models/project';import { ProjectWorkingDirectoryModel } from '@/database/models/projectWorkingDirectory';import { TopicModel } from '@/database/models/topic';import { ProjectDirectoryRepository } from '@/database/repositories/projectDirectory';+import { ProjectEnvironmentRepository } from '@/database/repositories/projectEnvironment';import { agents } from '@/database/schemas';import { buildWorkspaceWhere } from '@/database/utils/workspace';import { router } from '@/libs/trpc/lambda';@@ -28,6 +29,7 @@ import {} from './_helpers/conversationResourceGuard';import { getResourceConfigAccess } from './_helpers/resourceConfigGuard';import { assertCreatorTopicTargets } from './_helpers/shareVisitorTargetGuard';+import { configurationSchema } from './_schema/environment';const procedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { serverDB, userId, workspaceId } = opts.ctx;@@ -36,6 +38,7 @@ const procedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {directoryModel: new ProjectWorkingDirectoryModel(serverDB, userId, workspaceId ?? undefined),directoryRepo: new ProjectDirectoryRepository(serverDB, userId, workspaceId ?? undefined),environmentModel: new EnvironmentModel(serverDB, userId, workspaceId ?? undefined),+ environmentRepo: new ProjectEnvironmentRepository(serverDB, userId, workspaceId ?? undefined),projectModel: new ProjectModel(serverDB, userId, workspaceId ?? undefined),topicModel: new TopicModel(serverDB, userId, workspaceId ?? undefined),// Topics written here exist before any run does, so they have to pin their@@ -55,6 +58,13 @@ const procedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {});const write = procedure.use(withScopedPermission('agent:update'));+/** A project the caller cannot reach answers as not found, not as a server error. */+const notFound = (error: unknown): never => {+ if (error instanceof Error && /not found or access denied/i.test(error.message))+ throw new TRPCError({ code: 'NOT_FOUND', message: error.message });+ throw error;+};+/** Per-agent permission lookups each hit the database; a large project must not fan out unbounded. */const CONFIG_ACCESS_LOOKUP_CONCURRENCY = 5;@@ -134,9 +144,14 @@ 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. */+ /** Ignored: a project has one environment. Kept for older clients. */environmentId: z.string().optional(),title: z.string().trim().min(1).max(255),+ /**+ * Start in an empty working directory instead of one the project's+ * environment initializes — the composer's "No environment".+ */+ withoutEnvironment: z.boolean().optional(),}),).mutation(async ({ ctx, input }) => {@@ -152,14 +167,15 @@ export const projectWorkingDirectoryRouter = router({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,- }),+ input.withoutEnvironment+ ? {}+ : resolveProjectTopicSandbox({+ agentId: input.agentId,+ db: ctx.serverDB,+ projectId: input.projectId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ }),]);return {data: await ctx.topicModel.create({@@ -182,23 +198,44 @@ export const projectWorkingDirectoryRouter = router({);return { data: await redactAgentDevicePins(ctx, data), success: true };}),- attachEnvironment: write- .input(z.object({ projectId: z.string(), environmentId: z.string().uuid() }))- .mutation(async ({ ctx, input }) => ({- data: await ctx.projectModel.attachEnvironment(input.projectId, input.environmentId),+ /**+ * The project's environment — every project has exactly one. A project from+ * before that rule is brought to it on this first read (see+ * `ProjectEnvironmentRepository.ensure`), silently.+ */+ getEnvironment: procedure+ .input(z.object({ projectId: z.string() }))+ .query(async ({ ctx, input }) => ({+ data: await ctx.environmentRepo.get(input.projectId).catch(notFound),success: true,})),- /** Unlink an environment from the project; the environment itself is kept. */- detachEnvironment: write- .input(z.object({ projectId: z.string(), environmentId: z.string().uuid() }))- .mutation(async ({ ctx, input }) => ({- data: await ctx.projectModel.detachEnvironment(input.projectId, input.environmentId),+ /**+ * Edits the project's environment: its repositories (any number, or none),+ * setup and variables. A folder already built keeps the definition it was+ * built from; the next one takes this.+ */+ updateEnvironment: write+ .input(+ z.object({+ configuration: configurationSchema.optional(),+ description: z.string().max(2000).nullable().optional(),+ projectId: z.string(),+ }),+ )+ .mutation(async ({ ctx, input: { projectId, ...patch } }) => ({+ data: await ctx.environmentRepo.update(projectId, patch).catch(notFound),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.+ * Compatibility for clients built before a project had exactly one+ * environment (a tab left open across the deploy, a released desktop app).+ * Each maps onto the single environment rather than failing as an unknown+ * procedure; remove once no supported client calls them.+ *+ * - `attachRepository` adds the repository to the project's environment.+ * - `attachEnvironment` adds the repositories of an environment the caller+ * can read to it; nothing is linked.+ * - `detachEnvironment` has nothing to undo and returns the environment.*/attachRepository: write.input(@@ -209,28 +246,53 @@ export const projectWorkingDirectoryRouter = router({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,+ .mutation(async ({ ctx, input: { projectId, repository } }) => {+ const parsed = configurationSchema.safeParse({+ sources: [+ {+ kind: 'git',+ url: repository.url,+ ...(repository.defaultBranch && { ref: repository.defaultBranch }),+ },+ ],});- await ctx.projectModel.attachEnvironment(projectId, environment.id);- return { data: environment, success: true };+ if (!parsed.success)+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Unsupported repository URL' });+ return {+ data: await ctx.environmentRepo.addRepositories(projectId, [parsed.data]).catch(notFound),+ success: true,+ };}),+ attachEnvironment: write+ .input(z.object({ environmentId: z.string().uuid(), projectId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ const source = await ctx.environmentModel.findById(input.environmentId);+ if (!source) throw new TRPCError({ code: 'NOT_FOUND', message: 'Environment not found' });+ return {+ data: await ctx.environmentRepo+ .addRepositories(input.projectId, [source.configuration])+ .catch(notFound),+ success: true,+ };+ }),+ detachEnvironment: write+ .input(z.object({ environmentId: z.string().uuid(), projectId: z.string() }))+ .mutation(async ({ ctx, input }) => ({+ data: await ctx.environmentRepo.get(input.projectId).catch(notFound),+ success: true,+ })),+ /**+ * The project's environment as a one-row list, the shape the directory and+ * location pickers read; without a project, the caller's standalone ones.+ */listEnvironments: procedure.input(z.object({ projectId: z.string().optional() })).query(async ({ ctx, input }) => ({data: input.projectId- ? await ctx.projectModel.listEnvironments(input.projectId)+ ? [await ctx.environmentRepo.get(input.projectId).catch(notFound)]: await ctx.environmentModel.list(),success: true,})),diff --git a/apps/server/src/routers/lambda/sandboxStorage/instanceBuild.ts b/apps/server/src/routers/lambda/sandboxStorage/instanceBuild.tsindex a46b1d8bba0..2953d5338bc 100644--- a/apps/server/src/routers/lambda/sandboxStorage/instanceBuild.ts+++ b/apps/server/src/routers/lambda/sandboxStorage/instanceBuild.ts@@ -3,7 +3,7 @@ import { TRPCError } from '@trpc/server';import { z } from 'zod';import { router } from '@/libs/trpc/lambda';-import { resolveScmCloneCredential } from '@/server/services/scm/cloneCredential';+import { resolveScmCloneCredentials } from '@/server/services/scm/cloneCredential';import { assertNotLeftOnPublicDrive, resolveInstanceDrive } from './driveScope';import { isBuildable } from './instanceOperations';@@ -73,7 +73,7 @@ export const instanceBuildRouter = router({// private key lives on this side; the execution plane is handed the// result and never the inputs, the same way it is handed the workspace// claim.- const credential = await resolveScmCloneCredential({+ const credentials = await resolveScmCloneCredentials({configuration: specification,db: ctx.serverDB,userId: ctx.userId,@@ -82,7 +82,7 @@ export const instanceBuildRouter = router({try {const { buildId } = await client.buildInstance({- credentials: credential ? [credential] : undefined,+ credentials: credentials.length > 0 ? credentials : undefined,// Where the checkout lands on the volume: the instance's own folder,// which is what its file browser opens.instanceDir: instance.workingDirectory,diff --git a/apps/server/src/services/channel/README.md b/apps/server/src/services/channel/README.mdindex 1c4dda915fe..8feaed766e1 100644--- a/apps/server/src/services/channel/README.md+++ b/apps/server/src/services/channel/README.md@@ -8,7 +8,7 @@ replies never trigger another classification.## Enable-Configure a TypeSafe API key through the deployment's \`TYPESAFE\_API\_KEY\` environment variable,+Configure a TypeSafe API key through the deployment's \`TYPESAFE_API_KEY\` environment variable,or in the sender's provider settings (workspace provider settings in workspace scope).Routing is enabled by default. Configure its switch and decision model in Settings → Service Models → Advanced → Channels:diff --git a/apps/server/src/services/sandbox/__tests__/environmentInit.test.ts b/apps/server/src/services/sandbox/__tests__/environmentInit.test.tsindex c3d8853a6b4..9b645cd0bd9 100644--- a/apps/server/src/services/sandbox/__tests__/environmentInit.test.ts+++ b/apps/server/src/services/sandbox/__tests__/environmentInit.test.ts@@ -62,6 +62,24 @@ describe('toSandboxInitialization', () => {});});+ it('lays several repositories out side by side, never one inside another', () => {+ expect(+ toSandboxInitialization({+ configuration: {+ sources: [+ { kind: 'git', url: 'https://github.com/lobehub/lobehub' },+ { kind: 'git', path: 'lobe-ui', url: 'https://github.com/lobehub/lobe-ui' },+ ],+ },+ id: 'env-1',+ name: 'Two',+ })?.sources,+ ).toEqual([+ { path: 'lobehub', url: 'https://github.com/lobehub/lobehub' },+ { path: 'lobe-ui', url: 'https://github.com/lobehub/lobe-ui' },+ ]);+ });+it('asks for nothing when the environment has neither a repository nor setup', () => {expect(toSandboxInitialization({@@ -301,6 +319,24 @@ describe('buildSandboxEnvironmentInitCommand', () => {expect(result.stdout).not.toContain('c2VjcmV0');});+ it('gives git one credential per repository when there are several, and unsets them all', () => {+ const command = buildSandboxEnvironmentInitCommand(+ init({+ bootstrapCommand: 'echo "[$GIT_CONFIG_COUNT$GIT_CONFIG_VALUE_1]" > seen.txt',+ cloneCredentials: [+ { header: 'Authorization: Basic b25l', urlPrefix: 'https://github.com/acme/one' },+ { header: 'Authorization: Basic dHdv', urlPrefix: 'https://github.com/acme/two' },+ ],+ }),+ );++ expect(command).toContain('GIT_CONFIG_COUNT=2');+ expect(command).toContain('http.https://github.com/acme/two.extraHeader');+ const result = run(command, work);+ expect(environmentInitReport(result.stdout)).toContain('Initialized');+ expect(readFileSync(join(work, 'seen.txt'), 'utf8').trim()).toBe('[]');+ });+it('keeps the variables out of the shell that runs afterwards', () => {run(buildSandboxEnvironmentInitCommand(init()), work);diff --git a/apps/server/src/services/sandbox/__tests__/projectPlacement.test.ts b/apps/server/src/services/sandbox/__tests__/projectPlacement.test.tsindex 5cbde2bf76f..a4badc8962d 100644--- a/apps/server/src/services/sandbox/__tests__/projectPlacement.test.ts+++ b/apps/server/src/services/sandbox/__tests__/projectPlacement.test.ts@@ -2,14 +2,13 @@ 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(),+ getProjectEnvironment: vi.fn(),}));-vi.mock('@/database/models/project', () => ({- ProjectModel: vi.fn(function () {- return { listEnvironments: mocks.listEnvironments };+vi.mock('@/database/repositories/projectEnvironment', () => ({+ ProjectEnvironmentRepository: vi.fn(function () {+ return { get: mocks.getProjectEnvironment };}),}));@@ -19,23 +18,19 @@ vi.mock('@/database/models/agent', () => ({}),}));-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',+const environment = {+ configuration: {+ kind: 'code',+ sources: [+ { kind: 'git', url: 'https://github.com/lobehub-biz/agent-mail' },+ { kind: 'git', path: 'lobe-tts', url: 'https://github.com/lobehub/lobe-tts' },+ ],+ },+ id: 'env-project',+ name: 'Agent mail',visibility: 'private',};@@ -44,81 +39,45 @@ const resolve = (overrides: Record<string, unknown> = {}) =>describe('resolveProjectTopicSandbox', () => {beforeEach(() => {- mocks.listEnvironments.mockReset().mockResolvedValue([repository]);- mocks.findEnvironmentById.mockReset().mockResolvedValue(repository);+ mocks.getProjectEnvironment.mockReset().mockResolvedValue(environment);mocks.getAgentVisibility.mockReset().mockResolvedValue('private');});- // Coding belongs in the temporary sandbox: the repository is cloned into a- // fresh one, never checked out in a folder on the drive.- it("clones the project's repository into a temporary sandbox", async () => {- await expect(resolve()).resolves.toEqual({ sandboxEnvironmentId: 'env-repo' });- });-- it('names no drive or folder in a workspace either', async () => {- mocks.findEnvironmentById.mockResolvedValue({ ...repository, visibility: 'public' });-- await expect(resolve({ workspaceId: 'ws-1' })).resolves.toEqual({- sandboxEnvironmentId: 'env-repo',- });- });-- 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');+ // Coding belongs in the temporary sandbox: the project's environment is+ // applied to a fresh one, never to a folder on the drive.+ it("starts in the project's own environment", async () => {+ await expect(resolve()).resolves.toEqual({ sandboxEnvironmentId: 'env-project' });+ expect(mocks.getProjectEnvironment).toHaveBeenCalledWith('proj_1');});- 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);-+ it('ignores an environment the client names: a project has only its own', async () => {await expect(resolve({ environmentId: 'env-other' })).resolves.toEqual({- sandboxEnvironmentId: 'env-other',+ sandboxEnvironmentId: 'env-project',});});- // 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');+ it('starts nowhere special when the environment checks nothing out', async () => {+ mocks.getProjectEnvironment.mockResolvedValue({+ ...environment,+ configuration: { kind: 'code' },+ });- 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();+ await expect(resolve()).resolves.toEqual({});});- it('gives a workspace-public agent the published repository', async () => {- const published = { ...repository, id: 'env-pub', visibility: 'public' };+ it('gives a workspace-public agent the environment only once it is published', async () => {mocks.getAgentVisibility.mockResolvedValue('public');- mocks.listEnvironments.mockResolvedValue([repository, published]);- mocks.findEnvironmentById.mockResolvedValue(published);- await expect(resolve({ agentId: 'agt-shared', workspaceId: 'ws-1' })).resolves.toEqual({- sandboxEnvironmentId: 'env-pub',- });- });+ await expect(resolve({ agentId: 'agt_1', workspaceId: 'ws-1' })).resolves.toEqual({});- 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({});+ mocks.getProjectEnvironment.mockResolvedValue({ ...environment, visibility: 'public' });+ await expect(resolve({ agentId: 'agt_1', workspaceId: 'ws-1' })).resolves.toEqual({+ sandboxEnvironmentId: 'env-project',+ });});it('never throws', async () => {- mocks.listEnvironments.mockRejectedValue(new Error('db down'));+ mocks.getProjectEnvironment.mockRejectedValue(new Error('Project not found or access denied'));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.tsindex 19d353dfd74..345f02f9813 100644--- a/apps/server/src/services/sandbox/__tests__/session.test.ts+++ b/apps/server/src/services/sandbox/__tests__/session.test.ts@@ -19,6 +19,11 @@ const { findById, findInstanceById, getAgentVisibility, resolveSandboxStorageClavi.mock('@/server/services/scm/cloneCredential', () => ({resolveScmCloneCredential: mocks.resolveScmCloneCredential,+ // One repository: the single host-wide credential, as a list.+ resolveScmCloneCredentials: async (params: unknown) => {+ const credential = await mocks.resolveScmCloneCredential(params);+ return credential ? [credential] : [];+ },}));vi.mock('../entitlement', () => ({diff --git a/apps/server/src/services/sandbox/environmentInit.ts b/apps/server/src/services/sandbox/environmentInit.tsindex 6359dd71f66..70f6b9cef87 100644--- a/apps/server/src/services/sandbox/environmentInit.ts+++ b/apps/server/src/services/sandbox/environmentInit.ts@@ -1,4 +1,5 @@import type { EnvironmentConfiguration } from '@lobechat/types';+import { layoutRepositorySources, withRepositorySetup } from '@lobechat/types';/** Long enough for a shallow clone and a dependency install. */export const SANDBOX_ENVIRONMENT_INIT_TIMEOUT_MS = 600_000;@@ -26,6 +27,8 @@ export interface SandboxInitialization {* a build used to get. Resolved per run and never stored.*/cloneCredential?: { header: string; urlPrefix: string };+ /** One per repository when the environment checks out several GitHub repositories. */+ cloneCredentials?: { header: string; urlPrefix: string }[];env?: Record<string, string>;environmentId: string;name: string;@@ -50,8 +53,10 @@ export const toSandboxInitialization = (environment: {id: string;name: string;}): SandboxInitialization | undefined => {- const configuration = environment.configuration ?? {};- const sources = (configuration.sources ?? []).flatMap((source) =>+ // Each repository's own setup folded into the one setup command.+ const configuration = withRepositorySetup(environment.configuration ?? {});+ // One repository at the top, several side by side — see `layoutRepositorySources`.+ const sources = layoutRepositorySources(configuration.sources ?? []).flatMap((source) =>source.kind === 'git' && source.url? [{@@ -160,15 +165,26 @@ export const buildSandboxEnvironmentInitCommand = (init: SandboxInitialization):// Given to git through its environment for the clones alone, and unset// before setup runs: nothing writes it to disk or into the checkout's// `.git/config`, and setup — or a command after it — cannot read it back.+ // One entry per repository when there are several, each scoped to its url.+ const cloneCredentials = [+ ...(init.cloneCredentials ?? []),+ ...(init.cloneCredential ? [init.cloneCredential] : []),+ ];const credential =- init.cloneCredential && clones.length > 0+ cloneCredentials.length > 0 && clones.length > 0? {set: [- `export GIT_CONFIG_COUNT=1`,- `export GIT_CONFIG_KEY_0=${shellQuote(`http.${init.cloneCredential.urlPrefix}.extraHeader`)}`,- `export GIT_CONFIG_VALUE_0=${shellQuote(init.cloneCredential.header)}`,+ `export GIT_CONFIG_COUNT=${cloneCredentials.length}`,+ ...cloneCredentials.flatMap((item, index) => [+ `export GIT_CONFIG_KEY_${index}=${shellQuote(`http.${item.urlPrefix}.extraHeader`)}`,+ `export GIT_CONFIG_VALUE_${index}=${shellQuote(item.header)}`,+ ]),+ ],+ unset: [+ `unset GIT_CONFIG_COUNT ${cloneCredentials+ .map((_, index) => `GIT_CONFIG_KEY_${index} GIT_CONFIG_VALUE_${index}`)+ .join(' ')}`,],- unset: [`unset GIT_CONFIG_COUNT GIT_CONFIG_KEY_0 GIT_CONFIG_VALUE_0`],}: { set: [], unset: [] };diff --git a/apps/server/src/services/sandbox/projectPlacement.ts b/apps/server/src/services/sandbox/projectPlacement.tsindex 78ef7fcf94c..b20e9ffd627 100644--- a/apps/server/src/services/sandbox/projectPlacement.ts+++ b/apps/server/src/services/sandbox/projectPlacement.ts@@ -3,8 +3,7 @@ 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';+import { ProjectEnvironmentRepository } from '@/database/repositories/projectEnvironment';const log = debug('lobe-server:sandbox:project-placement');@@ -14,7 +13,7 @@ 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. */+ /** Ignored: a project has one environment. Kept for older clients. */environmentId?: string;projectId: string;userId: string;@@ -25,8 +24,8 @@ const hasGitSource = (configuration: { sources?: { kind?: string }[] } | null |(configuration?.sources ?? []).some((source) => source.kind === 'git');/**- * The sandbox a new project conversation starts in: the project's repository,- * cloned into a temporary Cloud Sandbox.+ * The sandbox a new project conversation starts in: the project's environment —+ * its repositories, setup and variables — applied to a temporary Cloud Sandbox.** Coding belongs in the temporary sandbox, which is discarded after use: a* repository's dependencies and build output would only fill the drive, and@@ -45,25 +44,21 @@ const hasGitSource = (configuration: { sources?: { kind?: string }[] } | null |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 environment = await new ProjectEnvironmentRepository(db, userId, workspaceId).get(+ projectId,+ );+ if (!hasGitSource(environment.configuration)) return {};+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 {};+ if (sharedAgent && environment.visibility !== 'public') return {};return { sandboxEnvironmentId: environment.id };} catch (error) {diff --git a/apps/server/src/services/sandbox/session.ts b/apps/server/src/services/sandbox/session.tsindex 48e19679d4c..1222f43a314 100644--- a/apps/server/src/services/sandbox/session.ts+++ b/apps/server/src/services/sandbox/session.ts@@ -12,13 +12,14 @@ import {} from '@lobechat/builtin-tool-cloud-sandbox';import type { LobeChatDatabase } from '@lobechat/database';import type { EnvironmentConfiguration } from '@lobechat/types';+import { withRepositorySetup } from '@lobechat/types';import debug from 'debug';import { AgentModel } from '@/database/models/agent';import { EnvironmentModel } from '@/database/models/environment';import { EnvironmentInstanceModel } from '@/database/models/environmentInstance';import { TopicModel } from '@/database/models/topic';-import { resolveScmCloneCredential } from '@/server/services/scm/cloneCredential';+import { resolveScmCloneCredentials } from '@/server/services/scm/cloneCredential';import { sandboxStorageBinding } from './binding';import { driveFolderExists, ensureDriveFolder } from './driveFolder';@@ -123,9 +124,11 @@ export interface SandboxSessionConfig {* session of every environment that gained one.*/const toSessionSpecification = (- configuration: EnvironmentConfiguration | null | undefined,+ stored: EnvironmentConfiguration | null | undefined,): SandboxSessionSpecification | undefined => {- if (!configuration) return undefined;+ if (!stored) return undefined;+ // Each repository's own setup rides in the one command the plane runs.+ const configuration = withRepositorySetup(stored);const specification: SandboxSessionSpecification = {...(configuration.bootstrapCommand && { bootstrapCommand: configuration.bootstrapCommand }),@@ -446,14 +449,18 @@ const resolveInitialization = async ({// The same credential a build used to get, so a private repository the// picker offered still clones. Never throws: without one, a public// repository clones and a private one fails in the report, by name.- const cloneCredential = await resolveScmCloneCredential({+ const cloneCredentials = await resolveScmCloneCredentials({configuration: environment.configuration ?? undefined,db: serverDB,userId,workspaceId,});- return cloneCredential ? { ...initialization, cloneCredential } : initialization;+ if (cloneCredentials.length === 0) return initialization;+ // One repository keeps the single host-wide credential it always had.+ return cloneCredentials.length === 1+ ? { ...initialization, cloneCredential: cloneCredentials[0] }+ : { ...initialization, cloneCredentials };} catch (error) {log('Failed to read the environment for topic %s: %O', topicId, error);return undefined;diff --git a/apps/server/src/services/scm/__tests__/cloneCredential.test.ts b/apps/server/src/services/scm/__tests__/cloneCredential.test.tsindex b5545fe7616..83c930fd290 100644--- a/apps/server/src/services/scm/__tests__/cloneCredential.test.ts+++ b/apps/server/src/services/scm/__tests__/cloneCredential.test.ts@@ -6,7 +6,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { ScmInstallationModel } from '@/database/models/scm';import { scmInstallations, users } from '@/database/schemas';-import { githubRepositoryOf, resolveScmCloneCredential } from '../cloneCredential';+import {+ githubRepositoryOf,+ resolveScmCloneCredential,+ resolveScmCloneCredentials,+} from '../cloneCredential';const mintGitHubRepositoryToken = vi.hoisted(() => vi.fn());@@ -165,3 +169,40 @@ describe('resolveScmCloneCredential', () => {).resolves.toBeNull();});});++describe('resolveScmCloneCredentials', () => {+ const resolveAll = (urls: string[]) =>+ resolveScmCloneCredentials({+ configuration: { sources: urls.map((url) => ({ kind: 'git', url })) },+ db: serverDB,+ userId,+ });++ it('keeps the single host-wide credential for one repository', async () => {+ await install({ accountLogin: 'acme', installationId: '200', repositorySelection: 'all' });++ expect(await resolveAll(['https://github.com/acme/app'])).toEqual([+ expect.objectContaining({ urlPrefix: 'https://github.com/' }),+ ]);+ });++ it('scopes one credential to each repository when there are several', async () => {+ await install({ accountLogin: 'acme', installationId: '201', repositorySelection: 'all' });++ const credentials = await resolveAll([+ 'https://github.com/acme/app',+ 'https://github.com/acme/docs.git',+ 'https://github.com/stranger/public',+ ]);++ // The third has no installation: it clones only if it is public.+ expect(credentials.map((credential) => credential.urlPrefix)).toEqual([+ 'https://github.com/acme/app',+ 'https://github.com/acme/docs.git',+ ]);+ expect(mintGitHubRepositoryToken).toHaveBeenCalledWith({+ installationId: '201',+ repoFullName: 'acme/docs',+ });+ });+});diff --git a/apps/server/src/services/scm/cloneCredential.ts b/apps/server/src/services/scm/cloneCredential.tsindex 3f675f6d953..3cb714bd9f8 100644--- a/apps/server/src/services/scm/cloneCredential.ts+++ b/apps/server/src/services/scm/cloneCredential.ts@@ -1,4 +1,5 @@import debug from 'debug';+import pMap from 'p-map';import { ScmInstallationModel } from '@/database/models/scm';import type { ScmInstallationItem } from '@/database/schemas';@@ -8,6 +9,9 @@ import { mintGitHubRepositoryToken } from './github/app';const log = debug('lobe-server:scm:clone-credential');+/** Token mints in flight at once for one specification. */+const CLONE_CREDENTIAL_CONCURRENCY = 3;+/** The only checkout host the sandbox build knows how to authenticate. */export const GITHUB_HTTPS_PREFIX = 'https://github.com/';@@ -130,3 +134,57 @@ export const resolveScmCloneCredential = async (params: {return null;}};++/** Every GitHub repository a specification checks out, as `{ owner/name, url }`, in order. */+export const githubRepositoriesOf = (+ configuration: SourcedConfiguration | undefined,+): { repository: string; url: string }[] => {+ const seen = new Set<string>();+ return (configuration?.sources ?? []).flatMap((source) => {+ if (source.kind !== 'git' || !source.url) return [];+ const repository = githubRepositoryOf({ sources: [source] });+ if (!repository || seen.has(repository.toLowerCase())) return [];+ seen.add(repository.toLowerCase());+ return [{ repository, url: source.url.replace(/\/$/, '') }];+ });+};++/**+ * One clone credential per GitHub repository the specification checks out.+ *+ * A single repository keeps the host-wide header {@link resolveScmCloneCredential}+ * has always produced. Several are each scoped to their own url: a minted+ * token reads only the repository it was minted for, and git picks the most+ * specific `http.<url>.extraHeader` — a path matches at a `/` boundary, so+ * `…/owner/repo` covers `…/owner/repo/info/refs` and nothing of `…/owner/repo2`.+ *+ * Never throws; a repository without a credential still clones when public.+ */+export const resolveScmCloneCredentials = async (params: {+ configuration: SourcedConfiguration | undefined;+ db: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+}): Promise<ScmCloneCredential[]> => {+ const repositories = githubRepositoriesOf(params.configuration);+ if (repositories.length <= 1) {+ const single = await resolveScmCloneCredential(params);+ return single ? [single] : [];+ }++ // Each one reads the installations and mints a token, so a specification+ // with many repositories is resolved a few at a time.+ const credentials = await pMap(+ repositories,+ async ({ url }) => {+ const credential = await resolveScmCloneCredential({+ ...params,+ configuration: { sources: [{ kind: 'git', url }] },+ });+ return credential ? { ...credential, urlPrefix: url } : undefined;+ },+ { concurrency: CLONE_CREDENTIAL_CONCURRENCY },+ );++ return credentials.filter((credential): credential is ScmCloneCredential => !!credential);+};diff --git a/docs/development/api/streaming.zh-CN.mdx b/docs/development/api/streaming.zh-CN.mdxindex 2948901ab0d..79331916a1b 100644--- a/docs/development/api/streaming.zh-CN.mdx+++ b/docs/development/api/streaming.zh-CN.mdx@@ -73,7 +73,7 @@ data: {"type":"response.completed","sequence_number":31,"response":{"id":"resp_| `response.function_call_arguments.delta` / `.done` | `delta` / `arguments`、`item_id`、`output_index` || `response.reasoning_summary_text.delta` / `.done` | `delta` / `text`、`item_id`、`output_index` |-流在 `response.completed`、`response.failed` 或 `response.incomplete` 之后结束。`/responses` 流没有事件 id,无法恢复;已结束的响应也没有读取端点——用 `previous_response_id` 重新发起请求**会开启新的一轮 Agent 运行**(topic 相同),重复工具副作用而不是重放中断掉的输出。连接中断时,运行仍会在服务端跑完,回复写进该 Agent 的 topic,可在应用内查看。可重放的流随 `/runs`([#23253](https://github.com/lobehub/lobehub/pull/23253))提供:`GET /runs/{id}/events` 返回已存储的事件,每条带 `id`,可据此续读。+流在 `response.completed`、`response.failed` 或 `response.incomplete` 之后结束。`/responses` 流没有事件 id,无法恢复;已结束的响应也没有读取端点 —— 用 `previous_response_id` 重新发起请求**会开启新的一轮 Agent 运行**(topic 相同),重复工具副作用而不是重放中断掉的输出。连接中断时,运行仍会在服务端跑完,回复写进该 Agent 的 topic,可在应用内查看。可重放的流随 `/runs`([#23253](https://github.com/lobehub/lobehub/pull/23253))提供:`GET /runs/{id}/events` 返回已存储的事件,每条带 `id`,可据此续读。当模型调用你的某个函数工具时,响应以一个 `function_call` 输出项结束。请自行执行该工具,然后携带 `previous_response_id` 和一个使用相同 `call_id` 的 `function_call_output` 项发送新请求。diff --git a/locales/ar/chat.json b/locales/ar/chat.jsonindex 8a56d0d77db..9a5fc11f31d 100644--- a/locales/ar/chat.json+++ b/locales/ar/chat.json@@ -2122,20 +2122,15 @@"sandboxDrive.folderDesc": "مجلد على محرك الأقراص الخاص بك · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "البيئات",- "sandboxDrive.pickerInfoTooltip": "اختر مجلدًا على محرك الأقراص الخاص بك ويتم الاحتفاظ بملفاته عبر المحادثات. بدون واحد، يكون الصندوق مؤقتًا.","sandboxDrive.pickerTitle": "دليل العمل","sandboxDrive.root": "جذر محرك الأقراص","sandboxDrive.upsell": "احتفظ بالملفات على محرك الأقراص",- "sandboxEnvironment.empty": "لا توجد بيئات حتى الآن. قم بإنشاء واحدة في البيئات.",- "sandboxEnvironment.hint": "يتم النسخ والإعداد مرة واحدة في دليل العمل قبل الأمر الأول. يتم ترك المجلد الذي يحتوي بالفعل على ملفات كما هو.","sandboxEnvironment.loadFailed": "تعذر تحميل البيئات","sandboxEnvironment.loading": "جارٍ تحميل البيئة…","sandboxEnvironment.missing": "البيئة غير متاحة",- "sandboxEnvironment.none": "لا توجد بيئة","sandboxEnvironment.noneDesc": "ابدأ من دليل عمل فارغ","sandboxEnvironment.retry": "إعادة المحاولة","sandboxEnvironment.saveFailed": "تعذر تغيير البيئة. حاول مرة أخرى.",- "sandboxEnvironment.title": "البيئة","sandboxStorage.allCopiesBusy": "كل النسخ قيد الاستخدام","sandboxStorage.buildFailed": "لم يتم البناء","sandboxStorage.building": "جاري البناء",diff --git a/locales/ar/project.json b/locales/ar/project.jsonindex 7645f58d3ce..76d86df1acb 100644--- a/locales/ar/project.json+++ b/locales/ar/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "الجهاز متصل","settings.directoryDescription": "اختر مجلدًا وابدأ موضوعًا. سيعمل الوكيل مع الملفات في هذا المجلد على الجهاز المتصل.","settings.directoryUnavailable": "الجهاز غير متصل أو الدليل غير متاح. قم بتوصيل الجهاز وتحقق من المسار، ثم حاول مرة أخرى.",- "settings.environmentDescription": "احتفظ بمصادر المستودع معًا في بيئة، ثم أضف مجلدًا على جهازك لبدء العمل.",- "settings.environments": "البيئات","settings.general": "عام","settings.generalDescription": "إدارة اسم المشروع وعنوانه ووصفه.","settings.identifier": "معرف المشروع",@@ -334,7 +332,6 @@"settings.members": "الأعضاء","settings.nameHint": "استخدم 255 حرفًا كحد أقصى.","settings.noDirectories": "لا توجد مجلدات في هذه البيئة حتى الآن. أضف مجلدًا موجودًا على جهاز متصل لبدء العمل.",- "settings.noEnvironments": "لا توجد بيئات مرتبطة حتى الآن","settings.noRepository": "لا يوجد مستودع GitHub مرتبط","settings.reuseEnvironment": "إضافة بيئة موجودة إلى هذا المشروع","settings.reuseEnvironmentDescription": "هل أنشأت بيئة بالفعل؟ اخترها لربط تكوين المستودع الخاص بها بهذا المشروع، ثم أضف دليل عمل لهذا المشروع.",diff --git a/locales/ar/setting.json b/locales/ar/setting.jsonindex ee8ba4633fd..2bcf5b72e9f 100644--- a/locales/ar/setting.json+++ b/locales/ar/setting.json@@ -691,12 +691,8 @@"environments.create": "بيئة جديدة","environments.createFailed": "تعذر إنشاء البيئة","environments.desc": "ما يحتاجه تشغيل صندوق الرمل حوله: مستودع، إعداده، متغيراته. كل نسخة يتم إنشاؤها من واحدة تحتفظ بملفاتها الخاصة بين الجلسات.",- "environments.detail.close": "إغلاق",- "environments.detail.initializerDesc": "يتم تطبيقه مرة واحدة على دليل العمل الذي تم اختياره للمحادثة: يتم استنساخ المستودع هناك وتشغيل أمر الإعداد.","environments.detail.noRepository": "لا يوجد مستودع","environments.detail.noSetup": "لا يوجد أمر إعداد",- "environments.detail.tabs.overview": "نظرة عامة",- "environments.detail.tabs.settings": "الإعدادات","environments.duplicateName": "لديك بالفعل بيئة بهذا الاسم","environments.empty": "لا توجد بيئات حتى الآن","environments.emptyPublished": "لا يوجد شيء منشور في مساحة العمل هذه حتى الآن",diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.jsonindex 9c7bbff04a9..a26c0248704 100644--- a/locales/bg-BG/chat.json+++ b/locales/bg-BG/chat.json@@ -2124,20 +2124,15 @@"sandboxDrive.folderDesc": "Папка на вашия диск · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "Среда",- "sandboxDrive.pickerInfoTooltip": "Изберете папка на вашия диск и файловете в нея ще се запазват между разговорите. Без такава, пясъчникът е временен.","sandboxDrive.pickerTitle": "Работна директория","sandboxDrive.root": "Корен на диска","sandboxDrive.upsell": "Запазете файлове на диск",- "sandboxEnvironment.empty": "Все още няма среди. Създайте една в Среда.",- "sandboxEnvironment.hint": "Клонира се и се настройва веднъж в работната директория преди първата команда. Папка, която вече има файлове, се оставя такава, каквато е.","sandboxEnvironment.loadFailed": "Не можа да се заредят среди","sandboxEnvironment.loading": "Зареждане на среда…","sandboxEnvironment.missing": "Средата е недостъпна",- "sandboxEnvironment.none": "Няма среда","sandboxEnvironment.noneDesc": "Започнете от празна работна директория","sandboxEnvironment.retry": "Опитайте отново","sandboxEnvironment.saveFailed": "Не можа да се промени средата. Опитайте отново.",- "sandboxEnvironment.title": "Среда","sandboxStorage.allCopiesBusy": "Всички копия са в употреба","sandboxStorage.buildFailed": "Не е изградено","sandboxStorage.building": "Изграждане",diff --git a/locales/bg-BG/project.json b/locales/bg-BG/project.jsonindex 531391e30cf..c5aa9e3d9dd 100644--- a/locales/bg-BG/project.json+++ b/locales/bg-BG/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "Устройството е свързано","settings.directoryDescription": "Изберете папка и започнете тема. Агента ще работи с файловете в тази папка на свързаното устройство.","settings.directoryUnavailable": "Устройството е изключено или директорията не е налична. Свържете устройството и проверете пътя, след това опитайте отново.",- "settings.environmentDescription": "Съхранявайте източниците на хранилището заедно в една среда, след това добавете папка на вашето устройство, за да започнете работа.",- "settings.environments": "Среда","settings.general": "Общи","settings.generalDescription": "Управлявайте името на проекта, адреса и описанието.","settings.identifier": "Идентификатор на проекта",@@ -334,7 +332,6 @@"settings.members": "Членове","settings.nameHint": "Използвайте най-много 255 символа.","settings.noDirectories": "Все още няма папки в тази среда. Добавете съществуваща папка на свързано устройство, за да започнете работа.",- "settings.noEnvironments": "Все още няма свързани среди","settings.noRepository": "Няма свързано GitHub хранилище","settings.reuseEnvironment": "Добавяне на съществуваща среда към този проект","settings.reuseEnvironmentDescription": "Вече сте създали среда? Изберете я, за да свържете конфигурацията на хранилището към този проект, след това добавете работна директория за този проект.",diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.jsonindex aa0013ffcda..b9e9508c17e 100644--- a/locales/bg-BG/setting.json+++ b/locales/bg-BG/setting.json@@ -691,12 +691,8 @@"environments.create": "Нова среда","environments.createFailed": "Не може да се създаде средата","environments.desc": "Какво е необходимо за изпълнение на пясъчник: хранилище, неговата настройка, неговите променливи. Всяко копие, създадено от едно, запазва собствените си файлове между сесиите.",- "environments.detail.close": "Затвори",- "environments.detail.initializerDesc": "Прилага се веднъж към работна директория, избрана за разговор: хранилището се клонира там и командата за настройка се изпълнява.","environments.detail.noRepository": "Няма хранилище","environments.detail.noSetup": "Няма команда за настройка",- "environments.detail.tabs.overview": "Преглед",- "environments.detail.tabs.settings": "Настройки","environments.duplicateName": "Вече имате среда с това име","environments.empty": "Все още няма среди","environments.emptyPublished": "Нищо не е публикувано в този работен простор",diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.jsonindex a478e745822..82cbc5218c5 100644--- a/locales/de-DE/chat.json+++ b/locales/de-DE/chat.json@@ -2122,20 +2122,15 @@"sandboxDrive.folderDesc": "Ordner auf Ihrem Laufwerk · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "Umgebungen",- "sandboxDrive.pickerInfoTooltip": "Wählen Sie einen Ordner auf Ihrem Laufwerk, und dessen Dateien werden über Gespräche hinweg beibehalten. Ohne einen ist der Sandbox temporär.","sandboxDrive.pickerTitle": "Arbeitsverzeichnis","sandboxDrive.root": "Laufwerksstamm","sandboxDrive.upsell": "Dateien auf einem Laufwerk speichern",- "sandboxEnvironment.empty": "Noch keine Umgebungen. Erstellen Sie eine in Umgebungen.",- "sandboxEnvironment.hint": "Einmal im Arbeitsverzeichnis geklont und eingerichtet, bevor der erste Befehl ausgeführt wird. Ein Ordner, der bereits Dateien enthält, bleibt unverändert.","sandboxEnvironment.loadFailed": "Konnte Umgebungen nicht laden","sandboxEnvironment.loading": "Umgebung wird geladen…","sandboxEnvironment.missing": "Umgebung nicht verfügbar",- "sandboxEnvironment.none": "Keine Umgebung","sandboxEnvironment.noneDesc": "Beginnen Sie mit einem leeren Arbeitsverzeichnis","sandboxEnvironment.retry": "Erneut versuchen","sandboxEnvironment.saveFailed": "Die Umgebung konnte nicht geändert werden. Versuchen Sie es erneut.",- "sandboxEnvironment.title": "Umgebung","sandboxStorage.allCopiesBusy": "Jede Kopie ist in Gebrauch","sandboxStorage.buildFailed": "Nicht gebaut","sandboxStorage.building": "Wird gebaut",diff --git a/locales/de-DE/project.json b/locales/de-DE/project.jsonindex 0405696aea7..dd8170db6ae 100644--- a/locales/de-DE/project.json+++ b/locales/de-DE/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "Gerät verbunden","settings.directoryDescription": "Wählen Sie einen Ordner aus und beginnen Sie ein Thema. Der Agent arbeitet mit Dateien in diesem Ordner auf dem verbundenen Gerät.","settings.directoryUnavailable": "Das Gerät ist getrennt oder das Verzeichnis ist nicht verfügbar. Gerät verbinden und Pfad überprüfen, dann erneut versuchen.",- "settings.environmentDescription": "Halten Sie Repository-Quellen in einer Umgebung zusammen und fügen Sie dann einen Ordner auf Ihrem Gerät hinzu, um mit der Arbeit zu beginnen.",- "settings.environments": "Umgebungen","settings.general": "Allgemein","settings.generalDescription": "Verwalten Sie den Projektnamen, die Adresse und die Beschreibung.","settings.identifier": "Projektkennung",@@ -334,7 +332,6 @@"settings.members": "Mitglieder","settings.nameHint": "Verwenden Sie maximal 255 Zeichen.","settings.noDirectories": "Noch keine Ordner in dieser Umgebung. Fügen Sie einen vorhandenen Ordner auf einem verbundenen Gerät hinzu, um mit der Arbeit zu beginnen.",- "settings.noEnvironments": "Noch keine Umgebungen verknüpft","settings.noRepository": "Kein GitHub-Repository verknüpft","settings.reuseEnvironment": "Vorhandene Umgebung zu diesem Projekt hinzufügen","settings.reuseEnvironmentDescription": "Haben Sie bereits eine Umgebung erstellt? Wählen Sie sie aus, um ihre Repository-Konfiguration mit diesem Projekt zu verknüpfen, und fügen Sie dann ein Arbeitsverzeichnis für dieses Projekt hinzu.",diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.jsonindex d1fc65be3a3..d8b71803620 100644--- a/locales/de-DE/setting.json+++ b/locales/de-DE/setting.json@@ -691,12 +691,8 @@"environments.create": "Neue Umgebung","environments.createFailed": "Die Umgebung konnte nicht erstellt werden","environments.desc": "Was ein Sandbox-Lauf benötigt: ein Repository, dessen Einrichtung, dessen Variablen. Jede Kopie, die daraus erstellt wird, behält ihre eigenen Dateien zwischen den Sitzungen.",- "environments.detail.close": "Schließen",- "environments.detail.initializerDesc": "Einmal auf ein Arbeitsverzeichnis angewendet, das für ein Gespräch ausgewählt wurde: Das Repository wird dort geklont und der Einrichtungsbefehl ausgeführt.","environments.detail.noRepository": "Kein Repository","environments.detail.noSetup": "Kein Einrichtungsbefehl",- "environments.detail.tabs.overview": "Übersicht",- "environments.detail.tabs.settings": "Einstellungen","environments.duplicateName": "Sie haben bereits eine Umgebung mit diesem Namen","environments.empty": "Noch keine Umgebungen","environments.emptyPublished": "Noch nichts in diesem Arbeitsbereich veröffentlicht",diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 42174bc95bc..95724248e49 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2193,20 +2193,21 @@"sandboxDrive.fallbackChip.rootNotAllowed": "Pick a folder","sandboxDrive.manageEnvironments": "Settings","sandboxDrive.openStorage": "Sandbox Storage",- "sandboxDrive.pickerInfoTooltip": "A temporary directory is cleaned up with the sandbox. A folder on your cloud drive is kept across conversations. A repository is cloned before the first command.",+ "sandboxDrive.pickerInfoTooltip": "A temporary directory is cleaned up with the sandbox. A folder on your cloud drive is kept across conversations. An environment is set up before the first command.","sandboxDrive.pickerTitle": "Work location","sandboxDrive.root": "Root","sandboxDrive.title": "Cloud drive",- "sandboxEnvironment.add": "Add repository",- "sandboxEnvironment.empty": "No repositories yet. Add one to get started.",- "sandboxEnvironment.hint": "Cloned and set up once before the first command.",+ "sandboxEnvironment.add": "New environment",+ "sandboxEnvironment.empty": "No environments yet. Create one to get started.",+ "sandboxEnvironment.hint": "Its repositories are cloned, setup runs and its variables are set before the first command.","sandboxEnvironment.loadFailed": "Couldn't load environments","sandboxEnvironment.loading": "Loading environment…","sandboxEnvironment.missing": "Environment unavailable",- "sandboxEnvironment.none": "No repository",+ "sandboxEnvironment.noRepository": "No repository",+ "sandboxEnvironment.none": "No environment","sandboxEnvironment.retry": "Retry","sandboxEnvironment.saveFailed": "Could not change the environment. Try again.",- "sandboxEnvironment.title": "Repository",+ "sandboxEnvironment.title": "Environment","sandboxStorage.allCopiesBusy": "Every copy is in use","sandboxStorage.buildFailed": "Not built","sandboxStorage.building": "Building",diff --git a/locales/en-US/project.json b/locales/en-US/project.jsonindex 8d2792ad728..e02581763b5 100644--- a/locales/en-US/project.json+++ b/locales/en-US/project.json@@ -59,16 +59,25 @@"create.slugPlaceholder": "my-project","create.slugTaken": "Another project in this workspace already uses this link name.","create.title": "New project",+ "createFromGithub.addRepository": "Add",+ "createFromGithub.advanced": "Advanced settings",+ "createFromGithub.advancedWithCount": "Advanced settings · {{count}} extra",+ "createFromGithub.alreadyAdded": "This repository is already added.",+ "createFromGithub.chooseFromGithub": "Choose from GitHub","createFromGithub.connect": "Connect GitHub","createFromGithub.disconnected": "Connect GitHub to choose from your repositories, or paste a public repository URL below.","createFromGithub.duplicateIdentifier": "Another project already uses this identifier. Choose a different one.","createFromGithub.duplicateName": "A project with this name already exists, including in the trash. Choose a different name.","createFromGithub.empty": "The connected GitHub accounts haven't given LobeHub access to any repositories yet.",- "createFromGithub.environmentHint": "The repository becomes this project's environment, so agents can check it out when they work on the project.",+ "createFromGithub.extraRepositoriesLabel": "More repositories",+ "createFromGithub.layoutHint": "Each repository is checked out in a folder of its own, side by side. You can change them later in the project's settings.","createFromGithub.loadFailed": "Couldn't load repositories from GitHub.","createFromGithub.manageAccess": "Manage access",+ "createFromGithub.openIntegrations": "Open GitHub settings","createFromGithub.private": "Private",+ "createFromGithub.removeRepository": "Remove","createFromGithub.repositoriesLabel": "Your repositories",+ "createFromGithub.repositoryTitle": "Repository","createFromGithub.searchEmpty": "No matching repositories","createFromGithub.searchPlaceholder": "Search repositories…","createFromGithub.title": "New project from GitHub",@@ -128,21 +137,8 @@"directories.untitled": "Untitled topic","disabled.action": "Enable in Labs","disabled.title": "Project workspaces are an Alpha experiment",- "environment.add.action": "Add",- "environment.add.existing": "Add an existing one",- "environment.add.failed": "Couldn't add the environment to this project",- "environment.add.github": "New from GitHub",- "environment.add.noExisting": "All of your environments are already in this project.",- "environment.add.noPublished": "No published environments to add. A shared project only uses published environments.",- "environment.add.title": "Add environment",- "environment.create": "New environment",- "environment.link": "Link environment",- "environment.privateInShared": "Private",- "environment.privateInSharedTooltip": "This project is shared, so its conversations only use published environments. This private environment won't be checked out.",- "environment.unlink": "Unlink from project",- "environment.unlinkConfirm.desc": "The environment stays in Settings → Environments. This project's folders that use it are kept, but can't run conversations until it is linked again.",- "environment.unlinkConfirm.title": "Unlink \"{{name}}\" from this project?",- "environment.unlinkFailed": "Couldn't unlink the environment from this project",+ "environment.configure": "Configure environment",+ "environment.none": "No environment — start in an empty folder","goals.create": "Create goal","goals.description": "Define the outcomes this project is pursuing and track them to acceptance.","goals.emptyDescription": "Create the first measurable outcome for this project.",@@ -384,8 +380,8 @@"settings.editDirectoryDescription": "Choose the device and folder this working directory points to. Its topics move to the new folder and start new sessions there.","settings.editDirectoryFailed": "Could not update the folder","settings.editDirectoryOtherEnvironment": "This folder already belongs to another environment. Choose a different folder or device.",- "settings.environmentDescription": "Link environments configured in Settings → Environments, then add a folder on your device to start working.",- "settings.environments": "Environments",+ "settings.environmentIntro": "Every conversation in this project runs in this environment: its repositories are cloned, the setup command runs, and its variables are set.",+ "settings.environments": "Environment","settings.general": "General","settings.generalDescription": "Manage the project name, address, and description.","settings.identifier": "Project identifier",@@ -400,7 +396,6 @@"settings.members": "Members","settings.nameHint": "Use 255 characters at most.","settings.noDirectories": "No folders in this environment yet. Add an existing folder on a connected device to start working.",- "settings.noEnvironments": "No environments associated yet","settings.noRepository": "No GitHub repository linked","settings.removeDirectory": "Remove folder","settings.removeDirectoryConfirmDescription": "{{path}} on {{device}} will no longer be a working directory of this project. Files on the device are not changed. Its topics stay in the project but are no longer linked to this folder.",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 12ec4f077cb..48d100f29b3 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -855,12 +855,10 @@"environments.create": "New environment","environments.createFailed": "Could not create the environment","environments.desc": "How to set up a project: the repository to check out, the setup command, the variables. Pick one from the environment menu under the chat input, and the conversation's working directory — a temporary sandbox or a folder on your drive — is initialized from it once.",- "environments.detail.close": "Close",- "environments.detail.initializerDesc": "Applied once to a working directory picked for a conversation: the repository is cloned there and the setup command runs.",+ "environments.detail.back": "Environments","environments.detail.noRepository": "No repository","environments.detail.noSetup": "No setup command",- "environments.detail.tabs.overview": "Overview",- "environments.detail.tabs.settings": "Settings",+ "environments.detail.notFound": "This environment doesn't exist or you can't see it.","environments.duplicateName": "You already have an environment with this name","environments.empty": "No environments yet","environments.emptyPublished": "Nothing published to this workspace yet",@@ -881,18 +879,24 @@"environments.files.unusedInstance": "Nothing here yet. The code appears once the copy is built or a conversation runs in it.","environments.files.up": "Up one level","environments.form.addEnv": "New variable",+ "environments.form.addPastedRepository": "Add",+ "environments.form.addRepository": "Add repository","environments.form.addSource": "Add repository","environments.form.appliesOnBuild": "Applied when a copy is created. Existing copies keep the definition they were made with — a rebuild replays that one, so use a new copy to pick this up.","environments.form.appliesOnInit": "Takes effect the next time the environment is applied to a working directory. Folders it was already applied to keep what they have.","environments.form.basics": "Basics","environments.form.bootstrap": "Setup command",+ "environments.form.bootstrapAfterRepositories": "Runs at the top of the working directory, after each repository's own setup. Setup for a single repository goes on that repository.","environments.form.bootstrapHint": "Runs once in the checkout, with network access, before the conversation starts.","environments.form.changeRepository": "Change repository","environments.form.desc": "Where the code comes from and what makes it usable.","environments.form.description": "Description","environments.form.descriptionPlaceholder": "What this environment is for","environments.form.disconnect": "Disconnect",+ "environments.form.doneEditing": "Done",+ "environments.form.duplicateFolder": "Another repository already uses this folder.","environments.form.editEnv": "Edit variable",+ "environments.form.editRepositorySettings": "Edit branch, folder and setup","environments.form.env": "Environment variables","environments.form.envCount_one": "{{count}} variable","environments.form.envCount_other": "{{count}} variables",@@ -906,8 +910,12 @@"environments.form.internetAccessHint": "Setup always has network access. This controls the conversation itself.","environments.form.jsonSyntax": "Invalid JSON. Check double quotes, commas and braces, then save again.","environments.form.jsonValues": "Use a JSON object with a string value for every variable, such as {\"NODE_ENV\":\"production\"}.",+ "environments.form.layoutHint": "Each repository is checked out in a folder of its own, side by side. You can change them later in the environment's settings.","environments.form.maintenance": "Maintenance command","environments.form.maintenanceHint": "Runs each time work resumes in a copy — refreshing a checkout, reapplying a migration. Not the setup command again: that one is expensive and is meant to run once.",+ "environments.form.noRepositories": "No repositories. Conversations start in an empty folder.",+ "environments.form.noVariables": "No variables",+ "environments.form.pasteRepository": "Or paste a public repository URL","environments.form.path": "Folder","environments.form.rawEditor": "Raw editor","environments.form.rawEditorHint": "One KEY=value per line, the way a .env file reads. Blank lines and # comments are ignored; saving replaces every variable.",@@ -918,6 +926,9 @@"environments.form.refDefault": "Repository default branch","environments.form.removeEnv": "Remove variable","environments.form.removeSource": "Remove repository",+ "environments.form.repositoryOptional": "Optional — an environment can start without a repository and get one later.",+ "environments.form.repositorySetupHint": "Runs inside this repository's folder after it's cloned, before the environment's setup command.",+ "environments.form.repositoryUrlInvalid": "Not a GitHub repository URL","environments.form.runtime": "Runtime and storage","environments.form.saved": "Saved","environments.form.setup": "Setup",@@ -928,6 +939,7 @@"environments.github.loadFailed": "Could not load GitHub repositories. Try again.","environments.github.noRepositories": "This connection cannot see any repositories yet","environments.github.notConnected": "No GitHub connection yet — connect one to build an environment from a repository",+ "environments.github.openIntegrations": "Open GitHub settings","environments.github.optional": "optional","environments.github.organization": "Organization","environments.github.organizationPlaceholder": "Search organizations",diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.jsonindex 327897e516f..408e6b7c0c0 100644--- a/locales/es-ES/chat.json+++ b/locales/es-ES/chat.json@@ -2122,20 +2122,15 @@"sandboxDrive.folderDesc": "Carpeta en tu unidad · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "Entornos",- "sandboxDrive.pickerInfoTooltip": "Elige una carpeta en tu unidad y sus archivos se mantienen entre conversaciones. Sin una, el entorno es temporal.","sandboxDrive.pickerTitle": "Directorio de trabajo","sandboxDrive.root": "Raíz de la unidad","sandboxDrive.upsell": "Mantén archivos en una unidad",- "sandboxEnvironment.empty": "Aún no hay entornos. Crea uno en Entornos.",- "sandboxEnvironment.hint": "Clonado y configurado una vez en el directorio de trabajo antes del primer comando. Una carpeta que ya tiene archivos se deja tal como está.","sandboxEnvironment.loadFailed": "No se pudieron cargar los entornos","sandboxEnvironment.loading": "Cargando entorno…","sandboxEnvironment.missing": "Entorno no disponible",- "sandboxEnvironment.none": "Sin entorno","sandboxEnvironment.noneDesc": "Comienza desde un directorio de trabajo vacío","sandboxEnvironment.retry": "Reintentar","sandboxEnvironment.saveFailed": "No se pudo cambiar el entorno. Inténtalo de nuevo.",- "sandboxEnvironment.title": "Entorno","sandboxStorage.allCopiesBusy": "Cada copia está en uso","sandboxStorage.buildFailed": "No construido","sandboxStorage.building": "Construyendo",diff --git a/locales/es-ES/project.json b/locales/es-ES/project.jsonindex 77d7b2bb89d..9a4be60bba0 100644--- a/locales/es-ES/project.json+++ b/locales/es-ES/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "Dispositivo conectado","settings.directoryDescription": "Elige una carpeta e inicia un tema. El Ajan trabajará con los archivos en esa carpeta en el dispositivo conectado.","settings.directoryUnavailable": "El dispositivo está desconectado o el directorio no está disponible. Conecta el dispositivo y verifica la ruta, luego inténtalo de nuevo.",- "settings.environmentDescription": "Mantén las fuentes del repositorio juntas en un entorno, luego agrega una carpeta en tu dispositivo para comenzar a trabajar.",- "settings.environments": "Entornos","settings.general": "General","settings.generalDescription": "Administra el nombre, dirección y descripción del proyecto.","settings.identifier": "Identificador del proyecto",@@ -334,7 +332,6 @@"settings.members": "Miembros","settings.nameHint": "Usa un máximo de 255 caracteres.","settings.noDirectories": "Aún no hay carpetas en este entorno. Agrega una carpeta existente en un dispositivo conectado para comenzar a trabajar.",- "settings.noEnvironments": "Aún no hay entornos asociados","settings.noRepository": "No hay repositorio de GitHub vinculado","settings.reuseEnvironment": "Agregar un entorno existente a este proyecto","settings.reuseEnvironmentDescription": "¿Ya creaste un entorno? Selecciónalo para vincular su configuración de repositorio a este proyecto, luego agrega un directorio de trabajo para este proyecto.",diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.jsonindex dd92a156e2c..03beff3ab56 100644--- a/locales/es-ES/setting.json+++ b/locales/es-ES/setting.json@@ -691,12 +691,8 @@"environments.create": "Nuevo entorno","environments.createFailed": "No se pudo crear el entorno","environments.desc": "Lo que necesita una ejecución de sandbox a su alrededor: un repositorio, su configuración, sus variables. Cada copia creada a partir de uno mantiene sus propios archivos entre sesiones.",- "environments.detail.close": "Cerrar",- "environments.detail.initializerDesc": "Se aplica una vez a un directorio de trabajo seleccionado para una conversación: el repositorio se clona allí y se ejecuta el comando de configuración.","environments.detail.noRepository": "Sin repositorio","environments.detail.noSetup": "Sin comando de configuración",- "environments.detail.tabs.overview": "Resumen",- "environments.detail.tabs.settings": "Configuración","environments.duplicateName": "Ya tienes un entorno con este nombre","environments.empty": "Aún no hay entornos","environments.emptyPublished": "Nada publicado en este espacio de trabajo aún",diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.jsonindex 50227d8ecc1..0ff066caf41 100644--- a/locales/fa-IR/chat.json+++ b/locales/fa-IR/chat.json@@ -2124,20 +2124,15 @@"sandboxDrive.folderDesc": "پوشه در درایو شما · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "محیطها",- "sandboxDrive.pickerInfoTooltip": "یک پوشه در درایو خود انتخاب کنید و فایلهای آن در مکالمات حفظ میشوند. بدون آن، محیط موقت است.","sandboxDrive.pickerTitle": "دایرکتوری کاری","sandboxDrive.root": "ریشه درایو","sandboxDrive.upsell": "فایلها را در یک درایو نگه دارید",- "sandboxEnvironment.empty": "هنوز محیطی وجود ندارد. یکی را در محیطها ایجاد کنید.",- "sandboxEnvironment.hint": "یک بار در دایرکتوری کاری قبل از اولین فرمان کلون و تنظیم میشود. یک پوشه که قبلاً فایل دارد به همان صورت باقی میماند.","sandboxEnvironment.loadFailed": "محیطها بارگذاری نشدند","sandboxEnvironment.loading": "در حال بارگذاری محیط…","sandboxEnvironment.missing": "محیط در دسترس نیست",- "sandboxEnvironment.none": "بدون محیط","sandboxEnvironment.noneDesc": "از یک دایرکتوری کاری خالی شروع کنید","sandboxEnvironment.retry": "تلاش مجدد","sandboxEnvironment.saveFailed": "تغییر محیط انجام نشد. دوباره تلاش کنید.",- "sandboxEnvironment.title": "محیط","sandboxStorage.allCopiesBusy": "همه نسخهها در حال استفاده هستند","sandboxStorage.buildFailed": "ساخته نشد","sandboxStorage.building": "در حال ساخت",diff --git a/locales/fa-IR/project.json b/locales/fa-IR/project.jsonindex 5d7c21f844a..37c8394212a 100644--- a/locales/fa-IR/project.json+++ b/locales/fa-IR/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "دستگاه متصل است","settings.directoryDescription": "یک پوشه انتخاب کنید و یک موضوع شروع کنید. آجان با فایلهای موجود در آن پوشه روی دستگاه متصل کار خواهد کرد.","settings.directoryUnavailable": "دستگاه قطع شده است یا دایرکتوری در دسترس نیست. دستگاه را متصل کنید و مسیر را بررسی کنید، سپس دوباره تلاش کنید.",- "settings.environmentDescription": "منابع مخزن را در یک محیط نگه دارید، سپس یک پوشه روی دستگاه خود اضافه کنید تا کار را شروع کنید.",- "settings.environments": "محیطها","settings.general": "عمومی","settings.generalDescription": "مدیریت نام پروژه، آدرس و توضیحات.","settings.identifier": "شناسه پروژه",@@ -334,7 +332,6 @@"settings.members": "اعضا","settings.nameHint": "حداکثر از ۲۵۵ کاراکتر استفاده کنید.","settings.noDirectories": "هنوز هیچ پوشهای در این محیط وجود ندارد. یک پوشه موجود روی یک دستگاه متصل اضافه کنید تا کار را شروع کنید.",- "settings.noEnvironments": "هنوز هیچ محیطی مرتبط نشده است","settings.noRepository": "هیچ مخزن GitHub لینک نشده است","settings.reuseEnvironment": "افزودن یک محیط موجود به این پروژه","settings.reuseEnvironmentDescription": "قبلاً یک محیط ایجاد کردهاید؟ آن را انتخاب کنید تا پیکربندی مخزن آن به این پروژه لینک شود، سپس یک دایرکتوری کاری برای این پروژه اضافه کنید.",diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.jsonindex 8764a19a761..b07f3ad595e 100644--- a/locales/fa-IR/setting.json+++ b/locales/fa-IR/setting.json@@ -691,12 +691,8 @@"environments.create": "محیط جدید","environments.createFailed": "امکان ایجاد محیط وجود ندارد","environments.desc": "آنچه یک اجرای سندباکس به آن نیاز دارد: یک مخزن، تنظیمات آن، متغیرهای آن. هر کپی ساخته شده از یکی، فایلهای خود را بین جلسات نگه میدارد.",- "environments.detail.close": "بستن",- "environments.detail.initializerDesc": "یک بار به یک دایرکتوری کاری انتخابشده برای یک گفتگو اعمال میشود: مخزن در آنجا کلون میشود و فرمان تنظیم اجرا میشود.","environments.detail.noRepository": "بدون مخزن","environments.detail.noSetup": "بدون فرمان تنظیم",- "environments.detail.tabs.overview": "نمای کلی",- "environments.detail.tabs.settings": "تنظیمات","environments.duplicateName": "شما قبلاً محیطی با این نام دارید","environments.empty": "هنوز هیچ محیطی وجود ندارد","environments.emptyPublished": "هنوز چیزی در این فضای کاری منتشر نشده است",diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.jsonindex b4d9ce587ff..c0c0c12c03c 100644--- a/locales/fr-FR/chat.json+++ b/locales/fr-FR/chat.json@@ -2124,20 +2124,15 @@"sandboxDrive.folderDesc": "Dossier sur votre disque · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "Environnements",- "sandboxDrive.pickerInfoTooltip": "Choisissez un dossier sur votre disque et ses fichiers seront conservés entre les conversations. Sans cela, le bac à sable est temporaire.","sandboxDrive.pickerTitle": "Répertoire de travail","sandboxDrive.root": "Racine du disque","sandboxDrive.upsell": "Conserver les fichiers sur un disque",- "sandboxEnvironment.empty": "Pas encore d'environnements. Créez-en un dans Environnements.",- "sandboxEnvironment.hint": "Cloné et configuré une fois dans le répertoire de travail avant la première commande. Un dossier qui contient déjà des fichiers est laissé tel quel.","sandboxEnvironment.loadFailed": "Impossible de charger les environnements","sandboxEnvironment.loading": "Chargement de l'environnement…","sandboxEnvironment.missing": "Environnement indisponible",- "sandboxEnvironment.none": "Aucun environnement","sandboxEnvironment.noneDesc": "Commencer à partir d'un répertoire de travail vide","sandboxEnvironment.retry": "Réessayer","sandboxEnvironment.saveFailed": "Impossible de modifier l'environnement. Veuillez réessayer.",- "sandboxEnvironment.title": "Environnement","sandboxStorage.allCopiesBusy": "Chaque copie est en cours d'utilisation","sandboxStorage.buildFailed": "Non construit","sandboxStorage.building": "Construction en cours",diff --git a/locales/fr-FR/project.json b/locales/fr-FR/project.jsonindex dc07a85171d..ab30befb112 100644--- a/locales/fr-FR/project.json+++ b/locales/fr-FR/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "Appareil connecté","settings.directoryDescription": "Choisissez un dossier et commencez un sujet. L'Ajan travaillera avec les fichiers de ce dossier sur l'appareil connecté.","settings.directoryUnavailable": "L'appareil est déconnecté ou le répertoire est indisponible. Connectez l'appareil et vérifiez le chemin, puis réessayez.",- "settings.environmentDescription": "Regroupez les sources de dépôt dans un environnement, puis ajoutez un dossier sur votre appareil pour commencer à travailler.",- "settings.environments": "Environnements","settings.general": "Général","settings.generalDescription": "Gérez le nom, l'adresse et la description du projet.","settings.identifier": "Identifiant du projet",@@ -334,7 +332,6 @@"settings.members": "Membres","settings.nameHint": "Utilisez au maximum 255 caractères.","settings.noDirectories": "Aucun dossier dans cet environnement pour le moment. Ajoutez un dossier existant sur un appareil connecté pour commencer à travailler.",- "settings.noEnvironments": "Aucun environnement associé pour le moment","settings.noRepository": "Aucun dépôt GitHub lié","settings.reuseEnvironment": "Ajouter un environnement existant à ce projet","settings.reuseEnvironmentDescription": "Vous avez déjà créé un environnement ? Sélectionnez-le pour lier sa configuration de dépôt à ce projet, puis ajoutez un répertoire de travail pour ce projet.",diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.jsonindex 3f9a6ad6575..f5cc62b2bca 100644--- a/locales/fr-FR/setting.json+++ b/locales/fr-FR/setting.json@@ -691,12 +691,8 @@"environments.create": "Nouvel environnement","environments.createFailed": "Impossible de créer l'environnement","environments.desc": "Ce dont une exécution en bac à sable a besoin autour d'elle : un dépôt, sa configuration, ses variables. Chaque copie créée à partir d'un modèle conserve ses propres fichiers entre les sessions.",- "environments.detail.close": "Fermer",- "environments.detail.initializerDesc": "Appliqué une fois à un répertoire de travail choisi pour une conversation : le dépôt est cloné là et la commande de configuration s'exécute.","environments.detail.noRepository": "Aucun dépôt","environments.detail.noSetup": "Aucune commande de configuration",- "environments.detail.tabs.overview": "Aperçu",- "environments.detail.tabs.settings": "Paramètres","environments.duplicateName": "Vous avez déjà un environnement avec ce nom","environments.empty": "Aucun environnement pour le moment","environments.emptyPublished": "Rien n'a encore été publié dans cet espace de travail",diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.jsonindex 3d2fe1d61f8..d68877f5282 100644--- a/locales/it-IT/chat.json+++ b/locales/it-IT/chat.json@@ -2124,20 +2124,15 @@"sandboxDrive.folderDesc": "Cartella sul tuo drive · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "Ambienti",- "sandboxDrive.pickerInfoTooltip": "Scegli una cartella sul tuo drive e i suoi file saranno mantenuti tra le conversazioni. Senza una, il sandbox è temporaneo.","sandboxDrive.pickerTitle": "Directory di lavoro","sandboxDrive.root": "Radice del drive","sandboxDrive.upsell": "Mantieni i file su un drive",- "sandboxEnvironment.empty": "Nessun ambiente ancora. Creane uno in Ambienti.",- "sandboxEnvironment.hint": "Clonato e configurato una volta nella directory di lavoro prima del primo comando. Una cartella che ha già file viene lasciata così com'è.","sandboxEnvironment.loadFailed": "Impossibile caricare gli ambienti","sandboxEnvironment.loading": "Caricamento dell'ambiente…","sandboxEnvironment.missing": "Ambiente non disponibile",- "sandboxEnvironment.none": "Nessun ambiente","sandboxEnvironment.noneDesc": "Inizia da una directory di lavoro vuota","sandboxEnvironment.retry": "Riprova","sandboxEnvironment.saveFailed": "Impossibile modificare l'ambiente. Riprova.",- "sandboxEnvironment.title": "Ambiente","sandboxStorage.allCopiesBusy": "Ogni copia è in uso","sandboxStorage.buildFailed": "Non costruito","sandboxStorage.building": "Costruzione in corso",diff --git a/locales/it-IT/project.json b/locales/it-IT/project.jsonindex 8362bda9226..659581c7a1e 100644--- a/locales/it-IT/project.json+++ b/locales/it-IT/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "Dispositivo connesso","settings.directoryDescription": "Scegli una cartella e inizia un argomento. L'Ajan lavorerà con i file in quella cartella sul dispositivo connesso.","settings.directoryUnavailable": "Il dispositivo è disconnesso o la directory non è disponibile. Connetti il dispositivo e controlla il percorso, quindi riprova.",- "settings.environmentDescription": "Mantieni le sorgenti del repository insieme in un ambiente, quindi aggiungi una cartella sul tuo dispositivo per iniziare a lavorare.",- "settings.environments": "Ambienti","settings.general": "Generale","settings.generalDescription": "Gestisci il nome, l'indirizzo e la descrizione del progetto.","settings.identifier": "Identificatore del progetto",@@ -334,7 +332,6 @@"settings.members": "Membri","settings.nameHint": "Usa al massimo 255 caratteri.","settings.noDirectories": "Nessuna cartella in questo ambiente al momento. Aggiungi una cartella esistente su un dispositivo connesso per iniziare a lavorare.",- "settings.noEnvironments": "Nessun ambiente associato al momento","settings.noRepository": "Nessun repository GitHub collegato","settings.reuseEnvironment": "Aggiungi un ambiente esistente a questo progetto","settings.reuseEnvironmentDescription": "Hai già creato un ambiente? Selezionalo per collegare la sua configurazione del repository a questo progetto, quindi aggiungi una directory di lavoro per questo progetto.",diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.jsonindex 1b84eb71d99..d78ba544b2d 100644--- a/locales/it-IT/setting.json+++ b/locales/it-IT/setting.json@@ -691,12 +691,8 @@"environments.create": "Nuovo ambiente","environments.createFailed": "Impossibile creare l'ambiente","environments.desc": "Cosa serve a un'esecuzione sandbox: un repository, la sua configurazione, le sue variabili. Ogni copia creata da uno mantiene i propri file tra le sessioni.",- "environments.detail.close": "Chiudi",- "environments.detail.initializerDesc": "Applicato una volta a una directory di lavoro scelta per una conversazione: il repository viene clonato lì e il comando di configurazione viene eseguito.","environments.detail.noRepository": "Nessun repository","environments.detail.noSetup": "Nessun comando di configurazione",- "environments.detail.tabs.overview": "Panoramica",- "environments.detail.tabs.settings": "Impostazioni","environments.duplicateName": "Hai già un ambiente con questo nome","environments.empty": "Nessun ambiente ancora","environments.emptyPublished": "Niente pubblicato in questo spazio di lavoro ancora",diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.jsonindex 2cc7da31b4c..30d60e4f5ed 100644--- a/locales/ja-JP/chat.json+++ b/locales/ja-JP/chat.json@@ -2124,20 +2124,15 @@"sandboxDrive.folderDesc": "ドライブ上のフォルダ · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "環境",- "sandboxDrive.pickerInfoTooltip": "ドライブ上のフォルダを選択すると、その中のファイルが会話間で保持されます。選択しない場合、サンドボックスは一時的です。","sandboxDrive.pickerTitle": "作業ディレクトリ","sandboxDrive.root": "ドライブのルート","sandboxDrive.upsell": "ファイルをドライブに保持",- "sandboxEnvironment.empty": "まだ環境がありません。「環境」で作成してください。",- "sandboxEnvironment.hint": "最初のコマンドの前に作業ディレクトリで一度クローンおよびセットアップされます。すでにファイルがあるフォルダはそのまま残されます。","sandboxEnvironment.loadFailed": "環境を読み込めませんでした","sandboxEnvironment.loading": "環境を読み込み中…","sandboxEnvironment.missing": "環境が利用できません",- "sandboxEnvironment.none": "環境なし","sandboxEnvironment.noneDesc": "空の作業ディレクトリから開始","sandboxEnvironment.retry": "再試行","sandboxEnvironment.saveFailed": "環境を変更できませんでした。もう一度お試しください。",- "sandboxEnvironment.title": "環境","sandboxStorage.allCopiesBusy": "すべてのコピーが使用中です","sandboxStorage.buildFailed": "ビルド失敗","sandboxStorage.building": "ビルド中",diff --git a/locales/ja-JP/project.json b/locales/ja-JP/project.jsonindex 7ba4ca8fb41..9842fb47cd4 100644--- a/locales/ja-JP/project.json+++ b/locales/ja-JP/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "デバイスが接続されました","settings.directoryDescription": "フォルダを選択してトピックを開始してください。エージェントは接続されたデバイス上のそのフォルダ内のファイルを操作します。","settings.directoryUnavailable": "デバイスが切断されているか、ディレクトリが利用できません。デバイスを接続し、パスを確認して再試行してください。",- "settings.environmentDescription": "リポジトリソースを環境にまとめてから、デバイス上のフォルダを追加して作業を開始してください。",- "settings.environments": "環境","settings.general": "一般","settings.generalDescription": "プロジェクト名、アドレス、説明を管理します。","settings.identifier": "プロジェクト識別子",@@ -334,7 +332,6 @@"settings.members": "メンバー","settings.nameHint": "最大255文字まで使用できます。","settings.noDirectories": "この環境にはまだフォルダがありません。接続されたデバイス上の既存フォルダを追加して作業を開始してください。",- "settings.noEnvironments": "関連付けられた環境がありません","settings.noRepository": "リンクされたGitHubリポジトリがありません","settings.reuseEnvironment": "既存の環境をこのプロジェクトに追加","settings.reuseEnvironmentDescription": "すでに環境を作成しましたか?それを選択してリポジトリ設定をこのプロジェクトにリンクし、このプロジェクト用の作業ディレクトリを追加してください。",diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.jsonindex 8d31f2b6a2c..391507c757b 100644--- a/locales/ja-JP/setting.json+++ b/locales/ja-JP/setting.json@@ -691,12 +691,8 @@"environments.create": "新しい環境","environments.createFailed": "環境を作成できませんでした","environments.desc": "サンドボックス実行に必要なもの:リポジトリ、そのセットアップ、変数。それぞれのコピーはセッション間で独自のファイルを保持します。",- "environments.detail.close": "閉じる",- "environments.detail.initializerDesc": "会話用に選択された作業ディレクトリに一度だけ適用されます: リポジトリがそこにクローンされ、セットアップコマンドが実行されます。","environments.detail.noRepository": "リポジトリなし","environments.detail.noSetup": "セットアップコマンドなし",- "environments.detail.tabs.overview": "概要",- "environments.detail.tabs.settings": "設定","environments.duplicateName": "この名前の環境はすでに存在します","environments.empty": "まだ環境がありません","environments.emptyPublished": "このワークスペースに公開されたものはありません",diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.jsonindex 590249a3c8e..7377853d436 100644--- a/locales/ko-KR/chat.json+++ b/locales/ko-KR/chat.json@@ -2122,20 +2122,15 @@"sandboxDrive.folderDesc": "드라이브의 폴더 · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "환경 관리",- "sandboxDrive.pickerInfoTooltip": "드라이브에서 폴더를 선택하면 그 안의 파일이 대화 간에 유지됩니다. 선택하지 않으면 샌드박스는 임시로 유지됩니다.","sandboxDrive.pickerTitle": "작업 디렉토리","sandboxDrive.root": "드라이브 루트","sandboxDrive.upsell": "드라이브에 파일 유지",- "sandboxEnvironment.empty": "아직 환경이 없습니다. 환경에서 하나를 만드세요.",- "sandboxEnvironment.hint": "작업 디렉토리에서 첫 번째 명령 전에 복제 및 설정됩니다. 이미 파일이 있는 폴더는 그대로 유지됩니다.","sandboxEnvironment.loadFailed": "환경을 로드할 수 없습니다","sandboxEnvironment.loading": "환경 로드 중…","sandboxEnvironment.missing": "환경 사용 불가",- "sandboxEnvironment.none": "환경 없음","sandboxEnvironment.noneDesc": "빈 작업 디렉토리에서 시작","sandboxEnvironment.retry": "다시 시도","sandboxEnvironment.saveFailed": "환경을 변경할 수 없습니다. 다시 시도하세요.",- "sandboxEnvironment.title": "환경","sandboxStorage.allCopiesBusy": "모든 복사본이 사용 중입니다","sandboxStorage.buildFailed": "빌드 실패","sandboxStorage.building": "빌드 중",diff --git a/locales/ko-KR/project.json b/locales/ko-KR/project.jsonindex 72a169f6e46..5ee58a3caec 100644--- a/locales/ko-KR/project.json+++ b/locales/ko-KR/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "장치 연결됨","settings.directoryDescription": "폴더를 선택하고 주제를 시작하세요. 에이전트는 연결된 장치의 해당 폴더에 있는 파일과 함께 작업합니다.","settings.directoryUnavailable": "장치가 연결되지 않았거나 디렉토리를 사용할 수 없습니다. 장치를 연결하고 경로를 확인한 후 다시 시도하세요.",- "settings.environmentDescription": "저장소 소스를 환경에 함께 보관한 다음, 장치에서 폴더를 추가하여 작업을 시작하세요.",- "settings.environments": "환경","settings.general": "일반","settings.generalDescription": "프로젝트 이름, 주소 및 설명을 관리합니다.","settings.identifier": "프로젝트 식별자",@@ -334,7 +332,6 @@"settings.members": "멤버","settings.nameHint": "최대 255자를 사용하세요.","settings.noDirectories": "이 환경에는 아직 폴더가 없습니다. 연결된 장치에서 기존 폴더를 추가하여 작업을 시작하세요.",- "settings.noEnvironments": "연결된 환경 없음","settings.noRepository": "연결된 GitHub 저장소 없음","settings.reuseEnvironment": "기존 환경을 이 프로젝트에 추가","settings.reuseEnvironmentDescription": "이미 환경을 생성했나요? 선택하여 해당 저장소 구성을 이 프로젝트에 연결한 다음, 이 프로젝트를 위한 작업 디렉토리를 추가하세요.",diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.jsonindex fea88f90618..71d09bc20e7 100644--- a/locales/ko-KR/setting.json+++ b/locales/ko-KR/setting.json@@ -691,12 +691,8 @@"environments.create": "새 환경","environments.createFailed": "환경을 생성할 수 없습니다","environments.desc": "샌드박스 실행에 필요한 것: 저장소, 설정, 변수. 여기서 생성된 각 복사본은 세션 간에 자체 파일을 유지합니다.",- "environments.detail.close": "닫기",- "environments.detail.initializerDesc": "대화의 작업 디렉토리로 선택되었을 때 한 번 적용됩니다: 저장소가 복제되고 설정 명령이 실행됩니다.","environments.detail.noRepository": "저장소 없음","environments.detail.noSetup": "설정 명령 없음",- "environments.detail.tabs.overview": "개요",- "environments.detail.tabs.settings": "설정","environments.duplicateName": "이 이름의 환경이 이미 있습니다","environments.empty": "아직 환경이 없습니다","environments.emptyPublished": "이 작업 공간에 게시된 내용이 없습니다",diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.jsonindex d37212693e8..ef0619cd704 100644--- a/locales/nl-NL/chat.json+++ b/locales/nl-NL/chat.json@@ -2124,20 +2124,15 @@"sandboxDrive.folderDesc": "Map op uw schijf · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "Omgevingen",- "sandboxDrive.pickerInfoTooltip": "Kies een map op uw schijf en de bestanden worden behouden tussen gesprekken. Zonder een map is de sandbox tijdelijk.","sandboxDrive.pickerTitle": "Werkmap","sandboxDrive.root": "Schijfroot","sandboxDrive.upsell": "Bestanden op een schijf bewaren",- "sandboxEnvironment.empty": "Nog geen omgevingen. Maak er een in Omgevingen.",- "sandboxEnvironment.hint": "Gekloond en ingesteld in de werkmap vóór het eerste commando. Een map die al bestanden heeft, blijft zoals het is.","sandboxEnvironment.loadFailed": "Kon omgevingen niet laden","sandboxEnvironment.loading": "Omgeving laden…","sandboxEnvironment.missing": "Omgeving niet beschikbaar",- "sandboxEnvironment.none": "Geen omgeving","sandboxEnvironment.noneDesc": "Begin vanuit een lege werkmap","sandboxEnvironment.retry": "Opnieuw proberen","sandboxEnvironment.saveFailed": "Kon de omgeving niet wijzigen. Probeer opnieuw.",- "sandboxEnvironment.title": "Omgeving","sandboxStorage.allCopiesBusy": "Elke kopie is in gebruik","sandboxStorage.buildFailed": "Niet gebouwd","sandboxStorage.building": "Bezig met bouwen",diff --git a/locales/nl-NL/project.json b/locales/nl-NL/project.jsonindex d3fcb13df13..eaba28ee235 100644--- a/locales/nl-NL/project.json+++ b/locales/nl-NL/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "Apparaat verbonden","settings.directoryDescription": "Kies een map en begin een onderwerp. De Ajan zal werken met bestanden in die map op het verbonden apparaat.","settings.directoryUnavailable": "Het apparaat is losgekoppeld of de map is niet beschikbaar. Verbind het apparaat en controleer het pad, probeer vervolgens opnieuw.",- "settings.environmentDescription": "Houd repositorybronnen samen in een omgeving, voeg vervolgens een map op je apparaat toe om te beginnen met werken.",- "settings.environments": "Omgevingen","settings.general": "Algemeen","settings.generalDescription": "Beheer de projectnaam, het adres en de beschrijving.","settings.identifier": "Projectidentificator",@@ -334,7 +332,6 @@"settings.members": "Leden","settings.nameHint": "Gebruik maximaal 255 tekens.","settings.noDirectories": "Nog geen mappen in deze omgeving. Voeg een bestaande map op een verbonden apparaat toe om te beginnen met werken.",- "settings.noEnvironments": "Nog geen omgevingen gekoppeld","settings.noRepository": "Geen GitHub-repository gekoppeld","settings.reuseEnvironment": "Bestaande omgeving toevoegen aan dit project","settings.reuseEnvironmentDescription": "Al een omgeving aangemaakt? Selecteer deze om de repositoryconfiguratie aan dit project te koppelen, voeg vervolgens een werkmap toe voor dit project.",diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.jsonindex 135d5c81428..7bac02d9f3d 100644--- a/locales/nl-NL/setting.json+++ b/locales/nl-NL/setting.json@@ -691,12 +691,8 @@"environments.create": "Nieuwe omgeving","environments.createFailed": "Kon de omgeving niet maken","environments.desc": "Wat een sandbox-run nodig heeft: een repository, de setup, de variabelen. Elke kopie die hiervan wordt gemaakt, behoudt zijn eigen bestanden tussen sessies.",- "environments.detail.close": "Sluiten",- "environments.detail.initializerDesc": "Eenmalig toegepast op een werkmap gekozen voor een gesprek: de repository wordt daar gekloond en het setup-commando wordt uitgevoerd.","environments.detail.noRepository": "Geen repository","environments.detail.noSetup": "Geen setup-commando",- "environments.detail.tabs.overview": "Overzicht",- "environments.detail.tabs.settings": "Instellingen","environments.duplicateName": "Je hebt al een omgeving met deze naam","environments.empty": "Nog geen omgevingen","environments.emptyPublished": "Nog niets gepubliceerd naar deze werkruimte",diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.jsonindex 1288728f170..04ba9876b41 100644--- a/locales/pl-PL/chat.json+++ b/locales/pl-PL/chat.json@@ -2122,20 +2122,15 @@"sandboxDrive.folderDesc": "Folder na Twoim dysku · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "Środowiska",- "sandboxDrive.pickerInfoTooltip": "Wybierz folder na swoim dysku, a jego pliki będą zachowywane między rozmowami. Bez niego sandbox jest tymczasowy.","sandboxDrive.pickerTitle": "Katalog roboczy","sandboxDrive.root": "Katalog główny dysku","sandboxDrive.upsell": "Zachowaj pliki na dysku",- "sandboxEnvironment.empty": "Brak środowisk. Utwórz jedno w Środowiskach.",- "sandboxEnvironment.hint": "Klonowane i konfigurowane raz w katalogu roboczym przed pierwszym poleceniem. Folder, który już ma pliki, pozostaje bez zmian.","sandboxEnvironment.loadFailed": "Nie udało się załadować środowisk","sandboxEnvironment.loading": "Ładowanie środowiska…","sandboxEnvironment.missing": "Środowisko niedostępne",- "sandboxEnvironment.none": "Brak środowiska","sandboxEnvironment.noneDesc": "Rozpocznij od pustego katalogu roboczego","sandboxEnvironment.retry": "Spróbuj ponownie","sandboxEnvironment.saveFailed": "Nie udało się zmienić środowiska. Spróbuj ponownie.",- "sandboxEnvironment.title": "Środowisko","sandboxStorage.allCopiesBusy": "Wszystkie kopie są w użyciu","sandboxStorage.buildFailed": "Nie zbudowano","sandboxStorage.building": "Budowanie",diff --git a/locales/pl-PL/project.json b/locales/pl-PL/project.jsonindex 7a060e77d35..2ddd2ef6aba 100644--- a/locales/pl-PL/project.json+++ b/locales/pl-PL/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "Urządzenie podłączone","settings.directoryDescription": "Wybierz folder i rozpocznij temat. Ajan będzie pracował z plikami w tym folderze na podłączonym urządzeniu.","settings.directoryUnavailable": "Urządzenie jest odłączone lub katalog jest niedostępny. Połącz urządzenie i sprawdź ścieżkę, a następnie spróbuj ponownie.",- "settings.environmentDescription": "Przechowuj źródła repozytoriów w jednym środowisku, a następnie dodaj folder na swoim urządzeniu, aby rozpocząć pracę.",- "settings.environments": "Środowiska","settings.general": "Ogólne","settings.generalDescription": "Zarządzaj nazwą projektu, adresem i opisem.","settings.identifier": "Identyfikator projektu",@@ -334,7 +332,6 @@"settings.members": "Członkowie","settings.nameHint": "Użyj maksymalnie 255 znaków.","settings.noDirectories": "Brak folderów w tym środowisku. Dodaj istniejący folder na podłączonym urządzeniu, aby rozpocząć pracę.",- "settings.noEnvironments": "Brak powiązanych środowisk","settings.noRepository": "Brak powiązanego repozytorium GitHub","settings.reuseEnvironment": "Dodaj istniejące środowisko do tego projektu","settings.reuseEnvironmentDescription": "Czy już utworzyłeś środowisko? Wybierz je, aby powiązać jego konfigurację repozytorium z tym projektem, a następnie dodaj katalog roboczy dla tego projektu.",diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.jsonindex 8f5a3f6665d..cd836922b6c 100644--- a/locales/pl-PL/setting.json+++ b/locales/pl-PL/setting.json@@ -691,12 +691,8 @@"environments.create": "Nowe środowisko","environments.createFailed": "Nie udało się utworzyć środowiska","environments.desc": "Czego potrzebuje uruchomienie w piaskownicy: repozytorium, jego konfiguracja, zmienne. Każda kopia zbudowana z jednego zachowuje własne pliki między sesjami.",- "environments.detail.close": "Zamknij",- "environments.detail.initializerDesc": "Zastosowane raz do katalogu roboczego wybranego dla rozmowy: repozytorium jest tam klonowane, a polecenie konfiguracji uruchamiane.","environments.detail.noRepository": "Brak repozytorium","environments.detail.noSetup": "Brak polecenia konfiguracji",- "environments.detail.tabs.overview": "Przegląd",- "environments.detail.tabs.settings": "Ustawienia","environments.duplicateName": "Masz już środowisko o tej nazwie","environments.empty": "Brak środowisk","environments.emptyPublished": "Nic nie opublikowano w tym obszarze roboczym",diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.jsonindex c653893d81c..1b5ce1d0e5a 100644--- a/locales/pt-BR/chat.json+++ b/locales/pt-BR/chat.json@@ -2122,20 +2122,15 @@"sandboxDrive.folderDesc": "Pasta no seu drive · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "Ambientes",- "sandboxDrive.pickerInfoTooltip": "Escolha uma pasta no seu drive e seus arquivos serão mantidos entre conversas. Sem uma, o sandbox é temporário.","sandboxDrive.pickerTitle": "Diretório de trabalho","sandboxDrive.root": "Raiz do drive","sandboxDrive.upsell": "Mantenha arquivos em um drive",- "sandboxEnvironment.empty": "Nenhum ambiente ainda. Crie um em Ambientes.",- "sandboxEnvironment.hint": "Clonado e configurado uma vez no diretório de trabalho antes do primeiro comando. Uma pasta que já possui arquivos é deixada como está.","sandboxEnvironment.loadFailed": "Não foi possível carregar os ambientes","sandboxEnvironment.loading": "Carregando ambiente…","sandboxEnvironment.missing": "Ambiente indisponível",- "sandboxEnvironment.none": "Nenhum ambiente","sandboxEnvironment.noneDesc": "Comece a partir de um diretório de trabalho vazio","sandboxEnvironment.retry": "Tentar novamente","sandboxEnvironment.saveFailed": "Não foi possível alterar o ambiente. Tente novamente.",- "sandboxEnvironment.title": "Ambiente","sandboxStorage.allCopiesBusy": "Todas as cópias estão em uso","sandboxStorage.buildFailed": "Não construído","sandboxStorage.building": "Construindo",diff --git a/locales/pt-BR/project.json b/locales/pt-BR/project.jsonindex 896501c827a..f199b839ec3 100644--- a/locales/pt-BR/project.json+++ b/locales/pt-BR/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "Dispositivo conectado","settings.directoryDescription": "Escolha uma pasta e inicie um tópico. O Agente trabalhará com os arquivos nessa pasta no dispositivo conectado.","settings.directoryUnavailable": "O dispositivo está desconectado ou o diretório está indisponível. Conecte o dispositivo e verifique o caminho, depois tente novamente.",- "settings.environmentDescription": "Mantenha as fontes do repositório juntas em um ambiente, depois adicione uma pasta no seu dispositivo para começar a trabalhar.",- "settings.environments": "Ambientes","settings.general": "Geral","settings.generalDescription": "Gerencie o nome, endereço e descrição do projeto.","settings.identifier": "Identificador do projeto",@@ -334,7 +332,6 @@"settings.members": "Membros","settings.nameHint": "Use no máximo 255 caracteres.","settings.noDirectories": "Ainda não há pastas neste ambiente. Adicione uma pasta existente em um dispositivo conectado para começar a trabalhar.",- "settings.noEnvironments": "Nenhum ambiente associado ainda","settings.noRepository": "Nenhum repositório GitHub vinculado","settings.reuseEnvironment": "Adicionar um ambiente existente a este projeto","settings.reuseEnvironmentDescription": "Já criou um ambiente? Selecione-o para vincular sua configuração de repositório a este projeto, depois adicione um diretório de trabalho para este projeto.",diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.jsonindex d328df80879..b9ba4925e0a 100644--- a/locales/pt-BR/setting.json+++ b/locales/pt-BR/setting.json@@ -691,12 +691,8 @@"environments.create": "Novo ambiente","environments.createFailed": "Não foi possível criar o ambiente","environments.desc": "O que uma execução de sandbox precisa ao seu redor: um repositório, sua configuração, suas variáveis. Cada cópia criada a partir de uma mantém seus próprios arquivos entre sessões.",- "environments.detail.close": "Fechar",- "environments.detail.initializerDesc": "Aplicado uma vez a um diretório de trabalho escolhido para uma conversa: o repositório é clonado lá e o comando de configuração é executado.","environments.detail.noRepository": "Nenhum repositório","environments.detail.noSetup": "Nenhum comando de configuração",- "environments.detail.tabs.overview": "Visão Geral",- "environments.detail.tabs.settings": "Configurações","environments.duplicateName": "Você já tem um ambiente com este nome","environments.empty": "Nenhum ambiente ainda","environments.emptyPublished": "Nada publicado neste espaço de trabalho ainda",diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.jsonindex ab0ab53d2ac..ff2e7612754 100644--- a/locales/ru-RU/chat.json+++ b/locales/ru-RU/chat.json@@ -2122,20 +2122,15 @@"sandboxDrive.folderDesc": "Папка на вашем диске · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "Окружения",- "sandboxDrive.pickerInfoTooltip": "Выберите папку на вашем диске, и ее файлы сохранятся между разговорами. Без нее песочница будет временной.","sandboxDrive.pickerTitle": "Рабочая директория","sandboxDrive.root": "Корень диска","sandboxDrive.upsell": "Сохраняйте файлы на диске",- "sandboxEnvironment.empty": "Пока нет окружений. Создайте одно в разделе Окружения.",- "sandboxEnvironment.hint": "Клонируется и настраивается один раз в рабочей директории перед первой командой. Папка, в которой уже есть файлы, остается без изменений.","sandboxEnvironment.loadFailed": "Не удалось загрузить окружения","sandboxEnvironment.loading": "Загрузка окружения…","sandboxEnvironment.missing": "Окружение недоступно",- "sandboxEnvironment.none": "Нет окружения","sandboxEnvironment.noneDesc": "Начать с пустой рабочей директории","sandboxEnvironment.retry": "Повторить","sandboxEnvironment.saveFailed": "Не удалось изменить окружение. Попробуйте еще раз.",- "sandboxEnvironment.title": "Окружение","sandboxStorage.allCopiesBusy": "Все копии заняты","sandboxStorage.buildFailed": "Не построено","sandboxStorage.building": "Построение",diff --git a/locales/ru-RU/project.json b/locales/ru-RU/project.jsonindex 86f21626ede..1e6f9572f24 100644--- a/locales/ru-RU/project.json+++ b/locales/ru-RU/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "Устройство подключено","settings.directoryDescription": "Выберите папку и начните тему. Агента будет работать с файлами в этой папке на подключенном устройстве.","settings.directoryUnavailable": "Устройство отключено или директория недоступна. Подключите устройство и проверьте путь, затем повторите попытку.",- "settings.environmentDescription": "Соберите источники репозиториев вместе в окружении, затем добавьте папку на вашем устройстве, чтобы начать работу.",- "settings.environments": "Окружения","settings.general": "Общее","settings.generalDescription": "Управляйте названием проекта, адресом и описанием.","settings.identifier": "Идентификатор проекта",@@ -334,7 +332,6 @@"settings.members": "Участники","settings.nameHint": "Используйте не более 255 символов.","settings.noDirectories": "В этом окружении пока нет папок. Добавьте существующую папку на подключенном устройстве, чтобы начать работу.",- "settings.noEnvironments": "Нет связанных окружений","settings.noRepository": "Нет связанного репозитория GitHub","settings.reuseEnvironment": "Добавить существующее окружение в этот проект","settings.reuseEnvironmentDescription": "Уже создали окружение? Выберите его, чтобы связать его конфигурацию репозитория с этим проектом, затем добавьте рабочую директорию для этого проекта.",diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.jsonindex 2fc15c92dbf..563f7b6a513 100644--- a/locales/ru-RU/setting.json+++ b/locales/ru-RU/setting.json@@ -691,12 +691,8 @@"environments.create": "Новая среда","environments.createFailed": "Не удалось создать среду","environments.desc": "Что нужно для запуска песочницы: репозиторий, его настройка, его переменные. Каждая копия, созданная из одного, сохраняет свои собственные файлы между сессиями.",- "environments.detail.close": "Закрыть",- "environments.detail.initializerDesc": "Применяется один раз к рабочему каталогу, выбранному для беседы: репозиторий клонируется туда, и выполняется команда настройки.","environments.detail.noRepository": "Нет репозитория","environments.detail.noSetup": "Нет команды настройки",- "environments.detail.tabs.overview": "Обзор",- "environments.detail.tabs.settings": "Настройки","environments.duplicateName": "У вас уже есть среда с таким именем","environments.empty": "Сред пока нет","environments.emptyPublished": "В этом рабочем пространстве пока ничего не опубликовано",diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.jsonindex 6e8cc2711cd..41db86d09db 100644--- a/locales/tr-TR/chat.json+++ b/locales/tr-TR/chat.json@@ -2124,20 +2124,15 @@"sandboxDrive.folderDesc": "Sürücünüzdeki klasör · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "Ortamlar",- "sandboxDrive.pickerInfoTooltip": "Sürücünüzde bir klasör seçin ve içindeki dosyalar konuşmalar arasında saklanır. Bir klasör olmadan, alan geçicidir.","sandboxDrive.pickerTitle": "Çalışma dizini","sandboxDrive.root": "Sürücü kökü","sandboxDrive.upsell": "Dosyaları bir sürücüde saklayın",- "sandboxEnvironment.empty": "Henüz ortam yok. Ortamlar'da bir tane oluşturun.",- "sandboxEnvironment.hint": "İlk komuttan önce çalışma dizininde bir kez klonlanır ve ayarlanır. Zaten dosyaları olan bir klasör olduğu gibi bırakılır.","sandboxEnvironment.loadFailed": "Ortamlar yüklenemedi","sandboxEnvironment.loading": "Ortam yükleniyor…","sandboxEnvironment.missing": "Ortam kullanılamaz",- "sandboxEnvironment.none": "Ortam yok","sandboxEnvironment.noneDesc": "Boş bir çalışma dizininden başlayın","sandboxEnvironment.retry": "Tekrar dene","sandboxEnvironment.saveFailed": "Ortam değiştirilemedi. Tekrar deneyin.",- "sandboxEnvironment.title": "Ortam","sandboxStorage.allCopiesBusy": "Tüm kopyalar kullanımda","sandboxStorage.buildFailed": "Derlenemedi","sandboxStorage.building": "Derleniyor",diff --git a/locales/tr-TR/project.json b/locales/tr-TR/project.jsonindex a3aaf7940ac..d8647118570 100644--- a/locales/tr-TR/project.json+++ b/locales/tr-TR/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "Cihaz bağlı","settings.directoryDescription": "Bir klasör seçin ve bir konu başlatın. Ajan, bağlı cihazdaki bu klasördeki dosyalarla çalışacak.","settings.directoryUnavailable": "Cihaz bağlantısı kesildi veya dizin kullanılamıyor. Cihazı bağlayın ve yolu kontrol edin, ardından tekrar deneyin.",- "settings.environmentDescription": "Depo kaynaklarını bir ortamda bir arada tutun, ardından bu projede çalışmaya başlamak için cihazınıza bir klasör ekleyin.",- "settings.environments": "Ortamlar","settings.general": "Genel","settings.generalDescription": "Proje adı, adresi ve açıklamasını yönetin.","settings.identifier": "Proje tanımlayıcısı",@@ -334,7 +332,6 @@"settings.members": "Üyeler","settings.nameHint": "En fazla 255 karakter kullanın.","settings.noDirectories": "Bu ortamda henüz klasör yok. Çalışmaya başlamak için bağlı bir cihazda mevcut bir klasör ekleyin.",- "settings.noEnvironments": "Henüz ilişkilendirilmiş bir ortam yok","settings.noRepository": "Bağlı bir GitHub deposu yok","settings.reuseEnvironment": "Bu projeye mevcut bir ortam ekle","settings.reuseEnvironmentDescription": "Zaten bir ortam oluşturdunuz mu? Onu seçerek depo yapılandırmasını bu projeye bağlayın, ardından bu proje için bir çalışma dizini ekleyin.",diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.jsonindex 63d8baad5d2..be5676eb4f9 100644--- a/locales/tr-TR/setting.json+++ b/locales/tr-TR/setting.json@@ -691,12 +691,8 @@"environments.create": "Yeni ortam","environments.createFailed": "Ortam oluşturulamadı","environments.desc": "Bir sandbox çalıştırmasının etrafında neye ihtiyacı var: bir depo, onun kurulumu, değişkenleri. Birinden oluşturulan her kopya, oturumlar arasında kendi dosyalarını saklar.",- "environments.detail.close": "Kapat",- "environments.detail.initializerDesc": "Bir konuşma için seçilen bir çalışma dizinine bir kez uygulanır: depo oraya klonlanır ve kurulum komutu çalıştırılır.","environments.detail.noRepository": "Depo yok","environments.detail.noSetup": "Kurulum komutu yok",- "environments.detail.tabs.overview": "Genel Bakış",- "environments.detail.tabs.settings": "Ayarlar","environments.duplicateName": "Bu isimde zaten bir ortamınız var","environments.empty": "Henüz ortam yok","environments.emptyPublished": "Bu çalışma alanına henüz bir şey yayınlanmadı",diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.jsonindex 22e3e2db18e..bb61775cdca 100644--- a/locales/vi-VN/chat.json+++ b/locales/vi-VN/chat.json@@ -2122,20 +2122,15 @@"sandboxDrive.folderDesc": "Thư mục trên ổ đĩa của bạn · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "Môi trường",- "sandboxDrive.pickerInfoTooltip": "Chọn một thư mục trên ổ đĩa của bạn và các tệp của nó được giữ lại qua các cuộc trò chuyện. Nếu không có, sandbox là tạm thời.","sandboxDrive.pickerTitle": "Thư mục làm việc","sandboxDrive.root": "Gốc ổ đĩa","sandboxDrive.upsell": "Giữ tệp trên ổ đĩa",- "sandboxEnvironment.empty": "Chưa có môi trường nào. Tạo một môi trường trong Môi trường.",- "sandboxEnvironment.hint": "Được sao chép và thiết lập một lần trong thư mục làm việc trước lệnh đầu tiên. Một thư mục đã có tệp sẽ được giữ nguyên.","sandboxEnvironment.loadFailed": "Không thể tải môi trường","sandboxEnvironment.loading": "Đang tải môi trường…","sandboxEnvironment.missing": "Môi trường không khả dụng",- "sandboxEnvironment.none": "Không có môi trường","sandboxEnvironment.noneDesc": "Bắt đầu từ một thư mục làm việc trống","sandboxEnvironment.retry": "Thử lại","sandboxEnvironment.saveFailed": "Không thể thay đổi môi trường. Thử lại.",- "sandboxEnvironment.title": "Môi trường","sandboxStorage.allCopiesBusy": "Mọi bản sao đang được sử dụng","sandboxStorage.buildFailed": "Không xây dựng được","sandboxStorage.building": "Đang xây dựng",diff --git a/locales/vi-VN/project.json b/locales/vi-VN/project.jsonindex 2325321f344..d0271b8febc 100644--- a/locales/vi-VN/project.json+++ b/locales/vi-VN/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "Thiết bị đã kết nối","settings.directoryDescription": "Chọn một thư mục và bắt đầu một chủ đề. Ajan sẽ làm việc với các tệp trong thư mục đó trên thiết bị được kết nối.","settings.directoryUnavailable": "Thiết bị đã ngắt kết nối hoặc thư mục không khả dụng. Kết nối thiết bị và kiểm tra đường dẫn, sau đó thử lại.",- "settings.environmentDescription": "Giữ các nguồn kho cùng nhau trong một môi trường, sau đó thêm một thư mục trên thiết bị của bạn để bắt đầu làm việc.",- "settings.environments": "Môi trường","settings.general": "Chung","settings.generalDescription": "Quản lý tên dự án, địa chỉ và mô tả.","settings.identifier": "Định danh dự án",@@ -334,7 +332,6 @@"settings.members": "Thành viên","settings.nameHint": "Sử dụng tối đa 255 ký tự.","settings.noDirectories": "Chưa có thư mục nào trong môi trường này. Thêm một thư mục hiện có trên một thiết bị được kết nối để bắt đầu làm việc.",- "settings.noEnvironments": "Chưa có môi trường nào được liên kết","settings.noRepository": "Chưa có kho GitHub nào được liên kết","settings.reuseEnvironment": "Thêm một môi trường hiện có vào dự án này","settings.reuseEnvironmentDescription": "Đã tạo một môi trường? Chọn nó để liên kết cấu hình kho của nó với dự án này, sau đó thêm một thư mục làm việc cho dự án này.",diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.jsonindex 3031ee320a8..5067602ea7d 100644--- a/locales/vi-VN/setting.json+++ b/locales/vi-VN/setting.json@@ -691,12 +691,8 @@"environments.create": "Môi trường mới","environments.createFailed": "Không thể tạo môi trường","environments.desc": "Những gì một sandbox cần để chạy: một kho lưu trữ, thiết lập của nó, các biến của nó. Mỗi bản sao được tạo từ một môi trường sẽ giữ các tệp riêng của nó giữa các phiên làm việc.",- "environments.detail.close": "Đóng",- "environments.detail.initializerDesc": "Áp dụng một lần cho thư mục làm việc được chọn cho một cuộc hội thoại: kho lưu trữ sẽ được sao chép vào đó và lệnh thiết lập sẽ được chạy.","environments.detail.noRepository": "Không có kho lưu trữ","environments.detail.noSetup": "Không có lệnh thiết lập",- "environments.detail.tabs.overview": "Tổng quan",- "environments.detail.tabs.settings": "Cài đặt","environments.duplicateName": "Bạn đã có một môi trường với tên này","environments.empty": "Chưa có môi trường nào","environments.emptyPublished": "Chưa có gì được xuất bản trong không gian làm việc này",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 20f3a7be9a0..0799f613e58 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2193,20 +2193,21 @@"sandboxDrive.fallbackChip.rootNotAllowed": "请选择文件夹","sandboxDrive.manageEnvironments": "设置","sandboxDrive.openStorage": "沙箱存储",- "sandboxDrive.pickerInfoTooltip": "临时工作目录随沙箱清理;云盘文件夹跨会话保留;代码仓库在第一条命令前克隆好。",+ "sandboxDrive.pickerInfoTooltip": "临时工作目录随沙箱清理;云盘文件夹跨会话保留;环境在第一条命令前初始化好。","sandboxDrive.pickerTitle": "工作位置","sandboxDrive.root": "根目录","sandboxDrive.title": "云盘",- "sandboxEnvironment.add": "添加代码仓库",- "sandboxEnvironment.empty": "还没有代码仓库,先添加一个。",- "sandboxEnvironment.hint": "在第一条命令前克隆仓库,并执行一次初始化。",+ "sandboxEnvironment.add": "新建环境",+ "sandboxEnvironment.empty": "还没有环境,先新建一个。",+ "sandboxEnvironment.hint": "在第一条命令前克隆环境里的仓库、执行初始化并注入环境变量。","sandboxEnvironment.loadFailed": "无法加载环境列表","sandboxEnvironment.loading": "正在加载环境…","sandboxEnvironment.missing": "环境不可用",- "sandboxEnvironment.none": "不使用仓库",+ "sandboxEnvironment.noRepository": "无仓库",+ "sandboxEnvironment.none": "不使用环境","sandboxEnvironment.retry": "重试","sandboxEnvironment.saveFailed": "无法更改环境,请重试。",- "sandboxEnvironment.title": "代码仓库",+ "sandboxEnvironment.title": "环境","sandboxStorage.allCopiesBusy": "所有副本都在使用中","sandboxStorage.buildFailed": "未构建","sandboxStorage.building": "构建中",diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.jsonindex ca27299b910..e941271aec3 100644--- a/locales/zh-CN/project.json+++ b/locales/zh-CN/project.json@@ -59,16 +59,25 @@"create.slugPlaceholder": "my-project","create.slugTaken": "当前空间已有项目使用该链接名,请换一个。","create.title": "新建项目",+ "createFromGithub.addRepository": "添加",+ "createFromGithub.advanced": "高级设置",+ "createFromGithub.advancedWithCount": "高级设置 · 另有 {{count}} 个仓库",+ "createFromGithub.alreadyAdded": "这个仓库已经添加过了。",+ "createFromGithub.chooseFromGithub": "从 GitHub 选择","createFromGithub.connect": "连接 GitHub","createFromGithub.disconnected": "连接 GitHub 后可直接选择你的仓库,也可以在下方粘贴公开仓库的链接。","createFromGithub.duplicateIdentifier": "其他项目已在使用这个标识,请换一个。","createFromGithub.duplicateName": "已存在同名项目(包括回收站中的项目),请换一个名称。","createFromGithub.empty": "已连接的 GitHub 账号还没有授权 LobeHub 访问任何仓库。",- "createFromGithub.environmentHint": "该仓库会成为项目的环境,智能体处理这个项目时可以检出它。",+ "createFromGithub.extraRepositoriesLabel": "更多仓库",+ "createFromGithub.layoutHint": "每个仓库各放在一个文件夹里,并排检出。之后可以在项目设置里调整。","createFromGithub.loadFailed": "无法从 GitHub 加载仓库。","createFromGithub.manageAccess": "管理授权",+ "createFromGithub.openIntegrations": "前往 GitHub 设置","createFromGithub.private": "私有",+ "createFromGithub.removeRepository": "移除","createFromGithub.repositoriesLabel": "你的仓库",+ "createFromGithub.repositoryTitle": "仓库","createFromGithub.searchEmpty": "没有匹配的仓库","createFromGithub.searchPlaceholder": "搜索仓库…","createFromGithub.title": "从 GitHub 创建项目",@@ -128,21 +137,8 @@"directories.untitled": "未命名话题","disabled.action": "前往实验室开启","disabled.title": "项目工作空间目前处于 Alpha 阶段",- "environment.add.action": "添加",- "environment.add.existing": "添加已有环境",- "environment.add.failed": "无法将环境添加到本项目",- "environment.add.github": "从 GitHub 新建",- "environment.add.noExisting": "你的环境都已添加到本项目。",- "environment.add.noPublished": "没有可添加的已发布环境。共享项目只会使用已发布的环境。",- "environment.add.title": "添加环境",- "environment.create": "新建环境",- "environment.link": "关联环境",- "environment.privateInShared": "仅自己可见",- "environment.privateInSharedTooltip": "这是共享项目,对话只会使用已发布的环境,这个私有环境不会被检出。",- "environment.unlink": "取消关联",- "environment.unlinkConfirm.desc": "环境本身会保留在「设置 → 环境」中。本项目里用到它的文件夹会保留,但在重新关联前不能运行对话。",- "environment.unlinkConfirm.title": "从本项目取消关联「{{name}}」?",- "environment.unlinkFailed": "无法从本项目取消关联该环境",+ "environment.configure": "配置环境",+ "environment.none": "不使用环境(从空目录开始)","goals.create": "新建目标","goals.description": "定义这个项目正在追求的成果,并持续跟踪到验收。","goals.emptyDescription": "为这个项目创建第一个可衡量的成果。",@@ -384,7 +380,7 @@"settings.editDirectoryDescription": "选择这个工作目录对应的设备和文件夹。相关话题会一起迁移到新文件夹,并在那里开始新的会话。","settings.editDirectoryFailed": "无法修改文件夹","settings.editDirectoryOtherEnvironment": "这个文件夹已属于其他环境,请选择别的文件夹或设备。",- "settings.environmentDescription": "关联在「设置 → 环境」中配置的环境,再添加设备上的文件夹,开始在项目中工作。",+ "settings.environmentIntro": "项目里的每个对话都在这个环境中运行:克隆下面的仓库、执行初始化命令,并注入环境变量。","settings.environments": "环境","settings.general": "基础设置","settings.generalDescription": "管理项目名称、链接和说明。",@@ -400,7 +396,6 @@"settings.members": "成员","settings.nameHint": "最多 255 个字符。","settings.noDirectories": "还没有工作目录。添加已连接设备上的文件夹后,即可在此新建对话。",- "settings.noEnvironments": "尚未关联环境","settings.noRepository": "未关联 GitHub 仓库","settings.removeDirectory": "移除文件夹","settings.removeDirectoryConfirmDescription": "{{device}} 上的 {{path}} 将不再是本项目的工作目录。设备上的文件不会改动,相关话题仍保留在项目中,但不再关联此文件夹。",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex d566b5fb5c9..66e489c37ba 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -855,12 +855,10 @@"environments.create": "新建环境","environments.createFailed": "环境没能创建","environments.desc": "项目的初始化方式:要拉取的仓库、setup 命令和环境变量。在输入框下方的「代码环境」中选择后,对话的工作目录(临时沙箱或网盘文件夹)会用它初始化一次。",- "environments.detail.close": "关闭",- "environments.detail.initializerDesc": "在对话所选的工作目录中执行一次:克隆仓库并运行初始化命令。",+ "environments.detail.back": "环境","environments.detail.noRepository": "未设置仓库","environments.detail.noSetup": "未设置初始化命令",- "environments.detail.tabs.overview": "概览",- "environments.detail.tabs.settings": "设置",+ "environments.detail.notFound": "这个环境不存在,或你没有权限查看。","environments.duplicateName": "你已经有一个同名的环境了","environments.empty": "还没有环境","environments.emptyPublished": "还没有环境发布到这个工作区",@@ -881,18 +879,24 @@"environments.files.unusedInstance": "这里还没有内容。副本构建完成或在其中运行过对话后,代码会出现在这里。","environments.files.up": "返回上一级","environments.form.addEnv": "新建变量",+ "environments.form.addPastedRepository": "添加",+ "environments.form.addRepository": "添加仓库","environments.form.addSource": "添加仓库","environments.form.appliesOnBuild": "在新建副本时生效。已有副本会一直用它创建时的那份定义——重建也是照它再跑一遍,要用上改动就新建一个副本。","environments.form.appliesOnInit": "下次将环境应用到工作目录时生效;已初始化过的文件夹保持原样。","environments.form.basics": "基本信息","environments.form.bootstrap": "初始化命令",+ "environments.form.bootstrapAfterRepositories": "在工作目录顶层执行,晚于各仓库自己的初始化命令。只跟某个仓库有关的命令,请写在那个仓库里。","environments.form.bootstrapHint": "在对话开始前,于代码目录中联网执行一次。","environments.form.changeRepository": "更换仓库","environments.form.desc": "代码从哪来,以及靠什么让它能跑起来。","environments.form.description": "描述","environments.form.descriptionPlaceholder": "这个环境是用来做什么的","environments.form.disconnect": "断开",+ "environments.form.doneEditing": "完成",+ "environments.form.duplicateFolder": "另一个仓库已经用了这个文件夹。","environments.form.editEnv": "编辑变量",+ "environments.form.editRepositorySettings": "编辑分支、文件夹和初始化命令","environments.form.env": "环境变量","environments.form.envCount_one": "{{count}} 个变量","environments.form.envCount_other": "{{count}} 个变量",@@ -906,8 +910,12 @@"environments.form.internetAccessHint": "初始化命令始终可以联网,这里控制的是对话本身。","environments.form.jsonSyntax": "JSON 格式有误,请检查双引号、逗号和花括号后重新保存。","environments.form.jsonValues": "请使用每个变量值均为字符串的 JSON 对象,例如 {\"NODE_ENV\":\"production\"}。",+ "environments.form.layoutHint": "每个仓库各放在一个文件夹里,并排检出。之后可以在环境设置里调整。","environments.form.maintenance": "维护命令","environments.form.maintenanceHint": "每次回到这个副本继续工作时执行——更新代码、补一次迁移。它不是再跑一遍初始化命令:那个很贵,本来就只该跑一次。",+ "environments.form.noRepositories": "没有关联仓库,对话从空文件夹开始。",+ "environments.form.noVariables": "没有环境变量",+ "environments.form.pasteRepository": "或粘贴公开仓库的链接","environments.form.path": "目录","environments.form.rawEditor": "原始编辑器","environments.form.rawEditorHint": "每行一条 KEY=value,和 .env 文件一样。空行和 # 注释会被忽略;保存会替换全部变量。",@@ -918,6 +926,9 @@"environments.form.refDefault": "仓库默认分支","environments.form.removeEnv": "移除变量","environments.form.removeSource": "移除仓库",+ "environments.form.repositoryOptional": "可不选,没有仓库的环境之后也能再添加。",+ "environments.form.repositorySetupHint": "仓库克隆后在它自己的文件夹里执行,早于环境的初始化命令。",+ "environments.form.repositoryUrlInvalid": "不是有效的 GitHub 仓库链接","environments.form.runtime": "运行与存储","environments.form.saved": "已保存","environments.form.setup": "初始化",@@ -928,6 +939,7 @@"environments.github.loadFailed": "无法加载 GitHub 仓库,请重试。","environments.github.noRepositories": "这个连接还看不到任何仓库","environments.github.notConnected": "还没有连接 GitHub——连接后即可按仓库创建环境",+ "environments.github.openIntegrations": "前往 GitHub 设置","environments.github.optional": "可不选","environments.github.organization": "组织","environments.github.organizationPlaceholder": "搜索组织",diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.jsonindex 30cabdcf249..0d4b3cdab30 100644--- a/locales/zh-TW/chat.json+++ b/locales/zh-TW/chat.json@@ -2125,20 +2125,15 @@"sandboxDrive.folderDesc": "您的磁碟上的資料夾 · {{path}}","sandboxDrive.folderOnDriveDesc": "{{drive}} · {{path}}","sandboxDrive.manageEnvironments": "環境",- "sandboxDrive.pickerInfoTooltip": "選擇您的磁碟上的資料夾,其檔案會在對話間保留。若無,沙盒將是臨時的。","sandboxDrive.pickerTitle": "工作目錄","sandboxDrive.root": "磁碟根目錄","sandboxDrive.upsell": "將檔案保存在磁碟上",- "sandboxEnvironment.empty": "尚無環境。在環境中創建一個。",- "sandboxEnvironment.hint": "在第一次命令之前,會在工作目錄中克隆並設置一次。已經有檔案的資料夾將保持原樣。","sandboxEnvironment.loadFailed": "無法載入環境","sandboxEnvironment.loading": "載入環境中…","sandboxEnvironment.missing": "環境不可用",- "sandboxEnvironment.none": "無環境","sandboxEnvironment.noneDesc": "從空的工作目錄開始","sandboxEnvironment.retry": "重試","sandboxEnvironment.saveFailed": "無法更改環境。請再試一次。",- "sandboxEnvironment.title": "環境","sandboxStorage.allCopiesBusy": "每個副本都在使用中","sandboxStorage.buildFailed": "未構建","sandboxStorage.building": "正在構建",diff --git a/locales/zh-TW/project.json b/locales/zh-TW/project.jsonindex e028cdc7367..3c13fabeb6c 100644--- a/locales/zh-TW/project.json+++ b/locales/zh-TW/project.json@@ -318,8 +318,6 @@"settings.deviceOnline": "設備已連線","settings.directoryDescription": "選擇一個資料夾並開始一個主題。Ajan 將與連接裝置中該資料夾的檔案一起工作。","settings.directoryUnavailable": "設備已斷線或目錄不可用。連接設備並檢查路徑,然後重試。",- "settings.environmentDescription": "將儲存庫來源集中在一個環境中,然後在您的設備上新增一個資料夾以開始工作。",- "settings.environments": "環境","settings.general": "一般","settings.generalDescription": "管理專案名稱、地址和描述。","settings.identifier": "專案識別碼",@@ -334,7 +332,6 @@"settings.members": "成員","settings.nameHint": "最多使用 255 個字元。","settings.noDirectories": "此環境中尚無資料夾。在已連接的設備上新增現有資料夾以開始工作。",- "settings.noEnvironments": "尚未關聯任何環境","settings.noRepository": "未連結 GitHub 儲存庫","settings.reuseEnvironment": "將現有環境新增到此專案","settings.reuseEnvironmentDescription": "已建立環境?選擇它以將其儲存庫配置連結到此專案,然後為此專案新增工作目錄。",diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.jsonindex 113381e2b07..8a53d17259c 100644--- a/locales/zh-TW/setting.json+++ b/locales/zh-TW/setting.json@@ -691,12 +691,8 @@"environments.create": "新建環境","environments.createFailed": "無法創建環境","environments.desc": "沙盒運行所需的環境:一個存儲庫、其設置、其變數。每個從中構建的副本在會話之間保留自己的文件。",- "environments.detail.close": "關閉",- "environments.detail.initializerDesc": "當選擇一個工作目錄用於對話時應用一次:儲存庫將被克隆到該目錄並執行設置命令。","environments.detail.noRepository": "無儲存庫","environments.detail.noSetup": "無設置命令",- "environments.detail.tabs.overview": "概覽",- "environments.detail.tabs.settings": "設置","environments.duplicateName": "您已經有一個同名的環境","environments.empty": "尚無環境","environments.emptyPublished": "此工作區尚未發布任何內容",diff --git a/packages/builtin-tool-cloud-sandbox/src/workspace.test.ts b/packages/builtin-tool-cloud-sandbox/src/workspace.test.tsindex 44feca851ca..84445fdca96 100644--- a/packages/builtin-tool-cloud-sandbox/src/workspace.test.ts+++ b/packages/builtin-tool-cloud-sandbox/src/workspace.test.ts@@ -119,3 +119,49 @@ describe('the three placements a run can have', () => {).not.toContain(persisted);});});++describe('the repositories of the environment', () => {+ it('tells a temporary run which repository its working directory checks out', () => {+ const { sandbox_workspace } = formatSandboxStoragePromptVariables({+ repositories: [{ ref: 'canary', repository: 'lobehub/lobehub' }],+ });++ expect(sandbox_workspace).toContain(+ 'Your working directory is a checkout of `lobehub/lobehub` (`canary`)',+ );+ expect(sandbox_workspace).toContain('AGENTS.md');+ });++ it('lists several side by side and says the top is not a repository', () => {+ const { sandbox_workspace } = formatSandboxStoragePromptVariables({+ repositories: [+ { folder: 'lobehub', repository: 'lobehub/lobehub' },+ { folder: 'lobe-ui', repository: 'lobehub/lobe-ui' },+ ],+ });++ expect(sandbox_workspace).toContain('checks out 2 repositories side by side');+ expect(sandbox_workspace).toContain('`lobehub/` — `lobehub/lobehub`');+ expect(sandbox_workspace).toContain('`lobe-ui/` — `lobehub/lobe-ui`');+ expect(sandbox_workspace).toContain('The working directory itself is not a git repository');+ });++ it('adds the same lines on a persistent run', () => {+ const { sandbox_workspace } = formatSandboxStoragePromptVariables({+ mode: 'persistent',+ repositories: [+ { folder: 'a', repository: 'o/a' },+ { folder: 'b', repository: 'o/b' },+ ],+ });++ expect(sandbox_workspace).toContain('environment directory');+ expect(sandbox_workspace).toContain('`b/` — `o/b`');+ });++ it('says nothing about repositories when there are none', () => {+ const { sandbox_workspace } = formatSandboxStoragePromptVariables();+ expect(sandbox_workspace).not.toContain('side by side');+ expect(sandbox_workspace).not.toContain('checkout of');+ });+});diff --git a/packages/builtin-tool-cloud-sandbox/src/workspace.ts b/packages/builtin-tool-cloud-sandbox/src/workspace.tsindex a8390bad882..16638b6ff2f 100644--- a/packages/builtin-tool-cloud-sandbox/src/workspace.ts+++ b/packages/builtin-tool-cloud-sandbox/src/workspace.ts@@ -289,6 +289,52 @@ export interface SandboxStoragePromptVariables {sandbox_workspace: string;}+/** A repository the environment checks out into the working directory. */+export interface SandboxRepositoryPromptInput {+ /** The folder it is checked out into, relative to the working directory; absent for the top. */+ folder?: string;+ /** Branch or tag; absent for the repository's default branch. */+ ref?: string;+ /** `owner/name`, or the checkout url for anything but GitHub. */+ repository: string;+}++/**+ * What the model is told about the repositories in its working directory.+ *+ * They are cloned the first time a command runs, so they are not there to be+ * discovered before the first call, and nothing else names them: without this+ * the model learns the layout from a clone log. With several, the working+ * directory itself is not a repository, which is the one thing a model reaching+ * for `git status` at the top would otherwise get wrong — and each repository+ * carries its own `AGENTS.md`, which no injection reads, since nothing is+ * cloned yet when the prompt is built.+ */+export const formatSandboxRepositoriesPrompt = (+ repositories: SandboxRepositoryPromptInput[] | undefined,+): string[] => {+ if (!repositories?.length) return [];++ const describe = ({ ref, repository }: SandboxRepositoryPromptInput) =>+ `\`${repository}\`${ref ? ` (\`${ref}\`)` : ''}`;++ if (repositories.length === 1) {+ const [only] = repositories;+ return [+ only.folder+ ? `- This project's environment checks out ${describe(only)} into \`${only.folder}/\` of your working directory when your first command runs. Work on it there, and read its \`AGENTS.md\` / \`CLAUDE.md\` before changing anything when it has one.`+ : `- Your working directory is a checkout of ${describe(only)}, cloned by this project's environment when your first command runs. Read its \`AGENTS.md\` / \`CLAUDE.md\` before changing anything when it has one.`,+ ];+ }++ return [+ `- This project's environment checks out ${repositories.length} repositories side by side in your working directory when your first command runs:`,+ ...repositories.map((item) => ` - \`${item.folder ?? '.'}/\` — ${describe(item)}`),+ '- The working directory itself is not a git repository. Run git, installs, builds and tests inside the folder of the repository they belong to, and commit to each repository separately.',+ "- Each repository may have its own `AGENTS.md` / `CLAUDE.md`; read the one in a repository's folder before changing anything there.",+ ];+};+export interface SandboxStoragePromptInput {/*** The folder the run works in, relative to the drive's root; absent on a@@ -296,6 +342,8 @@ export interface SandboxStoragePromptInput {*/cwd?: string;mode?: SandboxMode;+ /** The repositories the environment checks out, in order; see {@link formatSandboxRepositoriesPrompt}. */+ repositories?: SandboxRepositoryPromptInput[];/*** Where commands actually start when that is not {@link cwd}: the checkout* on the machine's own disk, for an instance built from a repository. The@@ -310,8 +358,10 @@ export interface SandboxStoragePromptInput {export const formatSandboxStoragePromptVariables = ({cwd,mode = DEFAULT_SANDBOX_MODE,+ repositories,workingDir,}: SandboxStoragePromptInput = {}): SandboxStoragePromptVariables => {+ const repositoryLines = formatSandboxRepositoriesPrompt(repositories);if (!isPersistentSandboxMode(mode)) {return {sandbox_session_files: '- Files from previous sessions may not persist',@@ -323,6 +373,7 @@ export const formatSandboxStoragePromptVariables = ({// What the disposable sandbox is FOR, so the model neither treats it as// somewhere to keep things nor apologizes for it on a coding task.'- This is a temporary sandbox, discarded after use: results and intermediate files are not kept once it is gone. It suits coding on a repository and one-off data processing, where nothing along the way needs keeping. Anything the user wants to keep has to leave the sandbox — export finished files with `exportFile`.',+ ...repositoryLines,].join('\n'),};}@@ -385,6 +436,7 @@ export const formatSandboxStoragePromptVariables = ({// platform treats as scratch.'- The drive is network storage: fine for source files, results and notes, but slow for the thousands of small files a package install or a build writes. Keep the drive for what is worth keeping.','- It has a storage quota, which covers what you leave on the drive.',+ ...repositoryLines,].join('\n'),};};diff --git a/packages/database/src/core/testCleanup.ts b/packages/database/src/core/testCleanup.tsnew file mode 100644index 00000000000..e5b50e6b002--- /dev/null+++ b/packages/database/src/core/testCleanup.ts@@ -0,0 +1,26 @@+import { inArray } from 'drizzle-orm';++import { releaseProjectEnvironments } from '../models/utils/projectEnvironmentCleanup';+import { environmentInstances, environments, projectEnvironments, users } from '../schemas';+import type { LobeChatDatabase } from '../type';++/**+ * Deletes test users the way account deletion does: every project has its own+ * environment, and `environments.user_id` is `restrict`, so the environments of+ * the users' projects are released first. Without ids, every user goes, and so+ * does every environment.+ */+export const deleteTestUsers = async (db: LobeChatDatabase, ids?: string[]) => {+ if (ids) {+ for (const userId of ids) await releaseProjectEnvironments(db, { userId });+ await db.delete(users).where(inArray(users.id, ids));+ return;+ }++ // A test that deleted a project directly leaves its environment behind,+ // standalone, still holding its user: every environment goes.+ await db.delete(projectEnvironments);+ await db.delete(environmentInstances);+ await db.delete(environments);+ await db.delete(users);+};diff --git a/packages/database/src/models/__tests__/acceptance.coverage.test.ts b/packages/database/src/models/__tests__/acceptance.coverage.test.tsindex 38b7631e16b..e33d1e0f495 100644--- a/packages/database/src/models/__tests__/acceptance.coverage.test.ts+++ b/packages/database/src/models/__tests__/acceptance.coverage.test.ts@@ -1,8 +1,8 @@// @vitest-environment node-import { inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { deleteTestUsers } from '../../core/testCleanup';import { ProjectRepository } from '../../repositories/project';import { topics, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';@@ -20,7 +20,7 @@ beforeEach(async () => {afterEach(async () => {// Acceptances, projects and topics all cascade with their owner.- await serverDB.delete(users).where(inArray(users.id, [userId]));+ await deleteTestUsers(serverDB, [userId]);});describe('AcceptanceModel coverage', () => {diff --git a/packages/database/src/models/__tests__/acceptance.test.ts b/packages/database/src/models/__tests__/acceptance.test.tsindex 88db0a3faf3..9c5c7b15ced 100644--- a/packages/database/src/models/__tests__/acceptance.test.ts+++ b/packages/database/src/models/__tests__/acceptance.test.ts@@ -4,6 +4,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { deleteTestUsers } from '../../core/testCleanup';import { ProjectRepository } from '../../repositories/project';import {acceptanceComments,@@ -29,7 +30,7 @@ const otherUserId = 'acceptance-test-other';const topicId = 'acceptance-test-topic';beforeEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);await serverDB.insert(topics).values([{ id: topicId, userId }]);});@@ -38,7 +39,7 @@ afterEach(async () => {await serverDB.delete(verifyRuns);await serverDB.delete(acceptances);await serverDB.delete(topics);- await serverDB.delete(users);+ await deleteTestUsers(serverDB);});describe('AcceptanceModel', () => {diff --git a/packages/database/src/models/__tests__/acceptanceReview.replies.test.ts b/packages/database/src/models/__tests__/acceptanceReview.replies.test.tsindex a080ca51f15..4043be859da 100644--- a/packages/database/src/models/__tests__/acceptanceReview.replies.test.ts+++ b/packages/database/src/models/__tests__/acceptanceReview.replies.test.ts@@ -5,6 +5,7 @@ import { and, eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { deleteTestUsers } from '../../core/testCleanup';import { ProjectRepository } from '../../repositories/project';import {acceptanceComments,@@ -59,7 +60,7 @@ const markIdsOf = async (reviewId: string) => {};beforeEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);await serverDB.insert(users).values([{ id: owner }, { id: reviewer }]);await serverDB.insert(workspaces)@@ -85,7 +86,7 @@ beforeEach(async () => {});afterEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);await serverDB.delete(workspaces);});diff --git a/packages/database/src/models/__tests__/acceptanceReview.test.ts b/packages/database/src/models/__tests__/acceptanceReview.test.tsindex eaa7bd57a7b..d4eb40fcf39 100644--- a/packages/database/src/models/__tests__/acceptanceReview.test.ts+++ b/packages/database/src/models/__tests__/acceptanceReview.test.ts@@ -2,6 +2,7 @@import { beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { deleteTestUsers } from '../../core/testCleanup';import { ProjectRepository } from '../../repositories/project';import { tasks, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';@@ -38,7 +39,7 @@ const settings = { routeKey: '/settings', url: 'https://preview.example.com/settconst draftOf = (userId: string) => model.createDraft({ projectId, siteId, userId });beforeEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);await serverDB.insert(users).values([{ id: owner }, { id: reviewer }]);const project = await new ProjectRepository(serverDB, owner).create({identifier: 'FNT',diff --git a/packages/database/src/models/__tests__/project.coverage.test.ts b/packages/database/src/models/__tests__/project.coverage.test.tsindex 379295d7a61..832c647d533 100644--- a/packages/database/src/models/__tests__/project.coverage.test.ts+++ b/packages/database/src/models/__tests__/project.coverage.test.ts@@ -4,6 +4,7 @@ import { eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { deleteTestUsers } from '../../core/testCleanup';import { ProjectRepository } from '../../repositories/project';import { agents, projects, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';@@ -35,7 +36,7 @@ beforeEach(async () => {afterEach(async () => {vi.restoreAllMocks();// Projects, agents, project members and tasks cascade with their owner.- await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));+ await deleteTestUsers(serverDB, [userId, otherUserId]);});describe('ProjectModel coverage', () => {diff --git a/packages/database/src/models/__tests__/project.mainAgent.test.ts b/packages/database/src/models/__tests__/project.mainAgent.test.tsindex d3be9082d6e..408da35b082 100644--- a/packages/database/src/models/__tests__/project.mainAgent.test.ts+++ b/packages/database/src/models/__tests__/project.mainAgent.test.ts@@ -2,6 +2,7 @@ import { and, eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { deleteTestUsers } from '../../core/testCleanup';import { ProjectRepository } from '../../repositories/project';import {agentLabelAssignments,@@ -41,13 +42,13 @@ describe('the main agent a project creates', () => {const repo = new ProjectRepository(serverDB, userId);beforeEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);await serverDB.insert(users).values([{ id: userId }, { id: memberId }]);});afterEach(async () => {+ await deleteTestUsers(serverDB);await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));- await serverDB.delete(users);});it('is an ordinary agent named after the project, wearing its avatar and the Project label', async () => {diff --git a/packages/database/src/models/__tests__/project.repository.test.ts b/packages/database/src/models/__tests__/project.repository.test.tsindex c3d1146f2ea..7f4fbe86921 100644--- a/packages/database/src/models/__tests__/project.repository.test.ts+++ b/packages/database/src/models/__tests__/project.repository.test.ts@@ -1,8 +1,10 @@+import { eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';import { ProjectRepository } from '../../repositories/project';-import { environments, projectEnvironments, users, workspaces } from '../../schemas';+import { ProjectEnvironmentRepository } from '../../repositories/projectEnvironment';+import { environments, projectEnvironments, projects, users, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { EnvironmentModel } from '../environment';import type { CreateProjectInput } from '../project';@@ -26,19 +28,33 @@ describe('a project created from a GitHub repository', () => {const repo = new ProjectRepository(serverDB, userId);const model = new ProjectModel(serverDB, userId);+ // Only this file's own rows: other test files share the database and run at+ // the same time, and their environments hold their users back.+ const cleanup = async () => {+ const own = serverDB+ .select({ id: environments.id })+ .from(environments)+ .where(eq(environments.userId, userId));+ await serverDB+ .delete(projectEnvironments)+ .where(inArray(projectEnvironments.environmentId, own));+ await serverDB.delete(environments).where(eq(environments.userId, userId));+ await serverDB.delete(projects).where(eq(projects.userId, userId));+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));+ await serverDB.delete(users).where(eq(users.id, userId));+ };+beforeEach(async () => {- await serverDB.delete(users);+ await cleanup();await serverDB.insert(users).values([{ id: userId }]);});- afterEach(async () => {- await serverDB.delete(projectEnvironments);- await serverDB.delete(environments);- await serverDB.delete(workspaces);- await serverDB.delete(users);- });+ afterEach(cleanup);- it('creates a project from a GitHub repository with its environment attached', async () => {+ const environmentOf = (database: typeof serverDB, projectId: string, workspace?: string) =>+ new ProjectEnvironmentRepository(database, userId, workspace).get(projectId);++ it('creates a project from a GitHub repository with its own environment checking it out', async () => {const project = await createProject(repo, {name: 'lobehub',repository: {@@ -48,28 +64,74 @@ describe('a project created from a GitHub repository', () => {},});- expect(await model.listEnvironments(project.id)).toEqual([+ const environment = await environmentOf(serverDB, project.id);+ expect(environment).toEqual(expect.objectContaining({configuration: expect.objectContaining({kind: 'code',sources: [{ kind: 'git', ref: 'canary', url: 'https://github.com/lobehub/lobehub' }],}),- name: 'lobehub/lobehub',+ name: 'lobehub',+ projectId: project.id,}),- ]);+ );- // A second project on the same repository shares the definition.+ // A second project on the same repository gets an environment of its own.const second = await createProject(repo, {name: 'lobehub again',repository: { name: 'lobehub/lobehub', url: '[email protected]:lobehub/lobehub.git' },});- const [first] = await model.listEnvironments(project.id);- expect(await model.listEnvironments(second.id)).toEqual([- expect.objectContaining({ id: first.id }),+ const secondEnvironment = await environmentOf(serverDB, second.id);+ expect(secondEnvironment.id).not.toBe(environment.id);+ expect(secondEnvironment.projectId).toBe(second.id);+ });++ it('checks out more repositories beside the main one, side by side', async () => {+ const project = await createProject(repo, {+ additionalRepositories: [+ { url: 'https://github.com/lobehub/lobe-ui' },+ // The main one again is not checked out twice.+ { url: '[email protected]:lobehub/lobehub.git' },+ { defaultBranch: 'main', url: 'https://github.com/lobehub/lobe-icons.git' },+ ],+ name: 'Monorepo and friends',+ repository: {+ defaultBranch: 'canary',+ name: 'lobehub/lobehub',+ url: 'https://github.com/lobehub/lobehub',+ },+ });++ expect((await environmentOf(serverDB, project.id)).configuration.sources).toEqual([+ { kind: 'git', path: 'lobehub', ref: 'canary', url: 'https://github.com/lobehub/lobehub' },+ { kind: 'git', path: 'lobe-ui', url: 'https://github.com/lobehub/lobe-ui' },+ {+ kind: 'git',+ path: 'lobe-icons',+ ref: 'main',+ url: 'https://github.com/lobehub/lobe-icons',+ },]);});- it('publishes the repository of a shared workspace project instead of reusing a private one', async () => {+ it('creates an empty environment for a project made without a repository', async () => {+ const project = await createProject(repo, { name: 'Notes' });++ const links = await serverDB+ .select()+ .from(projectEnvironments)+ .where(eq(projectEnvironments.projectId, project.id));+ const environment = await environmentOf(serverDB, project.id);+ expect(links).toEqual([+ expect.objectContaining({ environmentId: environment.id, enabled: true, isDefault: true }),+ ]);+ expect(environment.configuration.sources ?? []).toEqual([]);+ // Two projects of the same name do not collide on the environment name.+ const again = await createProject(repo, { name: 'Notes', slug: 'notes-2' });+ expect((await environmentOf(serverDB, again.id)).name).toBe('Notes');+ });++ it('publishes the environment of a shared workspace project and keeps a private one private', async () => {await serverDB.insert(workspaces).values({id: workspaceId,name: 'Repository Workspace',@@ -77,13 +139,7 @@ describe('a project created from a GitHub repository', () => {slug: workspaceId,});const repository = { name: 'lobehub/lobehub', url: 'https://github.com/lobehub/lobehub' };- // The creator already checks the repository out privately.- const own = await new EnvironmentModel(serverDB, userId, workspaceId).ensureForRepository({- name: repository.name,- repositoryUrl: repository.url,- });const workspaceRepo = new ProjectRepository(serverDB, userId, workspaceId);- const workspaceModel = new ProjectModel(serverDB, userId, workspaceId);const shared = await createProject(workspaceRepo, {name: 'Shared',@@ -96,12 +152,23 @@ describe('a project created from a GitHub repository', () => {visibility: 'private',});- const [sharedEnvironment] = await workspaceModel.listEnvironments(shared.id);- expect(sharedEnvironment).toEqual(expect.objectContaining({ visibility: 'public' }));- expect(sharedEnvironment.id).not.toBe(own.id);- expect(await workspaceModel.listEnvironments(privateProject.id)).toEqual([- expect.objectContaining({ id: own.id, visibility: 'private' }),- ]);+ expect(await environmentOf(serverDB, shared.id, workspaceId)).toEqual(+ expect.objectContaining({ visibility: 'public' }),+ );+ expect(await environmentOf(serverDB, privateProject.id, workspaceId)).toEqual(+ expect.objectContaining({ visibility: 'private' }),+ );+ // Neither shows up among the standalone environments of「设置 → 环境」.+ expect(await new EnvironmentModel(serverDB, userId, workspaceId).query()).toEqual([]);+ });++ it('removes an unbuilt environment with its project', async () => {+ const project = await createProject(repo, { name: 'Short lived' });+ await environmentOf(serverDB, project.id);++ await repo.delete(project.id);++ expect(await serverDB.select().from(environments)).toEqual([]);});it('names the unique index a taken slug violates, so the router can map it', async () => {diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.tsindex 351471d358a..9d098fca747 100644--- a/packages/database/src/models/__tests__/project.test.ts+++ b/packages/database/src/models/__tests__/project.test.ts@@ -1,5 +1,3 @@-import { randomUUID } from 'node:crypto';-import { INBOX_SESSION_ID } from '@lobechat/const';import { and, eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -24,11 +22,11 @@ import {} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { AgentModel } from '../agent';-import { EnvironmentModel } from '../environment';import type { CreateProjectInput } from '../project';import { ProjectModel } from '../project';import { TaskModel } from '../task';import { TopicModel } from '../topic';+import { releaseProjectEnvironment } from '../utils/projectEnvironmentCleanup';const serverDB: LobeChatDatabase = await getTestDB();const userId = 'project-model-user';@@ -960,6 +958,8 @@ describe('ProjectModel', () => {const disappearing = await createProject(repo, { name: 'Disappearing' });const snapshot = await model.findManageableById(disappearing.id);+ // A concurrent delete, which releases the project's environment first.+ await releaseProjectEnvironment(serverDB, disappearing.id);await serverDB.delete(projects).where(eq(projects.id, disappearing.id));vi.spyOn(model, 'findManageableById').mockResolvedValueOnce(snapshot);expect(await model.updateStatus(disappearing.id, 'active')).toBeNull();@@ -979,36 +979,6 @@ describe('ProjectModel', () => {expect(await model.getEnabledKnowledgeBaseIdsForTask(standaloneTask.id)).toEqual([]);});- it('attaches environments and lists them per project in the owner scope', async () => {- const project = await createProject(repo, { name: 'Env host' });- const environmentModel = new EnvironmentModel(serverDB, userId);- const env = await environmentModel.save({- name: 'Shared GitHub',- repositoryUrl: 'https://github.com/lobehub/lobehub',- });- expect(await model.listEnvironments(project.id)).toEqual([]);- await model.attachEnvironment(project.id, env.id);- await model.attachEnvironment(project.id, env.id);- expect(await model.listEnvironments(project.id)).toEqual([- expect.objectContaining({ id: env.id }),- ]);- await expect(otherModel.attachEnvironment(project.id, env.id)).rejects.toThrow('access denied');- await expect(otherModel.listEnvironments(project.id)).rejects.toThrow('access denied');- await expect(model.attachEnvironment(project.id, randomUUID())).rejects.toThrow(- 'access denied',- );-- await expect(otherModel.detachEnvironment(project.id, env.id)).rejects.toThrow('access denied');- await model.detachEnvironment(project.id, env.id);- await model.detachEnvironment(project.id, env.id);- expect(await model.listEnvironments(project.id)).toEqual([]);- // Unlinking leaves the environment itself for the other places using it.- await model.attachEnvironment(project.id, env.id);- expect(await model.listEnvironments(project.id)).toEqual([- expect.objectContaining({ id: env.id }),- ]);- });-it('lists project conversations with or without directories, retaining each agent', async () => {const project = await createProject(repo, { name: 'Topics host' });const topicModel = new TopicModel(serverDB, userId);diff --git a/packages/database/src/models/__tests__/project.topicAgents.test.ts b/packages/database/src/models/__tests__/project.topicAgents.test.tsindex 0d27e8bf1ec..b9fedb79cdd 100644--- a/packages/database/src/models/__tests__/project.topicAgents.test.ts+++ b/packages/database/src/models/__tests__/project.topicAgents.test.ts@@ -3,6 +3,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { deleteTestUsers } from '../../core/testCleanup';import { ProjectRepository } from '../../repositories/project';import { agents, projectAgents, projects, topics, users, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';@@ -30,12 +31,12 @@ describe('project members from project topics', () => {const topicModel = new TopicModel(serverDB, userId);beforeEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);await serverDB.insert(users).values({ id: userId });});afterEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);});it('adds the agent of a topic created in the project', async () => {diff --git a/packages/database/src/models/__tests__/projectReview.test.ts b/packages/database/src/models/__tests__/projectReview.test.tsindex 5b667ff88c2..bc315d333c2 100644--- a/packages/database/src/models/__tests__/projectReview.test.ts+++ b/packages/database/src/models/__tests__/projectReview.test.ts@@ -2,6 +2,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';+import { deleteTestUsers } from '../../core/testCleanup';import { ProjectRepository } from '../../repositories/project';import { projectMembers, projectSites, users, workspaceMembers, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';@@ -16,7 +17,7 @@ const createProject = () =>new ProjectRepository(serverDB, ownerId).create({ identifier: 'SITE', name: 'Fieldnotes' });beforeEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);await serverDB.insert(users).values([{ email: '[email protected]', id: ownerId },{ email: '[email protected]', id: guestId },@@ -24,7 +25,7 @@ beforeEach(async () => {});afterEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);});describe('ProjectSiteModel', () => {diff --git a/packages/database/src/models/__tests__/projectWorkingDirectory.test.ts b/packages/database/src/models/__tests__/projectWorkingDirectory.test.tsindex 934108cc235..ccac68147c8 100644--- a/packages/database/src/models/__tests__/projectWorkingDirectory.test.ts+++ b/packages/database/src/models/__tests__/projectWorkingDirectory.test.ts@@ -114,19 +114,14 @@ describe('project directory queries', () => {expect(await runnable()).toBe(true);await expect(model.resolve(directory.id)).resolves.toBeTruthy();- // A disabled project-environment link keeps the directory listed, but a- // start there would be refused, so the row is not runnable.- await db- .update(projectEnvironments)- .set({ enabled: false })- .where(eq(projectEnvironments.projectId, base.projectId));+ // A disabled environment keeps the directory listed, but a start there+ // would be refused, so the row is not runnable.+ const { environmentId } = await model.resolve(directory.id);+ await db.update(environments).set({ enabled: false }).where(eq(environments.id, environmentId));expect(await runnable()).toBe(false);await expect(model.resolve(directory.id)).rejects.toThrow('disabled');- await db- .update(projectEnvironments)- .set({ enabled: true })- .where(eq(projectEnvironments.projectId, base.projectId));+ await db.update(environments).set({ enabled: true }).where(eq(environments.id, environmentId));await db.update(projectWorkingDirectories).set({ permission: 'readOnly' })diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.tsindex f86154b1624..6de88600656 100644--- a/packages/database/src/models/__tests__/task.test.ts+++ b/packages/database/src/models/__tests__/task.test.ts@@ -7,7 +7,7 @@ import {import { eq, sql } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';-import { getTestDB } from '../../core/getTestDB';+import { deleteTestUsers, getTestDB } from '../../../tests/test-utils';import { ProjectRepository } from '../../repositories/project';import {agents,@@ -41,12 +41,12 @@ const createTopic = async (id: string, uid = userId) => {};beforeEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);await serverDB.insert(users).values([{ id: userId }, { id: userId2 }]);});afterEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);});const testDocumentInput = (): typeof documents.$inferInsert => ({diff --git a/packages/database/src/models/environment.ts b/packages/database/src/models/environment.tsindex 98d5a097e0e..31abf9f72b7 100644--- a/packages/database/src/models/environment.ts+++ b/packages/database/src/models/environment.ts@@ -1,5 +1,5 @@import type { EnvironmentConfiguration, EnvironmentVisibility } from '@lobechat/types';-import { DEFAULT_REGENERABLE_PATHS } from '@lobechat/types';+import { DEFAULT_REGENERABLE_PATHS, layoutRepositorySources } from '@lobechat/types';import { and, asc, eq, isNull, sql } from 'drizzle-orm';import type { EnvironmentItem, NewEnvironment } from '../schemas';@@ -122,7 +122,11 @@ export class EnvironmentModel {return { userId: this.userId, workspaceId: this.workspaceId };}- /** Enabled environments visible in the current workspace scope. */+ /**+ * Enabled standalone environments visible in the current workspace scope. A+ * project's own environment is part of that project and is never offered+ * anywhere else.+ */async list() {return this.db.select({@@ -132,7 +136,13 @@ export class EnvironmentModel {visibility: environments.visibility,}).from(environments)- .where(and(buildWorkspaceWhere(this.scope(), environments), eq(environments.enabled, true)));+ .where(+ and(+ buildWorkspaceWhere(this.scope(), environments),+ eq(environments.enabled, true),+ isNull(environments.projectId),+ ),+ );}/** Enabled, workspace-visible lookup used when linking projects or binding directories. */@@ -214,6 +224,7 @@ export class EnvironmentModel {and(eq(environments.name, name.trim()),eq(environments.userId, this.userId),+ isNull(environments.projectId),buildWorkspaceWhere(this.scope(), environments),),);@@ -248,6 +259,7 @@ export class EnvironmentModel {and(this.ownership(),eq(environments.enabled, true),+ isNull(environments.projectId),sql`${environments.configuration} -> 'sources' @> ${JSON.stringify([{ kind: 'git', url }])}::jsonb`,input.visibility === 'public' ? eq(environments.visibility, 'public') : undefined,),@@ -327,7 +339,8 @@ export class EnvironmentModel {}).from(environments).leftJoin(users, eq(environments.userId, users.id))- .where(and(this.visible(), this.pool(visibility)))+ // Standalone ones only: a project's environment is edited on the project.+ .where(and(this.visible(), this.pool(visibility), isNull(environments.projectId))).orderBy(asc(environments.createdAt));return rows.map(({ creatorAvatar, creatorFullName, creatorId, creatorUsername, ...row }) => ({@@ -394,6 +407,9 @@ export class EnvironmentModel {// explicit empty list is a decision.configuration: {...params.configuration,+ ...(params.configuration?.sources && {+ sources: layoutRepositorySources(params.configuration.sources),+ }),excludePaths: params.configuration?.excludePaths ?? [...DEFAULT_REGENERABLE_PATHS],},description: params.description ?? null,@@ -409,14 +425,25 @@ export class EnvironmentModel {return row;};+ /**+ * The writes below change standalone environments only. A project's+ * environment is edited through the project (see+ * `ProjectEnvironmentRepository`), by whoever may change the project, and+ * removed with it — so here it answers as not found.+ */update = async (id: string,params: Partial<Pick<NewEnvironment, 'configuration' | 'description' | 'enabled' | 'name'>>,): Promise<EnvironmentItem | undefined> => {+ // Stored with the folders it is checked out into, so what the form shows+ // is what runs (see `layoutRepositorySources`).+ const configuration = params.configuration?.sources+ ? { ...params.configuration, sources: layoutRepositorySources(params.configuration.sources) }+ : params.configuration;const [row] = await this.db.update(environments)- .set({ ...params, updatedAt: new Date() })- .where(and(eq(environments.id, id), this.ownership()))+ .set({ ...params, ...(configuration && { configuration }), updatedAt: new Date() })+ .where(and(eq(environments.id, id), this.ownership(), isNull(environments.projectId))).returning();return row;@@ -438,7 +465,7 @@ export class EnvironmentModel {const [row] = await this.db.update(environments).set({ updatedAt: new Date(), visibility })- .where(and(eq(environments.id, id), this.ownership()))+ .where(and(eq(environments.id, id), this.ownership(), isNull(environments.projectId))).returning();return row;@@ -453,7 +480,7 @@ export class EnvironmentModel {delete = async (id: string): Promise<EnvironmentItem | undefined> => {const [row] = await this.db.delete(environments)- .where(and(eq(environments.id, id), this.ownership()))+ .where(and(eq(environments.id, id), this.ownership(), isNull(environments.projectId))).returning();return row;diff --git a/packages/database/src/models/project/index.ts b/packages/database/src/models/project/index.tsindex 21c49ccfd9e..d4dfeb279ad 100644--- a/packages/database/src/models/project/index.ts+++ b/packages/database/src/models/project/index.ts@@ -6,7 +6,6 @@ import { and, asc, desc, eq, inArray, isNull, ne, or, sql } from 'drizzle-orm';import { agents } from '../../schemas/agent';import { channelMembers } from '../../schemas/channel';import { chatGroupsAgents } from '../../schemas/chatGroup';-import { environments } from '../../schemas/environment';import { knowledgeBases } from '../../schemas/file';import {projectAgents,@@ -14,7 +13,6 @@ import {projectKnowledgeBases,projects,} from '../../schemas/project';-import { projectEnvironments } from '../../schemas/projectEnvironment';import { projectWorks } from '../../schemas/projectWork';import { agentsToSessions } from '../../schemas/relations';import { tasks } from '../../schemas/task';@@ -31,13 +29,13 @@ import {normalizeWorkspaceId,} from '../../utils/workspace';import { AgentModel } from '../agent';-import { EnvironmentModel } from '../environment';import {isProjectIdentifierConflict,normalizeProjectIdentifier,ProjectIdentifierTakenError,} from '../projectIdentifier';import { topicHasGoal } from '../topicGoal';+import { releaseProjectEnvironment } from '../utils/projectEnvironmentCleanup';import type { ProjectAgentInput, ProjectAgentPatch } from './agents';import {deleteProjectAgent,@@ -51,6 +49,8 @@ export { normalizeProjectIdentifier, ProjectIdentifierTakenError } from '../projexport type { ProjectAgentInput, ProjectAgentPatch } from './agents';export interface CreateProjectInput {+ /** More repositories the project's environment checks out beside `repository`. */+ additionalRepositories?: { defaultBranch?: string; url: string }[];avatar?: string;/** Lead the project with an existing agent instead of creating one named after it. */coordinatorAgentId?: string;@@ -250,6 +250,17 @@ export class ProjectModel {* coordinator provisioned for it, which belongs to another aggregate.*/async delete(id: string) {+ const [manageable] = await this.db+ .select({ id: projects.id })+ .from(projects)+ .where(and(eq(projects.id, id), this.manageable()));+ if (!manageable) return null;++ // `environments.project_id` is `restrict`: the project's environment is+ // dealt with first, whichever path deletes the project. Callers that need+ // both steps atomic run this inside their transaction+ // (`ProjectRepository.delete` does).+ await releaseProjectEnvironment(this.db, id);const [deleted] = await this.db.delete(projects).where(and(eq(projects.id, id), this.manageable()))@@ -974,74 +985,6 @@ export class ProjectModel {};}- /** Link an existing environment to a project; re-attaching is a no-op. */- async attachEnvironment(projectId: string, environmentId: string) {- if (!(await this.findManageableById(projectId)))- throw new Error('Project not found or access denied');- const environment = await new EnvironmentModel(- this.db,- this.userId,- this.workspaceId,- ).findEnabledById(environmentId);- if (!environment) throw new Error('Environment not found or access denied');- await this.db- .insert(projectEnvironments)- .values({- projectId,- environmentId,- workspaceId: this.workspaceId,- addedByUserId: this.userId,- })- .onConflictDoNothing();- return { projectId, environmentId };- }-- /**- * Unlink an environment from a project. The environment itself stays — it is- * shared by every project that lists it — and so do the project's folders- * and conversations made from it; unlinking twice is a no-op.- */- async detachEnvironment(projectId: string, environmentId: string) {- if (!(await this.findManageableById(projectId)))- throw new Error('Project not found or access denied');- await this.db- .delete(projectEnvironments)- .where(- and(- eq(projectEnvironments.projectId, projectId),- eq(projectEnvironments.environmentId, environmentId),- ),- );- return { projectId, environmentId };- }-- /** Enabled environments linked to this project. */- async listEnvironments(projectId: string) {- if (!(await this.findById(projectId))) throw new Error('Project not found or access denied');- return this.db- .select({- id: environments.id,- name: environments.name,- configuration: environments.configuration,- visibility: environments.visibility,- })- .from(environments)- .innerJoin(- projectEnvironments,- and(- eq(projectEnvironments.environmentId, environments.id),- eq(projectEnvironments.projectId, projectId),- eq(projectEnvironments.enabled, true),- ),- )- .where(- and(- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, environments),- eq(environments.enabled, true),- ),- );- }-/** All conversations belonging to the project, with or without a working directory. */async listTopics(projectId: string) {if (!(await this.findById(projectId))) throw new Error('Project not found or access denied');diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.tsindex b97132538c3..9b50390f96e 100644--- a/packages/database/src/models/user.ts+++ b/packages/database/src/models/user.ts@@ -38,6 +38,7 @@ import type { LobeChatDatabase } from '../type';import { notTrashed } from '../utils/softDelete';import { hasLiveParentTopic } from '../utils/topicVisibility';import { AGENT_TRANSFER_PENDING_OWNER_DELETE, AgentTransferJobModel } from './agentTransferJob';+import { releaseProjectEnvironments } from './utils/projectEnvironmentCleanup';type DecryptUserKeyVaults = (encryptKeyVaultsStr: string | null,@@ -707,6 +708,10 @@ export class UserModel {.delete(taskLabels).where(and(eq(taskLabels.userId, id), isNull(taskLabels.workspaceId)));await applyRemainingTimeout();+ // The projects cascade away with the account; their environments would+ // otherwise hold it back through `environments.user_id`.+ await releaseProjectEnvironments(tx as unknown as LobeChatDatabase, { userId: id });+ await applyRemainingTimeout();const result = await tx.delete(users).where(eq(users.id, id));if (deadline !== undefined && Date.now() >= deadline)throw new Error('Account deletion transaction deadline exceeded');diff --git a/packages/database/src/models/utils/projectEnvironmentCleanup.ts b/packages/database/src/models/utils/projectEnvironmentCleanup.tsnew file mode 100644index 00000000000..00d7ee6b7df--- /dev/null+++ b/packages/database/src/models/utils/projectEnvironmentCleanup.ts@@ -0,0 +1,91 @@+import { count, eq, sql } from 'drizzle-orm';++import { environmentInstances, environments, projectEnvironments } from '../../schemas';+import type { LobeChatDatabase } from '../../type';++/**+ * Clears the way for an account or workspace deletion through the environments+ * of the projects it takes with it.+ *+ * Every project has an environment of its own, and `environments.user_id` /+ * `workspace_id` are `restrict` — deliberately, because an environment that was+ * built from has storage on the execution plane that someone must remove first.+ * One nothing was built from has nothing outside this database, so it goes with+ * its project instead of blocking the deletion; one with instances still blocks+ * it, as every environment did before.+ *+ * For an account, a project environment its user made in someone else's+ * project (possible only for rows migrated from linked environments) is handed+ * to that project's owner rather than removed: the project outlives the+ * account.+ *+ * Two statements, not one: the links reference the environments with+ * `restrict`, which is checked per statement.+ */+export const releaseProjectEnvironments = async (+ db: LobeChatDatabase,+ scope: { userId: string } | { workspaceId: string },+) => {+ if ('userId' in scope) {+ await db.execute(sql`+ UPDATE environments e SET user_id = p.user_id, updated_at = now()+ FROM projects p+ WHERE e.project_id = p.id AND e.user_id = ${scope.userId} AND p.user_id <> ${scope.userId}+ `);+ }++ const owned =+ 'userId' in scope+ ? sql`e.user_id = ${scope.userId}`+ : sql`e.workspace_id = ${scope.workspaceId}`;+ const unbuilt = sql`+ SELECT e.id FROM environments e+ WHERE e.project_id IS NOT NULL AND ${owned}+ AND NOT EXISTS (SELECT 1 FROM environment_instances i WHERE i.environment_id = e.id)+ `;++ await db.execute(sql`DELETE FROM project_environments WHERE environment_id IN (${unbuilt})`);+ await db.execute(sql`DELETE FROM environments WHERE id IN (${unbuilt})`);+};++/**+ * Deals with a project's environment before the project row goes —+ * `environments.project_id` is `restrict`, so the project cannot be deleted+ * while its environment still points at it.+ *+ * Nothing built from it: the environment goes, with its links. Something+ * built: it stays, standalone, for its creator to clean up from+ * 「设置 → 环境」 — its builds live on the execution plane, and dropping the+ * row first would leave storage nobody can name. It is released under a name+ * of its own (`<name> (<id prefix>)`), since its project-derived name may+ * already belong to a standalone environment of the same creator.+ */+export const releaseProjectEnvironment = async (db: LobeChatDatabase, projectId: string) => {+ const [own] = await db+ .select()+ .from(environments)+ .where(eq(environments.projectId, projectId))+ .limit(1);+ if (!own) return;++ const [{ value: instances }] = await db+ .select({ value: count() })+ .from(environmentInstances)+ .where(eq(environmentInstances.environmentId, own.id));++ if (instances === 0) {+ await db.delete(projectEnvironments).where(eq(projectEnvironments.environmentId, own.id));+ await db.delete(environments).where(eq(environments.id, own.id));+ return;+ }++ const suffix = ` (${own.id.slice(0, 8)})`;+ await db+ .update(environments)+ .set({+ name: `${own.name.slice(0, 255 - suffix.length)}${suffix}`,+ projectId: null,+ updatedAt: new Date(),+ })+ .where(eq(environments.id, own.id));+};diff --git a/packages/database/src/repositories/project/index.ts b/packages/database/src/repositories/project/index.tsindex c3402778878..64f24dea6dd 100644--- a/packages/database/src/repositories/project/index.ts+++ b/packages/database/src/repositories/project/index.ts@@ -1,7 +1,8 @@+import { layoutRepositorySources } from '@lobechat/types';import { eq, max } from 'drizzle-orm';import { AgentModel } from '../../models/agent';-import { EnvironmentModel } from '../../models/environment';+import { normalizeProjectRepository } from '../../models/environment';import type { CreateProjectInput, ProjectModelOptions } from '../../models/project';import {normalizeProjectIdentifier,@@ -10,8 +11,8 @@ import {} from '../../models/project';import { createProjectMainAgent } from '../../models/projectMainAgent';import { projectAgents, projectCompletionReviews } from '../../schemas/project';-import { projectEnvironments } from '../../schemas/projectEnvironment';import type { LobeChatDatabase } from '../../type';+import { ProjectEnvironmentRepository } from '../projectEnvironment';/*** Cross-aggregate write flow for projects. Creating a project also creates (or@@ -32,7 +33,12 @@ export class ProjectRepository {return new ProjectModel(db, this.userId, this.workspaceId, this.options);}- async create({ dedicatedAgentId, repository, ...input }: CreateProjectInput) {+ async create({+ additionalRepositories,+ dedicatedAgentId,+ repository,+ ...input+ }: CreateProjectInput) {const identifier = normalizeProjectIdentifier(input.identifier);return this.db.transaction(async (tx) => {@@ -75,33 +81,25 @@ export class ProjectRepository {});await this.linkCoordinator(db, project.id, mainAgent.id);- // The environment belongs to another aggregate too, and a repository the- // environment cannot accept must not leave a half-made project behind, so- // it is created in the same transaction.- //- // A workspace-public main agent applies published environments only, so- // its repository is published too; reusing the creator's private one- // would link a repository the project's conversations never check out.- if (repository) {- const publish =- !!this.workspaceId && (mainAgent as { visibility?: string }).visibility === 'public';- const environment = await new EnvironmentModel(- db,- this.userId,- this.workspaceId,- ).ensureForRepository({- defaultBranch: repository.defaultBranch,- name: repository.name,- repositoryUrl: repository.url,- ...(publish && { visibility: 'public' as const }),- });- await db.insert(projectEnvironments).values({- addedByUserId: this.userId,- environmentId: environment.id,- projectId: project.id,- workspaceId: this.workspaceId,- });- }+ // Every project has its own environment, made with it in the same+ // transaction so a repository it cannot accept leaves no half-made+ // project behind. One made from a repository checks it out; any other+ // starts with nothing to check out and is filled in from the project's+ // settings.+ const repositories = [...(repository ? [repository] : []), ...(additionalRepositories ?? [])];+ const seen = new Set<string>();+ const sources = repositories.flatMap((item) => {+ const url = normalizeProjectRepository(item.url);+ if (seen.has(url)) return [];+ seen.add(url);+ const ref = item.defaultBranch?.trim();+ return [{ kind: 'git' as const, url, ...(ref && { ref }) }];+ });+ await ProjectEnvironmentRepository.createForProject(+ db,+ project,+ sources.length > 0 ? { sources: layoutRepositorySources(sources) } : {},+ );return project;});@@ -119,6 +117,7 @@ export class ProjectRepository {const project = await projectModel.findManageableById(id);if (!project) return null;+ // Also releases the project's environment (see `ProjectModel.delete`).const deleted = await projectModel.delete(id);// Asked after the delete, so this project no longer counts as one still using it.const agentId = project.coordinatorAgentId;diff --git a/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts b/packages/database/src/repositories/projectCoordinator/__tests__/index.test.tsindex 342ef816de4..98b21c24300 100644--- a/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts+++ b/packages/database/src/repositories/projectCoordinator/__tests__/index.test.ts@@ -2,6 +2,7 @@ import { and, eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';+import { deleteTestUsers } from '../../../core/testCleanup';import { AgentModel } from '../../../models/agent';import { ProjectModel } from '../../../models/project';import { TaskModel } from '../../../models/task';@@ -49,12 +50,12 @@ const createLegacyProject = async (name: string) => {describe('ProjectCoordinatorRepository.replaceCoordinator', () => {beforeEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);});afterEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);});it('hands a dedicated coordinator history to the new main agent, then deletes it', async () => {diff --git a/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts b/packages/database/src/repositories/projectDirectory/__tests__/index.test.tsindex e629eb9feea..056c220298c 100644--- a/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts+++ b/packages/database/src/repositories/projectDirectory/__tests__/index.test.ts@@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';import { EnvironmentModel } from '../../../models/environment';-import { ProjectModel } from '../../../models/project';import { ProjectWorkingDirectoryModel } from '../../../models/projectWorkingDirectory';import { TopicModel } from '../../../models/topic';import {@@ -18,6 +17,7 @@ import {users,workspaces,} from '../../../schemas';+import { ProjectEnvironmentRepository } from '../../projectEnvironment';import { ProjectDirectoryRepository } from '../index';const db = await getTestDB();@@ -96,18 +96,29 @@ describe('ProjectDirectoryRepository.bind', () => {repositoryUrl: '[email protected]:lobehub/lobehub.git',});const row = await directoryModel.resolve(directory.id);- expect(row.configuration).toEqual({- sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobehub' }],- });+ expect(row.configuration).toEqual(+ expect.objectContaining({+ sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobehub' }],+ }),+ );await db.update(environments).set({ configuration: {} }).where(eq(environments.id, row.environmentId));const [instance] = await db.select().from(environmentInstances);expect(instance.configurationSnapshot).toEqual(row.configuration);- await expect(- repo.bind({ ...base, repositoryUrl: 'https://github.com/other/repo' }),- ).rejects.toThrow('Repository differs');+ // Another checkout bound to the project adds its repository to the+ // project's one environment; the folder already built keeps its snapshot.+ await repo.bind({ ...base, repositoryUrl: 'https://github.com/other/repo' });+ const [environment] = await db+ .select()+ .from(environments)+ .where(eq(environments.id, row.environmentId));+ expect(environment.configuration.sources).toEqual([+ { kind: 'git', url: 'https://github.com/other/repo' },+ ]);+ const [unchanged] = await db.select().from(environmentInstances);+ expect(unchanged.configurationSnapshot).toEqual(row.configuration);});it('isolates devices even when their path matches', async () => {@@ -129,9 +140,11 @@ describe('ProjectDirectoryRepository.bind', () => {.update(environments).set({ configuration: { sources: [{ kind: 'git', url: 'https://github.com/other/repo' }] } }).where(eq(environments.id, row.environmentId));- expect((await directoryModel.resolve(directory.id)).configuration).toEqual({- sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobehub' }],- });+ expect((await directoryModel.resolve(directory.id)).configuration).toEqual(+ expect.objectContaining({+ sources: [{ kind: 'git', url: 'https://github.com/lobehub/lobehub' }],+ }),+ );});it('does not expose or change another user’s project or device', async () => {@@ -145,36 +158,44 @@ describe('ProjectDirectoryRepository.bind', () => {await expect(repo.bind({ ...base, deviceId: 'private-device' })).rejects.toThrow();});- it('reuses an attached environment and keeps its instance snapshot across updates', async () => {- const projectModel = new ProjectModel(db, userId);- const env = await new EnvironmentModel(db, userId).save({- name: 'Shared GitHub',- repositoryUrl: '[email protected]:lobehub/lobehub.git',+ it("binds every folder to the project's own environment", async () => {+ const own = await new ProjectEnvironmentRepository(db, userId).get(base.projectId);+ const first = await directoryModel.resolve((await repo.bind(base)).id);+ const second = await directoryModel.resolve(+ (await repo.bind({ ...base, name: 'Other', path: '/work/other' })).id,+ );+ expect(first.environmentId).toBe(own.id);+ expect(second.environmentId).toBe(own.id);+ // A standalone environment the client names is not linked in its place.+ const standalone = await new EnvironmentModel(db, userId).save({ name: 'Standalone' });+ const third = await repo.bind({+ ...base,+ environmentId: standalone.id,+ name: 'Third',+ path: '/work/third',});- await projectModel.attachEnvironment(base.projectId, env.id);- const binding = await repo.bind({ ...base, environmentId: env.id });- const bound = await directoryModel.resolve(binding.id);- const [before] = await db- .select()- .from(environmentInstances)- .where(eq(environmentInstances.id, bound.instanceId!));- await new EnvironmentModel(db, userId).save({- id: env.id,- name: 'Updated resource',- repositoryUrl: 'https://github.com/lobehub/new-repo',- });- const [after] = await db- .select()- .from(environmentInstances)- .where(eq(environmentInstances.id, bound.instanceId!));- expect(after.configurationSnapshot).toEqual(before.configurationSnapshot);+ expect((await directoryModel.resolve(third.id)).environmentId).toBe(own.id);+ expect(+ await db+ .select()+ .from(projectEnvironments)+ .where(eq(projectEnvironments.projectId, base.projectId)),+ ).toEqual([expect.objectContaining({ environmentId: own.id })]);});- it('reports a disabled environment of the same name instead of hitting its unique index', async () => {- const env = await new EnvironmentModel(db, userId).save({ name: base.name });- await db.update(environments).set({ enabled: false }).where(eq(environments.id, env.id));- await expect(repo.bind(base)).rejects.toThrow('Environment is disabled');- expect(await db.select().from(environments)).toHaveLength(1);+ it("refuses a folder another project's environment already built", async () => {+ await repo.bind(base);+ await db.insert(agents).values({ id: 'second-coordinator', userId });+ await db.insert(projects).values({+ coordinatorAgentId: 'second-coordinator',+ id: 'second-project',+ identifier: 'SEC',+ name: 'Second project',+ userId,+ });+ await expect(repo.bind({ ...base, projectId: 'second-project' })).rejects.toThrow(+ 'belongs to another environment',+ );});it('rejects filing conversations for an agent fixed to another execution target', async () => {@@ -501,7 +522,11 @@ describe('ProjectDirectoryRepository.moveTopic', () => {name: 'Other project',userId,});- const foreign = await repo.bind({ ...second, projectId: 'other-project' });+ const foreign = await repo.bind({+ ...second,+ path: '/work/foreign',+ projectId: 'other-project',+ });await pinnedTopic(first.id);await expect(repo.moveTopic('to-move', foreign.id)).rejects.toThrow();await db.update(topics).set({ status: 'running' }).where(eq(topics.id, 'to-move'));diff --git a/packages/database/src/repositories/projectDirectory/index.ts b/packages/database/src/repositories/projectDirectory/index.tsindex 8573e5eb8d7..3727658eaf2 100644--- a/packages/database/src/repositories/projectDirectory/index.ts+++ b/packages/database/src/repositories/projectDirectory/index.ts@@ -3,7 +3,7 @@ import { getWorkingDirSourcePath } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { and, eq, inArray, isNull } from 'drizzle-orm';-import { EnvironmentModel, normalizeProjectRepository } from '../../models/environment';+import { normalizeProjectRepository } from '../../models/environment';import { EnvironmentInstanceModel } from '../../models/environmentInstance';import { ProjectModel } from '../../models/project';import {@@ -11,16 +11,11 @@ import {ProjectWorkingDirectoryModel,} from '../../models/projectWorkingDirectory';import { hasLiveTaskCallbackReservation } from '../../models/topic';-import {- agents,- devices,- projectEnvironments,- projectWorkingDirectories,- topics,-} from '../../schemas';+import { agents, devices, environments, projectWorkingDirectories, topics } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { joinTopicAgentsToProjects } from '../../utils/projectTopicAgents';import { buildWorkspaceWhere } from '../../utils/workspace';+import { mergeRepositories, ProjectEnvironmentRepository } from '../projectEnvironment';/*** A refused directory write. It carries its tRPC code, so a permission or@@ -87,6 +82,7 @@ export interface RelocateProjectDirectoryInput {export interface BindProjectDirectoryInput {agentId?: string;deviceId: string;+ /** Ignored: a folder always works in the project's own environment. Kept for older clients. */environmentId?: string;name: string;path: string;@@ -125,12 +121,10 @@ export class ProjectDirectoryRepository {}async bind(input: BindProjectDirectoryInput) {- await this.assertManageableProject(input.projectId);+ const project = await this.assertManageableProject(input.projectId);return this.db.transaction(async (tx) => {const db = tx as LobeChatDatabase;- const environmentModel = new EnvironmentModel(db, this.userId, this.workspaceId);const instanceModel = new EnvironmentInstanceModel(db, this.userId, this.workspaceId);- const projectModel = new ProjectModel(db, this.userId, this.workspaceId);const directoryModel = new ProjectWorkingDirectoryModel(db, this.userId, this.workspaceId);// Serialize bindings of the same device, including bindings from different projects.const [device] = await db@@ -147,45 +141,29 @@ export class ProjectDirectoryRepository {? normalizeProjectRepository(input.repositoryUrl): undefined;const existing = await instanceModel.findByDeviceAndDirectory(device.id, path);- let instance = existing;- let environment;- // An environment is the definition; an instance is one materialization of- // it. So the same project bound on a second device reuses the definition- // the first binding made and adds its own instance, rather than minting a- // second environment under the same name — which is both what the- // (user, scope, name) unique indexes require and what the two concepts- // already meant.- const knownId = existing?.environmentId ?? input.environmentId;- const named = knownId ? undefined : await environmentModel.findByName(input.name);- const environmentId = knownId ?? named?.id;- if (environmentId) {- environment = await environmentModel.findEnabledById(environmentId);- // The name lookup deliberately sees disabled rows, because the unique- // indexes do: a disabled environment of this name still owns the name,- // so minting a replacement would only hit the constraint.- if (!environment && named)- throw new ProjectDirectoryError('BAD_REQUEST', 'Environment is disabled');- if (!environment || (input.environmentId && input.environmentId !== environment.id))- throw new ProjectDirectoryError(- 'CONFLICT',- 'This directory belongs to another environment',- );- if (- repositoryUrl &&- !environment.configuration.sources?.some(- (source) => source.kind === 'git' && source.url === repositoryUrl,- )- )- throw new ProjectDirectoryError(- 'CONFLICT',- 'Repository differs from the existing environment',- );- } else {- environment = await environmentModel.save({- name: input.name,- repositoryUrl: input.repositoryUrl,- });+ // A folder works in the project's own environment — the only one it has.+ // A folder some other environment already built is that one's.+ let environment = await ProjectEnvironmentRepository.ensure(db, project);+ if (existing && existing.environmentId !== environment.id)+ throw new ProjectDirectoryError(+ 'CONFLICT',+ 'This directory belongs to another environment',+ );+ // A folder that is a checkout of a repository the environment does not+ // list yet adds it, the same as adding it on the project's settings.+ if (repositoryUrl) {+ const configuration = mergeRepositories(environment.configuration, [+ { sources: [{ kind: 'git', url: repositoryUrl }] },+ ]);+ if (configuration !== environment.configuration) {+ [environment] = await db+ .update(environments)+ .set({ configuration, updatedAt: new Date() })+ .where(eq(environments.id, environment.id))+ .returning();+ }}+ let instance = existing;if (!instance) {instance = await instanceModel.createForDeviceBinding({configurationSnapshot: environment.configuration,@@ -197,18 +175,6 @@ export class ProjectDirectoryRepository {}if (!instance.enabled)throw new ProjectDirectoryError('BAD_REQUEST', 'Environment instance is disabled');- await projectModel.attachEnvironment(input.projectId, environment.id);- const [link] = await db- .select()- .from(projectEnvironments)- .where(- and(- eq(projectEnvironments.projectId, input.projectId),- eq(projectEnvironments.environmentId, environment.id),- ),- );- if (!link.enabled)- throw new ProjectDirectoryError('BAD_REQUEST', 'Environment is disabled in this project');const prior = await directoryModel.findByLocation(input.projectId, device.id, path);const directory =prior ??diff --git a/packages/database/src/repositories/projectEnvironment/__tests__/index.test.ts b/packages/database/src/repositories/projectEnvironment/__tests__/index.test.tsnew file mode 100644index 00000000000..c7177d5465a--- /dev/null+++ b/packages/database/src/repositories/projectEnvironment/__tests__/index.test.ts@@ -0,0 +1,436 @@+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { EnvironmentModel } from '../../../models/environment';+import { ProjectModel } from '../../../models/project';+import { UserModel } from '../../../models/user';+import {+ agents,+ devices,+ environmentInstances,+ environments,+ projectEnvironments,+ projects,+ projectWorkingDirectories,+ users,+ workspaces,+} from '../../../schemas';+import { WorkspaceDeletionRepository } from '../../workspaceDeletion';+import { mergeRepositories, ProjectEnvironmentRepository } from '../index';++const db = await getTestDB();+const userId = 'project-env-user';+const otherUserId = 'project-env-other';+const repo = new ProjectEnvironmentRepository(db, userId);++const insertProject = async (id: string, name = id) => {+ await db+ .insert(agents)+ .values({ id: `${id}-agent`, userId })+ .onConflictDoNothing();+ const [project] = await db+ .insert(projects)+ .values({ coordinatorAgentId: `${id}-agent`, id, name, userId })+ .returning();+ return project;+};++const insertEnvironment = async (name: string, urls: string[]) => {+ const [environment] = await db+ .insert(environments)+ .values({+ configuration: { kind: 'code', sources: urls.map((url) => ({ kind: 'git' as const, url })) },+ name,+ userId,+ })+ .returning();+ return environment;+};++const link = (+ projectId: string,+ environmentId: string,+ extra: { isDefault?: boolean; sortOrder?: number } = {},+) => db.insert(projectEnvironments).values({ environmentId, projectId, ...extra });++const linksOf = (projectId: string) =>+ db.select().from(projectEnvironments).where(eq(projectEnvironments.projectId, projectId));++beforeEach(async () => {+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);+});++afterEach(async () => {+ await db.delete(projectWorkingDirectories);+ await db.delete(projectEnvironments);+ await db.delete(environmentInstances);+ await db.delete(environments);+ await db.delete(projects);+ await db.delete(devices);+ await db.delete(agents);+ await db.delete(workspaces);+ await db.delete(users);+});++describe('mergeRepositories', () => {+ it('appends missing repositories and lays several out side by side', () => {+ const merged = mergeRepositories(+ { sources: [{ kind: 'git', url: 'https://github.com/a/one' }] },+ [+ { sources: [{ kind: 'git', url: 'https://github.com/a/one' }] },+ { sources: [{ kind: 'git', ref: 'dev', url: 'https://github.com/a/two.git' }] },+ ],+ );+ expect(merged.sources).toEqual([+ { kind: 'git', path: 'one', url: 'https://github.com/a/one' },+ { kind: 'git', path: 'two', ref: 'dev', url: 'https://github.com/a/two.git' },+ ]);+ });++ it('returns the same object when there is nothing to add', () => {+ const into = { sources: [{ kind: 'git' as const, url: 'https://github.com/a/one' }] };+ expect(mergeRepositories(into, [into, null])).toBe(into);+ });+});++describe('ProjectEnvironmentRepository.ensure (existing projects)', () => {+ it('gives a project with no environment an empty one of its own', async () => {+ const project = await insertProject('empty');++ const environment = await repo.get(project.id);++ expect(environment).toMatchObject({ name: 'empty', projectId: project.id });+ expect(environment.configuration.sources ?? []).toEqual([]);+ expect(await linksOf(project.id)).toEqual([+ expect.objectContaining({ environmentId: environment.id, isDefault: true }),+ ]);+ });++ it('takes over an environment only this project links, merging the others into it', async () => {+ const project = await insertProject('legacy');+ const main = await insertEnvironment('main', ['https://github.com/a/main']);+ const extra = await insertEnvironment('extra', ['https://github.com/a/extra']);+ await link(project.id, extra.id, { sortOrder: 0 });+ await link(project.id, main.id, { isDefault: true, sortOrder: 1 });++ const environment = await repo.get(project.id);++ expect(environment.id).toBe(main.id);+ expect(environment.projectId).toBe(project.id);+ expect(environment.configuration.sources).toEqual([+ { kind: 'git', path: 'main', url: 'https://github.com/a/main' },+ { kind: 'git', path: 'extra', url: 'https://github.com/a/extra' },+ ]);+ expect(await linksOf(project.id)).toEqual([+ expect.objectContaining({ environmentId: main.id, isDefault: true }),+ ]);+ // Nothing is deleted: the environment it stopped linking stays standalone.+ const [kept] = await db.select().from(environments).where(eq(environments.id, extra.id));+ expect(kept.projectId).toBeNull();+ expect((await new EnvironmentModel(db, userId).query()).map((row) => row.id)).toEqual([+ extra.id,+ ]);+ });++ it('makes a new environment from one another project shares, leaving the other project alone', async () => {+ const first = await insertProject('first');+ const second = await insertProject('second');+ const shared = await insertEnvironment('shared', ['https://github.com/a/shared']);+ await link(first.id, shared.id, { isDefault: true });+ await link(second.id, shared.id, { isDefault: true });++ const environment = await repo.get(first.id);++ expect(environment.id).not.toBe(shared.id);+ expect(environment.configuration.sources).toEqual([+ { kind: 'git', url: 'https://github.com/a/shared' },+ ]);+ expect(await linksOf(second.id)).toEqual([+ expect.objectContaining({ environmentId: shared.id }),+ ]);++ // The second one, now the only project linking it, takes it over.+ expect((await repo.get(second.id)).id).toBe(shared.id);+ });++ it("moves a folder used only by this project to the project's environment", async () => {+ const project = await insertProject('folders');+ const other = await insertProject('other-folders');+ const main = await insertEnvironment('main', []);+ const extra = await insertEnvironment('extra', ['https://github.com/a/extra']);+ await link(project.id, main.id, { isDefault: true });+ await link(project.id, extra.id);+ await link(other.id, extra.id);+ const [device] = await db+ .insert(devices)+ .values({ deviceId: 'env-device', identitySource: 'fallback', platform: 'linux', userId })+ .returning();+ const instance = (path: string) => ({+ configurationSnapshot: {},+ deviceId: device.id,+ environmentId: extra.id,+ kind: 'device' as const,+ name: path,+ workingDirectory: path,+ });+ const [mine, shared] = await db+ .insert(environmentInstances)+ .values([instance('/work/mine'), instance('/work/shared')])+ .returning();+ await db.insert(projectWorkingDirectories).values([+ { deviceId: device.id, name: 'mine', path: '/work/mine', projectId: project.id },+ { deviceId: device.id, name: 'shared', path: '/work/shared', projectId: project.id },+ { deviceId: device.id, name: 'shared', path: '/work/shared', projectId: other.id },+ ]);++ const environment = await repo.get(project.id);++ const rows = await db.select().from(environmentInstances);+ expect(rows.find((row) => row.id === mine.id)?.environmentId).toBe(environment.id);+ expect(rows.find((row) => row.id === shared.id)?.environmentId).toBe(extra.id);+ });++ it('keeps the link to an environment holding a folder shared with another project', async () => {+ const project = await insertProject('shared-folder');+ const other = await insertProject('shared-folder-other');+ const main = await insertEnvironment('main', []);+ const extra = await insertEnvironment('extra', ['https://github.com/a/extra']);+ await link(project.id, main.id, { isDefault: true });+ await link(project.id, extra.id);+ await link(other.id, extra.id, { isDefault: true });+ const [device] = await db+ .insert(devices)+ .values({ deviceId: 'shared-device', identitySource: 'fallback', platform: 'linux', userId })+ .returning();+ const [instance] = await db+ .insert(environmentInstances)+ .values({+ configurationSnapshot: {},+ deviceId: device.id,+ environmentId: extra.id,+ kind: 'device',+ name: 'shared',+ workingDirectory: '/work/shared',+ })+ .returning();+ await db.insert(projectWorkingDirectories).values([+ { deviceId: device.id, name: 'shared', path: '/work/shared', projectId: project.id },+ { deviceId: device.id, name: 'shared', path: '/work/shared', projectId: other.id },+ ]);++ const environment = await repo.get(project.id);++ // The folder stays where it was built, and this project still reaches it.+ const [row] = await db+ .select()+ .from(environmentInstances)+ .where(eq(environmentInstances.id, instance.id));+ expect(row.environmentId).toBe(extra.id);+ expect(await linksOf(project.id)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ environmentId: environment.id, isDefault: true }),+ expect.objectContaining({ environmentId: extra.id, isDefault: false }),+ ]),+ );+ // Settled as it is: reading again changes nothing.+ expect((await repo.get(project.id)).id).toBe(environment.id);+ expect(await linksOf(project.id)).toHaveLength(2);+ });++ it('moves a folder that a link names as its default instance', async () => {+ const project = await insertProject('default-instance');+ const main = await insertEnvironment('main', []);+ const extra = await insertEnvironment('extra', ['https://github.com/a/extra']);+ const [device] = await db+ .insert(devices)+ .values({ deviceId: 'default-device', identitySource: 'fallback', platform: 'linux', userId })+ .returning();+ const [instance] = await db+ .insert(environmentInstances)+ .values({+ configurationSnapshot: {},+ deviceId: device.id,+ environmentId: extra.id,+ kind: 'device',+ name: 'mine',+ workingDirectory: '/work/default',+ })+ .returning();+ await link(project.id, main.id, { isDefault: true });+ await db+ .insert(projectEnvironments)+ .values({ defaultInstanceId: instance.id, environmentId: extra.id, projectId: project.id });+ await db.insert(projectWorkingDirectories).values({+ deviceId: device.id,+ name: 'mine',+ path: '/work/default',+ projectId: project.id,+ });++ const environment = await repo.get(project.id);++ const [row] = await db+ .select()+ .from(environmentInstances)+ .where(eq(environmentInstances.id, instance.id));+ expect(row.environmentId).toBe(environment.id);+ });++ it("follows the project's name after a rename", async () => {+ const project = await insertProject('renamed', 'Before');+ await repo.get(project.id);+ await db.update(projects).set({ name: 'After' }).where(eq(projects.id, project.id));++ expect((await repo.get(project.id)).name).toBe('After');+ });++ it('is idempotent and changes nothing on a settled project', async () => {+ const project = await insertProject('settled');+ const first = await repo.get(project.id);+ const second = await repo.get(project.id);++ expect(second).toEqual(first);+ expect(await db.select().from(environments)).toHaveLength(1);+ expect(await linksOf(project.id)).toHaveLength(1);+ });+});++describe('ProjectEnvironmentRepository.update', () => {+ it('lets whoever may change the project edit its environment, and nobody else', async () => {+ const project = await insertProject('editable');+ await repo.get(project.id);++ const updated = await repo.update(project.id, {+ configuration: {+ bootstrapCommand: 'pnpm i',+ sources: [+ { kind: 'git', url: 'https://github.com/a/one' },+ { kind: 'git', path: 'two', url: 'https://github.com/a/two' },+ ],+ },+ });+ expect(updated.configuration.sources).toHaveLength(2);+ expect(updated.configuration.bootstrapCommand).toBe('pnpm i');++ const stranger = new ProjectEnvironmentRepository(db, otherUserId);+ await expect(stranger.update(project.id, { configuration: {} })).rejects.toThrow(+ 'access denied',+ );+ await expect(stranger.get(project.id)).rejects.toThrow('access denied');+ });++ it('is refused by the standalone environment writes', async () => {+ const project = await insertProject('guarded');+ const environment = await repo.get(project.id);+ const model = new EnvironmentModel(db, userId);++ expect(await model.update(environment.id, { name: 'renamed' })).toBeUndefined();+ expect(await model.delete(environment.id)).toBeUndefined();+ });+});++describe('ProjectEnvironmentRepository.addRepositories', () => {+ it('adds only the repositories the environment does not check out yet', async () => {+ const project = await insertProject('adds');+ await repo.update(project.id, {+ configuration: { sources: [{ kind: 'git', url: 'https://github.com/a/one' }] },+ });++ const environment = await repo.addRepositories(project.id, [+ { sources: [{ kind: 'git', url: 'https://github.com/a/one' }] },+ { bootstrapCommand: 'ignored', sources: [{ kind: 'git', url: 'https://github.com/a/two' }] },+ ]);++ expect(environment.configuration.sources).toEqual([+ { kind: 'git', path: 'one', url: 'https://github.com/a/one' },+ { kind: 'git', path: 'two', url: 'https://github.com/a/two' },+ ]);+ expect(environment.configuration.bootstrapCommand).toBeUndefined();+ });+});++describe('deleting a project', () => {+ it('releases a built environment as standalone under a name that cannot collide', async () => {+ const project = await insertProject('released', 'Same name');+ const own = await repo.get(project.id);+ // A standalone environment already holds the project-derived name.+ await insertEnvironment('Same name', []);+ const [device] = await db+ .insert(devices)+ .values({+ deviceId: 'released-device',+ identitySource: 'fallback',+ platform: 'linux',+ userId,+ })+ .returning();+ await db.insert(environmentInstances).values({+ configurationSnapshot: {},+ deviceId: device.id,+ environmentId: own.id,+ kind: 'device',+ name: 'built',+ workingDirectory: '/work/released',+ });++ expect(await new ProjectModel(db, userId).delete(project.id)).toMatchObject({ id: project.id });++ const [released] = await db.select().from(environments).where(eq(environments.id, own.id));+ expect(released.projectId).toBeNull();+ expect(released.name).toBe(`Same name (${own.id.slice(0, 8)})`);+ });+});++describe('deleting what owns a project', () => {+ it('deletes an account together with the environments of its projects', async () => {+ const project = await insertProject('doomed');+ await repo.get(project.id);++ await UserModel.deleteUser(db, userId);++ expect(await db.select().from(environments)).toEqual([]);+ });++ it('still refuses while a project environment has something built from it', async () => {+ const project = await insertProject('built');+ const environment = await repo.get(project.id);+ const [device] = await db+ .insert(devices)+ .values({ deviceId: 'built-device', identitySource: 'fallback', platform: 'linux', userId })+ .returning();+ await db.insert(environmentInstances).values({+ configurationSnapshot: {},+ deviceId: device.id,+ environmentId: environment.id,+ kind: 'device',+ name: 'built',+ workingDirectory: '/work/built',+ });++ await expect(UserModel.deleteUser(db, userId)).rejects.toThrow();+ });++ it('deletes a workspace together with the environments of its projects', async () => {+ await db+ .insert(workspaces)+ .values({ id: 'env-ws', name: 'ws', primaryOwnerId: userId, slug: 'env-ws' });+ await db.insert(agents).values({ id: 'ws-agent', userId, workspaceId: 'env-ws' });+ const [project] = await db+ .insert(projects)+ .values({+ coordinatorAgentId: 'ws-agent',+ id: 'ws-project',+ name: 'ws project',+ userId,+ workspaceId: 'env-ws',+ })+ .returning();+ await new ProjectEnvironmentRepository(db, userId, 'env-ws').get(project.id);++ await new WorkspaceDeletionRepository(db, userId).delete('env-ws');++ expect(await db.select().from(workspaces)).toEqual([]);+ expect(await db.select().from(environments)).toEqual([]);+ });+});diff --git a/packages/database/src/repositories/projectEnvironment/index.ts b/packages/database/src/repositories/projectEnvironment/index.tsnew file mode 100644index 00000000000..b651d5bda5f--- /dev/null+++ b/packages/database/src/repositories/projectEnvironment/index.ts@@ -0,0 +1,499 @@+import type { EnvironmentConfiguration, EnvironmentSource } from '@lobechat/types';+import { DEFAULT_REGENERABLE_PATHS, layoutRepositorySources } from '@lobechat/types';+import { and, asc, desc, eq, inArray, ne, notExists } from 'drizzle-orm';++import { ProjectModel } from '../../models/project';+import {+ environmentInstances,+ type EnvironmentItem,+ environments,+ projectEnvironments,+ projects,+ projectWorkingDirectories,+} from '../../schemas';+import type { LobeChatDatabase } from '../../type';++/** The project columns its environment is derived from. */+export interface ProjectEnvironmentOwner {+ id: string;+ name: string;+ userId: string;+ visibility: string;+ workspaceId: string | null;+}++/** What a project's environment may change from the project's settings. */+export interface ProjectEnvironmentPatch {+ configuration?: EnvironmentConfiguration;+ description?: string | null;+}++/**+ * Who sees a project's environment follows the project: in a workspace-public+ * project every member's conversation checks it out, so it is published with+ * it; anything else stays private to its creator. A personal row has no other+ * state.+ */+export const projectEnvironmentVisibility = (project: ProjectEnvironmentOwner) =>+ project.workspaceId && project.visibility === 'public' ? 'public' : 'private';++const gitSources = (configuration: EnvironmentConfiguration | null | undefined) =>+ (configuration?.sources ?? []).filter(+ (source): source is Extract<EnvironmentSource, { kind: 'git' }> => source.kind === 'git',+ );++/**+ * The repositories of `from` that `into` lacks, appended to it. A repository+ * already there (by url) is not added twice. Once there is more than one, they+ * are laid out side by side (see `layoutRepositorySources`).+ */+export const mergeRepositories = (+ into: EnvironmentConfiguration,+ from: (EnvironmentConfiguration | null | undefined)[],+): EnvironmentConfiguration => {+ const sources = [...(into.sources ?? [])];+ const known = new Set(gitSources(into).map((source) => source.url));+ for (const configuration of from) {+ for (const source of gitSources(configuration)) {+ if (known.has(source.url)) continue;+ known.add(source.url);+ sources.push(source);+ }+ }+ if (sources.length === (into.sources ?? []).length) return into;++ return { ...into, sources: layoutRepositorySources(sources) };+};++/**+ * Every project has exactly one environment, made with the project and edited+ * on the project's own settings: the repositories it checks out (any number,+ * or none), the setup that makes them usable, and the variables every command+ * sees. It is `environments.project_id`, linked by the project's single+ * `project_environments` row so that the directory and run paths that resolve+ * through that link keep working unchanged.+ *+ * A project from before this rule — several linked environments, one shared+ * with other projects, or none — is brought to it by {@link ensure}, the first+ * time anything asks for its environment, and by the backfill script for the+ * rest. Nothing is deleted on the way: an environment the project stops+ * linking stays in「设置 → 环境」, where it already was.+ */+export class ProjectEnvironmentRepository {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ private projectModel() {+ return new ProjectModel(this.db, this.userId, this.workspaceId);+ }++ /** The environment of a project the caller can read. */+ async get(projectId: string): Promise<EnvironmentItem> {+ const project = await this.projectModel().findById(projectId);+ if (!project) throw new Error('Project not found or access denied');++ return ProjectEnvironmentRepository.ensure(this.db, project);+ }++ /**+ * Edits the environment of a project the caller can manage. Anyone who may+ * change the project may change its environment — it is part of the+ * project, not a row of its creator's that the project borrows — so the+ * write is scoped by the project rather than by the environment's owner.+ * The name follows the project and is not editable here.+ */+ async update(projectId: string, patch: ProjectEnvironmentPatch): Promise<EnvironmentItem> {+ const project = await this.projectModel().findManageableById(projectId);+ if (!project) throw new Error('Project not found or access denied');++ const environment = await ProjectEnvironmentRepository.ensure(this.db, project);+ const [row] = await this.db+ .update(environments)+ .set({+ ...(patch.configuration && {+ configuration: patch.configuration.sources+ ? {+ ...patch.configuration,+ sources: layoutRepositorySources(patch.configuration.sources),+ }+ : patch.configuration,+ }),+ ...(patch.description !== undefined && { description: patch.description }),+ updatedAt: new Date(),+ })+ .where(and(eq(environments.id, environment.id), eq(environments.projectId, project.id)))+ .returning();++ return row;+ }++ /**+ * Adds to the environment of a project the caller can manage the+ * repositories these definitions check out that it does not yet, laid out+ * side by side. What else they define is not taken.+ */+ async addRepositories(+ projectId: string,+ from: (EnvironmentConfiguration | null | undefined)[],+ ): Promise<EnvironmentItem> {+ const project = await this.projectModel().findManageableById(projectId);+ if (!project) throw new Error('Project not found or access denied');++ const environment = await ProjectEnvironmentRepository.ensure(this.db, project);+ const configuration = mergeRepositories(environment.configuration, from);+ if (configuration === environment.configuration) return environment;++ return this.update(projectId, { configuration });+ }++ /**+ * Makes a new project's environment, in the caller's transaction. It always+ * makes a new one: a project made from a repository checks that repository+ * out, any other starts with nothing to check out.+ */+ static async createForProject(+ db: LobeChatDatabase,+ project: ProjectEnvironmentOwner,+ configuration: EnvironmentConfiguration = {},+ ): Promise<EnvironmentItem> {+ const [environment] = await db+ .insert(environments)+ .values({+ configuration: {+ kind: 'code',+ ...configuration,+ excludePaths: configuration.excludePaths ?? [...DEFAULT_REGENERABLE_PATHS],+ },+ name: project.name,+ projectId: project.id,+ userId: project.userId,+ visibility: projectEnvironmentVisibility(project),+ workspaceId: project.workspaceId,+ })+ .returning();+ await db.insert(projectEnvironments).values({+ addedByUserId: project.userId,+ environmentId: environment.id,+ isDefault: true,+ projectId: project.id,+ workspaceId: project.workspaceId,+ });++ return environment;+ }++ /**+ * The project's environment, bringing a project from before the+ * one-environment rule to it first. Idempotent, and a no-op beyond one read+ * for a project that already follows it.+ *+ * 1. Its environment is the first linked one (the default, else the first in+ * order) when no other project links that one too; otherwise a new one is+ * made from that one's definition, or empty when nothing was linked.+ * 2. The repositories of every other linked environment are merged into it.+ * 3. A device folder of this project's — and of no other project's — that an+ * other linked environment built is moved to it, so the folder keeps+ * running. A folder another project also uses stays where it is.+ * 4. The other links are removed — except one whose environment still holds+ * a folder this project shares, kept as a non-default link so the folder+ * keeps resolving. The environments themselves stay in「设置 → 环境」.+ * 5. Its name follows the project's.+ */+ static async ensure(+ database: LobeChatDatabase,+ project: ProjectEnvironmentOwner,+ ): Promise<EnvironmentItem> {+ const [settled] = await database+ .select()+ .from(environments)+ .where(eq(environments.projectId, project.id))+ .limit(1);+ if (settled && (await ProjectEnvironmentRepository.isSettled(database, project, settled)))+ return settled;++ return database.transaction(async (tx) => {+ const db = tx as LobeChatDatabase;+ // Two first reads of the same project must not both make one.+ await db+ .select({ id: projects.id })+ .from(projects)+ .where(eq(projects.id, project.id))+ .for('update');++ const linked = await db+ .select({ environment: environments, link: projectEnvironments })+ .from(projectEnvironments)+ .innerJoin(environments, eq(environments.id, projectEnvironments.environmentId))+ .where(eq(projectEnvironments.projectId, project.id))+ .orderBy(+ desc(projectEnvironments.isDefault),+ asc(projectEnvironments.sortOrder),+ asc(projectEnvironments.createdAt),+ );++ let [own] = await db+ .select()+ .from(environments)+ .where(eq(environments.projectId, project.id))+ .limit(1);++ if (!own) {+ const primary = linked.find(({ environment }) => !environment.projectId)?.environment;+ const claimable =+ primary &&+ !(await ProjectEnvironmentRepository.linkedElsewhere(db, primary.id, project.id));+ if (claimable) {+ [own] = await db+ .update(environments)+ .set({ projectId: project.id, updatedAt: new Date() })+ .where(eq(environments.id, primary.id))+ .returning();+ } else {+ [own] = await db+ .insert(environments)+ .values({+ configuration: primary?.configuration ?? {+ excludePaths: [...DEFAULT_REGENERABLE_PATHS],+ kind: 'code',+ },+ description: primary?.description ?? null,+ name: project.name,+ projectId: project.id,+ userId: project.userId,+ visibility: projectEnvironmentVisibility(project),+ workspaceId: project.workspaceId,+ })+ .returning();+ }+ }++ const others = linked+ .map(({ environment }) => environment)+ .filter((environment) => environment.id !== own.id);++ const configuration = mergeRepositories(+ own.configuration,+ others.map((environment) => environment.configuration),+ );+ const visibility = projectEnvironmentVisibility(project);+ // The name follows the project: it is not editable on its own, so a+ // renamed project brings its environment's name along.+ if (+ configuration !== own.configuration ||+ own.visibility !== visibility ||+ own.name !== project.name+ ) {+ [own] = await db+ .update(environments)+ .set({ configuration, name: project.name, updatedAt: new Date(), visibility })+ .where(eq(environments.id, own.id))+ .returning();+ }++ if (others.length > 0) {+ const otherIds = others.map((environment) => environment.id);+ await ProjectEnvironmentRepository.moveFolders(db, project.id, own.id, otherIds);+ // A folder this project shares with another one stays in the+ // environment that built it (moving it would take it from the other+ // project), and a folder resolves only through an environment its+ // project links — so that link stays, as a non-default one. Every+ // other link goes.+ const kept = await ProjectEnvironmentRepository.foldersHeldBy(db, project.id, otherIds);+ const dropped = otherIds.filter((id) => !kept.has(id));+ if (kept.size > 0)+ await db+ .update(projectEnvironments)+ .set({ isDefault: false, updatedAt: new Date() })+ .where(+ and(+ eq(projectEnvironments.projectId, project.id),+ inArray(projectEnvironments.environmentId, [...kept]),+ ),+ );+ if (dropped.length > 0)+ await db+ .delete(projectEnvironments)+ .where(+ and(+ eq(projectEnvironments.projectId, project.id),+ inArray(projectEnvironments.environmentId, dropped),+ ),+ );+ }++ await db+ .insert(projectEnvironments)+ .values({+ addedByUserId: project.userId,+ environmentId: own.id,+ isDefault: true,+ projectId: project.id,+ workspaceId: project.workspaceId,+ })+ .onConflictDoUpdate({+ set: { enabled: true, isDefault: true, updatedAt: new Date() },+ target: [projectEnvironments.projectId, projectEnvironments.environmentId],+ });++ return own;+ });+ }++ /**+ * Removes a deleted project's environment when nothing was built from it.+ * One that has instances stays, standalone, for its creator to clean up from+ * 「设置 → 环境」: its builds live on the execution plane, and dropping the row+ * first would leave storage nobody can name.+ */+ /**+ * Whether a project already follows the rule: its own environment, named and+ * published as the project is, is its enabled default link, and any other+ * link is a non-default one kept for a folder it shares with another project.+ */+ private static async isSettled(+ db: LobeChatDatabase,+ project: ProjectEnvironmentOwner,+ own: EnvironmentItem,+ ) {+ if (own.visibility !== projectEnvironmentVisibility(project) || own.name !== project.name)+ return false;++ const links = await db+ .select({+ environmentId: projectEnvironments.environmentId,+ isDefault: projectEnvironments.isDefault,+ enabled: projectEnvironments.enabled,+ })+ .from(projectEnvironments)+ .where(eq(projectEnvironments.projectId, project.id));++ const ownLink = links.find((link) => link.environmentId === own.id);+ if (!ownLink?.isDefault || !ownLink.enabled) return false;++ const others = links.filter((link) => link.environmentId !== own.id);+ if (others.length === 0) return true;+ if (others.some((link) => link.isDefault)) return false;++ const kept = await ProjectEnvironmentRepository.foldersHeldBy(+ db,+ project.id,+ others.map((link) => link.environmentId),+ );+ return others.every((link) => kept.has(link.environmentId));+ }++ /**+ * Which of these environments still hold the instance behind one of this+ * project's device folders — the ones {@link moveFolders} left in place+ * because another project uses the same folder.+ */+ private static async foldersHeldBy(+ db: LobeChatDatabase,+ projectId: string,+ environmentIds: string[],+ ): Promise<Set<string>> {+ if (environmentIds.length === 0) return new Set();+ const rows = await db+ .selectDistinct({ environmentId: environmentInstances.environmentId })+ .from(environmentInstances)+ .innerJoin(+ projectWorkingDirectories,+ and(+ eq(projectWorkingDirectories.deviceId, environmentInstances.deviceId),+ eq(projectWorkingDirectories.path, environmentInstances.workingDirectory),+ eq(projectWorkingDirectories.projectId, projectId),+ ),+ )+ .where(+ and(+ inArray(environmentInstances.environmentId, environmentIds),+ eq(environmentInstances.kind, 'device'),+ ),+ );+ return new Set(rows.map((row) => row.environmentId));+ }++ private static async linkedElsewhere(+ db: LobeChatDatabase,+ environmentId: string,+ projectId: string,+ ) {+ const [row] = await db+ .select({ id: projectEnvironments.id })+ .from(projectEnvironments)+ .where(+ and(+ eq(projectEnvironments.environmentId, environmentId),+ ne(projectEnvironments.projectId, projectId),+ ),+ )+ .limit(1);++ return !!row;+ }++ /**+ * Re-homes the device instances behind this project's folders from the+ * environments it stops linking to its own, so each folder keeps resolving+ * through the project's link. An instance behind a folder of another project+ * too stays: moving it would take the folder away from that project.+ */+ private static async moveFolders(+ db: LobeChatDatabase,+ projectId: string,+ environmentId: string,+ fromEnvironmentIds: string[],+ ) {+ const folders = await db+ .select({ id: environmentInstances.id })+ .from(environmentInstances)+ .innerJoin(+ projectWorkingDirectories,+ and(+ eq(projectWorkingDirectories.deviceId, environmentInstances.deviceId),+ eq(projectWorkingDirectories.path, environmentInstances.workingDirectory),+ eq(projectWorkingDirectories.projectId, projectId),+ ),+ )+ .where(+ and(+ inArray(environmentInstances.environmentId, fromEnvironmentIds),+ eq(environmentInstances.kind, 'device'),+ notExists(+ db+ .select({ id: projectWorkingDirectories.id })+ .from(projectWorkingDirectories)+ .where(+ and(+ eq(projectWorkingDirectories.deviceId, environmentInstances.deviceId),+ eq(projectWorkingDirectories.path, environmentInstances.workingDirectory),+ ne(projectWorkingDirectories.projectId, projectId),+ ),+ ),+ ),+ ),+ );+ if (folders.length === 0) return;+ const moved = folders.map((folder) => folder.id);++ // A link may name a moved instance as its default, through a foreign key+ // on (environment, instance): left as it is, the move would break it.+ await db+ .update(projectEnvironments)+ .set({ defaultInstanceId: null, updatedAt: new Date() })+ .where(inArray(projectEnvironments.defaultInstanceId, moved));++ await db+ .update(environmentInstances)+ .set({ environmentId, updatedAt: new Date() })+ .where(+ inArray(+ environmentInstances.id,+ folders.map((folder) => folder.id),+ ),+ );+ }+}diff --git a/packages/database/src/repositories/projectOverview/__tests__/index.test.ts b/packages/database/src/repositories/projectOverview/__tests__/index.test.tsindex 788e87fe474..9ca2822610d 100644--- a/packages/database/src/repositories/projectOverview/__tests__/index.test.ts+++ b/packages/database/src/repositories/projectOverview/__tests__/index.test.ts@@ -2,6 +2,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';+import { deleteTestUsers } from '../../../core/testCleanup';import { AgentModel } from '../../../models/agent';import { ProjectModel } from '../../../models/project';import { TaskModel } from '../../../models/task';@@ -40,12 +41,12 @@ const createTask = async (describe('ProjectOverviewRepository.list', () => {beforeEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);});afterEach(async () => {- await serverDB.delete(users);+ await deleteTestUsers(serverDB);});it('returns nothing when the caller has no projects', async () => {diff --git a/packages/database/src/repositories/workspaceDeletion/index.ts b/packages/database/src/repositories/workspaceDeletion/index.tsnew file mode 100644index 00000000000..cee0d2546fb--- /dev/null+++ b/packages/database/src/repositories/workspaceDeletion/index.ts@@ -0,0 +1,37 @@+import { and, eq } from 'drizzle-orm';++import { releaseProjectEnvironments } from '../../models/utils/projectEnvironmentCleanup';+import { WorkspaceModel } from '../../models/workspace';+import { workspaces } from '../../schemas';+import type { LobeChatDatabase } from '../../type';++/**+ * Deleting a workspace, across the aggregates it takes with it.+ *+ * Its projects cascade away with the workspace row, but each project's+ * environment holds the workspace back through `environments.workspace_id`+ * (`restrict` — an environment something was built from has storage on the+ * execution plane to clean up first). So the environments nothing was built+ * from are released in the same transaction, and only then is the workspace+ * deleted through {@link WorkspaceModel.delete}, which keeps its own checks+ * (primary owner, pending agent transfers).+ */+export class WorkspaceDeletionRepository {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ ) {}++ delete = async (id: string) =>+ this.db.transaction(async (tx) => {+ const db = tx as unknown as LobeChatDatabase;+ const [owned] = await db+ .select({ id: workspaces.id })+ .from(workspaces)+ .where(and(eq(workspaces.id, id), eq(workspaces.primaryOwnerId, this.userId)))+ .for('update');+ if (owned) await releaseProjectEnvironments(db, { workspaceId: id });++ return new WorkspaceModel(db, this.userId).delete(id);+ });+}diff --git a/packages/database/tests/setup-db.ts b/packages/database/tests/setup-db.tsindex 05deb822c50..87f6d5e9a72 100644--- a/packages/database/tests/setup-db.ts+++ b/packages/database/tests/setup-db.ts@@ -6,3 +6,24 @@ import 'fake-indexeddb/auto';import * as dotenv from 'dotenv';dotenv.config();++// Server-DB mode runs every file in one shared database, one after another. A+// project now always has an environment, and `environments.user_id` /+// `workspace_id` are `restrict`: one environment a file leaves behind blocks+// the next file's `delete(users)` and cascades into hundreds of failures far+// from the file that left it. So each file ends with no environment in the+// database, whatever its own cleanup did.+if (process.env.TEST_SERVER_DB === '1') {+ const { afterAll } = await import('vitest');++ afterAll(async () => {+ const { getTestDB } = await import('../src/core/getTestDB');+ const { environmentInstances, environments, projectEnvironments } =+ await import('../src/schemas');+ const db = await getTestDB();++ await db.delete(projectEnvironments);+ await db.delete(environmentInstances);+ await db.delete(environments);+ });+}diff --git a/packages/database/tests/test-utils.ts b/packages/database/tests/test-utils.tsindex 95b0e3da602..02d14bce8b9 100644--- a/packages/database/tests/test-utils.ts+++ b/packages/database/tests/test-utils.ts@@ -1 +1,2 @@export * from '../src/core/getTestDB';+export * from '../src/core/testCleanup';diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex d4eb8a27cf5..29438cce308 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -4535,16 +4535,17 @@ export default {'you': 'You','sandboxDrive.manageEnvironments': 'Settings','sandboxDrive.openStorage': 'Sandbox Storage',- 'sandboxEnvironment.none': 'No repository',+ 'sandboxEnvironment.none': 'No environment','sandboxEnvironment.missing': 'Environment unavailable','sandboxEnvironment.loading': 'Loading environment…','sandboxDrive.pickerTitle': 'Work location','sandboxDrive.pickerInfoTooltip':- 'A temporary directory is cleaned up with the sandbox. A folder on your cloud drive is kept across conversations. A repository is cloned before the first command.',- 'sandboxEnvironment.title': 'Repository',- 'sandboxEnvironment.hint': 'Cloned and set up once before the first command.',- 'sandboxEnvironment.empty': 'No repositories yet. Add one to get started.',- 'sandboxEnvironment.add': 'Add repository',+ 'A temporary directory is cleaned up with the sandbox. A folder on your cloud drive is kept across conversations. An environment is set up before the first command.',+ 'sandboxEnvironment.title': 'Environment',+ 'sandboxEnvironment.hint':+ 'Its repositories are cloned, setup runs and its variables are set before the first command.',+ 'sandboxEnvironment.empty': 'No environments yet. Create one to get started.',+ 'sandboxEnvironment.add': 'New environment','sandboxEnvironment.loadFailed': "Couldn't load environments",'sandboxEnvironment.retry': 'Retry','sandboxEnvironment.saveFailed': 'Could not change the environment. Try again.',@@ -4604,4 +4605,5 @@ export default {'taskList.find.open': 'Find in view','taskList.find.placeholder': 'Find in view…','taskList.groupBy.labelGroup': 'Label: {{name}}',+ 'sandboxEnvironment.noRepository': 'No repository',};diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.tsindex 63397fa484c..56feef58f5d 100644--- a/packages/locales/src/default/project.ts+++ b/packages/locales/src/default/project.ts@@ -27,8 +27,6 @@ export default {'settings.workLocations': 'Working directories','settings.directoryListDescription':'Device folders this project works in. Agents read and change files in them on that device.',- 'settings.environmentDescription':- 'Link environments configured in Settings → Environments, then add a folder on your device to start working.','settings.allEnvironments': 'All environments','settings.viewDirectories': 'View folders ({{count}})','directories.noEnvironment': 'No environment linked',@@ -98,9 +96,8 @@ export default {'settings.noDirectories':'No folders in this environment yet. Add an existing folder on a connected device to start working.','settings.title': 'Project settings',- 'settings.environments': 'Environments',+ 'settings.environments': 'Environment','settings.addEnvironment': 'Add environment',- 'settings.noEnvironments': 'No environments associated yet','directories.environmentName': 'Environment name','directories.editEnvironment': 'Configure environment',@@ -212,8 +209,6 @@ export default {'A project with this name already exists, including in the trash. Choose a different name.','createFromGithub.empty':"The connected GitHub accounts haven't given LobeHub access to any repositories yet.",- 'createFromGithub.environmentHint':- "The repository becomes this project's environment, so agents can check it out when they work on the project.",'createFromGithub.loadFailed': "Couldn't load repositories from GitHub.",'createFromGithub.manageAccess': 'Manage access','createFromGithub.private': 'Private',@@ -311,24 +306,6 @@ export default {'rename.nameLabel': 'Project name','rename.success': 'Project renamed','rename.title': 'Rename project',- 'environment.add.action': 'Add',- 'environment.add.existing': 'Add an existing one',- 'environment.add.failed': "Couldn't add the environment to this project",- 'environment.add.github': 'New from GitHub',- 'environment.add.noExisting': 'All of your environments are already in this project.',- 'environment.add.noPublished':- 'No published environments to add. A shared project only uses published environments.',- 'environment.add.title': 'Add environment',- 'environment.create': 'New environment',- 'environment.link': 'Link environment',- 'environment.unlink': 'Unlink from project',- 'environment.unlinkConfirm.desc':- "The environment stays in Settings → Environments. This project's folders that use it are kept, but can't run conversations until it is linked again.",- 'environment.unlinkConfirm.title': 'Unlink "{{name}}" from this project?',- 'environment.unlinkFailed': "Couldn't unlink the environment from this project",- 'environment.privateInShared': 'Private',- 'environment.privateInSharedTooltip':- "This project is shared, so its conversations only use published environments. This private environment won't be checked out.",'overview.context.location.devices': 'Devices','overview.context.location.directories': 'Project folders','overview.context.location.directoryUnavailable':@@ -524,4 +501,19 @@ export default {'onboarding.connect.goal.title': 'Goals','onboarding.connect.goal.description': 'Set a goal you can sign off','onboarding.connect.goal.count': '{{count}} set',+ 'environment.configure': 'Configure environment',+ 'settings.environmentIntro':+ 'Every conversation in this project runs in this environment: its repositories are cloned, the setup command runs, and its variables are set.',+ 'createFromGithub.addRepository': 'Add',+ 'createFromGithub.removeRepository': 'Remove',+ 'createFromGithub.openIntegrations': 'Open GitHub settings',+ 'environment.none': 'No environment \u2014 start in an empty folder',+ 'createFromGithub.alreadyAdded': 'This repository is already added.',+ 'createFromGithub.layoutHint':+ "Each repository is checked out in a folder of its own, side by side. You can change them later in the project's settings.",+ 'createFromGithub.repositoryTitle': 'Repository',+ 'createFromGithub.advanced': 'Advanced settings',+ 'createFromGithub.advancedWithCount': 'Advanced settings · {{count}} extra',+ 'createFromGithub.extraRepositoriesLabel': 'More repositories',+ 'createFromGithub.chooseFromGithub': 'Choose from GitHub',};diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 5d3123a2ea7..6bb93dbe33b 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -4836,9 +4836,6 @@ When I am ___, I need ___'environments.form.editEnv': 'Edit variable','environments.form.changeRepository': 'Change repository','environments.form.disconnect': 'Disconnect',- 'environments.detail.tabs.overview': 'Overview',- 'environments.detail.initializerDesc':- 'Applied once to a working directory picked for a conversation: the repository is cloned there and the setup command runs.','environments.detail.noRepository': 'No repository','environments.detail.noSetup': 'No setup command','environments.instances.copy': 'Duplicate copy',@@ -4896,8 +4893,6 @@ When I am ___, I need ___'environments.meta.unknownCreator': 'Unknown','environments.meta.createdAt': 'Created {{time}}','environments.meta.storage': 'Using {{size}}',- 'environments.detail.close': 'Close',- 'environments.detail.tabs.settings': 'Settings','environments.sessions.title': 'Run history','environments.sessions.desc':'The most recent sessions that ran in these copies and the builds of them, newest first, with how each ended and whether what it installed was saved.',@@ -5385,4 +5380,24 @@ When I am ___, I need ___'automations.empty.title': 'No automations yet','automations.empty.desc':'Ask an agent to keep an eye on a connector for you, like "Tell me when CI fails on this PR". Subscriptions you approve show up here.',+ 'environments.form.addRepository': 'Add repository',+ 'environments.form.noRepositories': 'No repositories. Conversations start in an empty folder.',+ 'environments.form.noVariables': 'No variables',+ 'environments.github.openIntegrations': 'Open GitHub settings',+ 'environments.form.pasteRepository': 'Or paste a public repository URL',+ 'environments.form.addPastedRepository': 'Add',+ 'environments.form.repositoryUrlInvalid': 'Not a GitHub repository URL',+ 'environments.form.doneEditing': 'Done',+ 'environments.form.repositoryOptional':+ 'Optional \u2014 an environment can start without a repository and get one later.',+ 'environments.form.layoutHint':+ "Each repository is checked out in a folder of its own, side by side. You can change them later in the environment's settings.",+ 'environments.detail.back': 'Environments',+ 'environments.detail.notFound': "This environment doesn't exist or you can't see it.",+ 'environments.form.editRepositorySettings': 'Edit branch, folder and setup',+ 'environments.form.repositorySetupHint':+ "Runs inside this repository's folder after it's cloned, before the environment's setup command.",+ 'environments.form.bootstrapAfterRepositories':+ "Runs at the top of the working directory, after each repository's own setup. Setup for a single repository goes on that repository.",+ 'environments.form.duplicateFolder': 'Another repository already uses this folder.',};diff --git a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.tsindex 28da7362f53..d906ad64f2c 100644--- a/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts+++ b/packages/mecha/src/contextEngineering/facts/gatherContextFacts.ts@@ -671,7 +671,10 @@ export const gatherContextFacts = async (// Left out entirely for an ephemeral run so the variable generators'// fallback renders the original wording; spelling it out here would mean// two copies of the same ephemeral text to keep in step.- ...(isPersistentSandboxMode(sandboxPersistence?.mode)+ // Also for an ephemeral run whose environment checks repositories out:+ // the model is told where they are (see `formatSandboxRepositoriesPrompt`).+ ...(isPersistentSandboxMode(sandboxPersistence?.mode) ||+ sandboxPersistence?.repositories?.length? formatSandboxStoragePromptVariables(sandboxPersistence): {}),topic_id: request.topicId ?? '',diff --git a/packages/mecha/src/contextEngineering/facts/types.ts b/packages/mecha/src/contextEngineering/facts/types.tsindex 4ace2e15e21..3ad5b995431 100644--- a/packages/mecha/src/contextEngineering/facts/types.ts+++ b/packages/mecha/src/contextEngineering/facts/types.ts@@ -221,7 +221,14 @@ export interface ContextFactProviders {* ephemeral, which is what every run without one gets.*/resolveSandboxPersistence?: () => Promise<- { cwd?: string; mode: 'drive' | 'ephemeral' | 'persistent'; workingDir?: string } | undefined+ | {+ cwd?: string;+ mode: 'drive' | 'ephemeral' | 'persistent';+ /** The repositories the topic's environment checks out, in order. */+ repositories?: { folder?: string; ref?: string; repository: string }[];+ workingDir?: string;+ }+ | undefined>;}diff --git a/packages/types/src/environment/index.test.ts b/packages/types/src/environment/index.test.tsindex 6e38e792d21..2c06715baf7 100644--- a/packages/types/src/environment/index.test.ts+++ b/packages/types/src/environment/index.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from 'vitest';-import { type EnvironmentConfiguration, toExecutionConfiguration } from './index';+import {+ type EnvironmentConfiguration,+ layoutRepositorySources,+ toExecutionConfiguration,+ withRepositorySetup,+} from './index';describe('toExecutionConfiguration', () => {const before: EnvironmentConfiguration = {@@ -21,3 +26,100 @@ describe('toExecutionConfiguration', () => {expect(toExecutionConfiguration(before)).toEqual(before);});});++describe('layoutRepositorySources', () => {+ const git = (url: string, path?: string) => ({+ kind: 'git' as const,+ url,+ ...(path && { path }),+ });++ it('keeps one repository at the top of the working directory', () => {+ const sources = [git('https://github.com/lobehub/lobehub')];+ expect(layoutRepositorySources(sources)).toBe(sources);+ });++ it('lays several out side by side, each in a folder named after it', () => {+ expect(+ layoutRepositorySources([+ git('https://github.com/lobehub/lobehub'),+ git('https://github.com/lobehub/lobe-ui.git'),+ ]),+ ).toEqual([+ git('https://github.com/lobehub/lobehub', 'lobehub'),+ git('https://github.com/lobehub/lobe-ui.git', 'lobe-ui'),+ ]);+ });++ it('keeps a folder the author chose and never puts two repositories in one', () => {+ expect(+ layoutRepositorySources([+ git('https://github.com/a/app', 'web'),+ git('https://github.com/a/app-docs', './'),+ git('https://github.com/b/app-docs'),+ ]),+ ).toEqual([+ git('https://github.com/a/app', 'web'),+ git('https://github.com/a/app-docs', 'app-docs'),+ git('https://github.com/b/app-docs', 'b-app-docs'),+ ]);+ });++ it('is what the execution plane is sent', () => {+ expect(+ toExecutionConfiguration({+ kind: 'code',+ sources: [git('https://github.com/a/one'), git('https://github.com/a/two')],+ }).sources,+ ).toEqual([git('https://github.com/a/one', 'one'), git('https://github.com/a/two', 'two')]);+ });+});++describe('withRepositorySetup', () => {+ it('leaves a definition without repository setup untouched', () => {+ const configuration = {+ bootstrapCommand: 'pnpm i',+ sources: [{ kind: 'git' as const, url: 'https://github.com/a/one' }],+ };+ expect(withRepositorySetup(configuration)).toBe(configuration);+ });++ it("runs each repository's setup in its folder, then the environment's own", () => {+ const result = withRepositorySetup({+ bootstrapCommand: 'make all',+ sources: [+ { kind: 'git', setupCommand: 'pnpm i', url: 'https://github.com/a/web' },+ { kind: 'git', url: 'https://github.com/a/docs' },+ { kind: 'git', setupCommand: "echo 'hi'", url: 'https://github.com/a/api' },+ ],+ });+ expect(result.bootstrapCommand).toBe(+ "(cd 'web' && pnpm i\n) && (cd 'api' && echo 'hi'\n) && (make all\n)",+ );+ expect(result.sources).toEqual([+ { kind: 'git', url: 'https://github.com/a/web' },+ { kind: 'git', url: 'https://github.com/a/docs' },+ { kind: 'git', url: 'https://github.com/a/api' },+ ]);+ });++ it('runs a lone repository setup at the top, where that repository is checked out', () => {+ expect(+ withRepositorySetup({+ sources: [{ kind: 'git', setupCommand: 'npm ci', url: 'https://github.com/a/one' }],+ }).bootstrapCommand,+ ).toBe("(cd '.' && npm ci\n)");+ });++ it('is applied on the way to the execution plane', () => {+ expect(+ toExecutionConfiguration({+ kind: 'code',+ sources: [{ kind: 'git', setupCommand: 'npm ci', url: 'https://github.com/a/one' }],+ }),+ ).toEqual({+ bootstrapCommand: "(cd '.' && npm ci\n)",+ sources: [{ kind: 'git', url: 'https://github.com/a/one' }],+ });+ });+});diff --git a/packages/types/src/environment/index.ts b/packages/types/src/environment/index.tsindex 06badb8b0ae..6f0c7a2110f 100644--- a/packages/types/src/environment/index.ts+++ b/packages/types/src/environment/index.ts@@ -9,7 +9,20 @@ export type EnvironmentVisibility = 'private' | 'public';/** Abstract source material; paths are relative destinations within an instance. */export type EnvironmentSource =- | { kind: 'git'; path?: string; ref?: string; url: string }+ | {+ kind: 'git';+ path?: string;+ ref?: string;+ /**+ * Setup for this repository alone, run inside its folder once it is+ * checked out and before the environment's own+ * {@link EnvironmentConfiguration.bootstrapCommand}. Folded into that one+ * command by {@link withRepositorySetup} before anything reaches the+ * execution plane, which only knows the environment-wide one.+ */+ setupCommand?: string;+ url: string;+ }| { kind: 'files'; path?: string; uri: string };export interface EnvironmentResourceRequirements {@@ -122,7 +135,124 @@ export const DEFAULT_REGENERABLE_PATHS = ['node_modules', '.venv', 'target'] asexport const toExecutionConfiguration = (configuration: EnvironmentConfiguration,): EnvironmentConfiguration => {- const { kind: _kind, ...rest } = configuration;+ const { kind: _kind, ...rest } = withRepositorySetup(configuration);- return rest;+ return rest.sources ? { ...rest, sources: layoutRepositorySources(rest.sources) } : rest;+};++/** The last segment of a checkout url — the repository's name, without `.git`. */+export const repositoryFolderName = (url: string): string =>+ url+ .replace(/\.git$/, '')+ .replace(/\/+$/, '')+ .split('/')+ .pop() || 'repository';++/** `owner-name` of a checkout url, the fallback when two repositories share a name. */+const repositoryOwnerFolderName = (url: string): string => {+ const [owner, name] = url+ .replace(/\.git$/, '')+ .replace(/\/+$/, '')+ .split('/')+ .slice(-2);+ return owner && name ? `${owner}-${name}` : repositoryFolderName(url);+};++const isRootPath = (path: string | undefined) => {+ const value =+ path+ ?.trim()+ .replace(/^\.?\/+/, '')+ .replace(/\/+$/, '') ?? '';+ return value === '' || value === '.';+};++/**+ * Where each repository of an environment is checked out.+ *+ * One repository is checked out at the top of the working directory, as it+ * always was. Several are laid out side by side, each in a folder of its own+ * named after it (`lobehub/`, `lobe-ui/`), and the working directory itself is+ * none of them. Nesting one checkout inside another would put the second+ * repository in the first one's working tree — untracked in its `git status`,+ * one `git add -A` away from being committed into it as an embedded repository,+ * and inside every search, lint and build the first one runs.+ *+ * A folder the author set explicitly is kept; only a repository left at the+ * top gets one. Two repositories of the same name fall back to `owner-name`,+ * then a numeric suffix.+ */+export const layoutRepositorySources = (sources: EnvironmentSource[]): EnvironmentSource[] => {+ const repositories = sources.filter((source) => source.kind === 'git');+ if (repositories.length <= 1) return sources;++ const taken = new Set(+ repositories.flatMap((source) =>+ isRootPath(source.path)+ ? []+ : [+ source+ .path!.trim()+ .replace(/^\.?\/+/, '')+ .replace(/\/+$/, ''),+ ],+ ),+ );+ const claim = (url: string) => {+ let folder = repositoryFolderName(url);+ if (taken.has(folder)) folder = repositoryOwnerFolderName(url);+ for (let suffix = 2; taken.has(folder); suffix++)+ folder = `${repositoryOwnerFolderName(url)}-${suffix}`;+ taken.add(folder);+ return folder;+ };++ return sources.map((source) =>+ source.kind === 'git' && isRootPath(source.path)+ ? { ...source, path: claim(source.url) }+ : source,+ );+};++const shellQuote = (value: string): string => `'${value.replaceAll("'", String.raw`'\''`)}'`;++/**+ * The definition with each repository's own setup folded into the one setup+ * command the execution plane runs, and taken off the sources.+ *+ * Every repository's setup runs in its own folder, in the order the+ * repositories are checked out, each in a subshell so a `cd` in one does not+ * move the next; then the environment's own setup at the top of the working+ * directory. Chained with `&&`: the first failure stops the rest, as one+ * command failing always did.+ *+ * A definition without any repository setup comes back as it was, so the+ * digest of every build made before repositories had one is unchanged.+ */+export const withRepositorySetup = (+ configuration: EnvironmentConfiguration,+): EnvironmentConfiguration => {+ const sources = configuration.sources ?? [];+ const hasRepositorySetup = sources.some(+ (source) => source.kind === 'git' && source.setupCommand?.trim(),+ );+ if (!hasRepositorySetup) return configuration;++ const steps = layoutRepositorySources(sources).flatMap((source) => {+ const command = source.kind === 'git' ? source.setupCommand?.trim() : undefined;+ if (!command) return [];+ const folder = isRootPath(source.path) ? '.' : source.path!.trim();+ return [`(cd ${shellQuote(folder)} && ${command}\n)`];+ });+ const own = configuration.bootstrapCommand?.trim();++ return {+ ...configuration,+ bootstrapCommand: [...steps, ...(own ? [`(${own}\n)`] : [])].join(' && '),+ sources: sources.map((source) => {+ if (source.kind !== 'git' || source.setupCommand === undefined) return source;+ const { setupCommand: _setupCommand, ...rest } = source;+ return rest;+ }),+ };};diff --git a/scripts/backfillProjectEnvironments/index.ts b/scripts/backfillProjectEnvironments/index.tsnew file mode 100644index 00000000000..b89e51e5369--- /dev/null+++ b/scripts/backfillProjectEnvironments/index.ts@@ -0,0 +1,158 @@+/**+ * Bring every existing project to the one-environment rule: each project has+ * exactly one environment of its own (`environments.project_id`).+ *+ * Per project, `ProjectEnvironmentRepository.ensure` — the same routine the app+ * runs the first time it reads a project's environment, so a project the app+ * already reached is skipped here and vice versa:+ * - its first linked environment (default, else first in order) becomes the+ * project's own when no other project links it; otherwise a new one is+ * made from that one's definition, or empty when nothing was linked;+ * - the repositories of its other linked environments are merged in;+ * - a device folder used only by this project moves with them;+ * - the other links are removed. No environment is deleted: one the project+ * stops linking stays in「设置 → 环境」.+ *+ * Silent: no prompt, no notification, no change to `projects` rows.+ * Dry-run by default (reports what is pending); pass --apply to write.+ * Idempotent and resumable: a settled project is not selected again.+ *+ * Run migration 0221 first.+ *+ * bunx tsx scripts/backfillProjectEnvironments/index.ts+ * bunx tsx scripts/backfillProjectEnvironments/index.ts --apply --batch-size=100+ */+import { drizzle } from 'drizzle-orm/node-postgres';+import pg from 'pg';++import { ProjectEnvironmentRepository } from '../../packages/database/src/repositories/projectEnvironment';+import * as schema from '../../packages/database/src/schemas';+import type { LobeChatDatabase } from '../../packages/database/src/type';++/**+ * Projects not yet settled: no environment of their own, a link to it that is+ * not the enabled default, or another link beside it that is not one kept for+ * a folder shared with another project.+ */+export const SELECT_UNSETTLED_PROJECTS = `+ SELECT p.id, p.name, p.user_id AS "userId", p.workspace_id AS "workspaceId",+ p.visibility+ FROM projects p+ WHERE p.id > $1+ AND (+ NOT EXISTS (SELECT 1 FROM environments e WHERE e.project_id = p.id)+ OR EXISTS (+ SELECT 1 FROM project_environments pe+ LEFT JOIN environments e ON e.id = pe.environment_id AND e.project_id = p.id+ WHERE pe.project_id = p.id+ AND (+ (e.id IS NOT NULL AND (pe.is_default = false OR pe.enabled = false))+ -- Another environment's link stays only as a non-default one kept+ -- for a folder this project shares with another project.+ OR (e.id IS NULL AND (pe.is_default OR NOT EXISTS (+ SELECT 1 FROM environment_instances i+ INNER JOIN project_working_directories w+ ON w.device_id = i.device_id AND w.path = i.working_directory+ AND w.project_id = p.id+ WHERE i.environment_id = pe.environment_id AND i.kind = 'device'+ )))+ )+ )+ OR NOT EXISTS (+ SELECT 1 FROM project_environments pe+ INNER JOIN environments e ON e.id = pe.environment_id AND e.project_id = p.id+ WHERE pe.project_id = p.id+ )+ )+ ORDER BY p.id+ LIMIT $2+`;++export interface BackfillProgress {+ failed: number;+ scanned: number;+ settled: number;+}++export interface UnsettledProject {+ id: string;+ name: string;+ userId: string;+ visibility: string;+ workspaceId: string | null;+}++export const backfillProjectEnvironments = async (+ db: LobeChatDatabase,+ query: (text: string, params: unknown[]) => Promise<{ rows: UnsettledProject[] }>,+ {+ apply,+ batchSize,+ log = () => {},+ }: { apply: boolean; batchSize: number; log?: (line: object) => void },+): Promise<BackfillProgress> => {+ const progress: BackfillProgress = { failed: 0, scanned: 0, settled: 0 };+ let cursor = '';++ for (;;) {+ const { rows } = await query(SELECT_UNSETTLED_PROJECTS, [cursor, batchSize]);+ if (rows.length === 0) break;++ for (const project of rows) {+ progress.scanned++;+ cursor = project.id;+ if (!apply) continue;+ try {+ await ProjectEnvironmentRepository.ensure(db, project);+ progress.settled++;+ } catch (error) {+ // One project's failure must not stop the rest; it is retried next run.+ progress.failed++;+ log({ error: (error as Error).message, projectId: project.id });+ }+ }+ log({ apply, cursor, ...progress });+ }++ return progress;+};++const main = async () => {+ const args = new Set(process.argv.slice(2));+ const apply = args.has('--apply');+ const batchSizeArg = process.argv.find((arg) => arg.startsWith('--batch-size='));+ const batchSize = batchSizeArg+ ? Number.parseInt(batchSizeArg.slice('--batch-size='.length), 10)+ : 100;+ if (!Number.isInteger(batchSize) || batchSize < 1 || batchSize > 1000)+ throw new Error('--batch-size must be an integer between 1 and 1000');++ const connectionString = process.env.DATABASE_URL;+ if (!connectionString) throw new Error('DATABASE_URL is required');++ const pool = new pg.Pool({ connectionString });+ try {+ const db = drizzle(pool, { schema }) as unknown as LobeChatDatabase;+ const progress = await backfillProjectEnvironments(+ db,+ (text, params) => pool.query(text, params),+ {+ apply,+ batchSize,+ log: (line) => console.log(JSON.stringify(line)),+ },+ );+ console.log(JSON.stringify({ apply, complete: true, ...progress }));+ if (progress.failed > 0) process.exitCode = 1;+ } finally {+ await pool.end();+ }+};++// Only when run as a script, so the test can import the loop.+if (process.argv[1]?.includes('backfillProjectEnvironments')) {+ main().catch((error) => {+ console.error(error);+ process.exitCode = 1;+ });+}diff --git a/scripts/stylexMigration/legacyFiles.json b/scripts/stylexMigration/legacyFiles.jsonindex b3da5d51b3f..d213826a12e 100644--- a/scripts/stylexMigration/legacyFiles.json+++ b/scripts/stylexMigration/legacyFiles.json@@ -289,13 +289,11 @@"src/features/EntityLink/Render/InternalEntityLink.tsx","src/features/EntityLink/Render/InternalEntityPreview.tsx","src/features/EntityLink/Render/LinkChip.tsx",- "src/features/EnvironmentManager/EnvironmentDetailPanel.tsx","src/features/EnvironmentManager/EnvironmentForm.tsx","src/features/EnvironmentManager/EnvironmentItem.tsx","src/features/EnvironmentManager/EnvironmentVariables.tsx","src/features/EnvironmentManager/GithubRepositoryPicker.tsx","src/features/EnvironmentManager/InlineField.tsx",- "src/features/EnvironmentManager/PanelSection.tsx","src/features/EnvironmentManager/index.tsx","src/features/EvalCapture/CaptureContent.tsx","src/features/EvalCapture/CaptureSuccess.tsx",diff --git a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsxindex 765bd2b5587..519358d092b 100644--- a/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx+++ b/src/features/ChatInput/ControlBar/SandboxDrivePicker.tsx@@ -1,12 +1,12 @@'use client';import { ENABLE_BUSINESS_FEATURES } from '@lobechat/business-const';-import { Github } from '@lobehub/icons';import { Flexbox, Icon, Popover, Skeleton, Tag, Text, toast, Tooltip } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';import {ChevronDownIcon,+ ContainerIcon,FolderIcon,HardDriveIcon,InfoIcon,@@ -36,6 +36,7 @@ import SandboxDriveMenu from './SandboxDriveMenu';import {environmentChipState,pickableEnvironments,+ repositoriesLabel,repositorySelection,repositorySlug,} from './sandboxEnvironmentOptions';@@ -261,12 +262,14 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(const fallbackMessage = fallback ? t(`sandboxDrive.fallback.${fallback}`) : undefined;const chipIcon = fallback ? (<Icon icon={TriangleAlertIcon} size={14} />+ ) : onRepository && repository && repositorySlug(repository) ? (+ <RepositoryAvatar size={14} url={repositorySlug(repository)} />) : onRepository ? (- <RepositoryAvatar size={14} url={repository && repositorySlug(repository)} />+ <Icon icon={ContainerIcon} size={14} />) : persistent ? (<Icon icon={currentIcon} size={14} />) : repositoryOnly ? (- <Github size={14} />+ <Icon icon={ContainerIcon} size={14} />) : (<Icon icon={TimerIcon} size={14} />);@@ -330,16 +333,16 @@ const SandboxDrivePicker = memo<SandboxDrivePickerProps>(arrowcompactactive={onRepository}- hint={onRepository && repository ? repositorySlug(repository) : undefined}+ hint={onRepository && repository ? repositoriesLabel(repository) : undefined}icon={- onRepository && repository ? (+ onRepository && repository && repositorySlug(repository) ? (<RepositoryAvatar size={16} url={repositorySlug(repository)} />) : (- <Github size={16} />+ <Icon icon={ContainerIcon} size={16} />)}label={- // The repository the conversation works in, by name; the+ // The environment the conversation works in, by name; the// generic title only while none is picked.onRepository && repositoryState.kind === 'picked'? repositoryState.namediff --git a/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx b/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsxindex 47673e734c2..88a3bacdd4b 100644--- a/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx+++ b/src/features/ChatInput/ControlBar/SandboxRepositoryMenu.tsx@@ -4,14 +4,14 @@ import type { EnvironmentConfiguration } from '@lobechat/types';import { Button, Flexbox, Icon, Text } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { CircleOffIcon, PlusIcon, SettingsIcon } from 'lucide-react';+import { CircleOffIcon, ContainerIcon, PlusIcon, SettingsIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';import RepositoryAvatar from '@/components/RepositoryAvatar';import OptionRow from './OptionRow';-import { repositorySlug } from './sandboxEnvironmentOptions';+import { repositoriesLabel, repositorySlug } from './sandboxEnvironmentOptions';import SubmenuHeader from './SubmenuHeader';const styles = stylex.create({@@ -101,10 +101,19 @@ const SandboxRepositoryMenu = memo<SandboxRepositoryMenuProps>(compactactive={environment.id === selectedId}desc={environment.description || undefined}- hint={repositorySlug(environment)}- icon={<RepositoryAvatar size={16} url={repositorySlug(environment)} />}+ // An environment, which checks out any number of repositories or+ // none: its repositories as `owner/name +N`, said plainly when+ // it has none.+ hint={repositoriesLabel(environment) ?? t('sandboxEnvironment.noRepository')}key={environment.id}label={environment.name}+ icon={+ repositorySlug(environment) ? (+ <RepositoryAvatar size={16} url={repositorySlug(environment)} />+ ) : (+ <Icon icon={ContainerIcon} size={16} />+ )+ }onClick={() => {onClose();void onPick(environment);diff --git a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.tsindex 223197af8ed..2e7aa2be208 100644--- a/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts+++ b/src/features/ChatInput/ControlBar/sandboxEnvironmentOptions.ts@@ -30,6 +30,22 @@ export const repositorySlug = (environment: {}};+/**+ * The repositories an environment checks out, as a label: the first one's+ * `owner/name`, and `+N` for the rest — so a picker row never reads as one+ * repository when the environment clones several.+ */+export const repositoriesLabel = (environment: {+ configuration?: Pick<EnvironmentConfiguration, 'sources'> | null;+}): string | undefined => {+ const first = repositorySlug(environment);+ if (!first) return undefined;+ const count = (environment.configuration?.sources ?? []).filter(+ (source) => source.kind === 'git',+ ).length;+ return count > 1 ? `${first} +${count - 1}` : first;+};+/*** What the environment chip says. A list still loading, or one that failed to* load, says nothing about the topic's environment — so it is not reported asdiff --git a/src/features/EnvironmentManager/CreateEnvironmentModal.tsx b/src/features/EnvironmentManager/CreateEnvironmentModal.tsxindex 47b5529bf0b..3190a71da22 100644--- a/src/features/EnvironmentManager/CreateEnvironmentModal.tsx+++ b/src/features/EnvironmentManager/CreateEnvironmentModal.tsx@@ -1,6 +1,7 @@'use client';import type { EnvironmentVisibility } from '@lobechat/types';+import { layoutRepositorySources } from '@lobechat/types';import {Button,confirmModal,@@ -15,10 +16,16 @@ import { t as translate } from 'i18next';import { memo, 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 RepositoryField, {+ AdvancedRepositories,+ type PickedRepository,+} from '@/features/Projects/CreateFromGithub/RepositoryField';import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useIMECompositionEvent } from '@/hooks/useIMECompositionEvent';-import GithubRepositoryPicker, { type GithubRepositorySelection } from './GithubRepositoryPicker';import { type CreatedEnvironment, useEnvironmentActions } from './useEnvironmentData';/**@@ -49,7 +56,14 @@ const CreateEnvironmentContent = memo<CreateEnvironmentContentProps>(// the person typed is theirs, and picking a different repository must not// overwrite it; a suggested one is just a default and follows the pick.const [nameIsSuggested, setNameIsSuggested] = useState(true);- const [repository, setRepository] = useState<GithubRepositorySelection | undefined>();+ // Picked from the list or pasted, the same field the create-project dialog+ // uses. None is fine; several are laid out side by side.+ const [repositories, setRepositories] = useState<PickedRepository[]>([]);+ const navigate = useWorkspaceAwareNavigate();+ const connectGithub = () => {+ close();+ navigate(GITHUB_RETURN_TO);+ };const [creating, setCreating] = useState(false);// The Enter that confirms an IME candidate reaches `keydown` as an Enter,// so a Chinese name would submit the dialog on the keystroke that picked it.@@ -58,13 +72,13 @@ const CreateEnvironmentContent = memo<CreateEnvironmentContentProps>(const trimmed = name.trim();- const pickRepository = (selection: GithubRepositorySelection | undefined) => {- setRepository(selection);+ const changeRepositories = (next: PickedRepository[]) => {+ setRepositories(next);setError(undefined);// Naming a thing that does not exist yet is the harder half of this dialog,- // so the repository answers it: an environment for a repository is almost- // always called after it.- if (nameIsSuggested) setName(selection?.repository ?? '');+ // so the first repository answers it: an environment for a repository is+ // almost always called after it.+ if (nameIsSuggested) setName((next[0] && parseGithubRepository(next[0].url)?.name) ?? '');};const create = async () => {@@ -72,22 +86,22 @@ const CreateEnvironmentContent = memo<CreateEnvironmentContentProps>(setError(undefined);try {const created = await actions.createEnvironment({- // The repository is the environment's one source. Every repository- // carries the owner GitHub reported for it, so the checkout URL is- // built from the pair rather than from whichever owner the list was- // filtered by — those differ for a repository reached as a collaborator.- configuration: repository- ? {- kind: 'code',- sources: [- {- kind: 'git',- ref: repository.defaultBranch,- url: `https://github.com/${repository.owner}/${repository.repository}`,- },- ],- }- : { kind: 'code' },+ // Each picked repository is a source, checked out from the URL GitHub+ // reported for it. No repository at all is a valid environment: setup+ // and variables only, cloning nothing. Several are laid out side by side.+ configuration:+ repositories.length > 0+ ? {+ kind: 'code',+ sources: layoutRepositorySources(+ repositories.map((repository) => ({+ kind: 'git' as const,+ url: repository.url,+ ...(repository.defaultBranch && { ref: repository.defaultBranch }),+ })),+ ) as { kind: 'git'; path?: string; ref?: string; url: string }[],+ }+ : { kind: 'code' },name: trimmed,// Created into the pool the person is looking at. Opening the dialog// from the Private tab and having the result land in the workspace's@@ -135,7 +149,12 @@ const CreateEnvironmentContent = memo<CreateEnvironmentContentProps>({/* Repository first, name second. The name is the harder question and therepository usually answers it, so asking for the name first makes theperson invent something they are about to be handed. */}- <GithubRepositoryPicker value={repository} onChange={pickRepository} onLeave={close} />+ <RepositoryField+ emptyHint={t('environments.form.repositoryOptional')}+ value={repositories}+ onChange={changeRepositories}+ onConnect={connectGithub}+ /><Flexbox gap={6}><Text fontSize={12} type={'secondary'} weight={500}>@@ -161,6 +180,13 @@ const CreateEnvironmentContent = memo<CreateEnvironmentContentProps>(</Text>)}</Flexbox>++ <AdvancedRepositories+ layoutHint={t('environments.form.layoutHint')}+ value={repositories}+ onChange={changeRepositories}+ onConnect={connectGithub}+ /></Flexbox><ModalFooter><Button onClick={close}>{t('environments.cancel')}</Button>@@ -191,5 +217,5 @@ export const openCreateEnvironmentModal = (maskClosable: true,styles: { content: { padding: 0 } },title,- width: 'min(90vw, 480px)',+ width: 'min(90vw, 520px)',});diff --git a/src/features/EnvironmentManager/EnvironmentDetailPage.tsx b/src/features/EnvironmentManager/EnvironmentDetailPage.tsxnew file mode 100644index 00000000000..faec4967ce2--- /dev/null+++ b/src/features/EnvironmentManager/EnvironmentDetailPage.tsx@@ -0,0 +1,176 @@+'use client';++import type { EnvironmentVisibility } from '@lobechat/types';+import { Github } from '@lobehub/icons';+import { Button, Empty, Flexbox, Icon, Tag, Text, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import dayjs from 'dayjs';+import { ArrowLeftIcon, ContainerIcon, LockIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import UserAvatar from '@/components/UserAvatar';++import EnvironmentForm from './EnvironmentForm';+import EnvironmentSummary from './EnvironmentSummary';+import { EnvironmentDefinitionSkeleton } from './Skeleton';+import { useCanEditEnvironment } from './useCanEditEnvironment';+import { useEnvironmentActions, useEnvironments } from './useEnvironmentData';++const styles = stylex.create({+ header: {+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ paddingBlockEnd: 20,+ },+ /** The same dot the row uses between its facts. */+ metaDivider: {+ backgroundColor: cssVar.colorTextQuaternary,+ borderRadius: '50%',+ flex: 'none',+ height: 3,+ width: 3,+ },+ iconTile: {+ alignItems: 'center',+ backgroundColor: cssVar.colorFillTertiary,+ borderRadius: cssVar.borderRadius,+ color: cssVar.colorTextSecondary,+ display: 'flex',+ flex: 'none',+ height: 40,+ justifyContent: 'center',+ width: 40,+ },+});++interface EnvironmentDetailPageProps {+ environmentId: string;+ /** Back to the list this environment was opened from. */+ onBack: () => void;+ /** Workspace pages: the pool the environment is in. */+ visibility?: EnvironmentVisibility;+}++/**+ * One environment, on a page of its own (`environments/:id`): who made it,+ * then its whole definition laid out flat — no tabs, no card around it. Its+ * editor edits in place; everyone else reads what it will do. The same form a+ * project's environment page shows.+ *+ * Read by id from the list rather than handed a snapshot: the form writes+ * through to the same replica entry, so a copy taken at open time would go+ * stale the moment someone saved.+ */+const EnvironmentDetailPage = memo<EnvironmentDetailPageProps>(+ ({ environmentId, onBack, visibility }) => {+ const { t } = useTranslation('setting');+ const actions = useEnvironmentActions();+ const { environments, error, revalidate, settled } = useEnvironments(visibility);+ const environment = environments?.find((item) => item.id === environmentId);+ const canEditEnvironment = useCanEditEnvironment();+ const canEdit = environment ? canEditEnvironment(environment) : false;++ const back = (+ <Flexbox horizontal>+ <Button icon={<Icon icon={ArrowLeftIcon} />} size={'small'} type={'text'} onClick={onBack}>+ {t('environments.detail.back')}+ </Button>+ </Flexbox>+ );++ if (!environment) {+ if (error && !settled)+ return (+ <Flexbox gap={16}>+ {back}+ <AsyncError error={error} onRetry={() => revalidate()} />+ </Flexbox>+ );+ return (+ <Flexbox gap={16}>+ {back}+ {settled ? (+ <Empty icon={ContainerIcon} title={t('environments.detail.notFound')} />+ ) : (+ <EnvironmentDefinitionSkeleton />+ )}+ </Flexbox>+ );+ }++ // A row restored from storage has no configuration until the server+ // answers: it carries `env`, so it is never stored. The definition waits+ // for it rather than reading as empty — an editor saving over `{}` would+ // erase it.+ const configurationPending = environment.configuration === undefined;+ const creator =+ environment.creator?.fullName ||+ environment.creator?.username ||+ t('environments.meta.unknownCreator');++ return (+ <Flexbox gap={24}>+ {back}+ <Flexbox horizontal align={'center'} gap={12} {...stylex.props(styles.header)}>+ <span {...stylex.props(styles.iconTile)}>+ <Github size={20} />+ </span>+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>+ <Text ellipsis fontSize={18} weight={600}>+ {environment.name}+ </Text>+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ {environment.workspaceId && environment.visibility === 'public' && (+ <Tag size={'small'}>{t('environments.visibility.publicTag')}</Tag>+ )}+ <Flexbox horizontal align={'center'} gap={6}>+ <UserAvatar avatar={environment.creator?.avatar} name={creator} size={16} />+ <Text fontSize={12} type={'secondary'}>+ {creator}+ </Text>+ </Flexbox>+ <span {...stylex.props(styles.metaDivider)} />+ <Tooltip title={new Date(environment.createdAt).toLocaleString()}>+ <Text fontSize={12} type={'secondary'}>+ {t('environments.meta.createdAt', {+ time: dayjs(environment.createdAt).fromNow(),+ })}+ </Text>+ </Tooltip>+ </Flexbox>+ </Flexbox>+ </Flexbox>++ {/* Said plainly, rather than letting someone discover it by typing+ into a field whose save would be refused. */}+ {!canEdit && (+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon icon={LockIcon} size={14} style={{ color: cssVar.colorTextTertiary }} />+ <Text fontSize={12} type={'secondary'}>+ {t('environments.visibility.readonlyHint')}+ </Text>+ </Flexbox>+ )}++ {configurationPending ? (+ <EnvironmentDefinitionSkeleton />+ ) : canEdit ? (+ <EnvironmentForm+ environment={environment}+ onSave={(changes) => actions.updateEnvironment({ ...changes, id: environment.id })}+ />+ ) : (+ <EnvironmentSummary environment={environment} />+ )}+ </Flexbox>+ );+ },+);++EnvironmentDetailPage.displayName = 'EnvironmentDetailPage';++export default EnvironmentDetailPage;diff --git a/src/features/EnvironmentManager/EnvironmentDetailPanel.tsx b/src/features/EnvironmentManager/EnvironmentDetailPanel.tsxdeleted file mode 100644index 2d8a2b1f4de..00000000000--- a/src/features/EnvironmentManager/EnvironmentDetailPanel.tsx+++ /dev/null@@ -1,238 +0,0 @@-'use client';--import { Github } from '@lobehub/icons';-import {- ActionIcon,- createStaticStyles,- cssVar,- Flexbox,- Icon,- Tabs,- Tag,- Text,- Tooltip,-} from '@lobehub/ui';-import dayjs from 'dayjs';-import {- FolderGit2Icon,- KeyRoundIcon,- LayoutDashboardIcon,- LockIcon,- SettingsIcon,- TerminalIcon,- XIcon,-} from 'lucide-react';-import { memo, useState } from 'react';-import { useTranslation } from 'react-i18next';--import UserAvatar from '@/components/UserAvatar';--import EnvironmentForm, { type EnvironmentFormSection } from './EnvironmentForm';-import PanelSection from './PanelSection';-import { repositoryPath } from './repository';-import { EnvironmentDefinitionSkeleton } from './Skeleton';-import TabPane from './TabPane';-import { useCanEditEnvironment } from './useCanEditEnvironment';-import { type SandboxEnvironment, useEnvironmentActions } from './useEnvironmentData';--const styles = createStaticStyles(({ css }) => ({- container: css`- padding-block: 16px;- padding-inline: 20px;- `,- header: css`- padding-block-end: 16px;- border-block-end: 1px solid ${cssVar.colorBorderSecondary};- `,- /** The same dot the row uses between its facts. */- metaDivider: css`- flex: none;-- width: 3px;- height: 3px;- border-radius: 50%;-- background: ${cssVar.colorTextQuaternary};- `,- iconTile: css`- display: flex;- flex: none;- align-items: center;- justify-content: center;-- width: 32px;- height: 32px;- border-radius: ${cssVar.borderRadius};-- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorFillTertiary};- `,-}));--type DetailTab = 'overview' | EnvironmentFormSection;--interface EnvironmentDetailPanelProps {- environment: SandboxEnvironment;- onClose: () => void;-}--/**- * Everything one environment is, beside the list it was picked from.- *- * The list answers which environment; this answers what it holds — who made it,- * which repository it checks out and what setup runs after. An environment is- * a one-time initializer and keeps no copies, so there is nothing else to show.- * Its editor gets the definition to change; everyone else who can use it reads- * what it will do. Splitting it this way is what lets the row stay scannable:- * a setup command is worth reading about one environment and worth nothing when- * comparing six.- *- * Read by id from the list rather than handed a snapshot: the form writes- * through to the same replica entry, so a copy taken at open time would go stale- * the moment someone saved.- */-const EnvironmentDetailPanel = memo<EnvironmentDetailPanelProps>(({ environment, onClose }) => {- const { t } = useTranslation('setting');- const actions = useEnvironmentActions();- const canEdit = useCanEditEnvironment()(environment);- // Local to the panel and reset with it (the panel is keyed on the- // environment), so opening another environment lands on its first tab.- const [picked, setTab] = useState<DetailTab>();- // An editor works in the definition; a reader only has the summary.- const tab: DetailTab = canEdit ? (picked === 'variables' ? 'variables' : 'settings') : 'overview';- // A row restored from storage has no configuration until the server answers:- // it carries `env`, so it is never stored. The definition waits for it rather- // than reading as empty — an editor saving over `{}` would erase it.- const configurationPending = environment.configuration === undefined;- const configuration = environment.configuration ?? {};- const repository = repositoryPath(configuration);-- const creator =- environment.creator?.fullName ||- environment.creator?.username ||- t('environments.meta.unknownCreator');-- return (- <Flexbox className={styles.container} gap={20}>- <Flexbox horizontal align={'center'} className={styles.header} gap={12}>- <span className={styles.iconTile}>- <Github size={18} />- </span>- <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>- <Text ellipsis weight={600}>- {environment.name}- </Text>- {/* One line of facts under the name, the way the row does it,- rather than a labelled block of its own below the header: who- made it and when are context for the name, not fields to- fill in. The absolute time here, the relative one in the row:- the list is scanned for "is this recent", the panel is read- for "when". */}- <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>- {environment.workspaceId && environment.visibility === 'public' && (- <Tag size={'small'}>{t('environments.visibility.publicTag')}</Tag>- )}- <Flexbox horizontal align={'center'} gap={6}>- <UserAvatar avatar={environment.creator?.avatar} name={creator} size={16} />- <Text fontSize={12} type={'secondary'}>- {creator}- </Text>- </Flexbox>- <span className={styles.metaDivider} />- {/* The same relative phrasing as the row, so the panel does not- answer "when" in a different voice; the exact instant is a- hover away. */}- <Tooltip title={new Date(environment.createdAt).toLocaleString()}>- <Text fontSize={12} type={'secondary'}>- {t('environments.meta.createdAt', {- time: dayjs(environment.createdAt).fromNow(),- })}- </Text>- </Tooltip>- </Flexbox>- </Flexbox>- <ActionIcon- icon={XIcon}- size={'small'}- title={t('environments.detail.close')}- onClick={onClose}- />- </Flexbox>-- {/* Said plainly, rather than letting someone discover it by typing into- a field whose save would be refused. A published environment is one- you can run in; reshaping it stays with whoever made it. */}- {!canEdit && (- <Flexbox horizontal align={'center'} gap={8}>- <Icon icon={LockIcon} size={14} style={{ color: cssVar.colorTextTertiary }} />- <Text fontSize={12} type={'secondary'}>- {t('environments.visibility.readonlyHint')}- </Text>- </Flexbox>- )}-- <Tabs- activeKey={tab}- styles={{ list: { maxWidth: '100%', overflowX: 'auto' } }}- items={- canEdit- ? [- {- icon: <Icon icon={SettingsIcon} size={16} />,- key: 'settings',- label: t('environments.detail.tabs.settings'),- },- {- icon: <Icon icon={KeyRoundIcon} size={16} />,- key: 'variables',- label: t('environments.form.env'),- },- ]- : [- {- icon: <Icon icon={LayoutDashboardIcon} size={16} />,- key: 'overview',- label: t('environments.detail.tabs.overview'),- },- ]- }- onChange={(key) => setTab(key as DetailTab)}- />-- {/* One column with no gap: the settings rail is drawn by each of its- sections and meets the next one's icon exactly, so any space- between them would show as a break in the line. */}- <Flexbox>- {configurationPending && <EnvironmentDefinitionSkeleton />}-- {!configurationPending && tab === 'overview' && (- <TabPane desc={t('environments.detail.initializerDesc')}>- <PanelSection icon={FolderGit2Icon} title={t('environments.form.sources')}>- <Text fontSize={13}>{repository ?? t('environments.detail.noRepository')}</Text>- </PanelSection>- <PanelSection last icon={TerminalIcon} title={t('environments.form.bootstrap')}>- <Text code={!!configuration.bootstrapCommand} fontSize={13}>- {configuration.bootstrapCommand || t('environments.detail.noSetup')}- </Text>- </PanelSection>- </TabPane>- )}-- {/* Every field saves itself, so nothing is lost by unmounting the- form on a tab switch and each tab mounts only what it shows. */}- {!configurationPending && canEdit && (tab === 'variables' || tab === 'settings') && (- <EnvironmentForm- environment={environment}- section={tab}- onSave={(changes) => actions.updateEnvironment({ ...changes, id: environment.id })}- />- )}- </Flexbox>- </Flexbox>- );-});--EnvironmentDetailPanel.displayName = 'EnvironmentDetailPanel';--export default EnvironmentDetailPanel;diff --git a/src/features/EnvironmentManager/EnvironmentForm.tsx b/src/features/EnvironmentManager/EnvironmentForm.tsxindex 4adb8b74277..3459dd4da6f 100644--- a/src/features/EnvironmentManager/EnvironmentForm.tsx+++ b/src/features/EnvironmentManager/EnvironmentForm.tsx@@ -1,13 +1,33 @@'use client';+import { layoutRepositorySources, repositoryFolderName } from '@lobechat/types';import { Github } from '@lobehub/icons';-import { ActionIcon, Button, createStaticStyles, cssVar, Flexbox, Text, toast } from '@lobehub/ui';-import { FolderGit2Icon, InfoIcon, PencilIcon, TerminalIcon } from 'lucide-react';-import { memo, useState } from 'react';+import {+ ActionIcon,+ Button,+ createStaticStyles,+ cssVar,+ Flexbox,+ Icon,+ Input,+ Text,+ toast,+} from '@lobehub/ui';+import {+ ChevronUpIcon,+ FolderIcon,+ GitBranchIcon,+ PencilIcon,+ PlusIcon,+ TerminalIcon,+ Trash2Icon,+} from 'lucide-react';+import { memo, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import useSWR from 'swr';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { parseGithubRepository } from '@/features/Projects/CreateFromGithub/githubRepository';import { environmentService, type SandboxEnvironmentSpecification } from '@/services/environment';import EnvironmentVariables from './EnvironmentVariables';@@ -15,18 +35,12 @@ import { describeError } from './errorMessage';import GithubRepositoryPicker, { type GithubRepositorySelection } from './GithubRepositoryPicker';import InlineField from './InlineField';import PanelSection from './PanelSection';-import TabPane from './TabPane';import type { SandboxEnvironment } from './useEnvironmentData';const styles = createStaticStyles(({ css }) => ({- /** The same box every other value sits in; here it holds a repository. */- box: css`- display: flex;- gap: 10px;- align-items: center;-- min-height: 36px;- padding-block: 6px;+ /** One repository: a row, with its fields underneath while edited. */+ item: css`+ padding-block: 8px;padding-inline: 12px;border: 1px solid ${cssVar.colorBorderSecondary};border-radius: ${cssVar.borderRadius};@@ -35,23 +49,161 @@ const styles = createStaticStyles(({ css }) => ({`,}));-/**- * Which part of the specification the form is showing. The panel splits it- * across two tabs; every field saves on its own, so the split is only about- * what is on screen.- */-export type EnvironmentFormSection = 'settings' | 'variables';+/** What the form reads of an environment: a standalone one, or a project's. */+export type EnvironmentFormValue = Pick<SandboxEnvironment, 'configuration' | 'name'> & {+ description?: string | null;+};interface EnvironmentFormProps {- environment: SandboxEnvironment;+ environment: EnvironmentFormValue;+ /**+ * Hides the name and description: a project's environment is named after+ * the project and edited as part of it.+ */+ hideBasics?: boolean;onSave: (params: {configuration?: SandboxEnvironmentSpecification;description?: string;name?: string;}) => Promise<void>;- section: EnvironmentFormSection;}+type GitSource = {+ kind: 'git';+ path?: string;+ ref?: string;+ setupCommand?: string;+ url: string;+};++/** `owner/name` of a GitHub checkout url, or nothing for any other url. */+const repositoryPathOf = (url: string) => {+ const match = /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(url);+ return match ? { owner: match[1], repository: match[2] } : undefined;+};++/**+ * One repository the environment checks out, as one row: which repository,+ * and at a glance the branch, the folder it lands in and its own setup. The+ * fields open on Edit — with several repositories, every field laid out at+ * once read as a form to fill rather than a list of what is there.+ */+const RepositoryRow = memo<{+ busy: boolean;+ onChange: (next: Partial<Omit<GitSource, 'kind' | 'url'>>) => Promise<void>;+ onRemove: () => void;+ source: GitSource;+}>(({ busy, onChange, onRemove, source }) => {+ const { t } = useTranslation('setting');+ const [editing, setEditing] = useState(false);+ const github = repositoryPathOf(source.url);+ const label = github ? `${github.owner}/${github.repository}` : source.url;+ // One line: the name, then each setting as an icon and its value. The+ // default branch says nothing worth a word, so it shows only when one is set.+ const facts = [+ ...(source.ref+ ? [{ icon: GitBranchIcon, title: t('environments.form.ref'), value: source.ref }]+ : []),+ ...(source.path+ ? [{ icon: FolderIcon, title: t('environments.form.path'), value: `${source.path}/` }]+ : []),+ ...(source.setupCommand+ ? [+ {+ icon: TerminalIcon,+ title: t('environments.form.bootstrap'),+ value: source.setupCommand.split('\n')[0],+ },+ ]+ : []),+ ];++ return (+ <div className={styles.item}>+ <Flexbox horizontal align={'center'} gap={12}>+ <Github size={16} />+ <Flexbox horizontal align={'center'} flex={1} gap={16} style={{ minWidth: 0 }}>+ <Text ellipsis style={{ flex: 'none', maxWidth: '50%' }} weight={500}>+ {label}+ </Text>+ {facts.map((fact) => (+ <Flexbox+ horizontal+ align={'center'}+ gap={4}+ key={fact.title}+ style={{ color: cssVar.colorTextSecondary, minWidth: 0 }}+ title={fact.title}+ >+ <Icon icon={fact.icon} size={13} style={{ flex: 'none' }} />+ <Text ellipsis fontSize={12} type={'secondary'}>+ {fact.value}+ </Text>+ </Flexbox>+ ))}+ </Flexbox>+ <ActionIcon+ active={editing}+ icon={editing ? ChevronUpIcon : PencilIcon}+ size={'small'}+ title={t(+ editing ? 'environments.form.doneEditing' : 'environments.form.editRepositorySettings',+ )}+ onClick={() => setEditing((open) => !open)}+ />+ <ActionIcon+ icon={Trash2Icon}+ loading={busy}+ size={'small'}+ title={t('environments.form.disconnect')}+ onClick={onRemove}+ />+ </Flexbox>+ {editing && (+ <Flexbox gap={12} style={{ marginTop: 12 }}>+ <Flexbox horizontal align={'flex-start'} gap={12}>+ <div style={{ flex: 1 }}>+ {github ? (+ <BranchField+ owner={github.owner}+ repository={github.repository}+ value={source.ref ?? ''}+ onSave={(ref) => onChange({ ref })}+ />+ ) : (+ <InlineField+ label={t('environments.form.ref')}+ placeholder={'main'}+ value={source.ref ?? ''}+ onSave={(ref) => onChange({ ref })}+ />+ )}+ </div>+ <div style={{ flex: 1 }}>+ <InlineField+ label={t('environments.form.path')}+ placeholder={'/'}+ value={source.path ?? ''}+ onSave={(path) => onChange({ path })}+ />+ </div>+ </Flexbox>+ <InlineField+ multiline+ desc={t('environments.form.repositorySetupHint')}+ label={t('environments.form.bootstrap')}+ placeholder={'pnpm install'}+ value={source.setupCommand ?? ''}+ onSave={(setupCommand) => onChange({ setupCommand })}+ />+ </Flexbox>+ )}+ </div>+ );+});++RepositoryRow.displayName = 'EnvironmentRepositoryRow';+/** Drop the keys a blank value would otherwise store as empty. */const compact = (configuration: SandboxEnvironmentSpecification): SandboxEnvironmentSpecification =>Object.fromEntries(@@ -111,8 +263,12 @@ const BranchField = memo<{BranchField.displayName = 'EnvironmentBranchField';/**- * An environment's specification: where its source material comes from and- * what makes it usable. An environment is a one-time initializer: the next+ * An environment's specification, laid out flat in one column: basics, the+ * repositories it checks out (each with its own setup), the setup that runs+ * after them, and the variables every command sees. Shared by an environment's+ * own page and a project's environment page.+ *+ * An environment is a one-time initializer: the next* working directory it is applied to is cloned and set up from what is saved* here, and a folder it was already applied to is left as it is.*@@ -121,16 +277,47 @@ BranchField.displayName = 'EnvironmentBranchField';* at the bottom of four sections, and changes typed above it were lost to a* tab switch before anyone scrolled down to it.*/-const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, onSave, section }) => {+const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, hideBasics, onSave }) => {const { t } = useTranslation('setting');const configuration = (environment.configuration ?? {}) as SandboxEnvironmentSpecification;const [pickingRepository, setPickingRepository] = useState(false);const [busy, setBusy] = useState(false);+ // Every field saves the whole specification, so two saves in flight at once+ // would each start from the same snapshot and the later one would undo the+ // earlier. Saves run one after another, each on top of the last one saved;+ // while none is running, the snapshot follows what the server returned.+ const latest = useRef(configuration);+ const pending = useRef(0);+ const queue = useRef<Promise<unknown> | undefined>(undefined);+ const stored = environment.configuration;+ useEffect(() => {+ if (pending.current === 0) latest.current = (stored ?? {}) as SandboxEnvironmentSpecification;+ }, [stored]);++ type Changes = Partial<SandboxEnvironmentSpecification>;+/** Write one change to the specification; the toast is the only trace a per-field save leaves. */- const saveConfiguration = async (changes: Partial<SandboxEnvironmentSpecification>) => {- const next = compact({ ...configuration, ...changes });- await onSave({ configuration: next });+ const saveConfiguration = async (+ changes: Changes | ((current: SandboxEnvironmentSpecification) => Changes),+ ) => {+ pending.current++;+ const task = (queue.current ?? Promise.resolve())+ .catch(() => {})+ .then(async () => {+ const current = latest.current;+ const next = compact({+ ...current,+ ...(typeof changes === 'function' ? changes(current) : changes),+ });+ await onSave({ configuration: next });+ latest.current = next;+ })+ .finally(() => {+ pending.current--;+ });+ queue.current = task;+ await task;toast.success(t('environments.form.saved'));};@@ -146,73 +333,107 @@ const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, onSave, secti}};- const source = configuration.sources?.[0];- const setSource = (next: Partial<{ path: string; ref: string; url: string }> | undefined) =>- saveConfiguration({- sources:- next === undefined- ? []- : [- {- kind: 'git' as const,- url: next.url ?? source?.url ?? '',- ...((next.path ?? source?.path) && { path: next.path ?? source?.path }),- ...((next.ref ?? source?.ref) && { ref: next.ref ?? source?.ref }),- },- ],+ // Every repository, in the order they are checked out; anything that is+ // not a git source (an old `files` one) is kept as it is.+ const sources = configuration.sources ?? [];+ const repositories = sources.filter((source): source is GitSource => source.kind === 'git');+ /** Rewrites the repositories as they stand when the save runs, keeping other sources. */+ const saveRepositories = (update: (current: GitSource[]) => GitSource[]) =>+ saveConfiguration((current) => {+ const all = current.sources ?? [];+ const git = all.filter((source): source is GitSource => source.kind === 'git');+ return { sources: [...update(git), ...all.filter((source) => source.kind !== 'git')] };});- // The picker speaks in owner/name; the specification stores a checkout URL.- const repositoryPath = source?.url.replace(/^https:\/\/github\.com\//, '').replace(/\.git$/, '');- const selection = (() => {- const [owner, repository] = repositoryPath?.split('/') ?? [];- return owner && repository ? { defaultBranch: source?.ref, owner, repository } : undefined;- })();+ const folderOf = (path: string | undefined) =>+ path+ ?.trim()+ .replace(/^\.?\/+/, '')+ .replace(/\/+$/, '') || undefined;- const pickRepository = (picked: GithubRepositorySelection | undefined) => {- if (!picked) return;- setPickingRepository(false);- // A repository just chosen keeps whatever folder was set, but takes the- // new repository's default branch — the old branch belonged to the old one.- void run(() =>- saveConfiguration({- sources: [- {- kind: 'git' as const,- ...(source?.path && { path: source.path }),- ...(picked.defaultBranch && { ref: picked.defaultBranch }),- url: `https://github.com/${picked.owner}/${picked.repository}`,- },- ],+ const updateRepository = (url: string, changes: Partial<Omit<GitSource, 'kind' | 'url'>>) => {+ // Two checkouts in one folder would merge into each other.+ const folder = changes.path === undefined ? undefined : folderOf(changes.path);+ if (+ folder &&+ repositories.some((source) => source.url !== url && folderOf(source.path) === folder)+ )+ return Promise.reject(new Error(t('environments.form.duplicateFolder')));++ return saveRepositories((current) =>+ current.map((source) => {+ if (source.url !== url) return source;+ const next = { ...source, ...changes };+ // A blank field means "the default", which is the key left out.+ if (!next.ref) delete next.ref;+ if (!next.path) delete next.path;+ if (!next.setupCommand?.trim()) delete next.setupCommand;+ return next;}),);};- if (section === 'variables') {- return (- /* Said plainly because the shape cannot enforce it: a text field cannot- tell a region from a token. */- <TabPane- desc={- <>- {t('environments.form.envHint')} {t('environments.form.appliesOnInit')}- </>+ // The last repository left goes back to the top of the working directory+ // when its folder was only the one it got for sitting beside another.+ const removeRepository = (url: string) =>+ run(() =>+ saveRepositories((current) => {+ const rest = current.filter((source) => source.url !== url);+ if (rest.length === 1 && rest[0].path === repositoryFolderName(rest[0].url)) {+ const { path: _path, ...only } = rest[0];+ return [only];}- >- <EnvironmentVariables- entries={Object.entries(configuration.env ?? {})}- onSave={(entries) => saveConfiguration({ env: Object.fromEntries(entries) })}- />- </TabPane>+ return rest;+ }),);- }++ const [pastedUrl, setPastedUrl] = useState('');++ const pasted = parseGithubRepository(pastedUrl);++ const pastedInvalid = Boolean(pastedUrl.trim()) && !pasted;++ const addPasted = () => {+ if (!pasted) return;++ const [owner, repository] = pasted.fullName.split('/');++ addRepository({ owner, repository });++ setPastedUrl('');+ };++ const addRepository = (picked: GithubRepositorySelection | undefined) => {+ if (!picked) return;+ setPickingRepository(false);+ const url = `https://github.com/${picked.owner}/${picked.repository}`;+ if (+ repositories.some(+ (source) =>+ repositoryPathOf(source.url)?.repository === picked.repository &&+ repositoryPathOf(source.url)?.owner === picked.owner,+ )+ )+ return;+ // One repository is checked out at the top of the working directory;+ // several sit side by side, each in a folder named after it.+ void run(() =>+ saveRepositories(+ (current) =>+ layoutRepositorySources([+ ...current,+ {+ kind: 'git' as const,+ url,+ ...(picked.defaultBranch && { ref: picked.defaultBranch }),+ },+ ]) as GitSource[],+ ),+ );+ };const basics = (- <PanelSection- desc={t('environments.form.desc')}- icon={InfoIcon}- title={t('environments.form.basics')}- >+ <PanelSection title={t('environments.form.basics')}><InlineFieldrequiredlabel={t('environments.nameLabel')}@@ -231,11 +452,10 @@ const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, onSave, sectireturn (<Flexbox>- {basics}+ {!hideBasics && basics}<PanelSectiondesc={t('environments.form.sourcesHint')}- icon={FolderGit2Icon}title={t('environments.form.sources')}notice={/* When an edit here reaches an instance, which is the question this@@ -244,85 +464,83 @@ const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, onSave, secti— and a rebuild replays that one rather than reading theenvironment again. So an edit reaches new instances only, andsaying "rebuild to apply" would send people to a button that- cannot do it. Repeated on the setup section and the variables tab,- which are governed by the same snapshot. */+ cannot do it. Said once, here at the top: setup and variables are+ governed by the same snapshot. */<Text fontSize={12} type={'secondary'}>{t('environments.form.appliesOnInit')}</Text>}>- {/* One repository, so no list and no way to add a second. At rest it- is a box naming the repository with a pencil and a disconnect,- the way Railway shows a service's source; the same picker the- create dialog uses takes over while a different one is chosen. */}- {selection && !pickingRepository ? (- <div className={styles.box}>- <Github size={16} />- <Text ellipsis style={{ flex: 1 }} weight={500}>- {repositoryPath}- </Text>- <ActionIcon- icon={PencilIcon}- size={'small'}- title={t('environments.form.changeRepository')}- onClick={() => setPickingRepository(true)}- />- <Button loading={busy} size={'small'} onClick={() => run(() => setSource(undefined))}>- {t('environments.form.disconnect')}- </Button>- </div>- ) : (+ {repositories.length === 0 && !pickingRepository && (+ <Text fontSize={13} type={'secondary'}>+ {t('environments.form.noRepositories')}+ </Text>+ )}+ {repositories.length > 0 && (<Flexbox gap={8}>- <GithubRepositoryPicker value={selection} onChange={pickRepository} />- {selection && (- <Flexbox horizontal>- <Button size={'small'} onClick={() => setPickingRepository(false)}>- {t('cancel', { ns: 'common' })}- </Button>- </Flexbox>- )}+ {repositories.map((source) => (+ <RepositoryRow+ busy={busy}+ key={source.url}+ source={source}+ onChange={(changes) => updateRepository(source.url, changes)}+ onRemove={() => removeRepository(source.url)}+ />+ ))}</Flexbox>)}-- {source && (- <Flexbox horizontal align={'flex-start'} gap={12}>- <div style={{ flex: 1 }}>- {selection ? (- <BranchField- owner={selection.owner}- repository={selection.repository}- value={source.ref ?? ''}- onSave={(ref) => setSource({ ref })}- />- ) : (- <InlineField- label={t('environments.form.ref')}- placeholder={'main'}- value={source.ref ?? ''}- onSave={(ref) => setSource({ ref })}+ {pickingRepository ? (+ <Flexbox gap={8}>+ <GithubRepositoryPicker onChange={addRepository} />+ {/* Any public repository, whether or not GitHub is connected —+ the same fallback the create dialog offers. */}+ <Flexbox gap={6}>+ <Text fontSize={12} type={'secondary'}>+ {t('environments.form.pasteRepository')}+ </Text>+ <Flexbox horizontal gap={8}>+ <Input+ aria-invalid={pastedInvalid}+ placeholder={'https://github.com/owner/repo'}+ style={pastedInvalid ? { borderColor: cssVar.colorError } : undefined}+ value={pastedUrl}+ onChange={(event) => setPastedUrl(event.target.value)}+ onPressEnter={addPasted}/>+ <Button disabled={!pasted} onClick={addPasted}>+ {t('environments.form.addPastedRepository')}+ </Button>+ </Flexbox>+ {pastedInvalid && (+ <Text fontSize={12} type={'danger'}>+ {t('environments.form.repositoryUrlInvalid')}+ </Text>)}- </div>- <div style={{ flex: 1 }}>- <InlineField- label={t('environments.form.path')}- placeholder={'/'}- value={source.path ?? ''}- onSave={(path) => setSource({ path })}- />- </div>+ </Flexbox>+ <Flexbox horizontal>+ <Button size={'small'} onClick={() => setPickingRepository(false)}>+ {t('cancel', { ns: 'common' })}+ </Button>+ </Flexbox>+ </Flexbox>+ ) : (+ <Flexbox horizontal>+ <Button+ icon={<Icon icon={PlusIcon} />}+ loading={busy}+ size={'small'}+ onClick={() => setPickingRepository(true)}+ >+ {t('environments.form.addRepository')}+ </Button></Flexbox>)}</PanelSection><PanelSection- last- icon={TerminalIcon}title={t('environments.form.setup')}- notice={- <Text fontSize={12} type={'secondary'}>- {t('environments.form.appliesOnInit')}- </Text>+ desc={+ repositories.length > 0 ? t('environments.form.bootstrapAfterRepositories') : undefined}><InlineField@@ -334,6 +552,15 @@ const EnvironmentForm = memo<EnvironmentFormProps>(({ environment, onSave, sectionSave={(bootstrapCommand) => saveConfiguration({ bootstrapCommand })}/></PanelSection>++ {/* Said plainly because the shape cannot enforce it: a text field+ cannot tell a region from a token. */}+ <PanelSection desc={t('environments.form.envHint')} title={t('environments.form.env')}>+ <EnvironmentVariables+ entries={Object.entries(configuration.env ?? {})}+ onSave={(entries) => saveConfiguration({ env: Object.fromEntries(entries) })}+ />+ </PanelSection></Flexbox>);});diff --git a/src/features/EnvironmentManager/EnvironmentItem.tsx b/src/features/EnvironmentManager/EnvironmentItem.tsxindex 36a2fe6ec3f..6b808d1abea 100644--- a/src/features/EnvironmentManager/EnvironmentItem.tsx+++ b/src/features/EnvironmentManager/EnvironmentItem.tsx@@ -131,7 +131,7 @@ interface EnvironmentItemProps {* repository is this, and who put it here. Every* other property of an environment — setup command, variables, branch — is a* detail of one environment rather than a way to tell environments apart, so it- * lives in the panel this row opens.+ * lives on the page this row opens.*/const EnvironmentItem = memo<EnvironmentItemProps>((props) => {const { environment, extra, menuItems, onSelect, selected } = props;diff --git a/src/features/EnvironmentManager/EnvironmentSummary.tsx b/src/features/EnvironmentManager/EnvironmentSummary.tsxnew file mode 100644index 00000000000..b226157ab79--- /dev/null+++ b/src/features/EnvironmentManager/EnvironmentSummary.tsx@@ -0,0 +1,68 @@+'use client';++import { Flexbox, Text } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { EnvironmentFormValue } from './EnvironmentForm';+import PanelSection from './PanelSection';++/**+ * What someone who cannot change an environment reads: what it will do — the+ * repositories it checks out with their own setup, the setup after them, and+ * which variables it sets (names only). Laid out like the form, flat.+ */+const EnvironmentSummary = memo<{ environment: EnvironmentFormValue }>(({ environment }) => {+ const { t } = useTranslation('setting');+ const configuration = environment.configuration ?? {};+ const repositories = (configuration.sources ?? []).flatMap((source) =>+ source.kind === 'git' && source.url+ ? [+ {+ name: source.url.replace(/^https:\/\/github\.com\//, '').replace(/\.git$/, ''),+ setupCommand: (source as { setupCommand?: string }).setupCommand,+ },+ ]+ : [],+ );+ const variables = Object.keys(configuration.env ?? {});++ return (+ <Flexbox>+ <PanelSection title={t('environments.form.sources')}>+ {repositories.length > 0 ? (+ repositories.map((repository) => (+ <Flexbox gap={4} key={repository.name}>+ <Text fontSize={13} weight={500}>+ {repository.name}+ </Text>+ {repository.setupCommand && (+ <Text code fontSize={12}>+ {repository.setupCommand}+ </Text>+ )}+ </Flexbox>+ ))+ ) : (+ <Text fontSize={13} type={'secondary'}>+ {t('environments.detail.noRepository')}+ </Text>+ )}+ </PanelSection>+ <PanelSection title={t('environments.form.setup')}>+ <Text code={!!configuration.bootstrapCommand} fontSize={13}>+ {configuration.bootstrapCommand || t('environments.detail.noSetup')}+ </Text>+ </PanelSection>+ <PanelSection title={t('environments.form.env')}>+ <Text fontSize={13} type={variables.length ? undefined : 'secondary'}>+ {variables.length ? variables.join(', ') : t('environments.form.noVariables')}+ </Text>+ </PanelSection>+ </Flexbox>+ );+});++EnvironmentSummary.displayName = 'EnvironmentSummary';++export default EnvironmentSummary;diff --git a/src/features/EnvironmentManager/EnvironmentVariables.tsx b/src/features/EnvironmentManager/EnvironmentVariables.tsxindex 5b35c6d23d2..36d38437473 100644--- a/src/features/EnvironmentManager/EnvironmentVariables.tsx+++ b/src/features/EnvironmentManager/EnvironmentVariables.tsx@@ -282,10 +282,9 @@ const EnvironmentVariables = memo<EnvironmentVariablesProps>(({ entries, onSavereturn (<Flexbox gap={12}><Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>- <Text weight={600}>- {entries.length === 0- ? t('environments.form.env')- : t('environments.form.envCount', { count: entries.length })}+ {/* The section around this editor carries its title; only the count is said here. */}+ <Text fontSize={12} type={'secondary'}>+ {entries.length > 0 && t('environments.form.envCount', { count: entries.length })}</Text><Flexbox horizontal align={'center'} gap={4}>{raw === null ? (diff --git a/src/features/EnvironmentManager/GithubRepositoryPicker.tsx b/src/features/EnvironmentManager/GithubRepositoryPicker.tsxindex 7f54236b79b..0cfefd0125b 100644--- a/src/features/EnvironmentManager/GithubRepositoryPicker.tsx+++ b/src/features/EnvironmentManager/GithubRepositoryPicker.tsx@@ -139,7 +139,9 @@ const GithubRepositoryPicker = memo<GithubRepositoryPickerProps>(({ onChange, on),}: state === 'unconfigured'- ? { action: undefined, text: t('environments.github.unconfigured') }+ ? // Connecting needs the deployment's GitHub App first; the settings+ // page says what is missing, so the guide still leads somewhere.+ { action: 'settings', text: t('environments.github.unconfigured') }: state === 'disconnected'? { action: 'connect', text: t('environments.github.notConnected') }: state === 'empty'@@ -160,7 +162,9 @@ const GithubRepositoryPicker = memo<GithubRepositoryPickerProps>(({ onChange, on: t(guide.action === 'connect'? 'environments.github.connect'- : 'environments.github.reviewAccess',+ : guide.action === 'settings'+ ? 'environments.github.openIntegrations'+ : 'environments.github.reviewAccess',)}{guide.action !== 'retry' && <Icon icon={ArrowRightIcon} size={12} />}</Button>diff --git a/src/features/EnvironmentManager/PanelSection.tsx b/src/features/EnvironmentManager/PanelSection.tsxindex ac8550fbb09..d265ae47baf 100644--- a/src/features/EnvironmentManager/PanelSection.tsx+++ b/src/features/EnvironmentManager/PanelSection.tsx@@ -1,87 +1,49 @@'use client';-import { createStaticStyles, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';-import type { LucideIcon } from 'lucide-react';+import { Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';import { memo, type ReactNode } from 'react';-const styles = createStaticStyles(({ css }) => ({- icon: css`- display: flex;- flex: none;- align-items: center;- justify-content: center;-- width: 32px;- height: 32px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: 50%;-- color: ${cssVar.colorTextSecondary};-- background: ${cssVar.colorBgContainer};- `,- /**- * The connector, as its own element in the icon's column rather than a border- * on the content beside it. A border there began below the icon row and ended- * with the content, so every heading left a gap the width of its own icon and- * the rail arrived in pieces. Stretched to fill what the content leaves over,- * it meets the next section's icon exactly.- */- line: css`- flex: 1;- width: 1px;- margin-block: 4px;- background: ${cssVar.colorBorderSecondary};- `,-}));+const styles = stylex.create({+ group: {+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: {+ ':last-child': 'none',+ 'default': 'solid',+ },+ borderBlockEndWidth: 1,+ paddingBlock: 24,+ },+});interface PanelSectionProps {children: ReactNode;desc?: ReactNode;- icon: LucideIcon;- /** Drops the connector below this section, which would otherwise dangle. */- last?: boolean;- /** Sits under the description, for something true of this section only. */+ /** Sits under the description, for something true of this group only. */notice?: ReactNode;title: ReactNode;}/**- * One titled part of the detail panel, on a rail of its own.- *- * The panel used to be a single column of eight fields with nothing between- * them, so finding the setup command meant reading every label on the way. The- * rail gives each part a heading you can skip to and an icon to recognise it- * by, without the nested cards that grouping usually costs — this panel is- * already a card, and boxes inside boxes were how it got crowded before.- *- * Railway's settings page is the reference. Its right-hand jump list is not,- * because this panel is half a page wide and that nav would take the half that- * holds the fields.+ * One group of an environment's form: a title, what it is for, then its+ * fields. Groups sit one under another with a rule between them — they are+ * parts of one definition, not steps, so nothing draws them as a sequence.*/-const PanelSection = memo<PanelSectionProps>(({ children, desc, icon, last, notice, title }) => (- <Flexbox horizontal align={'stretch'} gap={12}>- <Flexbox align={'center'} style={{ flex: 'none' }}>- <span className={styles.icon}>- <Icon icon={icon} size={15} />- </span>- {!last && <div className={styles.line} />}- </Flexbox>-- <Flexbox flex={1} gap={12} paddingBlock={'4px 24px'} style={{ minWidth: 0 }}>- <Text weight={600}>{title}</Text>- {(desc || notice) && (- <Flexbox gap={4}>- {desc && (- <Text fontSize={12} type={'secondary'}>- {desc}- </Text>- )}- {notice}- </Flexbox>+const PanelSection = memo<PanelSectionProps>(({ children, desc, notice, title }) => (+ <Flexbox gap={12} {...stylex.props(styles.group)}>+ <Flexbox gap={4}>+ <Text fontSize={15} weight={600}>+ {title}+ </Text>+ {desc && (+ <Text fontSize={12} type={'secondary'}>+ {desc}+ </Text>)}- <Flexbox gap={16}>{children}</Flexbox>+ {notice}</Flexbox>+ <Flexbox gap={16}>{children}</Flexbox></Flexbox>));diff --git a/src/features/EnvironmentManager/TabPane.tsx b/src/features/EnvironmentManager/TabPane.tsxdeleted file mode 100644index 4051de9f8e4..00000000000--- a/src/features/EnvironmentManager/TabPane.tsx+++ /dev/null@@ -1,31 +0,0 @@-'use client';--import { Flexbox, Text } from '@lobehub/ui';-import { memo, type ReactNode } from 'react';--interface TabPaneProps {- children: ReactNode;- desc?: ReactNode;-}--/**- * The body of a tab that holds one thing.- *- * The tab strip already names it, so a rail heading under the strip said the- * same words twice with an icon between them. Only the settings tab keeps the- * rail, because it holds several sections and the rail is what tells them apart.- */-const TabPane = memo<TabPaneProps>(({ children, desc }) => (- <Flexbox gap={16} paddingBlock={'4px 24px'}>- {desc && (- <Text fontSize={12} type={'secondary'}>- {desc}- </Text>- )}- {children}- </Flexbox>-));--TabPane.displayName = 'TabPane';--export default TabPane;diff --git a/src/features/EnvironmentManager/index.tsx b/src/features/EnvironmentManager/index.tsxindex 3eda8c012b7..b34c2c5c853 100644--- a/src/features/EnvironmentManager/index.tsx+++ b/src/features/EnvironmentManager/index.tsx@@ -18,21 +18,11 @@ import { useTranslation } from 'react-i18next';import AsyncBoundary from '@/components/AsyncBoundary';import { openCreateEnvironmentModal } from './CreateEnvironmentModal';-import EnvironmentDetailPanel from './EnvironmentDetailPanel';import EnvironmentItem from './EnvironmentItem';import { EnvironmentListSkeleton } from './Skeleton';import { type CreatedEnvironment, useEnvironments } from './useEnvironmentData';const styles = createStaticStyles(({ css }) => ({- detailCol: css`- align-self: stretch;-- min-width: 0;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};-- background: ${cssVar.colorBgContainer};- `,/*** One frame around the list, on the page's own surface. A settings group* would nest a card inside a card and inset every row by its own padding,@@ -48,13 +38,6 @@ const styles = createStaticStyles(({ css }) => ({background: ${cssVar.colorBgContainer};`,- listScroll: css`- overflow-y: auto;-- /* Cap the list so a long shelf of environments stays scrollable rather than- pushing the page down past the panel sitting beside it. */- max-height: 480px;- `,}));/** What the list occupies before it knows its length — the skeleton's own rows. */@@ -70,11 +53,14 @@ const LIST_MIN_HEIGHT = 4 * 72;* by hand. Folders are initialized from the directory picker's "new folder";* this page lists them, rebuilds, stops and deletes them.*- * List beside detail, the shape the device manager uses: the rows carry only- * what tells one environment from another, and picking one opens everything- * else about it next to the list rather than in place of it.+ * A list; picking a row opens the environment's own page+ * (`environments/:id`), the shape the device manager uses. The rows carry only+ * what tells one environment from another; everything else about one is on+ * its page, laid out the same way a project's environment page is.*/interface EnvironmentManagerProps {+ /** Open one environment's page. */+ onOpenEnvironment: (id: string) => void;/*** Put beside the actions rather than above them, so the page has one header* row instead of two. Passed in rather than built here because only a page@@ -90,158 +76,133 @@ interface EnvironmentManagerProps {visibility?: EnvironmentVisibility;}-const EnvironmentManager = memo<EnvironmentManagerProps>(({ tabs, visibility }) => {- const { t } = useTranslation('setting');- // `settled`: a list to paint — the stored one on a reload, confirmed behind- // it, a tab switch included. A stored empty list waits for the server.- const { environments, error, revalidate, settled } = useEnvironments(visibility);-- const [selectedId, setSelectedId] = useState<string>();- // Whether a refresh the user asked for is still running.- const [refreshing, setRefreshing] = useState(false);-- const list = environments ?? [];- const selected = selectedId- ? list.find((environment) => environment.id === selectedId)- : undefined;-- const select = (id: string) => {- setSelectedId((current) => (current === id ? undefined : id));- };-- // Open what was just made. Nothing is built: an environment is applied to- // a working directory when a conversation picks it.- const onEnvironmentCreated = (created: CreatedEnvironment) => setSelectedId(created.id);-- /**- * The spinner is driven by this call rather than by `isValidating`, which is- * true of every fetch the page makes — read off that flag the button would- * spin on a tab switch and on any background revalidation.- */- const refresh = async () => {- setRefreshing(true);- try {- await revalidate();- } finally {- setRefreshing(false);- }- };-- /**- * The way to add one, and the way to refetch. Shared by both layouts because- * they are the same things wherever they sit; only the frame around them- * differs. How much of the drive is used is the plan's business, and is- * shown with the plan's other usage rather than here.- */- const actions = (- // `flex: none`, because this shares a `space-between` row with whatever- // names the list. Left shrinkable, the group gets compressed by a wide- // neighbour.- <Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>- <Button- icon={<Icon icon={RefreshCwIcon} />}- loading={refreshing}- title={t('environments.refresh')}- onClick={refresh}- />- <Button- icon={<Icon icon={PlusIcon} />}- type={'primary'}- onClick={() => openCreateEnvironmentModal(visibility, onEnvironmentCreated)}- >- {t('environments.create')}- </Button>- </Flexbox>- );-- const content = (- <AsyncBoundary- // A failed background refresh keeps the list it has: the boundary shows- // the error only while nothing has settled.- data={settled ? environments : undefined}- error={error}- errorVariant={'block'}- isEmpty={settled && list.length === 0}- isLoading={!settled && !error}- loading={<EnvironmentListSkeleton />}- empty={- // Inside the same frame the rows land in, sized to the skeleton's- // rows: loading, empty and loaded are one surface whose contents- // change, not three surfaces of three different heights.- <Flexbox className={styles.listCol}>- <Center style={{ minHeight: LIST_MIN_HEIGHT }} width={'100%'}>- <Empty- description={t('environments.desc')}- descriptionProps={{ fontSize: 13 }}- icon={ContainerIcon}- style={{ maxWidth: 360 }}- action={- <Button- icon={<Icon icon={PlusIcon} />}- onClick={() => openCreateEnvironmentModal(visibility, onEnvironmentCreated)}- >- {t('environments.create')}- </Button>- }- title={t(- visibility === 'public' ? 'environments.emptyPublished' : 'environments.empty',- )}- />- </Center>- </Flexbox>+const EnvironmentManager = memo<EnvironmentManagerProps>(+ ({ onOpenEnvironment, tabs, visibility }) => {+ const { t } = useTranslation('setting');+ // `settled`: a list to paint — the stored one on a reload, confirmed behind+ // it, a tab switch included. A stored empty list waits for the server.+ const { environments, error, revalidate, settled } = useEnvironments(visibility);++ // Whether a refresh the user asked for is still running.+ const [refreshing, setRefreshing] = useState(false);++ const list = environments ?? [];++ // Open what was just made. Nothing is built: an environment is applied to+ // a working directory when a conversation picks it.+ const onEnvironmentCreated = (created: CreatedEnvironment) => onOpenEnvironment(created.id);++ /**+ * The spinner is driven by this call rather than by `isValidating`, which is+ * true of every fetch the page makes — read off that flag the button would+ * spin on a tab switch and on any background revalidation.+ */+ const refresh = async () => {+ setRefreshing(true);+ try {+ await revalidate();+ } finally {+ setRefreshing(false);}- onRetry={refresh}- >- <Flexbox horizontal align={'flex-start'} gap={16} wrap={'wrap'}>- <Flexbox className={styles.listCol} flex={'1 1 320px'}>- <Flexbox className={styles.listScroll} gap={2} padding={4}>- {list.map((environment) => (- <EnvironmentItem- environment={environment}- key={environment.id}- selected={environment.id === selectedId}- onSelect={() => select(environment.id)}+ };++ /**+ * The way to add one, and the way to refetch. Shared by both layouts because+ * they are the same things wherever they sit; only the frame around them+ * differs. How much of the drive is used is the plan's business, and is+ * shown with the plan's other usage rather than here.+ */+ const actions = (+ // `flex: none`, because this shares a `space-between` row with whatever+ // names the list. Left shrinkable, the group gets compressed by a wide+ // neighbour.+ <Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>+ <Button+ icon={<Icon icon={RefreshCwIcon} />}+ loading={refreshing}+ title={t('environments.refresh')}+ onClick={refresh}+ />+ <Button+ icon={<Icon icon={PlusIcon} />}+ type={'primary'}+ onClick={() => openCreateEnvironmentModal(visibility, onEnvironmentCreated)}+ >+ {t('environments.create')}+ </Button>+ </Flexbox>+ );++ const content = (+ <AsyncBoundary+ // A failed background refresh keeps the list it has: the boundary shows+ // the error only while nothing has settled.+ data={settled ? environments : undefined}+ error={error}+ errorVariant={'block'}+ isEmpty={settled && list.length === 0}+ isLoading={!settled && !error}+ loading={<EnvironmentListSkeleton />}+ empty={+ // Inside the same frame the rows land in, sized to the skeleton's+ // rows: loading, empty and loaded are one surface whose contents+ // change, not three surfaces of three different heights.+ <Flexbox className={styles.listCol}>+ <Center style={{ minHeight: LIST_MIN_HEIGHT }} width={'100%'}>+ <Empty+ description={t('environments.desc')}+ descriptionProps={{ fontSize: 13 }}+ icon={ContainerIcon}+ style={{ maxWidth: 360 }}+ action={+ <Button+ icon={<Icon icon={PlusIcon} />}+ onClick={() => openCreateEnvironmentModal(visibility, onEnvironmentCreated)}+ >+ {t('environments.create')}+ </Button>+ }+ title={t(+ visibility === 'public' ? 'environments.emptyPublished' : 'environments.empty',+ )}/>- ))}+ </Center></Flexbox>- </Flexbox>- {/* Keep enough space to identify environments and read their details.- When both columns no longer fit, wrap the detail below the list. */}- {selected && (- <Flexbox className={styles.detailCol} flex={'2 1 480px'}>- {/* Keyed on the environment so the form's draft state resets when- the selection changes — a description typed for one- environment must not survive into another. */}- <EnvironmentDetailPanel- environment={selected}- key={selected.id}- onClose={() => setSelectedId(undefined)}+ }+ onRetry={refresh}+ >+ <Flexbox className={styles.listCol} gap={2} padding={4}>+ {list.map((environment) => (+ <EnvironmentItem+ environment={environment}+ key={environment.id}+ onSelect={() => onOpenEnvironment(environment.id)}/>- </Flexbox>- )}- </Flexbox>- </AsyncBoundary>- );-- /**- * One layout for both pages. What sits on the left of the header is the only- * difference: tabs where there is a pool to choose, and the section's own- * name where there is not.- */- return (- <Flexbox gap={16}>- <Flexbox horizontal align={'center'} gap={16} justify={'space-between'} wrap={'wrap'}>- {tabs ?? (- <Text fontSize={16} weight={600}>- {t('environments.mine')}- </Text>- )}- {actions}+ ))}+ </Flexbox>+ </AsyncBoundary>+ );++ /**+ * One layout for both pages. What sits on the left of the header is the only+ * difference: tabs where there is a pool to choose, and the section's own+ * name where there is not.+ */+ return (+ <Flexbox gap={16}>+ <Flexbox horizontal align={'center'} gap={16} justify={'space-between'} wrap={'wrap'}>+ {tabs ?? (+ <Text fontSize={16} weight={600}>+ {t('environments.mine')}+ </Text>+ )}+ {actions}+ </Flexbox>+ {content}</Flexbox>- {content}- </Flexbox>- );-});+ );+ },+);EnvironmentManager.displayName = 'EnvironmentManager';diff --git a/src/features/EnvironmentManager/repository.ts b/src/features/EnvironmentManager/repository.tsindex efd3407b73f..92610793fa7 100644--- a/src/features/EnvironmentManager/repository.ts+++ b/src/features/EnvironmentManager/repository.ts@@ -22,3 +22,11 @@ export const repositoryPath = (configuration?: SourcedConfiguration): string | ureturn path || undefined;};++/** Every repository an environment checks out, as `owner/name` (or the url when not GitHub). */+export const repositoryPaths = (configuration?: SourcedConfiguration): string[] =>+ (configuration?.sources ?? []).flatMap((source) => {+ if (source.kind !== 'git' || !source.url) return [];+ const path = source.url.replace(/^https:\/\/github\.com\//, '').replace(/\.git$/, '');+ return path ? [path] : [];+ });diff --git a/src/features/Projects/AddEnvironmentModal.tsx b/src/features/Projects/AddEnvironmentModal.tsxdeleted file mode 100644index de76f0eb176..00000000000--- a/src/features/Projects/AddEnvironmentModal.tsx+++ /dev/null@@ -1,264 +0,0 @@-'use client';--import {- Button,- createModal,- cssVar as lobeCssVar,- Flexbox,- Input,- ModalFooter,- Segmented,- Text,- toast,- useModalContext,-} from '@lobehub/ui';-import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';-import * as stylex from '@stylexjs/stylex';-import { t as translate } from 'i18next';-import { CheckIcon } from 'lucide-react';-import { useState } from 'react';-import { useTranslation } from 'react-i18next';--import AsyncError from '@/components/AsyncError';-import RepositoryAvatar from '@/components/RepositoryAvatar';-import { repositorySlug } from '@/features/ChatInput/ControlBar/sandboxEnvironmentOptions';-import { GITHUB_RETURN_TO } from '@/features/Integrations/Github/installHref';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { useProjectDirectoryStore, useProjectEnvironments } from '@/store/projectWorkingDirectory';--import { parseGithubRepository } from './CreateFromGithub/githubRepository';-import RepositoryList from './CreateFromGithub/RepositoryList';-import { environmentRepositoryUrl, reusableEnvironments } from './environmentSource';--const styles = stylex.create({- list: {- overflowY: 'auto',- maxHeight: '300px',- borderWidth: '1px',- borderStyle: 'solid',- borderColor: cssVar.colorBorderSecondary,- borderRadius: cssVar.borderRadius,- },- row: {- cursor: 'pointer',- display: 'flex',- gap: '12px',- alignItems: 'center',- width: '100%',- paddingBlock: '8px',- paddingInline: '12px',- borderBlockStartWidth: 0,- borderBlockEndWidth: '1px',- borderBlockEndStyle: { 'default': 'solid', ':last-child': 'none' },- borderBlockEndColor: cssVar.colorBorderSecondary,- borderInlineWidth: 0,- font: 'inherit',- color: 'inherit',- textAlign: 'start',- backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },- },- selected: {- backgroundColor: { 'default': cssVar.colorFillSecondary, ':hover': cssVar.colorFillSecondary },- },- check: {- flex: 'none',- color: cssVar.colorPrimary,- },-});--type Source = 'existing' | 'github';--interface AddEnvironmentContentProps {- /**- * Where the dialog opens. A project's environment list opens it on the- * environments already configured, since making one has its own button there.- */- defaultSource?: Source;- /** Called with the environment now linked to the project. */- onAdded?: (environmentId: string) => void;- projectId: string;- /**- * The project's conversations run a workspace-public agent, which applies- * published environments only: a new repository is published, and only- * published environments are offered for reuse.- */- publish?: boolean;-}--/**- * The one way to give a project an environment: a GitHub repository — one the- * connected GitHub App can read, or a pasted URL — or an environment the person- * already has, linked as it is.- */-const AddEnvironmentContent = ({- defaultSource = 'github',- onAdded,- projectId,- publish,-}: AddEnvironmentContentProps) => {- const { t } = useTranslation(['project', 'common']);- const { close } = useModalContext();- const navigate = useWorkspaceAwareNavigate();- const attachRepository = useProjectDirectoryStore((s) => s.attachRepository);- const attachEnvironment = useProjectDirectoryStore((s) => s.attachEnvironment);- const available = useProjectDirectoryStore((s) => s.useFetchEnvironments)();- useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);- const linked = useProjectEnvironments(projectId);- const owned = useProjectEnvironments();- const reusable = reusableEnvironments(owned, linked, publish);-- const [source, setSource] = useState<Source>(defaultSource);- const [url, setUrl] = useState('');- const [defaultBranch, setDefaultBranch] = useState<string>();- const [existingId, setExistingId] = useState<string>();- const [adding, setAdding] = useState(false);-- const repository = parseGithubRepository(url);- const urlInvalid = Boolean(url.trim()) && !repository;- const existing = reusable.find((environment) => environment.id === existingId);- const ready = source === 'github' ? !!repository : !!existing;-- const add = async () => {- if (!ready || adding) return;- setAdding(true);- try {- let environmentId: string;- if (source === 'github') {- const environment = await attachRepository({- projectId,- repository: { defaultBranch, name: repository!.fullName, url: repository!.url },- ...(publish && { visibility: 'public' as const }),- });- environmentId = environment.id;- } else {- await attachEnvironment(projectId, existing!.id);- environmentId = existing!.id;- }- close();- onAdded?.(environmentId);- } catch (error) {- console.error('Failed to add an environment to the project', error);- toast.error(t('environment.add.failed'));- } finally {- setAdding(false);- }- };-- return (- <>- <Flexbox gap={16} padding={16}>- <Segmented- block- value={source}- options={[- { label: t('environment.add.github'), value: 'github' },- { label: t('environment.add.existing'), value: 'existing' },- ]}- onChange={(value) => setSource(value as Source)}- />- {source === 'github' ? (- <>- <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: lobeCssVar.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>- )}- </>- ) : available.error && !available.hasData ? (- <AsyncError error={available.error} onRetry={() => available.revalidate()} />- ) : !available.hasData ? (- <Text type={'secondary'}>{t('loading', { ns: 'common' })}</Text>- ) : reusable.length === 0 ? (- <Flexbox align={'center'} gap={12} paddingBlock={24}>- <Text type={'secondary'}>- {t(publish ? 'environment.add.noPublished' : 'environment.add.noExisting')}- </Text>- <Button onClick={() => setSource('github')}>{t('environment.add.github')}</Button>- </Flexbox>- ) : (- <div {...stylex.props(styles.list)} role={'listbox'}>- {reusable.map((environment) => {- const selected = environment.id === existingId;- return (- <button- aria-selected={selected}- key={environment.id}- role={'option'}- type={'button'}- {...stylex.props(styles.row, selected && styles.selected)}- onClick={() => setExistingId(environment.id)}- >- <RepositoryAvatar size={28} url={environmentRepositoryUrl(environment)} />- <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>- <Text ellipsis weight={500}>- {environment.name}- </Text>- {/* A name that already is the slug needs no second copy of it. */}- {repositorySlug(environment) !== environment.name && (- <Text ellipsis fontSize={12} type={'secondary'}>- {repositorySlug(environment) ?? t('settings.noRepository')}- </Text>- )}- </Flexbox>- {selected && (- <span {...stylex.props(styles.check)}>- <CheckIcon size={16} />- </span>- )}- </button>- );- })}- </div>- )}- </Flexbox>- <ModalFooter>- <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>- <Button disabled={!ready} loading={adding} type={'primary'} onClick={add}>- {t('environment.add.action')}- </Button>- </ModalFooter>- </>- );-};--export const openAddEnvironmentModal = (props: AddEnvironmentContentProps) =>- createModal({- content: <AddEnvironmentContent {...props} />,- footer: null,- styles: { content: { padding: 0 } },- title: translate('environment.add.title', { ns: 'project' }),- width: 560,- });diff --git a/src/features/Projects/CreateFromGithub/Content.tsx b/src/features/Projects/CreateFromGithub/Content.tsxindex de2800b2ced..a9e10594006 100644--- a/src/features/Projects/CreateFromGithub/Content.tsx+++ b/src/features/Projects/CreateFromGithub/Content.tsx@@ -1,4 +1,3 @@-import type { ScmRepositoryListItem } from '@lobechat/types';import {Button,cssVar,@@ -30,11 +29,9 @@ import {import MainAgentSection from '../MainAgentSection';import { useDefaultMainAgent } from '../useDefaultMainAgent';import { parseGithubRepository } from './githubRepository';-import RepositoryList from './RepositoryList';+import RepositoryField, { AdvancedRepositories, type PickedRepository } from './RepositoryField';interface FormState {- /** Default branch of the picked repository; unknown for a pasted URL. */- defaultBranch?: string;/** The field another project already holds, as the last create reported it. */duplicate?: 'identifier' | 'name';identifier: string;@@ -44,7 +41,6 @@ interface FormState {mainAgentMode: MainAgentMode;name: string;nameEdited: boolean;- url: string;}/**@@ -65,14 +61,16 @@ const CreateFromGithubContent = () => {mainAgentMode: DEFAULT_MAIN_AGENT_MODE,name: '',nameEdited: false,- url: '',});+ // The project's environment checks these out; the first one names the project.+ const [repositories, setRepositories] = useState<PickedRepository[]>([]);+ const [main, ...extras] = repositories;+// Taken once per open dialog: the dedicated agent's previewed character is seeded by it.const [reservedIds] = useState(reserveProjectIds);- const repository = parseGithubRepository(form.url);- const urlInvalid = Boolean(form.url.trim()) && !repository;+ const repository = main && parseGithubRepository(main.url);const defaultMainAgentId = useDefaultMainAgent();const mainAgentId = form.mainAgentId ?? defaultMainAgentId;const identifierInvalid =@@ -86,17 +84,15 @@ const CreateFromGithubContent = () => {}): null;- /** A new repository renames the project unless the person already named it. */- const applyUrl = (url: string, defaultBranch?: string) => {- const parsed = parseGithubRepository(url);- setForm((current) => {- const name = current.nameEdited ? current.name : (parsed?.name ?? '');- return { ...current, defaultBranch, duplicate: undefined, name, url };- });- };-- const selectRepository = (repo: ScmRepositoryListItem) => {- applyUrl(repo.htmlUrl, repo.defaultBranch);+ /** A new first repository renames the project unless the person already named it. */+ const changeRepositories = (next: PickedRepository[]) => {+ setRepositories(next);+ const first = next[0] && parseGithubRepository(next[0].url);+ setForm((current) => ({+ ...current,+ duplicate: undefined,+ name: current.nameEdited ? current.name : (first?.name ?? ''),+ }));};const updateName = (name: string) => {@@ -119,10 +115,16 @@ const CreateFromGithubContent = () => {mainAgentMode: form.mainAgentMode,}),repository: {- defaultBranch: form.defaultBranch,+ defaultBranch: main?.defaultBranch,name: repository.fullName,url: repository.url,},+ ...(extras.length > 0 && {+ additionalRepositories: extras.map(({ defaultBranch, url }) => ({+ url,+ ...(defaultBranch && { defaultBranch }),+ })),+ }),});if (form.mainAgentMode === 'dedicated') {// The project created an agent and maybe the Project label; show both.@@ -150,32 +152,12 @@ const CreateFromGithubContent = () => {return (<><Flexbox gap={16} padding={16}>- {/* Picking a connected repository is the primary path; the URL field is the fallback. */}- <RepositoryList- selected={repository?.fullName}+ <RepositoryField+ value={repositories}+ onChange={changeRepositories}onConnect={connectGithub}- onSelect={selectRepository}/>- <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={form.url}- onChange={(event) => applyUrl(event.target.value)}- onPressEnter={handleCreate}- />- {urlInvalid && (- <Text fontSize={12} type={'danger'}>- {t('createFromGithub.urlInvalid')}- </Text>- )}- </Flexbox>-{repository && (<Flexbox horizontal gap={12}><Flexbox flex={1} gap={6}>@@ -214,15 +196,13 @@ const CreateFromGithubContent = () => {</Flexbox></Flexbox>)}- {repository && (- <Text fontSize={12} type={identifierInvalid || form.duplicate ? 'danger' : 'secondary'}>+ {repository && (identifierInvalid || form.duplicate) && (+ <Text fontSize={12} type={'danger'}>{form.duplicate === 'name'? t('createFromGithub.duplicateName'): form.duplicate === 'identifier'? t('createFromGithub.duplicateIdentifier')- : identifierInvalid- ? t('create.identifierInvalid')- : t('createFromGithub.environmentHint')}+ : t('create.identifierInvalid')}</Text>)}{repository && (@@ -236,6 +216,12 @@ const CreateFromGithubContent = () => {onModeChange={(mainAgentMode) => setForm((current) => ({ ...current, mainAgentMode }))}/>)}+ <AdvancedRepositories+ layoutHint={t('createFromGithub.layoutHint')}+ value={repositories}+ onChange={changeRepositories}+ onConnect={connectGithub}+ /></Flexbox><ModalFooter><Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>diff --git a/src/features/Projects/CreateFromGithub/RepositoryField.tsx b/src/features/Projects/CreateFromGithub/RepositoryField.tsxnew file mode 100644index 00000000000..971bcbe43b5--- /dev/null+++ b/src/features/Projects/CreateFromGithub/RepositoryField.tsx@@ -0,0 +1,363 @@+import type { ScmRepositoryListItem } from '@lobechat/types';+import { Github } from '@lobehub/icons';+import { ActionIcon, Button, Flexbox, Icon, Input, Popover, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ArrowRightIcon, ChevronDownIcon, ChevronRightIcon, XIcon } from 'lucide-react';+import { type ClipboardEvent, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { parseGithubRepository } from './githubRepository';+import RepositoryList from './RepositoryList';+import { useScmRepositories } from './useScmRepositories';++/** A repository picked for the new project or environment. */+export interface PickedRepository {+ defaultBranch?: string;+ /** `owner/name`. */+ fullName: string;+ url: string;+}++/** One environment checks out at most this many repositories. */+export const MAX_REPOSITORIES = 10;++const styles = stylex.create({+ item: {+ alignItems: 'center',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadius,+ borderStyle: 'solid',+ borderWidth: 1,+ display: 'flex',+ gap: 8,+ paddingBlock: 6,+ paddingInlineEnd: 6,+ paddingInlineStart: 12,+ },+ popover: {+ width: 'min(400px, calc(100vw - 32px))',+ },+});++const sameRepository = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();++interface PasteRepositoryProps {+ /** Above the input; none where the surrounding section already says what it is. */+ label?: string;+ onPick: (repository: PickedRepository) => void;+ picked: PickedRepository[];+}++/**+ * A pasted repository URL. Pasting a whole URL adds it at once; a typed one is+ * added with Enter or the button, so a half-typed path is never picked.+ */+const PasteRepository = ({ label, onPick, picked }: PasteRepositoryProps) => {+ const { t } = useTranslation('project');+ const [url, setUrl] = useState('');+ const parsed = parseGithubRepository(url);+ const invalid = Boolean(url.trim()) && !parsed;+ const taken = (fullName: string) =>+ picked.some((item) => sameRepository(item.fullName, fullName));++ const add = (value = url) => {+ const repository = parseGithubRepository(value);+ if (!repository || taken(repository.fullName)) return false;+ onPick({ fullName: repository.fullName, url: repository.url });+ setUrl('');+ return true;+ };++ const handlePaste = (event: ClipboardEvent<HTMLInputElement>) => {+ if (url.trim()) return;+ if (add(event.clipboardData.getData('text').trim())) event.preventDefault();+ };++ return (+ <Flexbox gap={6}>+ {label && (+ <Text fontSize={13} weight={500}>+ {label}+ </Text>+ )}+ <Flexbox horizontal gap={8}>+ <Input+ aria-invalid={invalid}+ placeholder={t('createFromGithub.urlPlaceholder')}+ style={invalid ? { borderColor: cssVar.colorError } : undefined}+ value={url}+ onChange={(event) => setUrl(event.target.value)}+ onPaste={handlePaste}+ onPressEnter={() => add()}+ />+ <Button disabled={!parsed || taken(parsed.fullName)} onClick={() => add()}>+ {t('createFromGithub.addRepository')}+ </Button>+ </Flexbox>+ {invalid && (+ <Text fontSize={12} type={'danger'}>+ {t('createFromGithub.urlInvalid')}+ </Text>+ )}+ {parsed && taken(parsed.fullName) && (+ <Text fontSize={12} type={'secondary'}>+ {t('createFromGithub.alreadyAdded')}+ </Text>+ )}+ </Flexbox>+ );+};++const toPicked = (repo: ScmRepositoryListItem): PickedRepository => ({+ defaultBranch: repo.defaultBranch ?? undefined,+ fullName: repo.fullName,+ url: repo.htmlUrl,+});++interface RepositoryPickerProps {+ onConnect: () => void;+ onPick: (repository: PickedRepository) => void;+ picked: PickedRepository[];+}++/** The main pick: the list the connected GitHub App can read, or a pasted URL. */+const RepositoryPicker = ({ onConnect, onPick, picked }: RepositoryPickerProps) => {+ const { t } = useTranslation('project');+ return (+ <Flexbox gap={12}>+ <RepositoryList+ picked={picked.map((item) => item.fullName)}+ onConnect={onConnect}+ onSelect={(repo) => onPick(toPicked(repo))}+ />+ <PasteRepository label={t('createFromGithub.urlLabel')} picked={picked} onPick={onPick} />+ </Flexbox>+ );+};++interface GithubRepositoryButtonProps {+ onConnect: () => void;+ onOpenChange: (open: boolean) => void;+ onPick: (repository: PickedRepository) => void;+ open: boolean;+ picked: PickedRepository[];+}++/**+ * The connected list, a click away: a popover once GitHub can list+ * repositories, otherwise the step that would make it — connect, open the+ * settings, or grant access. Nothing while loading or after a failed load; the+ * paste box beside it still works.+ */+const GithubRepositoryButton = ({+ onConnect,+ onOpenChange,+ onPick,+ open,+ picked,+}: GithubRepositoryButtonProps) => {+ const { t } = useTranslation('project');+ const { state } = useScmRepositories();++ if (state === 'loading' || state === 'error') return null;++ if (state !== 'ready')+ return (+ <Button+ icon={<Icon icon={ArrowRightIcon} />}+ iconPosition={'end'}+ size={'small'}+ type={'text'}+ onClick={onConnect}+ >+ {t(+ state === 'disconnected'+ ? 'createFromGithub.connect'+ : state === 'unconfigured'+ ? 'createFromGithub.openIntegrations'+ : 'createFromGithub.manageAccess',+ )}+ </Button>+ );++ return (+ <Popover+ open={open}+ placement={'bottomLeft'}+ trigger={'click'}+ content={+ <div {...stylex.props(styles.popover)}>+ <RepositoryList+ hideGuide+ picked={picked.map((item) => item.fullName)}+ onConnect={onConnect}+ onSelect={(repo) => onPick(toPicked(repo))}+ />+ </div>+ }+ onOpenChange={onOpenChange}+ >+ <Button icon={<Github size={14} />} size={'small'}>+ {t('createFromGithub.chooseFromGithub')}+ </Button>+ </Popover>+ );+};++interface RepositoryItemProps {+ onRemove: () => void;+ repository: PickedRepository;+}++const RepositoryItem = ({ onRemove, repository }: RepositoryItemProps) => {+ const { t } = useTranslation('project');+ return (+ <div {...stylex.props(styles.item)}>+ <Github size={14} />+ <Text ellipsis style={{ flex: 1 }} weight={500}>+ {repository.fullName}+ </Text>+ <ActionIcon+ icon={XIcon}+ size={'small'}+ title={t('createFromGithub.removeRepository')}+ onClick={onRemove}+ />+ </div>+ );+};++interface RepositoryFieldProps {+ /** Under the field while nothing is picked, e.g. that a repository is optional. */+ emptyHint?: string;+ onChange: (repositories: PickedRepository[]) => void;+ /** Leave the dialog for the GitHub integration settings. */+ onConnect: () => void;+ /** Every picked repository; this field shows the first, the main one. */+ value: PickedRepository[];+}++/**+ * The main repository of a new project or environment. Before the pick the+ * picker is the dialog's main content; after it, one row. More repositories are+ * an advanced setting ({@link AdvancedRepositories}); removing the main one+ * promotes the next.+ */+const RepositoryField = ({ emptyHint, onChange, onConnect, value }: RepositoryFieldProps) => {+ const { t } = useTranslation('project');+ const [main, ...extras] = value;++ if (!main)+ return (+ <Flexbox gap={6}>+ <RepositoryPicker+ picked={value}+ onConnect={onConnect}+ onPick={(repo) => onChange([repo])}+ />+ {emptyHint && (+ <Text fontSize={12} type={'secondary'}>+ {emptyHint}+ </Text>+ )}+ </Flexbox>+ );++ return (+ <Flexbox gap={6}>+ <Text fontSize={13} weight={500}>+ {t('createFromGithub.repositoryTitle')}+ </Text>+ <RepositoryItem repository={main} onRemove={() => onChange(extras)} />+ </Flexbox>+ );+};++interface AdvancedRepositoriesProps {+ /** How several repositories are laid out, in the caller's wording. */+ layoutHint: string;+ onChange: (repositories: PickedRepository[]) => void;+ onConnect: () => void;+ /** Every picked repository, the main one first; this section edits the rest. */+ value: PickedRepository[];+}++/**+ * Advanced settings: repositories checked out beside the main one. Collapsed+ * by default — one repository is what most people need — and added from a+ * popover with the same list and paste box as the main pick.+ */+export const AdvancedRepositories = ({+ layoutHint,+ onChange,+ onConnect,+ value,+}: AdvancedRepositoriesProps) => {+ const { t } = useTranslation('project');+ const [main, ...extras] = value;+ const [open, setOpen] = useState(extras.length > 0);+ const [adding, setAdding] = useState(false);++ /** Picking a repository already there removes it; the main one stays put. */+ const toggle = (repository: PickedRepository) => {+ if (main && sameRepository(main.fullName, repository.fullName)) return;+ if (extras.some((item) => sameRepository(item.fullName, repository.fullName)))+ return onChange(value.filter((item) => !sameRepository(item.fullName, repository.fullName)));+ if (value.length >= MAX_REPOSITORIES) return;+ onChange([...value, repository]);+ setAdding(false);+ };++ if (!main) return null;++ return (+ <Flexbox gap={8}>+ <Flexbox horizontal>+ <Button+ icon={<Icon icon={open ? ChevronDownIcon : ChevronRightIcon} />}+ size={'small'}+ type={'text'}+ onClick={() => setOpen((current) => !current)}+ >+ {extras.length > 0+ ? t('createFromGithub.advancedWithCount', { count: extras.length })+ : t('createFromGithub.advanced')}+ </Button>+ </Flexbox>+ {open && (+ <Flexbox gap={6}>+ <Text fontSize={13} weight={500}>+ {t('createFromGithub.extraRepositoriesLabel')}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {layoutHint}+ </Text>+ {extras.map((repository) => (+ <RepositoryItem+ key={repository.fullName}+ repository={repository}+ onRemove={() => toggle(repository)}+ />+ ))}+ {value.length < MAX_REPOSITORIES && (+ <>+ <PasteRepository picked={value} onPick={toggle} />+ <Flexbox horizontal>+ <GithubRepositoryButton+ open={adding}+ picked={value}+ onConnect={onConnect}+ onOpenChange={setAdding}+ onPick={toggle}+ />+ </Flexbox>+ </>+ )}+ </Flexbox>+ )}+ </Flexbox>+ );+};++export default RepositoryField;diff --git a/src/features/Projects/CreateFromGithub/RepositoryList.tsx b/src/features/Projects/CreateFromGithub/RepositoryList.tsxindex 0b9d13f0297..baf166582a3 100644--- a/src/features/Projects/CreateFromGithub/RepositoryList.tsx+++ b/src/features/Projects/CreateFromGithub/RepositoryList.tsx@@ -71,9 +71,18 @@ const styles = stylex.create({});interface RepositoryListProps {+ /**+ * Renders nothing unless there is a list to pick from — for a second list in+ * the same dialog, whose guidance the first one already gives.+ */+ hideGuide?: boolean;+ /** Overrides the list's own label, for a second list in the same dialog. */+ label?: string;/** Leave the dialog for the GitHub integration settings. */onConnect: () => void;onSelect: (repository: ScmRepositoryListItem) => void;+ /** More `owner/name`s shown as picked, beside `selected`. */+ picked?: string[];/** `owner/name` of the repository the URL field currently names. */selected?: string;}@@ -83,7 +92,14 @@ interface RepositoryListProps {* first and searchable. Not being connected is one click from being solved,* so that state offers the click instead of only reporting it.*/-const RepositoryList = ({ onConnect, onSelect, selected }: RepositoryListProps) => {+const RepositoryList = ({+ hideGuide,+ label: labelText,+ onConnect,+ onSelect,+ picked,+ selected,+}: RepositoryListProps) => {const { t } = useTranslation(['project', 'common']);const { isValidating, repositories, retry, state, truncated } = useScmRepositories();const [keyword, setKeyword] = useState('');@@ -99,13 +115,16 @@ const RepositoryList = ({ onConnect, onSelect, selected }: RepositoryListProps)}, [keyword, repositories]);const selectedKey = selected?.toLowerCase();+ const pickedKeys = new Set((picked ?? []).map((item) => item.toLowerCase()));const label = (<Text fontSize={13} weight={500}>- {t('createFromGithub.repositoriesLabel')}+ {labelText ?? t('createFromGithub.repositoriesLabel')}</Text>);+ if (hideGuide && state !== 'ready') return null;+if (state === 'loading')return (<Flexbox gap={6}>@@ -121,7 +140,9 @@ const RepositoryList = ({ onConnect, onSelect, selected }: RepositoryListProps)disconnected: { action: 'connect', text: t('createFromGithub.disconnected') },empty: { action: 'manage', text: t('createFromGithub.empty') },error: { action: 'retry', text: t('createFromGithub.loadFailed') },- unconfigured: { action: undefined, text: t('createFromGithub.unconfigured') },+ // Connecting is impossible until the deployment has a GitHub App, but+ // the settings page says what is missing — a lead, not a dead end.+ unconfigured: { action: 'settings', text: t('createFromGithub.unconfigured') },}[state];return (@@ -140,7 +161,9 @@ const RepositoryList = ({ onConnect, onSelect, selected }: RepositoryListProps): t(guide.action === 'connect'? 'createFromGithub.connect'- : 'createFromGithub.manageAccess',+ : guide.action === 'settings'+ ? 'createFromGithub.openIntegrations'+ : 'createFromGithub.manageAccess',)}{guide.action !== 'retry' && <Icon icon={ArrowRightIcon} size={12} />}</Button>@@ -166,7 +189,9 @@ const RepositoryList = ({ onConnect, onSelect, selected }: RepositoryListProps)) : (<div {...stylex.props(styles.list)} role={'listbox'}>{filtered.map((repo) => {- const isSelected = repo.fullName.toLowerCase() === selectedKey;+ const isSelected =+ repo.fullName.toLowerCase() === selectedKey ||+ pickedKeys.has(repo.fullName.toLowerCase());return (<buttonaria-selected={isSelected}diff --git a/src/features/Projects/WorkingDirectories/Page.tsx b/src/features/Projects/WorkingDirectories/Page.tsxindex 20cf30392dd..151e2a8cd41 100644--- a/src/features/Projects/WorkingDirectories/Page.tsx+++ b/src/features/Projects/WorkingDirectories/Page.tsx@@ -63,11 +63,7 @@ export function ProjectDirectoriesPage() {key: 'environments',label: t('settings.environments'),render: () => (- <ProjectWorkingDirectories- canManage={canManage}- projectId={detail.project.id}- shared={Boolean(detail.project.workspaceId) && detail.project.visibility === 'public'}- />+ <ProjectWorkingDirectories canManage={canManage} projectId={detail.project.id} />),},{diff --git a/src/features/Projects/WorkingDirectories/index.tsx b/src/features/Projects/WorkingDirectories/index.tsxindex 3b03b9fdd28..6b8b8856781 100644--- a/src/features/Projects/WorkingDirectories/index.tsx+++ b/src/features/Projects/WorkingDirectories/index.tsx@@ -1,334 +1,76 @@-import {- Button,- Center,- confirmModal,- DropdownMenu,- Empty,- Flexbox,- Icon,- Tag,- Text,- toast,- Tooltip,-} from '@lobehub/ui';-import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';-import * as stylex from '@stylexjs/stylex';-import {- ContainerIcon,- FolderIcon,- LinkIcon,- MoreHorizontalIcon,- PlusIcon,- UnlinkIcon,-} from 'lucide-react';-import { type ReactNode, useEffect, useRef, useState } from 'react';+import { Button, Flexbox, Icon, Text } from '@lobehub/ui';+import { FolderIcon } from 'lucide-react';+import { type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';-import { openCreateEnvironmentModal } from '@/features/EnvironmentManager/CreateEnvironmentModal';-import EnvironmentDetailPanel from '@/features/EnvironmentManager/EnvironmentDetailPanel';-import EnvironmentItem from '@/features/EnvironmentManager/EnvironmentItem';+import EnvironmentForm, {+ type EnvironmentFormValue,+} from '@/features/EnvironmentManager/EnvironmentForm';+import EnvironmentSummary from '@/features/EnvironmentManager/EnvironmentSummary';import { EnvironmentListSkeleton } from '@/features/EnvironmentManager/Skeleton';-import { useEnvironments } from '@/features/EnvironmentManager/useEnvironmentData';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import type { SandboxEnvironmentSpecification } from '@/services/environment';import {useProjectDirectories,useProjectDirectoryStore,useProjectEnvironments,} from '@/store/projectWorkingDirectory';-import type { SandboxEnvironment } from '@/store/sandbox';import { useDensityTokens } from '@/styles/density';-import { openAddEnvironmentModal } from '../AddEnvironmentModal';-import { environmentRepositoryUrl } from '../environmentSource';-import { hasEditedEnvironment, projectEnvironmentRows } from './projectEnvironmentRows';--/** The frames the environment settings use, so both lists read as one. */-const styles = stylex.create({- detailCol: {- alignSelf: 'stretch',- minWidth: 0,- borderWidth: '1px',- borderStyle: 'solid',- borderColor: cssVar.colorBorderSecondary,- borderRadius: cssVar.borderRadiusLG,- backgroundColor: cssVar.colorBgContainer,- },- listCol: {- overflow: 'hidden',- minWidth: 0,- borderWidth: '1px',- borderStyle: 'solid',- borderColor: cssVar.colorBorderSecondary,- borderRadius: cssVar.borderRadiusLG,- backgroundColor: cssVar.colorBgContainer,- },- unlistedRow: {- paddingBlock: '12px',- paddingInline: '12px',- },- unlistedTile: {- display: 'flex',- flexShrink: 0,- alignItems: 'center',- justifyContent: 'center',- width: '48px',- height: '48px',- borderRadius: '12px',- color: cssVar.colorTextSecondary,- backgroundColor: cssVar.colorFillTertiary,- },-});-interface ProjectWorkingDirectoriesProps {- /** Whether the caller may change which environments the project links. */+ /** Whether the caller may change the project, and so its environment. */canManage?: boolean;projectId: string;- /**- * A workspace-public project: its conversations run a public agent, which- * applies published environments only.- */- shared?: boolean;}/**- * The environments a project works with. They are the environments configured- * in settings — the same rows, the same detail panel — linked to the project:- * linking one, making a new one here or unlinking one never makes a second copy- * of a specification, so an edit made on either page is the edit.+ * The project's environment, laid out in full and flat — the same form an+ * environment's own page shows: the repositories it checks out (any number, or+ * none, each with its own setup), the setup that runs after, and the variables+ * every command sees. Every project has exactly one, made with it — there is nothing+ * to link, pick or create here, only the environment itself to fill in.*/export function ProjectWorkingDirectories({canManage,projectId,- shared,}: ProjectWorkingDirectoriesProps) {- const { t } = useTranslation(['project', 'common']);+ const { t } = useTranslation(['project', 'setting']);const { pageTitleFontSize } = useDensityTokens();const navigate = useWorkspaceAwareNavigate();- const linkedRequest = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);+ const request = useProjectDirectoryStore((s) => s.useFetchEnvironments)(projectId);const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectId);- const attachEnvironment = useProjectDirectoryStore((s) => s.attachEnvironment);- const detachEnvironment = useProjectDirectoryStore((s) => s.detachEnvironment);- const linked = useProjectEnvironments(projectId);+ const updateEnvironment = useProjectDirectoryStore((s) => s.updateProjectEnvironment);+ const [environment] = useProjectEnvironments(projectId);const directories = useProjectDirectories(projectId);- const configured = useEnvironments();- const [selectedId, setSelectedId] = useState<string>();-- const requestError = linkedRequest.error || directoriesRequest.error;- const loading =- !linkedRequest.hasData ||- !directoriesRequest.hasData ||- (!configured.settled && !configured.error);-- const { configured: rows, unlisted: unlistedRows } = projectEnvironmentRows(- linked,- configured.environments ?? [],- );- // Until the configured list has answered, "not in it" is not an answer yet.- const unlisted = configured.settled ? unlistedRows : [];- const selected = rows.find((environment) => environment.id === selectedId);- // The detail panel saves through the settings store; the project's own- // projections (directory rows carry the environment's name) follow when a- // linked environment's name or visibility changes there.- const refreshEnvironments = useProjectDirectoryStore((s) => s.refreshEnvironments);- const lastRows = useRef<SandboxEnvironment[]>(undefined);- useEffect(() => {- const previous = lastRows.current;- lastRows.current = rows;- if (previous && hasEditedEnvironment(previous, rows)) void refreshEnvironments();- }, [rows, refreshEnvironments]);-- const link = () =>- openAddEnvironmentModal({- defaultSource: 'existing',- onAdded: (environmentId) => {- setSelectedId(environmentId);- // A repository added from GitHub may have made a new environment.- void configured.revalidate();- },+ const save = async (changes: {+ configuration?: SandboxEnvironmentSpecification;+ description?: string;+ }) => {+ await updateEnvironment({projectId,- publish: shared,+ ...(changes.configuration && { configuration: changes.configuration }),+ ...(changes.description !== undefined && { description: changes.description }),});-- const create = () =>- openCreateEnvironmentModal(- shared ? 'public' : undefined,- async (created) => {- try {- await attachEnvironment(projectId, created.id);- setSelectedId(created.id);- } catch (error) {- console.error('Failed to link the new environment to the project', error);- toast.error(t('environment.add.failed'));- }- },- t('environment.create'),- );-- const unlink = (environment: { id: string; name: string }) =>- confirmModal({- cancelText: t('cancel', { ns: 'common' }),- content: t('environment.unlinkConfirm.desc'),- okText: t('environment.unlink'),- onOk: async () => {- try {- await detachEnvironment(projectId, environment.id);- setSelectedId((current) => (current === environment.id ? undefined : current));- } catch (error) {- console.error('Failed to unlink the environment from the project', error);- toast.error(t('environment.unlinkFailed'));- }- },- title: t('environment.unlinkConfirm.title', { name: environment.name }),- });-- const projectMenu = (environment: { id: string; name: string }) =>- canManage- ? [- {- icon: <Icon icon={UnlinkIcon} />,- key: 'unlink',- label: t('environment.unlink'),- onClick: () => unlink(environment),- },- ]- : [];-- /** What the project adds to a row: its folders, and whether it can be used. */- const projectFacts = (environment: { id: string; visibility?: string | null }): ReactNode => {- const count = directories.filter((d) => d.environmentId === environment.id).length;- // The project's conversations never check a private one out.- const unusable = shared && environment.visibility !== 'public';- return (- <Flexbox horizontal align="center" gap={8}>- {unusable && (- <Tooltip title={t('environment.privateInSharedTooltip')}>- <Tag color="warning" size="small">- {t('environment.privateInShared')}- </Tag>- </Tooltip>- )}- <Button- size="small"- onClick={() =>- navigate(`/project/${projectId}/settings/directories?environment=${environment.id}`)- }- >- {t(count ? 'settings.viewDirectories' : 'settings.configureDirectory', { count })}- </Button>- </Flexbox>- );};- const actions = canManage && (- <Flexbox horizontal align="center" gap={8} style={{ flex: 'none' }}>- <Button icon={<Icon icon={LinkIcon} />} onClick={link}>- {t('environment.link')}- </Button>- <Button icon={<Icon icon={PlusIcon} />} type="primary" onClick={create}>- {t('environment.create')}- </Button>- </Flexbox>- );-let content: ReactNode;- if (requestError) {- content = (- <AsyncError- error={requestError}- onRetry={() => Promise.all([linkedRequest.revalidate(), directoriesRequest.revalidate()])}- />- );- } else if (loading) {+ if (request.error && !environment) {+ content = <AsyncError error={request.error} onRetry={() => request.revalidate()} />;+ } else if (!request.hasData || !environment) {content = <EnvironmentListSkeleton />;- } else if (!linked.length) {- content = (- <Flexbox {...stylex.props(styles.listCol)}>- <Center paddingBlock={48} width="100%">- <Empty- action={canManage && <Button onClick={link}>{t('environment.link')}</Button>}- description={t('settings.environmentDescription')}- descriptionProps={{ fontSize: 13 }}- icon={ContainerIcon}- style={{ maxWidth: 360 }}- title={t('settings.noEnvironments')}- />- </Center>- </Flexbox>- );} else {- content = (- <Flexbox horizontal align="flex-start" gap={16} wrap="wrap">- <Flexbox {...stylex.props(styles.listCol)} flex="1 1 320px">- {!!configured.error && !configured.settled && (- <AsyncError error={configured.error} onRetry={() => configured.revalidate()} />- )}- <Flexbox gap={2} padding={4}>- {rows.map((environment) => (- <EnvironmentItem- environment={environment}- extra={projectFacts(environment)}- key={environment.id}- menuItems={projectMenu(environment)}- selected={environment.id === selectedId}- onSelect={() =>- setSelectedId((current) =>- current === environment.id ? undefined : environment.id,- )- }- />- ))}- {unlisted.map((environment) => {- const repository = environmentRepositoryUrl(environment);- return (- <Flexbox- horizontal- align="center"- {...stylex.props(styles.unlistedRow)}- gap={16}- key={environment.id}- >- <div {...stylex.props(styles.unlistedTile)}>- <FolderIcon size={20} />- </div>- <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>- <Text ellipsis fontSize={15} weight={500}>- {environment.name}- </Text>- <Text ellipsis fontSize={12} type="secondary">- {repository?.replace('https://github.com/', '') ?? t('settings.noRepository')}- </Text>- </Flexbox>- <Flexbox horizontal align="center" gap={8} style={{ flex: 'none' }}>- {projectFacts(environment)}- {canManage && (- <DropdownMenu items={projectMenu(environment)} placement="bottomRight">- <Button- aria-label={t('more', { ns: 'common' })}- icon={MoreHorizontalIcon}- />- </DropdownMenu>- )}- </Flexbox>- </Flexbox>- );- })}- </Flexbox>- </Flexbox>- {selected && (- <Flexbox {...stylex.props(styles.detailCol)} flex="2 1 480px">- <EnvironmentDetailPanel- environment={selected}- key={selected.id}- onClose={() => setSelectedId(undefined)}- />- </Flexbox>- )}- </Flexbox>+ const value: EnvironmentFormValue = environment;+ content = canManage ? (+ <EnvironmentForm hideBasics environment={value} onSave={save} />+ ) : (+ <EnvironmentSummary environment={value} />);}+ const folderCount = directoriesRequest.hasData ? directories.length : undefined;+return (<Flexbox gap={16}><Flexbox gap={8}>@@ -336,9 +78,18 @@ export function ProjectWorkingDirectories({<Text fontSize={pageTitleFontSize} weight={600}>{t('settings.environments')}</Text>- {actions}+ {folderCount !== undefined && (+ <Button+ icon={<Icon icon={FolderIcon} />}+ onClick={() => navigate(`/project/${projectId}/settings/directories`)}+ >+ {t(folderCount ? 'settings.viewDirectories' : 'settings.configureDirectory', {+ count: folderCount,+ })}+ </Button>+ )}</Flexbox>- <Text type="secondary">{t('settings.environmentDescription')}</Text>+ <Text type="secondary">{t('settings.environmentIntro')}</Text></Flexbox>{content}</Flexbox>diff --git a/src/features/Projects/WorkingDirectories/projectEnvironmentRows.test.ts b/src/features/Projects/WorkingDirectories/projectEnvironmentRows.test.tsdeleted file mode 100644index 2f23d17fa4b..00000000000--- a/src/features/Projects/WorkingDirectories/projectEnvironmentRows.test.ts+++ /dev/null@@ -1,58 +0,0 @@-import { describe, expect, it } from 'vitest';--import type { SandboxEnvironment } from '@/store/sandbox';--import { hasEditedEnvironment, projectEnvironmentRows } from './projectEnvironmentRows';--const configured = (id: string, name = id): SandboxEnvironment => ({- createdAt: '2026-10-01T00:00:00.000Z',- creator: null,- description: null,- id,- kind: 'code',- name,- userId: 'user-1',- visibility: 'private',- workspaceId: null,-});--describe('projectEnvironmentRows', () => {- it("shows a linked environment as the configured row, in the project's order", () => {- const result = projectEnvironmentRows(- [{ id: 'b' }, { id: 'a' }],- [configured('a', 'Renamed in settings'), configured('b'), configured('c')],- );-- expect(result.configured.map((row) => row.id)).toEqual(['b', 'a']);- // The configured row wins, so an edit made in settings shows here too.- expect(result.configured[1].name).toBe('Renamed in settings');- expect(result.unlisted).toEqual([]);- });-- it('keeps a linked environment the configured list does not hold apart', () => {- const result = projectEnvironmentRows(- [{ id: 'a' }, { id: 'gone', name: 'Theirs' }],- [configured('a')],- );-- expect(result.configured.map((row) => row.id)).toEqual(['a']);- expect(result.unlisted).toEqual([{ id: 'gone', name: 'Theirs' }]);- });-});--describe('hasEditedEnvironment', () => {- it('reports a rename or a visibility change of a row listed both times', () => {- expect(- hasEditedEnvironment([configured('a', 'Old: name')], [configured('a', 'New: name')]),- ).toBe(true);- expect(- hasEditedEnvironment([configured('a')], [{ ...configured('a'), visibility: 'public' }]),- ).toBe(true);- });-- it('ignores linking, unlinking and unchanged rows', () => {- expect(hasEditedEnvironment([configured('a')], [configured('a'), configured('b')])).toBe(false);- expect(hasEditedEnvironment([configured('a'), configured('b')], [configured('a')])).toBe(false);- expect(hasEditedEnvironment([configured('a')], [configured('a')])).toBe(false);- });-});diff --git a/src/features/Projects/WorkingDirectories/projectEnvironmentRows.ts b/src/features/Projects/WorkingDirectories/projectEnvironmentRows.tsdeleted file mode 100644index 22a14e59a15..00000000000--- a/src/features/Projects/WorkingDirectories/projectEnvironmentRows.ts+++ /dev/null@@ -1,42 +0,0 @@-import type { SandboxEnvironment } from '@/store/sandbox';--/**- * A project's environments, as the rows the environment settings list them- * with. The project holds only the link; the row — repository, creator, when it- * was made — is the configured environment itself, so both pages show the same- * thing and an edit made on either shows up on both.- *- * A linked environment the caller's configured list does not hold (a- * colleague's private one linked to a shared project) is returned separately,- * since there is no row to show for it beyond the link.- */-export const projectEnvironmentRows = <TLinked extends { id: string }>(- linked: TLinked[],- configured: SandboxEnvironment[],-): { configured: SandboxEnvironment[]; unlisted: TLinked[] } => {- const byId = new Map(configured.map((environment) => [environment.id, environment]));- const rows: SandboxEnvironment[] = [];- const unlisted: TLinked[] = [];- for (const environment of linked) {- const row = byId.get(environment.id);- if (row) rows.push(row);- else unlisted.push(environment);- }- return { configured: rows, unlisted };-};--/**- * Whether an environment listed both times changed in a way the project's own- * projections denormalize (its name) or depend on (its visibility). Linking or- * unlinking is not an edit: those refresh the project on their own.- */-export const hasEditedEnvironment = (- previous: Pick<SandboxEnvironment, 'id' | 'name' | 'visibility'>[],- next: Pick<SandboxEnvironment, 'id' | 'name' | 'visibility'>[],-): boolean => {- const before = new Map(previous.map((environment) => [environment.id, environment]));- return next.some((environment) => {- const old = before.get(environment.id);- return !!old && (old.name !== environment.name || old.visibility !== environment.visibility);- });-};diff --git a/src/features/Projects/Workspace/ProjectComposer.tsx b/src/features/Projects/Workspace/ProjectComposer.tsxindex 3ed075fbe2f..c9bc519ae83 100644--- a/src/features/Projects/Workspace/ProjectComposer.tsx+++ b/src/features/Projects/Workspace/ProjectComposer.tsx@@ -164,7 +164,10 @@ const ProjectComposer = memo<ProjectComposerProps>(({ detail, request }) => {mode !== 'chat'? {}: location.target === 'sandbox'- ? { environmentId: repositoryState.repository?.id }+ ? {+ environmentId: repositoryState.repository?.id,+ withoutEnvironment: repositoryState.withoutEnvironment,+ }: { directoryId: directoryState.directory?.id };const { send, sending } = useProjectComposer(project, mode, agentId, place);@@ -246,7 +249,6 @@ const ProjectComposer = memo<ProjectComposerProps>(({ detail, request }) => {disabled={sending}location={location}projectId={project.id}- publish={sharedAgent}showRepositories={mode === 'chat'}state={repositoryState}/>diff --git a/src/features/Projects/Workspace/ProjectWorkLocationPicker.tsx b/src/features/Projects/Workspace/ProjectWorkLocationPicker.tsxindex 7ded99abfc6..7211ff5e9bc 100644--- a/src/features/Projects/Workspace/ProjectWorkLocationPicker.tsx+++ b/src/features/Projects/Workspace/ProjectWorkLocationPicker.tsx@@ -4,21 +4,24 @@ import type { DeviceExecutionTarget } from '@lobechat/types';import { Flexbox, Icon, Popover, Text, toast, Tooltip } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { ChevronDownIcon, FolderIcon, PlusIcon } from 'lucide-react';+import { ChevronDownIcon, CircleOffIcon, FolderIcon, PlusIcon, SettingsIcon } from 'lucide-react';import { type ReactNode, useState } from 'react';import { useTranslation } from 'react-i18next';import RepositoryAvatar from '@/components/RepositoryAvatar';import OptionRow from '@/features/ChatInput/ControlBar/OptionRow';-import { repositorySlug } from '@/features/ChatInput/ControlBar/sandboxEnvironmentOptions';+import {+ repositoriesLabel,+ repositorySlug,+} from '@/features/ChatInput/ControlBar/sandboxEnvironmentOptions';import { workingDirectoryChipStyles } from '@/features/ChatInput/ControlBar/workingDirectoryChipStyles';import { ExecutionTargetDeviceStatus, ExecutionTargetIcon } from '@/features/ExecutionTargetPicker';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { openAddEnvironmentModal } from '../AddEnvironmentModal';import { environmentRepositoryUrl } from '../environmentSource';import { openAddDirectoryModal } from '../WorkingDirectories/AddDirectoryModal';import { addedFolderTarget, type useProjectDirectory } from './useProjectDirectory';-import type { useProjectRepository } from './useProjectRepository';+import { NO_ENVIRONMENT, type useProjectRepository } from './useProjectRepository';import type { useProjectWorkLocation } from './useProjectWorkLocation';/**@@ -76,8 +79,6 @@ interface ProjectWorkLocationPickerProps {/** Where the agent runs and where it can be moved to. */location: ReturnType<typeof useProjectWorkLocation>;projectId: string;- /** Environments added here are published: the agent is workspace-public and applies nothing else. */- publish?: boolean;/** A task starts no conversation, so it has no code environment or folder to pick. */showRepositories?: boolean;state: ReturnType<typeof useProjectRepository>;@@ -96,12 +97,12 @@ const ProjectWorkLocationPicker = ({disabled,location,projectId,- publish,showRepositories = true,state,}: ProjectWorkLocationPickerProps) => {const { t } = useTranslation('project');const { t: tChat } = useTranslation('chat');+ const navigate = useWorkspaceAwareNavigate();const [open, setOpen] = useState(false);const {boundDevice,@@ -116,7 +117,7 @@ const ProjectWorkLocationPicker = ({} = location;const onSandbox = target === 'sandbox';- const { repositories, repository, setPickedId } = state;+ const { repositories, repository, setPickedId, withoutEnvironment } = state;const repositoryShown = showRepositories && onSandbox && !!repository;const select = async (next: DeviceExecutionTarget, deviceId?: string) => {@@ -152,9 +153,11 @@ const ProjectWorkLocationPicker = ({});};- const addEnvironment = () => {+ // A project has one environment; its repositories are edited on the+ // project's settings, not picked or added here.+ const configureEnvironment = () => {setOpen(false);- openAddEnvironmentModal({ onAdded: pickRepository, projectId, publish });+ navigate(`/project/${projectId}/settings/environments`);};// What the chip says: the code environment when the run checks one out,@@ -177,7 +180,7 @@ const ProjectWorkLocationPicker = ({const hint = onSandbox? repositoryShown- ? `${repositorySlug(repository) ?? repository.name} · ${tChat('heteroAgent.executionTarget.sandbox')}`+ ? `${repositoriesLabel(repository) ?? repository.name} · ${tChat('heteroAgent.executionTarget.sandbox')}`: t('overview.context.target.sandboxTooltip'): target === 'none'? t('overview.context.target.noneTooltip')@@ -204,6 +207,17 @@ const ProjectWorkLocationPicker = ({<Flexbox gap={2} style={{ maxWidth: 360, minWidth: 260 }}><div {...stylex.props(styles.header)}>{t('overview.context.location.environments')}</div><div {...stylex.props(styles.list)}>+ {/* Not every conversation needs the checkout: this one starts in an+ empty working directory. */}+ {repositories.length > 0 && (+ <OptionRow+ compact+ active={onSandbox && withoutEnvironment}+ icon={<Icon icon={CircleOffIcon} size={16} />}+ label={t('environment.none')}+ onClick={() => pickRepository(NO_ENVIRONMENT)}+ />+ )}{repositories.map((environment) => (<OptionRowcompact@@ -214,9 +228,9 @@ const ProjectWorkLocationPicker = ({active={onSandbox && environment.id === repository?.id}// A name that already is the slug needs no second copy of it.hint={- repositorySlug(environment) === environment.name+ repositoriesLabel(environment) === environment.name? undefined- : repositorySlug(environment)+ : repositoriesLabel(environment)}/>))}@@ -229,9 +243,9 @@ const ProjectWorkLocationPicker = ({{canManage && (<OptionRowcompact- icon={<Icon icon={PlusIcon} size={16} />}- label={t('environment.add.title')}- onClick={addEnvironment}+ icon={<Icon icon={SettingsIcon} size={16} />}+ label={t('environment.configure')}+ onClick={configureEnvironment}/>)}</Flexbox>diff --git a/src/features/Projects/Workspace/useProjectComposer.ts b/src/features/Projects/Workspace/useProjectComposer.tsindex 7908bb98399..3ab80a3334b 100644--- a/src/features/Projects/Workspace/useProjectComposer.ts+++ b/src/features/Projects/Workspace/useProjectComposer.ts@@ -121,9 +121,9 @@ export const useProjectComposer = (* Where the conversation works: a project repository in the cloud sandbox* (the server picks the first when unset), or a project folder on a device.*/- place: { directoryId?: string; environmentId?: string } = {},+ place: { directoryId?: string; environmentId?: string; withoutEnvironment?: boolean } = {},) => {- const { directoryId, environmentId } = place;+ const { directoryId, environmentId, withoutEnvironment } = place;const { t } = useTranslation('project');const navigate = useWorkspaceAwareNavigate();const workspaceSlug = useActiveWorkspaceSlug();@@ -178,7 +178,13 @@ export const useProjectComposer = (? startDirectoryTopic(directoryId, agentId, title).catch((error: unknown) => {throw new DirectoryUnavailableError(error);})- : createProjectTopic({ agentId, environmentId, projectId: project.id, title }),+ : createProjectTopic({+ agentId,+ environmentId,+ projectId: project.id,+ title,+ ...(withoutEnvironment && { withoutEnvironment: true }),+ }),ensureAgentConfigLoaded(agentId),]);// Open the conversation right away: the send shows its message therediff --git a/src/features/Projects/Workspace/useProjectRepository.ts b/src/features/Projects/Workspace/useProjectRepository.tsindex e926dd0c795..3f53c334083 100644--- a/src/features/Projects/Workspace/useProjectRepository.ts+++ b/src/features/Projects/Workspace/useProjectRepository.ts@@ -4,6 +4,9 @@ import { useProjectDirectoryStore, useProjectEnvironments } from '@/store/projectype ProjectEnvironment = ReturnType<typeof useProjectEnvironments>[number];+/** The pick that starts a conversation without the project's environment. */+export const NO_ENVIRONMENT = 'none';+/** 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');@@ -25,8 +28,11 @@ export const useProjectRepository = (isRepositoryEnvironment(environment) && (!sharedAgent || environment.visibility === 'public'),);const [pickedId, setPickedId] = useState<string>();- const repository =- repositories.find((environment) => environment.id === pickedId) ?? repositories[0];+ // "No environment": the conversation starts in an empty working directory.+ const withoutEnvironment = pickedId === NO_ENVIRONMENT;+ const repository = withoutEnvironment+ ? undefined+ : (repositories.find((environment) => environment.id === pickedId) ?? repositories[0]);- return { loaded: hasData, repositories, repository, setPickedId };+ return { loaded: hasData, repositories, repository, setPickedId, withoutEnvironment };};diff --git a/src/features/Settings/environments/index.tsx b/src/features/Settings/environments/index.tsxindex e47ae8d41e2..a5434c0e5e8 100644--- a/src/features/Settings/environments/index.tsx+++ b/src/features/Settings/environments/index.tsx@@ -2,24 +2,41 @@import { Flexbox } from '@lobehub/ui';import { memo } from 'react';+import { useNavigate, useParams } from 'react-router';import { MAX_WIDTH } from '@/const/layoutTokens';import EnvironmentManager from '@/features/EnvironmentManager';+import EnvironmentDetailPage from '@/features/EnvironmentManager/EnvironmentDetailPage';/**- * Thin: the titled group, the list and the detail panel all live in the manager.- * The group heading carries the list's Refresh and New actions, so it stays even- * though the shared settings header already names the page.+ * `/settings/environments` lists them; `/settings/environments/:sub` is one+ * environment's page. The list's Refresh and New actions live in the manager.** No gate: an environment is a definition, and writing one down needs no* drive. Only initializing a folder from it does, and that is asked where it* happens.*/-const Page = memo(() => (- <Flexbox style={{ maxWidth: MAX_WIDTH, width: '100%' }}>- <EnvironmentManager />- </Flexbox>-));+const Page = memo(() => {+ const { sub: environmentId } = useParams<{ sub?: string }>();+ // Personal-only route: plain `navigate` keeps it out of any active workspace.+ const navigate = useNavigate();++ return (+ <Flexbox style={{ maxWidth: MAX_WIDTH, width: '100%' }}>+ {environmentId ? (+ <EnvironmentDetailPage+ environmentId={environmentId}+ key={environmentId}+ onBack={() => navigate('/settings/environments')}+ />+ ) : (+ <EnvironmentManager+ onOpenEnvironment={(id) => navigate(`/settings/environments/${encodeURIComponent(id)}`)}+ />+ )}+ </Flexbox>+ );+});Page.displayName = 'EnvironmentsSetting';diff --git a/src/routes/(main)/[workspaceSlug]/settings/environments/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/environments/index.tsxindex 75d2c76a632..776c5b64ffe 100644--- a/src/routes/(main)/[workspaceSlug]/settings/environments/index.tsx+++ b/src/routes/(main)/[workspaceSlug]/settings/environments/index.tsx@@ -3,11 +3,14 @@import type { EnvironmentVisibility } from '@lobechat/types';import { Flexbox, Icon, Tabs } from '@lobehub/ui';import { LockIcon, UsersIcon } from 'lucide-react';-import { memo, useState } from 'react';+import { memo } from 'react';import { useTranslation } from 'react-i18next';+import { useParams, useSearchParams } from 'react-router';import { MAX_WIDTH } from '@/const/layoutTokens';import EnvironmentManager from '@/features/EnvironmentManager';+import EnvironmentDetailPage from '@/features/EnvironmentManager/EnvironmentDetailPage';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';/*** The workspace's environments, in two pools behind tabs — the same split the@@ -22,16 +25,37 @@ import EnvironmentManager from '@/features/EnvironmentManager';** The tabs are handed to the manager rather than rendered above it: they belong* on the same row as the actions, and the manager owns that row.+ *+ * The pool lives in `?visibility=` and one environment's page is+ * `environments/:sub`, so going back from it lands on the tab it is in.*/const WorkspaceEnvironmentsSetting = memo(() => {const { t } = useTranslation('setting');- const [visibility, setVisibility] = useState<EnvironmentVisibility>('public');+ const { sub: environmentId } = useParams<{ sub?: string }>();+ const [searchParams, setSearchParams] = useSearchParams();+ const visibility: EnvironmentVisibility =+ searchParams.get('visibility') === 'private' ? 'private' : 'public';+ const navigate = useWorkspaceAwareNavigate();+ const query = visibility === 'private' ? '?visibility=private' : '';++ const setVisibility = (next: EnvironmentVisibility) =>+ setSearchParams(next === 'private' ? { visibility: next } : {}, { replace: true });++ if (environmentId)+ return (+ <Flexbox style={{ maxWidth: MAX_WIDTH, width: '100%' }}>+ <EnvironmentDetailPage+ environmentId={environmentId}+ key={environmentId}+ visibility={visibility}+ onBack={() => navigate(`/settings/environments${query}`)}+ />+ </Flexbox>+ );return (<Flexbox style={{ maxWidth: MAX_WIDTH, width: '100%' }}>- {/* Keyed on the pool so the selected row and its open panel do not- survive a tab switch — the environment they pointed at is not in- the list any more. */}+ {/* Keyed on the pool so a refresh in flight does not survive a tab switch. */}<EnvironmentManagerkey={visibility}visibility={visibility}@@ -56,6 +80,9 @@ const WorkspaceEnvironmentsSetting = memo(() => {onChange={(key) => setVisibility(key as EnvironmentVisibility)}/>}+ onOpenEnvironment={(id) =>+ navigate(`/settings/environments/${encodeURIComponent(id)}${query}`)+ }/></Flexbox>);diff --git a/src/services/project.ts b/src/services/project.tsindex 47ab83c4497..9aa6fc78b3f 100644--- a/src/services/project.ts+++ b/src/services/project.ts@@ -65,6 +65,7 @@ class ProjectService {description?: string;id?: string;identifier?: string;+ additionalRepositories?: { defaultBranch?: string; url: string }[];name: string;repository?: { defaultBranch?: string; name: string; url: string };slug?: string;diff --git a/src/services/projectWorkingDirectory.ts b/src/services/projectWorkingDirectory.tsindex 5c551fdf3f8..35b8260ea24 100644--- a/src/services/projectWorkingDirectory.ts+++ b/src/services/projectWorkingDirectory.ts@@ -14,12 +14,10 @@ class ProjectWorkingDirectoryService {lambdaClient.projectWorkingDirectory.listEnvironments.query({ projectId });saveEnvironment = (input: Parameters<Client['saveEnvironment']['mutate']>[0]) =>lambdaClient.projectWorkingDirectory.saveEnvironment.mutate(input);- attachEnvironment = (projectId: string, environmentId: string) =>- lambdaClient.projectWorkingDirectory.attachEnvironment.mutate({ projectId, environmentId });- detachEnvironment = (projectId: string, environmentId: string) =>- lambdaClient.projectWorkingDirectory.detachEnvironment.mutate({ projectId, environmentId });- attachRepository = (input: Parameters<Client['attachRepository']['mutate']>[0]) =>- lambdaClient.projectWorkingDirectory.attachRepository.mutate(input);+ getEnvironment = (projectId: string) =>+ lambdaClient.projectWorkingDirectory.getEnvironment.query({ projectId });+ updateEnvironment = (input: Parameters<Client['updateEnvironment']['mutate']>[0]) =>+ lambdaClient.projectWorkingDirectory.updateEnvironment.mutate(input);bind = (input: BindProjectDirectoryInput) =>lambdaClient.projectWorkingDirectory.bind.mutate(input);list = (projectId?: string) => lambdaClient.projectWorkingDirectory.list.query({ projectId });diff --git a/src/spa/router/workspaceSettingsRoutes.tsx b/src/spa/router/workspaceSettingsRoutes.tsxindex 6da11a994ed..7726819a0a1 100644--- a/src/spa/router/workspaceSettingsRoutes.tsx+++ b/src/spa/router/workspaceSettingsRoutes.tsx@@ -390,6 +390,20 @@ export const workspaceSettingsContentRoute: RouteObject = {},path: 'environments',},+ // Environment detail level — the page reads the environment id from `sub`.+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/environments'),+ 'Desktop > Workspace > Settings > Environments > Detail',+ ),+ handle: {+ meta: createWorkspaceSettingsRouteMeta(+ WorkspaceSettingsTabs.Environments,+ createSurfaceSkeleton('detail'),+ ),+ },+ path: 'environments/:sub',+ },// Sandbox storage moved to Docs (`/:slug/resource/sandbox-storage`).{ element: <LegacySandboxStorageRedirect />, path: 'drive' },// Account-level tabs mirrored inside the workspace so members candiff --git a/src/store/project/store.ts b/src/store/project/store.tsindex ef3c935cdb8..5ec4d850a58 100644--- a/src/store/project/store.ts+++ b/src/store/project/store.ts@@ -63,6 +63,8 @@ interface ProjectStore extends ProjectStoreState {id?: string;identifier?: string;name: string;+ /** More repositories the project's environment checks out beside `repository`. */+ additionalRepositories?: { defaultBranch?: string; url: string }[];/** GitHub repository to attach as the project's environment, in the same write. */repository?: { defaultBranch?: string; name: string; url: string };slug?: string;diff --git a/src/store/projectWorkingDirectory/index.test.ts b/src/store/projectWorkingDirectory/index.test.tsindex ab74b7db85b..8dbeeb23b2d 100644--- a/src/store/projectWorkingDirectory/index.test.ts+++ b/src/store/projectWorkingDirectory/index.test.ts@@ -84,23 +84,24 @@ describe('projectWorkingDirectory store', () => {});});- describe('detachEnvironment', () => {+ describe('updateProjectEnvironment', () => {afterEach(() => vi.restoreAllMocks());- it("unlinks through the service and refreshes only that project's environments", async () => {+ it("saves through the service and refreshes only that project's environment and folders", async () => {vi.mocked(mutate).mockClear();- const detach = vi- .spyOn(projectWorkingDirectoryService, 'detachEnvironment')- .mockResolvedValue({ data: {}, success: true } as never);+ const update = vi+ .spyOn(projectWorkingDirectoryService, 'updateEnvironment')+ .mockResolvedValue({ data: { id: 'env-1' }, success: true } as never);+ const configuration = { sources: [{ kind: 'git' as const, url: 'https://github.com/a/b' }] };- await useProjectDirectoryStore.getState().detachEnvironment('project-1', 'env-1');+ await useProjectDirectoryStore+ .getState()+ .updateProjectEnvironment({ configuration, projectId: 'project-1' });- expect(detach).toHaveBeenCalledWith('project-1', 'env-1');+ expect(update).toHaveBeenCalledWith({ configuration, projectId: 'project-1' });expect(invalidates('projectEnvironments', 'project-1')).toBe(true);- // Its folders in the project are no longer runnable.expect(invalidates('projectDirectories', 'project-1')).toBe(true);- expect(invalidates('projectDirectories', 'all')).toBe(true);- // The environment itself is untouched, so the scope-wide list stays as it is.+ // Standalone environments are untouched.expect(invalidates('projectEnvironments', 'all')).toBe(false);});});diff --git a/src/store/projectWorkingDirectory/index.ts b/src/store/projectWorkingDirectory/index.tsindex c3da2749fc3..e9b7c783a04 100644--- a/src/store/projectWorkingDirectory/index.ts+++ b/src/store/projectWorkingDirectory/index.ts@@ -91,20 +91,12 @@ interface ProjectDirectoryStore extends ProjectDirectoryStoreState {associateTopic: (...args: ServiceParams<'associateTopic'>) => 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. */createProjectTopic: (...args: ServiceParams<'createProjectTopic'>) => Promise<ServiceData<'createProjectTopic'>>;- /** Unlink an environment from a project; the environment itself is kept. */- detachEnvironment: (...args: ServiceParams<'detachEnvironment'>) => Promise<void>;/** Move a directory conversation to its project's directory on another device. */moveTopic: (...args: ServiceParams<'moveTopic'>) => Promise<ServiceData<'moveTopic'>>;/**@@ -125,6 +117,14 @@ interface ProjectDirectoryStore extends ProjectDirectoryStoreState {) => Promise<ServiceData<'saveEnvironment'>>;/** Start a conversation inside one directory. */startTopic: (id: string, agentId: string, title: string) => Promise<ServiceData<'startTopic'>>;+ /**+ * Edit the project's environment — its repositories, setup and variables.+ * The project's environment list and its folders (which carry the+ * environment's definition) follow.+ */+ updateProjectEnvironment: (+ ...args: ServiceParams<'updateEnvironment'>+ ) => Promise<ServiceData<'updateEnvironment'>>;/** Fetch orchestration only; read the rows with `useProjectDirectories`. */useFetchDirectories: (projectId?: string, enabled?: boolean) => ProjectListSyncResult;/** Fetch orchestration only; read the rows with `useDirectoryTopics`. */@@ -284,31 +284,11 @@ export const useProjectDirectoryStore: UseBoundStoreWithEqualityFn<await Promise.all([environments.revalidate(), directories.revalidate()]);return result.data;},- attachEnvironment: async (projectId, environmentId) => {- await projectWorkingDirectoryService.attachEnvironment(projectId, environmentId);- await Promise.all([- environments.revalidate(projectId),- // Relinking makes the project's folders made from it runnable again.- directories.revalidate(ALL_PROJECTS_KEY),- directories.revalidate(projectId),- // The scope-wide list gained the environment instanced by the attach.- environments.revalidate(ALL_PROJECTS_KEY),- ]);- },- detachEnvironment: async (projectId, environmentId) => {- await projectWorkingDirectoryService.detachEnvironment(projectId, environmentId);- await Promise.all([- environments.revalidate(projectId),- // The project's folders made from it lose their runnable environment.- directories.revalidate(ALL_PROJECTS_KEY),- directories.revalidate(projectId),- ]);- },- attachRepository: async (input) => {- const result = await projectWorkingDirectoryService.attachRepository(input);+ updateProjectEnvironment: async (input) => {+ const result = await projectWorkingDirectoryService.updateEnvironment(input);await Promise.all([environments.revalidate(input.projectId),- environments.revalidate(ALL_PROJECTS_KEY),+ directories.revalidate(input.projectId),]);return result.data;},